-
Notifications
You must be signed in to change notification settings - Fork 3
/
Zmeya.h
1391 lines (1176 loc) · 49.7 KB
/
Zmeya.h
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
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// The MIT License (MIT)
//
// Copyright (c) 2021 Sergey Makeev
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
#pragma once
#include <array>
#include <cstddef>
#include <cstring>
#include <limits>
#include <memory>
#include <string>
#include <unordered_map>
#include <unordered_set>
#include <vector>
#include <assert.h>
#include <xmmintrin.h>
// This macro is only needed if you want to create serializable data
// (deserialization doesn't need this)
//#define ZMEYA_ENABLE_SERIALIZE_SUPPORT
#define ZMEYA_ASSERT(cond) assert(cond)
//#define ZMEYA_NODISCARD [[nodiscard]]
#define ZMEYA_NODISCARD
#define ZMEYA_MAX_ALIGN (64)
#ifdef _DEBUG
#define ZMEYA_VALIDATE_HASH_DUPLICATES
#endif
namespace zm
{
#define ZMEYA_MURMURHASH_MAGIC64A 0xc6a4a7935bd1e995LLU
inline uint64_t murmur_hash_process64a(const char* key, uint32_t len, uint64_t seed)
{
const uint64_t m = ZMEYA_MURMURHASH_MAGIC64A;
const int r = 47;
uint64_t h = seed ^ (len * m);
const uint64_t* data = (const uint64_t*)key;
const uint64_t* end = data + (len / 8);
while (data != end)
{
uint64_t k = *data++;
k *= m;
k ^= k >> r;
k *= m;
h ^= k;
h *= m;
}
const unsigned char* data2 = (const unsigned char*)data;
switch (len & 7)
{
case 7:
h ^= (uint64_t)((uint64_t)data2[6] << (uint64_t)48);
case 6:
h ^= (uint64_t)((uint64_t)data2[5] << (uint64_t)40);
case 5:
h ^= (uint64_t)((uint64_t)data2[4] << (uint64_t)32);
case 4:
h ^= (uint64_t)((uint64_t)data2[3] << (uint64_t)24);
case 3:
h ^= (uint64_t)((uint64_t)data2[2] << (uint64_t)16);
case 2:
h ^= (uint64_t)((uint64_t)data2[1] << (uint64_t)8);
case 1:
h ^= (uint64_t)((uint64_t)data2[0]);
h *= m;
};
h ^= h >> r;
h *= m;
h ^= h >> r;
return h;
}
#undef ZMEYA_MURMURHASH_MAGIC64A
//
// Functions and types to interact with the application
// Feel free to replace them to your engine specific functions
//
namespace AppInterop
{
// hasher
template <typename T> ZMEYA_NODISCARD inline size_t hasher(const T& v) { return std::hash<T>{}(v); }
// string hasher
ZMEYA_NODISCARD inline size_t hashString(const char* str)
{
size_t len = std::strlen(str);
uint64_t hash = zm::murmur_hash_process64a(str, uint32_t(len), 13061979);
return size_t(hash);
}
// aligned allocator
ZMEYA_NODISCARD inline void* aligned_alloc(size_t size, size_t alignment) { return _mm_malloc(size, alignment); }
// aligned free
inline void aligned_free(void* p) { _mm_free(p); }
} // namespace AppInterop
// absolute offset/difference type
using offset_t = std::uintptr_t;
using diff_t = std::ptrdiff_t;
// relative offset type
using roffset_t = int32_t;
ZMEYA_NODISCARD inline offset_t toAbsolute(offset_t base, roffset_t offset)
{
offset_t res = base + diff_t(offset);
return res;
}
ZMEYA_NODISCARD inline uintptr_t toAbsoluteAddr(uintptr_t base, roffset_t offset)
{
uintptr_t res = base + ptrdiff_t(offset);
return res;
}
#ifdef ZMEYA_ENABLE_SERIALIZE_SUPPORT
template <typename T> class BlobPtr;
#endif
/*
Pointer - self-relative pointer relative to its own memory address
*/
template <typename T> class Pointer
{
// addr = this + offset
// offset(0) = this = nullptr (here is the limitation, pointer can't point to itself)
// this extra offset fits well into the x86/ARM addressing modes
// see for details https://godbolt.org/z/aTTW9E7o9
roffset_t relativeOffset;
bool isEqual(const Pointer& other) const noexcept { return get() == other.get(); }
ZMEYA_NODISCARD T* getUnsafe() const noexcept
{
uintptr_t self = uintptr_t(this);
// dereferencing a NULL pointer is undefined behavior, so we can skip nullptr check
ZMEYA_ASSERT(relativeOffset != 0);
uintptr_t addr = toAbsoluteAddr(self, relativeOffset);
return reinterpret_cast<T*>(addr);
}
public:
Pointer() noexcept = default;
// Pointer(const Pointer&) = delete;
// Pointer& operator=(const Pointer&) = delete;
ZMEYA_NODISCARD T* get() const noexcept
{
uintptr_t self = uintptr_t(this);
uintptr_t addr = (relativeOffset == 0) ? uintptr_t(0) : toAbsoluteAddr(self, relativeOffset);
return reinterpret_cast<T*>(addr);
}
#ifdef ZMEYA_ENABLE_SERIALIZE_SUPPORT
Pointer& operator=(const BlobPtr<T>& other);
#endif
// Note: implicit conversion operator
// operator const T*() const noexcept { return get(); }
// operator T*() noexcept { return get(); }
ZMEYA_NODISCARD T* operator->() const noexcept { return getUnsafe(); }
ZMEYA_NODISCARD T& operator*() const noexcept { return *(getUnsafe()); }
ZMEYA_NODISCARD bool operator==(const Pointer& other) const noexcept { return isEqual(other); }
ZMEYA_NODISCARD bool operator!=(const Pointer& other) const noexcept { return !isEqual(other); }
operator bool() const noexcept { return relativeOffset != 0; }
ZMEYA_NODISCARD bool operator==(std::nullptr_t) const noexcept { return relativeOffset == 0; }
ZMEYA_NODISCARD bool operator!=(std::nullptr_t) const noexcept { return relativeOffset != 0; }
friend class BlobBuilder;
};
/*
String
*/
class String
{
Pointer<char> data;
public:
String() noexcept = default;
// String(const String&) = delete;
// String& operator=(const String&) = delete;
bool isEqual(const char* s2) const noexcept
{
const char* s1 = c_str();
return (std::strcmp(s1, s2) == 0);
}
ZMEYA_NODISCARD const char* c_str() const noexcept
{
const char* v = data.get();
if (v != nullptr)
{
return v;
}
return "";
}
ZMEYA_NODISCARD bool empty() const noexcept { return data.get() != nullptr; }
ZMEYA_NODISCARD bool operator==(const String& other) const noexcept
{
// both strings can point to the same memory (fast-path)
if (other.c_str() == c_str())
{
return true;
}
return isEqual(other.c_str());
}
ZMEYA_NODISCARD bool operator!=(const String& other) const noexcept
{
// both strings can point to the same memory (fast-path)
if (other.c_str() == c_str())
{
return false;
}
return !isEqual(other.c_str());
}
friend class BlobBuilder;
};
ZMEYA_NODISCARD inline bool operator==(const String& left, const char* const right) noexcept { return left.isEqual(right); }
ZMEYA_NODISCARD inline bool operator!=(const String& left, const char* const right) noexcept { return !left.isEqual(right); }
ZMEYA_NODISCARD inline bool operator==(const char* const left, const String& right) noexcept { return right.isEqual(left); }
ZMEYA_NODISCARD inline bool operator!=(const char* const left, const String& right) noexcept { return !right.isEqual(left); }
ZMEYA_NODISCARD inline bool operator==(const String& left, const std::string& right) noexcept { return left.isEqual(right.c_str()); }
ZMEYA_NODISCARD inline bool operator!=(const String& left, const std::string& right) noexcept { return !left.isEqual(right.c_str()); }
ZMEYA_NODISCARD inline bool operator==(const std::string& left, const String& right) noexcept { return right.isEqual(left.c_str()); }
ZMEYA_NODISCARD inline bool operator!=(const std::string& left, const String& right) noexcept { return !right.isEqual(left.c_str()); }
/*
Array
*/
template <typename T> class Array
{
roffset_t relativeOffset;
uint32_t numElements;
private:
ZMEYA_NODISCARD const T* getConstData() const noexcept
{
uintptr_t addr = toAbsoluteAddr(uintptr_t(this), relativeOffset);
return reinterpret_cast<const T*>(addr);
}
ZMEYA_NODISCARD T* getData() const noexcept { return const_cast<T*>(getConstData()); }
public:
Array() noexcept = default;
// Array(const Array&) = delete;
// Array& operator=(const Array&) = delete;
ZMEYA_NODISCARD size_t size() const noexcept { return size_t(numElements); }
ZMEYA_NODISCARD T& operator[](const size_t index) noexcept
{
T* data = getData();
return data[index];
}
ZMEYA_NODISCARD const T& operator[](const size_t index) const noexcept
{
const T* data = getConstData();
return data[index];
}
ZMEYA_NODISCARD const T* at(const size_t index) const
{
ZMEYA_ASSERT(index < size());
const T* data = getConstData();
return data[index];
}
ZMEYA_NODISCARD T* data() noexcept { return getData(); }
ZMEYA_NODISCARD const T* data() const noexcept { return getConstData(); }
ZMEYA_NODISCARD const T* begin() const noexcept
{
const T* data = getConstData();
return data;
};
ZMEYA_NODISCARD const T* end() const noexcept
{
const T* data = getConstData();
return data + size();
};
ZMEYA_NODISCARD bool empty() const noexcept { return size() == 0; }
friend class BlobBuilder;
};
/*
Hash adapters
*/
// (key) generic adapter
template <typename Item> struct HashKeyAdapterGeneric
{
typedef Item ItemType;
static size_t hash(const ItemType& item) { return AppInterop::hasher(item); }
static bool eq(const ItemType& a, const ItemType& b) { return a == b; }
};
// (key) adapter for std::string
struct HashKeyAdapterStdString
{
typedef std::string ItemType;
static size_t hash(const ItemType& item) { return AppInterop::hashString(item.c_str()); }
static bool eq(const ItemType& a, const ItemType& b) { return a == b; }
};
// (key,value) generic adapter
template <typename Item> struct HashKeyValueAdapterGeneric
{
typedef Item ItemType;
static size_t hash(const ItemType& item) { return AppInterop::hasher(item.first); }
static bool eq(const ItemType& a, const ItemType& b) { return a.first == b.first; }
};
// (key,value) adapter for std::string
template <typename Value> struct HashKeyValueAdapterStdString
{
typedef std::pair<const std::string, Value> ItemType;
static size_t hash(const ItemType& item) { return AppInterop::hashString(item.first.c_str()); }
static bool eq(const ItemType& a, const ItemType& b) { return a.first == b.first; }
};
// (key) adapter for String and null-terminated c strings >> SearchAdapterCStrToString
// used only for search
struct HashKeyAdapterCStr
{
typedef const char* ItemType;
static size_t hash(const ItemType& item) { return AppInterop::hashString(item); }
static bool eq(const String& a, const ItemType& b) { return a == b; }
};
/*
HashSet
*/
template <typename Key> class HashSet
{
public:
typedef Key Item;
struct Bucket
{
uint32_t beginIndex;
uint32_t endIndex;
};
Array<Bucket> buckets;
Array<Item> items;
template <typename Key2, typename Adapter> ZMEYA_NODISCARD bool containsImpl(const Key2& key) const noexcept
{
size_t numBuckets = buckets.size();
if (numBuckets == 0)
{
return false;
}
size_t hashMod = numBuckets;
size_t hash = Adapter::hash(key);
size_t bucketIndex = hash % hashMod;
const Bucket& bucket = buckets[bucketIndex];
for (size_t i = bucket.beginIndex; i < bucket.endIndex; i++)
{
const Key& item = items[i];
if (Adapter::eq(item, key))
{
return true;
}
}
return false;
}
public:
HashSet() noexcept = default;
// HashSet(const HashSet&) = delete;
// HashSet& operator=(const HashSet&) = delete;
ZMEYA_NODISCARD size_t size() const noexcept { return items.size(); }
ZMEYA_NODISCARD bool empty() const noexcept { return items.empty(); }
ZMEYA_NODISCARD const Item* begin() const noexcept { return items.begin(); }
ZMEYA_NODISCARD const Item* end() const noexcept { return items.end(); }
ZMEYA_NODISCARD bool contains(const char* key) const noexcept
{
static_assert(std::is_same<Key, String>::value, "To use this function, the key type must be Zmeya::String");
return containsImpl<const char*, HashKeyAdapterCStr>(key);
}
ZMEYA_NODISCARD bool contains(const Key& key) const noexcept { return containsImpl<Key, HashKeyAdapterGeneric<Key>>(key); }
friend class BlobBuilder;
};
/*
Pair
*/
template <typename T1, typename T2> struct Pair
{
T1 first;
T2 second;
Pair() noexcept = default;
Pair(const T1& t1, const T2& t2) noexcept
: first(t1)
, second(t2)
{
}
};
/*
HashMap
*/
template <typename Key, typename Value> class HashMap
{
typedef Pair<const Key, Value> Item;
struct Bucket
{
uint32_t beginIndex;
uint32_t endIndex;
};
Array<Bucket> buckets;
Array<Item> items;
template <typename Adapter, typename Key2> ZMEYA_NODISCARD const Value* findImpl(const Key2& key) const noexcept
{
size_t numBuckets = buckets.size();
if (numBuckets == 0)
{
return nullptr;
}
size_t hashMod = numBuckets;
size_t hash = Adapter::hash(key);
size_t bucketIndex = hash % hashMod;
const Bucket& bucket = buckets[bucketIndex];
for (size_t i = bucket.beginIndex; i < bucket.endIndex; i++)
{
const Item& item = items[i];
if (Adapter::eq(item.first, key))
{
return &item.second;
}
}
return nullptr;
}
public:
HashMap() noexcept = default;
// HashMap(const HashMap&) = delete;
// HashMap& operator=(const HashMap&) = delete;
ZMEYA_NODISCARD size_t size() const noexcept { return items.size(); }
ZMEYA_NODISCARD bool empty() const noexcept { return items.empty(); }
ZMEYA_NODISCARD const Item* begin() const noexcept { return items.begin(); }
ZMEYA_NODISCARD const Item* end() const noexcept { return items.end(); }
ZMEYA_NODISCARD bool contains(const Key& key) const noexcept { return find(key) != nullptr; }
ZMEYA_NODISCARD Value* find(const Key& key) noexcept
{
typedef HashKeyAdapterGeneric<Key> Adapter;
const Value* res = findImpl<Adapter>(key);
return res ? const_cast<Value*>(res) : nullptr;
}
ZMEYA_NODISCARD const Value* find(const Key& key) const noexcept
{
typedef HashKeyAdapterGeneric<Key> Adapter;
const Value* res = findImpl<Adapter>(key);
return res;
}
ZMEYA_NODISCARD const Value& find(const Key& key, const Value& valueIfNotFound) const noexcept
{
typedef HashKeyAdapterGeneric<Key> Adapter;
const Value* res = findImpl<Adapter>(key);
if (res)
{
return *res;
}
return valueIfNotFound;
}
ZMEYA_NODISCARD bool contains(const char* key) const noexcept
{
static_assert(std::is_same<Key, String>::value, "To use this function, the key type must be Zmeya::String");
return find(key) != nullptr;
}
ZMEYA_NODISCARD Value* find(const char* key) noexcept
{
static_assert(std::is_same<Key, String>::value, "To use this function, the key type must be Zmeya::String");
typedef HashKeyAdapterCStr Adapter;
const Value* res = findImpl<Adapter>(key);
return res ? const_cast<Value*>(res) : nullptr;
}
ZMEYA_NODISCARD const Value* find(const char* key) const noexcept
{
static_assert(std::is_same<Key, String>::value, "To use this function, the key type must be Zmeya::String");
typedef HashKeyAdapterCStr Adapter;
const Value* res = findImpl<Adapter>(key);
return res;
}
ZMEYA_NODISCARD const Value& find(const char* key, const Value& valueIfNotFound) const noexcept
{
static_assert(std::is_same<Key, String>::value, "To use this function, the key type must be Zmeya::String");
typedef HashKeyAdapterCStr Adapter;
const Value* res = findImpl<Adapter>(key);
if (res)
{
return *res;
}
return valueIfNotFound;
}
ZMEYA_NODISCARD const char* find(const Key& key, const char* valueIfNotFound) const noexcept
{
static_assert(std::is_same<Value, String>::value, "To use this function, the value type must be Zmeya::String");
typedef HashKeyAdapterGeneric<Key> Adapter;
const Value* res = findImpl<Adapter>(key);
if (res)
{
return res->c_str();
}
return valueIfNotFound;
}
ZMEYA_NODISCARD const char* find(const char* key, const char* valueIfNotFound) const noexcept
{
static_assert(std::is_same<Key, String>::value, "To use this function, the key type must be Zmeya::String");
static_assert(std::is_same<Value, String>::value, "To use this function, the value type must be Zmeya::String");
typedef HashKeyAdapterCStr Adapter;
const Value* res = findImpl<Adapter>(key);
if (res)
{
return res->c_str();
}
return valueIfNotFound;
}
friend class BlobBuilder;
};
#ifdef ZMEYA_ENABLE_SERIALIZE_SUPPORT
ZMEYA_NODISCARD inline diff_t diff(offset_t a, offset_t b) noexcept
{
diff_t res = a - b;
return res;
}
ZMEYA_NODISCARD inline offset_t diffAddr(uintptr_t a, uintptr_t b)
{
ZMEYA_ASSERT(a >= b);
uintptr_t res = a - b;
ZMEYA_ASSERT(res <= uintptr_t(std::numeric_limits<offset_t>::max()));
return offset_t(res);
}
ZMEYA_NODISCARD inline roffset_t toRelativeOffset(diff_t v)
{
ZMEYA_ASSERT(v >= diff_t(std::numeric_limits<roffset_t>::min()));
ZMEYA_ASSERT(v <= diff_t(std::numeric_limits<roffset_t>::max()));
return roffset_t(v);
}
constexpr bool inline isPowerOfTwo(size_t v) { return v && ((v & (v - 1)) == 0); }
class BlobBuilder;
/*
This is a non-serializable pointer to blob internal memory
Note: blob is able to relocate its own memory that's is why we cannot use
standard pointers or references
*/
template <typename T> class BlobPtr
{
std::weak_ptr<const BlobBuilder> blob;
offset_t absoluteOffset = 0;
bool isEqual(const BlobPtr& other) const
{
if (blob != other.blob)
{
return false;
}
return absoluteOffset == other.absoluteOffset;
}
public:
explicit BlobPtr(std::weak_ptr<const BlobBuilder>&& _blob, offset_t _absoluteOffset)
: blob(std::move(_blob))
, absoluteOffset(_absoluteOffset)
{
}
BlobPtr() = default;
BlobPtr(BlobPtr&&) = default;
BlobPtr& operator=(BlobPtr&&) = default;
BlobPtr(const BlobPtr&) = default;
BlobPtr& operator=(const BlobPtr&) = default;
template <typename T2> BlobPtr(const BlobPtr<T2>& other)
{
static_assert(std::is_convertible<T2*, T*>::value, "Uncompatible types");
blob = other.blob;
absoluteOffset = other.absoluteOffset;
}
template <class T2> friend class BlobPtr;
offset_t getAbsoluteOffset() const { return absoluteOffset; }
ZMEYA_NODISCARD T* get() const;
T* operator->() const { return get(); }
T& operator*() const { return *(get()); }
operator bool() const { return get() != nullptr; }
bool operator==(const BlobPtr& other) const { return isEqual(other); }
bool operator!=(const BlobPtr& other) const { return !isEqual(other); }
template <typename T2> friend class Pointer;
};
/*
Blob allocator - aligned allocator for internal Blob usage
*/
template <typename T, int Alignment> class BlobBuilderAllocator : public std::allocator<T>
{
public:
typedef size_t size_type;
typedef T* pointer;
typedef const T* const_pointer;
template <typename _Tp1> struct rebind
{
typedef BlobBuilderAllocator<_Tp1, Alignment> other;
};
pointer allocate(size_type n)
{
void* const pv = AppInterop::aligned_alloc(n * sizeof(T), Alignment);
return static_cast<pointer>(pv);
}
void deallocate(pointer p, size_type) { AppInterop::aligned_free(p); }
BlobBuilderAllocator()
: std::allocator<T>()
{
}
BlobBuilderAllocator(const BlobBuilderAllocator& a)
: std::allocator<T>(a)
{
}
template <class U>
BlobBuilderAllocator(const BlobBuilderAllocator<U, Alignment>& a)
: std::allocator<T>(a)
{
}
~BlobBuilderAllocator() {}
};
/*
Span
*/
template <typename T> struct Span
{
T* data = nullptr;
size_t size = 0;
Span() = default;
Span(T* _data, size_t _size)
: data(_data)
, size(_size)
{
}
};
template <typename T> std::weak_ptr<T> weak_from(T* p)
{
std::shared_ptr<T> shared = p->shared_from_this();
return shared;
}
/*
Blob - a binary blob of data that is able to store POD types and special
"movable" data structures Note: Zmeya containers can be freely moved in
memory and deserialize from raw bytes without any extra work.
*/
class BlobBuilder : public std::enable_shared_from_this<BlobBuilder>
{
std::vector<char, BlobBuilderAllocator<char, ZMEYA_MAX_ALIGN>> data;
private:
ZMEYA_NODISCARD const char* get(offset_t absoluteOffset) const
{
ZMEYA_ASSERT(absoluteOffset < data.size());
return &data[absoluteOffset];
}
template <typename T> ZMEYA_NODISCARD BlobPtr<T> getBlobPtr(const T* p) const
{
ZMEYA_ASSERT(containsPointer(p));
offset_t absoluteOffset = diffAddr(uintptr_t(p), uintptr_t(data.data()));
return BlobPtr<T>(weak_from(this), absoluteOffset);
}
struct PrivateToken
{
};
public:
BlobBuilder() = delete;
BlobBuilder(size_t initialSizeInBytes, PrivateToken)
{
static_assert(std::is_trivially_copyable<Pointer<int>>::value, "Pointer is_trivially_copyable check failed");
static_assert(std::is_trivially_copyable<Array<int>>::value, "Array is_trivially_copyable check failed");
static_assert(std::is_trivially_copyable<HashSet<int>>::value, "HashSet is_trivially_copyable check failed");
static_assert(std::is_trivially_copyable<Pair<int, float>>::value, "Pair is_trivially_copyable check failed");
static_assert(std::is_trivially_copyable<HashMap<int, int>>::value, "HashMap is_trivially_copyable check failed");
static_assert(std::is_trivially_copyable<String>::value, "String is_trivially_copyable check failed");
data.reserve(initialSizeInBytes);
}
bool containsPointer(const void* p) const { return (!data.empty() && (p >= &data.front() && p <= &data.back())); }
BlobPtr<char> allocate(size_t numBytes, size_t alignment)
{
ZMEYA_ASSERT(isPowerOfTwo(alignment));
ZMEYA_ASSERT(alignment < ZMEYA_MAX_ALIGN);
//
size_t cursor = data.size();
// padding / alignment
size_t off = cursor & (alignment - 1);
size_t padding = 0;
if (off != 0)
{
padding = alignment - off;
}
size_t absoluteOffset = cursor + padding;
size_t numBytesToAllocate = numBytes + padding;
// Allocate more memory
// Note: new memory is filled with zeroes
// Zmeya containers rely on this behavior and we want to have all the padding zeroed as well
data.resize(data.size() + numBytesToAllocate, char(0));
// check alignment
ZMEYA_ASSERT((uintptr_t(&data[absoluteOffset]) & (alignment - 1)) == 0);
ZMEYA_ASSERT(absoluteOffset < size_t(std::numeric_limits<offset_t>::max()));
return BlobPtr<char>(weak_from(this), offset_t(absoluteOffset));
}
template <typename T, typename... _Valty> void placementCtor(void* ptr, _Valty&&... _Val)
{
::new (const_cast<void*>(static_cast<const volatile void*>(ptr))) T(std::forward<_Valty>(_Val)...);
}
template <typename T, typename... _Valty> BlobPtr<T> allocate(_Valty&&... _Val)
{
// compile time checks
static_assert(std::is_trivially_copyable<T>::value, "Only trivially copyable types allowed");
constexpr size_t alignOfT = std::alignment_of<T>::value;
static_assert(isPowerOfTwo(alignOfT), "Non power of two alignment not supported");
static_assert(alignOfT < ZMEYA_MAX_ALIGN, "Unsupported alignment");
constexpr size_t sizeOfT = sizeof(T);
BlobPtr<char> ptr = allocate(sizeOfT, alignOfT);
placementCtor<T>(ptr.get(), std::forward<_Valty>(_Val)...);
return BlobPtr<T>(weak_from(this), ptr.getAbsoluteOffset());
}
template <typename T> T& getDirectMemoryAccess(offset_t absoluteOffset)
{
const char* p = get(absoluteOffset);
return *const_cast<T*>(reinterpret_cast<const T*>(p));
}
template <typename T> void setArrayOffset(const BlobPtr<Array<T>>& dst, offset_t absoluteOffset)
{
dst->relativeOffset = toRelativeOffset(diff(absoluteOffset, dst.getAbsoluteOffset()));
}
template <typename T> offset_t resizeArrayWithoutInitialization(Array<T>& _dst, size_t numElements)
{
constexpr size_t alignOfT = std::alignment_of<T>::value;
constexpr size_t sizeOfT = sizeof(T);
static_assert((sizeOfT % alignOfT) == 0, "The size must be a multiple of the alignment");
BlobPtr<Array<T>> dst = getBlobPtr(&_dst);
// An array can be assigned/resized only once (non empty array detected)
ZMEYA_ASSERT(dst->relativeOffset == 0 && dst->numElements == 0);
BlobPtr<char> arrData = allocate(sizeOfT * numElements, alignOfT);
ZMEYA_ASSERT(numElements < size_t(std::numeric_limits<uint32_t>::max()));
dst->numElements = uint32_t(numElements);
setArrayOffset(dst, arrData.getAbsoluteOffset());
return arrData.getAbsoluteOffset();
}
// resize array (using copy constructor)
template <typename T> offset_t resizeArray(Array<T>& _dst, size_t numElements, const T& emptyElement)
{
BlobPtr<Array<T>> dst = getBlobPtr(&_dst);
offset_t absoluteOffset = resizeArrayWithoutInitialization(_dst, numElements);
T* current = &getDirectMemoryAccess<T>(absoluteOffset);
for (size_t i = 0; i < numElements; i++)
{
// call copy ctor
placementCtor<T>(current, emptyElement);
current++;
}
return absoluteOffset;
}
// resize array (using default constructor)
template <typename T> offset_t resizeArray(Array<T>& _dst, size_t numElements)
{
BlobPtr<Array<T>> dst = getBlobPtr(&_dst);
offset_t absoluteOffset = resizeArrayWithoutInitialization(_dst, numElements);
T* current = &getDirectMemoryAccess<T>(absoluteOffset);
for (size_t i = 0; i < numElements; i++)
{
// default ctor
placementCtor<T>(current);
current++;
}
return absoluteOffset;
}
// copyTo array fast (without using convertor)
template <typename T> offset_t copyToArrayFast(Array<T>& _dst, const T* begin, size_t numElements)
{
static_assert(std::is_trivially_copyable<T>::value, "Only trivially copyable types allowed");
BlobPtr<Array<T>> dst = getBlobPtr(&_dst);
offset_t absoluteOffset = resizeArrayWithoutInitialization(_dst, numElements);
T* arrData = &getDirectMemoryAccess<T>(absoluteOffset);
std::memcpy(arrData, begin, sizeof(T) * numElements);
return absoluteOffset;
}
// copyTo array from range
template <typename T, typename Iter, typename ConvertorFunc>
offset_t copyToArray(Array<T>& _dst, const Iter begin, const Iter end, int64_t size, ConvertorFunc convertorFunc)
{
size_t numElements = (size >= 0) ? size_t(size) : std::distance(begin, end);
BlobPtr<Array<T>> dst = getBlobPtr(&_dst);
resizeArray(_dst, numElements);
BlobPtr<T> firstElement = getBlobPtr(dst->data());
offset_t absoluteOffset = firstElement.getAbsoluteOffset();
offset_t currentIndex = 0;
for (Iter cur = begin; cur != end; ++cur)
{
offset_t currentItemAbsoluteOffset = absoluteOffset + sizeof(T) * currentIndex;
convertorFunc(this, currentItemAbsoluteOffset, *cur);
currentIndex++;
}
return absoluteOffset;
}
// copyTo hash container
template <typename ItemSrcAdapter, typename ItemDstAdapter, typename HashType, typename Iter, typename ConvertorFunc>
void copyToHash(HashType& _dst, Iter begin, Iter end, int64_t size, ConvertorFunc convertorFunc)
{
// Note: this bucketing method relies on the fact that the input data set is (already) unique
size_t numElements = (size >= 0) ? size_t(size) : std::distance(begin, end);
ZMEYA_ASSERT(numElements > 0);
size_t numBuckets = numElements * 2;
ZMEYA_ASSERT(numBuckets < size_t(std::numeric_limits<uint32_t>::max()));
size_t hashMod = numBuckets;
BlobPtr<HashType> dst = getBlobPtr(&_dst);
// allocate buckets & items
resizeArray(dst->buckets, numBuckets);
// 1-st pass count the number of elements per bucket (beginIndex / endIndex)
typename HashType::Bucket* buckets = &dst->buckets[0];
for (Iter cur = begin; cur != end; ++cur)
{
const auto& current = *cur;
size_t hash = ItemSrcAdapter::hash(current);
size_t bucketIndex = hash % hashMod;
buckets[bucketIndex].beginIndex++; // temporary use beginIndex to store the number of items
}
size_t beginIndex = 0;
for (size_t bucketIndex = 0; bucketIndex < numBuckets; bucketIndex++)
{
typename HashType::Bucket& bucket = buckets[bucketIndex];
size_t numElementsInBucket = bucket.beginIndex;
bucket.beginIndex = uint32_t(beginIndex);
bucket.endIndex = bucket.beginIndex;
beginIndex += numElementsInBucket;
}
// 2-st pass copy items
offset_t absoluteOffset = resizeArrayWithoutInitialization(dst->items, numElements);
for (Iter cur = begin; cur != end; ++cur)
{
const auto& current = *cur;
size_t hash = ItemSrcAdapter::hash(current);
size_t bucketIndex = hash % hashMod;
typename HashType::Bucket& bucket = dst->buckets[bucketIndex];
uint32_t elementIndex = bucket.endIndex;
offset_t currentItemAbsoluteOffset = absoluteOffset + sizeof(typename ItemDstAdapter::ItemType) * offset_t(elementIndex);
convertorFunc(this, currentItemAbsoluteOffset, *cur);
#ifdef ZMEYA_VALIDATE_HASH_DUPLICATES
const typename ItemDstAdapter::ItemType& lastItem =
getDirectMemoryAccess<typename ItemDstAdapter::ItemType>(currentItemAbsoluteOffset);
size_t newItemHash = ItemDstAdapter::hash(lastItem);
// inconsistent hashing! hash(srcItem) != hash(dstItem)
ZMEYA_ASSERT(hash == newItemHash);
for (uint32_t testElementIndex = bucket.beginIndex; testElementIndex < bucket.endIndex; testElementIndex++)
{
offset_t testItemAbsoluteOffset = absoluteOffset + sizeof(typename ItemDstAdapter::ItemType) * offset_t(testElementIndex);
const typename ItemDstAdapter::ItemType& testItem =
getDirectMemoryAccess<typename ItemDstAdapter::ItemType>(testItemAbsoluteOffset);
ZMEYA_ASSERT(!ItemDstAdapter::eq(testItem, lastItem));
}
#endif
bucket.endIndex++;
}
}
// assignTo pointer
template <typename T> static void assignTo(Pointer<T>& dst, std::nullptr_t) { dst.relativeOffset = 0; }
// assignTo pointer from absolute offset
template <typename T> void assignTo(Pointer<T>& _dst, offset_t targetAbsoluteOffset)
{
BlobPtr<Pointer<T>> dst = getBlobPtr(&_dst);
roffset_t relativeOffset = toRelativeOffset(diff(targetAbsoluteOffset, dst.getAbsoluteOffset()));