-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathio.vek
More file actions
858 lines (781 loc) · 26.3 KB
/
Copy pathio.vek
File metadata and controls
858 lines (781 loc) · 26.3 KB
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
// std:io — streams: the traits that describe them, the adapters that compose them,
// and the standard input and output of the process.
//
// Bytes and text are separate layers. The byte layer moves u8[]; the text layer moves
// string, which is UTF-8 by definition — so producing text from bytes means decoding,
// and decoding means holding state (a UTF-8 sequence can straddle two reads, a line can
// straddle a dozen). That state lives in an adapter you can point at, not in a method
// on the byte stream. TextReader/TextWriter are the bridge.
// The bytes<->string bridge and the UTF-8 vocabulary live in std:encoding now; the
// text layer here builds on it.
import "std:encoding" as encoding;
// Direct console writes. These go through the host's stdio, and so do the Stdout/Stderr
// handles below — two writers to one descriptor with only one of them buffered would
// emit their output out of order.
native fn __rt_io_print(message: string) -> void;
native fn __rt_io_println(message: string) -> void;
native fn __rt_io_eprint(message: string) -> void;
native fn __rt_io_eprintln(message: string) -> void;
native fn __rt_io_read_line() -> string?;
native fn __rt_io_read_all() -> string;
// Byte-level standard streams (1 = stdout, 2 = stderr; reads come from stdin).
native fn __rt_io_write(stream: i32, buf: u8[], off: usize, len: usize) -> i64;
native fn __rt_io_read(buf: u8[], off: usize, len: usize) -> i64;
native fn __rt_io_flush(stream: i32) -> i32;
// Shared with std:fs: the errno classifier. The names carry the io_ prefix because the
// runtime groups them there; the operations are not specific to a file.
native fn __rt_io_errkind(code: i32) -> u32;
native fn __rt_io_strerror(code: i32) -> string;
// ---- errors ---------------------------------------------------------------
// The failure arm of every fallible stream operation, whatever the stream. One error
// type, not one per stream: a `copy` from a file into a socket has to return
// *something*, and Vek has no conversion between unrelated error types to reconcile
// two. std:fs aliases this as FileError.
pub enum IoError {
NotFound;
PermissionDenied;
AlreadyExists;
IsDirectory;
NotDirectory;
DirectoryNotEmpty;
ReadOnlyFilesystem;
InvalidPath;
InvalidData; // not valid UTF-8, on a text stream
UnexpectedEof; // end of file before read_exact filled its buffer
WriteZero; // a writer stopped accepting bytes before the buffer drained
Interrupted;
WouldBlock;
BrokenPipe;
Unsupported;
Io(string);
satisfies Format {
fn format(self) -> string {
return match self {
NotFound => "NotFound",
PermissionDenied => "PermissionDenied",
AlreadyExists => "AlreadyExists",
IsDirectory => "IsDirectory",
NotDirectory => "NotDirectory",
DirectoryNotEmpty => "DirectoryNotEmpty",
ReadOnlyFilesystem => "ReadOnlyFilesystem",
InvalidPath => "InvalidPath",
InvalidData => "InvalidData",
UnexpectedEof => "UnexpectedEof",
WriteZero => "WriteZero",
Interrupted => "Interrupted",
WouldBlock => "WouldBlock",
BrokenPipe => "BrokenPipe",
Unsupported => "Unsupported",
Io(msg) => f"Io({msg})",
};
}
}
}
// Classify a host errno. The classification lives in the runtime so the errno macros
// stay on the C side.
pub fn from_errno(code: i32) -> IoError {
let kind: u32 = __rt_io_errkind(code);
if kind == 1 { return NotFound; }
if kind == 2 { return PermissionDenied; }
if kind == 3 { return AlreadyExists; }
if kind == 4 { return IsDirectory; }
if kind == 5 { return NotDirectory; }
if kind == 6 { return DirectoryNotEmpty; }
if kind == 7 { return ReadOnlyFilesystem; }
if kind == 8 { return InvalidPath; }
if kind == 9 { return Interrupted; }
if kind == 10 { return WouldBlock; }
if kind == 11 { return BrokenPipe; }
if kind == 12 { return Unsupported; }
return Io(__rt_io_strerror(code));
}
// Decode UTF-8 bytes, re-framing std:encoding's error as `IoError.InvalidData` — a
// text stream that silently corrupts what it read is worse than one that stops. The
// canonical UTF-8 API is `encoding.decode_utf8`; this is the stream-flavored adapter.
pub inline fn decode_utf8(bytes: u8[]) -> Result<string, IoError> {
return match encoding.decode_utf8(bytes) {
Ok(s) => Ok(s),
Err(_) => Err(InvalidData),
};
}
// The UTF-8 bytes of `s`. A string is already UTF-8, so nothing is re-encoded.
pub inline fn encode_utf8(s: string) -> u8[] {
return encoding.encode_utf8(s);
}
// ---- capabilities ---------------------------------------------------------
//
// One capability per trait, one method per trait. A type implements what it can honor
// and nothing else: an in-memory buffer cannot be flushed, a pipe cannot be sought.
// Read up to buf.length() bytes into `buf`. The count returned is 0 only at end of file
// — a reader with nothing available *right now* blocks. A read may be short at any time
// for any reason; that is not an error and not EOF. Use read_exact to fill a buffer.
pub trait Read {
fn read(mut self, mut buf: u8[]) -> Result<usize, IoError>;
}
// Write some of `bytes`, returning the count written, which may be short. Use write_all
// to drain a buffer.
pub trait Write {
fn write(mut self, bytes: u8[]) -> Result<usize, IoError>;
}
// Push buffered bytes onward, and report what pushing them cost. Only a stream that has
// a buffer satisfies this — it is where a buffered write finally reports failure, since
// a write that merely lands in the buffer succeeds even against a broken device.
pub trait Flush {
fn flush(mut self) -> Result<void, IoError>;
}
// Move the cursor; return the new absolute offset from the start.
pub trait Seek {
fn seek(mut self, pos: SeekFrom) -> Result<u64, IoError>;
}
// The next line without its trailing '\n', or null at end of file. A '\r\n' ending keeps
// its '\r'. A bare '\n' yields "" — an empty line, distinct from the null that means end
// of input. Invalid UTF-8 is InvalidData, not a panic and not a replacement character: a
// text stream that silently corrupts what it read is worse than one that stops.
pub trait TextRead {
fn read_line(mut self) -> Result<string?, IoError>;
}
// Write `s`. A string is already UTF-8, so nothing is encoded — the bytes are handed on.
// Unlike `write`, this is all-or-nothing; a partial line is not a useful return value.
pub trait TextWrite {
fn write_string(mut self, s: string) -> Result<void, IoError>;
}
pub enum SeekFrom {
Start(u64); // absolute, from the beginning
Current(i64); // relative to the cursor; may be negative
End(i64); // relative to the end; may be negative
}
// ---- functions over the capabilities --------------------------------------
//
// The conveniences are functions over the traits, not methods on them: a new stream type
// implements one method and gets all of these, with nothing to inherit, override, or
// accidentally reimplement.
// How many bytes the copying helpers move per underlying read/write.
const CHUNK: isize = 8192;
// Read from the cursor to end of file. `[]` if already there.
pub fn read_to_end<R: Read>(mut r: R) -> Result<u8[], IoError> {
let mut out: u8[] = [];
let mut chunk: u8[] = [];
let mut i: isize = 0;
while i < CHUNK {
chunk.push(0);
i = i + 1;
}
while true {
match r.read(mut chunk) {
Ok(n) => {
if n == 0 { return Ok(out); }
let mut j: usize = 0;
while j < n {
out.push(chunk[j as isize]);
j = j + 1;
}
}
Err(e) => { return Err(e); }
}
}
return Ok(out);
}
// Fill `buf` completely, reading across short reads. End of file first is UnexpectedEof,
// and the contents of `buf` are then unspecified.
pub fn read_exact<R: Read>(mut r: R, mut buf: u8[]) -> Result<void, IoError> {
let total: usize = buf.length() as usize;
let mut off: usize = 0;
while off < total {
// Read into a window and copy it back: `read` fills from index 0, and there is no
// slice-of-a-slice that aliases the caller's array.
let mut window: u8[] = [];
let mut i: usize = off;
while i < total {
window.push(0);
i = i + 1;
}
match r.read(mut window) {
Ok(n) => {
if n == 0 { return Err(UnexpectedEof); }
let mut j: usize = 0;
while j < n {
buf[(off + j) as isize] = window[j as isize];
j = j + 1;
}
off = off + n;
}
Err(e) => { return Err(e); }
}
}
return Ok();
}
// Write every byte of `bytes`, repeating across short writes. A writer that accepts zero
// bytes while bytes remain is making no progress: WriteZero rather than an endless loop.
pub fn write_all<W: Write>(mut w: W, bytes: u8[]) -> Result<void, IoError> {
let total: usize = bytes.length() as usize;
let mut off: usize = 0;
while off < total {
let mut rest: u8[] = [];
let mut i: usize = off;
while i < total {
rest.push(bytes[i as isize]);
i = i + 1;
}
match w.write(rest) {
Ok(n) => {
if n == 0 { return Err(WriteZero); }
off = off + n;
}
Err(e) => { return Err(e); }
}
}
return Ok();
}
// Copy `source` to `sink` until end of file; return the bytes copied. Goes through a fixed
// buffer, so a stream far larger than memory is fine. Does not flush `sink` — the caller
// owns that decision, and `sink` may not be flushable at all.
pub fn copy<R: Read, W: Write>(mut source: R, mut sink: W) -> Result<u64, IoError> {
let mut chunk: u8[] = [];
let mut i: isize = 0;
while i < CHUNK {
chunk.push(0);
i = i + 1;
}
let mut total: u64 = 0;
while true {
match source.read(mut chunk) {
Ok(n) => {
if n == 0 { return Ok(total); }
let mut piece: u8[] = [];
let mut j: usize = 0;
while j < n {
piece.push(chunk[j as isize]);
j = j + 1;
}
match write_all(mut sink, piece) {
Ok(_) => {}
Err(e) => { return Err(e); }
}
total = total + (n as u64);
}
Err(e) => { return Err(e); }
}
}
return Ok(total);
}
// Every remaining line, joined with a single '\n' between each. "" at end of input.
pub fn read_all_text<R: TextRead>(mut r: R) -> Result<string, IoError> {
let mut out: string = "";
let mut first: bool = true;
while true {
match r.read_line() {
Ok(line) => {
if line == null { return Ok(out); }
if first {
out = line;
first = false;
} else {
out = out + "\n" + line;
}
}
Err(e) => { return Err(e); }
}
}
return Ok(out);
}
// ---- the standard streams -------------------------------------------------
//
// Handles, not owners: dropping one does not close the descriptor, because a process
// does not own its own standard streams in a way that would make closing them
// meaningful. Take them as often as needed.
pub struct StdStream {
stream: i32;
satisfies Write {
inline fn write(mut self, bytes: u8[]) -> Result<usize, IoError> {
let n: i64 = __rt_io_write(self.stream, bytes, 0, bytes.length() as usize);
if n < 0 {
return Err(from_errno((0 - n) as i32));
}
return Ok(n as usize);
}
}
satisfies Flush {
inline fn flush(mut self) -> Result<void, IoError> {
let code: i32 = __rt_io_flush(self.stream);
if code != 0 {
return Err(from_errno(code));
}
return Ok();
}
}
satisfies TextWrite {
fn write_string(mut self, s: string) -> Result<void, IoError> {
// The write_all loop, inlined rather than `write_all(mut self, ...)`: a generic
// function instantiated at a type from inside that type's own satisfies block is
// emitted even when the block is unreachable, while the type's declaration is
// pruned — which fails IR validation for every program that does not otherwise
// use Stdout. Driving self.write directly sidesteps the instantiation.
let encoded: u8[] = encoding.encode_utf8(s);
let total: usize = encoded.length() as usize;
let mut off: usize = 0;
while off < total {
let mut rest: u8[] = [];
let mut i: usize = off;
while i < total {
rest.push(encoded[i as isize]);
i = i + 1;
}
match self.write(rest) {
Ok(n) => {
if n == 0 { return Err(WriteZero); }
off = off + n;
}
Err(e) => { return Err(e); }
}
}
return Ok();
}
}
}
pub struct Stdin {
satisfies Read {
inline fn read(mut self, mut buf: u8[]) -> Result<usize, IoError> {
let n: i64 = __rt_io_read(buf, 0, buf.length() as usize);
if n < 0 {
return Err(from_errno((0 - n) as i32));
}
return Ok(n as usize);
}
}
}
// stdout and stderr are one type at two descriptors — they differ only in where the
// bytes land, so there is nothing for a second type to say.
pub inline fn stdout() -> StdStream {
return StdStream { stream: 1 };
}
pub inline fn stderr() -> StdStream {
return StdStream { stream: 2 };
}
pub inline fn stdin() -> Stdin {
return Stdin {};
}
// ---- printing -------------------------------------------------------------
//
// The direct form, and what ordinary code should use: nothing above is needed to print a
// line. These write the UTF-8 bytes of `message` unchanged and do **not** report write
// failures — a closed pipe or a full disk is silently dropped. Code that must know uses
// stdout() and write_all, which return a Result.
pub inline fn print(message: string) -> void {
__rt_io_print(message);
}
pub inline fn println(message: string) -> void {
__rt_io_println(message);
}
pub inline fn eprint(message: string) -> void {
__rt_io_eprint(message);
}
pub inline fn eprintln(message: string) -> void {
__rt_io_eprintln(message);
}
// The next line of stdin without its trailing '\n', or null at end of file. Panics on
// invalid UTF-8 — this is the convenient form. For input that may be malformed and has
// to be handled rather than fatal, wrap stdin() in a TextReader.
pub inline fn read_line() -> string? {
return __rt_io_read_line();
}
// The rest of stdin through end of file ("" if already there). Panics on invalid UTF-8.
pub inline fn read_all() -> string {
return __rt_io_read_all();
}
// ---- in-memory streams ----------------------------------------------------
//
// What makes stream code testable: point a function at a buffer instead of a file and
// assert on what came out — no filesystem, no temp directory, no cleanup.
// An in-memory byte buffer with a cursor. Read + Write + Seek, but *not* Flush: there is
// nothing between it and its own storage.
pub struct Bytes {
pub data: u8[];
pub pos: usize;
pub inline fn new() -> Self {
return Self { data: [], pos: 0 };
}
pub inline fn from_bytes(data: u8[]) -> Self {
return Self { data, pos: 0 };
}
// Take the contents back out.
pub fn to_bytes(self) -> u8[] {
return self.data;
}
satisfies Read {
fn read(mut self, mut buf: u8[]) -> Result<usize, IoError> {
let len: usize = self.data.length() as usize;
let want: usize = buf.length() as usize;
let mut n: usize = 0;
while n < want && self.pos + n < len {
buf[n as isize] = self.data[(self.pos + n) as isize];
n = n + 1;
}
self.pos = self.pos + n;
return Ok(n);
}
}
satisfies Write {
// Writes at the cursor overwrite what is there and extend past the end.
fn write(mut self, bytes: u8[]) -> Result<usize, IoError> {
let mut i: usize = 0;
let count: usize = bytes.length() as usize;
while i < count {
let at: usize = self.pos + i;
if at < (self.data.length() as usize) {
self.data[at as isize] = bytes[i as isize];
} else {
self.data.push(bytes[i as isize]);
}
i = i + 1;
}
self.pos = self.pos + count;
return Ok(count);
}
}
satisfies Seek {
fn seek(mut self, pos: SeekFrom) -> Result<u64, IoError> {
let len: i64 = self.data.length() as i64;
let mut at: i64 = 0;
match pos {
Start(s) => { at = s as i64; }
Current(c) => { at = (self.pos as i64) + c; }
End(e) => { at = len + e; }
}
if at < 0 {
return Err(InvalidPath);
}
self.pos = at as usize;
return Ok(at as u64);
}
}
}
// An in-memory text buffer with a cursor over the *lines* of its contents.
pub struct Text {
pub data: string;
pub pos: isize;
pub inline fn new() -> Self {
return Self { data: "", pos: 0 };
}
pub inline fn from_string(data: string) -> Self {
return Self { data, pos: 0 };
}
pub inline fn to_string(self) -> string {
return self.data;
}
satisfies TextRead {
fn read_line(mut self) -> Result<string?, IoError> {
let len: isize = self.data.length();
if self.pos >= len {
let eof: string? = null;
return Ok(eof);
}
let mut end: isize = self.pos;
while end < len && self.data[end] != "\n" {
end = end + 1;
}
let line: string? = self.data.slice(self.pos, end);
// Step over the '\n'; at the end without one, land on `len` so the next call
// reports end of input.
self.pos = end + 1;
return Ok(line);
}
}
satisfies TextWrite {
inline fn write_string(mut self, s: string) -> Result<void, IoError> {
self.data += s;
return Ok();
}
}
}
// ---- adapters -------------------------------------------------------------
//
// Each adapter owns the stream it wraps: the wrapper is move-only if the inner stream is,
// and dropping the wrapper drops it.
// Byte buffering over any reader. Turns many small reads into few large ones — a one-byte
// read against a raw File is one syscall per byte, and against a BufReader one syscall
// per bufferful.
pub struct BufReader<R: Read> {
pub inner: R;
buf: u8[];
pos: usize;
filled: usize;
pub fn new<R: Read>(inner: R) -> BufReader<R> {
return BufReader<R> { inner, buf: [], pos: 0, filled: 0 };
}
// Refill from the inner reader. Returns how many bytes are now available.
fn fill(mut self) -> Result<usize, IoError> {
if self.pos < self.filled {
return Ok(self.filled - self.pos);
}
let mut chunk: u8[] = [];
let mut i: isize = 0;
while i < CHUNK {
chunk.push(0);
i = i + 1;
}
match self.inner.read(mut chunk) {
Ok(n) => {
self.buf = chunk;
self.pos = 0;
self.filled = n;
return Ok(n);
}
Err(e) => { return Err(e); }
}
}
satisfies Read {
fn read(mut self, mut buf: u8[]) -> Result<usize, IoError> {
match self.fill() {
Ok(available) => {
if available == 0 {
return Ok(0);
}
let want: usize = buf.length() as usize;
let mut n: usize = 0;
while n < want && n < available {
buf[n as isize] = self.buf[(self.pos + n) as isize];
n = n + 1;
}
self.pos = self.pos + n;
return Ok(n);
}
Err(e) => { return Err(e); }
}
}
}
}
// Byte buffering over any writer: accumulates writes and hands them on in bufferfuls.
//
// A BufWriter flushes when it is dropped, and a failure to flush at that point is
// discarded — `drop` returns void, so there is nowhere to report it. That is a deliberate
// choice between two bad options: *not* flushing on drop silently truncates the output of
// every program that forgets, which is worse and harder to notice. Code that cares whether
// its bytes landed calls flush explicitly and checks; the drop-flush is a safety net, not
// a reporting path.
pub struct BufWriter<W: Write> {
pub inner: W;
buf: u8[];
pub inline fn new<W: Write>(inner: W) -> BufWriter<W> {
return BufWriter<W> { inner, buf: [] };
}
satisfies Write {
fn write(mut self, bytes: u8[]) -> Result<usize, IoError> {
let count: usize = bytes.length() as usize;
let mut i: usize = 0;
while i < count {
self.buf.push(bytes[i as isize]);
i = i + 1;
}
if (self.buf.length() as isize) >= CHUNK {
match self.flush() {
Ok(_) => {}
Err(e) => { return Err(e); }
}
}
return Ok(count);
}
}
satisfies Flush {
fn flush(mut self) -> Result<void, IoError> {
if self.buf.length() == 0 {
return Ok();
}
let pending: u8[] = self.buf;
self.buf = [];
// The write_all loop, inlined: a `mut` argument must be a mutable identifier, and
// `self.inner` is a field, so the inner writer is driven through its own method.
let total: usize = pending.length() as usize;
let mut off: usize = 0;
while off < total {
let mut rest: u8[] = [];
let mut i: usize = off;
while i < total {
rest.push(pending[i as isize]);
i = i + 1;
}
match self.inner.write(rest) {
Ok(n) => {
if n == 0 { return Err(WriteZero); }
off = off + n;
}
Err(e) => { return Err(e); }
}
}
return Ok();
}
}
satisfies TextWrite {
fn write_string(mut self, s: string) -> Result<void, IoError> {
match self.write(encoding.encode_utf8(s)) {
Ok(_) => { return Ok(); }
Err(e) => { return Err(e); }
}
}
}
satisfies Drop {
fn drop(mut self) -> void {
match self.flush() {
Ok(_) => {}
Err(_) => {}
}
}
}
}
// The bytes-to-text bridge: buffers, decodes UTF-8, splits lines. This is a stateful
// adapter rather than a method on Read precisely because of the cases it has to handle —
// a UTF-8 sequence split across two reads, a line longer than one read, and a final line
// with no newline after it.
pub struct TextReader<R: Read> {
pub inner: R;
buf: u8[]; // bytes read from `inner` but not yet returned as a line
done: bool; // `inner` has reported end of file
pub inline fn new<R: Read>(inner: R) -> TextReader<R> {
return TextReader<R> { inner, buf: [], done: false };
}
satisfies TextRead {
// One self-contained method: every step mutates `self.buf`, and splitting those
// steps across `mut self` helpers made the buffer's updates hard to follow.
//
// The cases that make this a stateful adapter rather than a method on Read all live
// here: a line spanning several reads, a UTF-8 sequence split across two of them
// (harmless — a line is only ever cut at '\n', which is never a continuation byte),
// and a final line with no newline after it.
fn read_line(mut self) -> Result<string?, IoError> {
while true {
// A complete line is buffered: cut it at the newline and keep the rest.
let mut at: isize = 0 - 1;
let mut i: isize = 0;
let buffered: isize = self.buf.length();
while i < buffered {
if self.buf[i] == 10 {
at = i;
i = buffered;
} else {
i = i + 1;
}
}
let mut cut: isize = 0 - 1;
let mut skip: isize = 0;
if at >= 0 {
cut = at;
skip = 1;
} else if self.done {
if buffered == 0 {
let eof: string? = null;
return Ok(eof);
}
// A trailing line with no '\n' after it is still a line. The call after this
// one finds an empty buffer and reports end of input.
cut = buffered;
skip = 0;
}
if cut >= 0 {
let mut line: u8[] = [];
let mut k: isize = 0;
while k < cut {
line.push(self.buf[k]);
k = k + 1;
}
let mut rest: u8[] = [];
let mut j: isize = cut + skip;
while j < buffered {
rest.push(self.buf[j]);
j = j + 1;
}
self.buf = rest;
match encoding.decode_utf8(line) {
Ok(s) => {
let decoded: string? = s;
return Ok(decoded);
}
Err(_) => { return Err(InvalidData); }
}
}
// Nothing to cut yet and not at end of file: pull more bytes.
let mut chunk: u8[] = [];
let mut c: isize = 0;
while c < CHUNK {
chunk.push(0);
c = c + 1;
}
match self.inner.read(mut chunk) {
Ok(n) => {
if n == 0 {
self.done = true;
} else {
let mut m: usize = 0;
while m < n {
self.buf.push(chunk[m as isize]);
m = m + 1;
}
}
}
Err(e) => { return Err(e); }
}
}
let eof: string? = null;
return Ok(eof);
}
}
}
// The text-to-bytes bridge. Buffers, and hands the UTF-8 bytes of each string on. Flushes
// on drop under the same rule as BufWriter.
pub struct TextWriter<W: Write> {
pub inner: W;
buf: u8[];
pub inline fn new<W: Write>(inner: W) -> TextWriter<W> {
return TextWriter<W> { inner, buf: [] };
}
satisfies TextWrite {
fn write_string(mut self, s: string) -> Result<void, IoError> {
let encoded: u8[] = encoding.encode_utf8(s);
let count: usize = encoded.length() as usize;
let mut i: usize = 0;
while i < count {
self.buf.push(encoded[i as isize]);
i = i + 1;
}
if (self.buf.length() as isize) >= CHUNK {
return self.flush();
}
return Ok();
}
}
satisfies Flush {
fn flush(mut self) -> Result<void, IoError> {
if self.buf.length() == 0 {
return Ok();
}
let pending: u8[] = self.buf;
self.buf = [];
// The write_all loop, inlined: a `mut` argument must be a mutable identifier, and
// `self.inner` is a field, so the inner writer is driven through its own method.
let total: usize = pending.length() as usize;
let mut off: usize = 0;
while off < total {
let mut rest: u8[] = [];
let mut i: usize = off;
while i < total {
rest.push(pending[i as isize]);
i = i + 1;
}
match self.inner.write(rest) {
Ok(n) => {
if n == 0 { return Err(WriteZero); }
off = off + n;
}
Err(e) => { return Err(e); }
}
}
return Ok();
}
}
satisfies Drop {
fn drop(mut self) -> void {
match self.flush() {
Ok(_) => {}
Err(_) => {}
}
}
}
}