#include "shared_data.hpp"
#include <iostream>
#include <cstring>


bool SharedData::Init(uint8_t * p_data, uint32_t size)
{
    if ((p_data == nullptr) || (size == 0))
    {
        return false;
    }

    p_data_ = p_data;    
    size_ = size;

    std::lock_guard guard(mutex_);
    std::memset(p_data_, 0, size);

    return true;    
}

bool SharedData::Write(uint32_t offset_bytes, void * p_data, uint32_t length)
{
    if ((p_data == nullptr) || ((offset_bytes + length) > size_))
    {
        return false;
    }

    std::lock_guard guard(mutex_);
    std::memcpy(p_data_ + offset_bytes,  p_data, length);

    return true;
}

bool SharedData::Read(uint32_t offset_bytes, void * p_data, uint32_t length)
{     
    if ((p_data == nullptr) || ((offset_bytes + length) > size_))
    {
        return false;
    }

    std::lock_guard guard(mutex_);
    std::memcpy(p_data, p_data_ + offset_bytes, length);

    return true;  
}