#include "zoost/zt.mem.h"

#include <algorithm>

#ifdef min
#undef min
#endif

void zoostMutBuffer::Push(const char* data, int size)
{
    std::lock_guard<std::mutex> lock(mutex_);
    buffer_.insert(buffer_.end(), data, data + size);
}

int zoostMutBuffer::IndexOf(const char* data, int size, int start)
{
    std::lock_guard<std::mutex> lock(mutex_);
    if (start < 0 || start >= static_cast<int>(buffer_.size()) || size <= 0) {
        return -1;
    }
    auto it = std::search(buffer_.begin() + start, buffer_.end(), data, data + size);
    if (it != buffer_.end()) {
        return static_cast<int>(std::distance(buffer_.begin(), it));
    }
    return -1;
}

const char* zoostMutBuffer::Data() const
{
    return buffer_.data();
}

int zoostMutBuffer::GetSize() const
{
    return static_cast<int>(buffer_.size());
}

void zoostMutBuffer::RemoveOf(int start, int size)
{
    std::lock_guard<std::mutex> lock(mutex_);
    if (start < 0 || start >= static_cast<int>(buffer_.size()) || size <= 0) {
        return;
    }
    int end = std::min(start + size, static_cast<int>(buffer_.size()));
    buffer_.erase(buffer_.begin() + start, buffer_.begin() + end);
}

void zoostMutBuffer::Clear()
{
    std::lock_guard<std::mutex> lock(mutex_);
    buffer_.clear();
}
