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
|
use std
pkg bio =
type mode = int
const Rd : mode = 1
const Wr : mode = 2
const Rw : mode = 1 | 2
type file = struct
/* backing fd */
fd : std.fd
mode : mode
lasterr : std.errno
/* read buffer */
rbuf : byte[:]
rstart : std.size
rend : std.size
/* write buffer */
wbuf : byte[:]
wend : std.size
;;
type status(@a) = union
`Eof
`Ok @a
`Err ioerr
;;
type ioerr = union
`Ebadfile
`Ebadbuf
`Ebadfd
`Eioerr
;;
/* creation */
const mkfile : (fd : std.fd, mode : mode -> file#)
const open : (path : byte[:], mode : mode -> std.result(file#, byte[:]))
const dial : (srv : byte[:], mode : mode -> std.result(file#, byte[:]))
const create : (path : byte[:], mode : mode, perm : int -> std.result(file#, byte[:]))
const close : (f : file# -> bool)
const free : (f : file# -> void)
/* basic i/o. Returns sub-buffer when applicable. */
const write : (f : file#, src : byte[:] -> status(std.size))
const read : (f : file#, dst : byte[:] -> status(byte[:]))
const flush : (f : file# -> bool)
/* seeking */
const seek : (f : file#, std.off -> std.off)
/* single unit operations */
const putb : (f : file#, b : byte -> status(std.size))
const putc : (f : file#, c : char -> status(std.size))
const getb : (f : file# -> status(byte))
const getc : (f : file# -> status(char))
/* peeking */
const peekb : (f : file# -> status(byte))
const peekc : (f : file# -> status(char))
/* delimited read; returns freshly allocated buffer. */
const readln : (f : file# -> status(byte[:]))
const readto : (f : file#, delim : byte[:] -> status(byte[:]))
const skipto : (f : file#, delim : byte[:] -> bool)
const skipspace : (f : file# -> bool)
/* formatted i/o */
const put : (f : file#, fmt : byte[:], args : ... -> status(std.size))
/* pkg funcs */
pkglocal const ensureread : (f : file#, n : std.size -> status(std.size))
pkglocal const ensurewrite : (f : file#, n : std.size -> status(std.size))
;;
const Bufsz = 16*std.KiB
const Small = 512
/* Creates a file from an fd, opened in the given mode. */
const mkfile = {fd, mode
var f
f = std.alloc()
f.fd = fd
f.mode = mode
f.lasterr = 0
if mode & Rd != 0
f.rbuf = std.slalloc(Bufsz)
f.rstart = 0
f.rend = 0
;;
if mode & Wr != 0
f.wbuf = std.slalloc(Bufsz)
f.wend = 0
;;
-> f
}
/* Opens a file with mode provided. */
const open = {path, mode
-> sysopen(path, mode, sysmode(mode), 0o777)
}
/*
Creates a file for the provided path, with opened in
the requested mode, with the requested permissions
*/
const create = {path, mode, perm
-> sysopen(path, mode, sysmode(mode) | std.Ocreat | std.Otrunc, perm)
}
/* dial the server, and open a file using the returned fd */
const dial = {srv, mode
match std.dial(srv)
| `std.Ok sock: -> `std.Ok mkfile(sock, mode)
| `std.Fail m: -> `std.Fail m
;;
}
/* map from the bio modes to the unix open modes */
const sysmode = {mode
match mode
| Rd: -> std.Ordonly
| Wr: -> std.Owronly
| Rw: -> std.Ordwr
| _: std.fatal("bio: bad file mode")
;;
-> 0
}
/* open the file, and return it */
const sysopen = {path, mode, openmode, perm
var fd
fd = std.openmode(path, openmode, perm castto(int64))
if fd < 0
-> `std.Fail "could not open fd"
else
-> `std.Ok mkfile(fd, mode)
;;
}
/* closes a file, flushing it to the output fd */
const close = {f
var fd
fd = f.fd
free(f)
-> std.close(fd) == 0
}
const free = {f
flush(f)
if f.mode & Rd != 0
std.slfree(f.rbuf)
;;
if f.mode & Wr != 0
std.slfree(f.wbuf)
;;
std.free(f)
}
/*
writes to as much from `src` as possible to a file,
returning the number of bytes written.
*/
const write = {f, src
std.assert(f.mode & Wr != 0, "File is not in write mode")
/*
Tack small writes onto the buffer end. Big ones
flush the buffer and then go right to kernel.
*/
if src.len < (f.wbuf.len - f.wend)
std.slcp(f.wbuf[f.wend:f.wend+src.len], src)
f.wend += src.len
-> `Ok src.len
else
flush(f)
-> writebuf(f.fd, src)
;;
}
/*
reads as much into 'dst' as possible, up to the size of 'dst',
returning the number of bytes read.
*/
const read = {f, dst
var n, d
var count
/* Clear the error state so we can retry */
if f.lasterr != 0
-> `Err geterr(f)
;;
std.assert(f.mode & Rd != 0, "File is not in read mode")
/*
* small reads should try to fill, so we don't have to make a
* syscall for every read
*/
if dst.len < Small
fill(f, f.rbuf.len - f.rend)
;;
/* Read as much as we can from the buffer */
count = std.min(dst.len, f.rend - f.rstart)
std.slcp(dst[:count], f.rbuf[f.rstart:f.rstart+count])
f.rstart += count
/* if we drained the buffer, reset it */
if f.rstart == f.rend
f.rstart = 0
f.rend = 0
;;
/* Read the rest directly from the fd */
d = dst[count:]
while dst.len > 0
n = std.read(f.fd, d)
if n == 0
break
elif n < 0
if count > 0
f.lasterr = n castto(std.errno)
;;
break
;;
count += n
d = d[n:]
;;
if n < 0 && count == 0
-> `Err errtype(n)
elif count == 0
-> `Eof
else
-> `Ok dst[:count]
;;
}
/* flushes f out to the backing fd */
const flush = {f
var ret
ret = true
if f.mode & Wr != 0
match writebuf(f.fd, f.wbuf[:f.wend])
| `Ok n:
ret = (n == f.wend)
f.wend = 0
| _:
-> false
;;
;;
-> ret
}
const seek = {f, off
flush(f)
-> std.seek(f.fd, off, std.Seekset)
}
/* writes a single byte to the output stream */
const putb = {f, b
match ensurewrite(f, 1)
| `Eof: -> `Eof
| `Err e: -> `Err e
| `Ok n:
f.wbuf[f.wend++] = b
-> `Ok 1
;;
}
/* writes a single character to the output stream, encoded in utf8 */
const putc = {f, c
var sz
sz = std.charlen(c)
match ensurewrite(f, sz)
| `Eof: -> `Eof
| `Err e: -> `Err e
| `Ok n:
std.encode(f.wbuf[f.wend:], c)
f.wend += sz
-> `Ok sz
;;
}
/* reads a single byte from the input stream */
const getb = {f
match ensureread(f, 1)
| `Eof: -> `Eof
| `Err e: -> `Err e
| `Ok n:
-> `Ok f.rbuf[f.rstart++]
;;
}
/* reads a single character from the input stream, encoded in utf8 */
const getc = {f
var c
match ensurecodepoint(f)
| `Eof: -> `Eof
| `Err e: -> `Err e
| `Ok n:
c = std.decode(f.rbuf[f.rstart:f.rend])
f.rstart += std.charlen(c)
-> `Ok c
;;
}
/* ensures we have enough to read a single codepoint in the buffer */
const ensurecodepoint : (f : file# -> status(std.size)) = {f
var b
var len
match ensureread(f, 1)
| `Eof: -> `Eof
| `Err e: -> `Err e
| `Ok n:
b = f.rbuf[f.rstart]
if b & 0x80 == 0 /* 0b0xxx_xxxx */
len = 1
elif b & 0xe0 == 0xc0 /* 0b110x_xxxx */
len = 2
elif b & 0xf0 == 0xe0 /* 0b1110_xxxx */
len = 3
elif b & 0xf8 == 0xf0 /* 0b1111_0xxx */
len = 4
else
len = 1 /* invalid unicode char */
;;
-> ensureread(f, len)
;;
}
/*
writes a single integer-like value to the output stream, in
little endian format
*/
generic putle = {f, v : @a::(numeric,integral)
for var i = 0; i < sizeof(@a); i++
putb(f, (v & 0xff) castto(byte))
v >>= 8
;;
-> sizeof(@a)
}
/*
writes a single integer-like value to the output stream, in
big endian format
*/
generic putbe = {f, v : @a::(numeric,integral)
for var i = sizeof(@a); i != 0; i--
putb(f, ((v >> ((i-1)*8)) & 0xff) castto(byte))
;;
-> sizeof(@a)
}
/* peeks a single byte from an input stream */
const peekb = {f
match ensureread(f, 1)
| `Eof: -> `Eof
| `Err e: -> `Err e
| `Ok n:
-> `Ok f.rbuf[f.rstart]
;;
}
/* peeks a single character from a utf8 encoded input stream */
const peekc = {f
match ensurecodepoint(f)
| `Eof: -> `Eof
| `Err e: -> `Err e
| `Ok n:
-> `Ok std.decode(f.rbuf[f.rstart:f.rend])
;;
}
/*
reads up to a single character delimiter. drops the delimiter
from the input stream. EOF always counts as a delimiter.
Eg, with the input "foo,bar\n"
bio.readto(f, ',') -> "foo"
bio.readto(f, ',') -> "bar\n"
*/
const readto = {f, delim
-> readdelim(f, delim, false)
}
/* same as readto, but drops the read data. */
const skipto = {f, delim
match readdelim(f, delim, true)
| `Ok ign: -> true
| `Eof: -> false
| `Err _: -> false
;;
}
const skipspace = {f
while true
match bio.peekc(f)
| `Ok c:
if !std.isspace(c)
break
;;
bio.getc(f)
| `Err e: -> false
| `Eof: break
;;
;;
-> true
}
/* Same as delim, but with special handling for '\n', '\r', and '\r\n' */
const readln = {f
var ret, c, n
ret = [][:]
while true
/* get at least delimiter count of characters */
match ensureread(f, 1)
| `Ok _:
| `Err e: -> `Err e
| `Eof:
ret = readinto(f, ret, f.rend - f.rstart)
if ret.len > 0
-> `Ok ret
else
-> `Eof
;;
;;
/* scan for delimiter */
for var i = f.rstart; i < f.rend; i++
c = f.rbuf[i] castto(char)
if c == '\r' || c == '\n'
n = 1
/* if we have '\r', we can get '\r\n'. */
if c == '\r' && unwrapc(peekc(f), -1) == '\n'
n = 2
;;
ret = readinto(f, ret, i - f.rstart)
f.rstart += n
-> `Ok ret
;;
:nextitergetln
;;
ret = readinto(f, ret, f.rend - f.rstart)
;;
std.die("unreachable")
}
const unwrapc = {cc, v
match cc
| `Ok c: -> c
| _: -> v
;;
}
const readdelim = {f, delim, drop
var ret
ret = [][:]
while true
/* get at least delimiter count of characters */
match ensureread(f, 1)
| `Ok _:
| `Err e: -> `Err e
| `Eof:
if !drop
ret = readinto(f, ret, f.rend - f.rstart)
;;
if ret.len > 0
-> `Ok ret
else
-> `Eof
;;
;;
for var i = f.rstart; i < f.rend; i++
if f.rbuf[i] == delim[0]
for var j = 0; j < delim.len; j++
if f.rbuf[i + j] != delim[j]
goto nextiterread
;;
;;
if !drop
ret = readinto(f, ret, i - f.rstart)
;;
f.rstart += delim.len
-> `Ok ret
;;
:nextiterread
;;
if !drop
ret = readinto(f, ret, f.rend - f.rstart)
;;
;;
std.die("unreachable")
}
/*
Same as std.put, but buffered. Returns the number of bytes written.
FIXME: depends on std.fmt() having a flush buffer API. Until then,
we're stuck with a small static buffer.
*/
const put = {f, fmt, args
var sl, ap, n
ap = std.vastart(&args)
sl = std.fmtv(fmt, &ap)
n = write(f, sl)
std.slfree(sl)
-> n
}
/*
reads n bytes from the read buffer onto the heap-allocated slice
provided.
*/
const readinto = {f, buf, n
var ret
std.assert(f.rstart + n <= f.rend, "Reading too much from buffer")
ret = std.sljoin(buf, f.rbuf[f.rstart:f.rstart + n])
f.rstart += n
-> ret
}
/* makes sure we can bufferedly write at least n bytes */
const ensurewrite = {f, n
std.assert(n < f.wbuf.len, "ensured write capacity > buffer size")
if n > f.wbuf.len - f.wend
match writebuf(f.fd, f.wbuf[:f.wend])
| `Ok len:
f.wend = 0
-> `Ok len
| `Err e: -> `Err e
| `Eof: -> `Eof
;;
;;
-> `Ok n
}
/*
makes sure we have at least n bytes buffered. returns true if we succeed
in buffering n bytes, false if we fail.
*/
const ensureread = {f, n
var held
var cap
std.assert(n < f.rbuf.len, "ensured read capacity > buffer size")
held = f.rend - f.rstart
if n > held
/* if we need to shift the slice down to the start, do it */
cap = f.rend - f.rstart
if n > (cap + held)
std.slcp(f.rbuf[:cap], f.rbuf[f.rstart:f.rend])
f.rstart = 0
f.rend = cap
;;
match fill(f, n)
| `Eof: -> `Eof
| `Err e: -> `Err e
| `Ok len:
if len > n
-> `Ok len
else
-> `Eof
;;
;;
else
-> `Ok n
;;
}
/* blats a buffer to an fd */
const writebuf = {fd, src
var n
var count
count = 0
while src.len != 0
n = std.write(fd, src)
if n == 0
-> `Eof
elif n < 0
-> `Err errtype(n)
;;
count += n
src = src[n:]
;;
:writedone
-> `Ok count
}
/*
Reads as many bytes as possible from the file into
the read buffer.
*/
const fill = {f, min
var n
var count
count = 0
/* Clear the error state so we can retry */
if f.lasterr != 0
-> `Err geterr(f)
;;
while count < min
n = std.read(f.fd, f.rbuf[f.rend:])
/*
If we've already read data, we don't want to
throw it away, so we report a successful short
read, and then error on the next read.
*/
if n == 0
break
elif n < 0
if count > 0
f.lasterr = n castto(std.errno)
;;
break
;;
count += n
f.rend += n
;;
if n < 0 && count == 0
-> `Err errtype(n)
elif count == 0
-> `Eof
else
-> `Ok count
;;
}
const geterr = {f
var e
e = f.lasterr
f.lasterr = 0
-> errtype(e castto(std.size))
}
const errtype : (e : std.size -> ioerr )= {e : std.size -> ioerr
var errno
errno = e castto(std.errno)
if errno == std.Ebadf
-> `Ebadfile
elif errno == std.Einval
-> `Ebadfile
elif errno == std.Efault
-> `Ebadbuf
elif errno == std.Eio
-> `Eioerr
else
-> `Eioerr
;;
}
|