hare

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

tee.ha (970B)


      1 // SPDX-License-Identifier: MPL-2.0
      2 // (c) Hare authors <https://harelang.org>
      3 
      4 export type teestream = struct {
      5 	vtable: stream,
      6 	h: handle,
      7 	sink: handle,
      8 };
      9 
     10 const tee_vtable: vtable = vtable {
     11 	reader = &tee_read,
     12 	writer = &tee_write,
     13 	...
     14 };
     15 
     16 // Creates a stream which copies writes and reads into 'sink' after forwarding
     17 // them to the handle 'h'. This stream does not need to be closed, and closing
     18 // it will not close the secondary stream.
     19 export fn tee(h: handle, sink: handle) teestream = {
     20 	return teestream {
     21 		vtable = &tee_vtable,
     22 		h = h,
     23 		sink = sink,
     24 		...
     25 	};
     26 };
     27 
     28 fn tee_read(s: *stream, buf: []u8) (size | EOF | error) = {
     29 	let s = s: *teestream;
     30 	let z = match (read(s.h, buf)?) {
     31 	case EOF =>
     32 		return EOF;
     33 	case let z: size =>
     34 		yield z;
     35 	};
     36 	writeall(s.sink, buf[..z])?;
     37 	return z;
     38 };
     39 
     40 fn tee_write(s: *stream, buf: const []u8) (size | error) = {
     41 	let s = s: *teestream;
     42 	const z = write(s.h, buf)?;
     43 	writeall(s.sink, buf[..z])?;
     44 	return z;
     45 };