-
-
Notifications
You must be signed in to change notification settings - Fork 7
/
serialize.h
2105 lines (1779 loc) · 83.8 KB
/
serialize.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
/*
serialize
Copyright © 2016 - 2024, Mas Bandwidth LLC.
Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer
in the documentation and/or other materials provided with the distribution.
3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived
from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE
USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#ifndef SERIALIZE_H
#define SERIALIZE_H
/** @file */
#ifndef serialize_assert
#include <assert.h>
#define serialize_assert assert
#endif // #ifndef serialize_assert
#if defined(_MSC_VER) && !defined(_CRT_SECURE_NO_WARNINGS)
#define _CRT_SECURE_NO_WARNINGS
#endif
#if !defined(SERIALIZE_DEBUG) && !defined(SERIALIZE_RELEASE)
#if defined(NDEBUG)
#define SERIALIZE_RELEASE
#else
#define SERIALIZE_DEBUG
#endif
#elif defined(SERIALIZE_DEBUG) && defined(SERIALIZE_RELEASE)
#error Can only define one of debug & release
#endif
#if !defined(SERIALIZE_LITTLE_ENDIAN ) && !defined( SERIALIZE_BIG_ENDIAN )
#ifdef __BYTE_ORDER__
#if __BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__
#define SERIALIZE_LITTLE_ENDIAN 1
#elif __BYTE_ORDER__ == __ORDER_BIG_ENDIAN__
#define SERIALIZE_BIG_ENDIAN 1
#else
#error Unknown machine endianess detected. User needs to define SERIALIZE_LITTLE_ENDIAN or SERIALIZE_BIG_ENDIAN.
#endif // __BYTE_ORDER__
// Detect with GLIBC's endian.h
#elif defined(__GLIBC__)
#include <endian.h>
#if (__BYTE_ORDER == __LITTLE_ENDIAN)
#define SERIALIZE_LITTLE_ENDIAN 1
#elif (__BYTE_ORDER == __BIG_ENDIAN)
#define SERIALIZE_BIG_ENDIAN 1
#else
#error Unknown machine endianess detected. User needs to define SERIALIZE_LITTLE_ENDIAN or SERIALIZE_BIG_ENDIAN.
#endif // __BYTE_ORDER
// Detect with _LITTLE_ENDIAN and _BIG_ENDIAN macro
#elif defined(_LITTLE_ENDIAN) && !defined(_BIG_ENDIAN)
#define SERIALIZE_LITTLE_ENDIAN 1
#elif defined(_BIG_ENDIAN) && !defined(_LITTLE_ENDIAN)
#define SERIALIZE_BIG_ENDIAN 1
// Detect with architecture macros
#elif defined(__sparc) || defined(__sparc__) \
|| defined(_POWER) || defined(__powerpc__) \
|| defined(__ppc__) || defined(__hpux) || defined(__hppa) \
|| defined(_MIPSEB) || defined(_POWER) || defined(__s390__)
#define SERIALIZE_BIG_ENDIAN 1
#elif defined(__i386__) || defined(__alpha__) || defined(__ia64) \
|| defined(__ia64__) || defined(_M_IX86) || defined(_M_IA64) \
|| defined(_M_ALPHA) || defined(__amd64) || defined(__amd64__) \
|| defined(_M_AMD64) || defined(__x86_64) || defined(__x86_64__) \
|| defined(_M_X64) || defined(__bfin__)
#define SERIALIZE_LITTLE_ENDIAN 1
#elif defined(_MSC_VER) && defined(_M_ARM)
#define SERIALIZE_LITTLE_ENDIAN 1
#else
#error Unknown machine endianess detected. User needs to define SERIALIZE_LITTLE_ENDIAN or SERIALIZE_BIG_ENDIAN.
#endif
#endif
#ifndef SERIALIZE_LITTLE_ENDIAN
#define SERIALIZE_LITTLE_ENDIAN 0
#endif
#ifndef SERIALIZE_BIG_ENDIAN
#define SERIALIZE_BIG_ENDIAN 0
#endif
#ifdef _MSC_VER
#pragma warning( disable : 4127 )
#pragma warning( disable : 4244 )
#include <malloc.h>
#endif // #ifdef _MSC_VER
#include <stdint.h>
#include <stdlib.h>
#include <stddef.h>
#include <stdarg.h>
#include <stdio.h>
#include <string.h>
#include <memory.h>
#include <math.h>
#include <inttypes.h>
namespace serialize
{
/**
Calculates the population count of an unsigned 32 bit integer at compile time.
Population count is the number of bits in the integer that set to 1.
See "Hacker's Delight" and http://www.hackersdelight.org/hdcodetxt/popArrayHS.c.txt
@see serialize::Log2
@see serialize::BitsRequired
*/
template <uint32_t x> struct PopCount
{
enum { a = x - ( ( x >> 1 ) & 0x55555555 ),
b = ( ( ( a >> 2 ) & 0x33333333 ) + ( a & 0x33333333 ) ),
c = ( ( ( b >> 4 ) + b ) & 0x0f0f0f0f ),
d = c + ( c >> 8 ),
e = d + ( d >> 16 ),
result = e & 0x0000003f
};
};
/**
Calculates the log 2 of an unsigned 32 bit integer at compile time.
@see serialize::Log2
@see serialize::BitsRequired
*/
template <uint32_t x> struct Log2
{
enum { a = x | ( x >> 1 ),
b = a | ( a >> 2 ),
c = b | ( b >> 4 ),
d = c | ( c >> 8 ),
e = d | ( d >> 16 ),
f = e >> 1,
result = PopCount<f>::result
};
};
/**
Calculates the number of bits required to serialize an integer value in [min,max] at compile time.
@see Log2
@see PopCount
*/
template <int64_t min, int64_t max> struct BitsRequired
{
static const uint32_t result = ( min == max ) ? 0 : ( Log2<uint32_t(max-min)>::result + 1 );
};
/**
Calculates the population count of an unsigned 32 bit integer.
The population count is the number of bits in the integer set to 1.
@param x The input integer value.
@returns The number of bits set to 1 in the input value.
*/
inline uint32_t popcount( uint32_t x )
{
#ifdef __GNUC__
return __builtin_popcount( x );
#else // #ifdef __GNUC__
const uint32_t a = x - ( ( x >> 1 ) & 0x55555555 );
const uint32_t b = ( ( ( a >> 2 ) & 0x33333333 ) + ( a & 0x33333333 ) );
const uint32_t c = ( ( ( b >> 4 ) + b ) & 0x0f0f0f0f );
const uint32_t d = c + ( c >> 8 );
const uint32_t e = d + ( d >> 16 );
const uint32_t result = e & 0x0000003f;
return result;
#endif // #ifdef __GNUC__
}
/**
Calculates the log base 2 of an unsigned 32 bit integer.
@param x The input integer value.
@returns The log base 2 of the input.
*/
inline uint32_t log2( uint32_t x )
{
const uint32_t a = x | ( x >> 1 );
const uint32_t b = a | ( a >> 2 );
const uint32_t c = b | ( b >> 4 );
const uint32_t d = c | ( c >> 8 );
const uint32_t e = d | ( d >> 16 );
const uint32_t f = e >> 1;
return popcount( f );
}
/**
Calculates the number of bits required to serialize an integer in range [min,max].
@param min The minimum value.
@param max The maximum value.
@returns The number of bits required to serialize the integer.
*/
inline int bits_required( uint32_t min, uint32_t max )
{
#ifdef __GNUC__
return ( min == max ) ? 0 : 32 - __builtin_clz( max - min );
#else // #ifdef __GNUC__
return ( min == max ) ? 0 : log2( max - min ) + 1;
#endif // #ifdef __GNUC__
}
/**
Reverse the order of bytes in a 64 bit integer.
@param value The input value.
@returns The input value with the byte order reversed.
*/
inline uint64_t bswap( uint64_t value )
{
#ifdef __GNUC__
return __builtin_bswap64( value );
#else // #ifdef __GNUC__
value = ( value & 0x00000000FFFFFFFF ) << 32 | ( value & 0xFFFFFFFF00000000 ) >> 32;
value = ( value & 0x0000FFFF0000FFFF ) << 16 | ( value & 0xFFFF0000FFFF0000 ) >> 16;
value = ( value & 0x00FF00FF00FF00FF ) << 8 | ( value & 0xFF00FF00FF00FF00 ) >> 8;
return value;
#endif // #ifdef __GNUC__
}
/**
Reverse the order of bytes in a 32 bit integer.
@param value The input value.
@returns The input value with the byte order reversed.
*/
inline uint32_t bswap( uint32_t value )
{
#ifdef __GNUC__
return __builtin_bswap32( value );
#else // #ifdef __GNUC__
return ( value & 0x000000ff ) << 24 | ( value & 0x0000ff00 ) << 8 | ( value & 0x00ff0000 ) >> 8 | ( value & 0xff000000 ) >> 24;
#endif // #ifdef __GNUC__
}
/**
Reverse the order of bytes in a 16 bit integer.
@param value The input value.
@returns The input value with the byte order reversed.
*/
inline uint16_t bswap( uint16_t value )
{
return ( value & 0x00ff ) << 8 | ( value & 0xff00 ) >> 8;
}
/**
Template to convert an integer value from local byte order to network byte order.
IMPORTANT: Because most machines are little endian, serialize defines network byte order to be little endian.
@param value The input value in local byte order. Supported integer types: uint64_t, uint32_t, uint16_t.
@returns The input value converted to network byte order. If this processor is little endian the output is the same as the input. If the processor is big endian, the output is the input byte swapped.
@see serialize::bswap
*/
template <typename T> T host_to_network( T value )
{
#if SERIALIZE_BIG_ENDIAN
return bswap( value );
#else // #if SERIALIZE_BIG_ENDIAN
return value;
#endif // #if SERIALIZE_BIG_ENDIAN
}
/**
Template to convert an integer value from network byte order to local byte order.
IMPORTANT: Because most machines are little endian, serialize defines network byte order to be little endian.
@param value The input value in network byte order. Supported integer types: uint64_t, uint32_t, uint16_t.
@returns The input value converted to local byte order. If this processor is little endian the output is the same as the input. If the processor is big endian, the output is the input byte swapped.
@see serialize::bswap
*/
template <typename T> T network_to_host( T value )
{
#if SERIALIZE_BIG_ENDIAN
return bswap( value );
#else // #if SERIALIZE_BIG_ENDIAN
return value;
#endif // #if SERIALIZE_BIG_ENDIAN
}
/**
Convert a signed integer to an unsigned integer with zig-zag encoding.
0,-1,+1,-2,+2... becomes 0,1,2,3,4 ...
@param n The input value.
@returns The input value converted from signed to unsigned with zig-zag encoding.
*/
inline int signed_to_unsigned( int n )
{
return ( n << 1 ) ^ ( n >> 31 );
}
/**
Convert an unsigned integer to as signed integer with zig-zag encoding.
0,1,2,3,4... becomes 0,-1,+1,-2,+2...
@param n The input value.
@returns The input value converted from unsigned to signed with zig-zag encoding.
*/
inline int unsigned_to_signed( uint32_t n )
{
return ( n >> 1 ) ^ ( -int32_t( n & 1 ) );
}
template <typename T> T clamp( const T & value, const T & a, const T & b )
{
if ( value < a )
return a;
else if ( value > b )
return b;
else
return value;
}
/**
Bitpacks unsigned integer values to a buffer.
Integer bit values are written to a 64 bit scratch value from right to left.
Once the low 32 bits of the scratch is filled with bits it is flushed to memory as a dword and the scratch value is shifted right by 32.
The bit stream is written to memory in little endian order, which is considered network byte order for this library.
@see BitReader
*/
class BitWriter
{
public:
/**
Bit writer constructor.
Creates a bit writer object to write to the specified buffer.
@param data The pointer to the buffer to fill with bitpacked data.
@param bytes The size of the buffer in bytes. Must be a multiple of 4, because the bitpacker reads and writes memory as dwords, not bytes.
*/
BitWriter( void * data, int bytes ) : m_data( (uint32_t*) data ), m_numWords( bytes / 4 )
{
serialize_assert( data );
serialize_assert( ( bytes % 4 ) == 0 );
m_numBits = m_numWords * 32;
m_bitsWritten = 0;
m_wordIndex = 0;
m_scratch = 0;
m_scratchBits = 0;
}
/**
Write bits to the buffer.
Bits are written to the buffer as-is, without padding to nearest byte. Will assert if you try to write past the end of the buffer.
A boolean value writes just 1 bit to the buffer, a value in range [0,31] can be written with just 5 bits and so on.
IMPORTANT: When you have finished writing to your buffer, take care to call BitWrite::FlushBits, otherwise the last dword of data will not get flushed to memory!
@param value The integer value to write to the buffer. Must be in [0,(1<<bits)-1].
@param bits The number of bits to encode in [1,32].
@see BitReader::ReadBits
*/
void WriteBits( uint32_t value, int bits )
{
serialize_assert( bits > 0 );
serialize_assert( bits <= 32 );
serialize_assert( m_bitsWritten + bits <= m_numBits );
serialize_assert( uint64_t( value ) <= ( ( 1ULL << bits ) - 1 ) );
m_scratch |= uint64_t( value ) << m_scratchBits;
m_scratchBits += bits;
if ( m_scratchBits >= 32 )
{
serialize_assert( m_wordIndex < m_numWords );
m_data[m_wordIndex] = host_to_network( uint32_t( m_scratch & 0xFFFFFFFF ) );
m_scratch >>= 32;
m_scratchBits -= 32;
m_wordIndex++;
}
m_bitsWritten += bits;
}
/**
Write an alignment to the bit stream, padding zeros so the bit index becomes is a multiple of 8.
This is useful if you want to write some data to a packet that should be byte aligned. For example, an array of bytes, or a string.
IMPORTANT: If the current bit index is already a multiple of 8, nothing is written.
@see BitReader::ReadAlign
*/
void WriteAlign()
{
const int remainderBits = m_bitsWritten % 8;
if ( remainderBits != 0 )
{
uint32_t zero = 0;
WriteBits( zero, 8 - remainderBits );
serialize_assert( ( m_bitsWritten % 8 ) == 0 );
}
}
/**
Write an array of bytes to the bit stream.
Use this when you have to copy a large block of data into your bitstream.
Faster than just writing each byte to the bit stream via BitWriter::WriteBits( value, 8 ), because it aligns to byte index and copies into the buffer without bitpacking.
@param data The byte array data to write to the bit stream.
@param bytes The number of bytes to write.
@see BitReader::ReadBytes
*/
void WriteBytes( const uint8_t * data, int bytes )
{
serialize_assert( GetAlignBits() == 0 );
serialize_assert( m_bitsWritten + bytes * 8 <= m_numBits );
serialize_assert( ( m_bitsWritten % 32 ) == 0 || ( m_bitsWritten % 32 ) == 8 || ( m_bitsWritten % 32 ) == 16 || ( m_bitsWritten % 32 ) == 24 );
int headBytes = ( 4 - ( m_bitsWritten % 32 ) / 8 ) % 4;
if ( headBytes > bytes )
headBytes = bytes;
for ( int i = 0; i < headBytes; ++i )
WriteBits( data[i], 8 );
if ( headBytes == bytes )
return;
FlushBits();
serialize_assert( GetAlignBits() == 0 );
int numWords = ( bytes - headBytes ) / 4;
if ( numWords > 0 )
{
serialize_assert( ( m_bitsWritten % 32 ) == 0 );
memcpy( &m_data[m_wordIndex], data + headBytes, numWords * 4 );
m_bitsWritten += numWords * 32;
m_wordIndex += numWords;
m_scratch = 0;
}
serialize_assert( GetAlignBits() == 0 );
int tailStart = headBytes + numWords * 4;
int tailBytes = bytes - tailStart;
serialize_assert( tailBytes >= 0 && tailBytes < 4 );
for ( int i = 0; i < tailBytes; ++i )
WriteBits( data[tailStart+i], 8 );
serialize_assert( GetAlignBits() == 0 );
serialize_assert( headBytes + numWords * 4 + tailBytes == bytes );
}
/**
Flush any remaining bits to memory.
Call this once after you've finished writing bits to flush the last dword of scratch to memory!
@see BitWriter::WriteBits
*/
void FlushBits()
{
if ( m_scratchBits != 0 )
{
serialize_assert( m_scratchBits <= 32 );
serialize_assert( m_wordIndex < m_numWords );
m_data[m_wordIndex] = host_to_network( uint32_t( m_scratch & 0xFFFFFFFF ) );
m_scratch >>= 32;
m_scratchBits = 0;
m_wordIndex++;
}
}
/**
How many align bits would be written, if we were to write an align right now?
@returns Result in [0,7], where 0 is zero bits required to align (already aligned) and 7 is worst case.
*/
int GetAlignBits() const
{
return ( 8 - ( m_bitsWritten % 8 ) ) % 8;
}
/**
How many bits have we written so far?
@returns The number of bits written to the bit buffer.
*/
int GetBitsWritten() const
{
return m_bitsWritten;
}
/**
How many bits are still available to write?
For example, if the buffer size is 4, we have 32 bits available to write, if we have already written 10 bytes then 22 are still available to write.
@returns The number of bits available to write.
*/
int GetBitsAvailable() const
{
return m_numBits - m_bitsWritten;
}
/**
Get a pointer to the data written by the bit writer.
Corresponds to the data block passed in to the constructor.
@returns Pointer to the data written by the bit writer.
*/
const uint8_t * GetData() const
{
return (uint8_t*) m_data;
}
/**
The number of bytes flushed to memory.
This is effectively the size of the packet that you should send after you have finished bitpacking values with this class.
The returned value is not always a multiple of 4, even though we flush dwords to memory. You won't miss any data in this case because the order of bits written is designed to work with the little endian memory layout.
IMPORTANT: Make sure you call BitWriter::FlushBits before calling this method, otherwise you risk missing the last dword of data.
*/
int GetBytesWritten() const
{
return ( m_bitsWritten + 7 ) / 8;
}
private:
uint32_t * m_data; ///< The buffer we are writing to, as a uint32_t * because we're writing dwords at a time.
uint64_t m_scratch; ///< The scratch value where we write bits to (right to left). 64 bit for overflow. Once # of bits in scratch is >= 32, the low 32 bits are flushed to memory.
int m_numBits; ///< The number of bits in the buffer. This is equivalent to the size of the buffer in bytes multiplied by 8. Note that the buffer size must always be a multiple of 4.
int m_numWords; ///< The number of words in the buffer. This is equivalent to the size of the buffer in bytes divided by 4. Note that the buffer size must always be a multiple of 4.
int m_bitsWritten; ///< The number of bits written so far.
int m_wordIndex; ///< The current word index. The next word flushed to memory will be at this index in m_data.
int m_scratchBits; ///< The number of bits in scratch. When this is >= 32, the low 32 bits of scratch is flushed to memory as a dword and scratch is shifted right by 32.
};
/**
Reads bit packed integer values from a buffer.
Relies on the user reconstructing the exact same set of bit reads as bit writes when the buffer was written. This is an unattributed bitpacked binary stream!
Implementation: 32 bit dwords are read in from memory to the high bits of a scratch value as required. The user reads off bit values from the scratch value from the right, after which the scratch value is shifted by the same number of bits.
*/
class BitReader
{
public:
/**
Bit reader constructor.
Non-multiples of four buffer sizes are supported, as this naturally tends to occur when packets are read from the network.
However, actual buffer allocated for the packet data must round up at least to the next 4 bytes in memory, because the bit reader reads dwords from memory not bytes.
@param data Pointer to the bitpacked data to read.
@param bytes The number of bytes of bitpacked data to read.
@see BitWriter
*/
#ifdef SERIALIZE_DEBUG
BitReader( const void * data, int bytes ) : m_data( (const uint32_t*) data ), m_numBytes( bytes ), m_numWords( ( bytes + 3 ) / 4)
#else // #ifdef SERIALIZE_DEBUG
BitReader( const void * data, int bytes ) : m_data( (const uint32_t*) data ), m_numBytes( bytes )
#endif // #ifdef SERIALIZE_DEBUG
{
serialize_assert( data );
m_numBits = m_numBytes * 8;
m_bitsRead = 0;
m_scratch = 0;
m_scratchBits = 0;
m_wordIndex = 0;
}
/**
Would the bit reader would read past the end of the buffer if it read this many bits?
@param bits The number of bits that would be read.
@returns True if reading the number of bits would read past the end of the buffer.
*/
bool WouldReadPastEnd( int bits ) const
{
return m_bitsRead + bits > m_numBits;
}
/**
Read bits from the bit buffer.
This function will assert in debug builds if this read would read past the end of the buffer.
In production situations, the higher level ReadStream takes care of checking all packet data and never calling this function if it would read past the end of the buffer.
@param bits The number of bits to read in [1,32].
@returns The integer value read in range [0,(1<<bits)-1].
@see BitReader::WouldReadPastEnd
@see BitWriter::WriteBits
*/
uint32_t ReadBits( int bits )
{
serialize_assert( bits > 0 );
serialize_assert( bits <= 32 );
serialize_assert( m_bitsRead + bits <= m_numBits );
m_bitsRead += bits;
serialize_assert( m_scratchBits >= 0 && m_scratchBits <= 64 );
if ( m_scratchBits < bits )
{
#ifdef SERIALIZE_DEBUG
serialize_assert( m_wordIndex < m_numWords );
#endif // SERIALIZE_DEBUG
m_scratch |= uint64_t( network_to_host( m_data[m_wordIndex] ) ) << m_scratchBits;
m_scratchBits += 32;
m_wordIndex++;
}
serialize_assert( m_scratchBits >= bits );
const uint32_t output = m_scratch & ( (uint64_t(1)<<bits) - 1 );
m_scratch >>= bits;
m_scratchBits -= bits;
return output;
}
/**
Read an align.
Call this on read to correspond to a WriteAlign call when the bitpacked buffer was written.
This makes sure we skip ahead to the next aligned byte index. As a safety check, we verify that the padding to next byte is zero bits and return false if that's not the case.
This will typically abort packet read. Just another safety measure...
@returns True if we successfully read an align and skipped ahead past zero pad, false otherwise (probably means, no align was written to the stream).
@see BitWriter::WriteAlign
*/
bool ReadAlign()
{
const int remainderBits = m_bitsRead % 8;
if ( remainderBits != 0 )
{
uint32_t value = ReadBits( 8 - remainderBits );
serialize_assert( m_bitsRead % 8 == 0 );
if ( value != 0 )
return false;
}
return true;
}
/**
Read bytes from the bitpacked data.
@see BitWriter::WriteBytes
*/
void ReadBytes( uint8_t * data, int bytes )
{
serialize_assert( GetAlignBits() == 0 );
serialize_assert( m_bitsRead + bytes * 8 <= m_numBits );
serialize_assert( ( m_bitsRead % 32 ) == 0 || ( m_bitsRead % 32 ) == 8 || ( m_bitsRead % 32 ) == 16 || ( m_bitsRead % 32 ) == 24 );
int headBytes = ( 4 - ( m_bitsRead % 32 ) / 8 ) % 4;
if ( headBytes > bytes )
headBytes = bytes;
for ( int i = 0; i < headBytes; ++i )
data[i] = (uint8_t) ReadBits( 8 );
if ( headBytes == bytes )
return;
serialize_assert( GetAlignBits() == 0 );
int numWords = ( bytes - headBytes ) / 4;
if ( numWords > 0 )
{
serialize_assert( ( m_bitsRead % 32 ) == 0 );
memcpy( data + headBytes, &m_data[m_wordIndex], numWords * 4 );
m_bitsRead += numWords * 32;
m_wordIndex += numWords;
m_scratchBits = 0;
}
serialize_assert( GetAlignBits() == 0 );
int tailStart = headBytes + numWords * 4;
int tailBytes = bytes - tailStart;
serialize_assert( tailBytes >= 0 && tailBytes < 4 );
for ( int i = 0; i < tailBytes; ++i )
data[tailStart+i] = (uint8_t) ReadBits( 8 );
serialize_assert( GetAlignBits() == 0 );
serialize_assert( headBytes + numWords * 4 + tailBytes == bytes );
}
/**
How many align bits would be read, if we were to read an align right now?
@returns Result in [0,7], where 0 is zero bits required to align (already aligned) and 7 is worst case.
*/
int GetAlignBits() const
{
return ( 8 - m_bitsRead % 8 ) % 8;
}
/**
How many bits have we read so far?
@returns The number of bits read from the bit buffer so far.
*/
int GetBitsRead() const
{
return m_bitsRead;
}
/**
How many bits are still available to read?
For example, if the buffer size is 4, we have 32 bits available to read, if we have already written 10 bytes then 22 are still available.
@returns The number of bits available to read.
*/
int GetBitsRemaining() const
{
return m_numBits - m_bitsRead;
}
private:
const uint32_t * m_data; ///< The bitpacked data we're reading as a dword array.
uint64_t m_scratch; ///< The scratch value. New data is read in 32 bits at a top to the left of this buffer, and data is read off to the right.
int m_numBits; ///< Number of bits to read in the buffer. Of course, we can't *really* know this so it's actually m_numBytes * 8.
int m_numBytes; ///< Number of bytes to read in the buffer. We know this, and this is the non-rounded up version.
#ifdef SERIALIZE_DEBUG
int m_numWords; ///< Number of words to read in the buffer. This is rounded up to the next word if necessary.
#endif // #ifdef SERIALIZE_DEBUG
int m_bitsRead; ///< Number of bits read from the buffer so far.
int m_scratchBits; ///< Number of bits currently in the scratch value. If the user wants to read more bits than this, we have to go fetch another dword from memory.
int m_wordIndex; ///< Index of the next word to read from memory.
};
/**
Functionality common to all stream classes.
*/
class BaseStream
{
public:
/**
Base stream constructor.
*/
explicit BaseStream() : m_context( NULL ), m_allocator( NULL ) {}
/**
Set a context on the stream.
Contexts are used by the library supply data that is needed to read and write packets.
Specifically, this context is used by the connection to supply data needed to read and write connection packets.
*/
void SetContext( void * context )
{
m_context = context;
}
/**
Get the context pointer set on the stream.
@returns The context pointer. May be NULL.
*/
void * GetContext() const
{
return m_context;
}
/**
Set an allocator pointer on the stream.
This can be helpful if you want to perform allocations within serialize functions.
*/
void SetAllocator( void * allocator )
{
m_allocator = allocator;
}
/**
Get the allocator pointer set on the stream.
@returns The allocator pointer. May be NULL.
*/
void * GetAllocator() const
{
return m_allocator;
}
private:
void * m_context; ///< The context pointer set on the stream. May be NULL.
void * m_allocator; ///< The allocator pointer set on the stream. May be NULL.
};
/**
Stream class for writing bitpacked data.
This class is a wrapper around the bit writer class. Its purpose is to provide unified interface for reading and writing.
You can determine if you are writing to a stream by calling Stream::IsWriting inside your templated serialize method.
This is evaluated at compile time, letting the compiler generate optimized serialize functions without the hassle of maintaining separate read and write functions.
IMPORTANT: Generally, you don't call methods on this class directly. Use the serialize_* macros instead.
@see BitWriter
*/
class WriteStream : public BaseStream
{
public:
enum { IsWriting = 1 };
enum { IsReading = 0 };
/**
Write stream constructor.
@param buffer The buffer to write to.
@param bytes The number of bytes in the buffer. Must be a multiple of four.
@param allocator The allocator to use for stream allocations. This lets you dynamically allocate memory as you read and write packets.
*/
WriteStream( uint8_t * buffer, int bytes ) : m_writer( buffer, bytes ) {}
/**
Serialize an integer (write).
@param value The integer value in [min,max].
@param min The minimum value.
@param max The maximum value.
@returns Always returns true. All checking is performed by debug asserts only on write.
*/
bool SerializeInteger( int32_t value, int32_t min, int32_t max )
{
serialize_assert( min < max );
serialize_assert( value >= min );
serialize_assert( value <= max );
const int bits = bits_required( min, max );
uint32_t unsigned_value = value - min;
m_writer.WriteBits( unsigned_value, bits );
return true;
}
/**
Serialize a number of bits (write).
@param value The unsigned integer value to serialize. Must be in range [0,(1<<bits)-1].
@param bits The number of bits to write in [1,32].
@returns Always returns true. All checking is performed by debug asserts on write.
*/
bool SerializeBits( uint32_t value, int bits )
{
serialize_assert( bits > 0 );
serialize_assert( bits <= 32 );
m_writer.WriteBits( value, bits );
return true;
}
/**
Serialize an array of bytes (write).
@param data Array of bytes to be written.
@param bytes The number of bytes to write.
@returns Always returns true. All checking is performed by debug asserts on write.
*/
bool SerializeBytes( const uint8_t * data, int bytes )
{
serialize_assert( data );
serialize_assert( bytes >= 0 );
SerializeAlign();
m_writer.WriteBytes( data, bytes );
return true;
}
/**
Serialize an align (write).
@returns Always returns true. All checking is performed by debug asserts on write.
*/
bool SerializeAlign()
{
m_writer.WriteAlign();
return true;
}
/**
If we were to write an align right now, how many bits would be required?
@returns The number of zero pad bits required to achieve byte alignment in [0,7].
*/
int GetAlignBits() const
{
return m_writer.GetAlignBits();
}
/**
Flush the stream to memory after you finish writing.
Always call this after you finish writing and before you call WriteStream::GetData, or you'll potentially truncate the last dword of data you wrote.
@see BitWriter::FlushBits
*/
void Flush()
{
m_writer.FlushBits();
}
/**
Get a pointer to the data written by the stream.
IMPORTANT: Call WriteStream::Flush before you call this function!
@returns A pointer to the data written by the stream
*/
const uint8_t * GetData() const
{
return m_writer.GetData();
}
/**
How many bytes have been written so far?
@returns Number of bytes written. This is effectively the packet size.
*/
int GetBytesProcessed() const
{
return m_writer.GetBytesWritten();
}
/**
Get number of bits written so far.
@returns Number of bits written.
*/
int GetBitsProcessed() const
{
return m_writer.GetBitsWritten();
}
private:
BitWriter m_writer; ///< The bit writer used for all bitpacked write operations.
};
/**
Stream class for reading bitpacked data.
This class is a wrapper around the bit reader class. Its purpose is to provide unified interface for reading and writing.
You can determine if you are reading from a stream by calling Stream::IsReading inside your templated serialize method.
This is evaluated at compile time, letting the compiler generate optimized serialize functions without the hassle of maintaining separate read and write functions.
IMPORTANT: Generally, you don't call methods on this class directly. Use the serialize_* macros instead.
@see BitReader
*/
class ReadStream : public BaseStream
{
public:
enum { IsWriting = 0 };
enum { IsReading = 1 };
/**
Read stream constructor.
@param buffer The buffer to read from.
@param bytes The number of bytes in the buffer. May be a non-multiple of four, however if it is, the underlying buffer allocated should be large enough to read the any remainder bytes as a dword.
@param allocator The allocator to use for stream allocations. This lets you dynamically allocate memory as you read and write packets.
*/
ReadStream( const uint8_t * buffer, int bytes ) : m_reader( buffer, bytes ) {}
/**
Serialize an integer (read).
@param value The integer value read is stored here. It is guaranteed to be in [min,max] if this function succeeds.
@param min The minimum allowed value.
@param max The maximum allowed value.
@returns Returns true if the serialize succeeded and the value is in the correct range. False otherwise.
*/
bool SerializeInteger( int32_t & value, int32_t min, int32_t max )
{
serialize_assert( min < max );
const int bits = bits_required( min, max );
if ( m_reader.WouldReadPastEnd( bits ) )
return false;
uint32_t unsigned_value = m_reader.ReadBits( bits );
value = (int32_t) unsigned_value + min;
return true;
}
/**