This repository has been archived by the owner on Jun 3, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 2
/
BitBuffer.lua
1211 lines (1010 loc) · 31.4 KB
/
BitBuffer.lua
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
-- BitBuffer v1.0.0
-- Copyright (c) 2021, rstk
-- All rights reserved.
-- Distributed under the MIT license.
-- https://github.com/rstk/BitBuffer
local Character = table.create(256)
do
for i = 0, 255 do
Character[i + 1] = string.char(i)
end
end
type BaseLookup = {To: {[number]: string}, From: {[number]: number}}
local Base64: BaseLookup = {To = nil, From = nil}
do
local alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"
local to = table.create(64)
local from = {}
for i = 1, 64 do
local char = string.sub(alphabet, i, i)
to[i] = char
from[string.byte(char) + 1] = i - 1
end
Base64.To = to
Base64.From = from
end
local Base91: BaseLookup = {To = nil, From = nil}
do
local alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789!#$%&()*+,./:;<=>?@[]^_`{|}~'"
local to = table.create(91)
local from = {}
for i = 1, 91 do
local char = string.sub(alphabet, i, i)
to[i] = char
from[string.byte(char) + 1] = i - 1
end
Base91.To = to
Base91.From = from
end
local function Error(msg: string, ...: any?): ()
error("[BitBuffer] " .. string.format(msg, ...), 2)
end
local function WriteToBuffer(this: BitBuffer, size: number, value: number): ()
local buffer = this._buffer
local index = this._index
local bit = index % 32
local n = bit32.rshift(index, 5) + 1
if bit + size <= 32 then
buffer[n] = bit32.replace(buffer[n] or 0, value, bit, size)
else
local rem = 32 - bit
buffer[n] = bit32.replace(buffer[n] or 0, value, bit, rem)
buffer[n + 1] = bit32.replace(buffer[n + 1] or 0, bit32.extract(value, rem, size - rem), 0, size - rem)
end
index += size
this._size = math.max(this._size, index)
this._index = index
end
local function ReadFromBuffer(this: BitBuffer, size: number): number
local buffer = this._buffer
local index = this._index
this._index += size
local bit = index % 32
local n = bit32.rshift(index, 5) + 1
local value = buffer[n] or 0
if bit == 0 then
return bit32.extract(value, 0, size)
elseif bit + size <= 32 then
return bit32.extract(value, bit, size)
else
local rem = 32 - bit
local nextValue = buffer[n + 1] or 0
return bit32.replace(bit32.extract(value, bit, rem), nextValue, rem, size - rem)
end
end
local function WriteBytesAligned(this: BitBuffer, bytes: string): ()
local length = #bytes
if length < 4 then
WriteToBuffer(this, length * 8, (string.unpack("<I" .. length, bytes)))
elseif length == 4 then
local a, b, c, d = string.byte(bytes, 1, 4)
WriteToBuffer(this, 32, a + b * 256 + c * 65536 + d * 16777216)
elseif length < 8 then
local a, b, c, d = string.byte(bytes, 1, 4)
WriteToBuffer(this, 32, a + b * 256 + c * 65536 + d * 16777216)
WriteToBuffer(this, length * 8 - 32, (string.unpack("<I" .. length - 4, bytes, 5)))
else
local buffer = this._buffer
local index = this._index
local bit = index % 32
local n = bit32.rshift(index, 5) + 1
local offset = 0
if bit ~= 0 then
offset = 4 - bit / 8
WriteToBuffer(this, 32 - bit, (string.unpack("<I" .. offset, bytes)))
n += 1
end
for i = offset + 4, length, 4 do
local a, b, c, d = string.byte(bytes, i - 3, i)
buffer[n] = a + b * 256 + c * 65536 + d * 16777216
n += 1
end
local rem = (length - offset - 4) % 4
if rem > 0 then
local v = string.unpack("<I" .. rem, bytes, length - rem + 1)
buffer[n] = bit32.replace(buffer[n] or 0, v, 0, rem * 8)
end
index = (n - 1) * 32 + rem * 8
this._size = math.max(this._size, index)
this._index = index
end
end
local function ReadBytesAligned(this: BitBuffer, length: number): string
if length < 4 then
return string.pack("<I" .. length, ReadFromBuffer(this, length * 8))
elseif length == 4 then
local value = ReadFromBuffer(this, 32)
return string.char(bit32.extract(value, 0, 8), bit32.extract(value, 8, 8), bit32.extract(value, 16, 8), bit32.extract(value, 24, 8))
end
local prefix = 3 - (this._index / 8 - 1) % 4
local suffix = (length - prefix) % 4
local t = (length - prefix - suffix) / 4
local o = 0
local str = table.create(t + 2)
if prefix > 0 then
str[1] = string.pack("<I" .. prefix, ReadFromBuffer(this, prefix * 8))
o = 1
end
local buffer = this._buffer
local n = bit32.rshift(this._index, 5) + 1
for i = 1, t do
local value = buffer[n + i - 1] or 0
str[o + i] = string.char(bit32.extract(value, 0, 8), bit32.extract(value, 8, 8), bit32.extract(value, 16, 8), bit32.extract(value, 24, 8))
end
if suffix > 0 then
str[o + t + 1] = string.pack("<I" .. suffix, bit32.extract(buffer[n + t] or 0, 0, suffix * 8))
end
this._index += t * 32 + suffix * 8
return table.concat(str)
end
--[=[
@class BitBuffer
BitBuffer object.
]=]
local BitBuffer = {ClassName = "BitBuffer"}
BitBuffer.__index = BitBuffer
function BitBuffer:__tostring()
return "BitBuffer"
end
--[=[
@tag General
Returns whether the passed object is a BitBuffer.
```lua
print(BitBuffer.is(BitBuffer.new())) --> true
print(BitBuffer.is(true)) --> false
```
@param obj any
@return boolean
]=]
function BitBuffer.is(obj: any): boolean
return getmetatable(obj :: {}) == BitBuffer
end
--[=[
@tag Constructor
Creates a new BitBuffer with an initial size of `sizeInBits`.
```lua
local buffer = BitBuffer.new(128)
print(buffer:GetSize()) --> 128
```
@param sizeInBits number? -- Initial size of the buffer in bits (defaults to 0)
@return BitBuffer
]=]
function BitBuffer.new(sizeInBits: number?)
sizeInBits = sizeInBits or 0
return setmetatable({
_buffer = table.create(math.ceil(sizeInBits :: number / 32));
_index = 0;
_size = sizeInBits :: number;
}, BitBuffer)
end
--[=[
@tag Constructor
Creates a new BitBuffer from a binary string, starting with a size corresponding to number of bits in the input string (8 bits per character), and it's cursor positioned at 0.
```lua
local buffer = BitBuffer.FromString("\89")
print(buffer:ReadUInt(8)) --> 89
print(buffer:GetSize()) --> 8
```
See [BitBuffer::ToString](#ToString)
@param inputStr string
@return BitBuffer
]=]
function BitBuffer.FromString(inputStr: string): BitBuffer
if type(inputStr) ~= "string" then
Error("invalid argument #1 to 'FromString' (string expected, got %s)", typeof(inputStr))
end
local length = #inputStr
local buffer = table.create(math.ceil(length / 4))
for i = 1, length / 4 do
local a, b, c, d = string.byte(inputStr, i * 4 - 3, i * 4)
buffer[i] = a + b * 256 + c * 65536 + d * 16777216
end
local rem = length % 4
if rem ~= 0 then
buffer[math.ceil(length / 4)] = string.unpack("<I" .. rem, inputStr, length - rem)
end
return setmetatable({
_buffer = buffer;
_index = 0;
_size = #inputStr * 8;
}, BitBuffer)
end
--[=[
@tag Constructor
Creates a new BitBuffer from a Base64 string, starting with a size corresponding to the number of bits stored in the input string (6 bits per character), and it's cursor positioned at 0.
```lua
local str = base64("\45\180")
local buffer = BitBuffer.FromBase64(str)
print(buffer:ReadUInt(8)) --> 45
print(buffer:ReadUInt(8)) --> 180
```
See [BitBuffer::ToBase64](#ToBase64)
@param inputStr string
@return BitBuffer
]=]
function BitBuffer.FromBase64(inputStr: string): BitBuffer
if type(inputStr) ~= "string" then
Error("invalid argument #1 to 'FromBase64' (string expected, got %s)", typeof(inputStr))
end
local length = #inputStr
local fromBase64 = Base64.From
-- decode 4 base64 characters to 24 bits
local accumulator = 0
local accIndex = 0
local chunks = math.floor(length / 4)
local buffer = table.create(math.ceil((chunks * 24 + length % 4 * 6) / 32))
local bufIndex = 1
for i = 1, chunks do
local c0, c1, c2, c3 = string.byte(inputStr, i * 4 - 3, i * 4)
local v0, v1, v2, v3 = fromBase64[c0 + 1], fromBase64[c1 + 1], fromBase64[c2 + 1], fromBase64[c3 + 1]
-- pardon me for this horror
if v0 == nil then
Error("invalid argument #1 to 'FromBase64' (invalid Base64 character at position %d)", i)
elseif v1 == nil then
Error("invalid argument #1 to 'FromBase64' (invalid Base64 character at position %d)", i + 1)
elseif v2 == nil then
Error("invalid argument #1 to 'FromBase64' (invalid Base64 character at position %d)", i + 2)
elseif v3 == nil then
Error("invalid argument #1 to 'FromBase64' (invalid Base64 character at position %d)", i + 3)
end
local value = v0 + v1 * 64 + v2 * 4096 + v3 * 262144
if accIndex + 24 <= 32 then
accumulator = bit32.replace(accumulator, value, accIndex, 24)
accIndex += 24
else
buffer[bufIndex] = if accIndex < 32 then bit32.replace(accumulator, value, accIndex, 32 - accIndex) else accumulator
accumulator = bit32.rshift(value, 32 - accIndex)
accIndex -= 8
bufIndex += 1
end
end
for i = chunks * 4 + 1, length do
local value = fromBase64[string.byte(inputStr, i, i) + 1]
if accIndex + 6 <= 32 then
accumulator = bit32.replace(accumulator, value, accIndex, 6)
accIndex += 6
else
buffer[bufIndex] = bit32.replace(accumulator, value, accIndex, 32 - accIndex)
accumulator = bit32.rshift(value, 32 - accIndex)
accIndex -= 26 -- += 6 - 32
bufIndex += 1
end
end
if accIndex ~= 0 then
buffer[bufIndex] = accumulator
end
return setmetatable({
_buffer = buffer;
_index = 0;
_size = #inputStr * 6;
}, BitBuffer)
end
--[=[
@tag Constructor
Creates a new BitBuffer from a Base91 string, starting with a size corresponding to the number of bits stored in the input string, and it's cursor positioned at 0.
**This is the recommended function to use for DataStores.**
```lua
local initialBuffer = BitBuffer.new()
initialBuffer:WriteUInt(32, 78)
initialBuffer:WriteString("Hi")
local b91 = initialBuffer:ToBase91()
local newBuffer = BitBuffer.FromBase91(b91)
print(newBuffer:ReadUInt(32)) --> 78
print(newBuffer:ReadString()) --> Hi
```
See [BitBuffer::ToBase91](#ToBase91)
@param inputStr string
@return BitBuffer
:::info What is Base91?
Base91 is a way to pack binary data into text, similar to Base64. It is, on average, about 10% more efficient than Base64. Check [this page](http://base91.sourceforge.net) to learn more.
:::
]=]
function BitBuffer.FromBase91(inputStr: string): BitBuffer
if type(inputStr) ~= "string" then
Error("invalid argument #1 to 'FromBase91' (string expected, got %s)", typeof(inputStr))
elseif #inputStr % 2 ~= 0 then
Error("invalid argument #1 to 'FromBase91' (invalid Base91 string: string length must be an even number)")
end
local accumulator = 0
local accIndex = 0
local buffer = table.create(#inputStr / 2 * 13 / 32 + 1)
local bufIndex = 1
local totalBits = 0
local fromBase91 = Base91.From
for i = 1, #inputStr, 2 do
local i0, i1 = string.byte(inputStr, i, i + 1)
local v0, v1 = fromBase91[i0 + 1], fromBase91[i1 + 1]
if v0 == nil then
Error("invalid argument #1 to 'FromBase91' (invalid Base91 character at position %d)", i)
elseif v1 == nil then
Error("invalid argument #1 to 'FromBase91' (invalid Base91 character at position %d)", i + 1)
end
local value = v1 * 91 + v0
local nBits = if value % 8192 > 88 then 13 else 14
totalBits += nBits
if accIndex + nBits <= 32 then
accumulator = bit32.replace(accumulator, value, accIndex, nBits)
accIndex += nBits
else
local w = 32 - accIndex
buffer[bufIndex] = if w > 0 then bit32.replace(accumulator, value, accIndex, w) else accumulator
bufIndex += 1
accumulator = bit32.extract(value, w, nBits - w)
accIndex = (accIndex + nBits) % 32
end
end
if accIndex ~= 0 then
buffer[bufIndex] = accumulator
end
return setmetatable({
_buffer = buffer;
_index = 0;
_size = totalBits;
}, BitBuffer)
end
--[=[
@tag Constructor
Creates a new BitBuffer from a Base128 string, starting with a size corresponding to the number of bits stored in the input string (7 bits per character), and it's cursor positioned at 0.
```lua
local str = base128("\255\12")
local buffer = BitBuffer.FromBase128(str)
print(buffer:ReadUInt(8)) --> 255
print(buffer:ReadUInt(8)) --> 12
```
See [BitBuffer::ToBase128](#ToBase128)
@param inputStr string
@return BitBuffer
]=]
function BitBuffer.FromBase128(inputStr: string): BitBuffer
if type(inputStr) ~= "string" then
Error("invalid argument #1 to 'FromBase128' (string expected, got %s)", typeof(inputStr))
end
local length = #inputStr
local buffer = table.create(math.ceil(length / 7) * 7)
local accumulator = 0
local bit = 0
local n = 1
for i = 1, length do
local val = string.byte(inputStr, i)
if val > 127 then
Error("invalid argument #1 to 'FromBase128' (invalid Base128 character at position %d: got %d, expected lower than 128)", i, val)
end
if bit + 7 <= 32 then
accumulator += bit32.lshift(val, bit)
bit += 7
else
local rem = 32 - bit
if rem > 0 then
buffer[n] = (accumulator + bit32.lshift(val, bit)) % 4294967296
accumulator = bit32.extract(val, rem, 7 - rem)
bit -= 25 -- += 7 - 32
else
buffer[n] = accumulator
accumulator = val
bit = 7
end
n += 1
end
end
if bit ~= 0 then
buffer[n] = accumulator
end
return setmetatable({
_buffer = buffer;
_index = 0;
_size = #inputStr * 7;
}, BitBuffer)
end
--[=[
@tag General
Resets the position of the cursor.
```lua
local buffer = BitBuffer.new()
buffer:WriteUInt(32, 890)
buffer:ResetCursor()
print(buffer:GetCursor()) --> 0
```
]=]
function BitBuffer:ResetCursor(): ()
self._index = 0
end
--[=[
@tag General
Sets the position of the cursor to the given position.
```lua
local buffer = BitBuffer.new()
buffer:WriteUInt(32, 67)
buffer:WriteUInt(32, 44)
buffer:SetCursor(32)
print(buffer:ReadUInt(32)) --> 44
```
@param position number
]=]
function BitBuffer:SetCursor(position: number): ()
if type(position) ~= "number" then
Error("invalid argument #1 to 'SetCursor' (number expected, got %s)", typeof(position))
end
self._index = math.max(math.floor(position), 0)
end
--[=[
@tag General
Returns the position of the cursor.
```lua
local buffer = BitBuffer.new()
buffer:WriteUInt(17, 901)
buffer:WriteUInt(4, 2)
print(buffer:GetCursor()) --> 21
```
@return number
]=]
function BitBuffer:GetCursor(): number
return self._index
end
--[=[
@tag General
Clears the buffer, setting its size to zero, and sets its position to 0.
```lua
local buffer = BitBuffer.new()
buffer:WriteUInt(32, math.pow(2, 32) - 1)
buffer:ResetBuffer()
print(buffer:GetCursor()) --> 0
print(buffer:ReadUInt(32)) --> 0
```
]=]
function BitBuffer:ResetBuffer(): ()
table.clear(self._buffer)
self._size = 0
self._index = 0
end
--[=[
@tag General
Returns the size of the buffer.
```lua
local buffer = BitBuffer.new()
buffer:WriteUInt(18, 618)
print(buffer:GetSize()) --> 18
```
@return number
]=]
function BitBuffer:GetSize(): number
return self._size
end
--[=[
@tag Serialization
Serializes the buffer into a binary string.
You can retrieve the buffer from this string using [BitBuffer.FromString](#FromString).
```lua
local buffer = BitBuffer.new()
buffer:WriteUInt(8, 65)
buffer:WriteUInt(8, 66)
buffer:WriteUInt(8, 67)
print(buffer:ToString()) --> ABC
```
See [BitBuffer.FromString](#FromString)
@return string
]=]
function BitBuffer:ToString(): string
local bufSize = #self._buffer
if bufSize == 0 then
return ""
end
local oldIndex = self._index
self._index = 0
local str = ReadBytesAligned(self, bufSize * 4)
self._index = oldIndex
return str
end
--[=[
@tag Serialization
Serializes the buffer into a Base64 string.
You can retrieve the buffer from this string using [BitBuffer.FromBase64](#FromBase64).
```lua
local initialBuffer = BitBuffer.new()
initialBuffer:WriteUInt(15, 919)
initialBuffer:WriteString("Hello!")
local b64 = initialBuffer:ToBase64()
local newBuffer = BitBuffer.FromBase64(b64)
print(newBuffer:ReadUInt(15)) --> 919
print(newBuffer:ReadString()) --> Hello!
```
See [BitBuffer.FromBase64](#FromBase64)
@return string
]=]
function BitBuffer:ToBase64(): string
local buffer = self._buffer
local bufIndex = 2
local accumulator = buffer[1]
local accIndex = 0
local nChunks = math.ceil(#buffer * 32 / 24)
local output = table.create(nChunks)
local toBase64 = Base64.To
for i = 1, nChunks do
local v
if accIndex + 24 <= 32 then
v = bit32.extract(accumulator, accIndex, 24)
accIndex += 24
else
local b = 32 - accIndex
v = if b > 0 then bit32.extract(accumulator, accIndex, b) else 0
accumulator = buffer[bufIndex] or 0
bufIndex += 1
accIndex = 24 - b
v = bit32.replace(v, accumulator, b, accIndex)
end
output[i] = toBase64[bit32.extract(v, 0, 6) + 1]
.. toBase64[bit32.extract(v, 6, 6) + 1]
.. toBase64[bit32.extract(v, 12, 6) + 1]
.. toBase64[bit32.extract(v, 18, 6) + 1]
end
return table.concat(output)
end
--[=[
@tag Serialization
Serializes the buffer into a Base91 string.
You can retrieve the buffer from this string using [BitBuffer.FromBase91](#FromBase91).
**This is the recommended function to use for DataStores.**
```lua
local buffer = BitBuffer.new()
buffer:WriteString(playerData.CustomName)
buffer:WriteUInt(8, playerData.Level)
buffer:WriteUInt(16, playerData.Money)
SaveToDataStore(buffer:ToBase91())
```
```lua
local b91 = RetrieveFromDataStore()
local buffer = BitBuffer.FromBase91(b91)
local playerData = {
CustomName = buffer:ReadString();
Level = buffer:ReadUInt(8);
Money = buffer:ReadUInt(16);
}
```
See [BitBuffer.FromBase91](#FromBase91)
@return string
]=]
function BitBuffer:ToBase91(): string
local buffer = self._buffer
local bufIndex = 2
local accumulator = buffer[1]
local accIndex = 0
local output = table.create(32 * #buffer / 13 + 1)
local outputIndex = 1
local toBase91Char = Base91.To
while bufIndex <= #buffer + 1 do
local v
if accIndex + 13 <= 32 then
v = bit32.extract(accumulator, accIndex, 13)
accIndex += 13
else
local b = 32 - accIndex
local r = accIndex - 19
v = if b > 0 then bit32.extract(accumulator, accIndex, b) else 0
accumulator = buffer[bufIndex] or 0
bufIndex += 1
v = bit32.replace(v, accumulator, b, r)
accIndex = r
end
if v <= 88 then
if accIndex ~= 32 then
v += bit32.extract(accumulator, accIndex, 1) * 8192
accIndex += 1
else
accumulator = buffer[bufIndex] or 0
bufIndex += 1
v += accumulator % 2 * 8192
accIndex = 1
end
end
local i0 = v % 91
local i1 = (v - i0) / 91
output[outputIndex] = toBase91Char[i0 + 1] .. toBase91Char[i1 + 1]
outputIndex += 1
end
return table.concat(output)
end
--[=[
@tag Serialization
Serializes the buffer into a Base128 string.
You can retrieve the buffer from this string using [BitBuffer.FromBase128](#FromBase128).
return string
]=]
function BitBuffer:ToBase128(): string
local buffer = self._buffer
local b128 = table.create(#buffer)
local bit = 0
for i, value in ipairs(buffer) do
local str = ""
while bit + 7 <= 32 do
str ..= Character[bit32.extract(value, bit, 7) + 1]
bit += 7
end
if bit < 32 then
local rem = 32 - bit
str ..= Character[bit32.replace(bit32.extract(value, bit, rem), buffer[i + 1] or 0, rem, 7 - rem) + 1]
bit -= 25 -- += 7 - 32
else
bit = 0
end
b128[i] = str
end
return table.concat(b128)
end
--[=[
@tag Write
Writes an unsigned integer of `bitWidth` bits to the buffer.
`bitWidth` must be an integer between 1 and 32.
If the input integer uses more bits than `bitWidth`, it will overflow as expected.
```lua
buffer:WriteUInt(32, 560) -- Writes 560 to the buffer
buffer:WriteUInt(3, 9) -- Writes 0b101 (5) because 9 is 0b1101, but `bitWidth` is only 3!
```
@param bitWidth number
@param uint number
]=]
function BitBuffer:WriteUInt(bitWidth: number, uint: number): ()
if type(bitWidth) ~= "number" then
Error("invalid argument #1 to 'WriteUInt' (number expected, got %s)", typeof(bitWidth))
elseif bitWidth < 1 or bitWidth > 32 then
Error("invalid argument #1 to 'WriteUInt' (number must be in range [1,32])")
elseif type(uint) ~= "number" then
Error("invalid argument #2 to 'WriteUInt' (number expected, got %s)", typeof(uint))
end
WriteToBuffer(self, bitWidth, uint)
end
--[=[
@tag Read
Reads `bitWidth` bits from the buffer as an unsigned integer.
`bitWidth` must be an integer between 1 and 32.
```lua
buffer:WriteUInt(12, 89)
buffer:ResetCursor()
print(buffer:ReadUInt(12)) --> 89
```
@param bitWidth number
@return number
]=]
function BitBuffer:ReadUInt(bitWidth: number): number
if type(bitWidth) ~= "number" then
Error("invalid argument #1 to 'ReadUInt' (number expected, got %s)", typeof(bitWidth))
elseif bitWidth < 1 or bitWidth > 32 then
Error("invalid argument #1 to 'ReadUInt' (number must be in range [1,32])")
end
return ReadFromBuffer(self, bitWidth)
end
--[=[
@tag Write
Writes a signed integer of `bitWidth` bits using [two's complement](https://en.wikipedia.org/wiki/Two%27s_complement).
`bitWidth` must be an integer between 1 and 32.
Overflow is **untested**, use at your own risk.
```lua
local buffer = BitBuffer.new()
buffer:WriteInt(22, -901) --> Writes -901 to the buffer
```
@param bitWidth number
@param int number
]=]
function BitBuffer:WriteInt(bitWidth: number, int: number): ()
if type(bitWidth) ~= "number" then
Error("invalid argument #1 to 'WriteInt' (number expected, got %s)", typeof(bitWidth))
elseif bitWidth < 1 or bitWidth > 32 then
Error("invalid argument #1 to 'WriteInt' (number must be in range [1,32])")
elseif type(int) ~= "number" then
Error("invalid argument #2 to 'WriteInt' (number expected, got %s)", typeof(int))
end
WriteToBuffer(self, bitWidth, int % (bit32.lshift(1, bitWidth - 1) * 2))
end
--[=[
@tag Read
Reads `bitWidth` bits as a signed integer stored using [two's complement](https://en.wikipedia.org/wiki/Two%27s_complement).
`bitWidth` must be an integer between 1 and 32.
```lua
local buffer = BitBuffer.new()
buffer:WriteInt(15, -78)
buffer:ResetCursor()
print(buffer:ReadInt(15)) --> -78
```
@param bitWidth number
@return number
]=]
function BitBuffer:ReadInt(bitWidth: number): number
if type(bitWidth) ~= "number" then
Error("invalid argument #1 to 'ReadInt' (number expected, got %s)", typeof(bitWidth))
elseif bitWidth < 1 or bitWidth > 32 then
Error("invalid argument #1 to 'ReadInt' (number must be in range [1,32])")
end
local value = ReadFromBuffer(self, bitWidth)
local max = if bitWidth == 32 then 4294967296 else bit32.lshift(1, bitWidth)
return if value >= max / 2 then value - max else value
end
--[=[
@tag Write
Writes one bit the buffer: 1 if `value` is truthy, 0 otherwise.
```lua
local buffer = BitBuffer.new()
buffer:WriteBool(true) --> Writes 1
buffer:WriteBool("A") --> Also writes 1
buffer:WriteBool(nil) --> Writes 0
```
@param value any
]=]
function BitBuffer:WriteBool(value: any): ()
if value then
WriteToBuffer(self, 1, 1)
else
WriteToBuffer(self, 1, 0)
end
end
--[=[
@tag Read
Reads one bit from the buffer and returns a boolean: true if the bit is 1, false if the bit is 0.
```lua
local buffer = BitBuffer.new()
buffer:WriteUInt(4, 0b1011)
buffer:ResetCursor()
print(buffer:ReadBool()) --> true
print(buffer:ReadBool()) --> true
print(buffer:ReadBool()) --> false
print(buffer:ReadBool()) --> true
```
@return boolean
]=]
function BitBuffer:ReadBool(): boolean
return ReadFromBuffer(self, 1) == 1
end
--[=[
@tag Write
Writes one ASCII character (one byte) to the buffer.
`char` cannot be an empty string.
```lua
local buffer = BitBuffer.new()
buffer:WriteChar("k")
buffer:ResetCursor()
print(buffer:ReadChar()) --> k
```
@param char string
]=]
function BitBuffer:WriteChar(char: string): ()
if type(char) ~= "string" then
Error("invalid argument #1 to 'WriteChar' (string expected, got %s)", typeof(char))
elseif char == "" then
Error("invalid argument #1 to 'WriteChar' (string cannot be empty)")
end
WriteToBuffer(self, 8, string.byte(char, 1, 1))
end
--[=[
@tag Read
Reads one byte as an ASCII character from the buffer.
```lua
local buffer = BitBuffer.new()
buffer:WriteUInt(8, 65)
buffer:ResetCursor()
print(buffer:ReadChar()) --> A
```
@return string
]=]
function BitBuffer:ReadChar(): string
return Character[ReadFromBuffer(self, 8) + 1]
end
--[=[
@tag Write
Writes a stream of bytes to the buffer.
if `bytes` is an empty string, nothing will be written.
```lua
local buffer = BitBuffer.new()
buffer:WriteBytes("AD")
buffer:ResetCursor()
print(buffer:ReadUInt(8), buffer:ReadUInt(8)) --> 65 68
```
See [BitBuffer::WriteString](#WriteString)
@param bytes string
]=]
function BitBuffer:WriteBytes(bytes: string): ()
if type(bytes) ~= "string" then
Error("invalid argument #1 to 'WriteBytes' (string expected, got %s)", typeof(bytes))
end
if bytes == "" then
return
elseif self._index % 8 == 0 then
WriteBytesAligned(self, bytes)
else
local length = #bytes
for chunk = 1, length / 4 do
local index = chunk * 4
local a, b, c, d = string.byte(bytes, index - 3, index)
WriteToBuffer(self, 32, a + b * 256 + c * 65536 + d * 16777216)
end
local rem = length % 4
if rem ~= 0 then
WriteToBuffer(self, rem * 8, string.unpack("<I" .. rem, bytes, length - rem + 1))
end
end
end
--[=[
@tag Read
Reads `length` bytes as a string from the buffer.
if `length` is 0, nothing will be read and an empty string will be returned.
```lua
local buffer = BitBuffer.new()
buffer:WriteUInt(8, 65)
buffer:WriteUInt(8, 67)
print(buffer:ReadBytes(2)) --> AC
```