-
Notifications
You must be signed in to change notification settings - Fork 2
/
nio.nim
2060 lines (1911 loc) · 92.8 KB
/
nio.nim
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
## This is a system for managing pre-parsed N)umeric|N)ative binary data. File
## names have extensions with metadata needed to interpret data as typed rows.
## Syntax is *".N"* then 1|more *{COUNT{,COUNT..}}[cCsSiIlLfdg]* specs where
## **Uppercase => Unsigned** & letter=1st letter of C type except g=lonG double.
## No count => 1. *'_'* is ignored. *idDayVal.N2sf* <~> packed *struct{ short
## id,day; float val; }* can work for simple time series. N/A = NaN | signed.low
## | unsigned.high. "" before ".N" gives *stdin* row formats when needed.
const fmtUse* = "\nSyntax: ({COUNT{,COUNT...}}[cCsSiIlLfdg])+\n"
when not declared(FileMode): import std/[syncio, objectdollar]; export syncio
include cligen/unsafeAddr # `formatInt` --|
import std/strutils as su, std/[math, os, times, strtabs], std/strformat{.all.},
std/[tables, sets], system/ansi_C, cligen/[osUt, strUt, fileUt, mslice]
from std/memfiles as mf import nil
type #*** BASIC TYPE SETUP #NOTE: gcc __float128 CPU-portable but slow
IOKind* = enum cIk = "int8" , CIk = "uint8" , sIk = "int16", SIk = "uint16",
iIk = "int32", IIk = "uint32", lIk = "int64", LIk = "uint64",
fIk = "float32", dIk = "float64", gIk = "float80"
IOCol* = object ## column metadata
iok*: IOKind ## number kind
cnts*: seq[int] ## repetition counts for each dimension
off*: int ## offset of start of column within a row
width*: int ## cached cnts.prod: total width of a subcol
IORow* = object ## row metadata
bytes*: int ## width of a whole row buffer in bytes
cols*: seq[IOCol] ## specs for each column
NFile* = object
mode: FileMode # fm(Read|Write|ReadWrite|ReadWriteExisting|Append)
m*: mf.MemFile ## for memory mapped IO
f*: File ## for C stdio streams (e.g. pipes)
rowFmt*: IORow # row format for IO
off,j,k: int # next byte offset into `mf`; next col,subcol in row
float80* {.importc: "long double".} = object ## C backend long double type
IONumber* = SomeNumber|float80 ## all IO numbers type class
Strings* = seq[string] ## alias for seq[string]
func isNil*(nf: NFile): bool = nf.m.mem.isNil and nf.f.isNil
func ok* (nf: NFile): bool = not nf.isNil
func width*(nf: NFile): int = nf.rowFmt.bytes
func low* (T: typedesc[float80]): float80 = float64.low # float80 support
func high*(T: typedesc[float80]): float80 = float64.high
converter toFloat80*(pdqr: SomeNumber): float80 = {.emit: "result = `pdqr`;".}
template defc(T) {.dirty.} = # need dirty to avoid genSym so emit can work
converter `to T`*(xyzw: float80): T = {.emit: "result = `xyzw`;".}
defc uint8; defc uint16; defc uint32; defc uint64; defc float32
defc int8; defc int16; defc int32; defc int64; defc float64
const ioCode*: array[IOKind, char] = [ 'c','C', 's','S', 'i','I', 'l','L',
'f','d','g' ] ## type codes
const ioSize*: array[IOKind, int] = [1,1, 2,2, 4,4, 8,8, 4,8,16] ## type sizes
const ioFloats* = {fIk, dIk, gIk} ## float kinds
let nim2nio* = {"int8" : 'c', "uint8" : 'C', "int16": 's', "uint16": 'S',
"int32" : 'i', "uint32" : 'I', "int64": 'l', "uint64": 'L',
"float32": 'f', "float64": 'd', "float80": 'g', "int": 'l',
"uint": 'L', "float": 'd', "char": 'C', "byte": 'C'}.toTable
func kindOf*(c: char): IOKind {.inline.} =
## return IOKind corresponding to character `c`
let ix = ioCode.find(c)
if ix < 0: raise newException(ValueError, "expecting [cCsSiIlLfdg]")
IOKind(ix)
func kindOf*(x: IONumber): IOKind =
## return IOKind from a static Nim type
when x is int8 : result = cIk
elif x is uint8 : result = CIk
elif x is int16 : result = sIk
elif x is uint16 : result = SIk
elif x is int32 : result = iIk
elif x is uint32 : result = IIk
elif x is int64 : result = lIk
elif x is uint64 : result = LIk
elif x is float32: result = fIk
elif x is float64: result = dIk
elif x is float80: result = gIk
func isSigned* (k: IOKind): bool {.inline.} = (k.int and 1) == 0
func isUnsigned*(k: IOKind): bool {.inline.} = (k.int and 1) == 1
func isFloat* (k: IOKind): bool {.inline.} = k.int > LIk.int
#*** MISSING VALUE CONVENTION; NA-AWARE LOW/HIGH MOSTLY FOR CLIPPING PARSED DATA
template defs(c, T) {.dirty.} = # NA,Low,High-Signed
const `c na`* =T.low;const`c low`* =int64(T.low+1);const`c high`* =T.high.int64
defs c, int8; defs s, int16; defs i, int32; defs l, int64
template defu(C, T) {.dirty.} = # NA,Low,High-Unsigned
const `C na`* =T.high; const `C low`* =0u64; const `C high`* = uint64(T.high-1)
defu C, uint8; defu S, uint16; defu I, uint32; defu L, uint64
template deff(f, T) {.dirty.} = # NA,Low,High-floating point
const `f na`* = T(NaN); const `f low`* = T.low; const `f high`* = T.high
deff f, float32; deff d, float64; deff g, float80
const lowS* = [clow , slow , ilow , llow ] # [k.int shr 1] post-isSigned
const highS* = [chigh, shigh, ihigh, lhigh]
const lowU* = [Clow , Slow , Ilow , Llow ] # [k.int shr 1] post-isUnsigned
const highU* = [Chigh, Shigh, Ihigh, Lhigh]
const lowF* = [float64.low , float64.low , float64.low ] # [k.int-8] post-isFlt
const highF* = [float64.high, float64.high, float64.high]
template withTyped_P_NA(k, adr, p, na, body) =
case k
of cIk: (let p = cast[ptr int8 ](adr); let na{.used.} = cna; body)
of CIk: (let p = cast[ptr uint8 ](adr); let na{.used.} = Cna; body)
of sIk: (let p = cast[ptr int16 ](adr); let na{.used.} = sna; body)
of SIk: (let p = cast[ptr uint16 ](adr); let na{.used.} = Sna; body)
of iIk: (let p = cast[ptr int32 ](adr); let na{.used.} = ina; body)
of IIk: (let p = cast[ptr uint32 ](adr); let na{.used.} = Ina; body)
of lIk: (let p = cast[ptr int64 ](adr); let na{.used.} = lna; body)
of LIk: (let p = cast[ptr uint64 ](adr); let na{.used.} = Lna; body)
of fIk: (let p = cast[ptr float32](adr); let na{.used.} = fna; body)
of dIk: (let p = cast[ptr float64](adr); let na{.used.} = dna; body)
of gIk: (let p = cast[ptr float80](adr); let na{.used.} = gna; body)
func isNA*(k: IOKind, adr: pointer): bool {.inline.} =
## Test the number IO kind at `adr` against its missing/NA value
withTyped_P_NA(k, adr, p, na):
when declared(isNaN): return if k > LIk: p[].float64.isNaN else: p[] == na
else: return if k > LIk: p[].float.classify == fcNan else: p[] == na
proc setNA*(k: IOKind, adr: pointer) {.inline.} =
## Set the number IO kind at `adr` to its missing/NA value
withTyped_P_NA(k, adr, p, na): p[] = na
proc convert*(dk, sk: IOKind, da, sa: pointer, naCvt=false) {.inline.} =
## From-any to-any convertor, optionally translating NAs
if naCvt and sk.isNA(sa):
dk.setNA(da)
return
case dk
of cIk: withTyped_P_NA(sk, sa, p, na, (cast[ptr int8 ](da)[] = p[].int8 ))
of CIk: withTyped_P_NA(sk, sa, p, na, (cast[ptr uint8 ](da)[] = p[].uint8 ))
of sIk: withTyped_P_NA(sk, sa, p, na, (cast[ptr int16 ](da)[] = p[].int16 ))
of SIk: withTyped_P_NA(sk, sa, p, na, (cast[ptr uint16 ](da)[] = p[].uint16 ))
of iIk: withTyped_P_NA(sk, sa, p, na, (cast[ptr int32 ](da)[] = p[].int32 ))
of IIk: withTyped_P_NA(sk, sa, p, na, (cast[ptr uint32 ](da)[] = p[].uint32 ))
of lIk: withTyped_P_NA(sk, sa, p, na, (cast[ptr int64 ](da)[] = p[].int64 ))
of LIk: withTyped_P_NA(sk, sa, p, na, (cast[ptr uint64 ](da)[] = p[].uint64 ))
of fIk: withTyped_P_NA(sk, sa, p, na, (cast[ptr float32](da)[] = p[].float32))
of dIk: withTyped_P_NA(sk, sa, p, na, (cast[ptr float64](da)[] = p[].float64))
of gIk: withTyped_P_NA(sk, sa, p, na, (cast[ptr float80](da)[] = p[] ))
template withTypedPtrPair(k, aP, bP, a, b, body) =
case k # `withTypedP(a): withTypedP(b): ..` may also work but is likely slow.
of cIk: (let a = cast[ptr int8 ](aP); let b = cast[ptr int8 ](bP); body)
of CIk: (let a = cast[ptr uint8 ](aP); let b = cast[ptr uint8 ](bP); body)
of sIk: (let a = cast[ptr int16 ](aP); let b = cast[ptr int16 ](bP); body)
of SIk: (let a = cast[ptr uint16 ](aP); let b = cast[ptr uint16 ](bP); body)
of iIk: (let a = cast[ptr int32 ](aP); let b = cast[ptr int32 ](bP); body)
of IIk: (let a = cast[ptr uint32 ](aP); let b = cast[ptr uint32 ](bP); body)
of lIk: (let a = cast[ptr int64 ](aP); let b = cast[ptr int64 ](bP); body)
of LIk: (let a = cast[ptr uint64 ](aP); let b = cast[ptr uint64 ](bP); body)
of fIk: (let a = cast[ptr float32](aP); let b = cast[ptr float32](bP); body)
of dIk: (let a = cast[ptr float64](aP); let b = cast[ptr float64](bP); body)
of gIk: discard #(let a=cast[ptr float80](aP); let b=cast[ptr float80](bP))
proc compare*(k: IOKind; aP, bP: pointer): int {.inline.} =
withTypedPtrPair(k, aP, bP, a, b): result = cmp(a[], b[])
#*** METADATA ACQUISITION SECTION
func initIORow*(fmt: string, endAt: var int): IORow =
## Parse NIO format string `fmt` into an `IORow`
if fmt.len < 1: raise newException(IOError, "empty row format")
var col = IOCol(cnts: @[0])
endAt = fmt.len - 1
for i, c in fmt:
case c:
of '_': discard # Allow optional spacing stuff out
of '0'..'9': col.cnts[^1] *= 10; col.cnts[^1] += ord(c) - ord('0')
#Explicit "0+" -> raise newException(IOError, "0 dim in type fmt: "&fmt&fmtUse)
of ',': col.cnts.add 0 # Make room for next dimension
of 'c', 'C', 's', 'S', 'i', 'I', 'l', 'L', 'f', 'd', 'g':
col.iok = fmt[i].kindOf # Type code terminates IO-column spec
for i in 0 ..< col.cnts.len: # All 0s -> 1s
if col.cnts[i] == 0: col.cnts[0] = 1
col.width = col.cnts.prod
col.off = result.bytes
result.bytes += col.width * ioSize[col.iok]
result.cols.add move(col) # only GC'd type in an IOCol is `cnts`..
col.cnts = @[0] #..which we re-init here anyway.
else:
if c in {'a'..'z', 'A'..'Z'}:
raise newException(IOError, &"bad code {c} in fmt: " & fmt & fmtUse)
else: # Allow things like '@'.* after a format suffix
endAt = i
return
if result.cols.len == 0:
raise newException(IOError, "no columns in fmt: " & fmt & fmtUse)
#XXX Add $pfx$kind${sep}foo meta file|dirs for kind="fmt","out".. Eg: .fmt/foo
proc dotContents(path: string): string =
for line in lines(path): result.add line.commentStrip
proc metaData(path: string): (string, IORow, string) =
var endAt: int
var (dir, name) = splitPath(path)
let ext = name.find(".N")
let fmt = if ext != -1: name[ext+2 .. ^1] else:
try: dotContents(dir / "." & name) except Ce:
raise newException(ValueError,
path & ": has no .N extension | dotfile")
result[1] = fmt.initIORow(endAt)
if ext != -1: name = name[0..<ext]
if endAt >= fmt.len - 1:
result[0] = if name.len == 0 or ext == 0: "" else: path
else:
result[0] = if name.len == 0 or ext==0: ""
elif ext != -1: path[0 ..< path.len-fmt.len+endAt] else: path
result[2] = fmt[endAt..^1]
#*** FILE IO SECTION
# fmRead RDONLY fmWrite CREAT|TRUNC
# fmReadWrite RW|CREAT|TRUNC fmAppend WRONLY|APPEND fmReadWriteExisting RW
proc nOpen*(path: string, mode=fmRead, newFileSize = -1, allowRemap=false,
mapFlags=cint(-1), rest: ptr string=nil): NFile =
let (path, fmt, rst) = metaData(path)
if fmt.bytes == 0: raise newException(ValueError, &"{path}: some ext problem")
result.rowFmt = fmt
result.mode = mode
if path.len == 0:
case mode
of fmRead: result.f = stdin
of fmAppend, fmWrite: result.f = stdout
else: raise newException(ValueError, "nameless unsupported by " & $mode)
else:
try: # XXX could get this down to 1 open syscall & map setup
if mode == fmAppend: raise newException(ValueError, "") # force stdIO
if not (mode == fmRead and path.fileExists and path.getFileSize == 0):
result.m = mf.open(path, mode, newFileSize=newFileSize,
allowRemap=allowRemap, mapFlags=mapFlags)
else:
result.m.mem = cast[pointer](1)
except Ce:
result.f = open(path, mode, max(8192, result.rowFmt.bytes))
if rest != nil: rest[] = rst
proc close*(nf: var NFile) = # mf.close requires `var`
if not nf.m.mem.isNil and nf.m.mem != cast[pointer](1): mf.close nf.m
if not nf.f.isNil: close nf.f
template arrayBase[I, T](a: typedesc[array[I, T]]): untyped = T
proc makeSuffix[T](result: var string, x: T, inArray=false) =
when T is tuple or T is object:
if inArray:
raise newException(ValueError, "array[N, obj|tup] is unsupported")
for e in x.fields: # could maybe do 2-passes to count and for
result.makeSuffix e #..the special case of 1 field just unbox.
elif T is array:
if inArray: result.add ','
result.add $(T.high - T.low + 1)
var x: arrayBase(T) # Use devious `arrayBase` to handle tensors
result.makeSuffix x, inArray=true
else:
try :result.add nim2nio[$type(T)]
except Ce:raise newException(ValueError,"missing type key: " &
(when (NimMajor,NimMinor) < (2,1): repr($type(T)) else: T.repr))
proc makeName[T](result: var string, key: string, x: T, sep=",") =
when T is tuple or T is object:
for k, e in x.fieldPairs:
result.makeName k, e, sep
else:
if result.len > 0: result.add sep
result.add key
proc typedPath*[T: tuple|object|array|IONumber](path="", sep=","): string =
## Automatic suffix|basename simply by not providing in the passed `path`;
## E.g. `"./.Nl"` (gen name), `"./foo"` (gen sfx), or `"./"` (gen both).
var (dir, name, ext) = splitPathName(path)
if ".N" notin ext:
ext.add ".N"
var x: T
ext.makeSuffix x
if name.len == 0:
var x: T
name.makeName "field", x, sep
if dir.len > 0: dir/(name & ext)
else: name & ext #XXX Would be nice to detect&report missing {.packed.} pragma
proc save*[T: tuple|object|array|IONumber](x: openArray[T], path="",
mode=fmWrite, sep: static[string]=",") =
## Blast `x` to a file with optionally generated path a la `typedPath`.
var f = open(typedPath[T](path, sep), mode)
let n = T.sizeof * x.len
if f.writeBuffer(x[0].unsafeAddr, n) < n:
raise newException(ValueError, "nio.save: short write")
f.close
proc read*(nf: var NFile, buf: var string, sz=0): bool =
## Read `sz` bytes (a whole row by default); Returns false on short read/EOF.
## `while nf.read(buf): ..`
let sz = if sz > 0: sz else: nf.rowFmt.bytes
buf.setLen sz
if not nf.f.isNil:
result = nf.f.readBuffer(buf[0].addr, sz) == sz
elif not nf.m.mem.isNil:
result = nf.off + sz <= nf.m.size
if result:
copyMem buf[0].addr, cast[pointer](cast[int](nf.m.mem) +% nf.off), sz
nf.off += sz
proc read*(nf: var NFile, kind: var IOKind, s: var string): bool =
## Fill `s` with the next number, returning false at EOF & IOKind in `kind`.
kind = nf.rowFmt.cols[nf.j].iok
if nf.read(s, ioSize[kind]):
result = true
nf.k.inc
if nf.k == nf.rowFmt.cols[nf.j].width:
nf.k = 0
nf.j.inc
if nf.j == nf.rowFmt.cols.len:
nf.j = 0
var sBuf = newString(16) # Nim includes an extra byte for '\0'
template defr(T) =
proc read*(nf: var NFile, da: var T, naCvt=false): bool =
var sk: IOKind
if nf.read(sk, sBuf):
convert da.kindOf, sk, da.addr, sBuf[0].addr, naCvt
result = true
defr uint8; defr uint16; defr uint32; defr uint64; defr float32
defr int8; defr int16; defr int32; defr int64; defr float64; defr float80
proc readCvt*(nf: var NFile, nums: var openArray[IONumber], naCvt=false): bool =
## Read next `nums.len` items, converting to buf type & maybe converting NAs.
result = true
for i in 0 ..< nums.len:
if not nf.read(nums[i], naCvt): return false
proc add*[T: IONumber](buffer: var seq[T], path: string, naCvt=false) =
## Append whole file `path` to type-homogeneous `seq[T]` maybe-converting NAs.
var nf = nOpen(path)
var num: array[1, T]
while true:
if not nf.readCvt(num, naCvt): break
buffer.add num[0]
nf.close
proc readCvt*[T: IONumber](path: string, naCvt=false): seq[T] =
## Read whole file `path` into type-homogeneous `seq[T]` maybe-converting NAs.
result.add path, naCvt
proc nurite*(f: File, kout: IOKind, buf: pointer) =
## Numeric unlocked write to stdio `f`.
discard f.uriteBuffer(buf, ioSize[kout])
#*** MEMORY MAPPED IO SECTION
func len*(nf: NFile): int {.inline.} =
when not defined(danger):
if nf.m.mem.isNil:
raise newException(ValueError, "non-mmapped file")
nf.m.size div nf.rowFmt.bytes
template BadIndex: untyped =
when declared(IndexDefect): IndexDefect else: IndexError
func `[]`*(nf: NFile, i: int): pointer {.inline.} =
## Returns pointer to the i-th row of a file opened with whatever row format
## and whatever *mode* (eg. fmReadWrite). Cast it to an appropriate Nim type:
## `let p = cast[ptr MyType](nfil[17]); echo p.myField; p.bar=2 #May SEGV!`.
when not defined(danger):
if nf.m.mem.isNil:
raise newException(ValueError, "non-mmapped file")
let m = nf.rowFmt.bytes
when not defined(danger):
if i >=% nf.m.size div m:
raise newException(BadIndex(), formatErrorIndexBound(i, nf.m.size div m))
cast[pointer](cast[int](nf.m.mem) +% i*m)
func `[]`*(nf: NFile; T: typedesc; i: int): T {.inline.} =
## Returns i-th row of a file opened with whatever row format *copied* into
## `result`. E.g.: `echo nfil[float, 17]`.
cast[ptr T](nf[i])[]
iterator items*(nf: NFile): string =
## iteration over untyped rows; (only MemFile IO right now, but generalizable)
var s = newString(nf.width)
for e in 0 ..< nf.len:
copyMem s[0].addr, nf[e], s.len
yield s
iterator pairs*(nf: NFile): (int, string) =
## indexed iteration over untyped rows, like an `openArray[T]`
var i = 0
for e in nf:
yield (i, e)
inc i
type
FileArray*[T] = object ## For *typed* external arrays of general records
nf*: NFile # whole NFile here allows .close & maybe MemFile.resize niceness
IOTensor* = object ## Specialization for single-IOKind-base-types
m*: mf.MemFile ## backing file
t*: IOKind ## single IOKind, e.g. fIk for .N128,128f
fmt*: IORow ## parsed row format
d*: seq[int] ## dimensions
func initFileArray*[T](nf: NFile): FileArray[T] =
## An init from NFile in case you want to nf.close before program exit.
if T.sizeof != nf.rowFmt.bytes:
raise newException(ValueError, "path rowFmt.bytes != FileArray T.sizeof")
result.nf = nf
proc init*[T](fa: var FileArray[T], path: string, mode=fmRead, newLen = -1,
allowRemap=false, mapFlags=cint(-1), rest: ptr string=nil) =
## A var init from nOpen params for, e.g. init of FileArray fields in objects.
## `newLen` is in units of `T` row sizes.
let sz = if newLen == -1: -1 else: newLen * T.sizeof
fa = initFileArray[T](nOpen(path, mode, sz, allowRemap, mapFlags, rest))
proc initFileArray*[T](path: string, mode=fmRead, newLen = -1, allowRemap=false,
mapFlags=cint(-1), rest: ptr string=nil): FileArray[T] =
## The most likely entry point. Note that `result.close` is both allowed and
## encouraged if you finish with data prior to program exit.
result.init path, mode, newLen, allowRemap, mapFlags, rest
proc load*[T](path: string, mode=fmRead, newLen = -1, allowRemap=false,
mapFlags=cint(-1), rest: ptr string=nil): FileArray[T] =
## Short alias for `initFileArray`.
result.init path, mode, newLen, allowRemap, mapFlags, rest
proc close*[T](fa: var FileArray[T]) = close fa.nf
template toOA*[T](fa: FileArray[T]): untyped =
## Allow RO slice access like `myFileArray.toOA[^9..^1]` for a "tail".
toOpenArray[T](cast[ptr UncheckedArray[T]](fa.nf.m.mem), 0, fa.len - 1)
template toOpenArray*[T](fa: FileArray[T]): untyped =
## Some people enjoy longer idents
toOpenArray[T](cast[ptr UncheckedArray[T]](fa.nf.m.mem), 0, fa.len - 1)
iterator items*[T](fa: FileArray[T]): T =
for b in countup(0, fa.nf.m.size - T.sizeof, T.sizeof):
yield cast[ptr T](cast[int](fa.nf.m.mem) +% b)[]
iterator pairs*[T](fa: FileArray[T]): (int, T) =
let m = T.sizeof
for i in countup(0, fa.nf.m.size div m - 1):
yield (i, cast[ptr T](cast[int](fa.nf.m.mem) +% i * m)[])
func len*[T](fa: FileArray[T]): int {.inline.} =
## Returns length of `fa` in units of T.sizeof records. Since this does a
## divmod, you should save an answer rather than re-calling if appropriate.
when not defined(danger):
if fa.nf.m.mem.isNil:
raise newException(ValueError, "uninitialized FileArray[T]")
when not defined(danger):
if fa.nf.m.size mod T.sizeof != 0:
raise newException(ValueError,"FileArray[T] size non-multiple of T.sizeof")
fa.nf.m.size div T.sizeof
func `[]`*[T](fa: FileArray[T], i: int): T {.inline.} =
## Returns i-th row of `r` copied into `result`.
when not defined(danger):
if fa.nf.m.mem.isNil:
raise newException(ValueError, "uninitialized FileArray[T]")
let m = T.sizeof
when not defined(danger):
if i * m >=% fa.nf.m.size:
raise newException(BadIndex(),formatErrorIndexBound(i,fa.nf.m.size div m))
cast[ptr T](cast[int](fa.nf.m.mem) +% i * m)[]
func `[]`*[T](fa: var FileArray[T], i: int): var T {.inline.} =
## Returns i-th row of `r` copied into `result`.
when not defined(danger):
if fa.nf.m.mem.isNil:
raise newException(ValueError, "uninitialized FileArray[T]")
let m = T.sizeof
when not defined(danger):
if i * m >=% fa.nf.m.size:
raise newException(BadIndex(),formatErrorIndexBound(i,fa.nf.m.size div m))
cast[ptr T](cast[int](fa.nf.m.mem) +% i * m)[]
func `[]=`*[T](fa: FileArray[T], i: int, val: T) {.inline.} =
## Assign `val` to `i`-th row of `fa`.
when not defined(danger):
if fa.nf.m.mem.isNil:
raise newException(ValueError, "uninitialized FileArray[T]")
let m = T.sizeof
when not defined(danger):
if i * m >=% fa.nf.m.size:
raise newException(BadIndex(),formatErrorIndexBound(i,fa.nf.m.size div m))
cast[ptr T](cast[int](fa.nf.m.mem) +% i * m)[] = val
proc `$`*[M](x: array[M, char]): string =
## Sometimes `x=initFileArray[array[z,char]]("x.NzC"); echo x[i]` is nice.
let m = M.high + 1
result.setLen m + 1 # space for NUL-term for debug builds
copyMem result[0].addr, x[0].unsafeAddr, m
result.setLen result[0].addr.cstring.c_strlen
proc mOpen*(tsr: var IOTensor, path: string, mode=fmRead, mappedSize = -1,
offset=0, newFileSize = -1, allowRemap=false, mapFlags=cint(-1)) =
let (path, fmt, _) = metaData(path) #XXX match any filled in IOTensor fields
tsr.fmt = fmt #.. add DATA_PATH search; also for nOpen
tsr.t = fmt.cols[0].iok #.. add indexing/slicing ops or maybe..
if fmt.cols.len != 1: #.. just numnim/neo/Arraymancer compat.
raise newException(ValueError, &"{path}: impure tensors unsupported")
tsr.m = mf.open(path)
if tsr.m.size mod fmt.bytes != 0:
mf.close tsr.m
raise newException(ValueError, &"{path}: file size indivisible by row size")
tsr.d = @[ tsr.m.size div fmt.bytes ] & fmt.cols[0].cnts
proc mOpen*(path: string, mode=fmRead, mappedSize = -1, offset=0,
newFileSize = -1, allowRemap=false, mapFlags=cint(-1)): IOTensor =
result.mOpen path, mode, mappedSize, offset, newFileSize, allowRemap, mapFlags
proc close*(tsr: var IOTensor) = mf.close(tsr.m)
type #*** INDIRECTION SUBSYSTEM FOR FIXED OR VARIABLE-LENGTH STRING DATA
Ix* = uint32 ## max file size for repos is 4 GiB/GiEntry
RepoKind* = enum rkFixWid, ## Fixed Width buffers w/key truncation/0-pad
rkDelim, ## A popular format: Disallowed Delimiter Char
rkLenPfx ## An 8-bit clean format: Length-prefixed
RepoMode* = enum rmFast, ## Provide ptr->string only; not string->ptr
rmIndex, ## Non-updating bi-directional ptr<->string
rmUpdate ## Updating bi-directional ptr<->string
Repo* = ref object ## Mostly opaque string Repository type
case kind: RepoKind
of rkFixWid: fmt : IORow
of rkDelim : dlm : char
of rkLenPfx: lenK: IOKind
path: string
m: mf.MemFile
na: string # *output* N/A; input is always ""
mode: RepoMode
kout: IOKind # output pointer type for index|updating mode
f: File # updating mode only fields
off: Ix # running file size (what to set .[DL] ptrs to)
tab*: Table[string, Ix] ## index lookup table
const IxIk = IIk
const IxNA = Ina
iterator keysAtOpen*(r: Repo): (string, Ix) =
case r.kind
of rkFixWid:
var k = newString(r.fmt.bytes)
for i in countup(0, r.m.size - 1, k.len):
copyMem k[0].addr, cast[pointer](cast[int](r.m.mem) +% i), k.len
yield (k[0..^1], Ix(i div r.fmt.bytes)) #COPY
of rkDelim:
for ms in mf.memSlices(r.m, r.dlm):
yield (mf.`$`(ms), Ix(cast[int](ms.data) -% cast[int](r.m.mem)))
of rkLenPfx:
var k: string
var off: uint64; var len: int64
while off.int < r.m.size - 1:
let off0 = off.Ix
convert lIk, r.lenK, len.addr, cast[pointer](cast[uint64](r.m.mem) + off)
len = len.abs
off.inc ioSize[r.lenK]
k.setLen len
copyMem k[0].addr, cast[pointer](cast[uint64](r.m.mem) + off), len
off += len.uint64
yield (k[0..^1], off0) #COPY
var openRepos*: Table[string, Repo]
proc rOpen*(path: string, mode=rmFast, kout=IxIk, na=""): Repo =
## REPOs can be byte-delimited *.Dn* | length-prefixed *.Li* with byte-offset
## pointer values or fixed width like *.N16c* with row index vals. There are
## 3 open modes: mmap & go read-only, tab-building indexing, and full updates.
if path.len == 0: return
if path in openRepos: return openRepos[path]
let cols = su.split(path, maxSplit=1)
let path = cols[0]
new result
result.path = path
if mode != rmFast:
if cols.len > 1: # Schema-visible NOUP, NO_UP..
result.mode = (if "UP" in cols[1]: rmIndex else: rmUpdate)
else: # $NO_UP can switch off even w/o schema
result.mode = if getEnv("NO_UP", "xYz") == "xYz": rmUpdate else: rmIndex
var info: FileInfo
try : info = getFileInfo(path)
except Ce: discard
let openMode = if result.mode == rmUpdate and info.id.device == 0: fmWrite
else: fmAppend
if info.size > type(result.off).high.int:
raise newException(ValueError, &"{path}: too big for index pointer sizes")
result.off = info.size.Ix
let m = if openMode==fmWrite: mf.MemFile(mem: nil,size: 0) else:
try : mf.open(path)
except Ce: mf.MemFile(mem: nil, size: 0)
let (_, _, ext) = splitPathName(path)
if ext.len == 0 or ext == ".Dn":
result = Repo(kind:rkDelim, dlm: '\n', m: m, na: na, mode: mode, kout: kout)
elif ext.startsWith(".D"):
try:
let dlm = ext[2..^1]
result = Repo(kind:rkDelim, m: m, na: na, mode: mode, kout: kout,
dlm: (if dlm == "n": '\n' else: chr(parseInt(dlm))))
except Ce:
raise newException(ValueError, &"{path}: expecting .Dn or .D<INT>")
elif ext.startsWith(".L") and ext.len == 3:
result = Repo(kind:rkLenPfx, lenK: kindOf(ext[2]), m: m, na: na,
mode: mode, kout: kout)
elif ext.startsWith(".N"):
let (path, fmt, rst) = metaData(cols[0])
if rst.len > 0:
raise newException(ValueError, &"{path}: inappropriate for a repo")
if not (fmt.cols.len == 1 and fmt.cols[0].iok in {cIk, CIk}):
raise newException(ValueError, &"{path}: expecting .N<size>[cC]")
result = Repo(kind:rkFixWid, fmt: fmt, m: m, na: na, mode: mode, kout: kout)
else:
raise newException(ValueError, &"{path}: unknown repo ext {ext}")
if result.mode == rmUpdate and
(result.f = mkdirOpen(path, openMode); result.f == nil):
result.mode = rmIndex; erru &"{path}: cannot append; indexing anyway\n"
for k, i in result.keysAtOpen: result.tab[k] = i
openRepos[path] = result
proc close*(at: var Repo) =
if at.m.mem != nil: mf.close(at.m); at.m.mem = nil
if at.path in openRepos: openRepos.del at.path
proc `[]`*(at: Repo, i: Ix): string =
if i == IxNA: return at.na
var p: pointer
var n: Ix
case at.kind
of rkFixWid: # Here `i` is row/record number
n = at.fmt.bytes.Ix
p = cast[pointer](cast[uint](at.m.mem) + i * n)
of rkDelim: # Here `i` is a byte offset to start of row
p = cast[pointer](cast[uint](at.m.mem) + i)
let e = c_memchr(p, at.dlm.cint, csize_t(at.m.size.Ix - i))
if e == nil:
raise newException(ValueError, &"no terminating delimiter for {i.int}")
n = Ix(cast[uint](e) - cast[uint](p))
of rkLenPfx: # Here `i` is a byte offset to length field
let pL = cast[pointer](cast[uint](at.m.mem) + i)
convert IxIk, at.lenK, n.addr, pL
p = cast[pointer](cast[uint](at.m.mem) + i + ioSize[at.lenK].Ix)
result.setLen n
copyMem result[0].addr, p, n
proc padClip(k: string, n: int): string {.inline.} = # FixWid key adjust
let n0 = k.len
if n0 >= n: return k[0..<n] # too long: clip key
elif n0 < n: # too short: pad key
result.setLen n
result[0..<n0] = k # copyMem?
zeroMem result[n0].addr, n - n0
proc clip(r: var Repo; k: string, lenK: IOKind, lno: int): string {.inline.} =
if lenK.isSigned:
if (let lim = highS[lenK.int shr 1]; k.len.int64 > lim):
erru &"inputLine{lno}: truncating field of len {k.len}\n"
result = k[0..<lim]
else: result = k
elif lenK.isUnsigned: # No NA for lens => +1 @end, does full addr space,eg 255
if (let lim = highU[lenK.int shr 1]; k.len.uint64 > lim):
erru &"inputLine{lno}: truncating field of len {k.len}\n"
result = k[0..<lim]
else: result = k
else: raise newException(ValueError, "Length Prefix cannot be a float")
proc index*(r: var Repo, ixOut: pointer, k: string, lno: int) =
template retNA = # helper template to return NA
setNA(r.kout, ixOut); return
if ixOut == nil: r.close; return
if r.mode == rmFast:
raise newException(ValueError, "rmFast mode does not do index(string)")
if k.len == 0: retNA # NA key -> NA index
var i: Ix
let k = if r.kind == rkFixWid: padClip(k, r.fmt.bytes)
elif r.kind == rkLenPfx: r.clip(k, r.lenK, lno) else: k
try: i = r.tab[k] # get extant index
except Ce: # novel key
if r.mode == rmIndex: retNA # missing && !up -> NA index
case r.kind # update in-memory Table & repo
of rkFixWid: i = r.tab.len.Ix; r.tab[k] = i; r.f.urite k; r.off = i + 1
of rkDelim : i = r.off; r.tab[k]=i; r.f.urite k, r.dlm; r.off += Ix(k.len+1)
of rkLenPfx: # convert length to output type, write, then write key
i = r.off; r.tab[k] = i
r.off += Ix(k.len + ioSize[r.lenK])
var n = k.len; var nbuf: array[8, char] # IO buffers for length
convert r.lenK, lIk, nbuf[0].addr, n.addr
r.f.nurite r.lenK, nbuf[0].addr
r.f.urite k
if r.off < i: erru &"pointer overflow for repo {r.path}\n"
convert r.kout, IxIk, ixOut, i.addr # convert pointer type
type #*** FORMAT NUMBERS TO ASCII PRIMARILY FOR DEBUGGING/SLOPPY EXPORT
Formatter* = object
rowFmt: IORow
specs: seq[StandardFormatSpecifier]
radix: seq[int]
ffmode: seq[FloatFormatMode]
ats: seq[Repo]
na: string
proc radix(spec: StandardFormatSpecifier): int =
case spec.typ # strformat should export this proc
of 'x', 'X': 16
of 'd', '\0': 10
of 'b': 2
of 'o': 8
else: 0
proc ffmode(spec: StandardFormatSpecifier): FloatFormatMode =
case spec.typ # strformat should export this proc
of 'e', 'E': ffScientific
of 'f', 'F': ffDecimal
else: ffDefault
proc parseAugmentedSpecifier(s: string, start: int, at: var Repo,
spec: var StandardFormatSpecifier) =
# Parse [@[path]] & '%' & standardFormatSpecifier
if (let pct = s.find('%', start); pct >= 0 and pct + 1 < s.len):
if s.len > start and s[start] == '@' and pct > 1:
at = rOpen(s[1..<pct])
spec = parseStandardFormatSpecifier(s, pct + 1, ignoreUnknownSuffix=true)
else: raise newException(ValueError, &"{s}: missing '%' or type code")
proc initFormatter*(rowFmt: IORow, atShr: Repo = nil, fmTy: Strings = @[],
fmt="", na=""): Formatter =
result.rowFmt = rowFmt
result.ats.add atShr # [0] is the shared one (or nil if none)
result.na = na
var ft: array[IOKind, string] = ["d", "c", "d", "d", "d", "d", "d", "d",
".07g", ".016g", ".019g"]
for cf in fmTy:
if cf.len < 3: raise newException(ValueError, &"\"{cf}\" too short")
if cf[1]!='%': raise newException(ValueError, "no '%' between code & spec")
if cf[0] notin ioCode:
raise newException(ValueError, &"'{cf[0]}' not [cCsSiIlLfdg]")
ft[cf[0].kindOf] = cf[2..^1]
var fc: array[IOKind, StandardFormatSpecifier]
for k in IOKind: fc[k] = parseStandardFormatSpecifier(ft[k], 0, true)
for c in rowFmt.cols:
let spec = fc[c.iok]
result.specs .add spec
result.radix .add spec.radix
result.ffmode.add spec.ffmode
result.ats .add atShr
var start, j: int
while start < fmt.len:
if j >= rowFmt.cols.len:
raise newException(ValueError, &"\"{fmt}\" too many output formats")
parseAugmentedSpecifier fmt, start, result.ats[j+1], result.specs[j]
result.radix[j] = result.specs[j].radix
result.ffmode[j] = result.specs[j].ffmode
start = result.specs[j].endPosition
j.inc
proc formatFloat(result: var string, value: float64, ffmode: FloatFormatMode,
spec: StandardFormatSpecifier) =
var f = formatBiggestFloat(value, ffmode, spec.precision)
var sign = false # Fix `strformat.formatBiggestFloat` += `sign`,
if value >= 0.0: #.. `padWithZero`, `minimumWidth`, `align`, & uppercase
if spec.sign!='-':
sign = true
if value == 0.0:
if 1.0 / value == Inf: f.insert($spec.sign, 0)
else: f.insert($spec.sign, 0)
else: sign = true
if spec.padWithZero:
var signStr = ""
if sign: signStr = $f[0]; f = f[1..^1]
let toFill = spec.minimumWidth - f.len - ord(sign)
if toFill > 0: f = repeat('0', toFill) & f
if sign: f = signStr & f
let align = if spec.align == '\0': '>' else: spec.align
let res = alignString(f, spec.minimumWidth, align, spec.fill)
result.add if spec.typ in {'A'..'Z'}: toUpperAscii(res) else: res
proc formatFloat*(result: var string, value: float64, fmt=".04g") =
let spec = parseStandardFormatSpecifier(fmt, 0, true)
formatFloat(result, value, spec.ffmode, spec)
proc formatFloat*(value: float64, fmt: string): string = # E.g. ".4g"
formatFloat(result, value, fmt)
import std/unicode
proc fmt*(result: var string; fmtr: Formatter; j: int; k: IOKind, s: string,
naCvt=false) =
let spec = fmtr.specs[j]
let radix = fmtr.radix[j]
if k in ioFloats: # SOME FLOAT TYPE
var value: float64 #XXX port my C float80 to (prs|fmt)BiggestFloat
convert dIk, k, value.addr, s[0].unsafeAddr, naCvt
result.formatFloat(value, fmtr.ffmode[j], spec)
else:
var value: uint64 # SOME INTEGRAL TYPE, INCLUDING PTR
if k.isNA(s[0].unsafeAddr): result.add fmtr.na; return
convert LIk, k, value.addr, s[0].unsafeAddr, naCvt
let at = if fmtr.ats[j + 1].isNil: fmtr.ats[0] else: fmtr.ats[j + 1]
if spec.typ == 's' and at != nil: # STRING
var value = at[value.Ix] # Q: %r & lift for general indirect?
if spec.precision != -1 and spec.precision < runeLen(value):
setLen(value, runeOffset(value, spec.precision))
result.add alignString(value, spec.minimumWidth, spec.align, spec.fill)
elif k.isSigned:
let value = cast[int64](value)
result.add formatInt(value, (if radix == 0: 16 else: radix), spec)
else:
result.add formatInt(value, (if radix == 0: 16 else: radix), spec)
proc close*(fmtr: var Formatter) =
for i in 0 ..< fmtr.ats.len: fmtr.ats[i].close
proc stat*(format="", nios: Strings): int =
## print numeric file metadata {like stat(1)}.
let f = if format.len > 0: format
else: "name: %n\nrows: %r\nbytes/row: %z\nlastWidth: %w\nlastType: %b\n"
for path in nios:
let (path, fmt, _) = metaData(path)
let sz = getFileSize(if path.len > 0: path else: "/dev/stdin")
var inPct = false
for c in f:
if inPct:
case c
of '%': outu '%'
of 'n': outu path
of 'r': outu sz div fmt.bytes
of 'z': outu fmt.bytes
of 'w': outu $fmt.cols[^1].width
of 'b': outu $fmt.cols[^1].iok
else: erru &"bad meta specifier '{c}'\n"; return 1
inPct = false
else:
if c == '%': inPct = true
else: outu c
proc print*(sep="\t", at="", t='x', fmTy: Strings = @[], na="", paths: Strings)=
## print native numeric files; pasted side-by-side over rows.
##
## *.N* suffix + printf-esque extra suffix/`fmTy` may imply number conversion.
## Extra suffix fmt has no type code prefix (or space). Eg. **ixVal.Nif%x%g**.
## Specify location & formats for `stdin` by an empty path, e.g. `.Nsf%o%.2f`.
## Nim specifiers (see below) are pre-% augmented by *@* for `@REPO%s` to aid
## string renders. Augmented Nim format specs are like:
## [[fill]align][sign][#][0][minWidth][.prec][type]
## [[fill]<^>][+- ][#][0][minWidth][.prec][cbdoxXeEfFgG]
# C %[flags][minWidth][.prec][modifier][type]
# %[' +-#0]*[minWidth][.prec]{hh|h|l|ll|L|z|t}[csdiuoxXeEfFgGaA]
var atShr: Repo
try : atShr = rOpen(at, na=na) # `nil` if at == ""
except Ce: erru &"Cannot open \"{at}\"\n"; quit(1)
if t != 'x' and at.len > 0 and paths.len == 0:
for (key, ix) in atShr.keysAtOpen: outu key, t
return
elif paths.len<1: erru "nio print needs >= 1 path; --help for usage\n"; return
var ofmt: string
var nfs: seq[NFile]
var fms: seq[Formatter]
for path in paths:
nfs.add nOpen(path, rest=ofmt.addr)
fms.add initFormatter(nfs[^1].rowFmt, atShr, fmTy, ofmt, na)
var orow: string
var sk: IOKind
var item = newString(16) # Nim includes an extra byte for '\0'
while true:
orow.setLen 0
var i0, j0: int
var chFmt: bool
for i in 0 ..< nfs.len:
for j in 0 ..< nfs[i].rowFmt.cols.len:
for k in 0 ..< nfs[i].rowFmt.cols[j].width:
if not nfs[i].read(sk, item): # stop @first short file
return
if not(i==0 and j==0 and k==0): # skip 1st-1st-1st; sep leads data
if not chFmt or i != i0 or j != j0: orow.add sep
chFmt = fms[i].specs[j].typ == 'c' and sk in {cIk, CIk}
if chFmt:
orow.add (if item[0] == '\0': ' ' else: item[0])
else: # add formatted field
orow.fmt fms[i], j, sk, item, naCvt=true
j0 = j
i0 = i
orow.add '\n'
outu orow # cligen/osUt.urite?
#*** VARIOUS CL REFORMATTING/SELECTION TOOLS: rip, zip, cut, tails
proc rip*(input: string, names: Strings): int =
## rip apart all columns of `input` into files with given `names`.
##
## Output numeric formats are either the same as corresponding columns of
## input or the type specified in .N/.foo metaData.
var inp = nOpen(input)
if inp.rowFmt.cols.len != names.len:
erru &"too few/many names for input: \"{input}\"\n"; inp.close; return 1
var outs = newSeq[NFile](inp.rowFmt.cols.len)
var offs, ns: seq[int]
var off = 0
for j in 0 ..< outs.len: # open all outputs
try : outs[j] = nOpen(names[j], fmWrite)
except Ce:
if ".N" in names[j]: raise
var sfx = ".N"
for k, c in inp.rowFmt.cols[j].cnts:
if c > 1:
sfx.add $c
if k < inp.rowFmt.cols[j].cnts.len - 1: sfx.add ','
sfx.add ioCode[inp.rowFmt.cols[j].iok]
outs[j] = nOpen(names[j] & sfx, fmWrite)
offs.add off
let n = outs[j].rowFmt.cols[0].width * ioSize[outs[j].rowFmt.cols[0].iok]
ns.add n
off.inc n
var buf: string
while inp.read(buf):
for j in 0 ..< outs.len:
if outs[j].f.uriteBuffer(buf[offs[j]].addr, ns[j]) < ns[j]: return 2
for j in 0 ..< outs.len: outs[j].close
proc zip*(paths: Strings): int =
## opposite of `rip`; like `paste` but for rows from native files in `paths`.
if paths.len < 2: erru "`zip` needs 2 or more NIO paths\n"; return 1
var fs = newSeq[NFile](paths.len) #XXX smarten Re: merging dot files.
for i, p in paths: fs[i] = nOpen(p)
var buf: string
block outer:
while true:
for i in 0 ..< fs.len:
if not fs[i].read(buf): # stop @first short file
break outer
outu buf
for i in 0 ..< fs.len: fs[i].close
proc widen*(io: Strings, pad='\0'): int =
## Widen (/narrow) numeric types or subColumns.
##
## Egs: `nio w .N7C .N8C` right-pads rows with a 0-byte (shorter truncs)
## `nio w .N9f .N9d` widens float matrix on stdin to double on stdout
## `nio w .N3C5C .NLL | nio p .NLL` -> (24-bit decimal, 40-bit decimal)
proc c_fputc(c: char, f: File): cint {.importc: "fputc", header: "stdio.h".}
var i = nOpen(io[0])
var o = nOpen(io[1], fmAppend) # fmAppend here ensures nurite works
template bye = i.close; o.close; return 1
if i.rowFmt.cols.len != o.rowFmt.cols.len: #XXX COULD become more strict
erru "`width`: need out & in to have same number of major columns\n"; bye()
var row, obuf: string
while i.read row:
for j, ic in i.rowFmt.cols:
let oc = o.rowFmt.cols[j]
if ioSize[ic.iok] == 1 and ioSize[oc.iok] == 1: # Both iok 1-byte
if oc.width <= ic.width: # Truncating copy
discard o.f.uriteBuffer(row[ic.off].addr, oc.width)
else: # Pad
discard o.f.uriteBuffer(row[ic.off].addr, ic.width)
for k in 0 ..< oc.width - ic.width: discard c_fputc(pad, o.f)
elif ic.width == oc.width: # Convert elements 1-by-1
obuf.setLen ioSize[oc.iok]
for k in 0 ..< ic.width: # Same iok & width => just cp 1-by-1
convert oc.iok,ic.iok,obuf[0].addr,row[ic.off + k*ioSize[ic.iok]].addr
discard o.f.uriteBuffer(obuf[0].addr, ioSize[oc.iok])
elif ioSize[ic.iok] == 1 and oc.width == 1: #XXX COULD collapse fastest..
var u: uint64 # ..varying dim, not all.
for k in 0 ..< ic.width: u = u or (row[ic.off + k].uint64 shl (8*k))
obuf.setLen ioSize[oc.iok] #XXX ^- Handle big-endianness someday
convert oc.iok, LIk, obuf[0].addr, u.addr
discard o.f.uriteBuffer(obuf[0].addr, obuf.len)
proc cvtSlice(ab: tuple[a, b: int]; bound: int): (int, int) =
var a = ab.a
var b = ab.b
if a < 0: a.inc bound
if b < 0: b.inc bound
if b < a: b = a + 1
(a, min(b, bound))
iterator elts(slices: Strings, bound: int): (int, int) =
for s in slices: yield cvtSlice(parseSlice(s), bound)
proc cut*(drop: Strings = @[], pass: Strings = @[], path: Strings): int =
## pass|drop selected column slices {generalized cut(1)} to stdout.
##
## Slice specification is `[a][:[b]]`, like Python (incl negatives). Can
## either pass|drop but not both at once. Multiple slices are "set unioned".
if path.len != 1 or (drop.len > 0 and pass.len > 0):
erru "`cut` needs exactly 1 input and not both drop&pass\n"; return 1
let cPass = int(not (drop.len > 0))
var inp = nOpen(path[0])
var colSet: HashSet[int] #XXX tensors need a flat view
for (a, b) in (if drop.len > 0: drop else: pass).elts(inp.rowFmt.cols.len):
for j in a..<b: colSet.incl j
var buf: string
var pass, offs, lens: seq[int]
for j, c in inp.rowFmt.cols:
if (cPass xor (j in colSet).int) == 0: pass.add j
offs.add c.off
lens.add c.width * ioSize[c.iok]
while inp.read(buf):
for j in pass: # Passing column/field
if stdout.uriteBuffer(buf[offs[j]].addr, lens[j]) < lens[j]: return 1
proc tailsOuter(nf: NFile, head=0, tail=0, repeat=false): int =
let m = nf.rowFmt.bytes