-
Notifications
You must be signed in to change notification settings - Fork 8
/
Copy pathlibrary.awk
1551 lines (1376 loc) · 41.9 KB
/
library.awk
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
# library.awk
# globals EXITCODE, MISSING
# if you call die, assert, or check*: start END blocks with
# { if (EXITCODE) exit EXITCODE; ... }
function die(msg) {
EXITCODE=1
printf("%s: %s\n", ARGV[0], msg) > "/dev/stderr"
exit EXITCODE
}
function assert(test, msg) {
if (!test) die(msg ? msg : "assertion failed")
}
# missing values are only isnull(), isnum(), iszero(), isint(), isnat() when a true second arg is supplied
# "" values (even if set from command-line) are only isnull()
# 0 and "0" values are isnum(), iszero(), isint(), isnat(), but other values coercable to 0 aren't
# floats are isnum() but not ispos(), isneg()
# unitialized scalar
function ismissing(u) {
return u == 0 && u == ""
}
function check(u, missing) {
if (u == 0 && u == "") {
MISSING = 1
return missing
}
MISSING = 0
return u
}
# explicit ""
function isnull(s, u) {
if (u) return s == "" # accept missing as well
return !s && s != 0
}
function isnum(n, u) {
# return n ~ /^[+-]?[0-9]+$/
if (u) return n == n +0 # accept missing as well
return n "" == n +0
# NOTE: awk will also convert when there's leading space/trailing anything
# and will convert any other non-numeric to 0
}
# returns num or missing, else die(msg)
function checknum(n, missing, msg) {
if (n "" == n + 0) {
MISSING = 0
return n # explicit numbers are preserved
} else if (msg && n != n + 0) die(msg)
MISSING = 1
return missing
}
# explicit 0 or "0"
function iszero(n, u) {
# return n + 0 == 0 # accept any coercable
if (u) return n == 0 # accept missing as well
return n == 0 && n != ""
}
function isint(n, u) {
if (u) return int(n) == n # accept missing as well
return int(n) == n && n != ""
}
# explicit isnum >= 0
function isnat(n, u) {
if (u) return int(n) == n && n >= 0 # accept missing as well
return int(n) == n && n "" >= 0
}
# returns nat or missing, else die(msg)
function checknat(n, missing, msg) {
if (int(n) == n) {
if (n "" >= 0) {
MISSING = 0
return n # explicit numbers are preserved
} else if (msg && n < 0) die(msg)
} else if (msg) die(msg)
MISSING = 1
return missing
}
# explicit isnum > 0
function ispos(n) {
# return n "" == n +0 && n > 0 # accept float as well
return int(n) == n && n > 0
}
# returns pos or missing, else die(msg)
function checkpos(n, missing, msg) {
if (int(n) == n) {
if (n "" > 0) {
MISSING = 0
return n # explicit numbers are preserved
} else if (msg && (n < 0 || n "" >= 0)) die(msg)
} else if (msg) die(msg)
MISSING = 1
return missing
}
function isneg(n) {
# return n "" == n +0 && n < 0 # accept float as well
return int(n) == n && n < 0
}
## numeric utils #########
# might as well inline
function max(m, n) { return (m > n) ? m : n }
# might as well inline
function min(m, n) { return (m < n) ? m : n }
# return k=1 distinct random elements A[1 <= i <= n], separated by SUBSEP
function choose(n, k, A, i, r, p) {
k = checkpos(k, 1, "choose: second argument must be positive")
if (!isempty(A)) {
# A is already populated, choose k elements from A[1]..A[n], ordered by index
if (!n) {
n = 1
while (n in A) n++
n--
}
p = r = ""
for (i = 1; n > 0; i++)
if (rand() < k/n--) {
p = p r A[i]
r = SUBSEP
k--
}
return p
}
# else choose k integers from 1..n, ordered
if (k == 1)
return int(n*rand())+1
for (i = n-k+1; i <= n; i++)
((r = int(i*rand())+1) in A) ? A[i] : A[r]
p = r = ""
for (i=1; i<=n; i++)
if (i in A) {
p = p r i
r = SUBSEP
}
split("", A) # does it help to delete the aux array?
return p
}
# random permutation of k=n integers between 1 and n
# a random deck is: split(permute(52,52), deck, SUBSEP)
function permute(n, k, i, r, p) {
k = checkpos(k, n, "permute: second argument must be positive")
p = SUBSEP
for (i = n-k+1; i <= n; i++) {
if (p ~ SUBSEP (r = int(i*rand())+1) SUBSEP)
# since i is higher than before, p only contains r when r < i
sub(SUBSEP r SUBSEP, SUBSEP r SUBSEP i SUBSEP, p) # put i after r
else p = SUBSEP r p # put r at beginning
}
return substr(p, 2, length(p)-2)
}
# Shuffle an array with indexes from 1 to n. (Knuth or Fisher-Yates shuffle)
function shuffle(A, n, i, j, t) {
if (!n) {
n = 1
while (n in A) n++
n--
}
for (i = n; i > 1; i--) {
j = int(i * rand()) + 1 # random integer from 1 to i
t = A[i]; A[i] = A[j]; A[j] = t # swap A[i], A[j]
}
}
## array utils #########
function isempty(array, i) {
for (i in array) return 0
return 1
}
# insertion sort A[1..n]
# stable, O(n^2) but fast for small arrays
function sort(A,n, i,j,t) {
if (!n) {
n = 1
while (n in A) n++
n--
}
for (i = 2; i <= n; i++) {
t = A[i]
for (j = i; j > 1 && A[j-1] > t; j--)
A[j] = A[j-1]
A[j] = t
}
}
# mergesort is stable, O(n log n) worst-case
# on arrays uses O(n) auxiliary space; but on linked lists only a small constant space
# implementation not provided here
# in-place quicksort A[left..right]
# for efficiency, left and right must be supplied, default values aren't calculated
# unstable
# on avg thought to be constantly better than heapsort, but has worst-case O(n^2)
# choose random pivot to avoid worst-case behavior on already-sorted arrays
# advantage over mergesort is that it only uses O(log n) auxiliary space (if we have tail-calls)
function qsort(A,left,right, i,last,t) {
if (left >= right) # do nothing if array contains at most one element
return
i = left + int((right-left+1)*rand()) # choose pivot
t = A[left]; A[left] = A[i]; A[i] = t # swap A[left] and A[i]
last = left
for (i = left+1; i <= right; i++)
if (A[i] < A[left]) {
++last
t = A[last]; A[last] = A[i]; A[i] = t # swap A[last] and A[i]
}
t = A[left]; A[left] = A[last]; A[last] = t # swap A[left] and A[last]
qsort(A, left, last-1)
qsort(A, last+1, right)
}
# heapsort
# also unstable, and unlike merge and quicksort it relies on random-access so has poorer cache performance
# advantage over quicksort is that its worst-case same as avg: O(n log n)
# this presentation based on http://dada.perl.it/shootout/heapsort.lua5.html
function hsort(A, n, c, p, t, i) {
if (!n) {
n = 1
while (n in A) n++
n--
}
i = int(n/2) + 1
while (1) {
if (i > 1) {
i--
t = A[i]
} else {
t = A[n]
A[n] = A[1]
n--
if (n == 1) {
A[1] = t
return
}
}
for (p = i; (c = 2*p) <= n; p = c) {
if ((c < n) && (A[c] < A[c+1]))
c++
if (t < A[c])
A[p] = A[c]
else break
}
A[p] = t
}
}
# # one of the more usual presentations
# function hsort(A,n, i,t) {
# if (!n) {
# n = 1
# while (n in A) n++
# n--
# }
# for (i = int(n/2); i >= 1; i--)
# heapify(A, i, n)
# for (i = n; i > 1; i--) {
# t = A[1]; A[1] = A[i]; A[i] = t # swap A[1] and A[i]
# heapify(A, 1, i-1)
# }
# }
#
# function heapify(A,left,right, p,c,t) {
# for (p = left; (c = 2*p) <= right; p = c) {
# if (c < right && A[c] < A[c+1])
# c++
# if (A[p] < A[c]) {
# t = A[c]; A[c] = A[p]; A[p] = t # swap A[c] and A[p]
# } else break
# }
# }
# if used on $0, rewrites it using OFS
# if you want to preserve existing FS, need to use gsplit
# can also be used on array
# returns popped elements separated by SUBSEP
function pop(start, len, A, stop, p, last) {
start = checkpos(start, 0, "pop: first argument must be positive")
len = checknat(len, 0, "pop: second argument must be >= 0")
if (isempty(A)) {
if (!start)
start = NF
if (!len && !MISSING)
return "" # explicit len=0
if (!len)
len = NF - start + 1
stop = start + len - 1
p = res = ""
for(; ++stop <= NF; ++start) {
if (len-- > 0) {
res = res p $start
p = SUBSEP
}
$start = $stop
}
stop = start - 1
for (; start <= NF; ++start) {
if (len-- > 0) {
res = res p $start
p = SUBSEP
}
}
NF = stop
if (!p) {
# nawk won't recompute $0 just because NF was mutated
if (NF) $1 = $1
else $0 = ""
}
return res
} else {
# using array
last = 1
while (last in A) last++
last--
if (!start)
start = last
if (!len && !MISSING)
return "" # explicit len=0
if (!len)
len = last - start + 1
stop = start + len - 1
p = res = ""
for(; ++stop <= last; ++start) {
if (len-- > 0) {
res = res p A[start]
p = SUBSEP
}
A[start] = A[stop]
}
for (; start <= last; ++start) {
if (len-- > 0) {
res = res p A[start]
p = SUBSEP
}
delete A[start]
}
return res
}
}
function insert(value, start, A, stop, last) {
start = checkpos(start, 0, "insert: second argument must be positive")
if (isempty(A)) {
if (!start)
start = NF + 1
for (stop = NF; stop >= start; stop--) {
$(stop+1) = $stop
}
$start = value
return NF
} else {
# using array
last = 1
while (last in A) last++
last--
if (!start)
start = last+1
for (stop = last; stop >= start; stop--) {
A[stop+1] = A[stop]
}
A[start] = value
return (start > last) ? start : last + 1
}
}
function extend(V, start, A, stop, lastV, last) {
start = checkpos(start, 0, "insert: second argument must be positive")
lastV = 1
while (lastV in V) lastV++
lastV--
if (isempty(A)) {
if (!lastV)
return NF
if (!start)
start = NF + 1
for (stop = NF; stop >= start; stop--) {
$(stop+lastV) = $stop
}
for (start--; lastV > 0; lastV--)
$(start+lastV) = V[lastV]
return NF
} else {
# using array
last = 1
while (last in A) last++
last--
if (!lastV)
return last
if (!start)
start = last+1
for (stop = last; stop >= start; stop--) {
A[stop+lastV] = A[stop]
}
last = (start > last) ? start + lastV - 1 : last + lastV
for (start--; lastV > 0; lastV--)
A[start + lastV] = V[lastV]
return last
}
}
function reverse(A, i, t, last) {
if (isempty(A)) {
last = NF + 1
for (i=1; i < last--; i++) {
t = $i
$i = $last
$last = t
}
} else {
# using array
last = 1
while (last in A) last++
for (i=1; i < last--; i++) {
t = A[i]
A[i] = A[last]
A[last] = t
}
}
}
# defaults to fields $start..$NF, using OFS
# if you want to preserve existing FS, need to use gsplit
# to concat an array without specifying len: concat(start, <uninitialized>, OFS, array)
function concat(start, len, fs, A, i, s, p, stop) {
fs = check(fs, OFS)
start = checkpos(start, 1, "concat: first argument must be positive")
len = checknat(len, 0, "concat: second argument must be >= 0")
if (!len && !MISSING)
return "" # explicit len=0
s = p = ""
if (isempty(A)) {
if (len)
stop = start + len - 1
else
stop = NF
# more with fields
for (i=start; i<=stop; i++) {
s = s p $i
p = fs
}
} else {
# using array
if (len)
stop = start + len - 1
for (i=start; len ? i<=stop : i in A; i++) {
s = s p A[i]
p = fs
}
}
return s
}
function has_value(A, value, k) {
for (k in A)
if (A[k] == value)
return true
return false
}
# if onlykeys, values are ignored
function includes(A, B, onlykeys, k) {
for (k in B)
if (!(k in A && (onlykeys || A[k] == B[k])))
return 0
return 1
}
# if conflicts=0, drop keys; else favor A1 or A2; default=1
function union(A1, A2, conflicts, k) {
conflicts = checknat(conflicts, 1, "union: third argument must be 0, 1, or 2")
if (conflicts > 2) die("union: third argument must be 0, 1, or 2")
for (k in A2)
if (k in A1) {
if (conflicts == 2)
A1[k] = A2[k]
else if (conflicts == 0 && A1[k] != A2[k])
delete A1[k]
} else {
A1[k] = A2[k]
}
}
# if conflicts=0, drop keys; else favor A1 or A2; default=1
function intersect(A1, A2, conflicts, k) {
conflicts = checknat(conflicts, 1, "intersect: third argument must be 0, 1, or 2")
if (conflicts > 2) die("intersect: third argument must be 0, 1, or 2")
for (k in A1)
if (k in A2) {
if (conflicts == 2)
A1[k] = A2[k]
else if (conflicts == 0 && A1[k] != A2[k])
delete A1[k]
} else {
delete A1[k]
}
}
# if conflicts=0, drop keys; else keep them (favoring A1); default=1
function subtract(A1, A2, conflicts, k) {
conflicts = checknat(conflicts, 1, "subtract: third argument must be 0 or 1")
if (conflicts > 1) die("subtract: third argument must be 0 or 1")
for (k in A2)
if (k in A1) {
if (conflicts == 0 || A1[k] == A2[k])
delete A1[k]
}
}
## string utils #########
# 'quote' str for shell
function quote(str) {
gsub(/'/, "'\\''", str)
return "'" str "'"
}
# delete "quoted" spans, honoring \\ and \"
function delete_quoted(str, repl) {
# gsub(/"((\\")*([^"\\]|\\[^"])*)*"/, repl, str)
gsub(/"([^"\\]|\\.)*"/, repl, str)
return str
}
function parse_json(str, T, V, slack, c,s,n,a,A,b,B,C,U,W,i,j,k,u,v,w,root) {
# use strings, numbers, booleans as separators
# c = "[^\"\\\\[:cntrl:]]|\\\\[\"\\\\/bfnrt]|\\u[[:xdigit:]][[:xdigit:]][[:xdigit:]][[:xdigit:]]"
c = "[^\"\\\\\001-\037]|\\\\[\"\\\\/bfnrt]|\\\\u[[:xdigit:]A-F][[:xdigit:]A-F][[:xdigit:]A-F][[:xdigit:]A-F]"
s ="\"(" c ")*\""
n = "-?(0|[1-9][[:digit:]]*)([.][[:digit:]]+)?([eE][+-]?[[:digit:]]+)?"
root = gsplit(str, A, s "|" n "|true|false|null", T)
assert(root > 0, "unexpected")
# rejoin string using value indices
str = ""
for (i=1; i<root; i++)
str = str A[i] i
str = str A[root]
# cleanup types and values
for (i=1; i<root; i++) {
if (T[i] ~ /^\"/) {
b = split(substr(T[i], 2, length(T[i])-2), B, /\\/)
if (b == 0) v = ""
else {
v = B[1]
k = 0
for (j=2; j <= b; j++) {
u = B[j]
if (u == "") {
if (++k % 2 == 1) v = v "\\"
} else {
w = substr(u, 1, 1)
if (w == "b") v = v "\b" substr(u, 2)
else if (w == "f") v = v "\f" substr(u, 2)
else if (w == "n") v = v "\n" substr(u, 2)
else if (w == "r") v = v "\r" substr(u, 2)
else if (w == "t") v = v "\t" substr(u, 2)
else v = v u
}
}
}
V[i] = v
T[i] = "string"
} else if (T[i] !~ /true|false|null/) {
V[i] = T[i] + 0
T[i] = "number"
} else {
V[i] = T[i]
}
}
# sanitize string
gsub(/[[:space:]]+/, "", str)
if (str !~ /^[][{}[:digit:],:]+$/) {
if (slack !~ /:/) return -1
# handle ...unquoted:...
a = gsplit(str, A, "[[:alpha:]_][[:alnum:]_]*:", B)
str = ""
for (i=1; i < a; i++) {
T[root] = "string"
V[root] = substr(B[i], 1, length(B[i])-1)
str = str A[i] root ":"
root++
}
str = str A[a]
if (str !~ /^[][{}[:digit:],:]+$/) return -10
}
# atomic value?
a = gsplit(str, A, "[[{]", B)
if (A[1] != "") {
if (a > 1) return -2
else if (A[1] !~ /^[[:digit:]]+$/) return -3
else return A[1]+0
}
# parse objects and arrays
k = root
C[0] = 0
for (i=2; i<=a; i++) {
T[k] = (B[i-1] ~ /\{/) ? "object" : "array"
C[k] = C[0]
C[0] = k
u = gsplit(A[i], U, "[]}]", W)
assert(u > 0, "unexpected")
V[k++] = U[1]
if (i < a && A[i] != "" && U[u] !~ /[,:]$/)
return -4
for (j=1; j<u; j++) {
if (C[0] == 0 || T[C[0]] != ((W[j] == "}") ? "object" : "array")) return -5
v = C[0]
w = C[v]
C[0] = w
delete C[v]
if (w) V[w] = V[w] v U[j+1]
}
}
if (C[0] != 0) return -6
# check contents
for (i=root; i<k; i++) {
if (T[i] == "object") {
# check object contents
b = split(V[i], B, /,/)
for (j=1; j <= b; j++) {
if (B[j] !~ /^[[:digit:]]+:[[:digit:]]+$/)
return -7
if (T[substr(B[j], 1, index(B[j],":")-1)] != "string")
return -8
}
} else if (V[i] != "") {
# check array contents
if (slack ~ /,/ && V[i] ~ /,$/)
V[i] = substr(V[i], 1, length(V[i] -1))
if (V[i] !~ /^[[:digit:]]+(,[[:digit:]]+)*$/)
return -9
}
}
return root
}
function query_json(str, X, root, slack, T, V, A, B, C, i, j, k) {
k = parse_json(str, T, V, slack)
if (k < 1) return k
split(root, C, ".")
j = 1
while (j in C) {
if (T[k] == "array")
split(V[k], A, ",")
else {
split("", A)
asplit(V[k], B, ":", ",")
for (i in B)
A[V[i]] = B[i]
}
if (C[j] in A) {
k = A[C[j]]
j++
} else return -11 # can't find requested root
}
# split("", B)
# split("", C)
split("", X)
B[k] = ""
C[k] = 0
C[0] = k
do {
C[0] = C[k]
delete C[k]
j = T[k]
if (j == "array") {
j = split(V[k], A, ",")
k = B[k] ? B[k] SUBSEP : ""
X[k 0] = j
for (i=1; i<=j; i++) {
# push A[i] to C, (B[k],i) to B
C[A[i]] = C[0]
B[A[i]] = k i
C[0] = A[i]
}
} else if (j == "object") {
asplit(V[k], A, ":", ",")
k = B[k] ? B[k] SUBSEP : ""
for (i in A) {
# push A[i] to C, (B[k],V[i]) to B
C[A[i]] = C[0]
B[A[i]] = k V[i]
C[0] = A[i]
}
} else if (j == "number") {
X[B[k]] = V[k]
} else if (j == "true") {
X[B[k]] = 1
} else if (j == "false") {
X[B[k]] = 0
} else if (j == "string") {
X[B[k]] = V[k]
} else {
# null will satisfy ismissing()
X[B[k]]
}
k = C[0]
} while (k)
return 0
}
# repeat str n times, from http://awk.freeshell.org/RepeatAString
function rep(str, n, sep, remain, result) {
if (n < 2) {
remain = (n == 1)
result = sep = ""
} else {
remain = (n % 2 == 1)
result = rep(str, (n - remain) / 2, sep)
result = result sep result
}
return result (remain ? sep str :"")
}
# -- remove trailing and leading whitespace from string
function trim(str) {
if (match(str, /[^ \t\n].*[^ \t\n]/))
return substr(str, RSTART, RLENGTH)
else if (match(str, /[^ \t\n]/))
return substr(str, RSTART, 1)
else
return ""
}
# # faster than either of:
# function trim2(str) {
# sub(/^[ \t\n]+/, "", str)
# sub(/[ \t\n]+$/, "", str)
# return str
# }
# function trim3(str, from) {
# match(str, /^[ \t\n]*/)
# if ((from = RLENGTH) < length(str)) {
# match(str, /.*[^ \t\n]/)
# return substr(str, from+1, RLENGTH-from)
# } else return ""
# }
# -- remove leading whitespace from string
function trimleft(str) {
if (match(str, /^[ \t\n]+/))
return substr(str, RLENGTH+1)
else
return str
}
# # nearly the same performance as
# function trimleft2(str) {
# sub(/^[ \t\n]+/, "", str)
# return str
# }
# -- remove trailing whitespace from string
function trimright(str) {
if (match(str, /.*[^ \t\n]/))
return substr(str, RSTART, RLENGTH)
else
return ""
}
# # faster than either of:
# function trimright2(str, n) {
# n = length(str)
# while (n && match(substr(str, n), /^[ \t\n]/)) n--
# return substr(str, 1, n)
# }
# function trimright3(str) {
# sub(/[ \t\n]+$/, "", str)
# return str
# }
# TODO
## cut to max of 10 chars: `sprintf "%.10s", str`
# TODO
# function string:linewrap(width, indent)
# checktype(self, 1, "string")
# checkopt(width, 2, "positive!") or 72
# checkopt(indent, 3, "natural!") or 0
# local pos = 1
# -- rest needs to be converted from Lua
# return self:gsub("(%s+)()(%S+)()",
# function(sp, st, word, fi)
# if fi - pos > width then
# pos = st
# return "\n" .. rep(" ", indent) .. word
# end
# end)
# end
function has_prefix(str, pre, len2) {
len2 = length(pre)
return substr(str, 1, len2) == pre
}
function has_suffix(str, suf, len1, len2) {
len1 = length(str)
len2 = length(suf)
return len2 <= len1 && substr(str, len1 - len2 + 1) == suf
}
function detab(str, siz, n, r, s, start) {
siz = checkpos(siz, 8, "detab: second argument must be positive")
r = ""
n = start = 0
while (match(str, "\t")) {
start += RSTART
s = siz - (start - 1 + n) % siz
n += s - 1
r = r substr(str, 1, RSTART-1) rep(" ", s)
str = substr(str, RSTART+1)
}
return r str
}
function entab(str, siz) {
siz = checkpos(siz, 8, "detab: second argument must be positive")
str = detab(str, siz)
gsub(".{" siz "}", "&\1", str)
gsub(" +\1", "\t", str)
gsub("\1", "", str)
return str
}
## regexp utils #########
## WARNING: /re/ evaluates as boolean, so have to pass "re"s to user functions
# populate array from str="key key=value key=value"
# can optionally supply "re" for equals, space; if they're the same or equals is "", array will be setlike
function asplit(str, array, equals, space, aux, i, n) {
n = split(str, aux, (space == "") ? "[ \n]+" : space)
if (space && equals == space)
equals = ""
else if (ismissing(equals))
equals = "="
split("", array) # delete array
for (i=1; i<=n; i++) {
if (equals && match(aux[i], equals))
array[substr(aux[i], 1, RSTART-1)] = substr(aux[i], RSTART+RLENGTH)
else
array[aux[i]]
}
split("", aux) # does it help to delete the aux array?
return n
}
# like lua's find("%b()"), --> RSTART and sets RSTART and RLENGTH
function bmatch (s, opener, closer, len, i, n, c) {
len = length(s)
n = 0
for (i=1; i <= len; ++i) {
c = substr(s, i, 1)
if (c == opener) {
if (n == 0) RSTART = i
++n
} else if (c == closer) {
--n
if (n == 0) {
RLENGTH = i - RSTART + 1
return RSTART
}
}
}
return 0
}
# TODO
# tail not defined for negative nth (doesn't make sense, will always be none)
# negative nth with zero-length matches:
# - head returns one element too early, or sometimes wrongly?
# - matchstr diverges
function tail(str, re, nth, m, start, n) {
nth = checkpos(nth, 1, "tail: third argument must be positive")
re = check(re, SUBSEP)
if (nth == 1) {
if (match(str, re)) {
m = substr(str, RSTART + RLENGTH)
RSTART += RLENGTH
RLENGTH = length(m)
}
return m
} else {
RLENGTH = -1
start = 1
while (nth--) {
if (RLENGTH > 0) {
str = substr(str, RSTART + RLENGTH)
start += RLENGTH - 1
} else if (RLENGTH == 0) {
start++
if ((str = substr(str, RSTART + 1)) == "") {
nth--
break
}
}
n = (RLENGTH > 0)
if (!match(str, re)) break
if (n && !RLENGTH) {
assert(RSTART == 1 && nth >= 0)
if ((str = substr(str, 2)) == "" || !match(str, re)) break
start++
}
start += RSTART + n - 1
}
if (nth >= 0) {
RSTART = 0
RLENGTH = -1
} else {
m = substr(str, RSTART + RLENGTH)
RSTART = start + RLENGTH
RLENGTH = length(m)
}
return m
}
}
# this returns items between "re"; matchstr returns what matches "re"
# 3rd argument to specify which item (-1 for last)
# defaults to re=SUBSEP nth=1st none=""
function head(str, re, nth, none, start, m, n) {
if (nth != -1) {
nth = checkpos(nth, 1, "head: third argument must be positive")