zig

fork of https://codeberg.org/ziglang/zig
Log | Files | Refs | README | LICENSE

blob adaa3fcb (1659B) - Raw


      1 const std = @import("../std.zig");
      2 const os = std.os;
      3 const OutStream = std.io.OutStream;
      4 const builtin = @import("builtin");
      5 
      6 /// TODO make a proposal to make `std.fs.File` use *FILE when linking libc and this just becomes
      7 /// std.io.FileOutStream because std.fs.File.write would do this when linking
      8 /// libc.
      9 pub const COutStream = struct {
     10     pub const Error = std.fs.File.WriteError;
     11     pub const Stream = OutStream(Error);
     12 
     13     stream: Stream,
     14     c_file: *std.c.FILE,
     15 
     16     pub fn init(c_file: *std.c.FILE) COutStream {
     17         return COutStream{
     18             .c_file = c_file,
     19             .stream = Stream{ .writeFn = writeFn },
     20         };
     21     }
     22 
     23     fn writeFn(out_stream: *Stream, bytes: []const u8) Error!usize {
     24         const self = @fieldParentPtr(COutStream, "stream", out_stream);
     25         const amt_written = std.c.fwrite(bytes.ptr, 1, bytes.len, self.c_file);
     26         if (amt_written >= 0) return amt_written;
     27         switch (std.c._errno().*) {
     28             0 => unreachable,
     29             os.EINVAL => unreachable,
     30             os.EFAULT => unreachable,
     31             os.EAGAIN => unreachable, // this is a blocking API
     32             os.EBADF => unreachable, // always a race condition
     33             os.EDESTADDRREQ => unreachable, // connect was never called
     34             os.EDQUOT => return error.DiskQuota,
     35             os.EFBIG => return error.FileTooBig,
     36             os.EIO => return error.InputOutput,
     37             os.ENOSPC => return error.NoSpaceLeft,
     38             os.EPERM => return error.AccessDenied,
     39             os.EPIPE => return error.BrokenPipe,
     40             else => |err| return os.unexpectedErrno(@intCast(usize, err)),
     41         }
     42     }
     43 };