-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy pathLibSerialize.lua
1861 lines (1587 loc) · 70.1 KB
/
LibSerialize.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
--[[
Copyright (c) 2020 Ross Nichols
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.
Credits:
The following projects served as inspiration for aspects of this project:
1. LibDeflate, by Haoqian He. https://github.com/SafeteeWoW/LibDeflate
For the CreateReader/CreateWriter functions.
2. lua-MessagePack, by François Perrad. https://framagit.org/fperrad/lua-MessagePack
For the mechanism for packing/unpacking floats and ints.
3. LibQuestieSerializer, by aero. https://github.com/AeroScripts/LibQuestieSerializer
For the basis of the implementation, and initial inspiration.
]]
-- Latest version can be found at https://github.com/rossnichols/LibSerialize.
--[[ BEGIN_README
# LibSerialize
LibSerialize is a Lua library for efficiently serializing/deserializing arbitrary values.
It supports serializing nils, numbers, booleans, strings, and tables containing these types.
It is best paired with [LibDeflate](https://github.com/safeteeWow/LibDeflate), to compress
the serialized output and optionally encode it for World of Warcraft addon or chat channels.
IMPORTANT: if you decide not to compress the output and plan on transmitting over an addon
channel, it still needs to be encoded, but encoding via `LibDeflate:EncodeForWoWAddonChannel()`
or `LibCompress:GetAddonEncodeTable()` will likely inflate the size of the serialization
by a considerable amount. See the usage below for an alternative.
Note that serialization and compression are sensitive to the specifics of your data set.
You should experiment with the available libraries (LibSerialize, AceSerializer, LibDeflate,
LibCompress, etc.) to determine which combination works best for you.
## Usage
```lua
-- Dependencies: AceAddon-3.0, AceComm-3.0, LibSerialize, LibDeflate
MyAddon = LibStub("AceAddon-3.0"):NewAddon("MyAddon", "AceComm-3.0")
local LibSerialize = LibStub("LibSerialize")
local LibDeflate = LibStub("LibDeflate")
function MyAddon:OnEnable()
self:RegisterComm("MyPrefix")
end
-- With compression (recommended):
function MyAddon:Transmit(data)
local serialized = LibSerialize:Serialize(data)
local compressed = LibDeflate:CompressDeflate(serialized)
local encoded = LibDeflate:EncodeForWoWAddonChannel(compressed)
self:SendCommMessage("MyPrefix", encoded, "WHISPER", UnitName("player"))
end
function MyAddon:OnCommReceived(prefix, payload, distribution, sender)
local decoded = LibDeflate:DecodeForWoWAddonChannel(payload)
if not decoded then return end
local decompressed = LibDeflate:DecompressDeflate(decoded)
if not decompressed then return end
local success, data = LibSerialize:Deserialize(decompressed)
if not success then return end
-- Handle `data`
end
-- Without compression (custom codec):
MyAddon._codec = LibDeflate:CreateCodec("\000", "\255", "")
function MyAddon:Transmit(data)
local serialized = LibSerialize:Serialize(data)
local encoded = self._codec:Encode(serialized)
self:SendCommMessage("MyPrefix", encoded, "WHISPER", UnitName("player"))
end
function MyAddon:OnCommReceived(prefix, payload, distribution, sender)
local decoded = self._codec:Decode(payload)
if not decoded then return end
local success, data = LibSerialize:Deserialize(decoded)
if not success then return end
-- Handle `data`
end
-- Async Mode - Used in WoW to prevent locking the game while processing.
-- Serialize data:
local processing = CreateFrame("Frame")
local handler = LibSerialize:SerializeAsync(data_to_serialize)
processing:SetScript("OnUpdate", function()
local completed, serialized = handler()
if completed then
processing:SetScript("OnUpdate", nil)
-- Do something with `serialized`
end
end)
-- Deserialize data:
local handler = LibSerialize:DeserializeAsync(serialized)
processing:SetScript("OnUpdate", function()
local completed, success, deserialized = handler()
if completed then
processing:SetScript("OnUpdate", nil)
-- Do something with `deserialized`
end
end)
```
## API
* **`LibSerialize:SerializeEx(opts, ...)`**
Arguments:
* `opts`: options (see [Serialization Options])
* `...`: a variable number of serializable values
Returns:
* result: `...` serialized as a string
* **`LibSerialize:Serialize(...)`**
Arguments:
* `...`: a variable number of serializable values
Returns:
* `result`: `...` serialized as a string
Calls `SerializeEx(opts, ...)` with the default options (see [Serialization Options])
* **`LibSerialize:Deserialize(input)`**
Arguments:
* `input`: a string previously returned from a LibSerialize serialization API,
or an object that implements the [Reader protocol]
Returns:
* `success`: a boolean indicating if deserialization was successful
* `...`: the deserialized value(s) if successful, or a string containing the encountered
Lua error
* **`LibSerialize:DeserializeValue(input, opts)`**
Arguments:
* `input`: a string previously returned from a LibSerialize serialization API,
or an object that implements the [Reader protocol]
* `opts`: options (see [Deserialization Options])
Returns:
* `...`: the deserialized value(s)
* **`LibSerialize:IsSerializableType(...)`**
Arguments:
* `...`: a variable number of values
Returns:
* `result`: true if all of the values' types are serializable.
Note that if you pass a table, it will be considered serializable
even if it contains unserializable keys or values. Only the types
of the arguments are checked.
`Serialize()` will raise a Lua error if the input cannot be serialized.
This will occur if any of the following exceed 16777215: any string length,
any table key count, number of unique strings, number of unique tables.
It will also occur by default if any unserializable types are encountered,
though that behavior may be disabled (see [Serialization Options]).
`Deserialize()` and `DeserializeValue()` are equivalent, except the latter
returns the deserialization result directly and will not catch any Lua
errors that may occur when deserializing invalid input.
As of recent releases, the library supports reentrancy and concurrent usage
from multiple threads (coroutines) through the public API. Modifying tables
during the serialization process is unspecified and should be avoided.
Table serialization is multi-phased and assumes a consistent state for the
key/value pairs across the phases.
It is permitted for any user-supplied functions to suspend the current
thread during the serialization or deserialization process. It is however
not possible to yield the current thread if the `Deserialize()` API is used,
as this function inserts a C call boundary onto the call stack. This issue
does not affect the `DeserializeValue()` function.
## Asynchronous API
* **`LibSerialize:SerializeAsyncEx(opts, ...)`**
Arguments:
* `opts`: options (optional, see [Serialization Options])
* `...`: a variable number of serializable values
Returns:
* `handler`: function that performs the serialization. This should be called with
no arguments until the first returned value is false.
`handler` returns:
* `completed`: a boolean indicating whether serialization is finished
* `result`: once complete, `...` serialized as a string
Calls `SerializeEx(opts, ...)` with the specified options, as well as setting
the `async` option to true (see [Serialization Options]). Note that the passed-in
table is written to when doing so.
* **`LibSerialize:SerializeAsync(...)`**
Arguments:
* `...`: a variable number of serializable values
Returns:
* `handler`: function that performs the serialization. This should be called with
no arguments until the first returned value is false.
`handler` returns:
* `completed`: a boolean indicating whether serialization is finished
* `result`: once complete, `...` serialized as a string
Calls `SerializeEx(opts, ...)` with the default options, as well as setting
the `async` option to true (see [Serialization Options]). Note that the passed-in
table is written to when doing so.
* **`LibSerialize:DeserializeAsync(input, opts)`**
Arguments:
* `input`: a string previously returned from a LibSerialize serialization API
* `opts`: options (optional, see [Deserialization Options])
Returns:
* `handler`: function that performs the deserialization. This should be called with
no arguments until the first returned value is false.
`handler` returns:
* `completed`: a boolean indicating whether deserialization is finished
* `success`: once complete, a boolean indicating if deserialization was successful
* `...`: once complete, the deserialized value(s) if successful, or a string containing
the encountered Lua error
Calls `DeserializeValue(opts, ...)` with the specified options, as well as setting
the `async` option to true (see [Deserialization Options]). Note that the passed-in
table is written to when doing so.
Errors encountered when serializing behave the same way as the synchronous APIs.
Errors encountered when deserializing will always be caught and returned via the
handler's return values, even if `DeserializeValue()` is called directly. This is
different than when calling `DeserializeValue()` in synchronous mode.
## Serialization Options
The following serialization options are supported:
* `errorOnUnserializableType`: `boolean` (default true)
* `true`: unserializable types will raise a Lua error
* `false`: unserializable types will be ignored. If it's a table key or value,
the key/value pair will be skipped. If it's one of the arguments to the
call to SerializeEx(), it will be replaced with `nil`.
* `stable`: `boolean` (default false)
* `true`: the resulting string will be stable, even if the input includes
maps. This option comes with an extra memory usage and CPU time cost.
* `false`: the resulting string will be unstable and will potentially differ
between invocations if the input includes maps
* `filter`: `function(t, k, v) => boolean` (default nil)
* If specified, the function will be called on every key/value pair in every
table encountered during serialization. The function must return true for
the pair to be serialized. It may be called multiple times on a table for
the same key/value pair. See notes on reeentrancy and table modification.
* `async`: `boolean` (default false)
* `true`: the API returns a coroutine that performs the serialization
* `false`: the API performs the serialization directly
* `yieldCheck`: `function(t) => boolean` (default impl yields after 4096 items)
* Only applicable when serializing asynchronously. If specified, the function
will be called every time an item is about to be serialized. If the function
returns true, the coroutine will yield. The function is passed a "scratch"
table into which it can persist state.
* `writer`: `any` (default nil)
* If specified, the object referenced by this field will be checked to see
if it implements the [Writer protocol]. If so, the functions it defines
will be used to control how serialized data is written.
## Deserialization Options
The following deserialization options are supported:
* `async`: `boolean` (default false)
* `true`: the API returns a coroutine that performs the deserialization
* `false`: the API performs the deserialization directly
* `yieldCheck`: `function(t) => boolean` (default impl yields after 4096 items)
* Only applicable when deserializing asynchronously. If specified, the function
will be called every time an item is about to be deserialized. If the function
returns true, the coroutine will yield. The function is passed a "scratch"
table into which it can persist state.
If an option is unspecified in the table, then its default will be used.
This means that if an option `foo` defaults to true, then:
* `myOpts.foo = false`: option `foo` is false
* `myOpts.foo = nil`: option `foo` is true
## Reader Protocol
The library supports customizing how serialized data is provided to the
deserialization functions through the use of the "Reader" protocol. This
enables advanced use cases such as batched or throttled deserialization via
coroutines, or processing serialized data of an unknown-length in a streamed
manner.
Any value supplied as the `input` to any deserialization function will be
inspected and indexed to search for the following keys. If provided, these
will override default behaviors otherwise implemented by the library.
* `ReadBytes`: `function(input, i, j) => string` (optional)
* If specified, this function will be called every time the library needs
to read a sequence of bytes as a string from the supplied input. The range
of bytes is passed in the `i` and `j` parameters, with similar semantics
to standard Lua functions such as `string.sub` and `table.concat`. This
function must return a string whose length is equal to the requested range
of bytes.
It is permitted for this function to error if the range of bytes would
exceed the available bytes; if an error is raised it will pass through
the library back to the caller of Deserialize/DeserializeValue.
If not supplied, the default implementation will access the contents of
`input` as if it were a string and call `string.sub(input, i, j)`.
* `AtEnd`: `function(input, i) => boolean` (optional)
* If specified, this function will be called whenever the library needs to
test if the end of the input has been reached. The `i` parameter will be
supplied a byte offset from the start of the input, and should typically
return `true` if `i` is greater than the length of `input`.
If this function returns true, the stream is considered ended and further
values will not be deserialized. If this function returns false,
deserialization of further values will continue until it returns true.
If not supplied, the default implementation will compare the offset `i`
against the length of `input` as obtained through the `#` operator.
## Writer Protocol
The library supports customizing how byte strings are written during the
serialization process through the use of an object that implements the
"Writer" protocol. This enables advanced use cases such as batched or throttled
serialization via coroutines, or streaming the data to a target instead of
processing it all in one giant chunk.
Any value stored on the `writer` key of the options table passed to the
`SerializeEx()` function will be inspected and indexed to search for the
following keys. If the required keys are all found, all operations provided
by the writer will override the default behaviors otherwise implemented by
the library. Otherwise, the writer is ignored and not used for any operations.
* `WriteString`: `function(writer, str)` (required)
* This function will be called each time the library submits a byte string
that was created as result of serializing data.
If this function is not supplied, the supplied `writer` is considered
incomplete and will be ignored for all operations.
* `Flush`: `function(writer)` (optional)
* If specified, this function will be called at the end of the serialization
process. It may return any number of values - including zero - all of
which will be passed through to the caller of `SerializeEx()` verbatim.
The default behavior if this function is not specified - and if the writer
is otherwise valid - is a no-op that returns no values.
## Customizing table serialization
For any serialized table, LibSerialize will check for the presence of a
metatable key `__LibSerialize`. It will be interpreted as a table with
the following possible keys:
* `filter`: `function(t, k, v) => boolean`
* If specified, the function will be called on every key/value pair in that
table. The function must return true for the pair to be serialized. It may
be called multiple times on a table for the same key/value pair. See notes
on reeentrancy and table modification. If combined with the `filter` option,
both functions must return true.
## Examples
1. `LibSerialize:Serialize()` supports variadic arguments and arbitrary key types,
maintaining a consistent internal table identity.
```lua
local t = { "test", [false] = {} }
t[ t[false] ] = "hello"
local serialized = LibSerialize:Serialize(t, "extra")
local success, tab, str = LibSerialize:Deserialize(serialized)
assert(success)
assert(tab[1] == "test")
assert(tab[ tab[false] ] == "hello")
assert(str == "extra")
```
2. Normally, unserializable types raise an error when encountered during serialization,
but that behavior can be disabled in order to silently ignore them instead.
```lua
local serialized = LibSerialize:SerializeEx(
{ errorOnUnserializableType = false },
print, { a = 1, b = print })
local success, fn, tab = LibSerialize:Deserialize(serialized)
assert(success)
assert(fn == nil)
assert(tab.a == 1)
assert(tab.b == nil)
```
3. Tables may reference themselves recursively and will still be serialized properly.
```lua
local t = { a = 1 }
t.t = t
t[t] = "test"
local serialized = LibSerialize:Serialize(t)
local success, tab = LibSerialize:Deserialize(serialized)
assert(success)
assert(tab.t.t.t.t.t.t.a == 1)
assert(tab[tab.t] == "test")
```
4. You may specify a global filter that applies to all tables encountered during
serialization, and to individual tables via their metatable.
```lua
local t = { a = 1, b = print, c = 3 }
local nested = { a = 1, b = print, c = 3 }
t.nested = nested
setmetatable(nested, { __LibSerialize = {
filter = function(t, k, v) return k ~= "c" end
}})
local opts = {
filter = function(t, k, v) return LibSerialize:IsSerializableType(k, v) end
}
local serialized = LibSerialize:SerializeEx(opts, t)
local success, tab = LibSerialize:Deserialize(serialized)
assert(success)
assert(tab.a == 1)
assert(tab.b == nil)
assert(tab.c == 3)
assert(tab.nested.a == 1)
assert(tab.nested.b == nil)
assert(tab.nested.c == nil)
```
5. You may perform the serialization and deserialization operations asynchronously,
to avoid blocking for excessive durations when handling large amounts of data.
Note that you wouldn't call the handlers in a repeat-until loop like below, because
then you're still effectively performing the operations synchronously.
```lua
local t = { "test", [false] = {} }
t[ t[false] ] = "hello"
local co_handler = LibSerialize:SerializeAsync(t, "extra")
local completed, serialized
repeat
completed, serialized = co_handler()
until completed
local completed, success, tab, str
local co_handler = LibSerialize:DeserializeAsync(serialized)
repeat
completed, success, tab, str = co_handler()
until completed
assert(success)
assert(tab[1] == "test")
assert(tab[ tab[false] ] == "hello")
assert(str == "extra")
```
6. You may use the Reader and Writer protocols to have more control over writing the
results of serialization, or how those results are read when deserializing. The below
example implements the default behavior of the library using these protocols.
```lua
local t = { a = 1, b = 2, c = 3 }
local StandardWriter = {}
function StandardWriter:Initialize()
self.buffer = {}
self.bufferSize = 0
end
function StandardWriter:WriteString(str)
self.bufferSize = self.bufferSize + 1
self.buffer[self.bufferSize] = str
end
function StandardWriter:Flush()
local flushed = table.concat(self.buffer, "", 1, self.bufferSize)
self.bufferSize = 0
return flushed
end
local StandardReader = {}
function StandardReader:Initialize(input)
self.input = input
end
function StandardReader:ReadBytes(startOffset, endOffset)
return string.sub(self.input, startOffset, endOffset)
end
function StandardReader:AtEnd(offset)
return offset > #self.input
end
StandardWriter:Initialize()
local serialized = LibSerialize:SerializeEx({ writer = StandardWriter }, t)
StandardReader:Initialize(serialized)
local success, tab = LibSerialize:Deserialize(StandardReader)
assert(success)
assert(tab.a == 1)
assert(tab.b == 2)
assert(tab.c == 3)
```
## Encoding format
Every object is encoded as a type byte followed by type-dependent payload.
For numbers, the payload is the number itself, using a number of bytes
appropriate for the number. Small numbers can be embedded directly into
the type byte, optionally with an additional byte following for more
possible values. Negative numbers are encoded as their absolute value,
with the type byte indicating that it is negative. Floats are decomposed
into their eight bytes, unless serializing as a string is shorter.
For strings and tables, the length/count is also encoded so that the
payload doesn't need a special terminator. Small counts can be embedded
directly into the type byte, whereas larger counts are encoded directly
following the type byte, before the payload.
Strings are stored directly, with no transformations. Tables are stored
in one of three ways, depending on their layout:
* Array-like: all keys are numbers starting from 1 and increasing by 1.
Only the table's values are encoded.
* Map-like: the table has no array-like keys.
The table is encoded as key-value pairs.
* Mixed: the table has both map-like and array-like keys.
The table is encoded first with the values of the array-like keys,
followed by key-value pairs for the map-like keys. For this version,
two counts are encoded, one each for the two different portions.
Strings and tables are also tracked as they are encountered, to detect reuse.
If a string or table is reused, it is encoded instead as an index into the
tracking table for that type. Strings must be >2 bytes in length to be tracked.
Tables may reference themselves recursively.
#### Type byte:
The type byte uses the following formats to implement the above:
* `NNNN NNN1`: a 7 bit non-negative int
* `CCCC TT10`: a 2 bit type index and 4 bit count (strlen, #tab, etc.)
* Followed by the type-dependent payload
* `NNNN S100`: the lower four bits of a 12 bit int and 1 bit for its sign
* Followed by a byte for the upper bits
* `TTTT T000`: a 5 bit type index
* Followed by the type-dependent payload, including count(s) if needed
[Serialization Options]: #serialization-options
[Deserialization Options]: #deserialization-options
[Reader protocol]: #reader-protocol
[Writer protocol]: #writer-protocol
END_README --]]
local MAJOR, MINOR = "LibSerialize", 5
local LibSerialize
if LibStub then
LibSerialize = LibStub:NewLibrary(MAJOR, MINOR)
if not LibSerialize then return end -- This version is already loaded.
else
LibSerialize = {}
end
-- Rev the serialization version when making a breaking change.
-- Make sure to handle older versions properly within LibSerialize:DeserializeValue.
-- NOTE: these normally can be idential, but due to a bug when revving MINOR to 2,
-- we need to support both 1 and 2 as v1 serialization versions.
local SERIALIZATION_VERSION = 1
local DESERIALIZATION_VERSION = 2
--[[---------------------------------------------------------------------------
Local overrides of otherwise global library functions
--]]---------------------------------------------------------------------------
local assert = assert
local coroutine_create = coroutine.create
local coroutine_resume = coroutine.resume
local coroutine_status = coroutine.status
local coroutine_yield = coroutine.yield
local error = error
local getmetatable = getmetatable
local ipairs = ipairs
local math_floor = math.floor
local math_huge = math.huge
local math_max = math.max
local math_modf = math.modf
local pairs = pairs
local pcall = pcall
local print = print
local select = select
local setmetatable = setmetatable
local string_byte = string.byte
local string_char = string.char
local string_sub = string.sub
local table_concat = table.concat
local table_insert = table.insert
local table_sort = table.sort
local tonumber = tonumber
local tostring = tostring
local type = type
-- Compatibility shim to allow the library to work on Lua 5.4
local unpack = unpack or table.unpack
local frexp = math.frexp or function(num)
if num == math_huge then return num end
local fraction, exponent = num, 0
if fraction ~= 0 then
while fraction >= 1 do
fraction = fraction / 2
exponent = exponent + 1
end
while fraction < 0.5 do
fraction = fraction * 2
exponent = exponent - 1
end
end
return fraction, exponent
end
local ldexp = math.ldexp or function(m, e)
return m * 2 ^ e
end
-- If in an environment that supports `require` and `_ENV` (note: WoW does not),
-- then block reading/writing of globals. All needed globals should have been
-- converted to upvalues above.
if require and _ENV then
_ENV = setmetatable({}, {
__newindex = function(t, k, v)
assert(false, "Attempt to write to global variable: " .. k)
end,
__index = function(t, k)
assert(false, "Attempt to read global variable: " .. k)
end
})
end
--[[---------------------------------------------------------------------------
Library defaults.
--]]---------------------------------------------------------------------------
local defaultYieldCheck = function(self)
self._currentObjectCount = self._currentObjectCount or 0
if self._currentObjectCount > 4096 then
self._currentObjectCount = 0
return true
end
self._currentObjectCount = self._currentObjectCount + 1
end
local defaultSerializeOptions = {
errorOnUnserializableType = true,
stable = false,
filter = nil,
writer = nil,
async = false,
yieldCheck = defaultYieldCheck,
}
local defaultAsyncOptions = {
async = true,
}
local defaultDeserializeOptions = {
async = false,
yieldCheck = defaultYieldCheck,
}
local canSerializeFnOptions = {
errorOnUnserializableType = false
}
--[[---------------------------------------------------------------------------
Helper functions.
--]]---------------------------------------------------------------------------
-- Returns the number of bytes required to store the value,
-- up to a maximum of three. Errors if three bytes is insufficient.
local function GetRequiredBytes(value)
if value < 256 then return 1 end
if value < 65536 then return 2 end
if value < 16777216 then return 3 end
error("Object limit exceeded")
end
-- Returns the number of bytes required to store the value,
-- though always returning seven if four bytes is insufficient.
-- Doubles have room for 53bit numbers, so seven bits max.
local function GetRequiredBytesNumber(value)
if value < 256 then return 1 end
if value < 65536 then return 2 end
if value < 16777216 then return 3 end
if value < 4294967296 then return 4 end
return 7
end
-- Queries a given object for the value assigned to a specific key.
--
-- If the given object cannot be indexed, an error may be raised by the Lua
-- implementation.
local function GetValueByKey(object, key)
return object[key]
end
-- Queries a given object for the value assigned to a specific key, returning
-- it if non-nil or giving back a default.
--
-- If the given object cannot be indexed, the default will be returned and
-- no error raised.
local function GetValueByKeyOrDefault(object, key, default)
local ok, value = pcall(GetValueByKey, object, key)
if not ok or value == nil then
return default
else
return value
end
end
-- Returns whether the value (a number) is NaN.
local function IsNaN(value)
-- With floating point optimizations enabled all comparisons involving
-- NaNs will return true. Without them, these will both return false.
return (value < 0) == (value >= 0)
end
-- Returns whether the value (a number) is finite, as opposed to being a
-- NaN or infinity.
local function IsFinite(value)
return value > -math_huge and value < math_huge and not IsNaN(value)
end
-- Returns whether the value (a number) is fractional,
-- as opposed to a whole number.
local function IsFractional(value)
local _, fract = math_modf(value)
return fract ~= 0
end
-- Returns whether the value (a number) needs to be represented as a floating
-- point number due to either being fractional or non-finite.
local function IsFloatingPoint(value)
return IsFractional(value) or not IsFinite(value)
end
-- Returns true if the given table key is an integer that can reside in the
-- array section of a table (keys 1 through arrayCount).
local function IsArrayKey(k, arrayCount)
return type(k) == "number" and k >= 1 and k <= arrayCount and not IsFloatingPoint(k)
end
-- Portable no-op function that does absolutely nothing, and pushes no returns
-- onto the stack.
local function Noop()
end
-- Sort compare function which is used to sort table keys to ensure that the
-- serialization of maps is stable. We arbitrarily put strings first, then
-- numbers, and finally booleans.
local function StableKeySort(a, b)
local aType = type(a)
local bType = type(b)
-- Put strings first
if aType == "string" and bType == "string" then
return a < b
elseif aType == "string" then
return true
elseif bType == "string" then
return false
end
-- Put numbers next
if aType == "number" and bType == "number" then
return a < b
elseif aType == "number" then
return true
elseif bType == "number" then
return false
end
-- Put booleans last
if aType == "boolean" and bType == "boolean" then
return (a and 1 or 0) < (b and 1 or 0)
else
error(("Unhandled sort type(s): %s, %s"):format(aType, bType))
end
end
-- Prints args to the chat window. To enable debug statements,
-- do a find/replace in this file with "-- DebugPrint(" for "DebugPrint(",
-- or the reverse to disable them again.
local DebugPrint = function(...)
print(...)
end
--[[---------------------------------------------------------------------------
Helpers for reading/writing streams of bytes from/to a string
--]]---------------------------------------------------------------------------
-- Generic writer functions that defer their work to previously defined helpers.
local function Writer_WriteString(self, str)
if self.opts.async and self.opts.yieldCheck(self.asyncScratch) then
coroutine_yield()
end
self.writeString(self.writer, str)
end
local function Writer_FlushWriter(self)
return self.flushWriter(self.writer)
end
-- Functions for a writer that will lazily construct a string over multiple writes.
local function BufferedWriter_WriteString(self, str)
self.bufferSize = self.bufferSize + 1
self.buffer[self.bufferSize] = str
end
local function BufferedWriter_FlushBuffer(self)
local flushed = table_concat(self.buffer, "", 1, self.bufferSize)
self.bufferSize = 0
return flushed
end
-- Creates a writer object that will be called to write the serialized output.
-- Return values:
-- 1. Writer object
-- 2. WriteString(obj, str)
-- 3. FlushWriter(obj)
local function CreateWriter(opts)
-- If the supplied object implements the required functions to satisfy
-- the Writer interface, it will be used exclusively. Otherwise if any
-- of those are missing, the object is entirely ignored and we'll use
-- the original buffer-of-strings approach.
local object = {
opts = opts,
asyncScratch = opts.async and {} or nil,
}
local writeString = GetValueByKeyOrDefault(opts.writer, "WriteString", nil)
if writeString == nil then
-- Configure the object for the BufferedWriter approach.
object.writer = object
object.buffer = {}
object.bufferSize = 0
object.writeString = BufferedWriter_WriteString
object.flushWriter = BufferedWriter_FlushBuffer
else
-- Note that for custom writers if no Flush implementation is given the
-- default is a no-op; this means that no values will be returned to the
-- caller of Serialize/SerializeEx. It's expected in such a case that
-- you will have written the strings elsewhere yourself; perhaps having
-- already submitted them for transmission via a comms API for example.
object.writer = opts.writer
object.writeString = writeString
object.flushWriter = GetValueByKeyOrDefault(opts.writer, "Flush", Noop)
end
return object, Writer_WriteString, Writer_FlushWriter
end
-- Generic reader functions that defer their work to previously defined helpers.
local function Reader_ReadBytes(self, bytelen)
if self.opts.async and self.opts.yieldCheck(self.asyncScratch) then
coroutine_yield()
end
local result = self.readBytes(self.input, self.nextPos, self.nextPos + bytelen - 1)
self.nextPos = self.nextPos + bytelen
return result
end
local function Reader_AtEnd(self)
return self.atEnd(self.input, self.nextPos)
end
-- Implements the default end-of-stream check for a reader. This requires
-- that the supplied input object supports the length operator.
local function GenericReader_AtEnd(input, offset)
return offset > #input
end
-- Creates a reader object that will be called to read the to-be-deserialized input.
-- Return values:
-- 1. Reader object
-- 2. ReadBytes(bytelen)
-- 3. ReaderAtEnd()
local function CreateReader(input, opts)
-- We allow any type of input to be given and queried for the custom
-- reader interface; any errors that arise when attempting to index these
-- fields are swallowed silently with fallbacks to suitable defaults.
local object = {
input = input,
nextPos = 1,
opts = opts,
asyncScratch = opts.async and {} or nil,
readBytes = GetValueByKeyOrDefault(input, "ReadBytes", string_sub),
atEnd = GetValueByKeyOrDefault(input, "AtEnd", GenericReader_AtEnd),
}
return object, Reader_ReadBytes, Reader_AtEnd
end
--[[---------------------------------------------------------------------------
Helpers for serializing/deserializing numbers (ints and floats)
--]]---------------------------------------------------------------------------
local function FloatToString(n)
if IsNaN(n) then -- nan
return string_char(0xFF, 0xF8, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00)
end
local sign = 0
if n < 0.0 then
sign = 0x80
n = -n
end
local mant, expo = frexp(n)
-- If n is infinity, mant will be infinity inside WoW, but NaN elsewhere.
if (mant == math_huge or IsNaN(mant)) or expo > 0x400 then
if sign == 0 then -- inf
return string_char(0x7F, 0xF0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00)
else -- -inf
return string_char(0xFF, 0xF0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00)
end
elseif (mant == 0.0 and expo == 0) or expo < -0x3FE then -- zero
return string_char(sign, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00)
else
expo = expo + 0x3FE
mant = math_floor((mant * 2.0 - 1.0) * ldexp(0.5, 53))
return string_char(sign + math_floor(expo / 0x10),
(expo % 0x10) * 0x10 + math_floor(mant / 281474976710656),
math_floor(mant / 1099511627776) % 256,
math_floor(mant / 4294967296) % 256,
math_floor(mant / 16777216) % 256,
math_floor(mant / 65536) % 256,
math_floor(mant / 256) % 256,
mant % 256)
end
end
local function StringToFloat(str)
local b1, b2, b3, b4, b5, b6, b7, b8 = string_byte(str, 1, 8)
local sign = b1 > 0x7F
local expo = (b1 % 0x80) * 0x10 + math_floor(b2 / 0x10)
local mant = ((((((b2 % 0x10) * 256 + b3) * 256 + b4) * 256 + b5) * 256 + b6) * 256 + b7) * 256 + b8
if sign then
sign = -1
else
sign = 1
end
local n
if mant == 0 and expo == 0 then
n = sign * 0.0
elseif expo == 0x7FF then
if mant == 0 then
n = sign * math_huge
else
n = 0.0/0.0
end
else
n = sign * ldexp(1.0 + mant / 4503599627370496.0, expo - 0x3FF)
end
return n
end
local function IntToString(n, required)
if required == 1 then
return string_char(n)
elseif required == 2 then
return string_char(math_floor(n / 256),
n % 256)
elseif required == 3 then
return string_char(math_floor(n / 65536),
math_floor(n / 256) % 256,
n % 256)
elseif required == 4 then
return string_char(math_floor(n / 16777216),
math_floor(n / 65536) % 256,
math_floor(n / 256) % 256,