Skip to content

Instantly share code, notes, and snippets.

@jacobly0
Created March 30, 2025 19:16
Show Gist options
  • Save jacobly0/c804ff09709ccc3d353d3dee6388cbc7 to your computer and use it in GitHub Desktop.
Save jacobly0/c804ff09709ccc3d353d3dee6388cbc7 to your computer and use it in GitHub Desktop.
Zig `std.Io` example
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
Curabitur pretium tincidunt lacus. Nulla gravida orci a odio, et feugiat tellus facilisis sed. Phasellus viverra nulla ut metus varius laoreet. Quisque rutrum. Aenean imperdiet. Etiam ultricies nisi vel augue. Curabitur ullamcorper ultricies nisi. Nam eget dui. Etiam rhoncus. Maecenas tempus, tellus eget condimentum rhoncus, sem quam semper libero, sit amet adipiscing sem neque sed ipsum.
Suspendisse in justo eu magna luctus suscipit. Sed lectus. Integer euismod lacus luctus magna. Quisque cursus, metus vitae pharetra auctor, sem massa mattis sem, at interdum magna augue eget diam. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia curae; Morbi lacinia molestie dui. Praesent blandit dolor. Sed non quam lacus suspendisse faucibus interdum posuere lorem ipsum dolor sit amet.
const allocator_impl = .debug;
const enable_threaded = true;
const enable_evented = true;
const sleep_mode = .relative;
const cancel_sleep = true;
const std = @import("std");
const assert = std.debug.assert;
const Allocator = std.mem.Allocator;
const Io = std.Io;
pub fn main() !void {
var debug_allocator: std.heap.DebugAllocator(.{}) = .init;
defer _ = debug_allocator.deinit();
const gpa = switch (allocator_impl) {
.debug => debug_allocator.allocator(),
.smp => std.heap.smp_allocator(),
else => |impl| @compileError("unimplemented allocator impl: " ++ @tagName(impl)),
};
if (enable_threaded) {
var thread_pool: std.Thread.Pool = undefined;
try thread_pool.init(.{
.allocator = gpa,
.n_jobs = std.Thread.getCpuCount() catch 1,
});
defer thread_pool.deinit();
try main2(thread_pool.io());
}
if (enable_evented) {
var event_loop: std.Io.EventLoop = undefined;
try event_loop.init(gpa);
defer event_loop.deinit();
try main2(event_loop.io());
}
}
pub fn main2(io: std.Io) !void {
const start = try now(io);
var wait = switch (sleep_mode) {
.relative => io.@"async"(sleepFor, .{ io, 0.75 * std.time.ns_per_s }),
.absolute => io.@"async"(sleepUntil, .{ io, start.addDuration(0.75 * std.time.ns_per_s) }),
else => |mode| @compileError("unimplemented sleep mode: " ++ @tagName(mode)),
};
var first_half = io.@"async"(calcSum, .{ 0, 100 });
var second_half = io.@"async"(calcSum, .{ 100, 200 });
var rot13 = io.@"async"(processTextFile, .{io});
const total = first_half.@"await"(io) + second_half.@"await"(io);
std.log.info("[{}] total: {d}", .{ std.Thread.getCurrentId(), total });
try rot13.@"await"(io);
if (cancel_sleep) {
wait.cancel(io) catch |err| switch (err) {
error.AsyncCancel => {},
else => |e| return e,
};
} else {
try wait.@"await"(io);
}
std.log.info("{}", .{std.fmt.fmtDuration(@intCast(start.durationTo(try now(io))))});
}
fn calcSum(start: usize, end: usize) usize {
var sum: usize = 0;
for (start..end) |i| {
sum += i;
}
std.log.debug("[{}] calcSum returning {d}", .{ std.Thread.getCurrentId(), sum });
return sum;
}
fn processTextFile(io: Io) !void {
const f = try io.openFile(std.fs.cwd(), "example.txt", .{});
defer io.closeFile(f);
var buffer: [5000]u8 = undefined;
const n = try io.readAll(f, &buffer);
const contents = buffer[0..n];
for (contents) |*elem| {
if (elem.* < 0x40) continue;
elem.* ^= 0x20;
}
const out_file = try io.createFile(std.fs.cwd(), "output.txt", .{});
defer io.closeFile(out_file);
try io.writeAll(out_file, contents);
std.log.debug("[{}] processTextFile returning", .{std.Thread.getCurrentId()});
}
fn now(io: Io) !Io.Timestamp {
return io.now(.MONOTONIC);
}
fn sleepFor(io: Io, nanoseconds: i96) !void {
return io.sleep(.MONOTONIC, .{ .nanoseconds = nanoseconds });
}
fn sleepUntil(io: Io, timestamp: Io.Timestamp) !void {
return io.sleep(.MONOTONIC, .{ .timestamp = timestamp });
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment