file.ha (1605B)
1 // License: MPL-2.0 2 // (c) 2021-2022 Drew DeVault <sir@cmpwn.com> 3 // (c) 2021 Ember Sawady <ecs@d2evs.net> 4 use errors; 5 use rt; 6 use strings; 7 8 // This is an opaque type which encloses an OS-level file handle resource. It 9 // can be used as a [[handle]] in most situations, but there are some APIs which 10 // require a [[file]] with some OS-level handle backing it - this type is used 11 // for such APIs. 12 // 13 // On FreeBSD, [[io::file]] is a file descriptor. 14 export type file = int; 15 16 // Opens a Unix file descriptor as a file. This is a low-level interface, to 17 // open files most programs will use something like [[os::open]]. This function 18 // is not portable. 19 export fn fdopen(fd: int) file = fd; 20 21 fn fd_read(fd: file, buf: []u8) (size | EOF | error) = { 22 match (rt::read(fd, buf: *[*]u8, len(buf))) { 23 case let err: rt::errno => 24 return errors::errno(err); 25 case let n: size => 26 switch (n) { 27 case 0 => 28 return EOF; 29 case => 30 return n; 31 }; 32 }; 33 }; 34 35 fn fd_write(fd: file, buf: const []u8) (size | error) = { 36 match (rt::write(fd, buf: *const [*]u8, len(buf))) { 37 case let err: rt::errno => 38 return errors::errno(err); 39 case let n: size => 40 return n; 41 }; 42 }; 43 44 fn fd_close(fd: file) (void | error) = { 45 match (rt::close(fd)) { 46 case void => void; 47 case let err: rt::errno => 48 return errors::errno(err); 49 }; 50 }; 51 52 fn fd_seek( 53 fd: file, 54 offs: off, 55 whence: whence, 56 ) (off | error) = { 57 match (rt::lseek(fd, offs: i64, whence: int)) { 58 case let err: rt::errno => 59 return errors::errno(err); 60 case let n: i64 => 61 return n: off; 62 }; 63 }; 64 65 fn fd_copy(to: file, from: file) (size | error) = errors::unsupported;