#ifndef SERIALIZE_OPTIONAL_HPP_
#define SERIALIZE_OPTIONAL_HPP_

#include <Serialize/Base.hpp>
#include <optional>

template<typename T>
struct SerialCodec<std::optional<T>>
{
    static void encode(std::vector<uint8_t> &outBytes, const std::optional<T> &opt)
    {
        if (!opt.has_value())
        {
            outBytes.push_back(0);
        }
        else
        {
            outBytes.push_back(0xFF);
            serializeInto(outBytes, *opt);
        }
    }

    static size_t decode(const uint8_t *data, size_t size, std::optional<T> &opt)
    {
        if (size < 1)
        {
            return 0;
        }

        if (*data == 0)
        {
            opt = std::nullopt;
            return 1;
        }
        else if (*data == 0xFF)
        {
            T value;
            size_t result = 1 + deserialize(data + 1, size - 1, value);
            opt = value;
            return result;
        }
        else
        {
            return 0;
        }
    }
};

#endif