Skip to content

Instantly share code, notes, and snippets.

@tetsu-koba
Last active January 17, 2023 07:27
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tetsu-koba/fe4396d1782db500d90eb686c02124eb to your computer and use it in GitHub Desktop.
Save tetsu-koba/fe4396d1782db500d90eb686c02124eb to your computer and use it in GitHub Desktop.
Zig test for std.io.StreamSource
const std = @import("std");
const expect = std.testing.expect;
const io = std.io;
fn copy(dst: *io.StreamSource, src: *io.StreamSource) !usize {
const r = src.reader();
const w = dst.writer();
const BUFSIZE = 512;
var buf: [BUFSIZE]u8 = undefined;
var len: usize = BUFSIZE;
var count: usize = 0;
while (len == BUFSIZE) {
len = try r.readAll(&buf);
try w.writeAll(buf[0..len]);
count += len;
}
return count;
}
fn buf2file(buf: []const u8, filename: []const u8) !usize {
var f = io.StreamSource{ .file = try std.fs.cwd().createFile(filename, .{}) };
defer f.file.close();
var b = io.StreamSource{ .const_buffer = io.fixedBufferStream(buf) };
return try copy(&f, &b);
}
fn file2buf(filename: []const u8, buf: []u8) !usize {
var f = io.StreamSource{ .file = try std.fs.cwd().openFile(filename, .{}) };
defer f.file.close();
var b = io.StreamSource{ .buffer = io.fixedBufferStream(buf) };
return try copy(&b, &f);
}
test {
const str = "Alpha Bravo Charlie Delta Echo Foxtrot Golf Hotel India Juliett Kilo Lima Mike";
const filename = "tmpfile";
var buf: [str.len]u8 = undefined;
try expect(str.len == try buf2file(str, filename));
try expect(str.len == try file2buf(filename, &buf));
try expect(std.mem.eql(u8, str, &buf));
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment