1 | module os |
2 | |
3 | // file descriptor based operations: |
4 | |
5 | // close filedescriptor |
6 | pub fn fd_close(fd int) int { |
7 | if fd == -1 { |
8 | return 0 |
9 | } |
10 | return C.close(fd) |
11 | } |
12 | |
13 | pub fn fd_write(fd int, s string) { |
14 | if fd == -1 { |
15 | return |
16 | } |
17 | mut sp := s.str |
18 | mut remaining := s.len |
19 | for remaining > 0 { |
20 | written := C.write(fd, sp, remaining) |
21 | if written < 0 { |
22 | return |
23 | } |
24 | remaining = remaining - written |
25 | sp = unsafe { voidptr(sp + written) } |
26 | } |
27 | } |
28 | |
29 | // read from filedescriptor, block until data |
30 | pub fn fd_slurp(fd int) []string { |
31 | mut res := []string{} |
32 | if fd == -1 { |
33 | return res |
34 | } |
35 | for { |
36 | s, b := fd_read(fd, 4096) |
37 | if b <= 0 { |
38 | break |
39 | } |
40 | res << s |
41 | } |
42 | return res |
43 | } |
44 | |
45 | // read from filedescriptor, don't block |
46 | // return [bytestring,nrbytes] |
47 | pub fn fd_read(fd int, maxbytes int) (string, int) { |
48 | if fd == -1 { |
49 | return '', 0 |
50 | } |
51 | unsafe { |
52 | mut buf := malloc_noscan(maxbytes + 1) |
53 | nbytes := C.read(fd, buf, maxbytes) |
54 | if nbytes < 0 { |
55 | free(buf) |
56 | return '', nbytes |
57 | } |
58 | buf[nbytes] = 0 |
59 | return tos(buf, nbytes), nbytes |
60 | } |
61 | } |