summaryrefslogtreecommitdiff
path: root/lib/rawDataReader.h
blob: c3a537a26de53aca0711ea520b0b96a48daa7e86 (plain)
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
77
78
79
80
81
82
83
84
#ifndef MYGRATE_RAW_DATA_READER_H
#define MYGRATE_RAW_DATA_READER_H

#include "helpers.h"
#include "mariadb_repl.h"
#include <cstddef>
#include <cstdint>
#include <cstring>
#include <span>
#include <stdexcept>

namespace MyGrate {
	struct PackedInteger {
	};
	template<typename T> struct type_map {
		using target = T;
	};
	template<> struct type_map<PackedInteger> {
		using target = uint64_t;
	};

	class RawDataReader {
	public:
		explicit RawDataReader(const void * const d, std::size_t len);
		explicit RawDataReader(const MARIADB_STRING & str);

		template<typename T, size_t L = sizeof(T)>
		typename type_map<T>::target
		readValue()
		{
			static_assert(L > 0 && L <= sizeof(T), "Read exceeds target size");
			return readValue<T>(L);
		}

		template<typename T>
		typename type_map<T>::target
		readValue(size_t L)
		{
			static_assert(std::is_trivial_v<T>, "Do not read non-trivial types");
			verify<std::logic_error>(L > 0 && L <= sizeof(T), "Read exceeds target size");
			offsetSizeCheck(L);
			T v {};
			memcpy(&v, rawdata + offset, L);
			offset += L;
			return v;
		}

		template<typename T>
		T
		viewValue(size_t L)
		{
			static_assert(sizeof(typename T::value_type) == sizeof(std::byte));
			offsetSizeCheck(L);
			T v {reinterpret_cast<const typename T::value_type *>(rawdata + offset), L};
			offset += L;
			return v;
		}

		void discard(size_t);

		bool
		more() const
		{
			return offset < len;
		}

		std::span<const std::byte>
		raw() const
		{
			return {rawdata, len};
		}

	private:
		void offsetSizeCheck(size_t) const;

		const std::byte * const rawdata;
		const std::size_t len;
		std::size_t offset {0};
	};

	template<> uint64_t RawDataReader::readValue<PackedInteger>();
}

#endif