File: format.hpp

package info (click to toggle)
openmw 0.49.0-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 33,992 kB
  • sloc: cpp: 372,479; xml: 2,149; sh: 1,403; python: 797; makefile: 26
file content (76 lines) | stat: -rw-r--r-- 2,133 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
#ifndef OPENMW_COMPONENTS_SERIALIZATION_FORMAT_H
#define OPENMW_COMPONENTS_SERIALIZATION_FORMAT_H

#include <algorithm>
#include <array>
#include <cstddef>
#include <cstdint>
#include <functional>
#include <type_traits>
#include <utility>
#include <vector>

namespace Serialization
{
    enum class Mode
    {
        Read,
        Write,
    };

    template <class>
    struct IsContiguousContainer : std::false_type
    {
    };

    template <class... Args>
    struct IsContiguousContainer<std::vector<Args...>> : std::true_type
    {
    };

    template <class T, std::size_t n>
    struct IsContiguousContainer<std::array<T, n>> : std::true_type
    {
    };

    template <class T>
    inline constexpr bool isContiguousContainer = IsContiguousContainer<std::decay_t<T>>::value;

    template <Mode mode, class Derived>
    struct Format
    {
        template <class Visitor, class T>
        void operator()(Visitor&& visitor, T* data, std::size_t size) const
        {
            if constexpr (std::is_arithmetic_v<T> || std::is_enum_v<T>)
                visitor(self(), data, size);
            else
                std::for_each(data, data + size, [&](auto& v) { visitor(self(), v); });
        }

        template <class Visitor, class T, std::size_t size>
        void operator()(Visitor&& visitor, T (&data)[size]) const
        {
            self()(std::forward<Visitor>(visitor), data, size);
        }

        template <class Visitor, class T>
        auto operator()(Visitor&& visitor, T&& value) const -> std::enable_if_t<isContiguousContainer<T>>
        {
            if constexpr (mode == Mode::Write)
                visitor(self(), static_cast<std::uint64_t>(value.size()));
            else
            {
                static_assert(mode == Mode::Read);
                std::uint64_t size = 0;
                visitor(self(), size);
                value.resize(static_cast<std::size_t>(size));
            }
            self()(std::forward<Visitor>(visitor), value.data(), value.size());
        }

        const Derived& self() const { return static_cast<const Derived&>(*this); }
    };
}

#endif