2020-11-16 17:32:50 +01:00
|
|
|
module os
|
|
|
|
|
|
|
|
// file descriptor based operations:
|
2021-02-07 05:19:05 +01:00
|
|
|
|
|
|
|
// close filedescriptor
|
2020-11-16 17:32:50 +01:00
|
|
|
pub fn fd_close(fd int) int {
|
2021-04-04 16:05:06 +02:00
|
|
|
if fd == -1 {
|
|
|
|
return 0
|
|
|
|
}
|
2020-11-16 17:32:50 +01:00
|
|
|
return C.close(fd)
|
|
|
|
}
|
|
|
|
|
|
|
|
pub fn fd_write(fd int, s string) {
|
2021-04-04 16:05:06 +02:00
|
|
|
if fd == -1 {
|
|
|
|
return
|
|
|
|
}
|
2020-11-16 17:32:50 +01:00
|
|
|
mut sp := s.str
|
|
|
|
mut remaining := s.len
|
|
|
|
for remaining > 0 {
|
|
|
|
written := C.write(fd, sp, remaining)
|
|
|
|
if written < 0 {
|
|
|
|
return
|
|
|
|
}
|
|
|
|
remaining = remaining - written
|
2020-12-23 19:13:42 +01:00
|
|
|
sp = unsafe { sp + written }
|
2020-11-16 17:32:50 +01:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2021-02-07 05:19:05 +01:00
|
|
|
// read from filedescriptor, block until data
|
2020-11-16 17:32:50 +01:00
|
|
|
pub fn fd_slurp(fd int) []string {
|
|
|
|
mut res := []string{}
|
2021-04-04 16:05:06 +02:00
|
|
|
if fd == -1 {
|
|
|
|
return res
|
|
|
|
}
|
2020-11-16 17:32:50 +01:00
|
|
|
for {
|
|
|
|
s, b := fd_read(fd, 4096)
|
|
|
|
if b <= 0 {
|
|
|
|
break
|
|
|
|
}
|
|
|
|
res << s
|
|
|
|
}
|
|
|
|
return res
|
|
|
|
}
|
|
|
|
|
2021-02-07 05:19:05 +01:00
|
|
|
// read from filedescriptor, don't block
|
|
|
|
// return [bytestring,nrbytes]
|
2020-11-16 17:32:50 +01:00
|
|
|
pub fn fd_read(fd int, maxbytes int) (string, int) {
|
2021-04-04 16:05:06 +02:00
|
|
|
if fd == -1 {
|
|
|
|
return '', 0
|
|
|
|
}
|
2020-11-16 17:32:50 +01:00
|
|
|
unsafe {
|
2021-06-15 13:47:11 +02:00
|
|
|
mut buf := malloc_noscan(maxbytes + 1)
|
2021-02-14 19:31:42 +01:00
|
|
|
nbytes := C.read(fd, buf, maxbytes)
|
|
|
|
if nbytes < 0 {
|
|
|
|
free(buf)
|
|
|
|
return '', nbytes
|
|
|
|
}
|
2020-11-16 17:32:50 +01:00
|
|
|
buf[nbytes] = 0
|
2021-02-14 19:31:42 +01:00
|
|
|
return tos(buf, nbytes), nbytes
|
2020-11-16 17:32:50 +01:00
|
|
|
}
|
|
|
|
}
|