summaryrefslogtreecommitdiffstats
path: root/src/ByteBuffer.cpp
blob: 80be9baee98f3cdc19fa55a92dc0a771dc389d63 (plain) (blame)
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058

// ByteBuffer.cpp

// Implements the cByteBuffer class representing a ringbuffer of bytes

#include "Globals.h"

#include "ByteBuffer.h"
#include "Endianness.h"
#include "UUID.h"
#include "OSSupport/IsThread.h"





/** When defined, each access to a cByteBuffer object is checked whether it's done in the same thread.
cByteBuffer assumes that it is not used by multiple threads at once, this macro adds a runtime check for that.
Unfortunately it is very slow, so it is disabled even for regular DEBUG builds. */
// #define DEBUG_SINGLE_THREAD_ACCESS





// If a string sent over the protocol is larger than this, a warning is emitted to the console
#define MAX_STRING_SIZE (512 KiB)

#define NEEDBYTES(Num) if (!CanReadBytes(Num))  return false  // Check if at least Num bytes can be read from  the buffer, return false if not
#define PUTBYTES(Num)  if (!CanWriteBytes(Num)) return false  // Check if at least Num bytes can be written to the buffer, return false if not





#ifdef DEBUG_SINGLE_THREAD_ACCESS

	/** Simple RAII class that is used for checking that no two threads are using an object simultanously.
	It requires the monitored object to provide the storage for a thread ID.
	It uses that storage to check if the thread ID of consecutive calls is the same all the time. */
	class cSingleThreadAccessChecker
	{
	public:
		cSingleThreadAccessChecker(std::thread::id * a_ThreadID) :
			m_ThreadID(a_ThreadID)
		{
			ASSERT(
				(*a_ThreadID == std::this_thread::get_id()) ||  // Either the object is used by current thread...
				(*a_ThreadID == m_EmptyThreadID)                // ... or by no thread at all
			);

			// Mark as being used by this thread:
			*m_ThreadID = std::this_thread::get_id();
		}

		~cSingleThreadAccessChecker()
		{
			// Mark as not being used by any thread:
			*m_ThreadID = std::thread::id();
		}

	protected:
		/** Points to the storage used for ID of the thread using the object. */
		std::thread::id * m_ThreadID;

		/** The value of an unassigned thread ID, used to speed up checking. */
		static std::thread::id m_EmptyThreadID;
	};

	std::thread::id cSingleThreadAccessChecker::m_EmptyThreadID;

	#define CHECK_THREAD cSingleThreadAccessChecker Checker(&m_ThreadID);

#else
	#define CHECK_THREAD
#endif





////////////////////////////////////////////////////////////////////////////////
// cByteBuffer:

cByteBuffer::cByteBuffer(size_t a_BufferSize) :
	m_Buffer(new std::byte[a_BufferSize + 1]),
	m_BufferSize(a_BufferSize + 1),
	m_DataStart(0),
	m_WritePos(0),
	m_ReadPos(0)
{
	// Allocating one byte more than the buffer size requested, so that we can distinguish between
	// completely-full and completely-empty states
}





cByteBuffer::~cByteBuffer()
{
	CheckValid();
	delete[] m_Buffer;
	m_Buffer = nullptr;
}





bool cByteBuffer::Write(const void * a_Bytes, size_t a_Count)
{
	CHECK_THREAD
	CheckValid();

	// Store the current free space for a check after writing:
	size_t CurFreeSpace = GetFreeSpace();
	#ifndef NDEBUG
		size_t CurReadableSpace = GetReadableSpace();
		size_t WrittenBytes = 0;
	#endif

	if (CurFreeSpace < a_Count)
	{
		return false;
	}
	ASSERT(m_BufferSize >= m_WritePos);
	size_t TillEnd = m_BufferSize - m_WritePos;
	const char * Bytes = static_cast<const char *>(a_Bytes);
	if (TillEnd <= a_Count)
	{
		// Need to wrap around the ringbuffer end
		if (TillEnd > 0)
		{
			memcpy(m_Buffer + m_WritePos, Bytes, TillEnd);
			Bytes += TillEnd;
			a_Count -= TillEnd;
			#ifndef NDEBUG
				WrittenBytes = TillEnd;
			#endif
		}
		m_WritePos = 0;
	}

	// We're guaranteed that we'll fit in a single write op
	if (a_Count > 0)
	{
		memcpy(m_Buffer + m_WritePos, Bytes, a_Count);
		m_WritePos += a_Count;
		#ifndef NDEBUG
			WrittenBytes += a_Count;
		#endif
	}

	ASSERT(GetFreeSpace() == CurFreeSpace - WrittenBytes);
	ASSERT(GetReadableSpace() == CurReadableSpace + WrittenBytes);
	return true;
}





size_t cByteBuffer::GetFreeSpace(void) const
{
	CHECK_THREAD
	CheckValid();
	if (m_WritePos >= m_DataStart)
	{
		// Wrap around the buffer end:
		ASSERT(m_BufferSize >= m_WritePos);
		ASSERT((m_BufferSize - m_WritePos + m_DataStart) >= 1);
		return m_BufferSize - m_WritePos + m_DataStart - 1;
	}
	// Single free space partition:
	ASSERT(m_BufferSize >= m_WritePos);
	ASSERT(m_BufferSize - m_WritePos >= 1);
	return m_DataStart - m_WritePos - 1;
}





size_t cByteBuffer::GetUsedSpace(void) const
{
	CHECK_THREAD
	CheckValid();
	ASSERT(m_BufferSize >= GetFreeSpace());
	ASSERT((m_BufferSize - GetFreeSpace()) >= 1);
	return m_BufferSize - GetFreeSpace() - 1;
}





size_t cByteBuffer::GetReadableSpace(void) const
{
	CHECK_THREAD
	CheckValid();
	if (m_ReadPos > m_WritePos)
	{
		// Wrap around the buffer end:
		ASSERT(m_BufferSize >= m_ReadPos);
		return m_BufferSize - m_ReadPos + m_WritePos;
	}
	// Single readable space partition:
	ASSERT(m_WritePos >= m_ReadPos);
	return m_WritePos - m_ReadPos;
}





bool cByteBuffer::CanReadBytes(size_t a_Count) const
{
	CHECK_THREAD
	CheckValid();
	return (a_Count <= GetReadableSpace());
}





bool cByteBuffer::CanWriteBytes(size_t a_Count) const
{
	CHECK_THREAD
	CheckValid();
	return (a_Count <= GetFreeSpace());
}





bool cByteBuffer::ReadBEInt8(Int8 & a_Value)
{
	CHECK_THREAD
	CheckValid();
	NEEDBYTES(1);
	ReadBuf(&a_Value, 1);
	return true;
}





bool cByteBuffer::ReadBEUInt8(UInt8 & a_Value)
{
	CHECK_THREAD
	CheckValid();
	NEEDBYTES(1);
	ReadBuf(&a_Value, 1);
	return true;
}





bool cByteBuffer::ReadBEInt16(Int16 & a_Value)
{
	CHECK_THREAD
	CheckValid();
	NEEDBYTES(2);
	UInt16 val;
	ReadBuf(&val, 2);
	val = ntohs(val);
	memcpy(&a_Value, &val, 2);
	return true;
}





bool cByteBuffer::ReadBEUInt16(UInt16 & a_Value)
{
	CHECK_THREAD
	CheckValid();
	NEEDBYTES(2);
	ReadBuf(&a_Value, 2);
	a_Value = ntohs(a_Value);
	return true;
}





bool cByteBuffer::ReadBEInt32(Int32 & a_Value)
{
	CHECK_THREAD
	CheckValid();
	NEEDBYTES(4);
	UInt32 val;
	ReadBuf(&val, 4);
	val = ntohl(val);
	memcpy(&a_Value, &val, 4);
	return true;
}





bool cByteBuffer::ReadBEUInt32(UInt32 & a_Value)
{
	CHECK_THREAD
	CheckValid();
	NEEDBYTES(4);
	ReadBuf(&a_Value, 4);
	a_Value = ntohl(a_Value);
	return true;
}





bool cByteBuffer::ReadBEInt64(Int64 & a_Value)
{
	CHECK_THREAD
	CheckValid();
	NEEDBYTES(8);
	ReadBuf(&a_Value, 8);
	a_Value = NetworkToHostLong8(&a_Value);
	return true;
}





bool cByteBuffer::ReadBEUInt64(UInt64 & a_Value)
{
	CHECK_THREAD
	CheckValid();
	NEEDBYTES(8);
	ReadBuf(&a_Value, 8);
	a_Value = NetworkToHostULong8(&a_Value);
	return true;
}





bool cByteBuffer::ReadBEFloat(float & a_Value)
{
	CHECK_THREAD
	CheckValid();
	NEEDBYTES(4);
	ReadBuf(&a_Value, 4);
	a_Value = NetworkToHostFloat4(&a_Value);
	return true;
}





bool cByteBuffer::ReadBEDouble(double & a_Value)
{
	CHECK_THREAD
	CheckValid();
	NEEDBYTES(8);
	ReadBuf(&a_Value, 8);
	a_Value = NetworkToHostDouble8(&a_Value);
	return true;
}





bool cByteBuffer::ReadBool(bool & a_Value)
{
	CHECK_THREAD
	CheckValid();
	NEEDBYTES(1);
	UInt8 Value = 0;
	ReadBuf(&Value, 1);
	a_Value = (Value != 0);
	return true;
}





bool cByteBuffer::ReadVarInt32(UInt32 & a_Value)
{
	CHECK_THREAD
	CheckValid();
	UInt32 Value = 0;
	int Shift = 0;
	unsigned char b = 0;
	do
	{
		NEEDBYTES(1);
		ReadBuf(&b, 1);
		Value = Value | ((static_cast<UInt32>(b & 0x7f)) << Shift);
		Shift += 7;
	} while ((b & 0x80) != 0);
	a_Value = Value;
	return true;
}





bool cByteBuffer::ReadVarInt64(UInt64 & a_Value)
{
	CHECK_THREAD
	CheckValid();
	UInt64 Value = 0;
	int Shift = 0;
	unsigned char b = 0;
	do
	{
		NEEDBYTES(1);
		ReadBuf(&b, 1);
		Value = Value | ((static_cast<UInt64>(b & 0x7f)) << Shift);
		Shift += 7;
	} while ((b & 0x80) != 0);
	a_Value = Value;
	return true;
}





bool cByteBuffer::ReadVarUTF8String(AString & a_Value)
{
	CHECK_THREAD
	CheckValid();
	UInt32 Size = 0;
	if (!ReadVarInt(Size))
	{
		return false;
	}
	if (Size > MAX_STRING_SIZE)
	{
		LOGWARNING("%s: String too large: %u (%u KiB)", __FUNCTION__, Size, Size / 1024);
	}
	ContiguousByteBuffer Buffer;
	if (!ReadSome(Buffer, static_cast<size_t>(Size)))
	{
		return false;
	}
	// "Convert" a UTF-8 encoded string into system-native char.
	// This isn't great, better would be to use codecvt:
	a_Value = { reinterpret_cast<const char *>(Buffer.data()), Buffer.size() };
	return true;
}





bool cByteBuffer::ReadLEInt(int & a_Value)
{
	CHECK_THREAD
	CheckValid();
	NEEDBYTES(4);
	ReadBuf(&a_Value, 4);

	#ifdef IS_BIG_ENDIAN
		// Convert:
		a_Value = ((a_Value >> 24) & 0xff) | ((a_Value >> 16) & 0xff00) | ((a_Value >> 8) & 0xff0000) | (a_Value & 0xff000000);
	#endif

	return true;
}





bool cByteBuffer::ReadXYZPosition64(int & a_BlockX, int & a_BlockY, int & a_BlockZ)
{
	CHECK_THREAD
	Int64 Value;
	if (!ReadBEInt64(Value))
	{
		return false;
	}

	// Convert the 64 received bits into 3 coords:
	UInt32 BlockXRaw = (Value >> 38) & 0x03ffffff;  // Top 26 bits
	UInt32 BlockYRaw = (Value >> 26) & 0x0fff;      // Middle 12 bits
	UInt32 BlockZRaw = (Value & 0x03ffffff);        // Bottom 26 bits

	// If the highest bit in the number's range is set, convert the number into negative:
	a_BlockX = ((BlockXRaw & 0x02000000) == 0) ? static_cast<int>(BlockXRaw) : -(0x04000000 - static_cast<int>(BlockXRaw));
	a_BlockY = ((BlockYRaw & 0x0800) == 0)     ? static_cast<int>(BlockYRaw) : -(0x01000    - static_cast<int>(BlockYRaw));
	a_BlockZ = ((BlockZRaw & 0x02000000) == 0) ? static_cast<int>(BlockZRaw) : -(0x04000000 - static_cast<int>(BlockZRaw));
	return true;
}





bool cByteBuffer::ReadXZYPosition64(int & a_BlockX, int & a_BlockY, int & a_BlockZ)
{
	CHECK_THREAD
	Int64 Value;
	if (!ReadBEInt64(Value))
	{
		return false;
	}

	// Convert the 64 received bits into 3 coords:
	UInt32 BlockXRaw = (Value >> 38) & 0x03ffffff;  // Top 26 bits
	UInt32 BlockZRaw = (Value >> 12) & 0x03ffffff;  // Middle 26 bits
	UInt32 BlockYRaw = (Value & 0x0fff);            // Bottom 12 bits

	// If the highest bit in the number's range is set, convert the number into negative:
	a_BlockX = ((BlockXRaw & 0x02000000) == 0) ? static_cast<int>(BlockXRaw) : (static_cast<int>(BlockXRaw) - 0x04000000);
	a_BlockY = ((BlockYRaw & 0x0800)     == 0) ? static_cast<int>(BlockYRaw) : (static_cast<int>(BlockYRaw) - 0x01000);
	a_BlockZ = ((BlockZRaw & 0x02000000) == 0) ? static_cast<int>(BlockZRaw) : (static_cast<int>(BlockZRaw) - 0x04000000);
	return true;
}





bool cByteBuffer::ReadUUID(cUUID & a_Value)
{
	CHECK_THREAD

	std::array<Byte, 16> UUIDBuf;
	if (!ReadBuf(UUIDBuf.data(), UUIDBuf.size()))
	{
		return false;
	}

	a_Value.FromRaw(UUIDBuf);
	return true;
}





bool cByteBuffer::WriteBEInt8(Int8 a_Value)
{
	CHECK_THREAD
	CheckValid();
	PUTBYTES(1);
	return WriteBuf(&a_Value, 1);
}





bool cByteBuffer::WriteBEInt8(const std::byte a_Value)
{
	CHECK_THREAD
	CheckValid();
	PUTBYTES(1);
	return WriteBuf(&a_Value, 1);
}





bool cByteBuffer::WriteBEUInt8(UInt8 a_Value)
{
	CHECK_THREAD
	CheckValid();
	PUTBYTES(1);
	return WriteBuf(&a_Value, 1);
}





bool cByteBuffer::WriteBEInt16(Int16 a_Value)
{
	CHECK_THREAD
	CheckValid();
	PUTBYTES(2);
	UInt16 val;
	memcpy(&val, &a_Value, 2);
	val = htons(val);
	return WriteBuf(&val, 2);
}





bool cByteBuffer::WriteBEUInt16(UInt16 a_Value)
{
	CHECK_THREAD
	CheckValid();
	PUTBYTES(2);
	a_Value = htons(a_Value);
	return WriteBuf(&a_Value, 2);
}





bool cByteBuffer::WriteBEInt32(Int32 a_Value)
{
	CHECK_THREAD
	CheckValid();
	PUTBYTES(4);
	UInt32 Converted = HostToNetwork4(&a_Value);
	return WriteBuf(&Converted, 4);
}





bool cByteBuffer::WriteBEUInt32(UInt32 a_Value)
{
	CHECK_THREAD
	CheckValid();
	PUTBYTES(4);
	UInt32 Converted = HostToNetwork4(&a_Value);
	return WriteBuf(&Converted, 4);
}





bool cByteBuffer::WriteBEInt64(Int64 a_Value)
{
	CHECK_THREAD
	CheckValid();
	PUTBYTES(8);
	UInt64 Converted = HostToNetwork8(&a_Value);
	return WriteBuf(&Converted, 8);
}





bool cByteBuffer::WriteBEUInt64(UInt64 a_Value)
{
	CHECK_THREAD
	CheckValid();
	PUTBYTES(8);
	UInt64 Converted = HostToNetwork8(&a_Value);
	return WriteBuf(&Converted, 8);
}





bool cByteBuffer::WriteBEFloat(float a_Value)
{
	CHECK_THREAD
	CheckValid();
	PUTBYTES(4);
	UInt32 Converted = HostToNetwork4(&a_Value);
	return WriteBuf(&Converted, 4);
}





bool cByteBuffer::WriteBEDouble(double a_Value)
{
	CHECK_THREAD
	CheckValid();
	PUTBYTES(8);
	UInt64 Converted = HostToNetwork8(&a_Value);
	return WriteBuf(&Converted, 8);
}





bool cByteBuffer::WriteBool(bool a_Value)
{
	CHECK_THREAD
	CheckValid();
	UInt8 val = a_Value ? 1 : 0;
	return Write(&val, 1);
}





bool cByteBuffer::WriteVarInt32(UInt32 a_Value)
{
	CHECK_THREAD
	CheckValid();

	// A 32-bit integer can be encoded by at most 5 bytes:
	unsigned char b[5];
	size_t idx = 0;
	do
	{
		b[idx] = (a_Value & 0x7f) | ((a_Value > 0x7f) ? 0x80 : 0x00);
		a_Value = a_Value >> 7;
		idx++;
	} while (a_Value > 0);

	return WriteBuf(b, idx);
}





bool cByteBuffer::WriteVarInt64(UInt64 a_Value)
{
	CHECK_THREAD
	CheckValid();

	// A 64-bit integer can be encoded by at most 10 bytes:
	unsigned char b[10];
	size_t idx = 0;
	do
	{
		b[idx] = (a_Value & 0x7f) | ((a_Value > 0x7f) ? 0x80 : 0x00);
		a_Value = a_Value >> 7;
		idx++;
	} while (a_Value > 0);

	return WriteBuf(b, idx);
}





bool cByteBuffer::WriteVarUTF8String(const AString & a_Value)
{
	CHECK_THREAD
	CheckValid();
	PUTBYTES(a_Value.size() + 1);  // This is a lower-bound on the bytes that will be actually written. Fail early.
	bool res = WriteVarInt32(static_cast<UInt32>(a_Value.size()));
	if (!res)
	{
		return false;
	}
	return WriteBuf(a_Value.data(), a_Value.size());
}





bool cByteBuffer::WriteXYZPosition64(Int32 a_BlockX, Int32 a_BlockY, Int32 a_BlockZ)
{
	CHECK_THREAD
	CheckValid();
	return WriteBEInt64(
		(static_cast<Int64>(a_BlockX & 0x3FFFFFF) << 38) |
		(static_cast<Int64>(a_BlockY & 0xFFF) << 26) |
		(static_cast<Int64>(a_BlockZ & 0x3FFFFFF))
	);
}





bool cByteBuffer::WriteXZYPosition64(Int32 a_BlockX, Int32 a_BlockY, Int32 a_BlockZ)
{
	CHECK_THREAD
	CheckValid();
	return WriteBEInt64(
		(static_cast<Int64>(a_BlockX & 0x3FFFFFF) << 38) |
		(static_cast<Int64>(a_BlockZ & 0x3FFFFFF) << 26) |
		(static_cast<Int64>(a_BlockY & 0xFFF))
	);
}





bool cByteBuffer::ReadBuf(void * a_Buffer, size_t a_Count)
{
	CHECK_THREAD
	CheckValid();
	NEEDBYTES(a_Count);
	char * Dst = static_cast<char *>(a_Buffer);  // So that we can do byte math
	ASSERT(m_BufferSize >= m_ReadPos);
	size_t BytesToEndOfBuffer = m_BufferSize - m_ReadPos;
	if (BytesToEndOfBuffer <= a_Count)
	{
		// Reading across the ringbuffer end, read the first part and adjust parameters:
		if (BytesToEndOfBuffer > 0)
		{
			memcpy(Dst, m_Buffer + m_ReadPos, BytesToEndOfBuffer);
			Dst += BytesToEndOfBuffer;
			a_Count -= BytesToEndOfBuffer;
		}
		m_ReadPos = 0;
	}

	// Read the rest of the bytes in a single read (guaranteed to fit):
	if (a_Count > 0)
	{
		memcpy(Dst, m_Buffer + m_ReadPos, a_Count);
		m_ReadPos += a_Count;
	}
	return true;
}





bool cByteBuffer::WriteBuf(const void * a_Buffer, size_t a_Count)
{
	CHECK_THREAD
	CheckValid();
	PUTBYTES(a_Count);
	const char * Src = static_cast<const char *>(a_Buffer);  // So that we can do byte math
	ASSERT(m_BufferSize >= m_ReadPos);
	size_t BytesToEndOfBuffer = m_BufferSize - m_WritePos;
	if (BytesToEndOfBuffer <= a_Count)
	{
		// Reading across the ringbuffer end, read the first part and adjust parameters:
		memcpy(m_Buffer + m_WritePos, Src, BytesToEndOfBuffer);
		Src += BytesToEndOfBuffer;
		a_Count -= BytesToEndOfBuffer;
		m_WritePos = 0;
	}

	// Read the rest of the bytes in a single read (guaranteed to fit):
	if (a_Count > 0)
	{
		memcpy(m_Buffer + m_WritePos, Src, a_Count);
		m_WritePos += a_Count;
	}
	return true;
}





bool cByteBuffer::WriteBuf(size_t a_Count, unsigned char a_Value)
{
	CHECK_THREAD
	CheckValid();
	PUTBYTES(a_Count);
	ASSERT(m_BufferSize >= m_ReadPos);
	size_t BytesToEndOfBuffer = m_BufferSize - m_WritePos;
	if (BytesToEndOfBuffer <= a_Count)
	{
		// Reading across the ringbuffer end, read the first part and adjust parameters:
		memset(m_Buffer + m_WritePos, a_Value, BytesToEndOfBuffer);
		a_Count -= BytesToEndOfBuffer;
		m_WritePos = 0;
	}

	// Read the rest of the bytes in a single read (guaranteed to fit):
	if (a_Count > 0)
	{
		memset(m_Buffer + m_WritePos, a_Value, a_Count);
		m_WritePos += a_Count;
	}
	return true;
}





bool cByteBuffer::ReadSome(ContiguousByteBuffer & a_String, size_t a_Count)
{
	CHECK_THREAD
	CheckValid();
	NEEDBYTES(a_Count);
	a_String.clear();
	a_String.reserve(a_Count);
	ASSERT(m_BufferSize >= m_ReadPos);
	size_t BytesToEndOfBuffer = m_BufferSize - m_ReadPos;
	if (BytesToEndOfBuffer <= a_Count)
	{
		// Reading across the ringbuffer end, read the first part and adjust parameters:
		if (BytesToEndOfBuffer > 0)
		{
			a_String.assign(m_Buffer + m_ReadPos, BytesToEndOfBuffer);
			ASSERT(a_Count >= BytesToEndOfBuffer);
			a_Count -= BytesToEndOfBuffer;
		}
		m_ReadPos = 0;
	}

	// Read the rest of the bytes in a single read (guaranteed to fit):
	if (a_Count > 0)
	{
		a_String.append(m_Buffer + m_ReadPos, a_Count);
		m_ReadPos += a_Count;
	}
	return true;
}





bool cByteBuffer::SkipRead(size_t a_Count)
{
	CHECK_THREAD
	CheckValid();
	if (!CanReadBytes(a_Count))
	{
		return false;
	}
	AdvanceReadPos(a_Count);
	return true;
}





void cByteBuffer::ReadAll(ContiguousByteBuffer & a_Data)
{
	CHECK_THREAD
	CheckValid();
	ReadSome(a_Data, GetReadableSpace());
}





bool cByteBuffer::ReadToByteBuffer(cByteBuffer & a_Dst, size_t a_NumBytes)
{
	CHECK_THREAD
	if (!a_Dst.CanWriteBytes(a_NumBytes) || !CanReadBytes(a_NumBytes))
	{
		// There's not enough source bytes or space in the dest BB
		return false;
	}
	char buf[1024];
	// > 0 without generating warnings about unsigned comparisons where size_t is unsigned
	while (a_NumBytes != 0)
	{
		size_t num = (a_NumBytes > sizeof(buf)) ? sizeof(buf) : a_NumBytes;
		VERIFY(ReadBuf(buf, num));
		VERIFY(a_Dst.Write(buf, num));
		ASSERT(a_NumBytes >= num);
		a_NumBytes -= num;
	}
	return true;
}





void cByteBuffer::CommitRead(void)
{
	CHECK_THREAD
	CheckValid();
	m_DataStart = m_ReadPos;
}





void cByteBuffer::ResetRead(void)
{
	CHECK_THREAD
	CheckValid();
	m_ReadPos = m_DataStart;
}





void cByteBuffer::ReadAgain(ContiguousByteBuffer & a_Out)
{
	// Return the data between m_DataStart and m_ReadPos (the data that has been read but not committed)
	// Used by ProtoProxy to repeat communication twice, once for parsing and the other time for the remote party
	CHECK_THREAD
	CheckValid();
	size_t DataStart = m_DataStart;
	if (m_ReadPos < m_DataStart)
	{
		// Across the ringbuffer end, read the first part and adjust next part's start:
		ASSERT(m_BufferSize >= m_DataStart);
		a_Out.append(m_Buffer + m_DataStart, m_BufferSize - m_DataStart);
		DataStart = 0;
	}
	ASSERT(m_ReadPos >= DataStart);
	a_Out.append(m_Buffer + DataStart, m_ReadPos - DataStart);
}





void cByteBuffer::AdvanceReadPos(size_t a_Count)
{
	CHECK_THREAD
	CheckValid();
	m_ReadPos += a_Count;
	if (m_ReadPos >= m_BufferSize)
	{
		m_ReadPos -= m_BufferSize;
	}
}





void cByteBuffer::CheckValid(void) const
{
	ASSERT(m_ReadPos < m_BufferSize);
	ASSERT(m_WritePos < m_BufferSize);
}





size_t cByteBuffer::GetVarIntSize(UInt32 a_Value)
{
	size_t Count = 0;

	do
	{
		// If the value cannot be expressed in 7 bits, it needs to take up another byte
		Count++;
		a_Value >>= 7;
	} while (a_Value != 0);

	return Count;
}