File: tee.ha

package info (click to toggle)
hare 0.26.0-1
  • links: PTS, VCS
  • area: main
  • in suites: sid
  • size: 7,352 kB
  • sloc: asm: 1,374; makefile: 123; sh: 117; lisp: 101
file content (45 lines) | stat: -rw-r--r-- 970 bytes parent folder | download | duplicates (3)
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
// SPDX-License-Identifier: MPL-2.0
// (c) Hare authors <https://harelang.org>

export type teestream = struct {
	vtable: stream,
	h: handle,
	sink: handle,
};

const tee_vtable: vtable = vtable {
	reader = &tee_read,
	writer = &tee_write,
	...
};

// Creates a stream which copies writes and reads into 'sink' after forwarding
// them to the handle 'h'. This stream does not need to be closed, and closing
// it will not close the secondary stream.
export fn tee(h: handle, sink: handle) teestream = {
	return teestream {
		vtable = &tee_vtable,
		h = h,
		sink = sink,
		...
	};
};

fn tee_read(s: *stream, buf: []u8) (size | EOF | error) = {
	let s = s: *teestream;
	let z = match (read(s.h, buf)?) {
	case EOF =>
		return EOF;
	case let z: size =>
		yield z;
	};
	writeall(s.sink, buf[..z])?;
	return z;
};

fn tee_write(s: *stream, buf: const []u8) (size | error) = {
	let s = s: *teestream;
	const z = write(s.h, buf)?;
	writeall(s.sink, buf[..z])?;
	return z;
};