hare

[hare] The Hare programming language
git clone https://git.torresjrjr.com/hare.git
Log | Files | Refs | README | LICENSE

util.ha (1118B)


      1 // SPDX-License-Identifier: MPL-2.0
      2 // (c) Hare authors <https://harelang.org>
      3 
      4 // Reads an entire buffer, perhaps issuing several [[read]] calls to do so. If
      5 // EOF is immediately encountered, it is returned; if [[EOF]] is encountered
      6 // partway through reading the buffer, [[underread]] is returned.
      7 export fn readall(in: handle, buf: []u8) (size | EOF | error) = {
      8 	let z: size = 0;
      9 	for (z < len(buf)) {
     10 		match (read(in, buf[z..])?) {
     11 		case EOF =>
     12 			if (z == 0) {
     13 				return EOF;
     14 			};
     15 			return z: underread: error;
     16 		case let n: size =>
     17 			z += n;
     18 		};
     19 	};
     20 	return z;
     21 };
     22 
     23 // Writes an entire buffer, perhaps issuing several [[write]] calls to do so.
     24 // Aborts on errors after partial writes. Hence it should only be used if it is
     25 // certain that the underlying writes will not fail after an initial write.
     26 export fn writeall(out: handle, buf: const []u8) (size | error) = {
     27 	let z: size = 0;
     28 	for (z < len(buf)) {
     29 		z += match (write(out, buf[z..])) {
     30 		case let s: size =>
     31 			yield s;
     32 		case let e: error =>
     33 			if (z == 0) {
     34 				return e;
     35 			};
     36 
     37 			abort("error after partial write");
     38 		};
     39 	};
     40 	return z;
     41 };