62 lines
1.5 KiB
C++
62 lines
1.5 KiB
C++
|
/*
|
||
|
* This Source Code Form is subject to the terms of the Mozilla Public
|
||
|
* License, v. 2.0. If a copy of the MPL was not distributed with this
|
||
|
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
|
||
|
*
|
||
|
* Copyright 2022, Danny Robson <danny@nerdcruft.net>
|
||
|
*/
|
||
|
|
||
|
#pragma once
|
||
|
|
||
|
#include <cruft/util/view.hpp>
|
||
|
|
||
|
#include <cstddef>
|
||
|
|
||
|
|
||
|
namespace cruft::serialise {
|
||
|
template <typename ValueT>
|
||
|
struct converter {
|
||
|
static
|
||
|
cruft::view<std::byte*>
|
||
|
to_bytes [[nodiscard]] (
|
||
|
cruft::view<std::byte*> dst,
|
||
|
ValueT const &src
|
||
|
);
|
||
|
|
||
|
static
|
||
|
ValueT
|
||
|
from_bytes (cruft::view<std::byte*> &src);
|
||
|
|
||
|
static std::size_t size (ValueT const&);
|
||
|
};
|
||
|
|
||
|
template <typename ValueT> struct converter<ValueT const> : public converter<ValueT> {};
|
||
|
template <typename ValueT> struct converter<ValueT &> : public converter<ValueT> {};
|
||
|
|
||
|
template <typename ValueT>
|
||
|
requires (std::is_trivial_v<ValueT>)
|
||
|
struct converter<ValueT> {
|
||
|
static
|
||
|
cruft::view<std::byte*>
|
||
|
to_bytes [[nodiscard]] (
|
||
|
cruft::view<std::byte*> dst,
|
||
|
ValueT const &src
|
||
|
) {
|
||
|
if (dst.size () < sizeof (ValueT))
|
||
|
throw std::bad_alloc ();
|
||
|
|
||
|
return write (dst, src);
|
||
|
}
|
||
|
|
||
|
static
|
||
|
ValueT
|
||
|
from_bytes (cruft::view<std::byte*> &src)
|
||
|
{
|
||
|
return read<ValueT> (src);
|
||
|
}
|
||
|
|
||
|
|
||
|
static std::size_t size (ValueT const&) { return sizeof (ValueT); }
|
||
|
};
|
||
|
}
|