forked from allegory-software/allegory-sdk
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathglue.lua
2750 lines (2492 loc) · 77.6 KB
/
glue.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
--[=[
Lua "assorted lengths of wire" library.
Written by Cosmin Apreutesei. Public domain.
TYPES
isstr(v) is v a string
isnum(v) is v a number
isint(v) is v an integer (includes 1/0 and -1/0)
istab(v) is v a table
isbool(v) is v a boolean
isarray(v) is v a table with only array elements
isempty(v) is v a table and is it empty
isfunc(v) is v a function
iscdata(v) is v a cdata
istype(v, ctype) = ffi.istype
iserror(v[, classes]) is v a structured error
inherits(v, class) is v an object that inherits from class
MATH
floor = math.floor
ceil = math.ceil
round(x[, p]) -> y round x to nearest multiple of p=1 half-up
snap = round
min = math.min
max = math.max
clamp(x, min, max) -> y clamp x in range
abs = math.abs
sign(x) -> 1|0|-1 sign
strict_sign(x) -> 1|-1 strict sign
sqrt = math.sqrt
ln = math.log
log10 = math.log10
sin = math.sin
cos = math.cos
tan = math.tan
rad = math.rad
deg = math.deg
PI = math.pi
random = math.random
randomseed = math.randomseed
random_string(n) -> s generate random string of length n
uuid() -> s generate random UUID v4
lerp(x, x0, x1, y0, y1) -> y project x in x0..x1 over y0..y1
nextpow2(x) -> y next power-of-2 number
repl(x, v, r) -> x replace v with r in x
VARARGS
pack(...) -> t pack varargs, setting t.n to arg num
unpack(t, [i], [j]) -> ... unpack varargs, using t.n if any
ARRAYS
insert = table.insert
remove = table.remove
pop = remove
sort = table.sort
add(t, v) insert(t, v)
push(t, v) = add
extend(dt, t1, ...) -> dt extend an array
append(dt, v1, ...) -> dt append non-nil values to an array
shift(t, i, n) -> t shift array elements
slice(t, [i], [j]) -> t slice an array
imap(t, field|f,...) -> t map f over ipairs of t or pluck field
indexof(v, t, [i], [j]) -> i scan array for value
cmp'KEY1[>] ...' -> f create a cmp function for sort and binsearch
binsearch(v, t, [cmp], [i], [j]) -> i bin search in sorted array
sortedarray([sa]) -> sa stay-sorted array with fast search
sa:find(v) -> i|nil find value in O(logN)
sa:add(v) add value in O(N+logN)
sa:remove(v) -> v|nil remove value in O(N+logN)
sa.cmp cmp function for binsearch
reverse(t, [i], [j]) -> t reverse array in place
TABLES
empty shared empty r/o table
count(t[, maxn]) -> n count keys in table up to maxn=1/0
index(t) -> dt switch keys with values
keys(t,[cmp]) -> dt make a list with keys of t
sortedkeys(t,[cmp]) -> dt make a sorted list of keys of t
sortedpairs(t,[cmp]) => k, v like pairs() but in key order
update(dt, t1, ...) -> dt merge tables - overwrites keys
merge(dt, t1, ...) -> dt merge tables - no overwriting
map(t, field|f,...) -> t map f over pairs of t or pluck field
attr(t, k, [f, ...]) -> v autofield pattern for one key
attrs(t, N, [f], k1,...) -> v autofield pattern for a chain of keys
attrs_find(t, k1,...) -> v return t[k1][k2]... as found
attrs_clear(t, k1,...) remove value at the end of key chain
CACHING
memoize[_multiret](f,opt...) -> mf,cache memoize pattern
tuples(opt...) -> tuple(...) -> t create a tuple space
poison poision value to clear cache on memoized func
STRINGS
format = string.format
fmt = string.format
_ = string.format
concat = table.concat
cat = concat
catany(sep, ...) -> s concat non-nil args
catall(...) -> s concat args; return nil if any arg is nil
rep = string.rep
char = string.char
byte = string.byte
num = tonumber
split(s,sep[,start[,plain]]) => e[,captures...] split a string on regex
words'name1 ... ' => 'name1' iterate words in a string
lines(s, [opt], [i]) => s, i, j, k iterate the lines of a string
outdent(s, [indent]) -> s, indent outdent/reindent text
lineinfo(s, [i]) -> line, col find text position at byte position
trim(s) -> s remove whitespace paddings
lpad(s, n, [c]) -> s left-pad string
rpad(s, n, [c]) -> s right-pad string
pad(s, n, [c], dir) -> s pad string left or right
esc(s [,mode]) -> pat escape string to use in regex
tohex(s|n [,upper]) -> s string or number to hex
fromhex(s[, isvalid]) -> s hex to string
hexblock(s) string to hex block
starts(s, prefix) -> t|f find if string starts with prefix
ends(s, suffix) -> t|f find if string ends with suffix
subst(s, t) -> s string interpolation pattern
capitalize(s) -> s capitalize words
html_escape(s) -> s escape HTML string
kbytes(x [,decimals]) -> s format byte size in k/M/G/T-bytes
STDOUT & STDERR
print_function(write[, format]) -> f create a print()-like function
printf(fmt, ...) print with string formatting
say([fmt, ...]) print to stderr
sayn(fmt, ...]) print to stderr without newline
die([fmt, ...]) exit with abort message and exit code 1
ITERATORS
collect([i,] iter) -> t collect iterated values into an array
CALLBACKS
pass(...) -> ... does nothing, returns back all arguments
noop(...) does nothing, returns nothing
OBJECTS
object([super][, t], ...) -> t create a class or object
before(class, method_name, f) call f at the beginning of a method
after(class, method_name, f) call f at the end of a method
override(class, method_name, f) override a method
gettersandsetters([gets], [sets], [super]) -> mt add virtual properties
PLATFORM
Windows, win true if platform is Windows
Linux true if platform is Linux
OSX true if platform is OSX
PROCESS CONTROL
sleep(s) suspend process i.e. blocking sleep
exit = os.exit
env = os.getenv
TIME & DATES
now() -> ts os.time() but more accurate
clock() -> x os.clock() but more accurate
time([utc, ][t]) -> ts os.time() but more accurate and with utc option
time([utc, ][y], [m], [d], [H], [M], [S], [isdst]) -> ts with positional args
date = os.date
utc_diff(t) -> seconds seconds from local time t to UTC
sunday ([utc, ]t, [weeks]) -> ts time at last Sunday before t
day ([utc, ][t], [plus_days]) -> ts time at day's beginning from t
month ([utc, ][t], [plus_months]) -> ts time at month's beginning from t
year ([utc, ][t], [plus_years]) -> ts time at year's beginning from t
duration(s, ['approx[+s]'|'long']) -> s format a duration in seconds
timeago([utc, ]t[, from_t]) -> s format relative time
timeofday(seconds) -> s format time of day
week_start(country) -> n week start in country; 0=Sunday
ERRORS
assertf(v[,fmt,...]) -> v assert with error message formatting
fpcall(f, ...) -> ok,... pcall with finally/onerror
fcall(f, ...) -> ... same but re-raises errors
errortype([classname], [super]) -> E create/get an error class
E(...) -> e create an error object
E:__call(...) -> e error class constructor
E:__tostring() -> s to make `error(e)` work
E.addtraceback add a traceback to errors
newerror(classname,... | e) -> e create/wrap/pass-through an error object
e.message formatted error message
e.traceback traceback at error site
iserror(v[, classes]) -> true|false check an error object type
raise([level, ]classname,... | e) (create and) raise an error
catch([classes], f, ...) -> true,... | false,e pcall `f` and catch errors
pcall(f, ...) -> ok,... pcall that stores traceback in `e.traceback`
lua_pcall(f, ...) -> ok,... Lua's pcall renamed (no tracebacks)
protect([classes, ]f, [oncaught]) -> f turn raising f into nil,err-returning
MODULES
module([name, ][parent]) -> M create a module
autoload(t, submodules) -> M autoload table keys from submodules
autoload(t, key, module|loader) -> t autoload table key from module
rel_scriptdir get the script's directory
scriptname get the script's name
luapath(path [,index [,ext]]) insert a path in package.path
cpath(path [,index]) insert a path in package.cpath
LUA ALLOCATION
freelist([create], [destroy]) -> alloc,free freelist allocation pattern
INTERPRETER
[p]eval(s) -> ... = loadstring('return '..s)
BITS
bit = require'bit'
bnot = bit.bnot
shl = bit.lshift
shr = bit.rshift
band = bit.band
bor = bit.bor
xor = bit.bxor
getbit(x, mask) -> bit get the value of a single bit from x
setbit(bits, mask, [x]) -> x set the value of a single bit on x
setbits(bits, mask, [x]) -> x set the value of multiple bits over x
bitflags(flags, masks, [x], [strict]) -> mask bor() flags over x
FFI
ffi = require'ffi'
C = ffi.C
cdef = ffi.cdef
new = ffi.new
cast = ffi.cast
sizeof = ffi.sizeof
offsetof = ffi.offsetof
typeof = ffi.typeof
copy = ffi.copy
fill = ffi.fill
gc = ffi.gc
metatype = ffi.metatype
istype = ffi.istype
errno = ffi.errno
check_errno(v[, err]) -> v | nil, s
str(buf, len) = ffi.string(buf, len) if buf is not null
ptr(p) = p ~= nil and p or nil
ptr_serialize(p) -> n|s store pointer address in Lua value
ptr_deserialize([ctype,]n|s) -> p convert address to pointer
FFI ALLOCATION
buffer([ctype]) -> alloc
alloc(len) -> buf,len alloc len and get a buffer
dynarray([ctype][,cap]) -> alloc
alloc(len)->buf,len alloc len and get a buffer, contents preserved
dynarray_pump([dynarray]) -> write, collect
write(buf,len) append to internal buffer
collect() -> buf,len get internal buffer
dynarray_loader([dynarray]) -> get, commit, collect
get(len) -> buf,len get a buffer of len to write to
commit(len) commit len
collect() -> buf,len get internal buffer
readall(read,...) -> buf,len repeat read based on a read function
buffer_reader(buf,len)->read make a read function that consumes a buffer
malloc(size) -> p C malloc
realloc(p, size) -> p C realloc
free(p) C free
CONFIG
config(k[, default]) -> v get/set global config value
with_config(conf, f, ...) -> ... run f with custom config table
load_config_file(file) load config file
load_config_string(s) load config from string
DEBUGGING
traceback = debug.traceback
trace() print current stack trace to stderr
pr(...) print to stderr with logargs
LOGGING
see logging.lua
]=]
if not ... then require'glue_test'; return end
ffi = require'ffi'
bit = require'bit'
require'time'
require'pp'
local
type, select, pairs, next, rawget, rawset, assert, error, tostring, setmetatable, getmetatable =
type, select, pairs, next, rawget, rawset, assert, error, tostring, setmetatable, getmetatable
local format = string.format
local concat = table.concat
local insert = table.insert
local remove = table.remove
local sort = table.sort
local gsub = string.gsub
local io_stderr = io.stderr
local ffi_string = ffi.string
local function str(s, len)
if s == nil then return nil end
return ffi_string(s, len)
end
function ptr(p)
return p ~= nil and p or nil
end
--types ----------------------------------------------------------------------
isstr = function(v) return type(v) == 'string' end
isnum = function(v) return type(v) == 'number' end
isint = function(v) return type(v) == 'number' and floor(v) == v end
istab = function(v) return type(v) == 'table' end
isbool = function(v) return v == true or v == false end
isarray = require'table.isarray'
isempty = require'table.isempty'
isfunc = function(v) return type(v) == 'function' end
iscdata = function(v) return type(v) == 'cdata' end
isthread = function(v) return type(v) == 'thread' end
--math -----------------------------------------------------------------------
min = math.min
max = math.max
floor = math.floor
ceil = math.ceil
abs = math.abs
sqrt = math.sqrt
ln = math.log
log10 = math.log10
sin = math.sin
cos = math.cos
tan = math.tan
rad = math.rad
deg = math.deg
PI = math.pi
random = math.random
randomseed = math.randomseed
local
min, max, floor, ceil, ln, random =
min, max, floor, ceil, ln, random
--Round a number towards nearest integer or multiple of p.
--Rounds half-up (i.e. it returns -1 for -1.5).
--Works with numbers up to +/-2^52.
--It's not dead accurate as it returns eg. 1 instead of 0 for
-- 0.49999999999999997 (the number right before 0.5) which is < 0.5.
function round(x, p)
p = p or 1
return floor(x / p + .5) * p
end
snap = round
--clamp a value in range. If max < min, the result is max.
function clamp(x, x0, x1)
return min(max(x, x0), x1)
end
--linearly project x in x0..x1 range to the y0..y1 range.
function lerp(x, x0, x1, y0, y1)
return y0 + (x-x0) * ((y1-y0) / (x1 - x0))
end
function logbase(x, base)
return ln(x) / ln(base)
end
function nextpow2(x)
return max(0, 2^(ceil(ln(x) / ln(2))))
end
function sign(x)
return x > 0 and 1 or x == 0 and 0 or -1
end
function strict_sign(x)
return x >= 0 and 1 or -1
end
function repl(x, v, r)
if x == v then return r else return x end
end
function uuid() --don't forget to seed the randomizer!
return format('%08x-%04x-%04x-%04x-%08x%04x',
random(0xffffffff), random(0xffff),
0x4000 + random(0x0fff), --4xxx
0x8000 + random(0x3fff), --10bb-bbbb-bbbb-bbbb
random(0xffffffff), random(0xffff))
end
do
local u32a = ffi.typeof'uint32_t[?]'
function random_string(n)
local buf = u32a(n/4+1)
for i=0,n/4 do
buf[i] = random(0, 2^32-1)
end
return str(buf, n)
end
end
--varargs --------------------------------------------------------------------
if table.pack then
pack = table.pack
else
function pack(...)
return {n = select('#', ...), ...}
end
end
--always use this because table.unpack's default j is #t not t.n.
local lua_unpack = unpack
function unpack(t, i, j)
return lua_unpack(t, i or 1, j or t.n or #t)
end
--tables ---------------------------------------------------------------------
_G.concat = table.concat
_G.cat = table.concat
_G.insert = table.insert
_G.remove = table.remove
_G.pop = table.remove
_G.sort = table.sort
function add(t, v)
return insert(t, v)
end
push = add
--scan list for value. works with ffi arrays too given i and j.
--Works on ffi arrays too if i and j are provided.
function indexof(v, t, eq, i, j)
i = i or 1
j = j or #t
if eq then
for i = i, j do
if eq(t[i], v) then
return i
end
end
else
for i = i, j do
if t[i] == v then
return i
end
end
end
end
--reverse elements of a list in place. works with ffi arrays too given i and j.
function reverse(t, i, j)
i = i or 1
j = (j or #t) + 1
for k = 1, (j-i)/2 do
t[i+k-1], t[j-k] = t[j-k], t[i+k-1]
end
return t
end
-- binary search for the smallest insert position that keeps the table sorted.
-- returns nil if v is larger than the largest value or if t is empty.
-- works with ffi arrays too if lo and hi are provided.
-- cmp is f(t, i, v) -> t|f or it can be '<', '>', '<=', '>='.
-- use t[i] < v to get the smallest insert position.
-- use t[i] <= v to get the largest insert position.
-- use t[i] > v (i.e. '>') to search in a reverse-sorted array.
local cmps = {}
cmps['<' ] = function(t, i, v) return t[i] < v end
cmps['>' ] = function(t, i, v) return t[i] > v end
cmps['<='] = function(t, i, v) return t[i] <= v end
cmps['>='] = function(t, i, v) return t[i] >= v end
local less = cmps['<']
function binsearch(v, t, cmp, lo, hi)
lo, hi = lo or 1, hi or #t
cmp = cmp and cmps[cmp] or cmp or less
local len = hi - lo + 1
if len == 0 then return nil end
if len == 1 then return not cmp(t, lo, v) and lo or nil end
while lo < hi do
local mid = floor(lo + (hi - lo) / 2)
if cmp(t, mid, v) then
lo = mid + 1
if lo == hi and cmp(t, lo, v) then
return nil
end
else
hi = mid
end
end
return lo
end
--array that stays sorted with search in O(logN) and add/remove in O(N+logN).
--if given an array to be wrapped, it must be already sorted.
--sa.cmp is used for cmp in binarysearch().
do
local sa = {}
local insert, remove, binsearch = insert, remove, binsearch
function sa:find(v)
return binsearch(v, self, self.cmp)
end
function sa:add(v)
local i = self:find(v) or #self+1
insert(self, i, v)
return i
end
function sa:remove(v)
local i = self:find(v)
if not i then return nil end
return remove(self, i)
end
function sortedarray(t)
return object(sa, t)
end
end
empty = setmetatable({}, {
__newindex = function() error'trying to set a field in empty' end, --read-only
__metatable = false,
})
--count the keys in a table with an optional upper limit.
function count(t, maxn)
local maxn = maxn or 1/0
local n = 0
for _ in pairs(t) do
n = n + 1
if n >= maxn then break end
end
return n
end
--reverse keys with values.
function index(t)
local dt={}
for k,v in pairs(t) do dt[v]=k end
return dt
end
--create a comparison function for sorting objects with sort().
local function cmp_asc (a, b) return a < b end
local function cmp_desc (a, b) return a > b end
local function cmp_k_asc(k)
return function(a, b)
local a, b = a[k], b[k]
return a < b and -1 or a > b and 1
end
end
local function cmp_k_desc(k)
return function(a, b)
local a, b = a[k], b[k]
return a > b and -1 or a < b and 1
end
end
function cmp(keys) --true|false|'KEY1[>] ...'
if type(keys) ~= 'string' then
return keys
elseif keys == true then
return cmp_asc
elseif keys == false then
return cmd_desc
end
local f
for s in keys:gmatch'%S+' do
local k, desc = s:match'^(.-)([<>])$'
if k then
desc = desc == '>'
else
k = s
end
local f1 = desc and cmp_k_desc(k) or cmp_k_asc(k)
if not f then
f = f1
else
local f0 = f
f = function(a, b)
return f0(a, b) or f1(a, b)
end
end
end
return function(a, b)
return f(a, b) == -1
end
end
--put keys in a list, optionally sorted.
local function desc_cmp(a, b) return a > b end
local glue_cmp = cmp
function keys(t, cmp)
local dt={}
for k in pairs(t) do
dt[#dt+1]=k
end
if cmp == true then
sort(dt)
elseif cmp == false then
sort(dt, desc_cmp)
elseif type(cmp) == 'string' then
cmp = glue_cmp(cmp)
sort(dt, function(k1, k2)
return cmp(t[k1], t[k2])
end)
elseif cmp then
sort(dt, cmp)
end
return dt
end
local
repl, keys =
repl, keys
function sortedkeys(t, cmp)
return keys(t, repl(cmp, nil, true))
end
--stateless pairs() that iterate elements in key order.
function sortedpairs(t, cmp)
local kt = keys(t, repl(cmp, nil, true))
local i, n = 0, #kt
return function()
i = i + 1
if i > n then return end
return kt[i], t[kt[i]]
end
end
--update a table with the contents of other table(s) (falsey args skipped).
function update(dt,...)
for i=1,select('#',...) do
local t=select(i,...)
if t then
for k,v in pairs(t) do dt[k]=v end
end
end
return dt
end
--add the contents of other table(s) without overwrite.
function merge(dt,...)
for i=1,select('#',...) do
local t=select(i,...)
if t then
for k,v in pairs(t) do
if rawget(dt, k) == nil then dt[k]=v end
end
end
end
return dt
end
local NIL = {}
--`attr(t, k1)[k2] = v` is like `t[k1][k2] = v` with auto-creating `t[k1]`.
function attr(t, k, cons, ...)
if k == nil then k = NIL end
local v = t[k]
if v == nil then
if cons == nil then
v = {}
t[k] = v
else
v = cons(...)
t[k] = v == nil and NIL or v
end
end
return v
end
function attrs(t, n, cons, ...)
for i = 1, n do
local k = select(i,...)
if k == nil then k = NIL end
local v = t[k]
if i < n then
if v == nil then
v = {}
t[k] = v
end
t = v
else
if v == nil then
if cons then
v = cons(...)
t[k] = v == nil and NIL or v
else
v = {}
t[k] = v
end
elseif v == NIL then
v = nil
end
return v
end
end
end
function attrs_find(t, ...)
for i = 1, select('#', ...) do
local k = select(i,...)
if k == nil then k = NIL end
local v = t[k]
if v == nil then return nil end
t = v
end
return t
end
function attrs_clear(t, ...)
local n = select('#', ...)
if n == 0 then
for k,v in pairs(t) do
t[k] = nil
end
return
end
local empty_t, empty_k
--^^ first t[k] that will be pointing at a chain of empty tables after
--the value is removed, so they can be safely removed with t[k] = nil.
local t0, k0
for i = 1, n do
local k = select(i, ...)
if k == nil then k = NIL end
local v = t[k]
if v == nil then
break
end
if next(t) == k and next(t, k) == nil then --k is the only key left in t.
if not empty_t then
empty_t, empty_k = t0, k0
end
else
empty_t, empty_k = nil
end
if i < n then
t0, k0 = t, k
t = v
else
t[k] = nil
if empty_t then
empty_t[empty_k] = nil
end
end
end
end
local attrs, attrs_clear = attrs, attrs_clear
local NOARG = {} --special arg for zero-arg functions or calls.
--with fixarg functions we store the memoized value in the leaf node directly.
local function memoize_fixarg(f, n, cache)
cache = cache or {}
if n == 0 then
return function()
return attrs(cache, 1, f, NOARG)
end, cache
else
return function(...)
return attrs(cache, n, f, ...)
end, cache
end
end
--with vararg functions we can't just store the memoized value in the
--leaf node because any leaf node can become a key node on future calls.
local VAL = {} --special key to store the memozied value in the leaf node.
local function memoize_vararg(f, minarg, maxarg, cache)
cache = cache or {}
return function(...)
local n = min(max(select('#', ...), minarg), maxarg)
local t = n == 0
and attrs(cache, 1, nil, NOARG)
or attrs(cache, n, nil, ...)
local v = t[VAL]
if v == nil then
v = f(...)
assert(v ~= nil)
t[VAL] = v
end
return v
end, cache
end
--special value to use as arg#1 on a memoized function to clear the cache
--on a prefix of arguments.
poison = {}
local poison = poison
local debug_getinfo = debug.getinfo
function memoize(f, cache, minarg, maxarg)
if not minarg then
local info = debug_getinfo(f, 'u')
if info.isvararg then
minarg, maxarg = info.nparams, 1/0
else
minarg, maxarg = info.nparams, info.nparams
end
end
cache = cache or {}
local mf = minarg ~= maxarg
and memoize_vararg(f, minarg, maxarg, cache)
or memoize_fixarg(f, minarg, cache)
return function(...)
if ... == poison then
attrs_clear(cache, select(2, ...))
else
return mf(...)
end
end, cache, minarg, maxarg
end
function memoize_multiret(f, ...)
local mf = memoize(function(...)
return pack(f(...))
end, ...)
return function(...)
return unpack(mf(...))
end
end
--tuples are interned value lists that can be used as table keys to achieve
--multi-key indexing because they have value semantics: a tuple space returns
--the same tuple object for the same combination of values.
do
local tuple_mt = {__call = unpack}
function tuple_mt:__tostring()
local t = {}
for i=1,self.n do
t[i] = tostring(self[i])
end
return format('(%s)', concat(t, ', '))
end
function tuples(n, space)
space = space or {}
local function gen_tuple(...)
return setmetatable({n = select('#', ...), ...}, tuple_mt)
end
if n then --fixarg: use the leaf node itself as the tuple object.
assert(n >= 1)
return memoize_fixarg(gen_tuple, n, space)
else --vararg: put the tuple in the special VAL key of the value-table.
return memoize_vararg(gen_tuple, 0, 1/0, space)
end
end
function istuple(t)
return getmetatable(t) == tuple_mt
end
end
cmp_k_asc = memoize(cmp_k_asc)
cmp_k_desc = memoize(cmp_k_desc)
--extend a list with the elements of other lists (skipping falsey args).
function extend(dt,...)
for j=1,select('#',...) do
local t=select(j,...)
if t then
local j = dt.n or #dt
local n = t.n or #t
for i=1,n do dt[j+i]=t[i] end
if t.n or dt.n then dt.n = j+n end --adding a sparse array makes dt sparse.
end
end
return dt
end
--append non-nil arguments to a list.
function append(dt,...)
local j = #dt
for i=1,select('#',...) do
dt[j+i] = select(i,...)
end
return dt
end
--insert n elements at i, shifting elemens on the right of i (i inclusive)
--to the right.
local function insert_n(t, i, n)
if n == 1 then --shift 1
insert(t, i, false)
return
end
for p = #t,i,-1 do --shift n
t[p+n] = t[p]
end
end
--remove n elements at i, shifting elements on the right of i (i inclusive)
--to the left.
local function remove_n(t, i, n)
n = min(n, #t-i+1)
if n == 1 then --shift 1
remove(t, i)
return
end
for p=i+n,#t do --shift n
t[p-n] = t[p]
end
for p=#t,#t-n+1,-1 do --clean tail
t[p] = nil
end
end
local clamp = clamp
function slice(t, i, j) --TODO: not used. use it or scrape it.
local n = t.n or #t
i = i or 1
j = j or n
if i < 0 then i = n - i + 1 end
if j < 0 then j = n - i + 1 end
i = clamp(i, 1, n)
j = clamp(j, 1, n)
local dt = {}
for i=i,j do dt[i] = t[i] end
return dt
end
--shift all the elements on the right of i (i inclusive), n positions to the
--to the left (if n is negative), removing elements, or further to the right
--(if n is positive), making room for new elements.
function shift(t, i, n)
if n > 0 then
insert_n(t, i, n)
elseif n < 0 then
remove_n(t, i, -n)
end
return t
end
--map `f(k, v, ...) -> v1` over t or extract a column from a list of records.
--if f is not a function, then the values of t must be themselves tables,
--in which case f is a key to pluck from those tables. Plucked functions
--are called as methods and their result is selected instead. This allows eg.
--calling a method for each element in a table of objects and collecting
--the results in a table.
function map(t, f, ...)
local dt = {}
if type(f) == 'function' then
for k,v in pairs(t) do
dt[k] = f(k, v, ...)
end
else
for k,v in pairs(t) do
local sel = v[f]
if type(sel) == 'function' then --method to apply
dt[k] = sel(v, ...)
else --field to pluck
dt[k] = sel
end
end
end
return dt
end
--map `f(v, ...) -> v1` over t or extract a column from a list of records.
--same plucking semantics as map() but applied on lists.
function imap(t, f, ...)
local dt = {n = t.n}
local n = t.n or #t
if type(f) == 'function' then
for i=1,n do
dt[i] = f(t[i], ...)
end
else
for i=1,n do
local v = t[i]
local sel = v[f]
if type(sel) == 'function' then --method to apply
dt[i] = sel(v, ...)
else --field to pluck
dt[i] = sel
end
end
end
return dt
end
--strings --------------------------------------------------------------------
_G.format = format
fmt = format
_ = format
rep = string.rep
char = string.char
byte = string.byte
num = tonumber
--split a string by a separator pattern (or plain string).
--returns a stateless iterator for the pieces.
--if sep is '' returns the entire string in one iteration.
--empty strings between separators are always returned, eg. split(',', ',')
--produces 2 empty strings.
--captures are allowed in sep and they are returned after the element,
--except for the last element for which they don't match (by definition).
local function iterate_once(s, s1)
return s1 == nil and s or nil
end
function split(s, sep, start, plain)
start = start or 1
plain = plain or false
if not s:find(sep, start, plain) then
return iterate_once, s:sub(start)
end
local done = false
local function cont(i, j, ...)
if i then
local seg = s:sub(start, i - 1)
start = j + 1
return seg, ...
else
done = true
return s:sub(start)
end
end
return function()
if done then return end
if sep == '' then done = true; return s:sub(start) end
return cont(s:find(sep, start, plain))
end
end
string.split = split