summaryrefslogtreecommitdiff
path: root/modules/codec/c++/schema_hash.h
blob: 8f66fbf4652c16b2a9cf58c7f95734e67b3a03bb (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
85
#pragma once

#include <forstio/string_literal.h>
#include "schema.h"

namespace saw {
struct schema_hash_combine {
		static constexpr uint64_t apply(uint64_t seed, uint64_t v){
				return seed ^( std::hash<uint64_t>{}(v) + 0x9e3779b9 + (seed<<6) + (seed >> 2));
		}
};

template<string_literal lit>
struct hash_literal {
	static constexpr uint64_t apply(uint64_t seed){
		constexpr std::string_view view = lit.view();
		for(uint64_t i = 0; i < view.size(); ++i){
			seed = schema_hash_combine::apply(seed, static_cast<uint64_t>(view[i]));
		}
		return seed;
	}
};

template<typename Schema>
struct schema_hash_seed {
		static_assert(always_false<Schema>, "Not schema_hashable");
};

template<>
struct schema_hash_seed<schema::SignedInteger> {
	using Schema = schema::SignedInteger;

	static constexpr uint64_t apply(uint64_t seed){
		return hash_literal<Schema::name>::apply(seed);
	}
};

template<>
struct schema_hash_seed<schema::UnsignedInteger> {
	using Schema = schema::UnsignedInteger;

	static constexpr uint64_t apply(uint64_t seed){
		return hash_literal<Schema::name>::apply(seed);
	}
};

template<>
struct schema_hash_seed<schema::FloatingPoint> {
	using Schema = schema::FloatingPoint;

	static constexpr uint64_t apply(uint64_t seed){
		return hash_literal<Schema::name>::apply(seed);
	}
};

template<>
struct schema_hash_seed<schema::String> {
	using Schema = schema::String;

	static constexpr uint64_t apply(uint64_t seed){
		return hash_literal<Schema::name>::apply(seed);
	}
};

template<typename P, uint64_t N>
struct schema_hash_seed<schema::Primitive<P,N>> {
	using Schema = schema::Primitive<P,N>;

	static constexpr uint64_t apply(uint64_t seed){
		seed = hash_literal<Schema::name>::apply(seed);
		seed = schema_hash_seed<P>::apply(seed);
		seed = schema_hash_combine::apply(seed, N);
		return seed;
	}
};

template<typename Schema>
struct schema_hash {
	static constexpr uint64_t apply() {
		constexpr uint64_t seed = 0;
		return schema_hash_seed<Schema>::apply(seed);
	}
};

}