-
Notifications
You must be signed in to change notification settings - Fork 1
/
mst.lua
1759 lines (1557 loc) · 36.2 KB
/
mst.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
#!/usr/bin/env lua
-- -*-lua-*-
--
-- $Id: mst.lua $
--
-- Author: Markus Stenberg <[email protected]>
--
-- Copyright (c) 2012 cisco Systems, Inc.
--
-- Created: Wed Sep 19 15:13:37 2012 mstenber
-- Last modified: Thu Oct 31 12:59:29 2013 mstenber
-- Edit time: 783 min
--
-- data structure abstractions provided:
-- array_* = table with values in values, number indexes
-- set_* = table with values in keys
-- table_* = normal Python-style dictionary
-- class called 'dict' to prevent conflicts
local debug = require 'debug'
local io = require 'io'
local math = require 'math'
local os = require 'os'
local string = require 'string'
local table = require 'table'
local enable_debug_date_ms=true
if enable_debug_date_ms
then
socket = require 'socket'
end
local socket = socket
local assert = assert
--local collectgarbage = collectgarbage
local error = error
local getmetatable = getmetatable
local ipairs = ipairs
local pairs = pairs
local pcall = pcall
local print = print
local require = require
local select = select
local setmetatable = setmetatable
local tonumber = tonumber
local tostring = tostring
local type = type
local unpack = unpack
local xpcall = xpcall
-- allow prevention of loading strict (e.g. when dealing with luacov)
if not os.getenv("DISABLE_MST_STRICT")
then
-- vstruct fix (sigh)
if not jit
then
jit = false
end
require 'strict'
end
--module(..., package.seeall)
module(...)
-- global debug switch
enable_debug=false
enable_debug_date=true
-- enable own assert
enable_assert=true
-- forward declare types
array = nil
map = nil
set = nil
repr_show_duplicates = false
-- check parameters to e.g. function
function check_parameters(fname, o, l, depth)
depth = depth or 2
assert(o and l)
for i, f in ipairs(l) do
if o[f] == nil
then
error(f .. " is mandatory parameter to " .. fname, depth)
end
end
end
local _repr_metatable = {__tostring=function (self) return repr(self) end}
debug_print_raw = false -- going to be set to real value in set_enable_debug
function set_enable_debug(v)
-- empty string is not valid debug enabler either..
enable_debug = v and #v > 0 and v
if enable_debug and enable_debug ~= "1"
then
local f = io.open(enable_debug, "w")
f:setvbuf('full', 4096) -- write at least 4k at once (assume we're spammy)
debug_print_raw = function (...)
f:write(table.concat(array_map({...}, tostring), '\t'))
f:write("\n")
end
else
debug_print_raw = print
end
end
-- set the enable debug based on environment variable, by default..
set_enable_debug(os.getenv("ENABLE_MST_DEBUG"))
-- debugging (class stuff depends on this -> must be first)
function debug_print(...)
-- rewrite all table's to have metatable which has tostring => repr wrapper, if they don't have metatable
local sm
--print('handling arguments', #al)
for i=1,select('#', ...)
do
local v = select(i, ...)
--print(type(v))
if type(v) == 'table'
then
--print('xx', v, getmetatable(v))
if (not getmetatable(v) or not getmetatable(v).__tostring)
then
sm = sm or {}
--print(' setting metatable', v)
sm[v] = getmetatable(v) or false
setmetatable(v, _repr_metatable)
end
end
end
if enable_debug_date_ms
then
local ms = math.floor(socket.gettime()*1000%1000)
local ts = os.date('%x %X')
debug_print_raw(string.format('%s.%03d', ts, ms), ...)
elseif enable_debug_date
then
debug_print_raw(os.date(), ...)
else
debug_print_raw(...)
end
if sm
then
for v, mt in pairs(sm)
do
mt = mt or nil
setmetatable(v, mt)
end
end
end
function a(stmt, ...)
if not enable_assert
then
assert(stmt, ...)
return
end
if not stmt
then
print(debug.traceback())
debug_print(...)
error('assertion failed', 2)
end
end
function d(...)
if enable_debug
then
debug_print(...)
end
end
mst = {a=a, d=d}
-- baseclass used as base for all classes
-- magic features:
-- - mandatory contains array with list of mandatory parameters for
-- constructor
-- - events contains array of events (=magic callback-like things) the
-- class produces (event class is instantiated for each)
-- in new.. and in done, they're cleared out correctly
baseclass = {}
function baseclass:init()
end
function baseclass:uninit()
end
function baseclass:done()
if self._is_done
then
return
end
self._is_done = true
self:uninit()
end
function baseclass:new_subclass(o)
return create_class(o, self)
end
function baseclass:new(o)
o = o or {}
-- make sure it isn't already set with this metatable - would
-- indicate reuse of table for multiple objects, which is a no-no
local omt = getmetatable(o)
self:a(omt == nil, ':new with table that has non-empty metatable', o, omt)
-- set the child metatable
setmetatable(o, self)
mst.a(o.init, "missing init method?", self)
if o.mandatory
then
-- 1 = check_parameters, 2 == baseclass:new, 3 == whoever calls baseclass:new
check_parameters(tostring(o) .. ':new()', o, o.mandatory, 3)
end
o:init()
return o
end
function get_class(o)
if type(o) ~= 'table'
then
return nil, 'wrong type'
end
local cmt = getmetatable(o)
if not cmt
then
return nil, 'no metatable'
end
return cmt
end
function baseclass:is_instance(o)
local cl = get_class(o)
return cl == self
end
function baseclass:repr_data(shown)
return nil
end
function baseclass:repr(shown)
local omt = getmetatable(self)
setmetatable(self, {})
local t = tostring(self)
setmetatable(self, omt)
local r = self:repr_data(shown)
if r
then
reprs = ' - ' .. r
else
reprs = table_repr(self, shown)
end
return string.format('<%s %s%s>',
self.class or tostring(getmetatable(self)),
t,
reprs)
end
function baseclass:tostring()
-- by default, fall back to repr()
return self:repr()
end
function baseclass:d(...)
self:a(type(self) == 'table', "wrong self type ", type(self))
if self.debug or enable_debug
then
debug_print(self:tostring(), ...)
end
end
function baseclass:a(stmt, ...)
if not enable_assert
then
assert(stmt, ...)
return
end
if not stmt
then
print(debug.traceback())
debug_print(self:tostring(), ...)
error(self:tostring() .. ' assertion failed', 2)
end
end
function baseclass:call_callback(name, ...)
if self[name]
then
self[name](...)
end
end
function baseclass:call_callback_once(name, ...)
if self[name]
then
self[name](...)
self[name] = nil
end
end
local function _ts(self)
return self.tostring(self)
end
-- create a new class with the given superclass(es)
-- (the extra arguments)
function create_class(o, ...)
local scs = {...}
local _index
local h = o or {}
if #scs > 1
then
-- PIL style lookup in the parents (not super efficient but
-- caching, so should not be too bad). Note that we update the
-- _class_ object, not _instance_ objects with cache => cache is
-- small even if we have lots of instances
_index = function (self, k)
for i, super in ipairs(scs)
do
local v = super[k]
if v
then
-- store the result too
h[k] = v
return v
end
end
end
-- provide init/unint that do the nested calls too
if not h.init
then
function h:init()
for i, super in ipairs(scs)
do
super.init(self)
end
end
end
if not h.uninit
then
function h:uninit()
for i, super in ipairs(scs)
do
super.uninit(self)
end
end
end
elseif #scs == 1
then
_index = scs[1]
else
-- just look it up in the baseclass
_index = baseclass
end
-- as we have __index, we can be used as metatable (=class of object)
h.__index = h
h.__tostring = _ts
h.__mstype = true
-- but we need metatable too, which indexes either the superclass
-- directly (1 baseclass)
setmetatable(h, {__index=_index,
__tostring=_ts})
return h
end
function pcall_and_finally(fun1, fun2)
-- error propagation doesn't really matter as much.. as good tracebacks do
if enable_debug
then
fun1()
fun2()
return
end
-- catch errors
local r, err = pcall(fun1)
-- call finally
fun2()
-- and then propagate error
if not r
then
error(err)
end
end
--- array handling
-- index in array
function array_find(t, o)
for i, o2 in ipairs(t)
do
if o == o2
then
return i
end
end
end
-- remove from array (inefficient, sigh)
function array_remove(t, o)
local i = array_find(t, o)
if i
then
table.remove(t, i)
return true
end
end
function array_reverse(t)
-- in-place reversing of the array content
local nt = #t
for i=1,nt/2
do
local v = t[i]
local i2 = nt-i+1
local v2 = t[i2]
t[i2] = v
t[i] = v2
end
return t
end
function array_is(t)
-- whether it's actually table
if not table_is(t)
then
return
end
-- this method is expensive; is it really worth it? O(n) from just
-- table_count and O(<=n) from the second step too
local cnt = table_count(t)
for i=1,cnt
do
if t[i] == nil
then
return
end
end
return true
end
function array_repr(t, shown)
local s = {}
local first = true
a(type(t) == 'table', 'non-table to table_repr', t)
shown = shown or {}
table.insert(s, "{")
if shown[t] and not repr_show_duplicates
then
return '...'
end
shown[t] = true
for i, v in ipairs(t)
do
if i > 1
then
table.insert(s, ", ")
end
table.insert(s, repr(v, shown))
end
table.insert(s, "}")
return table.concat(s)
end
-- order-preserving unique array creation
function array_unique(a)
if not a then return end
local n = array:new{}
local seen = {}
for i, v in ipairs(a)
do
if not seen[v]
then
seen[v] = true
n:insert(v)
end
end
return n
end
-- transform array to table, with default value v if provided
function array_to_table(a, default, dest)
local t = dest or map:new()
local nv = default or true
for i, v in ipairs(a)
do
t[v] = nv
end
return t
end
-- array foreach
function array_foreach(a, fun)
for _, v in ipairs(a)
do
fun(v)
end
end
-- array map
function array_map(a, fun)
return table_map(a, function (k, v)
return fun(v)
end)
end
local function _value_truish(v)
return v
end
-- array filtering
function array_filter(a, fun)
local t = array:new()
fun = fun or _value_truish
for i, v in ipairs(a)
do
if fun(v)
then
t:insert(v)
end
end
return t
end
-- array filtering variant which produces _two_ lists
-- first one containing matched, second one not matched
function array_filter2(a, fun)
local t1 = array:new()
local t2 = array:new()
for i, v in ipairs(a)
do
if fun(v)
then
t1:insert(v)
else
t2:insert(v)
end
end
return t1, t2
end
function array_slice(a, i1, i2)
local function convert_real(i)
if i < 0
then
i = 1 + #a + i
end
return i
end
i1 = i1 or 1
i2 = i2 or #a
i1 = convert_real(i1)
i2 = convert_real(i2)
local t = array:new{}
for i=i1,i2
do
t:insert(a[i])
end
return t
end
function array_extend(self, ...)
for i, l in ipairs({...})
do
for i, v in ipairs(l)
do
table.insert(self, v)
end
end
end
function array_to_set(self)
return array_to_table(self, nil, set:new())
end
array = create_class{class='array',
extend=array_extend,
filter2=array_filter2,
filter=array_filter,
find=array_find,
foreach=array_foreach,
insert=table.insert,
join=table.concat,
map=array_map,
remove=array_remove,
remove_index=table.remove,
repr=array_repr,
reverse=array_reverse,
slice=array_slice,
sort=table.sort,
to_set=array_to_set,
to_table=array_to_table,
}
function array:clear()
while #self > 0
do
self[#self] = nil
end
end
function array:count()
return #self
end
function array:is_empty()
return #self == 0
end
--- string utilities
function string_ipairs_iterator(s, i)
i = i + 1
if i > #s
then
return
end
local ss = string.sub(s, i, i)
return i, ss
end
function string_ipairs(s, st)
mst.a(type(s) == "string", "non-string input", s)
st = st or 1
return string_ipairs_iterator, s, st-1
end
function string_to_set(s)
local t = set:new()
for i, c in string_ipairs(s)
do
t:insert(c)
end
return t
end
function string_strip(s)
-- from PiL2 20.4
return (s:gsub("^%s*(.-)%s*$", "%1"))
end
function string_rstrip(s)
-- from PiL2 20.4
return (s:gsub("^(.-)%s*$", "%1"))
end
function string_endswith(s, x)
if string.sub(s, -#x) == x
then
return string.sub(s, #x-1)
end
end
function string_startswith(s, x)
if string.sub(s, 1, #x) == x
then
return string.sub(s, #x+1)
end
end
local _my_varok_table = false
function string_is_varok(s)
local t = _my_varok_table
if not t
then
t = string_to_set("1234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ_")
_my_varok_table = t
end
mst.a(type(s) == 'string', 'string_is_varok with non-string', s)
mst.a(t ~= nil, '_my_varok_table not set')
for i, c in string_ipairs(s)
do
if not t[c]
then
--mst.d('non-varok', i, c, s)
return false
end
end
--mst.d('varok', s)
return true
end
function string_is_ascii(s)
for i, c in string_ipairs(s)
do
local b = string.byte(c)
if b < 32 or b >= 128
then
return false
end
end
return true
end
function string_split_rec(s, delim, ofs, t, part, maxparts)
mst.a(s and delim and ofs and t)
if not maxparts or part < maxparts
then
for i=ofs,#s
do
if string.sub(s, i, i+#delim-1) == delim
then
t:insert(string.sub(s, ofs, i-1))
string_split_rec(s, delim, i+#delim, t, part + 1, maxparts)
return
end
end
end
t:insert(string.sub(s, ofs))
end
function string_split(s, delim, maxparts)
mst.a(type(s) == 'string', 'non-string to string_split', s)
delim = delim or ' '
mst.a(s, 'undefined argument to string_split', s, delim)
local t = array:new()
string_split_rec(s, delim, 1, t, 1, maxparts)
return t
end
function string_to_hex(s)
local t = {}
for i, c in string_ipairs(s)
do
table.insert(t, string.format('%02x', string.byte(c)))
end
return table.concat(t)
end
function hex_to_string(s)
local t = {}
mst.a(#s % 2 == 0, 'not even # of hex data? odd')
for i=1, #s/2
do
local st = i * 2 - 1
local en = st + 1
local ss = string.sub(s, st, en)
table.insert(t, string.char(tonumber(ss, 16)))
end
return table.concat(t)
end
-- string_find_one
-- try to string_find among string with multiple pattern + action functions
-- to run out of functions is fatal error => add nop handler to end if desirable
function string_find_one(s, ...)
local l = {...}
for i=1,#l,2
do
local pat = l[i]
local act = l[i+1]
local r = {string.find(s, pat)}
if #r >= 2
then
if act
then
return act(unpack(array_slice(r, 3)))
end
return
end
end
mst.a(false, 'no match for string', s, l)
end
--- table utilities + class
function table_is(t)
return type(t) == 'table'
end
-- does t contain everything within t1?
-- (using repr_equal)
function table_contains(t, t1)
mst.a(t and t1, "missing parameters to table_contains")
for k, v in pairs(t1)
do
local v1 = t[k]
if not repr_equal(v1, v)
then
--mst.d('difference in key', k, v1, v)
return nil, k
end
end
return true
end
-- deep copy table
function table_deep_copy(t, already)
mst.a(type(t) == "table")
already = already or {}
-- first off, check if 't' already done => return it as-is
local na = already[t]
if na
then
return na
end
local n = {}
already[t] = n
for k, v in pairs(t)
do
local nk = deep_copy(k, already)
local nv = deep_copy(v, already)
n[nk] = nv
end
setmetatable(n, getmetatable(t))
return n
end
-- deep copy anything(!)
function deep_copy(o, already)
already = already or {}
if table_is(o)
then
return table_deep_copy(o, already)
end
-- the rest we can't (userdata), or won't copy (string, int, ...)
return o
end
-- shallow copy table
function table_copy(t, n)
mst.a(type(t) == "table")
n = n or {}
for k, v in pairs(t)
do
n[k] = v
end
return n
end
-- get count of items within table
function table_count(t)
c = 0
for k, v in pairs(t)
do
c = c + 1
end
return c
end
-- whether table is empty or not
function table_is_empty(t)
for k, v in pairs(t)
do
return false
end
return true
end
-- table mapping
function table_map(t, f)
mst.a(type(t) == "table", "invalid input to table_map", t)
local r = array:new{}
for k, v in pairs(t)
do
local fr = f(k, v)
table.insert(r, fr)
end
return r
end
-- keys of a table
function table_keys(t)
return table_map(t, function (k, v)
return k
end)
end
-- values of a table
function table_values(t)
return table_map(t, function (k, v)
return v
end)
end
-- sorted keys of a table
_not_comparable_type = {userdata=true,
table=true,
boolean=true,
['function']=true}
function first_before_cmp(x1, x2)
local t1 = type(x1)
local t2 = type(x2)
if x1 == x2
then
return false
end
if t1 ~= t2
then
return t1 < t2
end
if _not_comparable_type[t1]
then
x1 = repr(x1)
x2 = repr(x2)
end
return x1 < x2
end
function table_sorted_keys(t)
-- ugh.. this kinda sucks, if there's userdata keys within :p
-- ugly workaround
local keys = table_keys(t)
table.sort(keys, first_before_cmp)
return keys
end
-- sorted table pairs
function table_sorted_pairs_iterator(h, k)
local t, s, sr = unpack(h)
if not k
then
i = 0
else
i = sr[k]
end
i = i + 1
if s[i]
then
return s[i], t[s[i]]
end
end
function table_sorted_pairs(t)
local s = table_sorted_keys(t)
local sr = {}
for i, v in ipairs(s)
do
sr[v] = i
end
local h = {t, s, sr}
return table_sorted_pairs_iterator, h, nil
end
-- python-style table repr
function table_repr(t, shown)
local s = {}
local first = true
a(type(t) == 'table', 'non-table to table_repr', t)
shown = shown or {}
table.insert(s, "{")
if shown[t] and not repr_show_duplicates
then
return '...'
end
shown[t] = true
for k, v in table_sorted_pairs(t)
do
if not first then table.insert(s, ", ") end
if type(k) == 'string' and string_is_varok(k)
then
ks = k
else
ks = string.format('[%s]', repr(k, shown))
end
table.insert(s, ks .. "=" .. repr(v, shown))
first = false
end
table.insert(s, "}")
return table.concat(s)
end
function table_clear(t)