Skip to content

Instantly share code, notes, and snippets.

@notcancername
notcancername / subnet_to_range.zig
Created March 11, 2024 18:25
Convert a /N subnet to an IP range.
const std = @import("std");
pub fn main() !void {
var rd_state = std.io.bufferedReader(std.io.getStdIn().reader());
const rd = rd_state.reader();
var wr_state = std.io.bufferedWriter(std.io.getStdOut().writer());
const wr = wr_state.writer();
var buf: [64]u8 = undefined;
@notcancername
notcancername / sse.zig
Last active March 3, 2024 00:34
zig server-sent events parser
const std = @import("std");
pub const Event = struct {
event: ?[]const u8,
data: ?std.ArrayListUnmanaged(u8),
id: ?[]const u8,
retry: ?u64,
pub fn deinit(event: Event, ally: std.mem.Allocator) void {
inline for (.{ event.event, event.id }) |mx| if (mx) |x| ally.free(x);
@notcancername
notcancername / free_list_allocator.zig
Created January 29, 2024 00:48
A simple allocator wrapper with a free list, sort of, to reuse allocations.
// SPDX-License-Identifier: 0BSD
// Copyright (C) 2024 by cancername <notcancername@protonmail.com>
//
// Permission to use, copy, modify, and/or distribute this software for any purpose with or without
// fee is hereby granted.
//
// THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS
// SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE
// AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
// WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT,
@notcancername
notcancername / bench_add_inline.zig
Last active January 7, 2024 03:41
Zig add vs add inline vs @addWithOverflow
const std = @import("std");
extern fn not_inlined(ptr: [*]usize, len: usize) usize;
extern fn inlined(ptr: [*]usize, len: usize) usize;
extern fn builtin(ptr: [*]usize, len: usize) usize;
extern fn builtin_no_destructure(ptr: [*]usize, len: usize) usize;
extern fn sum_not_inlined(ptr: [*]usize, len: usize) usize;
extern fn sum_inlined(ptr: [*]usize, len: usize) usize;
extern fn sum_builtin(ptr: [*]usize, len: usize) usize;
extern fn sum_builtin_no_destructure(ptr: [*]usize, len: usize) usize;
const std = @import("std");
fn splice(src_rd: anytype, dst_wr: anytype, comptime buf_len: usize, lim: usize) !void {
var buf: [buf_len]u8 = undefined;
var left = lim;
while (true) {
const len = try src_rd.read(buf[0..@min(left, buf.len)]);
if (len == 0) break;
left = try std.math.sub(usize, left, len);
try dst_wr.writeAll(buf[0..len]);
const std = @import("std");
const io = std.io;
const math = std.math;
// TODO: this is a massive hack that relies on implementation details
// and **WILL** break when BufferedReader or SeekableStream change,
// however, I do not see any other way, so this is fine for now.
/// An amalgam of `std.io.BufferedReader` and `std.io.SeekableStream`, such that they work together.
///