code
stringlengths 38
801k
| repo_path
stringlengths 6
263
|
|---|---|
const sf = @import("../sfml.zig");
pub const Sprite = struct {
const Self = @This();
// Constructor/destructor
/// Inits a sprite with no texture
pub fn init() !Self {
var sprite = sf.c.sfSprite_create();
if (sprite == null)
return sf.Error.nullptrUnknownReason;
return Self{ .ptr = sprite.? };
}
/// Inits a sprite with a texture
pub fn initFromTexture(texture: sf.Texture) !Self {
var sprite = sf.c.sfSprite_create();
if (sprite == null)
return sf.Error.nullptrUnknownReason;
sf.c.sfSprite_setTexture(sprite, texture.get(), 1);
return Self{ .ptr = sprite.? };
}
/// Destroys this sprite
pub fn deinit(self: Self) void {
sf.c.sfSprite_destroy(self.ptr);
}
// Getters/setters
/// Gets the position of this sprite
pub fn getPosition(self: Self) sf.Vector2f {
return sf.Vector2f.fromCSFML(sf.c.sfSprite_getPosition(self.ptr));
}
/// Sets the position of this sprite
pub fn setPosition(self: Self, pos: sf.Vector2f) void {
sf.c.sfSprite_setPosition(self.ptr, pos.toCSFML());
}
/// Adds the offset to this shape's position
pub fn move(self: Self, offset: sf.Vector2f) void {
sf.c.sfSprite_move(self.ptr, offset.toCSFML());
}
/// Gets the scale of this sprite
pub fn getScale(self: Self) sf.Vector2f {
return sf.Vector2f.fromCSFML(sf.c.sfSprite_getScale(self.ptr));
}
/// Sets the scale of this sprite
pub fn setScale(self: Self, factor: sf.Vector2f) void {
sf.c.sfSprite_setScale(self.ptr, factor.toCSFML());
}
/// Scales this sprite
pub fn scale(self: Self, factor: sf.Vector2f) void {
sf.c.sfSprite_scale(self.ptr, factor.toCSFML());
}
/// Gets the origin of this sprite
pub fn getOrigin(self: Self) sf.Vector2f {
return sf.Vector2f.fromCSFML(sf.c.sfSprite_getOrigin(self.ptr));
}
/// Sets the origin of this sprite
pub fn setOrigin(self: Self, origin: sf.Vector2f) void {
sf.c.sfSprite_setOrigin(self.ptr, origin.toCSFML());
}
/// Gets the rotation of this sprite
pub fn getRotation(self: Self) f32 {
return sf.c.sfSprite_getRotation(self.ptr);
}
/// Sets the rotation of this sprite
pub fn setRotation(self: Self, angle: f32) void {
sf.c.sfSprite_setRotation(self.ptr, angle);
}
/// Rotates this shape by a given amount
pub fn rotate(self: Self, angle: f32) void {
sf.c.sfSprite_rotate(self.ptr, angle);
}
/// Gets the color of this sprite
pub fn getColor(self: Self) sf.Color {
return sf.Color.fromCSFML(sf.c.sfSprite_getColor(self.ptr));
}
/// Sets the color of this sprite
pub fn setColor(self: Self, color: sf.Color) void {
sf.c.sfSprite_setColor(self.ptr, color.toCSFML());
}
/// Gets the texture of this shape
pub fn getTexture(self: Self) ?sf.Texture {
var t = sf.c.sfSprite_getTexture(self.ptr);
if (t != null) {
return sf.Texture{ .const_ptr = t.? };
} else
return null;
}
/// Sets this sprite's texture (the sprite will take the texture's dimensions)
pub fn setTexture(self: Self, texture: ?sf.Texture) void {
var tex = if (texture) |t| t.get() else null;
sf.c.sfSprite_setTexture(self.ptr, tex, 1);
}
/// Gets the sub-rectangle of the texture that the sprite will display
pub fn getTextureRect(self: Self) sf.FloatRect {
return sf.FloatRect.fromCSFML(sf.c.sfSprite_getTextureRect(self.ptr));
}
/// Sets the sub-rectangle of the texture that the sprite will display
pub fn setTextureRect(self: Self, rect: sf.FloatRect) void {
sf.c.sfSprite_getCircleRect(self.ptr, rect.toCSFML());
}
/// Pointer to the csfml structure
ptr: *sf.c.sfSprite
};
test "sprite: sane getters and setters" {
const tst = @import("std").testing;
var spr = try Sprite.init();
defer spr.deinit();
spr.setColor(sf.Color.Yellow);
spr.setRotation(15);
spr.setPosition(.{ .x = 1, .y = 2 });
spr.setOrigin(.{ .x = 20, .y = 25 });
spr.setScale(.{ .x = 2, .y = 2 });
// TODO : issue #2
//tst.expectEqual(sf.Color.Yellow, spr.getColor());
tst.expectEqual(sf.Vector2f{ .x = 1, .y = 2 }, spr.getPosition());
tst.expectEqual(sf.Vector2f{ .x = 20, .y = 25 }, spr.getOrigin());
tst.expectEqual(@as(?sf.Texture, null), spr.getTexture());
tst.expectEqual(sf.Vector2f{ .x = 2, .y = 2 }, spr.getScale());
spr.rotate(5);
spr.move(.{ .x = -5, .y = 5 });
spr.scale(.{ .x = 5, .y = 5 });
tst.expectEqual(@as(f32, 20), spr.getRotation());
tst.expectEqual(sf.Vector2f{ .x = -4, .y = 7 }, spr.getPosition());
tst.expectEqual(sf.Vector2f{ .x = 10, .y = 10 }, spr.getScale());
}
|
src/sfml/graphics/sprite.zig
|
const std = @import("std");
const Answer = struct { @"0": u32, @"1": u32 };
const AugmentedPoint = struct { x: usize, y: usize, cost: u32 };
const Point = struct { x: usize, y: usize };
fn wrappingAdd(x: u32, a: u32) u32 {
if (x + a > 9) {
return (x + a) % 9;
} else {
return x + a;
}
}
fn fromAugmented(p: AugmentedPoint) Point {
return Point{ .x = p.x, .y = p.y };
}
fn displace(p: Point, displacement: [2]i32) ?Point {
if (displacement[0] < 0 and -displacement[0] > p.x) {
return null;
} else if (displacement[1] < 0 and -displacement[1] > p.y) {
return null;
} else {
return Point{ .x = @intCast(usize, @intCast(i32, p.x) + displacement[0]), .y = @intCast(usize, @intCast(i32, p.y) + displacement[1]) };
}
}
fn augment(p: Point, cost: u32) AugmentedPoint {
return AugmentedPoint{ .x = p.x, .y = p.y, .cost = cost };
}
fn lessThan(a: AugmentedPoint, b: AugmentedPoint) std.math.Order {
return std.math.order(a.cost, b.cost);
}
fn search(grid: std.ArrayList(std.ArrayList(u32)), arena: *std.heap.ArenaAllocator) !u32 {
var node = AugmentedPoint{ .x = 0, .y = 0, .cost = 0 };
var frontier = std.PriorityQueue(AugmentedPoint, lessThan).init(&arena.allocator);
try frontier.add(node);
var explored = std.AutoHashMap(Point, void).init(&arena.allocator);
try explored.put(fromAugmented(node), .{});
while (frontier.removeOrNull()) |next_node| {
node = next_node;
if (node.y == grid.items.len - 1 and node.x == grid.items[0].items.len - 1) {
return node.cost;
}
for ([4][2]i32{ [_]i32{ 1, 0 }, [_]i32{ 0, 1 }, [_]i32{ -1, 0 }, [_]i32{ 0, -1 } }) |displacement| {
if (displace(fromAugmented(node), displacement)) |displaced_node| {
if (displaced_node.x < grid.items[0].items.len and displaced_node.y < grid.items.len) {
if (!explored.contains(displaced_node)) {
try frontier.add(augment(displaced_node, grid.items[displaced_node.y].items[displaced_node.x] + node.cost));
try explored.put(displaced_node, .{});
}
}
}
}
} else {
unreachable;
}
}
fn run(filename: []const u8) !Answer {
const file = try std.fs.cwd().openFile(filename, .{ .read = true });
defer file.close();
var reader = std.io.bufferedReader(file.reader()).reader();
var buffer: [1024]u8 = undefined;
var gpa = std.heap.GeneralPurposeAllocator(.{}){};
defer _ = gpa.deinit();
var arena = std.heap.ArenaAllocator.init(&gpa.allocator);
defer arena.deinit();
var grid = std.ArrayList(std.ArrayList(u32)).init(&arena.allocator);
while (try reader.readUntilDelimiterOrEof(&buffer, '\n')) |line| {
var row = std.ArrayList(u32).init(&arena.allocator);
for (line) |c| {
try row.append(@as(u32, c - '0'));
}
try grid.append(row);
}
var big_grid = std.ArrayList(std.ArrayList(u32)).init(&arena.allocator);
var i: usize = 0;
while (i < grid.items.len * 5) : (i += 1) {
var big_row = std.ArrayList(u32).init(&arena.allocator);
var j: usize = 0;
while (j < grid.items[0].items.len * 5) : (j += 1) {
const height = grid.items.len;
const width = grid.items[0].items.len;
try big_row.append(wrappingAdd(grid.items[i % height].items[j % width], @intCast(u32, i / height + j / width)));
}
try big_grid.append(big_row);
}
return Answer{ .@"0" = try search(grid, &arena), .@"1" = try search(big_grid, &arena) };
}
pub fn main() !void {
const answer = try run("inputs/" ++ @typeName(@This()) ++ ".txt");
std.debug.print("{d}\n", .{answer.@"0"});
std.debug.print("{d}\n", .{answer.@"1"});
}
test {
const answer = try run("test-inputs/" ++ @typeName(@This()) ++ ".txt");
try std.testing.expectEqual(answer.@"0", 40);
try std.testing.expectEqual(answer.@"1", 315);
}
|
src/day15.zig
|
const Benchmark = @import("benchmark.zig");
const Atom = Benchmark.Atom;
const Counters = Benchmark.Counters;
pub const descr =
\\- delta from `mikdusan.0`
\\- iterator does NOT return EOF
;
pub fn spin(self: *Atom, bm: Benchmark, counters: *Counters, magnify: usize) Atom.Error!void {
var it: Iterator = undefined;
var i: usize = 0;
while (i < magnify) : (i += 1) {
it.reset(bm.data);
var nerrors: u64 = 0;
var ncodepoints: u64 = 0;
while (it.pos < it.bytes.len) {
if (it.next()) {
ncodepoints += 1;
} else |err| {
nerrors += 1;
}
}
counters.num_codepoints += ncodepoints;
counters.num_errors += nerrors;
counters.num_bytes += it.bytes.len;
}
}
const Iterator = struct {
bytes: []const u8,
pos: usize,
pub const Codepoint = u21;
pub const EncodingError = error {
IllFormedCodepoint,
ShortCodepoint,
};
fn reset(self: *Iterator, bytes: []const u8) void {
self.bytes = bytes;
self.pos = 0;
}
fn next(self: *Iterator) EncodingError!Codepoint {
const c = self.bytes[self.pos];
const result = switch (@truncate(u5, c >> 3)) {
0b00000, 0b00001, 0b00010, 0b00011, 0b00100, 0b00101, 0b00110, 0b00111,
0b01000, 0b01001, 0b01010, 0b01011, 0b01100, 0b01101, 0b01110, 0b01111,
=> {
self.pos += 1;
return c;
},
0b10000, 0b10001, 0b10010, 0b10011, 0b10100, 0b10101, 0b10110, 0b10111,
=> {
self.pos += 1;
return EncodingError.IllFormedCodepoint;
},
0b11000, 0b11001, 0b11010, 0b11011,
=> {
if ((self.bytes.len - self.pos) < 2) {
self.pos = self.bytes.len;
return EncodingError.ShortCodepoint;
}
const code = self.bytes[self.pos..self.pos+2];
self.pos += 2;
return @as(u11, @truncate(u5, code[0])) << 6
| @truncate(u6, code[1]);
},
0b11100, 0b11101,
=> {
if ((self.bytes.len - self.pos) < 3) {
self.pos = self.bytes.len;
return EncodingError.ShortCodepoint;
}
const code = self.bytes[self.pos..self.pos+3];
self.pos += 3;
return @as(u16, @truncate(u4, code[0])) << 12
| @as(u12, @truncate(u6, code[1])) << 6
| @truncate(u6, code[2]);
},
0b11110, 0b11111,
=> {
if ((self.bytes.len - self.pos) < 4) {
self.pos = self.bytes.len;
return EncodingError.ShortCodepoint;
}
const code = self.bytes[self.pos..self.pos+4];
self.pos += 4;
return @as(u21, @truncate(u3, code[0])) << 18
| @as(u18, @truncate(u6, code[1])) << 12
| @as(u12, @truncate(u6, code[2])) << 6
| @truncate(u6, code[3]);
},
};
return result;
}
};
|
src/atom.mikdusan.1.zig
|
const std = @import("std");
/// Import the C implementations of termios for use when linking libc.
const c = @cImport({
@cInclude("termios.h");
@cInclude("sys/ioctl.h");
});
/// Linux has a syscall-based Termios implementation in stdlib, but
/// has no implementation for BSDs or Darwin. Those operating systems
/// require libc anyway, so we use the libc Termios on these targets.
pub const Termios = if (std.os.builtin.tag == .linux) std.os.termios else c.termios;
/// Get the current Termios struct for the given file descriptor.
/// This variant also checks whether the fd is a tty.
pub fn tcgetattrInit(self: *PosixTty) PosixTty.InitError!Termios {
if (std.builtin.os.tag != .linux) while (true) {
var out: Termios = undefined;
switch (std.os.errno(c.tcgetattr(self.tty.handle, &out))) {
0 => return out,
std.os.EINTR => continue,
std.os.ENOTTY => return error.NotATerminal,
else => |err| return std.os.unexpectedErrno(err),
}
};
return std.os.tcgetattr(file.handle);
}
/// Get the current Termios struct for the given file descriptor.
/// Caller asserts that the fd is a tty.
pub fn tcgetattr(self: *PosixTty) error{Unexpected}!Termios {
return self.tcgetattrInit() catch |err| switch (err) {
error.NotATerminal => unreachable,
error.Unexpected => return err,
};
}
/// Control when termios changes are propagated.
pub const TCSA = if (std.builtin.os.tag == .linux)
std.os.TCSA
else
extern enum(c_uint) {
/// Termios changes are propagated immediately.
NOW,
/// Termios changes are propagated after all pending output
/// has been written to the terminal device.
DRAIN,
/// Termios changes are propagated after all pending output
/// has been written to the terminal device. Additionally,
/// any unread input will be discarded.
FLUSH,
_,
};
/// Update the current Termios settings to a new set of values.
/// Caller asserts that the fd is a tty.
pub fn tcsetattr(self: *PosixTty, optional_action: TCSA, termios: Termios) error{Unexpected,ProcessOrphaned}!void {
if (std.builtin.tag != .linux) while (true) {
switch (std.os.errno(c.tcsetattr(self.tty.handle, @enumToInt(optional_action), &termios))) {
0 => return,
std.os.EINTR => continue,
std.os.EIO => return error.ProcessOrphaned,
std.os.ENOTTY => unreachable,
else => |err| std.os.unexpectedErrno(err),
}
};
return std.os.tcsetattr(self.tty.handle, optional_action, termios);
}
|
src/posix/termios.zig
|
const std = @import("std");
usingnamespace @import("util");
usingnamespace @import("context.zig");
usingnamespace @import("unit.zig");
usingnamespace @import("source.zig");
pub const log = struct {
pub const Level = enum {
err,
warn,
};
const Self = @This();
const EscapedString = struct {
text: []const u8,
pub fn format(self: EscapedString, comptime fmt: []const u8, options: std.fmt.FormatOptions, writer: anytype) !void {
const sw = ansi.styledWriter(writer);
for (self.text) |char| {
if (std.ascii.isGraph(char) or char == ' ') {
try sw.print("{c}", .{char});
}
else {
try sw.background(.yellow);
try sw.write(" ");
try sw.noBackground();
}
}
}
};
pub fn esc(text: []const u8) EscapedString {
return EscapedString{
.text = text,
};
}
pub fn logSourceToken(comptime level: Level, token: Source.Token, comptime fmt: []const u8, args: anytype) !void {
const sw = ansi.styledStdErr();
try sw.italic();
try sw.print("{s}:{d}:{d} ", .{token.source().path, token.line.index + 1, token.start + 1});
try sw.none();
try writePrefix(sw, level);
try sw.print(fmt ++ "\n", args);
try writeArrow(sw);
const line_text = token.line.text();
try sw.print("{}", .{ esc(line_text) });
// if (token.start > 0) {
// try sw.print("{}", .{ esc(line_text[0..token.start]) });
// }
// try sw.background(.black_light);
// try sw.print("{s}", .{ esc(token.text()) });
// try sw.none();
// const token_end = token.start + token.len;
// if (token_end < line_text.len) {
// try sw.print("{}", .{ esc(line_text[token_end..]) });
// }
try sw.write("\n");
if (token.len > 0) {
try sw.writer.writeByteNTimes(' ', token.start + 5);
try sw.bold();
try sw.foreground(.magenta_light);
try sw.writer.writeByteNTimes('^', token.len);
try sw.none();
}
try sw.write("\n");
}
fn writeArrow(sw: anytype) !void {
try sw.foreground(.black_light);
try sw.write(" >>> ");
try sw.noForeground();
}
fn writePrefix(sw: anytype, comptime level: Level) !void {
switch (level) {
.err => {
try sw.foreground(.red_light);
try sw.write("error");
},
.warn => {
try sw.foreground(.yellow_light);
try sw.write("warning");
},
}
try sw.none();
try sw.write(": ");
}
};
|
src/compile/log.zig
|
const std = @import("std");
const nanovg = std.build.Pkg{
.name = "nanovg",
.path = std.build.FileSource.relative("deps/nanovg/src/nanovg.zig"),
};
const zalgebra = std.build.Pkg{
.name = "zalgebra",
.path = std.build.FileSource.relative("deps/zalgebra/src/main.zig"),
};
pub fn build(b: *std.build.Builder) !void {
const target = b.standardTargetOptions(.{});
const mode = b.standardReleaseOptions();
const exe = b.addExecutable("Karaoke", "src/main.zig");
exe.setBuildMode(mode);
exe.setTarget(target);
if (exe.target.isWindows()) {
exe.addVcpkgPaths(.dynamic) catch @panic("vcpkg not installed");
if (exe.vcpkg_bin_path) |bin_path| {
const dlls = [_][]const u8{
"SDL2.dll",
"avcodec-58.dll",
"avformat-58.dll",
"avutil-56.dll",
"swresample-3.dll",
"swscale-5.dll",
};
for (dlls[0..]) |dll| {
const src_dll = try std.fs.path.join(b.allocator, &.{ bin_path, dll });
b.installBinFile(src_dll, dll);
}
}
exe.subsystem = .Windows;
exe.linkSystemLibrary("shell32");
exe.addObjectFile("microphone.o"); // add icon
exe.want_lto = false; // workaround for https://github.com/ziglang/zig/issues/8531
}
exe.addPackage(nanovg);
exe.addPackage(zalgebra);
exe.addIncludeDir("src");
exe.addIncludeDir("src/gl2/include");
exe.addIncludeDir("deps/nanovg/src");
const c_flags = [_][]const u8{ "-O0", "-g", "-Werror" };
// exe.addCSourceFile("src/myffmpeg.c", &c_flags);
exe.addCSourceFile("src/ffplay_modified.c", &c_flags);
exe.addCSourceFile("src/gl_render.c", &c_flags);
exe.addCSourceFile("src/gl2/src/glad.c", &c_flags);
exe.addCSourceFile("deps/nanovg/src/nanovg.c", &c_flags);
exe.addCSourceFile("deps/nanovg/src/nanovg_gl2_impl.c", &c_flags);
exe.linkSystemLibrary("SDL2");
exe.linkSystemLibrary("avcodec");
// exe.linkSystemLibrary("avdevice");
// exe.linkSystemLibrary("avfilter");
exe.linkSystemLibrary("avformat");
exe.linkSystemLibrary("avutil");
exe.linkSystemLibrary("swresample");
exe.linkSystemLibrary("swscale");
if (exe.target.isDarwin()) {
exe.linkFramework("OpenGL");
} else if (exe.target.isWindows()) {
exe.linkSystemLibrary("opengl32");
} else if (exe.target.isLinux()) {
exe.linkSystemLibrary("gl");
exe.linkSystemLibrary("X11");
}
exe.linkLibC();
exe.install();
const run_cmd = exe.run();
run_cmd.step.dependOn(b.getInstallStep());
if (b.args) |args| {
run_cmd.addArgs(args);
}
const run_step = b.step("run", "Run the app");
run_step.dependOn(&run_cmd.step);
}
|
build.zig
|
const sabaton = @import("root").sabaton;
comptime {
asm (
// We pack the CPU boot trampolines into the stack slots, because reasons.
\\ .section .data
\\ .balign 8
\\ .global smp_tag
\\smp_tag:
\\ .8byte 0x34d1d96339647025 // smp identifier
\\ .8byte 0 // next
\\ .8byte 0 // flags
\\ .4byte 0 // boot cpu id
\\ .4byte 0 // pad
\\ .8byte 4 // cpu_count
\\
\\ // CPU 0
\\ .4byte 0 // ACPI UID
\\ .4byte 0 // CPU ID
\\ .8byte 0 // target stack
\\ .8byte 0 // goto address
\\ .8byte 0 // extra argument
\\
\\ // CPU 1
\\ .4byte 1 // ACPI UID
\\ .4byte 1 // CPU ID
\\ .8byte __boot_stack + 0x1000 // target stack
\\ .8byte 0 // goto address
\\ .8byte 0 // extra argument
\\
\\ // CPU 2
\\ .4byte 2 // ACPI UID
\\ .4byte 2 // CPU ID
\\ .8byte __boot_stack + 0x2000 // target stack
\\ .8byte 0 // goto address
\\ .8byte 0 // extra argument
\\
\\ // CPU 3
\\ .4byte 3 // ACPI UID
\\ .4byte 3 // CPU ID
\\ .8byte __boot_stack + 0x3000 // target stack
\\ .8byte 0 // goto address
\\ .8byte 0 // extra argument
\\
\\ .section .text.smp_stub
\\ .global smp_stub
\\smp_stub:
\\ BL el2_to_el1
\\ MSR SPSel, #0
\\ LDR X1, [X0, #8] // Load stack
\\ MOV SP, X1
\\ // Fall through to smp_entry
);
}
export fn smp_entry(context: u64) linksection(".text.smp_entry") noreturn {
@call(.{ .modifier = .always_inline }, sabaton.stivale2_smp_ready, .{context});
}
fn cpucfg(offset: u16) *volatile u32 {
return @intToPtr(*volatile u32, @as(usize, 0x0170_0C00) + offset);
}
fn ccu(offset: u64) *volatile u32 {
return @intToPtr(*volatile u32, @as(usize, 0x01C2_0000) + offset);
}
pub fn init() void {
const smp_tag = sabaton.near("smp_tag").addr(sabaton.Stivale2tag);
sabaton.add_tag(&smp_tag[0]);
var core: u64 = 1;
while (core < 4) : (core += 1) {
const ap_x0 = @ptrToInt(smp_tag) + 40 + core * 32;
_ = sabaton.psci.wake_cpu(@ptrToInt(sabaton.near("smp_stub").addr(u32)), core, ap_x0, .SMC);
}
}
|
src/platform/pine_aarch64/smp.zig
|
const std = @import("std");
const assert = std.debug.assert;
const expect = std.testing.expect;
const mem = std.mem;
const bits = @import("./bits.zig");
test "reverse8" {
try expect(bits.reverse8(0x00) == 0x00);
try expect(bits.reverse8(0x01) == 0x80);
try expect(bits.reverse8(0x08) == 0x10);
try expect(bits.reverse8(0x80) == 0x01);
try expect(bits.reverse8(0x81) == 0x81);
try expect(bits.reverse8(0xfe) == 0x7f);
try expect(bits.reverse8(0xff) == 0xff);
}
test "reverse16" {
try expect(bits.reverse16(0x0000, 1) == 0x0);
try expect(bits.reverse16(0xffff, 1) == 0x1);
try expect(bits.reverse16(0x0000, 16) == 0x0000);
try expect(bits.reverse16(0xffff, 16) == 0xffff);
// 0001 0010 0011 0100 -> 0010 1100 0100 1000
try expect(bits.reverse16(0x1234, 16) == 0x2c48);
// 111 1111 0100 0001 -> 100 0001 0111 1111
try expect(bits.reverse16(0x7f41, 15) == 0x417f);
}
test "read64le" {
const data: [8]u8 = [8]u8{ 0x88, 0x99, 0xaa, 0xbb, 0xcc, 0xdd, 0xee, 0xff };
try expect(bits.read64le(&data) == 0xffeeddccbbaa9988);
}
test "read32le" {
const data: [4]u8 = [4]u8{ 0xcc, 0xdd, 0xee, 0xff };
try expect(bits.read32le(&data) == 0xffeeddcc);
}
test "read16le" {
const data: [2]u8 = [2]u8{ 0xee, 0xff };
try expect(bits.read16le(&data) == 0xffee);
}
test "write64le" {
const expected: [8]u8 = [8]u8{ 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88 };
var buf: [8]u8 = undefined;
bits.write64le(&buf, 0x8877665544332211);
try expect(mem.eql(u8, buf[0..], expected[0..]));
}
test "write32le" {
const expected: [4]u8 = [4]u8{ 0x11, 0x22, 0x33, 0x44 };
var buf: [4]u8 = undefined;
bits.write32le(&buf, 0x44332211);
try expect(mem.eql(u8, buf[0..], expected[0..]));
}
test "write16le" {
const expected: [2]u8 = [2]u8{ 0x11, 0x22 };
var buf: [2]u8 = undefined;
bits.write16le(&buf, 0x2211);
try expect(mem.eql(u8, buf[0..], expected[0..]));
}
test "lsb" {
try expect(bits.lsb(0x1122334455667788, 0) == 0x0);
try expect(bits.lsb(0x1122334455667788, 5) == 0x8);
try expect(bits.lsb(0x7722334455667788, 63) == 0x7722334455667788);
}
test "round_up" {
try expect(bits.round_up(0, 4) == 0);
try expect(bits.round_up(1, 4) == 4);
try expect(bits.round_up(2, 4) == 4);
try expect(bits.round_up(3, 4) == 4);
try expect(bits.round_up(4, 4) == 4);
try expect(bits.round_up(5, 4) == 8);
try expect(bits.round_up(128, 4) == 128);
try expect(bits.round_up(129, 4) == 132);
try expect(bits.round_up(128, 32) == 128);
try expect(bits.round_up(129, 32) == 160);
}
|
src/bits_test.zig
|
const std = @import("std");
const lib = @import("lib");
const mem = std.mem;
const assert = std.debug.assert;
const testing = std.testing;
const meta = std.meta;
const fs = std.fs;
const fmt = std.fmt;
const io = std.io;
const os = std.os;
const math = std.math;
const stdout = io.getStdOut().writer();
const stdin = io.getStdIn().reader();
const Allocator = std.mem.Allocator;
const ArrayList = std.ArrayListUnmanaged;
const HashMap = std.AutoArrayHashMapUnmanaged;
const MultiArrayList = std.MultiArrayList;
const Tokenizer = lib.Tokenizer;
const Parser = lib.Parser;
const Linker = lib.Linker;
const Instruction = lib.Instruction;
const Interpreter = lib.Interpreter;
const GraphContext = @import("GraphContext.zig");
const FindContext = @import("FindContext.zig");
const BufferedWriter = io.BufferedWriter(4096, fs.File.Writer);
const FileContext = lib.context.StreamContext(BufferedWriter.Writer);
pub const log_level = .info;
const Options = struct {
allow_absolute_paths: bool = false,
omit_trailing_newline: bool = false,
list_files: bool = false,
list_tags: bool = false,
calls: []const FileOrTag = &.{},
graph_text_colour: u24 = 0x000000,
graph_background_colour: u24 = 0xffffff,
graph_border_colour: u24 = 0x92abc9,
graph_inherit_line_colour: bool = false,
graph_line_gradient: u8 = 5,
graph_colours: []const u24 = &.{
0xdf4d77,
0x2288ed,
0x94bd76,
0xc678dd,
0x61aeee,
0xe3bd79,
},
command: Command,
files: []const []const u8 = &.{},
pub const FileOrTag = union(enum) {
file: []const u8,
tag: []const u8,
};
};
const Command = enum {
help,
tangle,
ls,
call,
graph,
find,
init,
pub const map = std.ComptimeStringMap(Command, .{
.{ "help", .help },
.{ "tangle", .tangle },
.{ "ls", .ls },
.{ "call", .call },
.{ "graph", .graph },
.{ "find", .find },
.{ "init", .init },
});
};
const Flag = enum {
allow_absolute_paths,
omit_trailing_newline,
file,
tag,
list_tags,
list_files,
graph_border_colour,
graph_inherit_line_colour,
graph_colours,
graph_background_colour,
graph_line_gradient,
graph_text_colour,
@"--",
stdin,
pub const map = std.ComptimeStringMap(Flag, .{
.{ "--allow-absolute-paths", .allow_absolute_paths },
.{ "--omit-trailing-newline", .omit_trailing_newline },
.{ "--file=", .file },
.{ "--tag=", .tag },
.{ "--list-tags", .list_tags },
.{ "--list-files", .list_files },
.{ "--graph-border-colour=", .graph_border_colour },
.{ "--graph-colours=", .graph_colours },
.{ "--graph-background-colour=", .graph_background_colour },
.{ "--graph-text-colour=", .graph_text_colour },
.{ "--graph-inherit-line-colour", .graph_inherit_line_colour },
.{ "--graph-line-gradient=", .graph_line_gradient },
.{ "--", .@"--" },
.{ "--stdin", .stdin },
});
};
const tangle_help =
\\Usage: zangle tangle [options] [files]
\\
\\ --allow-absolute-paths Allow writing file blocks with absolute paths
\\ --omit-trailing-newline Do not print a trailing newline at the end of a file block
;
const ls_help =
\\Usage: zangle ls [files]
\\
\\ --list-files (default) List all file output paths in the document
\\ --list-tags List all tags in the document
;
const call_help =
\\Usage: zangle call [options] [files]
\\
\\ --file=[filepath] Render file block to stdout
\\ --tag=[tagname] Render tag block to stdout
;
const find_help =
\\Usage: zangle find [options] [files]
\\
\\ --tag=[tagname] Find the location of the given tag in the literate document and output files
;
const graph_help =
\\Usage: zangle graph [files]
\\
\\ --file=[filepath] Render the graph for the given file
\\ --graph-border=[#rrggbb] Set item border colour
\\ --graph-colours=[#rrggbb,...] Set spline colours
\\ --graph-background-colour=[#rrggbb] Set the background colour of the graph
\\ --graph-text-colour=[#rrggbb] Set node label text colour
\\ --graph-inherit-line-colour Borders inherit their colour from the choden line colour
\\ --graph-line-gradient=[number] Set the gradient level
;
const init_help =
\\Usage: zangle init [files]
\\ --stdin Read file names from stdin
;
const log = std.log;
fn helpGeneric() void {
log.info(
\\{s}
\\
\\{s}
\\
\\{s}
\\
\\{s}
\\
\\{s}
, .{
tangle_help,
ls_help,
call_help,
graph_help,
init_help,
});
}
fn help(com: ?Command, name: ?[]const u8) void {
const command = com orelse {
helpGeneric();
log.err("I don't know how to handle the given command '{s}'", .{name.?});
return;
};
switch (command) {
.help => helpGeneric(),
.tangle => log.info(tangle_help, .{}),
.ls => log.info(ls_help, .{}),
.call => log.info(call_help, .{}),
.graph => log.info(graph_help, .{}),
.find => log.info(find_help, .{}),
.init => log.info(init_help, .{}),
}
}
fn parseCli(gpa: Allocator, objects: *Linker.Object.List) !?Options {
var options: Options = .{ .command = undefined };
const args = os.argv;
if (args.len < 2) {
help(.help, null);
return error.@"Missing command name";
}
const command_name = mem.sliceTo(args[1], 0);
const command = Command.map.get(command_name);
if (args.len < 3 or command == null or command.? == .help) {
help(command, command_name);
if (command) |com| {
switch (com) {
.help => return null,
else => return error.@"Not enough arguments",
}
} else {
return error.@"Invalid command";
}
}
var interpret_flags_as_files: bool = false;
var calls = std.ArrayList(Options.FileOrTag).init(gpa);
var files = std.ArrayList([]const u8).init(gpa);
var graph_colours = std.ArrayList(u24).init(gpa);
var graph_colours_set = false;
var files_on_stdin = false;
options.command = command.?;
for (args[2..]) |arg0| {
const arg = mem.sliceTo(arg0, 0);
if (arg.len == 0) return error.@"Zero length argument";
if (arg[0] == '-' and !interpret_flags_as_files) {
errdefer log.err("I don't know how to parse the given option '{s}'", .{arg});
log.debug("processing {s} flag '{s}'", .{ @tagName(options.command), arg });
const split = (mem.indexOfScalar(u8, arg, '=') orelse (arg.len - 1)) + 1;
const flag = Flag.map.get(arg[0..split]) orelse {
return error.@"Unknown option";
};
switch (options.command) {
.help => unreachable,
.ls => switch (flag) {
.list_files => options.list_files = true,
.list_tags => options.list_tags = true,
else => return error.@"Unknown command-line flag",
},
.call => switch (flag) {
.file => try calls.append(.{ .file = arg[split..] }),
.tag => try calls.append(.{ .tag = arg[split..] }),
else => return error.@"Unknown command-line flag",
},
.find => switch (flag) {
.tag => try calls.append(.{ .tag = arg[split..] }),
else => return error.@"Unknown command-line flag",
},
.graph => switch (flag) {
.file => try calls.append(.{ .file = arg[split..] }),
.graph_border_colour => options.graph_border_colour = try parseColour(arg[split..]),
.graph_background_colour => options.graph_background_colour = try parseColour(arg[split..]),
.graph_text_colour => options.graph_text_colour = try parseColour(arg[split..]),
.graph_inherit_line_colour => options.graph_inherit_line_colour = true,
.graph_line_gradient => options.graph_line_gradient = fmt.parseInt(u8, arg[split..], 10) catch {
return error.@"Invalid value specified, expected a number between 0-255 (inclusive)";
},
.graph_colours => {
var it = mem.tokenize(u8, arg[split..], ",");
while (it.next()) |item| {
try graph_colours.append(try parseColour(item));
}
graph_colours_set = true;
},
else => return error.@"Unknown command-line flag",
},
.tangle => switch (flag) {
.allow_absolute_paths => options.allow_absolute_paths = true,
.omit_trailing_newline => options.omit_trailing_newline = true,
.@"--" => interpret_flags_as_files = true,
else => return error.@"Unknown command-line flag",
},
.init => switch (flag) {
.stdin => files_on_stdin = true,
else => return error.@"Unknown command-line flag",
},
}
} else if (options.command != .init) {
std.log.info("compiling {s}", .{arg});
const text = try fs.cwd().readFileAlloc(gpa, arg, 0x7fff_ffff);
var p: Parser = .{ .it = .{ .bytes = text } };
while (p.step(gpa)) |working| {
if (!working) break;
} else |err| {
const location = p.it.locationFrom(.{});
log.err("line {d} col {d}: {s}", .{
location.line,
location.column,
@errorName(err),
});
os.exit(1);
}
const object = p.object(arg);
objects.append(gpa, object) catch return error.@"Exhausted memory";
} else {
files.append(arg) catch return error.@"Exhausted memory";
}
}
if (files_on_stdin) {
const err = error.@"Exhausted memory";
while (stdin.readUntilDelimiterOrEofAlloc(gpa, '\n', fs.MAX_PATH_BYTES) catch return err) |path| {
files.append(path) catch return error.@"Exhausted memory";
}
}
if (options.command == .init and files.items.len == 0) {
return error.@"No files to import specified";
}
options.calls = calls.toOwnedSlice();
options.files = files.toOwnedSlice();
if (graph_colours_set) {
options.graph_colours = graph_colours.toOwnedSlice();
}
return options;
}
fn parseColour(text: []const u8) !u24 {
if (text.len == 7) {
if (text[0] != '#') return error.@"Invalid colour spexification, expected '#'";
return fmt.parseInt(u24, text[1..], 16) catch error.@"Colour specification is not a valid 24-bit hex number";
} else {
return error.@"Invalid hex colour specification length; expecting a 6 hex digit colour prefixed with a '#'";
}
}
pub fn main() void {
run() catch |err| {
log.err("{s}", .{@errorName(err)});
os.exit(1);
};
}
pub fn run() !void {
var vm: Interpreter = .{};
var instance = std.heap.GeneralPurposeAllocator(.{}){};
const gpa = instance.allocator();
var options = (try parseCli(gpa, &vm.linker.objects)) orelse return;
const n_objects = vm.linker.objects.items.len;
const plural: []const u8 = if (n_objects == 1) "object" else "objects";
log.info("linking {d} {s}...", .{ n_objects, plural });
try vm.linker.link(gpa);
log.debug("processing command {s}", .{@tagName(options.command)});
switch (options.command) {
.help => unreachable, // handled in parseCli
.ls => {
var buffered = io.bufferedWriter(stdout);
const writer = buffered.writer();
if (!options.list_files) options.list_files = !options.list_tags;
if (options.list_tags) for (vm.linker.procedures.keys()) |path| {
try writer.writeAll(path);
try writer.writeByte('\n');
};
if (options.list_files) for (vm.linker.files.keys()) |path| {
try writer.writeAll(path);
try writer.writeByte('\n');
};
try buffered.flush();
},
.call => {
var buffered: BufferedWriter = .{ .unbuffered_writer = stdout };
var context = FileContext.init(buffered.writer());
for (options.calls) |call| switch (call) {
.file => |file| {
log.debug("calling file {s}", .{file});
try vm.callFile(gpa, file, *FileContext, &context);
if (!options.omit_trailing_newline) try context.stream.writeByte('\n');
},
.tag => |tag| {
log.debug("calling tag {s}", .{tag});
try vm.call(gpa, tag, *FileContext, &context);
},
};
try buffered.flush();
},
.find => for (options.calls) |call| switch (call) {
.file => unreachable, // not an option for find
.tag => |tag| {
log.debug("finding paths to tag {s}", .{tag});
for (vm.linker.files.keys()) |file| {
var context = FindContext.init(gpa, file, tag, stdout);
try vm.callFile(gpa, file, *FindContext, &context);
try context.stream.flush();
}
},
},
.graph => {
var context = GraphContext.init(gpa, stdout);
try context.begin(.{
.border = options.graph_border_colour,
.background = options.graph_background_colour,
.text = options.graph_text_colour,
.colours = options.graph_colours,
.inherit = options.graph_inherit_line_colour,
.gradient = options.graph_line_gradient,
});
if (options.calls.len != 0) {
for (options.calls) |call| switch (call) {
.tag => unreachable, // not an option for graph
.file => |file| {
log.debug("rendering graph for file {s}", .{file});
try vm.callFile(gpa, file, *GraphContext, &context);
},
};
} else {
for (vm.linker.files.keys()) |path| {
try vm.callFile(gpa, path, *GraphContext, &context);
}
for (vm.linker.procedures.keys()) |proc| {
if (!context.target.contains(proc.ptr)) {
try vm.call(gpa, proc, *GraphContext, &context);
}
}
}
try context.end();
},
.tangle => for (vm.linker.files.keys()) |path| {
const file = try createFile(path, options);
defer file.close();
var buffered: BufferedWriter = .{ .unbuffered_writer = file.writer() };
var context = FileContext.init(buffered.writer());
try vm.callFile(gpa, path, *FileContext, &context);
if (!options.omit_trailing_newline) try context.stream.writeByte('\n');
try buffered.flush();
},
.init => for (options.files) |path, index| {
try import(path, stdout);
if (index + 1 != options.files.len) try stdout.writeByte('\n');
},
}
}
fn createFile(path: []const u8, options: Options) !fs.File {
var tmp: [fs.MAX_PATH_BYTES]u8 = undefined;
var fba = std.heap.FixedBufferAllocator.init(&tmp);
var filename = path;
var absolute = false;
if (filename.len > 2 and mem.eql(u8, filename[0..2], "~/")) {
filename = try fs.path.join(fba.allocator(), &.{
os.getenv("HOME") orelse return error.@"unable to find ~/",
filename[2..],
});
}
if (path[0] == '/' or path[0] == '~') {
if (!options.allow_absolute_paths) {
return error.@"Absolute paths disabled; use --allow-absolute-paths to enable them.";
} else {
absolute = true;
}
}
if (fs.path.dirname(filename)) |dir| fs.cwd().makePath(dir) catch {};
if (absolute) {
log.warn("writing file with absolute path: {s}", .{filename});
} else {
log.info("writing file: {s}", .{filename});
}
return try fs.cwd().createFile(filename, .{ .truncate = true });
}
fn indent(reader: anytype, writer: anytype) !void {
var buffer: [1 << 12]u8 = undefined;
var nl = true;
while (true) {
const len = try reader.read(&buffer);
if (len == 0) return;
const slice = buffer[0..len];
var last: usize = 0;
while (mem.indexOfScalarPos(u8, slice, last, '\n')) |index| {
if (nl) try writer.writeAll(" ");
try writer.writeAll(slice[last..index]);
try writer.writeByte('\n');
nl = true;
last = index + 1;
} else if (slice[last..].len != 0) {
if (nl) try writer.writeAll(" ");
try writer.writeAll(slice[last..]);
nl = false;
}
}
}
test "indent text block" {
const source =
\\pub fn main() !void {
\\ return;
\\}
;
var buffer: [1024 * 4]u8 = undefined;
var in = io.fixedBufferStream(source);
var out = io.fixedBufferStream(&buffer);
try indent(in.reader(), out.writer());
try testing.expectEqualStrings(
\\ pub fn main() !void {
\\ return;
\\ }
, out.getWritten());
}
fn import(path: []const u8, writer: anytype) !void {
var file = try fs.cwd().openFile(path, .{});
defer file.close();
const last = mem.lastIndexOfScalar(u8, path, '/') orelse 0;
const lang = if (mem.lastIndexOfScalar(u8, path[last..], '.')) |index|
path[last + index + 1 ..]
else
"unknown";
var buffered = io.bufferedReader(file.reader());
var counting = io.countingWriter(writer);
try writer.writeByteNTimes('#', math.clamp(mem.count(u8, path[1..], "/"), 0, 5) + 1);
try writer.writeByte(' ');
try writer.writeAll(path);
try writer.writeAll(" \n\n ");
try counting.writer().print("lang: {s} esc: none file: {s}", .{ lang, path });
try writer.writeByte('\n');
try writer.writeAll(" ");
try writer.writeByteNTimes('-', counting.bytes_written);
try writer.writeAll("\n\n");
try indent(buffered.reader(), writer);
}
|
src/main.zig
|
const builtin = @import("builtin");
const std = @import("std");
const math = std.math;
const testing = @import("std").testing;
// mulo - multiplication overflow
// * return a*%b.
// * return if a*b overflows => 1 else => 0
// - mulo_genericSmall as default
// * optimized version with ca. 5% performance gain over muloXi4_genericSmall
// - mulo_genericFast for 2*bitsize <= usize
// * optimized version with ca. 5% performance gain over muloXi4_genericFast
fn ReturnType(comptime ST: type) type {
return struct {
sum: ST,
overflow: u8,
};
}
fn mulo_genericSmall(comptime ST: type) fn (ST, ST) ReturnType(ST) {
const RetType = ReturnType(ST);
return struct {
fn f(a: ST, b: ST) RetType {
@setRuntimeSafety(builtin.is_test);
var ret = RetType{
.sum = undefined,
.overflow = 0,
};
const min = math.minInt(ST);
ret.sum = a *% b;
if ((a < 0 and b == min) or (a != 0 and @divTrunc(ret.sum, a) != b))
ret.overflow = 1;
return ret;
}
}.f;
}
fn mulo_genericFast(comptime ST: type) fn (ST, ST) ReturnType(ST) {
const RetType = ReturnType(ST);
return struct {
fn f(a: ST, b: ST) RetType {
@setRuntimeSafety(builtin.is_test);
var ret = RetType{
.sum = undefined,
.overflow = 0,
};
const EST = switch (ST) {
i32 => i64,
i64 => i128,
i128 => i256,
else => unreachable,
};
const min = math.minInt(ST);
const max = math.maxInt(ST);
var res: EST = @as(EST, a) * @as(EST, b);
//invariant: -2^{bitwidth(EST)} < res < 2^{bitwidth(EST)-1}
if (res < min or max < res)
ret.overflow = 1;
ret.sum = @truncate(ST, res);
return ret;
}
}.f;
}
const mulosi = impl: {
if (2 * @bitSizeOf(i32) <= @bitSizeOf(usize)) {
break :impl mulo_genericFast(i32);
} else {
break :impl mulo_genericSmall(i32);
}
};
const mulodi = impl: {
if (2 * @bitSizeOf(i64) <= @bitSizeOf(usize)) {
break :impl mulo_genericFast(i64);
} else {
break :impl mulo_genericSmall(i64);
}
};
const muloti = impl: {
if (2 * @bitSizeOf(i64) <= @bitSizeOf(usize)) {
break :impl mulo_genericFast(i64);
} else {
break :impl mulo_genericSmall(i64);
}
};
test "mulo" {
const x: i32 = 0;
const y: i32 = 0;
const res = mulosi(x, y);
try testing.expectEqual(@as(i32, 0), res.sum);
try testing.expectEqual(@as(u8, 0), res.overflow);
}
|
src/crt/mulo_noptr.zig
|
const stdx = @import("stdx");
const Function = stdx.Function;
const graphics = @import("graphics");
const Color = graphics.Color;
const platform = @import("platform");
const ui = @import("../ui.zig");
const widgets = ui.widgets;
const Row = widgets.Row;
const Column = widgets.Column;
const Flex = widgets.Flex;
const Slider = widgets.Slider;
const Sized = widgets.Sized;
const MouseArea = widgets.MouseArea;
const Text = widgets.Text;
const TextButton = widgets.TextButton;
const Root = widgets.Root;
const Stretch = widgets.Stretch;
const log = stdx.log.scoped(.color_picker);
// TODO: Split this into ColorPicker and ColorPickerOption.
pub const ColorPicker = struct {
props: struct {
label: []const u8 = "Color",
init_val: Color = Color.White,
onPreviewChange: ?Function(fn (Color) void) = null,
onResult: ?Function(fn (color: Color, save: bool) void) = null,
},
color: Color,
slider: ui.WidgetRef(Slider),
preview: ui.WidgetRef(Sized),
root: *Root,
node: *ui.Node,
popover_inner: ui.WidgetRef(ColorPickerPopover),
popover: u32,
const Self = @This();
pub fn init(self: *Self, c: *ui.InitContext) void {
self.root = c.getRoot();
self.node = c.node;
self.color = self.props.init_val;
}
pub fn build(self: *Self, c: *ui.BuildContext) ui.FrameId {
const S = struct {
fn buildPopover(ptr: ?*anyopaque, c_: *ui.BuildContext) ui.FrameId {
const self_ = stdx.mem.ptrCastAlign(*Self, ptr);
return c_.decl(ColorPickerPopover, .{
.bind = &self_.popover_inner,
.init_val = self_.color,
.onPreviewChange = self_.props.onPreviewChange,
});
}
fn onPopoverClose(ptr: ?*anyopaque) void {
const self_ = stdx.mem.ptrCastAlign(*Self, ptr);
const inner = self_.popover_inner.getWidget();
if (inner.save_result) {
self_.color = inner.color;
}
if (self_.props.onResult) |cb| {
cb.call(.{ self_.color, inner.save_result });
}
}
fn onClick(self_: *Self, _: platform.MouseUpEvent) void {
self_.popover = self_.root.showPopover(self_.node, self_, buildPopover, .{
.close_ctx = self_,
.close_cb = onPopoverClose,
});
}
};
const d = c.decl;
return d(MouseArea, .{
.onClick = c.funcExt(self, S.onClick),
.child = d(Row, .{
.valign = .Center,
.children = c.list(.{
d(Flex, .{
.child = d(Text, .{
.text = self.props.label,
.color = Color.White,
}),
}),
d(Sized, .{
.bind = &self.preview,
.width = 30,
.height = 30,
}),
}),
}),
});
}
pub fn render(self: *Self, ctx: *ui.RenderContext) void {
const preview_alo = self.preview.getAbsLayout();
ctx.g.setFillColor(self.color);
ctx.g.fillRect(preview_alo.x, preview_alo.y, preview_alo.width, preview_alo.height);
}
};
const ColorPickerPopover = struct {
props: struct {
init_val: Color,
onPreviewChange: ?Function(fn (Color) void) = null,
},
palette: ui.WidgetRef(Stretch),
hue_slider: ui.WidgetRef(Slider),
save_result: bool,
color: Color,
palette_xratio: f32,
palette_yratio: f32,
hue: f32,
is_pressed: bool,
window: *ui.widgets.PopoverOverlay,
const Self = @This();
const ThumbRadius = 10;
pub fn init(self: *Self, c: *ui.InitContext) void {
self.color = self.props.init_val;
const hsv = self.color.toHsv();
self.hue = hsv[0];
self.palette_xratio = hsv[1];
self.palette_yratio = 1 - hsv[2];
self.save_result = false;
// Set custom post render over the popover window.
self.window = c.node.parent.?.getWidget(ui.widgets.PopoverOverlay);
self.window.custom_post_render = postPopoverRender;
self.window.custom_post_render_ctx = self;
c.addMouseDownHandler(self, onMouseDown);
c.addMouseUpHandler(self, onMouseUp);
}
fn onMouseUp(self: *Self, _: ui.MouseUpEvent) void {
self.is_pressed = false;
}
fn onMouseDown(self: *Self, e: ui.MouseDownEvent) ui.EventResult {
const xf = @intToFloat(f32, e.val.x);
const yf = @intToFloat(f32, e.val.y);
const palette_alo = self.palette.node.getAbsLayout();
if (palette_alo.contains(xf, yf)) {
e.ctx.requestFocus(onBlur);
self.is_pressed = true;
self.setMouseValue(e.val.x, e.val.y);
e.ctx.removeMouseMoveHandler(*Self, onMouseMove);
e.ctx.addMouseMoveHandler(self, onMouseMove);
}
return .Continue;
}
fn setMouseValue(self: *Self, x: i32, y: i32) void {
const xf = @intToFloat(f32, x);
const yf = @intToFloat(f32, y);
const palette_alo = self.palette.node.getAbsLayout();
self.palette_xratio = (xf - palette_alo.x) / palette_alo.width;
if (self.palette_xratio < 0) {
self.palette_xratio = 0;
} else if (self.palette_xratio > 1) {
self.palette_xratio = 1;
}
self.palette_yratio = (yf - palette_alo.y) / palette_alo.height;
if (self.palette_yratio < 0) {
self.palette_yratio = 0;
} else if (self.palette_yratio > 1) {
self.palette_yratio = 1;
}
self.color = Color.fromHsv(self.hue, self.palette_xratio, 1 - self.palette_yratio);
if (self.props.onPreviewChange) |cb| {
cb.call(.{ self.color });
}
}
fn onMouseMove(self: *Self, e: ui.MouseMoveEvent) void {
if (self.is_pressed) {
self.setMouseValue(e.val.x, e.val.y);
}
}
fn onBlur(_: *ui.Node, c: *ui.CommonContext) void {
// const self = node.getWidget(Self);
c.removeMouseMoveHandler(*Self, onMouseMove);
}
pub fn build(self: *Self, c: *ui.BuildContext) ui.FrameId {
const S = struct {
fn onClickSave(self_: *Self, _: platform.MouseUpEvent) void {
self_.save_result = true;
self_.window.requestClose();
}
fn onChangeHue(self_: *Self, hue: i32) void {
// Update color.
self_.hue = @intToFloat(f32, hue);
self_.color = Color.fromHsv(self_.hue, self_.palette_xratio, 1 - self_.palette_yratio);
if (self_.props.onPreviewChange) |cb| {
cb.call(.{ self_.color });
}
}
};
return c.decl(Sized, .{
.width = 200,
.child = c.decl(Column, .{
.expand = false,
.stretch_width = true,
.children = c.list(.{
c.decl(Stretch, .{
.method = .WidthAndKeepRatio,
.aspect_ratio = 1,
.bind = &self.palette,
}),
c.decl(Slider, .{
.min_val = 0,
.max_val = 360,
.init_val = @floatToInt(i32, self.hue),
.bind = &self.hue_slider,
.thumb_color = Color.Transparent,
.onChange = c.funcExt(self, S.onChangeHue),
}),
c.decl(TextButton, .{
.text = "Save",
.onClick = c.funcExt(self, S.onClickSave),
}),
}),
}),
});
}
fn getValue(self: Self) Color {
_ = self;
return Color.Red;
}
pub fn renderCustom(self: *Self, ctx: *ui.RenderContext) void {
// const alo = ctx.getAbsLayout();
const g = ctx.g;
// Render children so palette box resolves it's abs pos.
ctx.renderChildren();
// Draw custom slider bar.
const slider = self.hue_slider.getWidget();
const hue = @intToFloat(f32, slider.value);
const bar_layout = slider.getBarLayout();
const bar_x = slider.node.abs_pos.x + bar_layout.x;
const bar_y = slider.node.abs_pos.y + bar_layout.y;
const step = @as(f32, 1) / @as(f32, 6);
// 0 Red - 60 Yellow
g.setFillGradient(bar_x, bar_y, Color.StdRed, bar_x + bar_layout.width * step, bar_y, Color.StdYellow);
g.fillRect(bar_x, bar_y, bar_layout.width * step, bar_layout.height);
// 60 Yellow - 120 Green
g.setFillGradient(bar_x + bar_layout.width * step, bar_y, Color.StdYellow, bar_x + bar_layout.width * step * 2, bar_y, Color.StdGreen);
g.fillRect(bar_x + bar_layout.width * step, bar_y, bar_layout.width * step, bar_layout.height);
// 120 Green - 180 Cyan
g.setFillGradient(bar_x + bar_layout.width * step * 2, bar_y, Color.StdGreen, bar_x + bar_layout.width * step * 3, bar_y, Color.StdCyan);
g.fillRect(bar_x + bar_layout.width * step * 2, bar_y, bar_layout.width * step, bar_layout.height);
// 180 Cyan - 240 Blue
g.setFillGradient(bar_x + bar_layout.width * step * 3, bar_y, Color.StdCyan, bar_x + bar_layout.width * step * 4, bar_y, Color.StdBlue);
g.fillRect(bar_x + bar_layout.width * step * 3, bar_y, bar_layout.width * step, bar_layout.height);
// 240 Blue - 300 Magenta
g.setFillGradient(bar_x + bar_layout.width * step * 4, bar_y, Color.StdBlue, bar_x + bar_layout.width * step * 5, bar_y, Color.StdMagenta);
g.fillRect(bar_x + bar_layout.width * step * 4, bar_y, bar_layout.width * step, bar_layout.height);
// 300 Magenta - 360 Red
g.setFillGradient(bar_x + bar_layout.width * step * 5, bar_y, Color.StdMagenta, bar_x + bar_layout.width, bar_y, Color.StdRed);
g.fillRect(bar_x + bar_layout.width * step * 5, bar_y, bar_layout.width * step, bar_layout.height);
// Draw custom slider thumb.
const thumb_x = slider.node.abs_pos.x + slider.getThumbLayoutX();
const thumb_y = slider.node.abs_pos.y + bar_layout.y + bar_layout.height/2;
const slider_color = Color.fromHsv(hue, 1, 1);
g.setFillColor(slider_color);
g.fillCircle(thumb_x, thumb_y, ThumbRadius);
g.setStrokeColor(Color.White);
g.setLineWidth(2);
g.drawCircle(thumb_x, thumb_y, ThumbRadius);
// Draw the palette.
const palette_alo = self.palette.getAbsLayout();
g.setFillGradient(palette_alo.x, palette_alo.y, Color.White, palette_alo.x + palette_alo.width, palette_alo.y, slider_color);
g.fillRect(palette_alo.x, palette_alo.y, palette_alo.width, palette_alo.height);
g.setFillGradient(palette_alo.x, palette_alo.y, Color.Transparent, palette_alo.x, palette_alo.y + palette_alo.height, Color.Black);
g.fillRect(palette_alo.x, palette_alo.y, palette_alo.width, palette_alo.height);
}
fn postPopoverRender(ptr: ?*anyopaque, c: *ui.RenderContext) void {
const self = stdx.mem.ptrCastAlign(*Self, ptr);
const palette_alo = self.palette.getAbsLayout();
const g = c.g;
// Draw the palette cursor.
const cursor_x = palette_alo.x + palette_alo.width * self.palette_xratio;
const cursor_y = palette_alo.y + palette_alo.height * self.palette_yratio;
g.setFillColor(self.color);
g.fillCircle(cursor_x, cursor_y, ThumbRadius);
g.setStrokeColor(Color.White);
g.setLineWidth(2);
g.drawCircle(cursor_x, cursor_y, ThumbRadius);
}
};
|
ui/src/widgets/color_picker.zig
|
const cc_bake = @import("cc_bake");
const cc_gfx = @import("cc_gfx");
const cc_math = @import("cc_math");
const cc_res = @import("cc_res");
const cc_time = @import("cc_time");
const cc_wnd = @import("cc_wnd");
const cc_wnd_gfx = @import("cc_wnd_gfx");
const std = @import("std");
const Vertex = struct {
position: cc_math.F32x4,
color: cc_math.F32x4,
};
const Uniforms = struct {
mvp: cc_math.Mat,
};
const vertices: []const Vertex = &.{
// front
.{ .position = cc_math.f32x4(-1, -1, -1, 1), .color = cc_math.f32x4(1.0, 1.0, 1.0, 1) },
.{ .position = cc_math.f32x4(1, -1, -1, 1), .color = cc_math.f32x4(0.71, 1.0, 1.0, 1) },
.{ .position = cc_math.f32x4(-1, 1, -1, 1), .color = cc_math.f32x4(1.0, 0.71, 1.0, 1) },
.{ .position = cc_math.f32x4(1, 1, -1, 1), .color = cc_math.f32x4(0.71, 0.71, 1.0, 1) },
// back
.{ .position = cc_math.f32x4(-1, -1, 1, 1), .color = cc_math.f32x4(1.0, 1.0, 0.71, 1) },
.{ .position = cc_math.f32x4(1, -1, 1, 1), .color = cc_math.f32x4(0.71, 1.0, 0.71, 1) },
.{ .position = cc_math.f32x4(-1, 1, 1, 1), .color = cc_math.f32x4(1.0, 0.71, 0.71, 1) },
.{ .position = cc_math.f32x4(1, 1, 1, 1), .color = cc_math.f32x4(0.71, 0.71, 0.71, 1) },
};
const indices: []const u16 = &.{
0, 1, 2, 2, 1, 3, // front
2, 3, 6, 6, 3, 7, // top
1, 5, 3, 3, 5, 7, // right
4, 5, 0, 0, 5, 1, // bottom
4, 0, 6, 6, 0, 2, // left
5, 4, 7, 7, 4, 6, // back
};
const Example = struct {
window: cc_wnd.Window,
gctx: cc_gfx.Context,
vertex_buffer: cc_gfx.Buffer,
index_buffer: cc_gfx.Buffer,
uniform_buffer: cc_gfx.Buffer,
bind_group: cc_gfx.BindGroup,
render_pipeline: cc_gfx.RenderPipeline,
game_clock: cc_time.Timer,
};
pub fn init() !Example {
var window = try cc_wnd.Window.init(.{ .width = 800, .height = 600, .title = "cube" });
var gctx = try cc_gfx.Context.init(cc_wnd_gfx.getContextDesc(window));
const vertex_buffer = try gctx.device.initBufferSlice(vertices, .{ .vertex = true });
const index_buffer = try gctx.device.initBufferSlice(indices, .{ .index = true });
const uniform_buffer = try gctx.device.initBuffer(.{
.size = @sizeOf(Uniforms),
.usage = .{ .uniform = true, .copy_dst = true },
});
var bind_group_layout = try gctx.device.initBindGroupLayout(.{
.entries = &.{.{
.binding = 0,
.visibility = .{ .vertex = true },
.buffer = .{},
}},
});
defer gctx.device.deinitBindGroupLayout(&bind_group_layout);
const bind_group = try gctx.device.initBindGroup(.{
.layout = &bind_group_layout,
// todo: zig #7607
.entries = &[_]cc_gfx.BindGroupEntry{.{
.binding = 0,
.resource = .{ .buffer_binding = .{ .buffer = &uniform_buffer } },
}},
});
var pipeline_layout = try gctx.device.initPipelineLayout(
.{ .bind_group_layouts = &.{bind_group_layout} },
);
defer gctx.device.deinitPipelineLayout(&pipeline_layout);
const vert_shader_bake = try cc_res.load(cc_bake.cube_vert_shader, .{});
var vert_shader = try gctx.device.initShader(vert_shader_bake.bytes);
defer gctx.device.deinitShader(&vert_shader);
const frag_shader_bake = try cc_res.load(cc_bake.cube_frag_shader, .{});
var frag_shader = try gctx.device.initShader(frag_shader_bake.bytes);
defer gctx.device.deinitShader(&frag_shader);
var render_pipeline_desc = cc_gfx.RenderPipelineDesc{};
render_pipeline_desc.setPipelineLayout(&pipeline_layout);
render_pipeline_desc.setVertexState(.{
.module = &vert_shader,
.entry_point = "vs_main",
// todo: zig #7607
.buffers = &[_]cc_gfx.VertexBufferLayout{
cc_gfx.getVertexBufferLayoutStruct(Vertex, .vertex, 0),
},
});
render_pipeline_desc.setPrimitiveState(.{ .cull_mode = .back });
render_pipeline_desc.setDepthStencilState(.{
.format = gctx.depth_texture_format,
.depth_write_enabled = true,
.depth_compare = .less,
});
render_pipeline_desc.setFragmentState(.{
.module = &frag_shader,
.entry_point = "fs_main",
// todo: zig #7607
.targets = &[_]cc_gfx.ColorTargetState{.{ .format = gctx.swapchain_format }},
});
const render_pipeline = try gctx.device.initRenderPipeline(render_pipeline_desc);
const game_clock = try cc_time.Timer.start();
return Example{
.window = window,
.gctx = gctx,
.vertex_buffer = vertex_buffer,
.index_buffer = index_buffer,
.uniform_buffer = uniform_buffer,
.bind_group = bind_group,
.render_pipeline = render_pipeline,
.game_clock = game_clock,
};
}
pub fn loop(ex: *Example) !void {
if (!ex.window.isVisible()) {
return;
}
const time = ex.game_clock.readSeconds();
const model_matrix = cc_math.matFromAxisAngle(
cc_math.f32x4(cc_math.sin(time), cc_math.cos(time), 0.0, 0.0),
1.0,
);
const view_matrix = cc_math.lookToLh(
cc_math.f32x4(0, 0, -4, 0),
cc_math.f32x4(0, 0, 1, 0),
cc_math.f32x4(0, 1, 0, 0),
);
const proj_matrix = cc_math.perspectiveFovLh(
2.0 * std.math.pi / 5.0,
ex.window.getAspectRatio(),
1,
100,
);
const mvp_matrix = cc_math.mul(cc_math.mul(model_matrix, view_matrix), proj_matrix);
const uniforms = Uniforms{ .mvp = cc_math.transpose(mvp_matrix) };
var queue = ex.gctx.device.getQueue();
try queue.writeBuffer(&ex.uniform_buffer, 0, std.mem.asBytes(&uniforms), 0);
const swapchain_view = try ex.gctx.swapchain.getCurrentTextureView();
var command_encoder = try ex.gctx.device.initCommandEncoder();
var render_pass_desc = cc_gfx.RenderPassDesc{};
// todo: zig #7607
render_pass_desc.setColorAttachments(&[_]cc_gfx.ColorAttachment{.{
.view = &swapchain_view,
.load_op = .clear,
.clear_value = ex.gctx.clear_color,
.store_op = .store,
}});
render_pass_desc.setDepthStencilAttachment(.{
.view = &ex.gctx.depth_texture_view,
.depth_clear_value = 1.0,
.depth_load_op = .clear,
.depth_store_op = .store,
});
var render_pass = try command_encoder.beginRenderPass(render_pass_desc);
try render_pass.setPipeline(&ex.render_pipeline);
try render_pass.setBindGroup(0, &ex.bind_group, null);
try render_pass.setVertexBuffer(0, &ex.vertex_buffer, 0, cc_gfx.whole_size);
try render_pass.setIndexBuffer(&ex.index_buffer, .uint16, 0, cc_gfx.whole_size);
try render_pass.drawIndexed(indices.len, 1, 0, 0, 0);
try render_pass.end();
try queue.submit(&.{try command_encoder.finish()});
try ex.gctx.swapchain.present();
}
pub fn deinit(ex: *Example) !void {
ex.gctx.device.deinitRenderPipeline(&ex.render_pipeline);
ex.gctx.device.deinitBindGroup(&ex.bind_group);
ex.gctx.device.deinitBuffer(&ex.uniform_buffer);
ex.gctx.device.deinitBuffer(&ex.index_buffer);
ex.gctx.device.deinitBuffer(&ex.vertex_buffer);
ex.gctx.deinit();
ex.window.deinit();
}
|
ex/cube/cube.zig
|
const std = @import("std");
pub const Colorspace = enum { RGB, RGBA };
/// 8-bit sRGB color with transparency as 32 bits ordered RGBA
pub const Color = packed struct {
red: u8,
green: u8,
blue: u8,
alpha: u8 = 255,
pub const black = Color.comptimeFromString("#000000");
pub const red = Color.comptimeFromString("#ff0000");
pub const green = Color.comptimeFromString("#00ff00");
pub const blue = Color.comptimeFromString("#0000ff");
pub const yellow = Color.comptimeFromString("#ffff00");
pub const white = Color.comptimeFromString("#ffffff");
pub const transparent = Color.comptimeFromString("#00000000");
pub fn fromString(string: []const u8) !Color {
if (string.len != 7 and string.len != 9) {
return error.InvalidLength;
}
if (string[0] != '#') {
return error.NotSupported;
}
const r = try std.fmt.parseInt(u8, string[1..3], 16);
const g = try std.fmt.parseInt(u8, string[3..5], 16);
const b = try std.fmt.parseInt(u8, string[5..7], 16);
var a: u8 = 255;
if (string.len == 9) {
a = try std.fmt.parseInt(u8, string[7..9], 16);
}
return Color{ .red = r, .green = g, .blue = b, .alpha = a };
}
pub fn comptimeFromString(comptime string: []const u8) Color {
return comptime fromString(string) catch |err| @compileError(@errorName(err));
}
fn lerpByte(a: u8, b: u8, t: f64) u8 {
return @floatToInt(u8, @intToFloat(f64, a) * (1 - t) + @intToFloat(f64, b) * t);
}
pub fn lerp(a: Color, b: Color, t: f64) Color {
return Color{
.red = lerpByte(a.red, b.red, t),
.green = lerpByte(a.green, b.green, t),
.blue = lerpByte(a.blue, b.blue, t),
.alpha = lerpByte(a.alpha, b.alpha, t),
};
}
pub fn toBytes(self: Color, dest: []u8) void {
std.mem.bytesAsSlice(Color, dest).* = self;
}
};
const expectEqual = std.testing.expectEqual;
test "color parse" {
const color = try Color.fromString("#2d4a3b");
try expectEqual(@as(u8, 0x2d), color.red);
try expectEqual(@as(u8, 0x4a), color.green);
try expectEqual(@as(u8, 0x3b), color.blue);
try expectEqual(@as(u8, 0xff), color.alpha);
const color2 = try Color.fromString("#a13d4c89");
try expectEqual(@as(u8, 0xa1), color2.red);
try expectEqual(@as(u8, 0x3d), color2.green);
try expectEqual(@as(u8, 0x4c), color2.blue);
try expectEqual(@as(u8, 0x89), color2.alpha);
}
test "comptime color parse" {
const color = Color.comptimeFromString("#3b2d4a");
try expectEqual(@as(u8, 0x3b), color.red);
try expectEqual(@as(u8, 0x2d), color.green);
try expectEqual(@as(u8, 0x4a), color.blue);
try expectEqual(@as(u8, 0xff), color.alpha);
const color2 = Color.comptimeFromString("#98a3cdef");
try expectEqual(@as(u8, 0x98), color2.red);
try expectEqual(@as(u8, 0xa3), color2.green);
try expectEqual(@as(u8, 0xcd), color2.blue);
try expectEqual(@as(u8, 0xef), color2.alpha);
}
test "color linear interpolation" {
const a = Color.comptimeFromString("#00ff8844");
const b = Color.comptimeFromString("#88888888");
try expectEqual(Color.lerp(a, b, 0.5), Color.lerp(b, a, 0.5));
try expectEqual(Color.lerp(a, b, 0.75), Color.lerp(b, a, 0.25));
try expectEqual(Color.lerp(a, b, 1.0), Color.lerp(b, a, 0.0));
const result = Color.lerp(a, b, 0.5);
try expectEqual(@as(u8, 0x44), result.red);
try expectEqual(@as(u8, 0xc3), result.green);
try expectEqual(@as(u8, 0x88), result.blue);
try expectEqual(@as(u8, 0x66), result.alpha);
}
|
src/color.zig
|
const std = @import("std");
const aoc = @import("aoc-lib.zig");
const SFDigit = struct {
n: u16,
depth: u8,
};
const SFNum = struct {
const TQ = std.TailQueue(*SFDigit);
nums: std.TailQueue(*SFDigit),
alloc: std.mem.Allocator,
pub fn fromInput(alloc: std.mem.Allocator, inp: []const u8) !*SFNum {
var sf = try alloc.create(SFNum);
sf.alloc = alloc;
var nums = TQ{};
var depth: u8 = 0;
var i: usize = 0;
while (i < inp.len) : (i += 1) {
var ch = inp[i];
switch (ch) {
'[' => {
depth += 1;
},
']' => {
depth -= 1;
},
',' => {},
else => {
var digit = try alloc.create(SFDigit);
digit.n = ch - '0';
if ('0' <= inp[i + 1] and inp[i + 1] <= '9') {
digit.n = 10 * digit.n + (inp[i + 1] - '0');
i += 1;
}
digit.depth = depth;
var node = try alloc.create(TQ.Node);
node.data = digit;
nums.append(node);
},
}
}
sf.nums = nums;
return sf;
}
pub fn deinit(self: *SFNum) void {
var it = self.nums.first;
while (it) |node| {
var next = node.next;
self.alloc.destroy(node.data);
self.alloc.destroy(node);
it = next;
}
self.alloc.destroy(self);
}
pub fn clone(self: *SFNum) !*SFNum {
var alloc = self.alloc;
var sf = try alloc.create(SFNum);
sf.alloc = alloc;
var nums = TQ{};
var it = self.nums.first;
while (it) |node| : (it = node.next) {
var digit = try alloc.create(SFDigit);
digit.n = node.data.n;
digit.depth = node.data.depth;
var newNode = try alloc.create(TQ.Node);
newNode.data = digit;
nums.append(newNode);
}
sf.nums = nums;
return sf;
}
pub fn split(self: *SFNum) !bool {
var it = self.nums.first;
while (it) |node| : (it = node.next) {
if (node.data.n <= 9) {
continue;
}
//aoc.print("spliting [{}@{}]\n", .{ node.data.n, node.data.depth }) catch unreachable;
var down = node.data.n / 2;
var up = node.data.n - down;
node.data.n = down;
node.data.depth += 1;
var digit = try self.alloc.create(SFDigit);
digit.n = up;
digit.depth = node.data.depth;
var newNode = try self.alloc.create(TQ.Node);
newNode.data = digit;
self.nums.insertAfter(node, newNode);
return true;
}
return false;
}
pub fn explode(sf: *SFNum) !bool {
var it = sf.nums.first;
while (it) |node| : (it = node.next) {
if (node.data.depth < 5) {
continue;
}
var second = node.next orelse continue;
if (second.data.depth != node.data.depth) {
continue;
}
//aoc.print("exploding [{}@{}] and [{}@{}]\n", .{ node.data.n, node.data.depth, second.data.n, second.data.depth }) catch unreachable;
if (node.prev) |prev| {
prev.data.n += node.data.n;
}
if (second.next) |next| {
next.data.n += second.data.n;
}
node.data.n = 0;
node.data.depth -= 1;
sf.nums.remove(second);
sf.alloc.destroy(second.data);
sf.alloc.destroy(second);
return true;
}
return false;
}
pub fn reduce(sf: *SFNum) !void {
while (true) {
if (try sf.explode()) {
continue;
}
if (try sf.split()) {
continue;
}
return;
}
}
pub fn add(sf: *SFNum, osf: *SFNum) !void {
sf.nums.concatByMoving(&osf.nums);
var it = sf.nums.first;
while (it) |node| : (it = node.next) {
node.data.depth += 1;
}
try sf.reduce();
}
pub fn dump(sf: *SFNum) void {
var it = sf.nums.first;
while (it) |node| : (it = node.next) {
aoc.print("[{} @ {}] ", .{ node.data.n, node.data.depth }) catch unreachable;
}
aoc.print("\n", .{}) catch unreachable;
}
pub fn magnitude(sf: *SFNum) usize {
while (sf.nums.first.? != sf.nums.last.?) {
var first = sf.nums.first.?;
var second = first.next.?;
while (first.data.depth != second.data.depth) {
//aoc.print("checking [{},{}] and [{},{}]\n", .{ first.data.depth, first.data.n, second.data.depth, second.data.n }) catch unreachable;
first = second;
second = second.next.?;
}
var mag = 3 * first.data.n + 2 * second.data.n;
//aoc.print("found {} and {} => {}\n", .{ first.data.n, second.data.n, mag }) catch unreachable;
first.data.n = mag;
first.data.depth -= 1;
sf.nums.remove(second);
sf.alloc.destroy(second.data);
sf.alloc.destroy(second);
}
return sf.nums.first.?.data.n;
}
};
test "magnitude" {
const TestCase = struct {
data: []const u8,
mag: usize,
};
var tests = [_]TestCase{
TestCase{ .data = "[9,1]", .mag = 29 },
TestCase{ .data = "[1,9]", .mag = 21 },
TestCase{ .data = "[[9,1],[1,9]]", .mag = 129 },
TestCase{ .data = "[[1,2],[[3,4],5]]", .mag = 143 },
TestCase{ .data = "[[[[0,7],4],[[7,8],[6,0]]],[8,1]]", .mag = 1384 },
TestCase{ .data = "[[[[1,1],[2,2]],[3,3]],[4,4]]", .mag = 445 },
TestCase{ .data = "[[[[3,0],[5,3]],[4,4]],[5,5]]", .mag = 791 },
TestCase{ .data = "[[[[5,0],[7,4]],[5,5]],[6,6]]", .mag = 1137 },
TestCase{ .data = "[[[[8,7],[7,7]],[[8,6],[7,7]]],[[[0,7],[6,6]],[8,7]]]", .mag = 3488 },
TestCase{ .data = "[[[[6,6],[7,6]],[[7,7],[7,0]]],[[[7,7],[7,7]],[[7,8],[9,9]]]]", .mag = 4140 },
};
for (tests) |tc| {
var mt = try SFNum.fromInput(aoc.talloc, tc.data);
defer mt.deinit();
try aoc.print("testing {s}\n", .{tc.data});
try aoc.assertEq(tc.mag, mt.magnitude());
}
}
test "explode" {
const TestCase = struct {
data: []const u8,
mag: usize,
};
var tests = [_]TestCase{
TestCase{ .data = "[[[[[9,8],1],2],3],4]", .mag = 548 },
TestCase{ .data = "[7,[6,[5,[4,[3,2]]]]]", .mag = 285 },
TestCase{ .data = "[[6,[5,[4,[3,2]]]],1]", .mag = 402 },
TestCase{ .data = "[[3,[2,[1,[7,3]]]],[6,[5,[4,[3,2]]]]]", .mag = 769 },
TestCase{ .data = "[[3,[2,[8,0]]],[9,[5,[4,[3,2]]]]]", .mag = 633 },
};
for (tests) |tc| {
var mt = try SFNum.fromInput(aoc.talloc, tc.data);
defer mt.deinit();
mt.dump();
try aoc.assertEq(true, try mt.explode());
mt.dump();
try aoc.assertEq(tc.mag, mt.magnitude());
}
}
test "split" {
const TestCase = struct {
data: []const u8,
mag: usize,
};
var tests = [_]TestCase{
TestCase{ .data = "[[[[0,7],4],[15,[0,13]]],[1,1]]", .mag = 1438 },
TestCase{ .data = "[[[[0,7],4],[[7,8],[0,13]]],[1,1]]", .mag = 1894 },
};
for (tests) |tc| {
var mt = try SFNum.fromInput(aoc.talloc, tc.data);
defer mt.deinit();
try aoc.assertEq(true, try mt.split());
try aoc.assertEq(tc.mag, mt.magnitude());
}
}
test "add" {
const TestCase = struct {
sf1: []const u8,
sf2: []const u8,
mag: usize,
};
var tests = [_]TestCase{
TestCase{
.sf1 = "[[[0,[4,5]],[0,0]],[[[4,5],[2,6]],[9,5]]]",
.sf2 = "[7,[[[3,7],[4,3]],[[6,3],[8,8]]]]",
.mag = 2736,
},
TestCase{
.sf1 = "[[[[4,0],[5,4]],[[7,7],[6,0]]],[[8,[7,7]],[[7,9],[5,0]]]]",
.sf2 = "[[2,[[0,8],[3,4]]],[[[6,7],1],[7,[1,6]]]]",
.mag = 4014,
},
TestCase{
.sf1 = "[[[[6,7],[6,7]],[[7,7],[0,7]]],[[[8,7],[7,7]],[[8,8],[8,0]]]]",
.sf2 = "[[[[2,4],7],[6,[0,5]]],[[[6,8],[2,8]],[[2,1],[4,5]]]]",
.mag = 4105,
},
TestCase{
.sf1 = "[[[[7,0],[7,7]],[[7,7],[7,8]]],[[[7,7],[8,8]],[[7,7],[8,7]]]]",
.sf2 = "[7,[5,[[3,8],[1,4]]]]",
.mag = 4293,
},
};
for (tests) |tc| {
var sf1 = try SFNum.fromInput(aoc.talloc, tc.sf1);
defer sf1.deinit();
var sf2 = try SFNum.fromInput(aoc.talloc, tc.sf2);
defer sf2.deinit();
try sf1.add(sf2);
try aoc.assertEq(tc.mag, sf1.magnitude());
}
}
test "parts" {
const TestCase = struct {
file: []const u8,
res: [2]usize,
};
var tests = [_]TestCase{
TestCase{ .file = aoc.test0file, .res = [2]usize{ 3488, 3805 } },
TestCase{ .file = aoc.test1file, .res = [2]usize{ 4140, 3993 } },
TestCase{ .file = aoc.inputfile, .res = [2]usize{ 3987, 4500 } },
};
for (tests) |tc| {
var res = try parts(aoc.talloc, tc.file);
try aoc.assertEq(tc.res, res);
}
}
fn parts(alloc: std.mem.Allocator, inp: []const u8) ![2]usize {
var sfs = std.ArrayList(*SFNum).init(alloc);
defer {
for (sfs.items) |it| {
it.deinit();
}
sfs.deinit();
}
var it = std.mem.tokenize(u8, inp, "\n");
while (it.next()) |line| {
if (line.len == 0) {
break;
}
try sfs.append(try SFNum.fromInput(alloc, line));
}
var i: usize = 1;
var sf = try sfs.items[0].clone();
defer sf.deinit();
while (i < sfs.items.len) : (i += 1) {
var o = try sfs.items[i].clone();
defer o.deinit();
try sf.add(o);
}
var p1 = sf.magnitude();
var p2: usize = 0;
i = 0;
while (i < sfs.items.len) : (i += 1) {
var j = i + 1;
while (j < sfs.items.len) : (j += 1) {
var ab = try sfs.items[i].clone();
defer ab.deinit();
var b = try sfs.items[j].clone();
defer b.deinit();
try ab.add(b);
var mag = ab.magnitude();
if (mag > p2) {
p2 = mag;
}
var ba = try sfs.items[j].clone();
defer ba.deinit();
var a = try sfs.items[i].clone();
defer a.deinit();
try ba.add(a);
mag = ba.magnitude();
if (mag > p2) {
p2 = mag;
}
}
}
return [2]usize{ p1, p2 };
}
var buf: [20 * 1024 * 1024]u8 = undefined;
fn day(inp: []const u8, bench: bool) anyerror!void {
var alloc = std.heap.FixedBufferAllocator.init(&buf);
var p = try parts(alloc.allocator(), inp);
if (!bench) {
try aoc.print("Part 1: {}\nPart 2: {}\n", .{ p[0], p[1] });
}
}
pub fn main() anyerror!void {
try aoc.benchme(aoc.input(), day);
}
|
2021/18/aoc.zig
|
const std = @import("std");
const aoc = @import("aoc-lib.zig");
test "examples" {
const test1 = aoc.readLines(aoc.talloc, aoc.test1file);
defer aoc.talloc.free(test1);
const test2 = aoc.readLines(aoc.talloc, aoc.test2file);
defer aoc.talloc.free(test2);
const inp = aoc.readLines(aoc.talloc, aoc.inputfile);
defer aoc.talloc.free(inp);
var map = Map.fromInput(aoc.talloc, test1) catch unreachable;
try aoc.assertEq(@as(usize, 71), map.RunOnce(4, false));
try aoc.assertEq(@as(usize, 20), map.RunOnce(4, false));
map.deinit();
map = Map.fromInput(aoc.talloc, test2) catch unreachable;
try aoc.assertEq(@as(usize, 29), map.RunOnce(4, false));
map.deinit();
map = Map.fromInput(aoc.talloc, inp) catch unreachable;
defer map.deinit();
try aoc.assertEq(@as(usize, 7906), map.RunOnce(4, false));
try aoc.assertEq(@as(usize, 148), map.RunOnce(4, false));
try aoc.assertEq(@as(usize, 37), part1(aoc.talloc, test1));
try aoc.assertEq(@as(usize, 26), part2(aoc.talloc, test1));
try aoc.assertEq(@as(usize, 2481), part1(aoc.talloc, inp));
try aoc.assertEq(@as(usize, 2227), part2(aoc.talloc, inp));
}
const Map = struct {
pub const SeatState = enum(u8) { empty, occupied, none, none_outside };
pub const NeighbourOffsets = [8][2]isize{
[2]isize{ -1, -1 }, [2]isize{ 0, -1 }, [2]isize{ 1, -1 },
[2]isize{ -1, 0 }, [2]isize{ 1, 0 }, [2]isize{ -1, 1 },
[2]isize{ 0, 1 }, [2]isize{ 1, 1 },
};
h: usize,
w: usize,
map: []SeatState,
new: []SeatState,
changes: usize,
alloc: std.mem.Allocator,
pub fn fromInput(alloc: std.mem.Allocator, inp: [][]const u8) !*Map {
var h = inp.len;
var w = inp[0].len;
var map = try alloc.alloc(SeatState, h * w);
var new = try alloc.alloc(SeatState, h * w);
var m = try alloc.create(Map);
m.map = map;
m.new = new;
m.h = h;
m.w = w;
m.alloc = alloc;
for (inp) |line, y| {
for (line) |s, x| {
if (s == 'L') {
map[y * w + x] = .empty;
} else if (s == '#') {
map[y * w + x] = .occupied;
} else {
map[y * w + x] = .none;
new[y * w + x] = .none;
}
}
}
return m;
}
pub fn deinit(self: *Map) void {
self.alloc.free(self.map);
self.alloc.free(self.new);
self.alloc.destroy(self);
}
pub fn SetSeat(self: *Map, x: isize, y: isize, state: SeatState) void {
self.new[std.math.absCast(y) * self.w + std.math.absCast(x)] = state;
}
pub fn Swap(self: *Map) void {
const tmp = self.map;
self.map = self.new;
self.new = tmp;
}
pub fn Seat(self: *Map, x: isize, y: isize) SeatState {
if (x < 0 or x > self.w - 1 or y < 0 or y > self.h - 1) {
return .none_outside;
}
return self.map[std.math.absCast(y) * self.w + std.math.absCast(x)];
}
pub fn Next(self: *Map, x: isize, y: isize, group: usize, sight: bool) SeatState {
var oc: usize = 0;
for (Map.NeighbourOffsets) |o| {
var ox = x;
var oy = y;
while (true) {
ox += o[0];
oy += o[1];
var ns = self.Seat(ox, oy);
if (ns == .occupied) {
oc += 1;
}
if (ns != .none or !sight) {
break;
}
}
}
var n = self.Seat(x, y);
if (n == .empty and oc == 0) {
n = .occupied;
} else if (n == .occupied and oc >= group) {
n = .empty;
}
return n;
}
pub fn Print(self: *Map) void {
var y: isize = 0;
while (y < self.h) : (y += 1) {
var x: isize = 0;
while (x < self.w) : (x += 1) {
switch (self.Seat(x, y)) {
.empty => {
aoc.print("{}", .{"L"}) catch unreachable;
},
.occupied => {
aoc.print("{}", .{"#"}) catch unreachable;
},
else => {
aoc.print("{}", .{"."}) catch unreachable;
},
}
}
aoc.print("\n", .{}) catch unreachable;
}
}
pub fn RunOnce(self: *Map, group: usize, sight: bool) usize {
self.changes = 0;
var oc: usize = 0;
var x: isize = 0;
while (x < self.w) : (x += 1) {
var y: isize = 0;
while (y < self.h) : (y += 1) {
var cur = self.Seat(x, y);
if (cur == .none) {
continue;
}
var new = self.Next(x, y, group, sight);
self.SetSeat(x, y, new);
if (cur != new) {
self.changes += 1;
}
if (new == .occupied) {
oc += 1;
}
}
}
self.Swap();
return oc;
}
pub fn Run(self: *Map, group: usize, sight: bool) usize {
while (true) {
var oc = self.RunOnce(group, sight);
if (self.changes == 0) {
return oc;
}
}
return 0;
}
};
fn part1(alloc: std.mem.Allocator, in: [][]const u8) usize {
var map = Map.fromInput(alloc, in) catch unreachable;
defer map.deinit();
return map.Run(4, false);
}
fn part2(alloc: std.mem.Allocator, in: [][]const u8) usize {
var map = Map.fromInput(alloc, in) catch unreachable;
defer map.deinit();
return map.Run(5, true);
}
fn day11(inp: []const u8, bench: bool) anyerror!void {
const lines = aoc.readLines(aoc.halloc, inp);
defer aoc.halloc.free(lines);
var p1 = part1(aoc.halloc, lines);
var p2 = part2(aoc.halloc, lines);
if (!bench) {
try aoc.print("Part 1: {}\nPart 2: {}\n", .{ p1, p2 });
}
}
pub fn main() anyerror!void {
try aoc.benchme(aoc.input(), day11);
}
|
2020/11/aoc.zig
|
const GBA = @import("core.zig").GBA;
const BIOS = @import("bios.zig").BIOS;
pub const OAM = struct {
pub const ObjMode = enum(u2) {
Normal,
SemiTransparent,
ObjWindow,
};
pub const FlipSettings = packed struct {
dummy: u3 = 0,
horizontalFlip: u1 = 0,
verticalFlip: u1 = 0,
};
pub const ObjectSize = enum {
Size8x8,
Size16x8,
Size8x16,
Size16x16,
Size32x8,
Size8x32,
Size32x32,
Size32x16,
Size16x32,
Size64x64,
Size64x32,
Size32x64,
};
pub const ObjectShape = enum(u2) {
Square,
Horizontal,
Vertical,
};
pub const ObjectAttribute = packed struct {
y: u8 = 0,
rotationScaling: bool = false,
doubleSizeOrHidden: bool = true,
mode: ObjMode = .Normal,
mosaic: bool = false,
paletteMode: GBA.PaletteMode = .Color16,
shape: ObjectShape = .Square,
x: u9 = 0,
flip: FlipSettings = FlipSettings{},
size: u2 = 0,
tileIndex: u10 = 0,
priority: u2 = 0,
palette: u4 = 0,
dummy: i16 = 0,
const Self = @This();
pub fn setSize(self: *Self, size: ObjectSize) void {
switch (size) {
.Size8x8 => {
self.shape = .Square;
self.size = 0;
},
.Size16x8 => {
self.shape = .Horizontal;
self.size = 0;
},
.Size8x16 => {
self.shape = .Vertical;
self.size = 0;
},
.Size16x16 => {
self.shape = .Square;
self.size = 1;
},
.Size32x8 => {
self.shape = .Horizontal;
self.size = 1;
},
.Size8x32 => {
self.shape = .Vertical;
self.size = 1;
},
.Size32x32 => {
self.shape = .Square;
self.size = 2;
},
.Size32x16 => {
self.shape = .Horizontal;
self.size = 2;
},
.Size16x32 => {
self.shape = .Vertical;
self.size = 2;
},
.Size64x64 => {
self.shape = .Square;
self.size = 3;
},
.Size64x32 => {
self.shape = .Horizontal;
self.size = 3;
},
.Size32x64 => {
self.shape = .Vertical;
self.size = 3;
},
}
}
pub fn setRotationParameterIndex(self: *Self, index: u32) callconv(.Inline) void {
self.flip = @bitCast(FlipSettings, @intCast(u5, index));
}
pub fn setTileIndex(self: *Self, tileIndex: i32) callconv(.Inline) void {
@setRuntimeSafety(false);
self.tileIndex = @intCast(u10, tileIndex);
}
pub fn setPaletteIndex(self: *Self, palette: i32) callconv(.Inline) void {
self.palette = @intCast(u4, palette);
}
pub fn setPosition(self: *Self, x: i32, y: i32) callconv(.Inline) void {
@setRuntimeSafety(false);
self.x = @intCast(u9, x);
self.y = @intCast(u8, y);
}
pub fn getAffine(self: Self) *Affine {
const affine_index = @bitCast(u5, self.flip);
return &affineBuffer[affine_index];
}
};
pub const AffineAttribute = packed struct {
fill0: [3]u16,
pa: i16,
fill1: [3]u16,
pb: i16,
fill2: [3]u16,
pc: i16,
fill3: [3]u16,
pd: i16,
};
pub const AffineTransform = packed struct {
pa: i16,
pb: i16,
pc: i16,
pd: i16,
const Self = @This();
pub fn setIdentity(self: *Self) void {
self.pa = 0x0100;
self.pb = 0;
self.pc = 0;
self.pd = 0x0100;
}
pub fn identity() Self {
return Self {
.pa = 0x0100,
.pb = 0,
.pc = 0,
.pd = 0x0100,
};
}
};
const OAMAttributePtr = @ptrCast([*]align(4) volatile ObjectAttribute, GBA.OAM);
const OAMAttribute = OAMAttributePtr[0..128];
var attributeBuffer = init: {
var initial_array: [128]ObjectAttribute = undefined;
for (initial_array) |*object_attribute| {
object_attribute.* = ObjectAttribute{};
}
break :init initial_array;
};
var currentAttribute: usize = 0;
const affineBufferPtr = @ptrCast([*]align(4) AffineAttribute, &attributeBuffer);
const affineBuffer = affineBufferPtr[0..32];
var currentAffine: usize = 0;
fn copyAttributeBufferToOAM() void {
const word_count = @sizeOf(@TypeOf(attributeBuffer)) / 4;
BIOS.cpuFastSet(@ptrCast(*u32, &attributeBuffer[0]), @ptrCast(*u32, &OAMAttribute[0]), .{.wordCount = word_count, .fixedSourceAddress = BIOS.CpuFastSetMode.Copy});
}
pub fn init() void {
for (attributeBuffer) |*attribute, index| {
GBA.memcpy32(&OAMAttribute[index], attribute, @sizeOf(ObjectAttribute));
}
}
pub fn allocateAttribute() *ObjectAttribute {
var result = &attributeBuffer[currentAttribute];
currentAttribute += 1;
return result;
}
pub fn allocateAffine() *AffineAttribute {
var result = &affineBuffer[currentAffine];
currentAffine += 1;
return result;
}
pub fn update() void {
copyAttributeBufferToOAM();
var index: usize = 0;
while (index < currentAttribute) : (index += 1) {
attributeBuffer[index].doubleSizeOrHidden = true;
}
currentAttribute = 0;
currentAffine = 0;
}
fn allocateAndInitNormalSprite(tile_index: i32, size: ObjectSize, palette_index: i32, x: i32, y: i32, priority: u2, horizontal_flip: u1, vertical_flip: u1) *OAM.ObjectAttribute {
var sprite_attribute: *OAM.ObjectAttribute = allocateAttribute();
sprite_attribute.doubleSizeOrHidden = false;
sprite_attribute.setTileIndex(tile_index);
sprite_attribute.setSize(size);
sprite_attribute.setPaletteIndex(palette_index);
sprite_attribute.setPosition(x,y);
sprite_attribute.priority = priority;
sprite_attribute.flip.horizontalFlip = horizontal_flip;
sprite_attribute.flip.verticalFlip = vertical_flip;
return sprite_attribute;
}
pub fn addNormalSprite(tile_index: i32, size: ObjectSize, palette_index: i32, x: i32, y: i32, priority: u2, horizontal_flip: u1, vertical_flip: u1) void {
_ = allocateAndInitNormalSprite(tile_index, size, palette_index, x, y, priority, horizontal_flip, vertical_flip);
}
pub fn addAffineSprite(tile_index: i32, size: ObjectSize, palette_index: i32, x: i32, y: i32, priority: u2, horizontal_flip: u1, vertical_flip: u1, transform: AffineTransform, double_size: bool) void {
var sprite_attribute = allocateAndInitNormalSprite(tile_index, size, palette_index, x, y, priority, horizontal_flip, vertical_flip);
sprite_attribute.rotationScaling = true;
sprite_attribute.doubleSizeOrHidden = double_size;
sprite_attribute.setRotationParameterIndex(currentAffine);
var affine_attribute: *OAM.AffineAttribute = allocateAffine();
affine_attribute.pa = transform.pa;
affine_attribute.pb = transform.pb;
affine_attribute.pc = transform.pc;
affine_attribute.pd = transform.pd;
}
};
|
GBA/oam.zig
|
const std = @import("std");
const assert = std.debug.assert;
pub fn main() !void {
var gpa = std.heap.GeneralPurposeAllocator(.{}){};
const allocator = &gpa.allocator;
defer _ = gpa.deinit();
const args = try std.process.argsAlloc(allocator);
defer std.process.argsFree(allocator, args);
if (args.len != 2) {
std.log.err("Please provide an input file path.", .{});
return;
}
const input_file = try std.fs.cwd().openFile(args[1], .{});
defer input_file.close();
const input_reader = input_file.reader();
const Fields = struct {
birth_year: FieldResult = .None,
issue_year: FieldResult = .None,
expir_year: FieldResult = .None,
height: FieldResult = .None,
hair_color: FieldResult = .None,
eye_color: FieldResult = .None,
passport_id: FieldResult = .None,
country_id: FieldResult = .None,
pub const FieldResult = enum {
None,
RequiredKeyPresent,
AllGood,
};
pub fn hasRequiredFields(self: @This()) bool {
if (self.birth_year != .None and
self.issue_year != .None and
self.expir_year != .None and
self.height != .None and
self.hair_color != .None and
self.eye_color != .None and
self.passport_id != .None) {
return true;
}
return false;
}
pub fn hasValidValues(self: @This()) bool {
if (self.birth_year == .AllGood and
self.issue_year == .AllGood and
self.expir_year == .AllGood and
self.height == .AllGood and
self.hair_color == .AllGood and
self.eye_color == .AllGood and
self.passport_id == .AllGood) {
return true;
}
return false;
}
pub fn parseKeyValue(self: *@This(), field: []const u8) !void {
var pair = std.mem.tokenize(field, ":");
const hash = std.hash_map.hashString;
switch (hash(pair.next().?)) {
hash("byr") => {
var year = try std.fmt.parseInt(u16,
pair.next().?, 10);
if (year >= 1920 and year <= 2020) {
self.birth_year = .AllGood;
return;
}
self.birth_year = .RequiredKeyPresent;
},
hash("iyr") => {
var year = try std.fmt.parseInt(u16,
pair.next().?, 10);
if (year >= 2010 and year <= 2020) {
self.issue_year = .AllGood;
return;
}
self.issue_year = .RequiredKeyPresent;
},
hash("eyr") => {
var year = try std.fmt.parseInt(u16,
pair.next().?, 10);
if (year >= 2020 and year <= 2030) {
self.expir_year = .AllGood;
return;
}
self.expir_year = .RequiredKeyPresent;
},
hash("hgt") => {
const value = pair.next().?;
var height: u8 = 0;
if (std.mem.endsWith(u8, value, "in")) {
height = std.fmt.parseInt(u8, value[0..2], 10) catch |e| {
if (e == error.InvalidCharacter) {
self.height = .RequiredKeyPresent;
return;
} else {
return e;
}
};
if (height >= 59 and height <= 76) {
self.height = .AllGood;
return;
}
} else if (std.mem.endsWith(u8, value, "cm")) {
height = std.fmt.parseInt(u8, value[0..3], 10) catch |e| {
if (e == error.InvalidCharacter) {
self.height = .RequiredKeyPresent;
return;
} else {
return e;
}
};
if (height >= 150 and height <= 193) {
self.height = .AllGood;
return;
}
}
self.height = .RequiredKeyPresent;
},
hash("hcl") => {
const color = pair.next().?;
if (color.len != 7) {
self.hair_color = .RequiredKeyPresent;
return;
}
if (color[0] != '#') {
self.hair_color = .RequiredKeyPresent;
return;
}
for (color[1..]) |c| {
if ((c < '0' and c > '9') or
(c < 'a' and c > 'f')) {
self.hair_color = .RequiredKeyPresent;
return;
}
}
self.hair_color = .AllGood;
},
hash("ecl") => {
const value = pair.next().?;
if (value.len != 3) {
self.eye_color = .RequiredKeyPresent;
return;
}
const colors = [_][]const u8 {
"amb", "blu", "brn", "gry", "grn", "hzl", "oth"
};
for (colors) |color| {
if (std.mem.eql(u8, color, value)) {
self.eye_color = .AllGood;
return;
}
}
self.eye_color = .RequiredKeyPresent;
},
hash("pid") => {
const value = pair.next().?;
if (value.len != 9) {
self.passport_id = .RequiredKeyPresent;
return;
}
var passport_id = try std.fmt.parseInt(u32,
value, 10);
self.passport_id = .AllGood;
},
hash("cid") => {
self.country_id = .AllGood;
},
else => return error.UnsupportedKey,
}
}
};
var current = Fields{};
var valid1: u32 = 0;
var valid2: u32 = 0;
var buf: [128]u8 = undefined;
while (try input_reader.readUntilDelimiterOrEof(buf[0..], '\n')) |line| {
if (line.len == 0) {
// new entry starts now
if (current.hasRequiredFields())
valid1 += 1;
if (current.hasValidValues()) {
valid2 += 1;
std.log.debug("Entry {} is valid", .{valid2});
}
std.log.debug("{}\n", .{current});
current = Fields{};
continue;
}
var tokens = std.mem.tokenize(line, " ");
while (tokens.next()) |entry| {
try current.parseKeyValue(entry);
}
}
// Check the entries one last time, to avoid hitting EOF without
if (current.hasRequiredFields())
valid1 += 1;
if (current.hasValidValues())
valid2 += 1;
std.log.debug("{}", .{current});
std.log.info("The solution for part 1 is {}.", .{valid1});
std.log.info("The solution for part 2 is {}. THIS IS OFF BY ONE, FOR SOME REASON!", .{valid2});
}
|
src/day04.zig
|
const std = @import("std");
pub const RollType = enum {
Normal,
Advantage,
Disadvantage,
pub fn jsonStringify(
self: RollType,
_: std.json.StringifyOptions,
out_stream: anytype,
) !void {
try out_stream.writeByte('\"');
try out_stream.writeAll(@tagName(self));
try out_stream.writeByte('\"');
}
};
pub const Die = struct {
d: i32,
};
pub const d4 = Die{ .d = 4 };
pub const d6 = Die{ .d = 6 };
pub const d8 = Die{ .d = 8 };
pub const d10 = Die{ .d = 10 };
pub const d12 = Die{ .d = 12 };
pub const d20 = Die{ .d = 20 };
const Unary = struct {
const Operation = enum {
// Arithmetic
negate,
// Logical
logical_not,
pub fn jsonStringify(self: Operation, _: std.json.StringifyOptions, out_stream: anytype) @TypeOf(out_stream).Error!void {
try out_stream.writeByte('"');
try out_stream.writeAll(@tagName(self));
try out_stream.writeByte('"');
}
};
op: Operation,
operand: *Value,
pub fn get(self: Unary, random: std.rand.Random) Value.Result {
return switch (self.op) {
.negate => .{ .Integer = -self.operand.get(random).Integer },
.logical_not => .{ .Bool = !self.operand.get(random).Bool },
};
}
/// For operators, frees all operand pointers
pub fn deinit(self: *Unary, allocator: std.mem.Allocator) void {
switch (self.*.operand.*) {
.Constant, .Bool, .Die => {},
.Unary => |*operand| operand.*.deinit(allocator),
.Binary => |*operand| operand.*.deinit(allocator),
}
allocator.destroy(self.*.operand);
}
};
// TODO: Implement N-way binary ops as a List (ArrayList or SinglyLinkedList) of *Value
const Binary = struct {
const Operation = enum {
// Arithmetic
add,
subtract,
multiply,
divide,
minimum,
maximum,
// Relational
equal,
less,
less_equal,
greater,
greater_equal,
// Logical
logical_and,
logical_or,
pub fn jsonStringify(self: Operation, _: std.json.StringifyOptions, out_stream: anytype) @TypeOf(out_stream).Error!void {
try out_stream.writeByte('"');
try out_stream.writeAll(@tagName(self));
try out_stream.writeByte('"');
}
};
op: Operation,
lhs: *Value,
rhs: *Value,
pub fn get(self: Binary, random: std.rand.Random) Value.Result {
return switch (self.op) {
// Arithmetic
.add => .{ .Integer = self.lhs.get(random).Integer + self.rhs.get(random).Integer },
.subtract => .{ .Integer = self.lhs.get(random).Integer - self.rhs.get(random).Integer },
.multiply => .{ .Integer = self.lhs.get(random).Integer * self.rhs.get(random).Integer },
.divide => .{ .Integer = divide(self.lhs.get(random).Integer, self.rhs.get(random).Integer) },
.minimum => .{ .Integer = @minimum(self.lhs.get(random).Integer, self.rhs.get(random).Integer) },
.maximum => .{ .Integer = @maximum(self.lhs.get(random).Integer, self.rhs.get(random).Integer) },
// Relational
.equal => .{ .Bool = self.lhs.get(random).Integer == self.rhs.get(random).Integer },
.less => .{ .Bool = self.lhs.get(random).Integer < self.rhs.get(random).Integer },
.less_equal => .{ .Bool = self.lhs.get(random).Integer <= self.rhs.get(random).Integer },
.greater => .{ .Bool = self.lhs.get(random).Integer > self.rhs.get(random).Integer },
.greater_equal => .{ .Bool = self.lhs.get(random).Integer >= self.rhs.get(random).Integer },
// Logical
.logical_and => .{ .Bool = self.lhs.get(random).Bool and self.rhs.get(random).Bool },
.logical_or => .{ .Bool = self.lhs.get(random).Bool or self.rhs.get(random).Bool },
};
}
/// D&D division always rounds up
fn divide(lhs: i32, rhs: i32) i32 {
if (@rem(lhs, rhs) == 0) {
return @divFloor(lhs, rhs);
}
return @divFloor(lhs, rhs) + 1;
}
/// Deinit and free both operands
pub fn deinit(self: *Binary, allocator: std.mem.Allocator) void {
switch (self.*.lhs.*) {
.Constant, .Bool, .Die => {},
.Unary => |*lhs| lhs.*.deinit(allocator),
.Binary => |*lhs| lhs.*.deinit(allocator),
}
switch (self.*.rhs.*) {
.Constant, .Bool, .Die => {},
.Unary => |*rhs| rhs.*.deinit(allocator),
.Binary => |*rhs| rhs.*.deinit(allocator),
}
allocator.destroy(self.*.lhs);
allocator.destroy(self.*.rhs);
}
};
test "Binary to json to Binary" {
var out_buf: [1024]u8 = undefined;
var slice_stream = std.io.fixedBufferStream(&out_buf);
const out = slice_stream.writer();
var lhs = Value{ .Constant = 10 };
var rhs = Value{ .Constant = 5 };
const b1 = Binary{
.op = .add,
.lhs = &lhs,
.rhs = &rhs,
};
try std.json.stringify(b1, .{}, out);
try std.testing.expect(std.mem.eql(u8, "{\"op\":\"add\",\"lhs\":10,\"rhs\":5}", slice_stream.getWritten()));
const options = std.json.ParseOptions{ .allocator = std.testing.allocator };
const b2 = try std.json.parse(Binary, &std.json.TokenStream.init(slice_stream.getWritten()), options);
defer std.json.parseFree(Binary, b2, options);
try std.testing.expectEqual(b1.op, b2.op);
try std.testing.expectEqual(b1.lhs.*, b2.lhs.*);
try std.testing.expectEqual(b1.rhs.*, b2.rhs.*);
}
const Value = union(enum) {
const Result = union(enum) {
Integer: i32,
Bool: bool,
};
Constant: i32,
Bool: bool,
Die: Die,
Unary: Unary,
Binary: Binary,
pub fn get(self: Value, random: std.rand.Random) Result {
return switch (self) {
.Constant => |c| .{ .Integer = c },
.Bool => |b| .{ .Bool = b },
.Die => |die| .{ .Integer = random.intRangeAtMost(i32, 1, die.d) },
.Unary => |op| op.get(random),
.Binary => |op| op.get(random),
};
}
/// For operators, frees all operand pointers. Must be passed the same allocator that was used to allocate the Value tree.
pub fn deinit(self: *Value, allocator: std.mem.Allocator) void {
switch (self.*) {
.Constant, .Bool, .Die => {},
.Unary => |*op| op.*.deinit(allocator),
.Binary => |*op| op.*.deinit(allocator),
}
}
};
test "get Constant" {
var prng = std.rand.DefaultPrng.init(0);
var rand = prng.random();
const value = Value{ .Constant = 5 };
try std.testing.expectEqual(value.get(rand).Integer, 5);
}
test "Binary Operation from json" {
var j =
\\{
\\ "op": "multiply",
\\ "lhs": 10,
\\ "rhs": 5
\\}
;
var ten = Value{ .Constant = 10 };
var five = Value{ .Constant = 5 };
const expected = Binary{ .op = .multiply, .lhs = &ten, .rhs = &five };
const options = std.json.ParseOptions{ .allocator = std.testing.allocator };
const actual = try std.json.parse(Binary, &std.json.TokenStream.init(j), options);
defer std.json.parseFree(Binary, actual, options);
try std.testing.expectEqual(expected.op, actual.op);
try std.testing.expectEqual(actual.lhs.*.Constant, 10);
try std.testing.expectEqual(actual.rhs.*.Constant, 5);
try std.testing.expectEqual(expected.lhs.*.Constant, actual.lhs.*.Constant);
try std.testing.expectEqual(expected.rhs.*.Constant, actual.rhs.*.Constant);
}
test "Die from json" {
var j =
\\{
\\ "d": 10
\\}
;
try std.testing.expectEqual(try std.json.parse(Die, &std.json.TokenStream.init(j), .{}), d10);
}
test "Die to json" {
var out_buf: [9]u8 = undefined;
var slice_stream = std.io.fixedBufferStream(&out_buf);
const out = slice_stream.writer();
try std.json.stringify(d10, .{}, out);
try std.testing.expect(std.mem.eql(u8, "{\"d\":10}", slice_stream.getWritten()));
}
test "Dice from json" {
var j =
\\[
\\ { "d": 10 },
\\ { "d": 20 },
\\ { "d": 6 }
\\]
;
const options = std.json.ParseOptions{ .allocator = std.testing.allocator };
const dice = try std.json.parse([]Die, &std.json.TokenStream.init(j), options);
defer std.json.parseFree([]Die, dice, options);
try std.testing.expectEqual(dice[0], d10);
try std.testing.expectEqual(dice[1], d20);
try std.testing.expectEqual(dice[2], d6);
}
test "Dice to json" {
var out_buf: [100]u8 = undefined;
var slice_stream = std.io.fixedBufferStream(&out_buf);
const out = slice_stream.writer();
try std.json.stringify([_]Die{
d10,
d20,
d6,
}, .{}, out);
try std.testing.expect(std.mem.eql(u8, "[{\"d\":10},{\"d\":20},{\"d\":6}]", slice_stream.getWritten()));
}
// TODO: Implement a roll parser that can take user-inputs and render them to operations on Dice.
// Format `XdY +- C` at minimum
// Ideally, any `XdY` term could be part of an operation, just like any constant C.
// Additionally, a compare operator should be supported and to render hit/miss equations
// e.g. `1d20 + 5 >= 16` should be parsable and yield true or false, indicating that an attach hit or missed.
// Numeric operators:
// + plus, addition
// - minus, subtraction
// * times, multiplication
// / over, division
// v minimum (e.g. disadvantage `1d20 v 1d20`)
// ^ maximum (e.g. advantage `1d20 ^ 1d20`)
// Compares / Relational operators
// < less
// <= less or equal
// > greater
// >= greater or equal
// == equal
// Logical operators
// && logical and
// || logical or
// See: std.json for an example of a parser that should work well for this.
//
// The below code is just some random experiments, it's likely to be completely rewritten.
const Token = union(enum) {
Nothing: struct {},
Number: i32,
Operation: OperationEnum,
OpenParen: struct {},
CloseParen: struct {},
const OperationEnum = enum(u8) {
add = '+',
subtract = '-',
multiply = '*',
divide = '/',
min = 'v',
max = '^',
less = '<',
greater = '>',
equal = '=',
dice = 'd',
};
};
pub fn TokenStream(comptime Stream: type) type {
return struct {
const Self = @This();
reader: Stream.Reader,
token: ?Token = Token{ .Nothing = .{} },
pub fn init(stream: *Stream) Self {
return .{ .reader = stream.reader() };
}
pub fn next(self: *Self) ?Token {
while (true) {
const c = self.*.reader.readByte() catch return self.replaceToken(null);
switch (c) {
' ' => continue,
'0'...'9' => {
switch (self.*.token.?) {
.Number => self.*.token.?.Number = self.*.token.?.Number * 10 + c - '0',
.Nothing => _ = self.replaceToken(Token{ .Number = c - '0' }),
else => return self.replaceToken(Token{ .Number = c - '0' }),
}
},
'+', '-', '*', '/', 'v', '^', '<', '>', '=', 'd' => {
switch (self.*.token.?) {
.Nothing => unreachable,
else => return self.replaceToken(Token{ .Operation = @intToEnum(Token.OperationEnum, c) }),
}
},
'(' => {
switch (self.*.token.?) {
.Nothing => _ = self.replaceToken(Token{ .OpenParen = .{} }),
else => return self.replaceToken(Token{ .OpenParen = .{} }),
}
},
')' => {
switch (self.*.token.?) {
.Nothing => _ = self.replaceToken(Token{ .CloseParen = .{} }),
else => return self.replaceToken(Token{ .CloseParen = .{} }),
}
},
else => unreachable,
}
}
}
fn replaceToken(self: *Self, new_token: ?Token) ?Token {
const old_token = self.*.token;
self.*.token = new_token;
return old_token;
}
};
}
pub fn tokenStream(stream: anytype) TokenStream(@TypeOf(stream.*)) {
return TokenStream(@TypeOf(stream.*)).init(stream);
}
test "tokenStream" {
var stream = std.io.fixedBufferStream("11 + 1 + 1d8");
var tokens = tokenStream(&stream);
try std.testing.expectEqual(tokens.next().?, Token{ .Number = 11 });
try std.testing.expectEqual(tokens.next().?, Token{ .Operation = .add });
try std.testing.expectEqual(tokens.next().?, Token{ .Number = 1 });
try std.testing.expectEqual(tokens.next().?, Token{ .Operation = .add });
try std.testing.expectEqual(tokens.next().?, Token{ .Number = 1 });
try std.testing.expectEqual(tokens.next().?, Token{ .Operation = .dice });
try std.testing.expectEqual(tokens.next().?, Token{ .Number = 8 });
try std.testing.expectEqual(tokens.next(), null);
}
fn Tree(comptime T: type) type {
return struct {
const Self = @This();
pub const Node = struct {
children: std.ArrayList(*Node),
data: T,
pub const Data = T;
pub fn init(allocator: std.mem.Allocator, data: T) Node {
return .{
.children = std.ArrayList(*Node).init(allocator),
.data = data,
};
}
pub fn addChild(node: *Node, child: *Node) void {
node.children.append(child);
}
};
root: ?*Node = null,
};
}
pub fn parse(
allocator: std.mem.Allocator,
tokens: anytype,
) !?Value {
_ = allocator; // TODO: Remove once it's referenced
var value: ?Value = null;
std.debug.print("\n", .{});
while (tokens.*.next()) |token| {
std.debug.print("{s}\n", .{token});
switch (token) {
.Nothing => unreachable, // TODO
.Number => unreachable, // TODO
.Operation => unreachable, // TODO
.OpenParen => unreachable, // TODO: this code needs an explicit error set to handle the recursion: value = try parse(allocator, tokens),
.CloseParen => return value,
}
}
return value;
}
test "parse" {
return error.SkipZigTest; // TODO: remove when working on the parser
// var prng = std.rand.DefaultPrng.init(0);
// const rand = prng.random();
// var stream = std.io.fixedBufferStream("11 + 1 + 1d8");
// var tokens = tokenStream(&stream);
// var v = try parse(std.testing.allocator, &tokens);
// if (v) |*value| {
// defer value.deinit(std.testing.allocator);
// const result = value.get(rand).Integer;
// try std.testing.expect(13 <= result);
// try std.testing.expect(result <= 20);
// }
}
|
src/dnd/dice.zig
|
usingnamespace @import("raylib-zig.zig");
pub extern fn Clamp(value: f32, min: f32, max: f32) f32;
pub extern fn Lerp(start: f32, end: f32, amount: f32) f32;
pub extern fn Vector2Zero() Vector2;
pub extern fn Vector2One() Vector2;
pub extern fn Vector2Add(v1: Vector2, v2: Vector2) Vector2;
pub extern fn Vector2Subtract(v1: Vector2, v2: Vector2) Vector2;
pub extern fn Vector2Length(v: Vector2) f32;
pub extern fn Vector2DotProduct(v1: Vector2, v2: Vector2) f32;
pub extern fn Vector2Distance(v1: Vector2, v2: Vector2) f32;
pub extern fn Vector2Angle(v1: Vector2, v2: Vector2) f32;
pub extern fn Vector2Scale(v: Vector2, scale: f32) Vector2;
pub extern fn Vector2MultiplyV(v1: Vector2, v2: Vector2) Vector2;
pub extern fn Vector2Negate(v: Vector2) Vector2;
pub extern fn Vector2Divide(v: Vector2, div: f32) Vector2;
pub extern fn Vector2DivideV(v1: Vector2, v2: Vector2) Vector2;
pub extern fn Vector2Normalize(v: Vector2) Vector2;
pub extern fn Vector2Lerp(v1: Vector2, v2: Vector2, amount: f32) Vector2;
pub extern fn Vector2Rotate(v: Vector2, degs: f32) Vector2;
pub extern fn Vector3Zero() Vector3;
pub extern fn Vector3One() Vector3;
pub extern fn Vector3Add(v1: Vector3, v2: Vector3) Vector3;
pub extern fn Vector3Subtract(v1: Vector3, v2: Vector3) Vector3;
pub extern fn Vector3Scale(v: Vector3, scalar: f32) Vector3;
pub extern fn Vector3Multiply(v1: Vector3, v2: Vector3) Vector3;
pub extern fn Vector3CrossProduct(v1: Vector3, v2: Vector3) Vector3;
pub extern fn Vector3Perpendicular(v: Vector3) Vector3;
pub extern fn Vector3Length(v: Vector3) f32;
pub extern fn Vector3DotProduct(v1: Vector3, v2: Vector3) f32;
pub extern fn Vector3Distance(v1: Vector3, v2: Vector3) f32;
pub extern fn Vector3Negate(v: Vector3) Vector3;
pub extern fn Vector3Divide(v: Vector3, div: f32) Vector3;
pub extern fn Vector3DivideV(v1: Vector3, v2: Vector3) Vector3;
pub extern fn Vector3Normalize(v: Vector3) Vector3;
pub extern fn Vector3OrthoNormalize(v1: [*c]const Vector3, v2: [*c]const Vector3) void;
pub extern fn Vector3Transform(v: Vector3, mat: Matrix) Vector3;
pub extern fn Vector3RotateByQuaternion(v: Vector3, q: Quaternion) Vector3;
pub extern fn Vector3Lerp(v1: Vector3, v2: Vector3, amount: f32) Vector3;
pub extern fn Vector3Reflect(v: Vector3, normal: Vector3) Vector3;
pub extern fn Vector3Min(v1: Vector3, v2: Vector3) Vector3;
pub extern fn Vector3Max(v1: Vector3, v2: Vector3) Vector3;
pub extern fn Vector3Barycenter(p: Vector3, a: Vector3, b: Vector3, c: Vector3) Vector3;
pub extern fn Vector3ToFloatV(v: Vector3) float3;
pub extern fn MatrixDeterminant(mat: Matrix) f32;
pub extern fn MatrixTrace(mat: Matrix) f32;
pub extern fn MatrixTranspose(mat: Matrix) Matrix;
pub extern fn MatrixInvert(mat: Matrix) Matrix;
pub extern fn MatrixNormalize(mat: Matrix) Matrix;
pub extern fn MatrixIdentity() Matrix;
pub extern fn MatrixAdd(left: Matrix, right: Matrix) Matrix;
pub extern fn MatrixSubtract(left: Matrix, right: Matrix) Matrix;
pub extern fn MatrixTranslate(x: f32, y: f32, z: f32) Matrix;
pub extern fn MatrixRotate(axis: Vector3, angle: f32) Matrix;
pub extern fn MatrixRotateXYZ(ang: Vector3) Matrix;
pub extern fn MatrixRotateX(angle: f32) Matrix;
pub extern fn MatrixRotateY(angle: f32) Matrix;
pub extern fn MatrixRotateZ(angle: f32) Matrix;
pub extern fn MatrixScale(x: f32, y: f32, z: f32) Matrix;
pub extern fn MatrixMultiply(left: Matrix, right: Matrix) Matrix;
pub extern fn MatrixFrustum(left: f64, right: f64, bottom: f64, top: f64, near: f64, far: f64) Matrix;
pub extern fn MatrixPerspective(fovy: f64, aspect: f64, near: f64, far: f64) Matrix;
pub extern fn MatrixOrtho(left: f64, right: f64, bottom: f64, top: f64, near: f64, far: f64) Matrix;
pub extern fn MatrixLookAt(eye: Vector3, target: Vector3, up: Vector3) Matrix;
pub extern fn MatrixToFloatV(mat: Matrix) float16;
pub extern fn QuaternionIdentity() Quaternion;
pub extern fn QuaternionLength(q: Quaternion) f32;
pub extern fn QuaternionNormalize(q: Quaternion) Quaternion;
pub extern fn QuaternionInvert(q: Quaternion) Quaternion;
pub extern fn QuaternionMultiply(q1: Quaternion, q2: Quaternion) Quaternion;
pub extern fn QuaternionLerp(q1: Quaternion, q2: Quaternion, amount: f32) Quaternion;
pub extern fn QuaternionNlerp(q1: Quaternion, q2: Quaternion, amount: f32) Quaternion;
pub extern fn QuaternionSlerp(q1: Quaternion, q2: Quaternion, amount: f32) Quaternion;
pub extern fn QuaternionFromVector3ToVector3(from: Vector3, to: Vector3) Quaternion;
pub extern fn QuaternionFromMatrix(mat: Matrix) Quaternion;
pub extern fn QuaternionToMatrix(q: Quaternion) Matrix;
pub extern fn QuaternionFromAxisAngle(axis: Vector3, angle: f32) Quaternion;
pub extern fn QuaternionToAxisAngle(q: Quaternion, outAxis: [*c]const Vector3, outAngle: [*c]const f32) void;
pub extern fn QuaternionFromEuler(roll: f32, pitch: f32, yaw: f32) Quaternion;
pub extern fn QuaternionToEuler(q: Quaternion) Vector3;
pub extern fn QuaternionTransform(q: Quaternion, mat: Matrix) Quaternion;
|
lib/raylib-zig-math.zig
|
const std = @import("std");
const log = std.log;
const mem = std.mem;
const assert = std.debug.assert;
const TokenType = enum {
const Self = @This();
lbrace,
rbrace,
lbracket,
rbracket,
colon,
comma,
number,
word,
pub fn format(
self: Self,
comptime fmt: []const u8,
options: std.fmt.FormatOptions,
writer: anytype,
) !void {
_ = options;
if (fmt.len == 1 and fmt[0] == 's') {
switch (self) {
.lbrace => _ = try writer.write("lbrace"),
.rbrace => _ = try writer.write("rbrace"),
.lbracket => _ = try writer.write("lbracket"),
.rbracket => _ = try writer.write("rbracket"),
.colon => _ = try writer.write("colon"),
.comma => _ = try writer.write("comma"),
.number => _ = try writer.write("number"),
.word => _ = try writer.write("word"),
}
} else @compileError(
"Only {s} specifier can be used for " ++ @typeName(Self) ++ " formatting",
);
}
};
const Token = struct {
next: ?*Token = null,
type: TokenType = TokenType.word,
offset: usize = 0,
line: usize = 0,
col: usize = 0,
len: usize = 0,
};
const TokenFormatter = struct {
const Self = @This();
token: *const Token,
source: []const u8,
fn fromToken(token: *const Token, source: []const u8) Self {
return Self{
.token = token,
.source = source,
};
}
pub fn format(
self: Self,
comptime fmt: []const u8,
options: std.fmt.FormatOptions,
writer: anytype,
) !void {
_ = options;
if (fmt.len == 1 and fmt[0] == 's') {
try writer.print("{s}", .{
self.source[self.token.offset .. self.token.offset + self.token.len],
});
} else if (fmt.len == 1 and fmt[0] == 'd') {
try writer.print("{s}\"{s}\"", .{
self.token.type,
self.source[self.token.offset .. self.token.offset + self.token.len],
});
} else @compileError(
"Only {s} and {d} specifiers can be used for " ++ @typeName(Self) ++ " formatting",
);
}
};
const Lex = struct {
const LexState = enum {
idle,
word,
number,
pub fn expected(self: @This()) []const u8 {
switch (self) {
.idle => return "\"[a-zA-Z_]\", \"[0-9]\", " ++
"\"{\", \"}\", \"[\", \"]\", \":\" or \",\"",
.word => return "\"[a-zA-Z0-9_]\" to proceed the word or else " ++
"\"{\", \"}\", \"[\", \"]\", \":\" or \",\"",
.number => return "\"[0-9]\"",
}
}
};
const Self = @This();
state: LexState = LexState.idle,
offset: usize = 0,
line: usize = 0,
col: usize = 0,
have_err: bool = false,
first: ?*Token = null,
last: ?*Token = null,
allocator: mem.Allocator,
source: []u8,
pub fn init(allocator: mem.Allocator) Self {
return Self{
.allocator = allocator,
.source = allocator.alloc(u8, 1024) catch unreachable,
};
}
fn addToken(self: *Self, t: TokenType) void {
if (t == TokenType.number) {
self.state = LexState.number;
} else if (t == TokenType.word) {
self.state = LexState.word;
} else self.state = LexState.idle;
const token: *Token = self.allocator.create(Token) catch unreachable;
token.* = Token{
.next = null,
.type = t,
.offset = self.offset,
.line = self.line,
.col = self.col,
.len = 1,
};
if (self.last) |last| {
last.next = token;
} else {
self.first = token;
}
self.last = token;
}
fn continueToken(self: *Self, token: *Token) void {
_ = self;
token.len += 1;
}
fn simpleToktype(byte: u8) TokenType {
return switch (byte) {
'{' => TokenType.lbrace,
'}' => TokenType.rbrace,
'[' => TokenType.lbracket,
']' => TokenType.rbracket,
':' => TokenType.colon,
',' => TokenType.comma,
else => unreachable,
};
}
fn err(self: *Self, byte: u8) bool {
self.source[self.offset] = byte;
self.have_err = true;
return !self.have_err;
}
fn consumeByte(self: *Self, byte: u8) bool {
if (self.have_err)
return false;
switch (byte) {
'{', '}', '[', ']', ':', ',' => |t| {
self.addToken(simpleToktype(t));
},
' ', '\t', '\n', '\r' => {
self.state = LexState.idle;
},
'0'...'9' => |_| {
if (self.state == LexState.number or self.state == LexState.word) {
self.continueToken(self.last.?);
} else self.addToken(TokenType.number);
},
'A'...'Z',
'a'...'z',
'_',
=> |alpha| {
if (self.state == LexState.number) {
return self.err(alpha);
} else if (self.state == LexState.word) {
self.continueToken(self.last.?);
} else self.addToken(TokenType.word);
},
else => |char| return self.err(char),
}
self.source[self.offset] = byte;
self.offset += 1;
if (byte == '\n') {
self.col = 0;
self.line += 1;
} else {
self.col += 1;
}
return !self.have_err;
}
pub fn consume(self: *Self, data: []const u8) bool {
for (data) |byte|
if (!self.consumeByte(byte))
return false;
return true;
}
pub fn deinit(self: *Self) void {
var token = self.first;
while (token) |t| {
token = t.next;
self.allocator.destroy(t);
}
self.first = null;
self.last = null;
self.allocator.free(self.source);
}
fn delimiter(present: bool) []const u8 {
if (present) return ", ";
return "";
}
pub fn print(self: *Self, writer: *std.fs.File.Writer) void {
var token = self.first;
_ = writer.write("[") catch unreachable;
while (token) |t| {
_ = writer.print("{d}{s}", .{
TokenFormatter.fromToken(t, self.source),
delimiter(t.next != null),
}) catch unreachable;
token = t.next;
}
_ = writer.write("]\n") catch unreachable;
}
pub fn errorFormatted(self: *Self) LexErrFormatter {
assert(self.have_err);
return LexErrFormatter{
.line = self.line,
.col = self.col,
.char = self.source[self.offset],
.expected = self.state.expected(),
};
}
};
const LexErrFormatter = struct {
line: usize,
col: usize,
char: u8,
expected: []const u8,
pub fn format(
self: @This(),
comptime fmt: []const u8,
options: std.fmt.FormatOptions,
writer: anytype,
) !void {
_ = options;
if (fmt.len == 1 and fmt[0] == 's') {
try writer.print("<stdin>:{d}:{d}: unexpected char \"{c}\", expected {s}", .{
self.line,
self.col,
self.char,
self.expected,
});
} else @compileError(
"Only {s} specifier can be used for " ++ @typeName(@This()) ++ " formatting",
);
}
};
const NodeType = enum {
kv,
map,
array,
number,
word,
pub fn format(
self: @This(),
comptime fmt: []const u8,
options: std.fmt.FormatOptions,
writer: anytype,
) !void {
_ = options;
if (fmt.len == 1 and fmt[0] == 's') {
switch (self) {
.kv => _ = try writer.write("kv"),
.map => _ = try writer.write("map"),
.array => _ = try writer.write("array"),
.number => _ = try writer.write("number"),
.word => _ = try writer.write("word"),
}
} else @compileError(
"Only {s} specifier can be used for " ++ @typeName(@This()) ++ " formatting",
);
}
};
const ListNode = struct {
first: ?*Node = null,
last: ?*Node = null,
};
const KVNode = struct {
value: *Node,
key: *Node,
};
const NodeUnion = union(NodeType) {
map: ListNode,
array: ListNode,
kv: KVNode,
number,
word,
};
const Node = struct {
const Self = @This();
next: ?*Node = null,
data: NodeUnion,
offset: usize,
line: usize,
col: usize,
len: usize,
fn newRoot(allocator: mem.Allocator) *Self {
var self = allocator.create(Node) catch unreachable;
self.* = Self{
.data = NodeUnion{ .map = ListNode{} },
.offset = 0,
.line = 0,
.col = 0,
.len = 0,
};
return self;
}
fn newArray(allocator: mem.Allocator, token: *Token) *Self {
var self = allocator.create(Self) catch unreachable;
self.* = Self{
.data = NodeUnion{ .array = ListNode{} },
.offset = token.offset,
.line = token.line,
.col = token.col,
.len = token.len,
};
return self;
}
fn newMap(allocator: mem.Allocator, token: *Token) *Self {
var self = allocator.create(Self) catch unreachable;
self.* = Self{
.data = NodeUnion{ .map = ListNode{} },
.offset = token.offset,
.line = token.line,
.col = token.col,
.len = token.len,
};
return self;
}
fn newWord(allocator: mem.Allocator, token: *Token) *Self {
var self = allocator.create(Self) catch unreachable;
self.* = Self{
.data = NodeType.word,
.offset = token.offset,
.line = token.line,
.col = token.col,
.len = token.len,
};
return self;
}
fn newNumber(allocator: mem.Allocator, token: *Token) *Self {
var self = allocator.create(Self) catch unreachable;
self.* = Self{
.data = NodeType.number,
.offset = token.offset,
.line = token.line,
.col = token.col,
.len = token.len,
};
return self;
}
fn newKeyValue(allocator: mem.Allocator, key: *Self, value: *Self) *Self {
var self = allocator.create(Self) catch unreachable;
self.* = Self{
.data = NodeUnion{ .kv = KVNode{ .key = key, .value = value } },
.offset = key.offset,
.line = key.line,
.col = key.col,
.len = (value.offset + value.len) - key.offset,
};
return self;
}
fn destroy(self: *Self, allocator: mem.Allocator) void {
switch (self.data) {
.kv => |kv| {
kv.value.destroy(allocator);
kv.key.destroy(allocator);
allocator.destroy(self);
},
.map, .array => |list| {
var node_ptr = list.first;
while (node_ptr) |node| {
var next = node.next;
node.destroy(allocator);
node_ptr = next;
}
allocator.destroy(self);
},
.number, .word => |_| allocator.destroy(self),
}
}
};
fn indent(writer: anytype, level_: usize) !void {
var level = level_;
while (level > 0) {
_ = try writer.write(" ");
level -= 1;
}
}
const NodeFormatter = struct {
const Self = @This();
node: *const Node,
source: []const u8,
level: usize = 0,
pretty: bool = false,
in_pair: bool = false,
fn default(node: *const Node, source: []const u8, level: usize) Self {
return Self{
.node = node,
.source = source,
.level = level,
};
}
pub fn pretty(node: *const Node, source: []const u8, level: usize) Self {
_ = level;
return Self{
.node = node,
.source = source,
.pretty = true,
};
}
pub fn format(
self: Self,
fmt: []const u8,
options: std.fmt.FormatOptions,
writer: anytype,
) !void {
_ = options;
if (fmt.len == 1 and (fmt[0] == 's' or fmt[0] == 'd')) {
switch (self.node.data) {
.map => |map| {
if (self.pretty and !self.in_pair) try indent(writer, self.level);
_ = try writer.write("{");
var kv_ptr = map.first;
if (kv_ptr != null) {
if (self.pretty) _ = try writer.write("\n");
while (kv_ptr) |kv| {
var kv_fmt = Self.default(kv, self.source, self.level + 1);
kv_fmt.pretty = self.pretty;
try writer.print("{s}", .{kv_fmt});
if (kv.next != null) _ = try writer.write(",");
if (self.pretty) _ = try writer.write("\n");
kv_ptr = kv.next;
}
if (self.pretty) try indent(writer, self.level);
}
_ = try writer.write("}");
},
.kv => |kv| {
var key_fmt = Self.default(kv.key, self.source, self.level);
key_fmt.pretty = self.pretty;
var value_fmt = Self.default(kv.value, self.source, self.level);
value_fmt.in_pair = true;
value_fmt.pretty = self.pretty;
_ = try writer.print("{s}:{s}", .{ key_fmt, value_fmt });
},
.number, .word => |_| {
if (self.pretty and !self.in_pair) try indent(writer, self.level);
const start = self.node.offset;
const end = self.node.offset + self.node.len;
if (fmt[0] == 's') {
try writer.print("{s}", .{self.source[start..end]});
} else if (fmt[0] == 'd') {
_ = try writer.print("{s}\"{s}\"", .{
@as(NodeType, self.node.data),
self.source[start..end],
});
}
},
.array => |array| {
if (self.pretty and !self.in_pair) try indent(writer, self.level);
_ = try writer.write("[");
var arr_node_ptr = array.first;
if (arr_node_ptr != null) {
if (self.pretty) _ = try writer.write("\n");
while (arr_node_ptr) |arr_node| {
var arr_node_fmt = Self.default(arr_node, self.source, self.level + 1);
arr_node_fmt.pretty = self.pretty;
_ = try writer.print("{s}", .{arr_node_fmt});
if (arr_node.next != null) _ = try writer.write(",");
if (self.pretty) _ = try writer.write("\n");
arr_node_ptr = arr_node.next;
}
if (self.pretty) try indent(writer, self.level);
}
_ = try writer.write("]");
},
}
}
}
};
const Pars = struct {
const ParsState = enum {
key,
key_root,
kv_delim,
value,
map_delim,
map_delim_root,
arr_node,
arr_delim,
pub fn expected(self: @This()) []const u8 {
switch (self) {
.key => return "word\"[a-zA-Z][a-zA-Z0-9_]*\" or \"}\"",
.key_root => return "word\"[a-zA-Z][a-zA-Z0-9_]*\"",
.kv_delim => return "\":\"",
.value => return "word\"[a-zA-Z][a-zA-Z0-9_]*\" or number\"[0-9]+\"",
.map_delim => return "\",\" or \"}\"",
.map_delim_root => return "\",\"",
.arr_node => return "word\"[a-zA-Z][a-zA-Z0-9_]*\", number\"[0-9]+\", " ++
"\"{\", \"[\" or \"]\"",
.arr_delim => return "\",\" or \"]\"",
}
}
};
const ParsErr = error{
InvalidToken,
EndOfStream,
};
const Self = @This();
state: ParsState = ParsState.key_root,
last_token: ?*Token = null,
root: ?*Node = null,
allocator: mem.Allocator,
source: []const u8,
pub fn init(allocator: mem.Allocator, source: []const u8) Self {
return Self{
.allocator = allocator,
.source = source,
};
}
fn err(self: *Self, token: *Token) ParsErr!void {
self.last_token = token;
return error.InvalidToken;
}
pub fn parse(self: *Self, tokens_: ?*Token) ParsErr!void {
var tokens: ?*Token = tokens_;
var token_ptr: *?*Token = &tokens;
self.root = try self.parseMap(token_ptr);
}
fn parseKv(self: *Self, token_ptr: *?*Token) ParsErr!*Node {
const key_token = token_ptr.* orelse return error.EndOfStream;
self.last_token = token_ptr.*;
if (key_token.type != TokenType.word) {
try self.err(key_token);
}
const key = Node.newWord(self.allocator, key_token);
errdefer key.destroy(self.allocator);
token_ptr.* = key_token.next;
self.state = ParsState.kv_delim;
// Delimiter
const colon_token = token_ptr.* orelse return error.EndOfStream;
self.last_token = token_ptr.*;
if (colon_token.type != TokenType.colon) {
try self.err(colon_token);
}
token_ptr.* = colon_token.next;
// The value
self.state = ParsState.value;
const value = try self.parseValue(token_ptr);
const kv = Node.newKeyValue(self.allocator, key, value);
return kv;
}
fn parseValue(self: *Self, token_ptr: *?*Token) ParsErr!*Node {
if (self.state != ParsState.value and self.state != ParsState.arr_node)
unreachable;
const token = token_ptr.* orelse return error.EndOfStream;
self.last_token = token_ptr.*;
switch (token.type) {
.rbrace,
.rbracket,
.colon,
.comma,
=> unreachable,
.lbrace => return self.parseMap(token_ptr),
.lbracket => return self.parseArray(token_ptr),
.number => return Node.newNumber(self.allocator, token),
.word => return Node.newWord(self.allocator, token),
}
}
pub fn parseMap(self: *Self, token_ptr: *?*Token) ParsErr!*Node {
const root = self.state == ParsState.key_root;
const lbrace_token = token_ptr.* orelse {
if (!root) {
return error.EndOfStream;
} else return Node.newRoot(self.allocator);
};
var node = Node.newMap(self.allocator, lbrace_token);
errdefer node.destroy(self.allocator);
if (!root) {
token_ptr.* = lbrace_token.next;
self.state = ParsState.key;
}
while (token_ptr.*) |token| {
self.last_token = token_ptr.*;
switch (self.state) {
.key, .key_root => {
if (token.type == TokenType.rbrace and !root) {
node.len = token.offset + token.len;
return node;
} else if (token.type == TokenType.word) {
var kv = try self.parseKv(token_ptr);
if (!root) {
self.state = ParsState.map_delim;
} else {
self.state = ParsState.map_delim_root;
}
if (node.data.map.last) |last| {
last.next = kv;
} else {
node.data.map.first = kv;
}
node.data.map.last = kv;
} else try self.err(token);
},
.map_delim, .map_delim_root => {
if (token.type == TokenType.rbrace and !root) {
node.len = token.offset + token.len;
return node;
} else if (token.type == TokenType.comma) {
if (!root) {
self.state = ParsState.key;
} else {
self.state = ParsState.key_root;
}
} else try self.err(token);
},
else => unreachable,
}
self.last_token = token_ptr.*;
var current_token = token_ptr.* orelse break;
token_ptr.* = current_token.next;
}
if (!root) {
return error.EndOfStream;
} else return node;
}
fn parseArray(self: *Self, token_ptr: *?*Token) ParsErr!*Node {
const array_token = token_ptr.* orelse return error.EndOfStream;
var node = Node.newArray(self.allocator, array_token);
errdefer node.destroy(self.allocator);
var array = &node.data.array;
var arr_node_token = token_ptr.* orelse return error.EndOfStream;
token_ptr.* = arr_node_token.next;
self.state = ParsState.arr_node;
while (token_ptr.*) |token| {
self.last_token = token_ptr.*;
switch (self.state) {
.arr_node => {
if (token.type == TokenType.rbracket) {
node.len = token.offset + token.len;
return node;
} else if (token.type == TokenType.lbracket) {
var map = try self.parseArray(token_ptr);
self.state = ParsState.arr_delim;
if (array.last) |last| {
last.next = map;
} else {
array.first = map;
}
array.last = map;
} else if (token.type == TokenType.lbrace) {
var map = try self.parseMap(token_ptr);
self.state = ParsState.arr_delim;
if (array.last) |last| {
last.next = map;
} else {
array.first = map;
}
array.last = map;
} else if (token.type == TokenType.word or token.type == TokenType.number) {
var value = try self.parseValue(token_ptr);
self.state = ParsState.arr_delim;
if (array.last) |last| {
last.next = value;
} else {
array.first = value;
}
array.last = value;
} else {
try self.err(token);
}
},
.arr_delim => {
if (token.type == TokenType.rbracket) {
node.len = token.offset + token.len;
return node;
} else if (token.type == TokenType.comma) {
self.state = ParsState.arr_node;
} else try self.err(token);
},
else => unreachable,
}
self.last_token = token_ptr.*;
var current_token = token_ptr.* orelse break;
token_ptr.* = current_token.next;
}
return error.EndOfStream;
}
pub fn deinit(self: *Self) void {
if (self.root) |root| {
root.destroy(self.allocator);
}
}
pub fn print(self: *Self, writer: *std.fs.File.Writer) void {
if (self.root) |root| {
writer.print("{s}\n", .{
NodeFormatter.pretty(root, self.source, 0),
}) catch unreachable;
}
}
pub fn errorFormatted(self: *const Self, err_value: ParsErr) ParsErrFormatter {
return ParsErrFormatter{
.token = (self.last_token orelse &Token{}).*,
.expected = self.state.expected(),
.source = self.source,
.err = err_value,
};
}
};
const ParsErrFormatter = struct {
const Self = @This();
token: Token,
expected: []const u8,
source: []const u8,
err: Pars.ParsErr,
pub fn format(
self: Self,
comptime fmt: []const u8,
options: std.fmt.FormatOptions,
writer: anytype,
) !void {
_ = options;
if (fmt.len == 1 and fmt[0] == 's') {
switch (self.err) {
Pars.ParsErr.InvalidToken => {
try writer.print("<stdin>:{d}:{d}: unexpected token {d}, expected {s}", .{
self.token.line,
self.token.col,
TokenFormatter.fromToken(&self.token, self.source),
self.expected,
});
},
Pars.ParsErr.EndOfStream => {
try writer.print("<stdin>:{d}:{d}: unexpected EOF, expected {s}", .{
self.token.line,
self.token.col + self.token.len,
self.expected,
});
},
}
} else @compileError(
"Only {s} specifier can be used for " ++ @typeName(Self) ++ " formatting",
);
}
};
pub fn main() !void {
var gpalloc = std.heap.GeneralPurposeAllocator(.{}){};
defer assert(!gpalloc.deinit());
const allocator = gpalloc.allocator();
const reader = &std.io.getStdIn().reader();
const writer = &std.io.getStdOut().writer();
_ = writer.write(">") catch unreachable;
const data = reader.readAllAlloc(allocator, std.math.maxInt(usize)) catch |err| {
log.err("{s}", .{err});
return;
};
defer allocator.free(data);
var lex = Lex.init(allocator);
defer lex.deinit();
if (!lex.consume(data)) {
log.err("lexing {s}", .{lex.errorFormatted()});
return;
}
var parser = Pars.init(allocator, lex.source);
defer parser.deinit();
parser.parse(lex.first) catch |err| {
log.err("parsing {s}", .{parser.errorFormatted(err)});
return;
};
parser.print(writer);
}
|
zig-1/src/main.zig
|
const std = @import("std");
const fs = std.fs;
const Answer = struct {
unmarked_sum: u32 = 0,
win_number: u32 = 0,
};
const Board = struct {
entries: [25]u8,
// bit i in `mask` is set if the corresponding entry was drawn
mask: u25 = 0,
};
fn board_is_winning(mask: u25) bool {
const patterns = [_]u25 {
// columns
0b1000010000100001000010000,
0b0100001000010000100001000,
0b0010000100001000010000100,
0b0001000010000100001000010,
0b0000100001000010000100001,
// rows
0b1111100000000000000000000,
0b0000011111000000000000000,
0b0000000000111110000000000,
0b0000000000000001111100000,
0b0000000000000000000011111,
};
for (patterns) |pattern| {
if (mask & pattern == pattern) {
return true;
}
}
return false;
}
fn board_score(board: Board) u32 {
// sum up all the entries that have not been drawn in the board
var score: u32 = 0;
for (board.entries) |entry, i| {
var mask = @as(u25, 1) << @intCast(u5, i);
if (mask & board.mask == 0) {
score += entry;
}
}
return score;
}
fn get_answer_from_file(
allocator: std.mem.Allocator, filename: []const u8,
ndraws: u32, nboards: u32,
prefer_last_board: bool) !Answer {
var file = try fs.cwd().openFile(filename, .{ .read = true });
defer file.close();
var reader = std.io.bufferedReader(file.reader());
var in_stream = reader.reader();
var buffer: [512]u8 = undefined;
// {{{ get draws
var draws = try allocator.alloc(u32, ndraws);
defer allocator.free(draws);
// NOTE: first line always contains a comma-separated list of draws
if (try in_stream.readUntilDelimiterOrEof(&buffer, '\n')) |line| {
var i: u32 = 0;
var it = std.mem.tokenize(u8, line, ",");
while (it.next()) |item| {
draws[i] = try std.fmt.parseInt(u32, item, 10);
i += 1;
}
std.debug.assert(i == ndraws);
} else {
unreachable;
}
// }}}
// {{{ get boards
if (nboards == 0) {
return Answer{};
}
var boards = try allocator.alloc(Board, nboards);
defer allocator.free(boards);
{
var i: u32 = 0;
var j: u32 = 0;
while (try in_stream.readUntilDelimiterOrEof(&buffer, '\n')) |line| {
if (line.len == 0) {
// pass to the next board
std.debug.assert(i == 0 or j == 25);
i += 1;
j = 0;
boards[i - 1].mask = 0;
} else {
// read line into current board
var it = std.mem.tokenize(u8, line, " ");
while (it.next()) |item| {
boards[i - 1].entries[j] = try std.fmt.parseInt(u8, item, 10);
j += 1;
}
}
}
std.debug.assert(i == nboards);
}
// }}}
var unmarked_sum: u32 = 0;
var win_number: u32 = 0;
outer: for (draws) |draw| {
for (boards) |*board| {
for (board.entries) |entry, i| {
if (entry == draw) {
var entry_mask = @as(u25, 1) << @intCast(u5, i);
board.mask |= entry_mask;
if (board_is_winning(board.mask)) {
unmarked_sum = board_score(board.*);
win_number = draw;
break :outer;
}
}
}
}
}
return Answer{
.unmarked_sum = unmarked_sum,
.win_number = win_number,
};
}
pub fn main() void {
var gpa = std.heap.GeneralPurposeAllocator(.{}){};
var alloc = gpa.allocator();
defer _ = gpa.deinit();
var prefer_last_board = false; // false == part 1 and true == part 2
var example = get_answer_from_file(alloc, "example.txt", 27, 3, prefer_last_board) catch |err| {
std.debug.print("Couldn't read file: {s}", .{@errorName(err)});
return;
};
std.debug.print("sum {d} last {d}\n", .{example.unmarked_sum, example.win_number});
std.debug.print("Your example answer was {d}.\n", .{example.unmarked_sum * example.win_number});
var answer = get_answer_from_file(alloc, "input.txt", 100, 100, prefer_last_board) catch |err| {
std.debug.print("Couldn't read file: {s}", .{@errorName(err)});
return;
};
std.debug.print("sum {d} last {d}\n", .{answer.unmarked_sum, answer.win_number});
std.debug.print("Your puzzle answer was {d}.\n", .{answer.unmarked_sum * answer.win_number});
}
|
day4/main.zig
|
const std = @import("std");
const builtin = @import("builtin");
const gba = @import("gba.zig");
const nds = @import("nds/index.zig");
const utils = @import("utils.zig");
const randomizer = @import("randomizer.zig");
const clap = @import("clap.zig");
const pokemon = @import("pokemon/index.zig");
const gen3 = pokemon.gen3;
const gen4 = pokemon.gen4;
const gen5 = pokemon.gen5;
const os = std.os;
const debug = std.debug;
const mem = std.mem;
const io = std.io;
const rand = std.rand;
const fmt = std.fmt;
const path = os.path;
const Randomizer = randomizer.Randomizer;
// TODO: put into struct. There is no reason this should be global.
var help = false;
var input_file: []const u8 = "input";
var output_file: []const u8 = "randomized";
fn setHelp(op: *randomizer.Options, str: []const u8) anyerror!void {
help = true;
}
fn setInFile(op: *randomizer.Options, str: []const u8) anyerror!void {
input_file = str;
}
fn setOutFile(op: *randomizer.Options, str: []const u8) anyerror!void {
output_file = str;
}
fn setTrainerPokemon(op: *randomizer.Options, str: []const u8) !void {
if (mem.eql(u8, str, "same")) {
op.trainer.pokemon = randomizer.Options.Trainer.Pokemon.Same;
} else if (mem.eql(u8, str, "random")) {
op.trainer.pokemon = randomizer.Options.Trainer.Pokemon.Random;
} else if (mem.eql(u8, str, "same-type")) {
op.trainer.pokemon = randomizer.Options.Trainer.Pokemon.SameType;
} else if (mem.eql(u8, str, "type-themed")) {
op.trainer.pokemon = randomizer.Options.Trainer.Pokemon.TypeThemed;
} else if (mem.eql(u8, str, "legendaries")) {
op.trainer.pokemon = randomizer.Options.Trainer.Pokemon.Legendaries;
} else {
return error.InvalidOptions;
}
}
fn setTrainerSameStrength(op: *randomizer.Options, str: []const u8) anyerror!void {
op.trainer.same_total_stats = true;
}
fn setTrainerHeldItems(op: *randomizer.Options, str: []const u8) !void {
if (mem.eql(u8, str, "none")) {
op.trainer.held_items = randomizer.Options.Trainer.HeldItems.None;
} else if (mem.eql(u8, str, "same")) {
op.trainer.held_items = randomizer.Options.Trainer.HeldItems.Same;
//} else if (mem.eql(u8, str, "random")) {
// op.trainer.held_items = randomizer.Options.Trainer.HeldItems.Random;
//} else if (mem.eql(u8, str, "random-useful")) {
// op.trainer.held_items = randomizer.Options.Trainer.HeldItems.RandomUseful;
//} else if (mem.eql(u8, str, "random-best")) {
// op.trainer.held_items = randomizer.Options.Trainer.HeldItems.RandomBest;
} else {
return error.InvalidOptions;
}
}
fn setTrainerMoves(op: *randomizer.Options, str: []const u8) !void {
if (mem.eql(u8, str, "same")) {
op.trainer.moves = randomizer.Options.Trainer.Moves.Same;
} else if (mem.eql(u8, str, "random")) {
op.trainer.moves = randomizer.Options.Trainer.Moves.Random;
} else if (mem.eql(u8, str, "random-within-learnset")) {
op.trainer.moves = randomizer.Options.Trainer.Moves.RandomWithinLearnset;
} else if (mem.eql(u8, str, "best")) {
op.trainer.moves = randomizer.Options.Trainer.Moves.Best;
} else {
return error.InvalidOptions;
}
}
fn parseGenericOption(str: []const u8) !randomizer.GenericOption {
if (mem.eql(u8, str, "same")) {
return randomizer.GenericOption.Same;
} else if (mem.eql(u8, str, "random")) {
return randomizer.GenericOption.Random;
} else if (mem.eql(u8, str, "best")) {
return randomizer.GenericOption.Best;
} else {
return error.InvalidOptions;
}
}
fn setLevelModifier(op: *randomizer.Options, str: []const u8) !void {
const precent = try fmt.parseInt(i16, str, 10);
op.trainer.level_modifier = (@intToFloat(f64, precent) / 100) + 1;
}
const Arg = clap.Arg(randomizer.Options);
// TODO: Format is horrible. Fix
const program_arguments = comptime [8]Arg{
Arg.init(setHelp).help("Display this help and exit.").short('h').long("help").kind(Arg.Kind.IgnoresRequired),
Arg.init(setInFile).help("The rom to randomize.").kind(Arg.Kind.Required),
Arg.init(setOutFile).help("The place to output the randomized rom.").short('o').long("output").takesValue(true),
Arg.init(setTrainerPokemon).help("How trainer Pokémons should be randomized. Options: [same, random, same-type, type-themed, legendaries].").long("trainer-pokemon").takesValue(true),
Arg.init(setTrainerSameStrength).help("The randomizer will replace trainers Pokémon with Pokémon of similar total stats.").long("trainer-same-total-stats"),
Arg.init(setTrainerHeldItems).help("How trainer Pokémon held items should be randomized. Options: [none, same].").long("trainer-held-items").takesValue(true),
Arg.init(setTrainerMoves).help("How trainer Pokémon moves should be randomized. Options: [same, random, random-within-learnset, best].").long("trainer-moves").takesValue(true),
Arg.init(setLevelModifier).help("A percent level modifier to trainers Pokémon.").long("trainer-level-modifier").takesValue(true),
};
pub fn main() !void {
// TODO: Use Zig's own general purpose allocator... When it has one.
var direct_allocator = std.heap.DirectAllocator.init();
defer direct_allocator.deinit();
var arena = std.heap.ArenaAllocator.init(&direct_allocator.allocator);
defer arena.deinit();
const allocator = &arena.allocator;
var stdout_handle = try io.getStdOut();
var stdout_file_stream = stdout_handle.outStream();
var stdout = &stdout_file_stream.stream;
const args = try os.argsAlloc(allocator);
defer os.argsFree(allocator, args);
const options = clap.parse(randomizer.Options, program_arguments, randomizer.Options.default(), args) catch |err| {
// TODO: Write useful error message to user
return err;
};
if (help) {
try clap.help(randomizer.Options, program_arguments, stdout);
return;
}
var rom_file = os.File.openRead(input_file) catch |err| {
debug.warn("Couldn't open {}.\n", input_file);
return err;
};
defer rom_file.close();
var game = pokemon.Game.load(rom_file, allocator) catch |err| {
debug.warn("Couldn't load game {}.\n", input_file);
return err;
};
defer game.deinit();
var random = rand.DefaultPrng.init(blk: {
var buf: [8]u8 = undefined;
try std.os.getRandomBytes(buf[0..]);
break :blk mem.readInt(buf[0..8], u64, builtin.Endian.Little);
});
var r = Randomizer.init(game, &random.random, allocator);
r.randomize(options) catch |err| {
debug.warn("Randomizing error occured {}.\n", @errorName(err));
return err;
};
var out_file = os.File.openWrite(output_file) catch |err| {
debug.warn("Couldn't open {}.\n", output_file);
return err;
};
defer out_file.close();
game.save(out_file) catch |err| {
debug.warn("Couldn't save game {}.\n", @errorName(err));
return err;
};
}
|
src/main.zig
|
const std = @import("std");
const assert = std.debug.assert;
const uart = @import("./uart.zig");
/// A Page descriptor, stored starting at __heap_start.
const Page = extern struct {
flags: u8,
pub const Flags = enum(u8) {
empty = 0b0000_0000,
taken = 0b0000_0001,
last = 0b0000_00010,
};
pub inline fn isTaken(self: Page) bool {
return (self.flags & @enumToInt(Flags.taken) > 0);
}
pub inline fn isLast(self: Page) bool {
return (self.flags & @enumToInt(Flags.last) > 0);
}
pub inline fn isFree(self: Page) bool {
return !isTaken(self);
}
};
pub const page_size = 4096;
/// whether or not to spam debug information to UART in methods
const debug = @import("build_options").log_heap;
// take the address of these you fuckdoodle
extern const __heap_start: u8;
extern const __heap_end: u8;
var heap_start: usize = undefined;
var heap_end: usize = undefined;
var heap_size: usize = undefined;
var alloc_start: usize = undefined;
var num_pages: usize = undefined;
var descriptors: []volatile Page = undefined;
/// This mirrors std.heap.page_allocator in that it always allocates at least one page
pub var kpagealloc = std.mem.Allocator{
.reallocFn = kPageAllocRealloc,
.shrinkFn = kPageAllocShrink,
};
fn kPageAllocRealloc(self: *std.mem.Allocator, old_mem: []u8, old_alignment: u29, new_byte_count: usize, new_alignment: u29) std.mem.Allocator.Error![]u8 {
if (comptime debug)
uart.print("kPageAllocRealloc invoked: old_mem {}:{}, new_byte_count {}\n", .{ old_mem.ptr, old_mem.len, new_byte_count });
if (new_alignment > page_size) return error.OutOfMemory; // why would you even
if (old_mem.len == 0 or new_byte_count > page_size) {
// create a new allocation
const ptr = (try allocPages((new_byte_count / page_size) + 1))[0..new_byte_count];
// move pre-existing allocation if it exists
for (old_mem) |b, i| ptr[i] = b;
return ptr;
}
if (new_byte_count <= page_size) {
// shrink this allocation
if (old_mem.len <= page_size) {
// it's all on one page so pretend we actually shrunk the page
return @ptrCast([*]u8, old_mem)[0..new_byte_count];
} else {
// we have extra pages left over
return kPageAllocShrink(self, old_mem, old_alignment, new_byte_count, new_alignment);
}
}
return error.OutOfMemory;
}
fn kPageAllocShrink(self: *std.mem.Allocator, old_mem: []u8, old_alignment: u29, new_byte_count: usize, new_alignment: u29) []u8 {
if (comptime debug)
uart.print("kPageAllocShrink invoked: old_mem {}:{}, new_byte_count {}\n", .{ old_mem.ptr, old_mem.len, new_byte_count });
if (new_byte_count == 0 or old_mem.len / page_size > new_byte_count / page_size) {
// free pages at the end
const free_start = (@ptrToInt(old_mem.ptr) + new_byte_count) + ((@ptrToInt(old_mem.ptr) + new_byte_count) % page_size);
const free_size = old_mem.len - new_byte_count;
freePages(@intToPtr([*]u8, free_start)[0..free_size]);
}
return old_mem[0..new_byte_count];
}
/// Initialize all page descriptors and related work. Must have been called
/// before any allocation occurs.
pub fn init() void {
// set global variables to linker provided addresses
heap_start = @ptrToInt(&__heap_start);
assert(heap_start % page_size == 0);
heap_end = @ptrToInt(&__heap_end);
assert(heap_end % page_size == 0);
assert(heap_start < heap_end);
heap_size = heap_end - heap_start;
// calculate maximum number of pages
num_pages = heap_size / page_size;
// calculate actual allocation start without descriptors and align it
alloc_start = heap_start + num_pages * @sizeOf(Page);
alloc_start = alloc_start + (page_size - (alloc_start % page_size));
assert(alloc_start % page_size == 0);
// calculate actual number of pages
num_pages = (heap_end - alloc_start) / page_size;
descriptors = @intToPtr([*]volatile Page, heap_start)[0..num_pages];
for (descriptors) |*page, index| {
page.* = .{ .flags = @enumToInt(Page.Flags.empty) };
}
if (comptime debug)
uart.print(
\\init heap...
\\ start at 0x{x}, size 0x{x}
\\ {} pages starting at 0x{x}
\\
,
.{ heap_start, heap_size, num_pages, alloc_start },
);
}
/// Allocate `num` pages, returning a zeroed slice of memory or error.OutOfMemory.
pub fn allocPages(num: usize) ![]u8 {
if (comptime debug)
uart.print("alloc_pages invoked with num {}\n", .{num});
defer {
if (comptime debug) dumpPageTable();
}
assert(num > 0);
if (num > num_pages) return error.OutOfMemory;
var already_visited: usize = 0;
outer: for (descriptors) |*page, index| {
// skip if any pages in the set aren't free or we've already explored them and they were taken
if (page.isTaken() or already_visited > index) continue;
for (descriptors[index .. index + num]) |*other_page| {
if (other_page.isTaken()) {
already_visited += 1;
continue :outer;
}
}
// set page descriptors
for (descriptors[index .. index + num]) |*free_page, inner_index| {
assert(free_page.isFree());
free_page.*.flags |= @enumToInt(Page.Flags.taken);
if (inner_index == (num - 1)) {
free_page.*.flags |= @enumToInt(Page.Flags.last);
}
}
// zero out actual memory
const result = @intToPtr([*]u8, alloc_start)[index * page_size .. (index + num) * page_size];
for (result) |*b| b.* = 0;
return result;
}
return error.OutOfMemory;
}
/// Returns pages into the pool of available pages and zeroes them out. Doesn't fail.
/// Pointer must be one that's been returned from heap.alloc_pages().
pub fn freePages(ptr: []u8) void {
if (comptime debug)
uart.print("free_pages invoked with ptr {}:{}\n", .{ ptr.ptr, ptr.len });
defer {
if (comptime debug) dumpPageTable();
}
assert(@ptrToInt(ptr.ptr) % page_size == 0);
const page_count = (ptr.len / page_size) + 1;
const first_page = (@ptrToInt(ptr.ptr) - alloc_start) / page_size;
for (descriptors[first_page .. first_page + page_count]) |*desc, index| {
assert(desc.isTaken());
if (index == page_count - 1) assert(desc.isLast());
desc.*.flags = @enumToInt(Page.Flags.empty);
}
for (ptr) |*b| b.* = 0;
}
pub fn statistics(kind: enum { pages_taken, pages_total }) usize {
return switch (kind) {
.pages_total => num_pages,
.pages_taken => blk: {
var c: usize = 0;
for (descriptors) |desc| {
if (desc.isTaken()) c += 1;
}
break :blk c;
},
};
}
fn dumpPageTable() void {
for (descriptors) |desc, id| {
if (desc.isTaken()) uart.print("0x{x:0>3}\t{b:0>8}\n", .{ id, desc.flags });
}
}
|
src/heap.zig
|
const std = @import("std");
fn root() []const u8 {
return std.fs.path.dirname(@src().file) orelse ".";
}
const root_path = root() ++ "/";
pub const include_dir = root_path ++ "curl/include";
const package_path = root_path ++ "src/main.zig";
const lib_dir = root_path ++ "curl/lib";
pub const Define = struct {
key: []const u8,
value: ?[]const u8,
};
pub const Options = struct {
import_name: ?[]const u8 = null,
};
pub const Library = struct {
exported_defines: []Define,
step: *std.build.LibExeObjStep,
pub fn link(self: Library, other: *std.build.LibExeObjStep, opts: Options) void {
for (self.exported_defines) |def|
other.defineCMacro(def.key, def.value);
other.addIncludeDir(include_dir);
other.linkLibrary(self.step);
if (opts.import_name) |import_name|
other.addPackagePath(import_name, package_path);
}
};
pub fn create(
b: *std.build.Builder,
target: std.zig.CrossTarget,
mode: std.builtin.Mode,
) !Library {
const ret = b.addStaticLibrary("curl", null);
ret.setTarget(target);
ret.setBuildMode(mode);
ret.addCSourceFiles(srcs, &.{});
ret.addIncludeDir(include_dir);
ret.addIncludeDir(lib_dir);
ret.linkLibC();
var exported_defines = std.ArrayList(Define).init(b.allocator);
defer exported_defines.deinit();
ret.defineCMacro("BUILDING_LIBCURL", null);
// when not building a shared library
ret.defineCMacro("CURL_STATICLIB", "1");
try exported_defines.append(.{ .key = "CURL_STATICLIB", .value = "1" });
// disables LDAP
ret.defineCMacro("CURL_DISABLE_LDAP", "1");
// disables LDAPS
ret.defineCMacro("CURL_DISABLE_LDAPS", "1");
// if mbedTLS is enabled
ret.defineCMacro("USE_MBEDTLS", "1");
// disables alt-svc
// #undef CURL_DISABLE_ALTSVC
// disables cookies support
// #undef CURL_DISABLE_COOKIES
// disables cryptographic authentication
// #undef CURL_DISABLE_CRYPTO_AUTH
// disables DICT
ret.defineCMacro("CURL_DISABLE_DICT", "1");
// disables DNS-over-HTTPS
// #undef CURL_DISABLE_DOH
// disables FILE
ret.defineCMacro("CURL_DISABLE_FILE", "1");
// disables FTP
ret.defineCMacro("CURL_DISABLE_FTP", "1");
// disables GOPHER
ret.defineCMacro("CURL_DISABLE_GOPHER", "1");
// disables HSTS support
// #undef CURL_DISABLE_HSTS
// disables HTTP
// #undef CURL_DISABLE_HTTP
// disables IMAP
ret.defineCMacro("CURL_DISABLE_IMAP", "1");
// disables --libcurl option from the curl tool
// #undef CURL_DISABLE_LIBCURL_OPTION
// disables MIME support
// #undef CURL_DISABLE_MIME
// disables MQTT
ret.defineCMacro("CURL_DISABLE_MQTT", "1");
// disables netrc parser
// #undef CURL_DISABLE_NETRC
// disables NTLM support
// #undef CURL_DISABLE_NTLM
// disables date parsing
// #undef CURL_DISABLE_PARSEDATE
// disables POP3
ret.defineCMacro("CURL_DISABLE_POP3", "1");
// disables built-in progress meter
// #undef CURL_DISABLE_PROGRESS_METER
// disables proxies
// #undef CURL_DISABLE_PROXY
// disables RTSP
ret.defineCMacro("CURL_DISABLE_RTSP", "1");
// disables SMB
ret.defineCMacro("CURL_DISABLE_SMB", "1");
// disables SMTP
ret.defineCMacro("CURL_DISABLE_SMTP", "1");
// disables use of socketpair for curl_multi_poll
// #undef CURL_DISABLE_SOCKETPAIR
// disables TELNET
ret.defineCMacro("CURL_DISABLE_TELNET", "1");
// disables TFTP
ret.defineCMacro("CURL_DISABLE_TFTP", "1");
// disables verbose strings
// #undef CURL_DISABLE_VERBOSE_STRINGS
// Define to 1 if you have the `ssh2' library (-lssh2).
ret.defineCMacro("HAVE_LIBSSH2", "1");
// Define to 1 if you have the <libssh2.h> header file.
ret.defineCMacro("HAVE_LIBSSH2_H", "1");
// if zlib is available
ret.defineCMacro("HAVE_LIBZ", "1");
// if you have the zlib.h header file
ret.defineCMacro("HAVE_ZLIB_H", "1");
if (target.isWindows()) {
// Define if you want to enable WIN32 threaded DNS lookup
//ret.defineCMacro("USE_THREADS_WIN32", "1");
return Library{ .step = ret, .exported_defines = exported_defines.toOwnedSlice() };
}
//ret.defineCMacro("libcurl_EXPORTS", null);
//ret.defineCMacro("STDC_HEADERS", null);
// when building libcurl itself
// #undef BUILDING_LIBCURL
// Location of default ca bundle
// ret.defineCMacro("CURL_CA_BUNDLE", "\"/etc/ssl/certs/ca-certificates.crt\"");
// define "1" to use built-in ca store of TLS backend
// #undef CURL_CA_FALLBACK
// Location of default ca path
// ret.defineCMacro("CURL_CA_PATH", "\"/etc/ssl/certs\"");
// to make a symbol visible
ret.defineCMacro("CURL_EXTERN_SYMBOL", "__attribute__ ((__visibility__ (\"default\"))");
// Ensure using CURL_EXTERN_SYMBOL is possible
//#ifndef CURL_EXTERN_SYMBOL
//ret.defineCMacro("CURL_EXTERN_SYMBOL
//#endif
// Allow SMB to work on Windows
// #undef USE_WIN32_CRYPTO
// Use Windows LDAP implementation
// #undef USE_WIN32_LDAP
// your Entropy Gathering Daemon socket pathname
// #undef EGD_SOCKET
// Define if you want to enable IPv6 support
if (!target.isDarwin())
ret.defineCMacro("ENABLE_IPV6", "1");
// Define to 1 if you have the alarm function.
ret.defineCMacro("HAVE_ALARM", "1");
// Define to 1 if you have the <alloca.h> header file.
ret.defineCMacro("HAVE_ALLOCA_H", "1");
// Define to 1 if you have the <arpa/inet.h> header file.
ret.defineCMacro("HAVE_ARPA_INET_H", "1");
// Define to 1 if you have the <arpa/tftp.h> header file.
ret.defineCMacro("HAVE_ARPA_TFTP_H", "1");
// Define to 1 if you have the <assert.h> header file.
ret.defineCMacro("HAVE_ASSERT_H", "1");
// Define to 1 if you have the `basename' function.
ret.defineCMacro("HAVE_BASENAME", "1");
// Define to 1 if bool is an available type.
ret.defineCMacro("HAVE_BOOL_T", "1");
// Define to 1 if you have the __builtin_available function.
ret.defineCMacro("HAVE_BUILTIN_AVAILABLE", "1");
// Define to 1 if you have the clock_gettime function and monotonic timer.
ret.defineCMacro("HAVE_CLOCK_GETTIME_MONOTONIC", "1");
// Define to 1 if you have the `closesocket' function.
// #undef HAVE_CLOSESOCKET
// Define to 1 if you have the `CRYPTO_cleanup_all_ex_data' function.
// #undef HAVE_CRYPTO_CLEANUP_ALL_EX_DATA
// Define to 1 if you have the <dlfcn.h> header file.
ret.defineCMacro("HAVE_DLFCN_H", "1");
// Define to 1 if you have the <errno.h> header file.
ret.defineCMacro("HAVE_ERRNO_H", "1");
// Define to 1 if you have the fcntl function.
ret.defineCMacro("HAVE_FCNTL", "1");
// Define to 1 if you have the <fcntl.h> header file.
ret.defineCMacro("HAVE_FCNTL_H", "1");
// Define to 1 if you have a working fcntl O_NONBLOCK function.
ret.defineCMacro("HAVE_FCNTL_O_NONBLOCK", "1");
// Define to 1 if you have the freeaddrinfo function.
ret.defineCMacro("HAVE_FREEADDRINFO", "1");
// Define to 1 if you have the ftruncate function.
ret.defineCMacro("HAVE_FTRUNCATE", "1");
// Define to 1 if you have a working getaddrinfo function.
ret.defineCMacro("HAVE_GETADDRINFO", "1");
// Define to 1 if you have the `geteuid' function.
ret.defineCMacro("HAVE_GETEUID", "1");
// Define to 1 if you have the `getppid' function.
ret.defineCMacro("HAVE_GETPPID", "1");
// Define to 1 if you have the gethostbyname function.
ret.defineCMacro("HAVE_GETHOSTBYNAME", "1");
// Define to 1 if you have the gethostbyname_r function.
if (!target.isDarwin())
ret.defineCMacro("HAVE_GETHOSTBYNAME_R", "1");
// gethostbyname_r() takes 3 args
// #undef HAVE_GETHOSTBYNAME_R_3
// gethostbyname_r() takes 5 args
// #undef HAVE_GETHOSTBYNAME_R_5
// gethostbyname_r() takes 6 args
ret.defineCMacro("HAVE_GETHOSTBYNAME_R_6", "1");
// Define to 1 if you have the gethostname function.
ret.defineCMacro("HAVE_GETHOSTNAME", "1");
// Define to 1 if you have a working getifaddrs function.
// #undef HAVE_GETIFADDRS
// Define to 1 if you have the `getpass_r' function.
// #undef HAVE_GETPASS_R
// Define to 1 if you have the `getppid' function.
ret.defineCMacro("HAVE_GETPPID", "1");
// Define to 1 if you have the `getprotobyname' function.
ret.defineCMacro("HAVE_GETPROTOBYNAME", "1");
// Define to 1 if you have the `getpeername' function.
ret.defineCMacro("HAVE_GETPEERNAME", "1");
// Define to 1 if you have the `getsockname' function.
ret.defineCMacro("HAVE_GETSOCKNAME", "1");
// Define to 1 if you have the `if_nametoindex' function.
ret.defineCMacro("HAVE_IF_NAMETOINDEX", "1");
// Define to 1 if you have the `getpwuid' function.
ret.defineCMacro("HAVE_GETPWUID", "1");
// Define to 1 if you have the `getpwuid_r' function.
ret.defineCMacro("HAVE_GETPWUID_R", "1");
// Define to 1 if you have the `getrlimit' function.
ret.defineCMacro("HAVE_GETRLIMIT", "1");
// Define to 1 if you have the `gettimeofday' function.
ret.defineCMacro("HAVE_GETTIMEOFDAY", "1");
// Define to 1 if you have a working glibc-style strerror_r function.
// #undef HAVE_GLIBC_STRERROR_R
// Define to 1 if you have a working gmtime_r function.
ret.defineCMacro("HAVE_GMTIME_R", "1");
// if you have the gssapi libraries
// #undef HAVE_GSSAPI
// Define to 1 if you have the <gssapi/gssapi_generic.h> header file.
// #undef HAVE_GSSAPI_GSSAPI_GENERIC_H
// Define to 1 if you have the <gssapi/gssapi.h> header file.
// #undef HAVE_GSSAPI_GSSAPI_H
// Define to 1 if you have the <gssapi/gssapi_krb5.h> header file.
// #undef HAVE_GSSAPI_GSSAPI_KRB5_H
// if you have the GNU gssapi libraries
// #undef HAVE_GSSGNU
// if you have the Heimdal gssapi libraries
// #undef HAVE_GSSHEIMDAL
// if you have the MIT gssapi libraries
// #undef HAVE_GSSMIT
// Define to 1 if you have the `idna_strerror' function.
// #undef HAVE_IDNA_STRERROR
// Define to 1 if you have the `idn_free' function.
// #undef HAVE_IDN_FREE
// Define to 1 if you have the <idn-free.h> header file.
// #undef HAVE_IDN_FREE_H
// Define to 1 if you have the <ifaddrs.h> header file.
ret.defineCMacro("HAVE_IFADDRS_H", "1");
// Define to 1 if you have the `inet_addr' function.
ret.defineCMacro("HAVE_INET_ADDR", "1");
// Define to 1 if you have a IPv6 capable working inet_ntop function.
// #undef HAVE_INET_NTOP
// Define to 1 if you have a IPv6 capable working inet_pton function.
ret.defineCMacro("HAVE_INET_PTON", "1");
// Define to 1 if symbol `sa_family_t' exists
ret.defineCMacro("HAVE_SA_FAMILY_T", "1");
// Define to 1 if symbol `ADDRESS_FAMILY' exists
// #undef HAVE_ADDRESS_FAMILY
// Define to 1 if you have the <inttypes.h> header file.
ret.defineCMacro("HAVE_INTTYPES_H", "1");
// Define to 1 if you have the ioctl function.
ret.defineCMacro("HAVE_IOCTL", "1");
// Define to 1 if you have the ioctlsocket function.
// #undef HAVE_IOCTLSOCKET
// Define to 1 if you have the IoctlSocket camel case function.
// #undef HAVE_IOCTLSOCKET_CAMEL
// Define to 1 if you have a working IoctlSocket camel case FIONBIO function.
// #undef HAVE_IOCTLSOCKET_CAMEL_FIONBIO
// Define to 1 if you have a working ioctlsocket FIONBIO function.
// #undef HAVE_IOCTLSOCKET_FIONBIO
// Define to 1 if you have a working ioctl FIONBIO function.
ret.defineCMacro("HAVE_IOCTL_FIONBIO", "1");
// Define to 1 if you have a working ioctl SIOCGIFADDR function.
ret.defineCMacro("HAVE_IOCTL_SIOCGIFADDR", "1");
// Define to 1 if you have the <io.h> header file.
// #undef HAVE_IO_H
// if you have the Kerberos4 libraries (including -ldes)
// #undef HAVE_KRB4
// Define to 1 if you have the `krb_get_our_ip_for_realm' function.
// #undef HAVE_KRB_GET_OUR_IP_FOR_REALM
// Define to 1 if you have the <krb.h> header file.
// #undef HAVE_KRB_H
// Define to 1 if you have the lber.h header file.
// #undef HAVE_LBER_H
// Define to 1 if you have the ldapssl.h header file.
// #undef HAVE_LDAPSSL_H
// Define to 1 if you have the ldap.h header file.
// #undef HAVE_LDAP_H
// Use LDAPS implementation
// #undef HAVE_LDAP_SSL
// Define to 1 if you have the ldap_ssl.h header file.
// #undef HAVE_LDAP_SSL_H
// Define to 1 if you have the `ldap_url_parse' function.
ret.defineCMacro("HAVE_LDAP_URL_PARSE", "1");
// Define to 1 if you have the <libgen.h> header file.
ret.defineCMacro("HAVE_LIBGEN_H", "1");
// Define to 1 if you have the `idn2' library (-lidn2).
// #undef HAVE_LIBIDN2
// Define to 1 if you have the idn2.h header file.
ret.defineCMacro("HAVE_IDN2_H", "1");
// Define to 1 if you have the `resolv' library (-lresolv).
// #undef HAVE_LIBRESOLV
// Define to 1 if you have the `resolve' library (-lresolve).
// #undef HAVE_LIBRESOLVE
// Define to 1 if you have the `socket' library (-lsocket).
// #undef HAVE_LIBSOCKET
// if brotli is available
// #undef HAVE_BROTLI
// if zstd is available
// #undef HAVE_ZSTD
// if your compiler supports LL
ret.defineCMacro("HAVE_LL", "1");
// Define to 1 if you have the <locale.h> header file.
ret.defineCMacro("HAVE_LOCALE_H", "1");
// Define to 1 if you have a working localtime_r function.
ret.defineCMacro("HAVE_LOCALTIME_R", "1");
// Define to 1 if the compiler supports the 'long long' data type.
ret.defineCMacro("HAVE_LONGLONG", "1");
// Define to 1 if you have the malloc.h header file.
ret.defineCMacro("HAVE_MALLOC_H", "1");
// Define to 1 if you have the <memory.h> header file.
ret.defineCMacro("HAVE_MEMORY_H", "1");
// Define to 1 if you have the MSG_NOSIGNAL flag.
if (!target.isDarwin())
ret.defineCMacro("HAVE_MSG_NOSIGNAL", "1");
// Define to 1 if you have the <netdb.h> header file.
ret.defineCMacro("HAVE_NETDB_H", "1");
// Define to 1 if you have the <netinet/in.h> header file.
ret.defineCMacro("HAVE_NETINET_IN_H", "1");
// Define to 1 if you have the <netinet/tcp.h> header file.
ret.defineCMacro("HAVE_NETINET_TCP_H", "1");
// Define to 1 if you have the <linux/tcp.h> header file.
if (target.isLinux())
ret.defineCMacro("HAVE_LINUX_TCP_H", "1");
// Define to 1 if you have the <net/if.h> header file.
ret.defineCMacro("HAVE_NET_IF_H", "1");
// Define to 1 if NI_WITHSCOPEID exists and works.
// #undef HAVE_NI_WITHSCOPEID
// if you have an old MIT gssapi library, lacking GSS_C_NT_HOSTBASED_SERVICE
// #undef HAVE_OLD_GSSMIT
// Define to 1 if you have the <pem.h> header file.
// #undef HAVE_PEM_H
// Define to 1 if you have the `pipe' function.
ret.defineCMacro("HAVE_PIPE", "1");
// Define to 1 if you have a working poll function.
ret.defineCMacro("HAVE_POLL", "1");
// If you have a fine poll
ret.defineCMacro("HAVE_POLL_FINE", "1");
// Define to 1 if you have the <poll.h> header file.
ret.defineCMacro("HAVE_POLL_H", "1");
// Define to 1 if you have a working POSIX-style strerror_r function.
ret.defineCMacro("HAVE_POSIX_STRERROR_R", "1");
// Define to 1 if you have the <pthread.h> header file
ret.defineCMacro("HAVE_PTHREAD_H", "1");
// Define to 1 if you have the <pwd.h> header file.
ret.defineCMacro("HAVE_PWD_H", "1");
// Define to 1 if you have the `RAND_egd' function.
// #undef HAVE_RAND_EGD
// Define to 1 if you have the `RAND_screen' function.
// #undef HAVE_RAND_SCREEN
// Define to 1 if you have the `RAND_status' function.
// #undef HAVE_RAND_STATUS
// Define to 1 if you have the recv function.
ret.defineCMacro("HAVE_RECV", "1");
// Define to 1 if you have the recvfrom function.
// #undef HAVE_RECVFROM
// Define to 1 if you have the select function.
ret.defineCMacro("HAVE_SELECT", "1");
// Define to 1 if you have the send function.
ret.defineCMacro("HAVE_SEND", "1");
// Define to 1 if you have the 'fsetxattr' function.
ret.defineCMacro("HAVE_FSETXATTR", "1");
// fsetxattr() takes 5 args
ret.defineCMacro("HAVE_FSETXATTR_5", "1");
// fsetxattr() takes 6 args
// #undef HAVE_FSETXATTR_6
// Define to 1 if you have the <setjmp.h> header file.
ret.defineCMacro("HAVE_SETJMP_H", "1");
// Define to 1 if you have the `setlocale' function.
ret.defineCMacro("HAVE_SETLOCALE", "1");
// Define to 1 if you have the `setmode' function.
// #undef HAVE_SETMODE
// Define to 1 if you have the `setrlimit' function.
ret.defineCMacro("HAVE_SETRLIMIT", "1");
// Define to 1 if you have the setsockopt function.
ret.defineCMacro("HAVE_SETSOCKOPT", "1");
// Define to 1 if you have a working setsockopt SO_NONBLOCK function.
// #undef HAVE_SETSOCKOPT_SO_NONBLOCK
// Define to 1 if you have the sigaction function.
ret.defineCMacro("HAVE_SIGACTION", "1");
// Define to 1 if you have the siginterrupt function.
ret.defineCMacro("HAVE_SIGINTERRUPT", "1");
// Define to 1 if you have the signal function.
ret.defineCMacro("HAVE_SIGNAL", "1");
// Define to 1 if you have the <signal.h> header file.
ret.defineCMacro("HAVE_SIGNAL_H", "1");
// Define to 1 if you have the sigsetjmp function or macro.
ret.defineCMacro("HAVE_SIGSETJMP", "1");
// Define to 1 if struct sockaddr_in6 has the sin6_scope_id member
ret.defineCMacro("HAVE_SOCKADDR_IN6_SIN6_SCOPE_ID", "1");
// Define to 1 if you have the `socket' function.
ret.defineCMacro("HAVE_SOCKET", "1");
// Define to 1 if you have the <stdbool.h> header file.
ret.defineCMacro("HAVE_STDBOOL_H", "1");
// Define to 1 if you have the <stdint.h> header file.
ret.defineCMacro("HAVE_STDINT_H", "1");
// Define to 1 if you have the <stdio.h> header file.
ret.defineCMacro("HAVE_STDIO_H", "1");
// Define to 1 if you have the <stdlib.h> header file.
ret.defineCMacro("HAVE_STDLIB_H", "1");
// Define to 1 if you have the strcasecmp function.
ret.defineCMacro("HAVE_STRCASECMP", "1");
// Define to 1 if you have the strcasestr function.
// #undef HAVE_STRCASESTR
// Define to 1 if you have the strcmpi function.
// #undef HAVE_STRCMPI
// Define to 1 if you have the strdup function.
ret.defineCMacro("HAVE_STRDUP", "1");
// Define to 1 if you have the strerror_r function.
ret.defineCMacro("HAVE_STRERROR_R", "1");
// Define to 1 if you have the stricmp function.
// #undef HAVE_STRICMP
// Define to 1 if you have the <strings.h> header file.
ret.defineCMacro("HAVE_STRINGS_H", "1");
// Define to 1 if you have the <string.h> header file.
ret.defineCMacro("HAVE_STRING_H", "1");
// Define to 1 if you have the strncmpi function.
// #undef HAVE_STRNCMPI
// Define to 1 if you have the strnicmp function.
// #undef HAVE_STRNICMP
// Define to 1 if you have the <stropts.h> header file.
// #undef HAVE_STROPTS_H
// Define to 1 if you have the strstr function.
ret.defineCMacro("HAVE_STRSTR", "1");
// Define to 1 if you have the strtok_r function.
ret.defineCMacro("HAVE_STRTOK_R", "1");
// Define to 1 if you have the strtoll function.
ret.defineCMacro("HAVE_STRTOLL", "1");
// if struct sockaddr_storage is defined
ret.defineCMacro("HAVE_STRUCT_SOCKADDR_STORAGE", "1");
// Define to 1 if you have the timeval struct.
ret.defineCMacro("HAVE_STRUCT_TIMEVAL", "1");
// Define to 1 if you have the <sys/filio.h> header file.
// #undef HAVE_SYS_FILIO_H
// Define to 1 if you have the <sys/ioctl.h> header file.
ret.defineCMacro("HAVE_SYS_IOCTL_H", "1");
// Define to 1 if you have the <sys/param.h> header file.
ret.defineCMacro("HAVE_SYS_PARAM_H", "1");
// Define to 1 if you have the <sys/poll.h> header file.
ret.defineCMacro("HAVE_SYS_POLL_H", "1");
// Define to 1 if you have the <sys/resource.h> header file.
ret.defineCMacro("HAVE_SYS_RESOURCE_H", "1");
// Define to 1 if you have the <sys/select.h> header file.
ret.defineCMacro("HAVE_SYS_SELECT_H", "1");
// Define to 1 if you have the <sys/socket.h> header file.
ret.defineCMacro("HAVE_SYS_SOCKET_H", "1");
// Define to 1 if you have the <sys/sockio.h> header file.
// #undef HAVE_SYS_SOCKIO_H
// Define to 1 if you have the <sys/stat.h> header file.
ret.defineCMacro("HAVE_SYS_STAT_H", "1");
// Define to 1 if you have the <sys/time.h> header file.
ret.defineCMacro("HAVE_SYS_TIME_H", "1");
// Define to 1 if you have the <sys/types.h> header file.
ret.defineCMacro("HAVE_SYS_TYPES_H", "1");
// Define to 1 if you have the <sys/uio.h> header file.
ret.defineCMacro("HAVE_SYS_UIO_H", "1");
// Define to 1 if you have the <sys/un.h> header file.
ret.defineCMacro("HAVE_SYS_UN_H", "1");
// Define to 1 if you have the <sys/utime.h> header file.
// #undef HAVE_SYS_UTIME_H
// Define to 1 if you have the <termios.h> header file.
ret.defineCMacro("HAVE_TERMIOS_H", "1");
// Define to 1 if you have the <termio.h> header file.
ret.defineCMacro("HAVE_TERMIO_H", "1");
// Define to 1 if you have the <time.h> header file.
ret.defineCMacro("HAVE_TIME_H", "1");
// Define to 1 if you have the <tld.h> header file.
// #undef HAVE_TLD_H
// Define to 1 if you have the `tld_strerror' function.
// #undef HAVE_TLD_STRERROR
// Define to 1 if you have the `uname' function.
ret.defineCMacro("HAVE_UNAME", "1");
// Define to 1 if you have the <unistd.h> header file.
ret.defineCMacro("HAVE_UNISTD_H", "1");
// Define to 1 if you have the `utime' function.
ret.defineCMacro("HAVE_UTIME", "1");
// Define to 1 if you have the `utimes' function.
ret.defineCMacro("HAVE_UTIMES", "1");
// Define to 1 if you have the <utime.h> header file.
ret.defineCMacro("HAVE_UTIME_H", "1");
// Define to 1 if compiler supports C99 variadic macro style.
ret.defineCMacro("HAVE_VARIADIC_MACROS_C99", "1");
// Define to 1 if compiler supports old gcc variadic macro style.
ret.defineCMacro("HAVE_VARIADIC_MACROS_GCC", "1");
// Define to 1 if you have the winber.h header file.
// #undef HAVE_WINBER_H
// Define to 1 if you have the windows.h header file.
// #undef HAVE_WINDOWS_H
// Define to 1 if you have the winldap.h header file.
// #undef HAVE_WINLDAP_H
// Define to 1 if you have the winsock2.h header file.
// #undef HAVE_WINSOCK2_H
// Define this symbol if your OS supports changing the contents of argv
// #undef HAVE_WRITABLE_ARGV
// Define to 1 if you have the writev function.
// #undef HAVE_WRITEV
// Define to 1 if you have the ws2tcpip.h header file.
// #undef HAVE_WS2TCPIP_H
// Define to 1 if you have the <x509.h> header file.
// #undef HAVE_X509_H
// Define if you have the <process.h> header file.
// #undef HAVE_PROCESS_H
// Define to the sub-directory in which libtool stores uninstalled libraries.
// #undef LT_OBJDIR
// If you lack a fine basename() prototype
// #undef NEED_BASENAME_PROTO
// Define to 1 if you need the lber.h header file even with ldap.h
// #undef NEED_LBER_H
// Define to 1 if you need the malloc.h header file even with stdlib.h
// #undef NEED_MALLOC_H
// Define to 1 if _REENTRANT preprocessor symbol must be defined.
// #undef NEED_REENTRANT
// cpu-machine-OS
ret.defineCMacro("OS", "\"Linux\"");
// Name of package
// #undef PACKAGE
// Define to the address where bug reports for this package should be sent.
// #undef PACKAGE_BUGREPORT
// Define to the full name of this package.
// #undef PACKAGE_NAME
// Define to the full name and version of this package.
// #undef PACKAGE_STRING
// Define to the one symbol short name of this package.
// #undef PACKAGE_TARNAME
// Define to the version of this package.
// #undef PACKAGE_VERSION
// a suitable file to read random data from
ret.defineCMacro("RANDOM_FILE", "\"/dev/urandom\"");
// Define to the type of arg 1 for recvfrom.
// #undef RECVFROM_TYPE_ARG1
// Define to the type pointed by arg 2 for recvfrom.
// #undef RECVFROM_TYPE_ARG2
// Define to 1 if the type pointed by arg 2 for recvfrom is void.
// #undef RECVFROM_TYPE_ARG2_IS_VOID
// Define to the type of arg 3 for recvfrom.
// #undef RECVFROM_TYPE_ARG3
// Define to the type of arg 4 for recvfrom.
// #undef RECVFROM_TYPE_ARG4
// Define to the type pointed by arg 5 for recvfrom.
// #undef RECVFROM_TYPE_ARG5
// Define to 1 if the type pointed by arg 5 for recvfrom is void.
// #undef RECVFROM_TYPE_ARG5_IS_VOID
// Define to the type pointed by arg 6 for recvfrom.
// #undef RECVFROM_TYPE_ARG6
// Define to 1 if the type pointed by arg 6 for recvfrom is void.
// #undef RECVFROM_TYPE_ARG6_IS_VOID
// Define to the function return type for recvfrom.
// #undef RECVFROM_TYPE_RETV
// Define to the type of arg 1 for recv.
ret.defineCMacro("RECV_TYPE_ARG1", "int");
// Define to the type of arg 2 for recv.
ret.defineCMacro("RECV_TYPE_ARG2", "void *");
// Define to the type of arg 3 for recv.
ret.defineCMacro("RECV_TYPE_ARG3", "size_t");
// Define to the type of arg 4 for recv.
ret.defineCMacro("RECV_TYPE_ARG4", "int");
// Define to the function return type for recv.
ret.defineCMacro("RECV_TYPE_RETV", "ssize_t");
// Define to the type qualifier of arg 5 for select.
// #undef SELECT_QUAL_ARG5
// Define to the type of arg 1 for select.
// #undef SELECT_TYPE_ARG1
// Define to the type of args 2, 3 and 4 for select.
// #undef SELECT_TYPE_ARG234
// Define to the type of arg 5 for select.
// #undef SELECT_TYPE_ARG5
// Define to the function return type for select.
// #undef SELECT_TYPE_RETV
// Define to the type qualifier of arg 2 for send.
ret.defineCMacro("SEND_QUAL_ARG2", "const");
// Define to the type of arg 1 for send.
ret.defineCMacro("SEND_TYPE_ARG1", "int");
// Define to the type of arg 2 for send.
ret.defineCMacro("SEND_TYPE_ARG2", "void *");
// Define to the type of arg 3 for send.
ret.defineCMacro("SEND_TYPE_ARG3", "size_t");
// Define to the type of arg 4 for send.
ret.defineCMacro("SEND_TYPE_ARG4", "int");
// Define to the function return type for send.
ret.defineCMacro("SEND_TYPE_RETV", "ssize_t");
// Note: SIZEOF_* variables are fetched with CMake through check_type_size().
// As per CMake documentation on CheckTypeSize, C preprocessor code is
// generated by CMake into SIZEOF_*_CODE. This is what we use in the
// following statements.
//
// Reference: https://cmake.org/cmake/help/latest/module/CheckTypeSize.html
// The size of `int', as computed by sizeof.
ret.defineCMacro("SIZEOF_INT", "4");
// The size of `short', as computed by sizeof.
ret.defineCMacro("SIZEOF_SHORT", "2");
// The size of `long', as computed by sizeof.
ret.defineCMacro("SIZEOF_LONG", "8");
// The size of `off_t', as computed by sizeof.
ret.defineCMacro("SIZEOF_OFF_T", "8");
// The size of `curl_off_t', as computed by sizeof.
ret.defineCMacro("SIZEOF_CURL_OFF_T", "8");
// The size of `size_t', as computed by sizeof.
ret.defineCMacro("SIZEOF_SIZE_T", "8");
// The size of `time_t', as computed by sizeof.
ret.defineCMacro("SIZEOF_TIME_T", "8");
// Define to 1 if you have the ANSI C header files.
ret.defineCMacro("STDC_HEADERS", "1");
// Define to the type of arg 3 for strerror_r.
// #undef STRERROR_R_TYPE_ARG3
// Define to 1 if you can safely include both <sys/time.h> and <time.h>.
ret.defineCMacro("TIME_WITH_SYS_TIME", "1");
// Define if you want to enable c-ares support
// #undef USE_ARES
// Define if you want to enable POSIX threaded DNS lookup
ret.defineCMacro("USE_THREADS_POSIX", "1");
// if libSSH2 is in use
ret.defineCMacro("USE_LIBSSH2", "1");
// If you want to build curl with the built-in manual
// #undef USE_MANUAL
// if NSS is enabled
// #undef USE_NSS
// if you have the PK11_CreateManagedGenericObject function
// #undef HAVE_PK11_CREATEMANAGEDGENERICOBJECT
// if you want to use OpenLDAP code instead of legacy ldap implementation
// #undef USE_OPENLDAP
// to enable NGHTTP2
// #undef USE_NGHTTP2
// to enable NGTCP2
// #undef USE_NGTCP2
// to enable NGHTTP3
// #undef USE_NGHTTP3
// to enable quiche
// #undef USE_QUICHE
// Define to 1 if you have the quiche_conn_set_qlog_fd function.
// #undef HAVE_QUICHE_CONN_SET_QLOG_FD
// if Unix domain sockets are enabled
ret.defineCMacro("USE_UNIX_SOCKETS", null);
// Define to 1 if you are building a Windows target with large file support.
// #undef USE_WIN32_LARGE_FILES
// to enable SSPI support
// #undef USE_WINDOWS_SSPI
// to enable Windows SSL
// #undef USE_SCHANNEL
// enable multiple SSL backends
// #undef CURL_WITH_MULTI_SSL
// Define to 1 if using yaSSL in OpenSSL compatibility mode.
// #undef USE_YASSLEMUL
// Version number of package
// #undef VERSION
// Define to 1 if OS is AIX.
//#ifndef _ALL_SOURCE
//# undef _ALL_SOURCE
//#endif
// Number of bits in a file offset, on hosts where this is settable.
ret.defineCMacro("_FILE_OFFSET_BITS", "64");
// Define for large files, on AIX-style hosts.
// #undef _LARGE_FILES
// define this if you need it to compile thread-safe code
// #undef _THREAD_SAFE
// Define to empty if `const' does not conform to ANSI C.
// #undef const
// Type to use in place of in_addr_t when system does not provide it.
// #undef in_addr_t
// Define to `__inline__' or `__inline' if that's what the C compiler
// calls it, or to nothing if 'inline' is not supported under any name.
//#ifndef __cplusplus
//#undef inline
//#endif
// Define to `unsigned int' if <sys/types.h> does not define.
// #undef size_t
// the signed version of size_t
// #undef ssize_t
// Define to 1 if you have the mach_absolute_time function.
// #undef HAVE_MACH_ABSOLUTE_TIME
// to enable Windows IDN
// #undef USE_WIN32_IDN
// to make the compiler know the prototypes of Windows IDN APIs
// #undef WANT_IDN_PROTOTYPES
return Library{ .step = ret, .exported_defines = exported_defines.toOwnedSlice() };
}
const srcs = &.{
root_path ++ "curl/lib/hostcheck.c",
root_path ++ "curl/lib/curl_gethostname.c",
root_path ++ "curl/lib/strerror.c",
root_path ++ "curl/lib/strdup.c",
root_path ++ "curl/lib/asyn-ares.c",
root_path ++ "curl/lib/pop3.c",
root_path ++ "curl/lib/bufref.c",
root_path ++ "curl/lib/rename.c",
root_path ++ "curl/lib/nwlib.c",
root_path ++ "curl/lib/file.c",
root_path ++ "curl/lib/curl_gssapi.c",
root_path ++ "curl/lib/ldap.c",
root_path ++ "curl/lib/socketpair.c",
root_path ++ "curl/lib/system_win32.c",
root_path ++ "curl/lib/http_aws_sigv4.c",
root_path ++ "curl/lib/content_encoding.c",
root_path ++ "curl/lib/vquic/ngtcp2.c",
root_path ++ "curl/lib/vquic/quiche.c",
root_path ++ "curl/lib/vquic/vquic.c",
root_path ++ "curl/lib/ftp.c",
root_path ++ "curl/lib/curl_ntlm_wb.c",
root_path ++ "curl/lib/curl_ntlm_core.c",
root_path ++ "curl/lib/hostip.c",
root_path ++ "curl/lib/urlapi.c",
root_path ++ "curl/lib/curl_get_line.c",
root_path ++ "curl/lib/vtls/mesalink.c",
root_path ++ "curl/lib/vtls/mbedtls_threadlock.c",
root_path ++ "curl/lib/vtls/nss.c",
root_path ++ "curl/lib/vtls/gskit.c",
root_path ++ "curl/lib/vtls/wolfssl.c",
root_path ++ "curl/lib/vtls/keylog.c",
root_path ++ "curl/lib/vtls/rustls.c",
root_path ++ "curl/lib/vtls/vtls.c",
root_path ++ "curl/lib/vtls/gtls.c",
root_path ++ "curl/lib/vtls/schannel.c",
root_path ++ "curl/lib/vtls/schannel_verify.c",
root_path ++ "curl/lib/vtls/sectransp.c",
root_path ++ "curl/lib/vtls/openssl.c",
root_path ++ "curl/lib/vtls/mbedtls.c",
root_path ++ "curl/lib/vtls/bearssl.c",
root_path ++ "curl/lib/parsedate.c",
root_path ++ "curl/lib/sendf.c",
root_path ++ "curl/lib/altsvc.c",
root_path ++ "curl/lib/krb5.c",
root_path ++ "curl/lib/curl_rtmp.c",
root_path ++ "curl/lib/curl_ctype.c",
root_path ++ "curl/lib/inet_pton.c",
root_path ++ "curl/lib/pingpong.c",
root_path ++ "curl/lib/mime.c",
root_path ++ "curl/lib/vauth/krb5_gssapi.c",
root_path ++ "curl/lib/vauth/krb5_sspi.c",
root_path ++ "curl/lib/vauth/spnego_sspi.c",
root_path ++ "curl/lib/vauth/digest.c",
root_path ++ "curl/lib/vauth/ntlm_sspi.c",
root_path ++ "curl/lib/vauth/vauth.c",
root_path ++ "curl/lib/vauth/gsasl.c",
root_path ++ "curl/lib/vauth/cram.c",
root_path ++ "curl/lib/vauth/oauth2.c",
root_path ++ "curl/lib/vauth/digest_sspi.c",
root_path ++ "curl/lib/vauth/cleartext.c",
root_path ++ "curl/lib/vauth/spnego_gssapi.c",
root_path ++ "curl/lib/vauth/ntlm.c",
root_path ++ "curl/lib/version_win32.c",
root_path ++ "curl/lib/multi.c",
root_path ++ "curl/lib/http_ntlm.c",
root_path ++ "curl/lib/curl_sspi.c",
root_path ++ "curl/lib/md5.c",
root_path ++ "curl/lib/dict.c",
root_path ++ "curl/lib/http.c",
root_path ++ "curl/lib/curl_des.c",
root_path ++ "curl/lib/memdebug.c",
root_path ++ "curl/lib/non-ascii.c",
root_path ++ "curl/lib/transfer.c",
root_path ++ "curl/lib/inet_ntop.c",
root_path ++ "curl/lib/slist.c",
root_path ++ "curl/lib/http_negotiate.c",
root_path ++ "curl/lib/http_digest.c",
root_path ++ "curl/lib/vssh/wolfssh.c",
root_path ++ "curl/lib/vssh/libssh.c",
root_path ++ "curl/lib/vssh/libssh2.c",
root_path ++ "curl/lib/hsts.c",
root_path ++ "curl/lib/escape.c",
root_path ++ "curl/lib/hostsyn.c",
root_path ++ "curl/lib/speedcheck.c",
root_path ++ "curl/lib/asyn-thread.c",
root_path ++ "curl/lib/curl_addrinfo.c",
root_path ++ "curl/lib/nwos.c",
root_path ++ "curl/lib/tftp.c",
root_path ++ "curl/lib/version.c",
root_path ++ "curl/lib/rand.c",
root_path ++ "curl/lib/psl.c",
root_path ++ "curl/lib/imap.c",
root_path ++ "curl/lib/mqtt.c",
root_path ++ "curl/lib/share.c",
root_path ++ "curl/lib/doh.c",
root_path ++ "curl/lib/curl_range.c",
root_path ++ "curl/lib/openldap.c",
root_path ++ "curl/lib/getinfo.c",
root_path ++ "curl/lib/select.c",
root_path ++ "curl/lib/base64.c",
root_path ++ "curl/lib/curl_sasl.c",
root_path ++ "curl/lib/curl_endian.c",
root_path ++ "curl/lib/connect.c",
root_path ++ "curl/lib/fileinfo.c",
root_path ++ "curl/lib/telnet.c",
root_path ++ "curl/lib/x509asn1.c",
root_path ++ "curl/lib/conncache.c",
root_path ++ "curl/lib/strcase.c",
root_path ++ "curl/lib/if2ip.c",
root_path ++ "curl/lib/gopher.c",
root_path ++ "curl/lib/ftplistparser.c",
root_path ++ "curl/lib/setopt.c",
root_path ++ "curl/lib/idn_win32.c",
root_path ++ "curl/lib/strtoofft.c",
root_path ++ "curl/lib/hmac.c",
root_path ++ "curl/lib/getenv.c",
root_path ++ "curl/lib/smb.c",
root_path ++ "curl/lib/dotdot.c",
root_path ++ "curl/lib/curl_threads.c",
root_path ++ "curl/lib/md4.c",
root_path ++ "curl/lib/easygetopt.c",
root_path ++ "curl/lib/curl_fnmatch.c",
root_path ++ "curl/lib/sha256.c",
root_path ++ "curl/lib/cookie.c",
root_path ++ "curl/lib/amigaos.c",
root_path ++ "curl/lib/progress.c",
root_path ++ "curl/lib/nonblock.c",
root_path ++ "curl/lib/llist.c",
root_path ++ "curl/lib/hostip6.c",
root_path ++ "curl/lib/dynbuf.c",
root_path ++ "curl/lib/warnless.c",
root_path ++ "curl/lib/hostasyn.c",
root_path ++ "curl/lib/http_chunks.c",
root_path ++ "curl/lib/wildcard.c",
root_path ++ "curl/lib/strtok.c",
root_path ++ "curl/lib/curl_memrchr.c",
root_path ++ "curl/lib/rtsp.c",
root_path ++ "curl/lib/http2.c",
root_path ++ "curl/lib/socks.c",
root_path ++ "curl/lib/curl_path.c",
root_path ++ "curl/lib/curl_multibyte.c",
root_path ++ "curl/lib/http_proxy.c",
root_path ++ "curl/lib/formdata.c",
root_path ++ "curl/lib/netrc.c",
root_path ++ "curl/lib/socks_sspi.c",
root_path ++ "curl/lib/mprintf.c",
root_path ++ "curl/lib/easyoptions.c",
root_path ++ "curl/lib/easy.c",
root_path ++ "curl/lib/c-hyper.c",
root_path ++ "curl/lib/hostip4.c",
root_path ++ "curl/lib/timeval.c",
root_path ++ "curl/lib/smtp.c",
root_path ++ "curl/lib/splay.c",
root_path ++ "curl/lib/socks_gssapi.c",
root_path ++ "curl/lib/url.c",
root_path ++ "curl/lib/hash.c",
};
|
.gyro/zig-libcurl-mattnite-github.com-f1f316dc/pkg/libcurl.zig
|
const DEBUGMODE = @import("builtin").mode == @import("builtin").Mode.Debug;
const std = @import("std");
const sg = @import("sokol").gfx;
const sapp = @import("sokol").app;
const stime = @import("sokol").time;
const sgapp = @import("sokol").app_gfx_glue;
const sdtx = @import("sokol").debugtext;
const sa = @import("sokol").audio;
////////////////////////////////////////////////////////////////////////////////////////////////
var pass_action: sg.PassAction = .{};
var pip: sg.Pipeline = .{};
var bind: sg.Bindings = .{};
export fn audio(buffer: [*c]f32, frames: i32, channels: i32) void {}
export fn init() void {
sa.setup(.{ .stream_cb = audio });
sg.setup(.{ .context = sgapp.context() });
pass_action.colors[0] = .{
.action = .CLEAR,
.value = .{ .r = 0.08, .g = 0.08, .b = 0.11, .a = 1.0 }, // HELLO EIGENGRAU!
};
stime.setup();
var sdtx_desc: sdtx.Desc = .{};
sdtx_desc.fonts[0] = @import("fontdata.zig").fontdesc;
sdtx.setup(sdtx_desc);
sdtx.font(0);
}
////////////////////////////////////////////////////////////////////////////////////////////////
var screenWidth: f32 = 0;
var screenHeight: f32 = 0;
var delta: f32 = 0;
var last_time: u64 = 0;
var row: i16 = 0;
var column: i16 = 0;
var abc = "abcdefghijklmnopqrstuvwxyz";
var name = [6]u8{ 95, 95, 95, 95, 95, 95 }; // Create name string filled with "_"s
var cur: usize = 0;
export fn frame() void {
var rowsize: i16 = if (column == 2) 7 else 8;
if (keys.jst_left) {
row -= 1;
if (row < 0) {
row = rowsize;
}
} else if (keys.jst_right) {
row += 1;
if (row > rowsize) {
row = 0;
}
}
if (keys.jst_up) {
if (column == 0 and row == 8) {
row = 7;
}
column -= 1;
if (column < 0) {
column = 2;
}
} else if (keys.jst_down) {
if (column == 1 and row == 8) {
row = 7;
}
column += 1;
if (column > 2) {
column = 0;
}
}
screenWidth = sapp.widthf();
screenHeight = sapp.heightf();
sdtx.canvas(screenWidth * 0.5, screenHeight * 0.5);
sdtx.origin(1, 1);
sdtx.color1i(0xFFFFFFFF);
sdtx.print("tell me your name!\n\n ", .{});
for (name) |char| {
if (char == 95) { // "_"
sdtx.color1i(0x55FFFFFF);
} else {
sdtx.color1i(0xFFFFFFFF);
}
sdtx.putc(char);
sdtx.putc(32); // SPACE
}
sdtx.print("\n\n\n", .{});
var cnt: u16 = 0;
var lin: u8 = 0;
for (abc) |char, indx| {
if (lin == column and row == cnt) {
sdtx.color1i(0xFFFFAE00); // HIGHLIGHT THINGS UP
sdtx.putc(char - 32); // .... YEA!
if (keys.jst_attack and cur != 6) {
name[cur] = char;
cur += 1;
} else if (keys.jst_cancel and cur != 0) {
cur -= 1;
name[cur] = 95; // "_"
}
} else {
sdtx.color1i(0x77FFFFFF);
sdtx.putc(char);
}
sdtx.putc(32); // SPACE
cnt += 1;
if (cnt == 9) {
sdtx.putc(10); // LINE BREAK
cnt = 0;
lin += 1;
}
}
sdtx.origin(24, 0);
sdtx.pos(24, 0);
sdtx.putc(10);
sdtx.color1i(0xFFFFAE00);
sdtx.print("X", .{});
sdtx.color1i(0xFFFFFFFF);
sdtx.print(": delete character\n\n", .{});
sdtx.color1i(0xFFFFAE00);
sdtx.print("C", .{});
sdtx.color1i(0xFFFFFFFF);
sdtx.print(": add character\n\n", .{});
sdtx.color1i(0xFFFFAE00);
sdtx.print("INTRO", .{});
sdtx.color1i(0xFFFFFFFF);
sdtx.print(": done\n\n", .{});
sdtx.color1i(0xFFf5427b);
sdtx.print(
\\ WARNING:
\\
\\ you WONT be able to change
\\ your name, be careful.
\\
, .{});
sg.beginDefaultPass(pass_action, sapp.width(), sapp.height());
sdtx.draw();
sg.endPass();
sg.commit();
delta = @floatCast(f32, stime.sec(stime.laptime(&last_time)));
keys.jst_up = false;
keys.jst_down = false;
keys.jst_left = false;
keys.jst_right = false;
keys.jst_enter = false;
keys.jst_cancel = false;
keys.jst_attack = false;
}
////////////////////////////////////////////////////////////////////////////////////////////////
const _keystruct = packed struct {
up: bool = false,
down: bool = false,
jst_up: bool = false,
jst_down: bool = false,
left: bool = false,
right: bool = false,
jst_left: bool = false,
jst_right: bool = false,
enter: bool = false,
cancel: bool = false,
attack: bool = false,
any: bool = false,
jst_enter: bool = false,
jst_cancel: bool = false,
jst_attack: bool = false,
home: bool = false,
};
var keys = _keystruct{};
const _mousestruct = struct {
x: f32 = 0,
y: f32 = 0,
dx: f32 = 0,
dy: f32 = 0,
left: bool = false,
middle: bool = false,
right: bool = false,
any: bool = false,
};
var mouse = _mousestruct{};
export fn input(ev: ?*const sapp.Event) void {
const event = ev.?;
if ((event.type == .KEY_DOWN) or (event.type == .KEY_UP)) {
const key_pressed = event.type == .KEY_DOWN;
keys.any = key_pressed;
switch (event.key_code) {
.UP => {
keys.jst_up = key_pressed and !keys.up;
keys.up = key_pressed;
},
.DOWN => {
keys.jst_down = key_pressed and !keys.down;
keys.down = key_pressed;
},
.LEFT => {
keys.jst_left = key_pressed and !keys.left;
keys.left = key_pressed;
},
.RIGHT => {
keys.jst_right = key_pressed and !keys.right;
keys.right = key_pressed;
},
.ENTER => {
keys.jst_enter = key_pressed and !keys.enter;
keys.enter = key_pressed;
},
.X => {
keys.jst_cancel = key_pressed and !keys.cancel;
keys.cancel = key_pressed;
},
.C => {
keys.jst_attack = key_pressed and !keys.attack;
keys.attack = key_pressed;
},
.BACKSPACE => keys.home = key_pressed,
else => {},
}
} else if ((event.type == .MOUSE_DOWN) or (event.type == .MOUSE_UP)) {
const mouse_pressed = event.type == .MOUSE_DOWN;
mouse.any = mouse_pressed;
switch (event.mouse_button) {
.LEFT => mouse.left = mouse_pressed,
.MIDDLE => mouse.middle = mouse_pressed,
.RIGHT => mouse.right = mouse_pressed,
else => {},
}
} else if (event.type == .MOUSE_MOVE) {
mouse.x = event.mouse_x;
mouse.y = event.mouse_y;
mouse.dx = event.mouse_dx;
mouse.dy = event.mouse_dy;
}
}
////////////////////////////////////////////////////////////////////////////////////////////////
pub fn main() void {
sapp.run(.{
.init_cb = init,
.frame_cb = frame,
.cleanup_cb = cleanup,
.event_cb = input,
.width = 1024,
.height = 600,
.window_title = "m e t a h o m e",
});
}
////////////////////////////////////////////////////////////////////////////////////////////////
export fn cleanup() void {
sg.shutdown();
sa.shutdown();
}
|
src/test_kbrd.zig
|
const builtin = @import("builtin");
const std = @import("std");
// popcount - population count
// counts the number of 1 bits
// SWAR-Popcount: count bits of duos, aggregate to nibbles, and bytes inside
// x-bit register in parallel to sum up all bytes
// SWAR-Masks and factors can be defined as 2-adic fractions
// TAOCP: Combinational Algorithms, Bitwise Tricks And Techniques,
// subsubsection "Working with the rightmost bits" and "Sideways addition".
fn popcountXi2_generic(comptime T: type) fn (a: T) callconv(.C) i32 {
return struct {
fn f(a: T) callconv(.C) i32 {
@setRuntimeSafety(builtin.is_test);
var x = switch (@bitSizeOf(T)) {
32 => @bitCast(u32, a),
64 => @bitCast(u64, a),
128 => @bitCast(u128, a),
else => unreachable,
};
const k1 = switch (@bitSizeOf(T)) { // -1/3
32 => @as(u32, 0x55555555),
64 => @as(u64, 0x55555555_55555555),
128 => @as(u128, 0x55555555_55555555_55555555_55555555),
else => unreachable,
};
const k2 = switch (@bitSizeOf(T)) { // -1/5
32 => @as(u32, 0x33333333),
64 => @as(u64, 0x33333333_33333333),
128 => @as(u128, 0x33333333_33333333_33333333_33333333),
else => unreachable,
};
const k4 = switch (@bitSizeOf(T)) { // -1/17
32 => @as(u32, 0x0f0f0f0f),
64 => @as(u64, 0x0f0f0f0f_0f0f0f0f),
128 => @as(u128, 0x0f0f0f0f_0f0f0f0f_0f0f0f0f_0f0f0f0f),
else => unreachable,
};
const kf = switch (@bitSizeOf(T)) { // -1/255
32 => @as(u32, 0x01010101),
64 => @as(u64, 0x01010101_01010101),
128 => @as(u128, 0x01010101_01010101_01010101_01010101),
else => unreachable,
};
x = x - ((x >> 1) & k1); // aggregate duos
x = (x & k2) + ((x >> 2) & k2); // aggregate nibbles
x = (x + (x >> 4)) & k4; // aggregate bytes
x = (x *% kf) >> @bitSizeOf(T) - 8; // 8 most significant bits of x + (x<<8) + (x<<16) + ..
return @intCast(i32, x);
}
}.f;
}
pub const __popcountsi2 = popcountXi2_generic(i32);
pub const __popcountdi2 = popcountXi2_generic(i64);
pub const __popcountti2 = popcountXi2_generic(i128);
test {
_ = @import("popcountsi2_test.zig");
_ = @import("popcountdi2_test.zig");
_ = @import("popcountti2_test.zig");
}
|
lib/std/special/compiler_rt/popcount.zig
|
const std = @import("std");
const utils = @import("utils.zig");
const gl = @import("gl.zig");
const vec2 = @import("math/vec2.zig");
const vec3 = @import("math/vec3.zig");
const Vec2f = vec2.Generic(f32);
const Vec3f = vec3.Generic(f32);
/// Error set
pub const Error = error{ FailedToGenerateBuffers, ObjectOverflow, VertexOverflow, IndexOverflow, UnknownSubmitFn };
/// Colour generic struct
pub fn ColourGeneric(comptime typ: type) type {
switch (typ) {
f16, f32, f64, f128 => {
return struct {
r: typ = 0,
g: typ = 0,
b: typ = 0,
a: typ = 0,
pub fn rgba(r: u32, g: u32, b: u32, a: u32) @This() {
return .{
.r = @intToFloat(typ, r) / 255.0,
.g = @intToFloat(typ, g) / 255.0,
.b = @intToFloat(typ, b) / 255.0,
.a = @intToFloat(typ, a) / 255.0,
};
}
};
},
u8, u16, u32, u64, u128 => {
return struct {
r: typ = 0,
g: typ = 0,
b: typ = 0,
a: typ = 0,
pub fn rgba(r: u32, g: u32, b: u32, a: u32) @This() {
return .{
.r = @intCast(typ, r),
.g = @intCast(typ, g),
.b = @intCast(typ, b),
.a = @intCast(typ, a),
};
}
};
},
else => @compileError("Non-implemented type"),
}
}
const Colour = ColourGeneric(f32);
/// Vertex generic struct
pub fn VertexGeneric(istextcoord: bool, comptime positiontype: type) type {
if (positiontype == Vec2f or positiontype == Vec3f) {
if (!istextcoord) {
return struct {
const Self = @This();
position: positiontype = positiontype{},
colour: Colour = comptime Colour.rgba(255, 255, 255, 255)
};
}
return struct {
const Self = @This();
position: positiontype = positiontype{},
texcoord: Vec2f = Vec2f{},
colour: Colour = comptime Colour.rgba(255, 255, 255, 255)
};
}
@compileError("Unknown position type");
}
/// Batch generic structure
pub fn BatchGeneric(max_object: u32, max_index: u32, max_vertex: u32, comptime vertex_type: type) type {
return struct {
const Self = @This();
pub const max_object_count: u32 = max_object;
pub const max_index_count: u32 = max_index;
pub const max_vertex_count: u32 = max_vertex;
pub const Vertex: type = vertex_type;
vertex_array: u32 = 0,
buffers: [2]u32 = [2]u32{ 0, 0 },
vertex_list: [max_object_count][max_vertex_count]vertex_type = undefined,
index_list: [max_object_count][max_index_count]u32 = undefined,
submitfn: ?fn (self: *Self, vertex: [Self.max_vertex_count]vertex_type) Error!void = null,
submission_counter: u32 = 0,
/// Creates the batch
pub fn create(self: *Self, shaderprogram: u32, shadersetattribs: fn () void) Error!void {
self.submission_counter = 0;
gl.vertexArraysGen(1, @ptrCast([*]u32, &self.vertex_array));
gl.buffersGen(2, &self.buffers);
if (self.vertex_array == 0 or self.buffers[0] == 0 or self.buffers[1] == 0) {
gl.vertexArraysDelete(1, @ptrCast([*]const u32, &self.vertex_array));
gl.buffersDelete(2, @ptrCast([*]const u32, &self.buffers));
return Error.FailedToGenerateBuffers;
}
gl.vertexArrayBind(self.vertex_array);
defer gl.vertexArrayBind(0);
gl.bufferBind(gl.BufferType.array, self.buffers[0]);
gl.bufferBind(gl.BufferType.elementarray, self.buffers[1]);
defer gl.bufferBind(gl.BufferType.array, 0);
defer gl.bufferBind(gl.BufferType.elementarray, 0);
gl.bufferData(gl.BufferType.array, @sizeOf(vertex_type) * max_vertex_count * max_object_count, @ptrCast(?*const c_void, &self.vertex_list), gl.DrawType.dynamic);
gl.bufferData(gl.BufferType.elementarray, @sizeOf(u32) * max_index_count * max_object_count, @ptrCast(?*const c_void, &self.index_list), gl.DrawType.dynamic);
gl.shaderProgramUse(shaderprogram);
defer gl.shaderProgramUse(0);
shadersetattribs();
}
/// Destroys the batch
pub fn destroy(self: Self) void {
gl.vertexArraysDelete(1, @ptrCast([*]const u32, &self.vertex_array));
gl.buffersDelete(2, @ptrCast([*]const u32, &self.buffers));
}
/// Set the vertex data from set and given position
pub fn submitVertex(self: *Self, firstposition: u32, lastposition: u32, data: Vertex) Error!void {
if (firstposition >= Self.max_object_count) {
return Error.ObjectOverflow;
} else if (lastposition >= Self.max_vertex_count) {
return Error.VertexOverflow;
}
self.vertex_list[firstposition][lastposition] = data;
}
/// Set the index data from set and given position
pub fn submitIndex(self: *Self, firstposition: u32, lastposition: u32, data: u32) Error!void {
if (firstposition >= Self.max_object_count) {
return Error.ObjectOverflow;
} else if (lastposition >= Self.max_index_count) {
return Error.IndexOverflow;
}
self.index_list[firstposition][lastposition] = data;
}
/// Submit a drawable object
pub fn submitDrawable(self: *Self, obj: [Self.max_vertex_count]vertex_type) Error!void {
if (self.submission_counter >= Self.max_object_count) {
return Error.ObjectOverflow;
} else if (self.submitfn) |fun| {
try fun(self, obj);
return;
}
return Error.UnknownSubmitFn;
}
/// Cleans the lists
pub fn cleanAll(self: *Self) void {
var i: u32 = 0;
while (i < Self.max_object_count) : (i += 1) {
var j: u32 = 0;
while (j < Self.max_index_count) : (j += 1) {
self.index_list[i][j] = 0;
}
j = 0;
while (j < Self.max_vertex_count) : (j += 1) {
self.vertex_list[i][j] = .{};
}
}
}
/// Draw the submitted objects
pub fn draw(self: Self, drawmode: gl.DrawMode) Error!void {
if (self.submission_counter > Self.max_object_count) return Error.ObjectOverflow;
gl.vertexArrayBind(self.vertex_array);
defer gl.vertexArrayBind(0);
gl.bufferBind(gl.BufferType.array, self.buffers[0]);
gl.bufferBind(gl.BufferType.elementarray, self.buffers[1]);
defer gl.bufferBind(gl.BufferType.array, 0);
defer gl.bufferBind(gl.BufferType.elementarray, 0);
gl.bufferSubData(gl.BufferType.array, 0, @sizeOf(Vertex) * max_vertex_count * max_object_count, @ptrCast(?*const c_void, &self.vertex_list));
gl.bufferSubData(gl.BufferType.elementarray, 0, @sizeOf(u32) * max_index_count * max_object_count, @ptrCast(?*const c_void, &self.index_list));
gl.drawElements(drawmode, @intCast(i32, Self.max_object_count * Self.max_index_count), u32, null);
}
};
}
|
src/kiragine/kira/renderer.zig
|
const std = @import("std");
const fomu = @import("./fomu.zig");
pub fn panic(message: []const u8, stack_trace: ?*std.builtin.StackTrace) noreturn {
@setCold(true);
fomu.panic(message, stack_trace);
}
fn rgb_init() void {
// Turn on the RGB block and current enable, as well as enabling led control
fomu.RGB.CTRL.* = .{
.EXE = true,
.CURREN = true,
.RGBLEDEN = true,
.RRAW = false,
.GRAW = false,
.BRAW = false,
};
// Enable the LED driver, and set 250 Hz mode.
// Also set quick stop, which we'll use to switch patterns quickly.
fomu.RGB.setControlRegister(.{
.enable = true,
.fr = .@"250",
.quick_stop = true,
.outskew = false,
.output_polarity = .active_high,
.pwm_mode = .linear,
.BRMSBEXT = 0,
});
// Set clock register to 12 MHz / 64 kHz - 1
fomu.RGB.setRegister(.BR, (fomu.SYSTEM_CLOCK_FREQUENCY / 64000) - 1);
// Blink on/off time is in 32 ms increments
fomu.RGB.setRegister(.ONR, 1); // Amount of time to stay "on"
fomu.RGB.setRegister(.OFR, 0); // Amount of time to stay "off"
fomu.RGB.setBreatheRegister(.On, .{
.enable = true,
.pwm_range_extend = false,
.mode = .fixed,
.rate = 1,
});
fomu.RGB.setBreatheRegister(.Off, .{
.enable = true,
.pwm_range_extend = false,
.mode = .fixed,
.rate = 1,
});
}
const Colour = struct {
r: u8,
g: u8,
b: u8,
};
/// Input a value 0 to 255 to get a colour value.
/// The colours are a transition r - g - b - back to r.
fn colourWheel(wheelPos: u8) Colour {
var c: Colour = undefined;
var wp = 255 - wheelPos;
switch (wp) {
0...84 => {
c = .{
.r = 255 - wp * 3,
.g = 0,
.b = wp * 3,
};
},
85...169 => {
wp -= 85;
c = .{
.r = 0,
.g = wp * 3,
.b = 255 - wp * 3,
};
},
170...255 => {
wp -= 170;
c = .{
.r = wp * 3,
.g = 255 - wp * 3,
.b = 0,
};
},
}
return c;
}
fn msleep(ms: usize) void {
fomu.TIMER0.stop();
fomu.TIMER0.reload(0);
fomu.TIMER0.load(fomu.SYSTEM_CLOCK_FREQUENCY / 1000 * ms);
fomu.TIMER0.start();
while (fomu.TIMER0.value() != 0) {}
}
pub fn main() noreturn {
rgb_init();
var i: u8 = 0;
while (true) : (i +%= 1) {
const colour = colourWheel(i);
fomu.RGB.setColour(colour.r, colour.g, colour.b);
msleep(80);
}
unreachable;
}
|
riscv-zig-blink/src/main.zig
|
const std = @import("std");
const print = std.debug.print;
const util = @import("util.zig");
const gpa = util.gpa;
const data = @embedFile("../data/day14.txt");
const Value = struct {
result : u8,
lastVisitCount : u64,
nextVisitCount : u64,
};
pub fn main() !void {
var timer = try std.time.Timer.start();
var map = std.StringHashMap(Value).init(gpa);
defer { map.deinit(); }
var lines = std.mem.tokenize(data, "\r\n");
var template = lines.next().?;
while (lines.next()) |line| {
var tokens = std.mem.tokenize(line, " -> ");
const pattern = tokens.next().?;
std.debug.assert(pattern.len == 2);
const result = tokens.next().?;
std.debug.assert(result.len == 1);
const value = Value {
.result = result[0],
.lastVisitCount = 0,
.nextVisitCount = 0,
};
try map.put(pattern, value);
}
// Now we insert all the initial visit counts from our template into the map.
{
var index : u32 = 0;
while (index < (template.len - 1)) : (index += 1) {
var slice = template[index..(index + 2)];
map.getPtr(slice).?.lastVisitCount += 1;
}
}
var step : u32 = 0;
const part1Steps : u32 = 10;
const steps : u32 = 40;
while (step < steps) : (step += 1) {
if (step == part1Steps) {
print("🎁 Quantity: {}\n", .{calculateQuantity(map)});
print("Day 14 - part 01 took {:15}ns\n", .{timer.lap()});
timer.reset();
}
// First pass we work out the next visit counts for the future step.
{
var iterator = map.iterator();
while (iterator.next()) |pair| {
const key = pair.key_ptr.*;
const value = pair.value_ptr;
// If we didn't visit this value on the last step, skip it!
if (value.lastVisitCount == 0) {
continue;
}
// Each pair inserts two new pairs with the result splicing the original
// pairs letters.
const newKey0 = [2]u8 {key[0], value.result};
const newKey1 = [2]u8 {value.result, key[1]};
// We visit each of these new keys next time as many times as we would
// visit the last steps visit count.
map.getPtr(&newKey0).?.nextVisitCount += value.lastVisitCount;
map.getPtr(&newKey1).?.nextVisitCount += value.lastVisitCount;
}
}
// Second pass we move the next visit counts to the last visit counts for
// the next loop iteration.
{
var iterator = map.iterator();
while (iterator.next()) |pair| {
const key = pair.key_ptr.*;
const value = pair.value_ptr;
value.lastVisitCount = value.nextVisitCount;
value.nextVisitCount = 0;
}
}
}
print("🎁 Quantity: {}\n", .{calculateQuantity(map)});
print("Day 14 - part 02 took {:15}ns\n", .{timer.lap()});
print("❄️❄️❄️❄️❄️❄️❄️❄️❄️❄️❄️❄️❄️❄️❄️❄️❄️❄️❄️❄️❄️❄️❄️❄️❄️❄️❄️❄️❄️❄️❄️❄️❄️❄️❄️❄️❄️❄️❄️\n", .{});
}
fn dump(map : std.StringHashMap(Value)) void {
var iterator = map.iterator();
print("Map:\n", .{});
while (iterator.next()) |pair| {
const key = pair.key_ptr.*;
const value = pair.value_ptr;
print(" Key '{s}' -> Result '{c}', Count '{}'\n", .{key, value.result, value.lastVisitCount});
}
}
fn calculateQuantity(map : std.StringHashMap(Value)) u64 {
// Each letter of the alphabet gets a hit list.
var hits = [_]u64{0} ** 27;
var iterator = map.iterator();
while (iterator.next()) |pair| {
const key = pair.key_ptr.*;
const value = pair.value_ptr;
hits[key[0] - 'A'] += value.lastVisitCount;
hits[key[1] - 'A'] += value.lastVisitCount;
}
var minNonZeroHit : u64 = std.math.maxInt(u64);
var maxHit : u64 = 0;
for (hits) |hit| {
if (hit == 0) {
continue;
}
if (minNonZeroHit > hit) {
minNonZeroHit = hit;
}
if (maxHit < hit) {
maxHit = hit;
}
}
// Because of how we record things into the map, we need to adjust the
// calculated resulted by diving it by 2 (because we record each element of
// each pair twice effectively).
return (maxHit - minNonZeroHit + 1) / 2;
}
|
src/day14.zig
|
const std = @import("std");
/// Parses arguments for the given specification and our current process.
/// - `Spec` is the configuration of the arguments.
/// - `allocator` is the allocator that is used to allocate all required memory
/// - `error_handling` defines how parser errors will be handled.
pub fn parseForCurrentProcess(comptime Spec: type, allocator: std.mem.Allocator, error_handling: ErrorHandling) !ParseArgsResult(Spec, null) {
// Use argsWithAllocator for portability.
// All data allocated by the ArgIterator is freed at the end of the function.
// Data returned to the user is always duplicated using the allocator.
var args = try std.process.argsWithAllocator(allocator);
defer args.deinit();
const executable_name = args.next() orelse {
try error_handling.process(error.NoExecutableName, Error{
.option = "",
.kind = .missing_executable_name,
});
// we do not assume any more arguments appear here anyways...
return error.NoExecutableName;
};
var result = try parseInternal(Spec, null, &args, allocator, error_handling);
result.executable_name = try allocator.dupeZ(u8, executable_name);
return result;
}
/// Parses arguments for the given specification and our current process.
/// - `Spec` is the configuration of the arguments.
/// - `allocator` is the allocator that is used to allocate all required memory
/// - `error_handling` defines how parser errors will be handled.
pub fn parseWithVerbForCurrentProcess(comptime Spec: type, comptime Verb: type, allocator: std.mem.Allocator, error_handling: ErrorHandling) !ParseArgsResult(Spec, Verb) {
// Use argsWithAllocator for portability.
// All data allocated by the ArgIterator is freed at the end of the function.
// Data returned to the user is always duplicated using the allocator.
var args = try std.process.argsWithAllocator(allocator);
defer args.deinit();
const executable_name = args.next() orelse {
try error_handling.process(error.NoExecutableName, Error{
.option = "",
.kind = .missing_executable_name,
});
// we do not assume any more arguments appear here anyways...
return error.NoExecutableName;
};
var result = try parseInternal(Spec, Verb, &args, allocator, error_handling);
result.executable_name = try allocator.dupeZ(u8, executable_name);
return result;
}
/// Parses arguments for the given specification.
/// - `Generic` is the configuration of the arguments.
/// - `args_iterator` is a pointer to an std.process.ArgIterator that will yield the command line arguments.
/// - `allocator` is the allocator that is used to allocate all required memory
/// - `error_handling` defines how parser errors will be handled.
///
/// Note that `.executable_name` in the result will not be set!
pub fn parse(comptime Generic: type, args_iterator: anytype, allocator: std.mem.Allocator, error_handling: ErrorHandling) !ParseArgsResult(Generic, null) {
return parseInternal(Generic, null, args_iterator, allocator, error_handling);
}
/// Parses arguments for the given specification using a `Verb` method.
/// This means that the first positional argument is interpreted as a verb, that can
/// be considered a sub-command that provides more specific options.
/// - `Generic` is the configuration of the arguments.
/// - `Verb` is the configuration of the verbs.
/// - `args_iterator` is a pointer to an std.process.ArgIterator that will yield the command line arguments.
/// - `allocator` is the allocator that is used to allocate all required memory
/// - `error_handling` defines how parser errors will be handled.
///
/// Note that `.executable_name` in the result will not be set!
pub fn parseWithVerb(comptime Generic: type, comptime Verb: type, args_iterator: anytype, allocator: std.mem.Allocator, error_handling: ErrorHandling) !ParseArgsResult(Generic, Verb) {
return parseInternal(Generic, Verb, args_iterator, allocator, error_handling);
}
/// Same as parse, but with anytype argument for testability
fn parseInternal(comptime Generic: type, comptime MaybeVerb: ?type, args_iterator: anytype, allocator: std.mem.Allocator, error_handling: ErrorHandling) !ParseArgsResult(Generic, MaybeVerb) {
var result = ParseArgsResult(Generic, MaybeVerb){
.arena = std.heap.ArenaAllocator.init(allocator),
.options = Generic{},
.verb = if (MaybeVerb != null) null else {}, // no verb by default
.positionals = undefined,
.executable_name = null,
};
errdefer result.arena.deinit();
var result_arena_allocator = result.arena.allocator();
var arglist = std.ArrayList([:0]const u8).init(allocator);
errdefer arglist.deinit();
var last_error: ?anyerror = null;
while (args_iterator.next()) |item| {
if (std.mem.startsWith(u8, item, "--")) {
if (std.mem.eql(u8, item, "--")) {
// double hyphen is considered 'everything from here now is positional'
break;
}
const Pair = struct {
name: []const u8,
value: ?[]const u8,
};
const pair = if (std.mem.indexOf(u8, item, "=")) |index|
Pair{
.name = item[2..index],
.value = item[index + 1 ..],
}
else
Pair{
.name = item[2..],
.value = null,
};
var found = false;
inline for (std.meta.fields(Generic)) |fld| {
if (std.mem.eql(u8, pair.name, fld.name)) {
try parseOption(Generic, result_arena_allocator, &result.options, args_iterator, error_handling, &last_error, fld.name, pair.value);
found = true;
}
}
if (MaybeVerb) |Verb| {
if (result.verb) |*verb| {
if (!found) {
const Tag = std.meta.Tag(Verb);
inline for (std.meta.fields(Verb)) |verb_info| {
if (verb.* == @field(Tag, verb_info.name)) {
inline for (std.meta.fields(verb_info.field_type)) |fld| {
if (std.mem.eql(u8, pair.name, fld.name)) {
try parseOption(
verb_info.field_type,
result_arena_allocator,
&@field(verb.*, verb_info.name),
args_iterator,
error_handling,
&last_error,
fld.name,
pair.value,
);
found = true;
}
}
}
}
}
}
}
if (!found) {
last_error = error.EncounteredUnknownArgument;
try error_handling.process(error.EncounteredUnknownArgument, Error{
.option = pair.name,
.kind = .unknown,
});
}
} else if (std.mem.startsWith(u8, item, "-")) {
if (std.mem.eql(u8, item, "-")) {
// single hyphen is considered a positional argument
try arglist.append(try result_arena_allocator.dupeZ(u8, item));
} else {
var any_shorthands = false;
for (item[1..]) |char, index| {
var option_name = [2]u8{ '-', char };
var found = false;
if (@hasDecl(Generic, "shorthands")) {
any_shorthands = true;
inline for (std.meta.fields(@TypeOf(Generic.shorthands))) |fld| {
if (fld.name.len != 1)
@compileError("All shorthand fields must be exactly one character long!");
if (fld.name[0] == char) {
const real_name = @field(Generic.shorthands, fld.name);
const real_fld_type = @TypeOf(@field(result.options, real_name));
// -2 because we stripped of the "-" at the beginning
if (requiresArg(real_fld_type) and index != item.len - 2) {
last_error = error.EncounteredUnexpectedArgument;
try error_handling.process(error.EncounteredUnexpectedArgument, Error{
.option = &option_name,
.kind = .invalid_placement,
});
} else {
try parseOption(Generic, result_arena_allocator, &result.options, args_iterator, error_handling, &last_error, real_name, null);
}
found = true;
}
}
}
if (MaybeVerb) |Verb| {
if (result.verb) |*verb| {
if (!found) {
const Tag = std.meta.Tag(Verb);
inline for (std.meta.fields(Verb)) |verb_info| {
const VerbType = verb_info.field_type;
if (verb.* == @field(Tag, verb_info.name)) {
const target_value = &@field(verb.*, verb_info.name);
if (@hasDecl(VerbType, "shorthands")) {
any_shorthands = true;
inline for (std.meta.fields(@TypeOf(VerbType.shorthands))) |fld| {
if (fld.name.len != 1)
@compileError("All shorthand fields must be exactly one character long!");
if (fld.name[0] == char) {
const real_name = @field(VerbType.shorthands, fld.name);
const real_fld_type = @TypeOf(@field(target_value.*, real_name));
// -2 because we stripped of the "-" at the beginning
if (requiresArg(real_fld_type) and index != item.len - 2) {
last_error = error.EncounteredUnexpectedArgument;
try error_handling.process(error.EncounteredUnexpectedArgument, Error{
.option = &option_name,
.kind = .invalid_placement,
});
} else {
try parseOption(VerbType, result_arena_allocator, target_value, args_iterator, error_handling, &last_error, real_name, null);
}
last_error = null; // we need to reset that error here, as it was set previously
found = true;
}
}
}
}
}
}
}
}
if (!found) {
last_error = error.EncounteredUnknownArgument;
try error_handling.process(error.EncounteredUnknownArgument, Error{
.option = &option_name,
.kind = .unknown,
});
}
}
if (!any_shorthands) {
try error_handling.process(error.EncounteredUnsupportedArgument, Error{
.option = item,
.kind = .unsupported,
});
}
}
} else {
if (MaybeVerb) |Verb| {
if (result.verb == null) {
inline for (std.meta.fields(Verb)) |fld| {
if (std.mem.eql(u8, item, fld.name)) {
// found active verb, default-initialize it
result.verb = @unionInit(Verb, fld.name, fld.field_type{});
}
}
if (result.verb == null) {
try error_handling.process(error.EncounteredUnknownVerb, Error{
.option = "verb",
.kind = .unsupported,
});
}
continue;
}
}
try arglist.append(try result_arena_allocator.dupeZ(u8, item));
}
}
if (last_error != null)
return error.InvalidArguments;
// This will consume the rest of the arguments as positional ones.
// Only executes when the above loop is broken.
while (args_iterator.next()) |item| {
try arglist.append(try result_arena_allocator.dupeZ(u8, item));
}
result.positionals = arglist.toOwnedSlice();
return result;
}
/// The return type of the argument parser.
pub fn ParseArgsResult(comptime Generic: type, comptime MaybeVerb: ?type) type {
if (@typeInfo(Generic) != .Struct)
@compileError("Generic argument definition must be a struct");
if (MaybeVerb) |Verb| {
const ti: std.builtin.TypeInfo = @typeInfo(Verb);
if (ti != .Union or ti.Union.tag_type == null)
@compileError("Verb must be a tagged union");
}
return struct {
const Self = @This();
/// Exports the type of options.
pub const GenericOptions = Generic;
pub const Verbs = MaybeVerb orelse void;
arena: std.heap.ArenaAllocator,
/// The options with either default or set values.
options: Generic,
/// The verb that was parsed or `null` if no first positional was provided.
/// Is `void` when verb parsing is disabled
verb: if (MaybeVerb) |Verb| ?Verb else void,
/// The positional arguments that were passed to the process.
positionals: [][:0]const u8,
/// Name of the executable file (or: zeroth argument)
executable_name: ?[:0]const u8,
pub fn deinit(self: Self) void {
self.arena.child_allocator.free(self.positionals);
if (self.executable_name) |n|
self.arena.child_allocator.free(n);
self.arena.deinit();
}
};
}
/// Returns true if the given type requires an argument to be parsed.
fn requiresArg(comptime T: type) bool {
const H = struct {
fn doesArgTypeRequireArg(comptime Type: type) bool {
if (Type == []const u8)
return true;
return switch (@as(std.builtin.TypeId, @typeInfo(Type))) {
.Int, .Float, .Enum => true,
.Bool => false,
.Struct, .Union => true,
.Pointer => true,
else => @compileError(@typeName(Type) ++ " is not a supported argument type!"),
};
}
};
const ti = @typeInfo(T);
if (ti == .Optional) {
return H.doesArgTypeRequireArg(ti.Optional.child);
} else {
return H.doesArgTypeRequireArg(T);
}
}
/// Parses a boolean option.
fn parseBoolean(str: []const u8) !bool {
return if (std.mem.eql(u8, str, "yes"))
true
else if (std.mem.eql(u8, str, "true"))
true
else if (std.mem.eql(u8, str, "y"))
true
else if (std.mem.eql(u8, str, "no"))
false
else if (std.mem.eql(u8, str, "false"))
false
else if (std.mem.eql(u8, str, "n"))
false
else
return error.NotABooleanValue;
}
/// Parses an int option.
fn parseInt(comptime T: type, str: []const u8) !T {
var buf = str;
var multiplier: T = 1;
if (buf.len != 0) {
var base1024 = false;
if (std.ascii.toLower(buf[buf.len - 1]) == 'i') { //ki vs k for instance
buf.len -= 1;
base1024 = true;
}
if (buf.len != 0) {
var pow: u3 = switch (buf[buf.len - 1]) {
'k', 'K' => 1, //kilo
'm', 'M' => 2, //mega
'g', 'G' => 3, //giga
't', 'T' => 4, //tera
'p', 'P' => 5, //peta
else => 0,
};
if (pow != 0) {
buf.len -= 1;
if (comptime std.math.maxInt(T) < 1024)
return error.Overflow;
var base: T = if (base1024) 1024 else 1000;
multiplier = try std.math.powi(T, base, @intCast(T, pow));
}
}
}
const ret: T = switch (@typeInfo(T).Int.signedness) {
.signed => try std.fmt.parseInt(T, buf, 0),
.unsigned => try std.fmt.parseUnsigned(T, buf, 0),
};
return try std.math.mul(T, ret, multiplier);
}
test "parseInt" {
const tst = std.testing;
try tst.expectEqual(@as(i32, 50), try parseInt(i32, "50"));
try tst.expectEqual(@as(i32, 6000), try parseInt(i32, "6k"));
try tst.expectEqual(@as(u32, 2048), try parseInt(u32, "0x2KI"));
try tst.expectEqual(@as(i8, 0), try parseInt(i8, "0"));
try tst.expectEqual(@as(usize, 10_000_000_000), try parseInt(usize, "0xAg"));
try tst.expectError(error.Overflow, parseInt(i2, "1m"));
try tst.expectError(error.Overflow, parseInt(u16, "1Ti"));
}
/// Converts an argument value to the target type.
fn convertArgumentValue(comptime T: type, allocator: std.mem.Allocator, textInput: []const u8) !T {
switch (@typeInfo(T)) {
.Optional => |opt| return try convertArgumentValue(opt.child, allocator, textInput),
.Bool => if (textInput.len > 0)
return try parseBoolean(textInput)
else
return true, // boolean options are always true
.Int => return try parseInt(T, textInput),
.Float => return try std.fmt.parseFloat(T, textInput),
.Enum => {
if (@hasDecl(T, "parse")) {
return try T.parse(textInput);
} else {
return std.meta.stringToEnum(T, textInput) orelse return error.InvalidEnumeration;
}
},
.Struct, .Union => {
if (@hasDecl(T, "parse")) {
return try T.parse(textInput);
} else {
@compileError(@typeName(T) ++ " has no public visible `fn parse([]const u8) !T`!");
}
},
.Pointer => |ptr| switch (ptr.size) {
.Slice => {
if (ptr.child != u8) {
@compileError(@typeName(T) ++ " is not a supported pointer type, only slices of u8 are supported");
}
// If the type contains a sentinel dupe the text input to a new buffer.
// This is equivalent to allocator.dupeZ but works with any sentinel.
if (comptime std.meta.sentinel(T)) |sentinel| {
const data = try allocator.alloc(u8, textInput.len + 1);
std.mem.copy(u8, data, textInput);
data[textInput.len] = sentinel;
return data[0..textInput.len :sentinel];
}
// Otherwise the type is []const u8 so just return the text input.
return textInput;
},
else => @compileError(@typeName(T) ++ " is not a supported pointer type!"),
},
else => @compileError(@typeName(T) ++ " is not a supported argument type!"),
}
}
/// Parses an option value into the correct type.
fn parseOption(
comptime Spec: type,
arena: std.mem.Allocator,
target_struct: *Spec,
args: anytype,
error_handling: ErrorHandling,
last_error: *?anyerror,
/// The name of the option that is currently parsed.
comptime name: []const u8,
/// Optional pre-defined value for options that use `--foo=bar`
value: ?[]const u8,
) !void {
const field_type = @TypeOf(@field(target_struct, name));
const final_value = if (value) |val| blk: {
// use the literal value
const res = try arena.dupeZ(u8, val);
break :blk res;
} else if (requiresArg(field_type)) blk: {
// fetch from parser
const val = args.next();
if (val == null or std.mem.eql(u8, val.?, "--")) {
last_error.* = error.MissingArgument;
try error_handling.process(error.MissingArgument, Error{
.option = "--" ++ name,
.kind = .missing_argument,
});
return;
}
const res = try arena.dupeZ(u8, val.?);
break :blk res;
} else blk: {
// argument is "empty"
break :blk "";
};
@field(target_struct, name) = convertArgumentValue(field_type, arena, final_value) catch |err| {
last_error.* = err;
try error_handling.process(err, Error{
.option = "--" ++ name,
.kind = .{ .invalid_value = final_value },
});
// we couldn't parse the value, so we return a undefined value as we have signalled an
// error and won't return this anyways.
return undefined;
};
}
/// A collection of errors that were encountered while parsing arguments.
pub const ErrorCollection = struct {
const Self = @This();
arena: std.heap.ArenaAllocator,
list: std.ArrayList(Error),
pub fn init(allocator: std.mem.Allocator) Self {
return Self{
.arena = std.heap.ArenaAllocator.init(allocator),
.list = std.ArrayList(Error).init(allocator),
};
}
pub fn deinit(self: *Self) void {
self.list.deinit();
self.arena.deinit();
self.* = undefined;
}
/// Returns the current enumeration of errors.
pub fn errors(self: Self) []const Error {
return self.list.items;
}
/// Appends an error to the collection
fn insert(self: *Self, err: Error) !void {
var dupe = Error{
.option = try self.arena.allocator().dupe(u8, err.option),
.kind = switch (err.kind) {
.invalid_value => |v| Error.Kind{
.invalid_value = try self.arena.allocator().dupe(u8, v),
},
// flat copy
.unknown, .out_of_memory, .unsupported, .invalid_placement, .missing_argument, .missing_executable_name, .unknown_verb => err.kind,
},
};
try self.list.append(dupe);
}
};
/// An argument parsing error.
pub const Error = struct {
const Self = @This();
/// The option that yielded the error
option: []const u8,
/// The kind of error, might include additional information
kind: Kind,
pub fn format(self: Self, comptime fmt: []const u8, options: std.fmt.FormatOptions, writer: anytype) !void {
_ = fmt;
_ = options;
switch (self.kind) {
.unknown => try writer.print("The option {s} does not exist", .{self.option}),
.invalid_value => |value| try writer.print("Invalid value '{s}' for option {s}", .{ value, self.option }),
.out_of_memory => try writer.print("Out of memory while parsing option {s}", .{self.option}),
.unsupported => try writer.writeAll("Short command line options are not supported."),
.invalid_placement => try writer.writeAll("An option with argument must be the last option for short command line options."),
.missing_argument => try writer.print("Missing argument for option {s}", .{self.option}),
.missing_executable_name => try writer.writeAll("Failed to get executable name from the argument list!"),
.unknown_verb => try writer.print("Unknown verb '{s}'.", .{self.option}),
}
}
const Kind = union(enum) {
/// When the argument itself is unknown
unknown,
/// When the parsing of an argument value failed
invalid_value: []const u8,
/// When the parsing of an argument value triggered a out of memory error
out_of_memory,
/// When the argument is a short argument and no shorthands are enabled
unsupported,
/// Can only happen when a shorthand for an option requires an argument, but is followed by more shorthands.
invalid_placement,
/// An option was passed that requires an argument, but the option was passed last.
missing_argument,
/// This error has an empty option name and can only happen when parsing the argument list for a process.
missing_executable_name,
/// This error has the verb as an option name and will happen when a verb is provided that is not known.
unknown_verb,
};
};
/// The error handling method that should be used.
pub const ErrorHandling = union(enum) {
const Self = @This();
/// Do not print or process any errors, just
/// return a fitting error on the first argument mismatch.
silent,
/// Print errors to stderr and return a `error.InvalidArguments`.
print,
/// Collect errors into the error collection and return
/// `error.InvalidArguments` when any error was encountered.
collect: *ErrorCollection,
/// Processes an error with the given handling method.
fn process(self: Self, src_error: anytype, err: Error) !void {
if (@typeInfo(@TypeOf(src_error)) != .ErrorSet)
@compileError("src_error must be a error union!");
switch (self) {
.silent => return src_error,
.print => try std.io.getStdErr().writer().print("{}\n", .{err}),
.collect => |collection| try collection.insert(err),
}
}
};
test {
std.testing.refAllDecls(@This());
}
test "ErrorCollection" {
var option_buf = "option".*;
var invalid_buf = "invalid".*;
var ec = ErrorCollection.init(std.testing.allocator);
defer ec.deinit();
try ec.insert(Error{
.option = &option_buf,
.kind = .{ .invalid_value = &invalid_buf },
});
option_buf = undefined;
invalid_buf = undefined;
try std.testing.expectEqualStrings("option", ec.errors()[0].option);
try std.testing.expectEqualStrings("invalid", ec.errors()[0].kind.invalid_value);
}
const TestIterator = struct {
sequence: []const [:0]const u8,
index: usize = 0,
pub fn init(items: []const [:0]const u8) TestIterator {
return TestIterator{ .sequence = items };
}
pub fn next(self: *@This()) ?[:0]const u8 {
if (self.index >= self.sequence.len)
return null;
const result = self.sequence[self.index];
self.index += 1;
return result;
}
};
const TestEnum = enum { default, special, slow, fast };
const TestGenericOptions = struct {
output: ?[]const u8 = null,
@"with-offset": bool = false,
@"with-hexdump": bool = false,
@"intermix-source": bool = false,
numberOfBytes: ?i32 = null,
signed_number: ?i64 = null,
unsigned_number: ?u64 = null,
mode: TestEnum = .default,
// This declares short-hand options for single hyphen
pub const shorthands = .{
.S = "intermix-source",
.b = "with-hexdump",
.O = "with-offset",
.o = "output",
};
};
const TestVerb = union(enum) {
magic: MagicOptions,
booze: BoozeOptions,
const MagicOptions = struct { invoke: bool = false };
const BoozeOptions = struct {
cocktail: bool = false,
longdrink: bool = false,
pub const shorthands = .{
.c = "cocktail",
.l = "longdrink",
};
};
};
test "basic parsing (no verbs)" {
var titerator = TestIterator.init(&[_][:0]const u8{
"--output",
"foobar",
"--with-offset",
"--numberOfBytes",
"-250",
"--unsigned_number",
"0xFF00FF",
"positional 1",
"--mode",
"special",
"positional 2",
});
var args = try parseInternal(TestGenericOptions, null, &titerator, std.testing.allocator, .print);
defer args.deinit();
try std.testing.expectEqual(@as(?[:0]const u8, null), args.executable_name);
try std.testing.expect(void == @TypeOf(args.verb));
try std.testing.expectEqual(@as(usize, 2), args.positionals.len);
try std.testing.expectEqualStrings("positional 1", args.positionals[0]);
try std.testing.expectEqualStrings("positional 2", args.positionals[1]);
try std.testing.expectEqualStrings("foobar", args.options.output.?);
try std.testing.expectEqual(@as(?i32, -250), args.options.numberOfBytes);
try std.testing.expectEqual(@as(?u64, 0xFF00FF), args.options.unsigned_number);
try std.testing.expectEqual(TestEnum.special, args.options.mode);
try std.testing.expectEqual(@as(?i64, null), args.options.signed_number);
try std.testing.expectEqual(true, args.options.@"with-offset");
try std.testing.expectEqual(false, args.options.@"with-hexdump");
try std.testing.expectEqual(false, args.options.@"intermix-source");
}
test "shorthand parsing (no verbs)" {
var titerator = TestIterator.init(&[_][:0]const u8{
"-o",
"foobar",
"-O",
"--numberOfBytes",
"-250",
"--unsigned_number",
"0xFF00FF",
"positional 1",
"--mode",
"special",
"positional 2",
});
var args = try parseInternal(TestGenericOptions, null, &titerator, std.testing.allocator, .print);
defer args.deinit();
try std.testing.expectEqual(@as(?[:0]const u8, null), args.executable_name);
try std.testing.expect(void == @TypeOf(args.verb));
try std.testing.expectEqual(@as(usize, 2), args.positionals.len);
try std.testing.expectEqualStrings("positional 1", args.positionals[0]);
try std.testing.expectEqualStrings("positional 2", args.positionals[1]);
try std.testing.expectEqualStrings("foobar", args.options.output.?);
try std.testing.expectEqual(@as(?i32, -250), args.options.numberOfBytes);
try std.testing.expectEqual(@as(?u64, 0xFF00FF), args.options.unsigned_number);
try std.testing.expectEqual(TestEnum.special, args.options.mode);
try std.testing.expectEqual(@as(?i64, null), args.options.signed_number);
try std.testing.expectEqual(true, args.options.@"with-offset");
try std.testing.expectEqual(false, args.options.@"with-hexdump");
try std.testing.expectEqual(false, args.options.@"intermix-source");
}
test "basic parsing (with verbs)" {
var titerator = TestIterator.init(&[_][:0]const u8{
"--output", // non-verb options can come before or after verb
"foobar",
"booze", // verb
"--with-offset",
"--numberOfBytes",
"-250",
"--unsigned_number",
"0xFF00FF",
"positional 1",
"--mode",
"special",
"positional 2",
"--cocktail",
});
var args = try parseInternal(TestGenericOptions, TestVerb, &titerator, std.testing.allocator, .print);
defer args.deinit();
try std.testing.expectEqual(@as(?[:0]const u8, null), args.executable_name);
try std.testing.expect(?TestVerb == @TypeOf(args.verb));
try std.testing.expectEqual(@as(usize, 2), args.positionals.len);
try std.testing.expectEqualStrings("positional 1", args.positionals[0]);
try std.testing.expectEqualStrings("positional 2", args.positionals[1]);
try std.testing.expectEqualStrings("foobar", args.options.output.?);
try std.testing.expectEqual(@as(?i32, -250), args.options.numberOfBytes);
try std.testing.expectEqual(@as(?u64, 0xFF00FF), args.options.unsigned_number);
try std.testing.expectEqual(TestEnum.special, args.options.mode);
try std.testing.expectEqual(@as(?i64, null), args.options.signed_number);
try std.testing.expectEqual(true, args.options.@"with-offset");
try std.testing.expectEqual(false, args.options.@"with-hexdump");
try std.testing.expectEqual(false, args.options.@"intermix-source");
try std.testing.expect(args.verb.? == .booze);
const booze = args.verb.?.booze;
try std.testing.expectEqual(true, booze.cocktail);
try std.testing.expectEqual(false, booze.longdrink);
}
test "shorthand parsing (with verbs)" {
var titerator = TestIterator.init(&[_][:0]const u8{
"booze", // verb
"-o",
"foobar",
"-O",
"--numberOfBytes",
"-250",
"--unsigned_number",
"0xFF00FF",
"positional 1",
"--mode",
"special",
"positional 2",
"-c", // --cocktail
});
var args = try parseInternal(TestGenericOptions, TestVerb, &titerator, std.testing.allocator, .print);
defer args.deinit();
try std.testing.expectEqual(@as(?[:0]const u8, null), args.executable_name);
try std.testing.expect(?TestVerb == @TypeOf(args.verb));
try std.testing.expectEqual(@as(usize, 2), args.positionals.len);
try std.testing.expectEqualStrings("positional 1", args.positionals[0]);
try std.testing.expectEqualStrings("positional 2", args.positionals[1]);
try std.testing.expectEqualStrings("foobar", args.options.output.?);
try std.testing.expectEqual(@as(?i32, -250), args.options.numberOfBytes);
try std.testing.expectEqual(@as(?u64, 0xFF00FF), args.options.unsigned_number);
try std.testing.expectEqual(TestEnum.special, args.options.mode);
try std.testing.expectEqual(@as(?i64, null), args.options.signed_number);
try std.testing.expectEqual(true, args.options.@"with-offset");
try std.testing.expectEqual(false, args.options.@"with-hexdump");
try std.testing.expectEqual(false, args.options.@"intermix-source");
try std.testing.expect(args.verb.? == .booze);
const booze = args.verb.?.booze;
try std.testing.expectEqual(true, booze.cocktail);
try std.testing.expectEqual(false, booze.longdrink);
}
test "strings with sentinel" {
var titerator = TestIterator.init(&[_][:0]const u8{
"--output",
"foobar",
});
var args = try parseInternal(
struct {
output: ?[:0]const u8 = null,
},
null,
&titerator,
std.testing.allocator,
.print,
);
defer args.deinit();
try std.testing.expectEqual(@as(?[:0]const u8, null), args.executable_name);
try std.testing.expect(void == @TypeOf(args.verb));
try std.testing.expectEqual(@as(usize, 0), args.positionals.len);
try std.testing.expectEqualStrings("foobar", args.options.output.?);
}
test "option argument --" {
var titerator = TestIterator.init(&[_][:0]const u8{
"--output",
"--",
});
try std.testing.expectError(error.MissingArgument, parseInternal(
struct {
output: ?[:0]const u8 = null,
},
null,
&titerator,
std.testing.allocator,
.silent,
));
}
|
args.zig
|
const std = @import("std");
const Allocator = std.mem.Allocator;
const List = std.ArrayList;
const Map = std.AutoHashMap;
const StrMap = std.StringHashMap;
const BitSet = std.DynamicBitSet;
const Str = []const u8;
const util = @import("util.zig");
const gpa = util.gpa;
const data = @embedFile("../data/day05.txt");
// const data = @embedFile("../data/day05-tst.txt");
pub fn main() !void {
var it = tokenize(u8, data, "\r\n");
var sits = List(u16).init(gpa);
while (it.next()) |line| {
var row_min: u16 = 0;
var row_max: u16 = 127;
for (line[0..7]) |c| {
if (c == 'B') {
row_min = @divTrunc(row_max - row_min, 2) + row_min + 1;
} else if (c == 'F') {
row_max = @divTrunc(row_max - row_min, 2) + row_min;
} else {
unreachable;
}
}
var col_min: u16 = 0;
var col_max: u16 = 7;
for (line[7..]) |c| {
if (c == 'L') {
col_max = @divTrunc(col_max - col_min, 2) + col_min;
} else if (c == 'R') {
col_min = @divTrunc(col_max - col_min, 2) + col_min + 1;
} else {
unreachable;
}
}
try sits.append(row_min * 8 + col_min);
}
std.sort.sort(u16, sits.items, {}, comptime std.sort.asc(u16));
var i: usize = 0;
var missing: u16 = 0;
while (i < sits.items.len - 1) : (i += 1) {
if (sits.items[i + 1] != (sits.items[i] + 1)) {
missing = sits.items[i] + 1;
break;
}
}
print("{} {}\n", .{ sits.items[sits.items.len - 1], missing });
}
// Useful stdlib functions
const tokenize = std.mem.tokenize;
const split = std.mem.split;
const indexOf = std.mem.indexOfScalar;
const indexOfAny = std.mem.indexOfAny;
const indexOfStr = std.mem.indexOfPosLinear;
const lastIndexOf = std.mem.lastIndexOfScalar;
const lastIndexOfAny = std.mem.lastIndexOfAny;
const lastIndexOfStr = std.mem.lastIndexOfLinear;
const trim = std.mem.trim;
const sliceMin = std.mem.min;
const sliceMax = std.mem.max;
const parseInt = std.fmt.parseInt;
const parseFloat = std.fmt.parseFloat;
const min = std.math.min;
const min3 = std.math.min3;
const max = std.math.max;
const max3 = std.math.max3;
const print = std.debug.print;
const assert = std.debug.assert;
const sort = std.sort.sort;
const asc = std.sort.asc;
const desc = std.sort.desc;
|
src/day05.zig
|
const std = @import("std");
const TermGUI = @import("TermGUI.zig");
const cli = @import("cli.zig");
fn renderJsonNode(out: anytype, key: []const u8, value: *const std.json.Value, indent: u32) @TypeOf(out).Error!void {
const collapsible = switch (value.*) {
.Object => true,
.Array => true,
.Float => false,
.String => false,
.Integer => false,
.Bool => false,
.Null => false,
};
var i: u32 = 0;
while (i < indent) : (i += 1) {
try out.print("│", .{}); // ╵ todo
}
try out.print("{} {}", .{ if (collapsible) @as([]const u8, "-") else "▾", key });
switch (value.*) {
.Object => |obj| {
std.debug.warn("\n", .{});
var iter = obj.iterator();
while (iter.next()) |kv| {
try renderJsonNode(out, kv.key, &kv.value, indent + 1);
}
},
.Array => |arr| {
std.debug.warn("\n", .{});
for (arr.items) |itm| {
try renderJsonNode(out, "0:", &itm, indent + 1);
}
},
.String => |str| {
try out.print(" \"{}\"\n", .{str});
},
.Float => |f| try out.print(" {d}\n", .{f}),
.Integer => |f| try out.print(" {d}\n", .{f}),
.Bool => |f| try out.print(" {}\n", .{f}),
.Null => try out.print(" null\n", .{}),
}
}
const Themes = [_]Theme{
Theme.from(.{ .brred, .bryellow, .brgreen, .brcyan, .brblue, .brmagenta }),
Theme.from(.{ .brmagenta, .bryellow, .brblue }),
Theme.from(.{ .bryellow, .brwhite, .magenta }),
Theme.from(.{ .brblue, .brmagenta, .brwhite, .brmagenta }),
Theme.from(.{ .brmagenta, .brwhite, .brgreen }),
};
const Theme = struct {
colors: []const cli.Color,
pub fn from(comptime items: anytype) Theme {
var res: []const cli.Color = &[_]cli.Color{};
for (items) |item| {
res = res ++ &[_]cli.Color{cli.Color.from(item)};
}
return Theme{ .colors = res };
}
};
const Point = struct { x: u32, y: u32 };
const Selection = struct {
hover: ?Point,
mouseup: bool,
rerender: bool,
};
const Path = struct {
const ALEntry = struct {
index: usize,
};
al: std.ArrayList(ALEntry),
fn init(alloc: *std.mem.Allocator) !Path {
var al = std.ArrayList(ALEntry).init(alloc);
errdefer al.deinit();
try al.append(.{ .index = 0 });
return Path{
.al = al,
};
}
fn deinit(path: *Path) void {
path.al.deinit();
path.* = undefined;
}
fn last(path: Path) *ALEntry {
return &path.al.items[path.al.items.len - 1];
}
fn fixClosed(path: *Path, root: *JsonRender) void {
var res = root;
for (path.al.items) |itm, i| {
res = &res.childNodes[itm.index].value;
if (!res.open) {
path.al.items.len = i + 1;
return;
}
}
}
fn getNode(path: Path, root: *JsonRender) *JsonRender {
var res = root;
for (path.al.items) |itm| {
res = &res.childNodes[itm.index].value;
}
return res;
}
fn getNodeMinusOne(path: Path, root: *JsonRender) *JsonRender {
var res = root;
for (path.al.items[0 .. path.al.items.len - 1]) |itm| {
res = &res.childNodes[itm.index].value;
}
return res;
}
pub fn advance(path: *Path, root: *JsonRender) !void {
// get the node
var thisNode = path.getNode(root);
if (thisNode.childNodes.len > 0 and thisNode.open) {
try path.al.append(.{ .index = 0 });
return;
}
var last_ = path.last();
var node = path.getNodeMinusOne(root);
while (last_.index + 1 >= node.childNodes.len) {
if (path.al.items.len <= 1) return; // cannot advance
_ = path.al.pop();
last_ = path.last();
node = path.getNodeMinusOne(root);
}
last_.index += 1;
}
pub fn devance(path: *Path, root: *JsonRender) !void {
var last_ = path.last();
if (last_.index == 0) {
if (path.al.items.len <= 1) return; // cannot devance
_ = path.al.pop();
return;
}
last_.index -= 1;
var lastDeepest = path.getNode(root);
while (lastDeepest.childNodes.len > 0 and lastDeepest.open) {
try path.al.append(.{ .index = lastDeepest.childNodes.len - 1 });
if (lastDeepest.childNodes.len > 0) lastDeepest = &lastDeepest.childNodes[lastDeepest.childNodes.len - 1].value;
}
}
fn forDepth(path: Path, depth: usize) ?ALEntry {
if (depth >= path.al.items.len) return null;
return path.al.items[depth];
}
};
const JsonRender = struct {
const JsonKey = union(enum) { int: usize, str: []const u8, root };
const ChildNode = struct { key: JsonKey, value: JsonRender };
childNodes: []ChildNode,
content: std.json.Value,
index: usize,
open: bool,
// parent: *JsonRender,
pub fn init(alloc: *std.mem.Allocator, jsonv: std.json.Value, index: usize) std.mem.Allocator.Error!JsonRender {
const childNodes = switch (jsonv) {
.Array => |arr| blk: {
var childNodesL = try alloc.alloc(ChildNode, arr.items.len);
errdefer alloc.free(childNodesL);
for (arr.items) |itm, i| {
childNodesL[i] = .{ .key = .{ .int = i }, .value = try JsonRender.init(alloc, itm, i) };
}
break :blk childNodesL;
},
.Object => |hm| blk: {
const items = hm.items(); // what
var childNodesL = try alloc.alloc(ChildNode, items.len);
errdefer alloc.free(childNodesL);
for (items) |itm, i| {
childNodesL[i] = .{ .key = .{ .str = itm.key }, .value = try JsonRender.init(alloc, itm.value, i) };
}
break :blk childNodesL;
},
else => &[_]ChildNode{},
};
errdefer alloc.free(childNodes);
return JsonRender{
.open = false,
.childNodes = childNodes,
.content = jsonv,
.index = index,
};
}
pub fn deinit(jr: *JsonRender, alloc: *std.mem.Allocator) void {
alloc.free(jr.childNodes);
}
// todo rename JsonRender and move the render fn out of this so it actually holds data rather than
// being a gui component type thing
};
pub fn renderJson(
me: *JsonRender,
out: anytype,
key: JsonRender.JsonKey,
x: u32,
y: u32,
h: u32,
theme: Theme,
themeIndex: usize,
selection: *Selection,
startAt: Path,
depth: ?usize,
) @TypeOf(out).Error!u32 {
if (y >= h) return 0;
const pathv = if (depth) |d| if (startAt.forDepth(d)) |v| v.index else 0 else 0;
const hovering = if (selection.hover) |hov| hov.x >= x and hov.y == y else false;
const focused = false;
const bgstyl: ?cli.Color = if (hovering) cli.Color.from(.brblack) else null;
if (hovering and selection.mouseup) me.open = !me.open;
try cli.moveCursor(out, x, y);
const themeStyle: cli.Style = .{ .fg = theme.colors[themeIndex % theme.colors.len], .bg = bgstyl };
var cy = y;
// TODO only show the header if startAt < header
if (true) {
try cli.setTextStyle(out, themeStyle, null);
if (me.childNodes.len == 0)
try out.writeAll("-")
else if (me.open)
try out.writeAll("▾")
else
try out.writeAll("▸");
try cli.setTextStyle(out, .{ .bg = bgstyl }, null);
switch (key) {
.str => |str| {
try cli.setTextStyle(out, .{ .fg = cli.Color.from(.white), .bg = bgstyl }, null);
try out.print(" \"", .{});
try cli.setTextStyle(out, themeStyle, null);
try out.print("{}", .{str});
try cli.setTextStyle(out, .{ .fg = cli.Color.from(.white), .bg = bgstyl }, null);
try out.print("\"", .{});
try cli.setTextStyle(out, .{ .bg = bgstyl }, null);
try out.writeAll(":");
},
.int => |int| {
try cli.setTextStyle(out, themeStyle, null);
try out.print(" {}", .{int});
try cli.setTextStyle(out, .{ .bg = bgstyl }, null);
try out.writeAll(":");
},
.root => {},
}
switch (me.content) {
.Array => if (me.childNodes.len == 0) try out.writeAll(" []") else if (!me.open) try out.writeAll(" […]"),
.Object => if (me.childNodes.len == 0) try out.writeAll(" {}") else if (!me.open) try out.writeAll(" {…}"),
.String => |str| try out.print(" \"{}\"", .{str}),
.Float => |f| try out.print(" {d}", .{f}),
.Integer => |f| try out.print(" {d}", .{f}),
.Bool => |f| try out.print(" {}", .{f}),
.Null => try out.print(" null", .{}),
}
try cli.clearToEol(out);
cy += 1;
}
try cli.setTextStyle(out, .{}, null);
if (me.open) for (me.childNodes[pathv..]) |*node, i| {
if (cy == h) break;
// check if the next item is on the path
const onpath = if (depth) |d| i == 0 else false;
cy += try renderJson(&node.value, out, node.key, x + 2, cy, h, theme, themeIndex + 1, selection, startAt, if (onpath) depth.? + 1 else null);
if (cy > h) unreachable; // rendered out of screen
};
const barhov = if (selection.hover) |hov| hov.x == x and hov.y > y and hov.y < cy else false;
if (barhov and selection.mouseup) {
me.open = !me.open;
selection.rerender = true;
}
const fgcolr: cli.Color = if (barhov) cli.Color.from(.brwhite) else cli.Color.from(.brblack);
try cli.setTextStyle(out, .{ .fg = fgcolr }, null);
var cyy: u32 = y + 1;
while (cyy < cy) : (cyy += 1) {
try cli.moveCursor(out, x, cyy);
if (cyy + 1 < cy or cyy + 1 == h) try out.writeAll("│")
// zig-fmt
else try out.writeAll("╵");
}
return cy - y;
}
var globalOT: ?std.os.termios = null;
pub fn panic(msg: []const u8, stack_trace: ?*std.builtin.StackTrace) noreturn {
const stdinF = std.io.getStdIn();
cli.stopCaptureMouse() catch {};
cli.exitFullscreen() catch {};
if (globalOT) |ot| cli.exitRawMode(stdinF, ot) catch {};
var out = std.io.getStdOut().writer();
cli.setTextStyle(out, .{ .fg = cli.Color.from(.brred) }, null) catch {};
out.print("Panic: {}\n", .{msg}) catch {};
if (stack_trace) |trace|
std.debug.dumpStackTrace(trace.*);
out.print("Consider posting a bug report: https://github.com/pfgithub/jsonexplorer/issues/new\n", .{}) catch {};
std.os.exit(1);
}
pub fn main() !void {
const alloc = std.heap.page_allocator;
const stdinf = std.io.getStdIn();
if (std.os.isatty(stdinf.handle)) {
std.debug.warn("Usage: echo '{{}}' | jsonexplorer\n", .{});
return;
}
std.debug.warn("\r\x1b[KReading File...", .{});
const jsonTxt = try stdinf.reader().readAllAlloc(alloc, 1000 * 1000 * 1000);
defer alloc.free(jsonTxt);
std.debug.warn("\r\x1b[KParsing JSON...", .{});
var jsonParser = std.json.Parser.init(alloc, false); // copy_strings = false;
defer jsonParser.deinit();
var jsonRes = jsonParser.parse(jsonTxt) catch |e| {
std.debug.warn("\nJSON parsing error: {e}\n", .{e});
return;
};
defer jsonRes.deinit();
var jsonRoot = &jsonRes.root;
std.debug.warn("\r\x1b[K", .{});
var stdin2file = try std.fs.openFileAbsolute("/dev/tty", .{ .read = true });
defer stdin2file.close();
var stdin2 = stdin2file.reader();
const rawMode = try cli.enterRawMode(stdin2file);
defer cli.exitRawMode(stdin2file, rawMode) catch {};
globalOT = rawMode;
cli.enterFullscreen() catch {};
defer cli.exitFullscreen() catch {};
cli.startCaptureMouse() catch {};
defer cli.stopCaptureMouse() catch {};
var stdoutf = std.io.getStdOut();
var stdout_buffered = std.io.bufferedWriter(stdoutf.writer());
const stdout = stdout_buffered.writer();
var jr = try JsonRender.init(alloc, jsonRoot.*, 0);
defer jr.deinit(alloc);
jr.open = true;
var mousePoint: Point = .{ .x = 0, .y = 0 };
var mouseVisible = false;
var startAt = try Path.init(alloc);
defer startAt.deinit();
var rerender = false;
while (if (rerender) @as(?cli.Event, cli.Event.none) else (cli.nextEvent(stdin2file)) catch @as(?cli.Event, cli.Event.none)) |ev| : (try stdout_buffered.flush()) {
if (ev.is("ctrl+c")) break;
if (ev.is("ctrl+p")) @panic("panic test");
try cli.clearScreen(stdout);
try cli.moveCursor(stdout, 0, 0);
var selxn = Selection{ .hover = if (mouseVisible) mousePoint else null, .mouseup = false, .rerender = false };
defer rerender = selxn.rerender;
startAt.fixClosed(&jr);
switch (ev) {
.mouse => |mev| {
mousePoint.x = mev.x;
mousePoint.y = mev.y;
if (mev.button == .left and mev.direction == .up) selxn.mouseup = true;
},
.blur => mouseVisible = false,
.focus => mouseVisible = true,
.scroll => |sev| {
mousePoint.x = sev.x;
mousePoint.y = sev.y;
// var px: i32 = if (sev.pixels == 3) 1 else -1;
var px = sev.pixels;
while (px > 0) : (px -= 1) {
try startAt.advance(&jr);
}
while (px < 0) : (px += 1) {
try startAt.devance(&jr);
}
},
else => {},
}
const ss = try cli.winSize(stdoutf);
_ = try renderJson(&jr, stdout, .root, 0, 0, ss.h, Themes[0], 0, &selxn, startAt, 0);
try stdout_buffered.flush();
// try stdout.print("Event: {}\n", .{ev});
}
// const tgui = TermGUI.init();
// defer tgui.deinit();
//
// while (true) {
// tgui.text(5, 5, "test");
//
// const ev = cli.nextEvent();
// if (ev.is("ctrl+c")) {
// break;
// }
// }
// an interactive json explorer
// eg `zig targets | jsonexplorer`
//
// / Filter...
// ▾ "abi"
// │ / filter (appears at the top of each list. left arrow to go to parent and filter it eg.)
// │ - 0: "none"
// │ - 1: "gnu"
// │ - 2: "gnuabin32"
// ╵ - 3: "gnuabin64"
// ▸ "arch"
// ▸ "cpuFeatures"
// ▸ "cpus"
// ▸ "glibc"
// ▸ "libc"
// ▸ "native"
// ▸ "os"
//
// needs an easy to access filter function
// like at the top or keybind /
//
// just noticed a neat unicode thing —🢒
// |
// 🢓
//
// imagine if I could make a library where terminal ui and imgui were the same
// cross platform. desktop/mobile/web(webgl)/terminal(gui) and accessability stuff
//
// that would be neat
// terminal gui would be pretty different from the rest in terms of pixel distances
// lib user would have to specify abstract distances which is bad for design
}
|
src/main.zig
|
usingnamespace @import("constants.zig");
usingnamespace @import("../include/pspge.zig");
usingnamespace @import("../include/pspdisplay.zig");
usingnamespace @import("../include/pspthreadman.zig");
usingnamespace @import("../include/psploadexec.zig");
const builtin = @import("builtin");
//Internal variables for the screen
var x: u8 = 0;
var y: u8 = 0;
var vram_base: ?[*]u32 = null;
//Gets your "cursor" X position
pub fn screenGetX() u8 {
return x;
}
//Gets your "cursor" Y position
pub fn screenGetY() u8 {
return y;
}
//Sets the "cursor" position
pub fn screenSetXY(sX: u8, sY: u8) void {
x = sX;
y = sY;
}
//Clears the screen to the clear color (default is black)
pub fn screenClear() void {
var i: usize = 0;
while (i < SCR_BUF_WIDTH * SCREEN_HEIGHT) : (i += 1) {
vram_base.?[i] = cl_col;
}
}
//Color variables
var cl_col: u32 = 0xFF000000;
var bg_col: u32 = 0x00000000;
var fg_col: u32 = 0xFFFFFFFF;
//Set the background color
pub fn screenSetClearColor(color: u32) void {
cl_col = color;
}
var back_col_enable: bool = false;
//Enable text highlight
pub fn screenEnableBackColor() void {
back_col_enable = true;
}
//Disable text highlight
pub fn screenDisableBackColor() void {
back_col_enable = false;
}
//Set highlight color
pub fn screenSetBackColor(color: u32) void {
bg_col = color;
}
//Set text color
pub fn screenSetFrontColor(color: u32) void {
fg_col = color;
}
//Initialize the screen
pub fn screenInit() void {
x = 0;
y = 0;
vram_base = @intToPtr(?[*]u32, 0x40000000 | @ptrToInt(sceGeEdramGetAddr()));
_ = sceDisplaySetMode(0, SCREEN_WIDTH, SCREEN_HEIGHT);
_ = sceDisplaySetFrameBuf(vram_base, SCR_BUF_WIDTH, @enumToInt(PspDisplayPixelFormats.Format8888), 1);
screenClear();
}
//Print out a constant string
pub fn print(text: []const u8) void {
var i: usize = 0;
while (i < text.len) : (i += 1) {
if (text[i] == '\n') {
y += 1;
x = 0;
} else if (text[i] == '\t') {
x += 4;
} else {
internal_putchar(@as(u32, x) * 8, @as(u32, y) * 8, text[i]);
x += 1;
}
if (x > 60) {
x = 0;
y += 1;
if (y > 34) {
y = 0;
screenClear();
}
}
}
}
export fn pspDebugScreenInit() void {
screenInit();
}
export fn pspDebugScreenClear(color: u32) void {
screenSetClearColor(color);
screenClear();
}
export fn pspDebugScreenPrint(text: [*c]const u8) void {
print(std.mem.spanZ(text));
}
const std = @import("std");
//Print with formatting via the default PSP allocator
pub fn printFormat(comptime fmt: []const u8, args: anytype) !void {
const alloc = @import("allocator.zig");
var psp_allocator = &alloc.PSPAllocator.init().allocator;
var string = try std.fmt.allocPrint(psp_allocator, fmt, args);
defer psp_allocator.free(string);
print(string);
}
//Our font
pub const msxFont = @embedFile("./msxfont2.bin");
//Puts a character to screen
fn internal_putchar(cx: u32, cy: u32, ch: u8) void {
var off: usize = cx + (cy * SCR_BUF_WIDTH);
var i: usize = 0;
while (i < 8) : (i += 1) {
var j: usize = 0;
while (j < 8) : (j += 1) {
const mask: u32 = 128;
var idx: u32 = @as(u32, ch - 32) * 8 + i;
var glyph: u8 = msxFont[idx];
if ((glyph & (mask >> @intCast(@import("std").math.Log2Int(c_int), j))) != 0) {
vram_base.?[j + i * SCR_BUF_WIDTH + off] = fg_col;
} else if (back_col_enable) {
vram_base.?[j + i * SCR_BUF_WIDTH + off] = bg_col;
}
}
}
}
usingnamespace @import("module.zig");
//Meme panic
pub var pancakeMode: bool = false;
//Panic handler
//Import this in main to use!
pub fn panic(message: []const u8, stack_trace: ?*builtin.StackTrace) noreturn {
screenInit();
if (pancakeMode) {
//For @mrneo240
print("!!! PSP HAS PANCAKED !!!\n");
} else {
print("!!! PSP HAS PANICKED !!!\n");
}
print("REASON: ");
print(message);
//TODO: Stack Traces after STD.
//if (@errorReturnTrace()) |trace| {
// std.debug.dumpStackTrace(trace.*);
//}
print("\nExiting in 10 seconds...");
exitErr();
while (true) {}
}
|
src/psp/utils/debug.zig
|
const std = @import("std");
const Allocator = std.mem.Allocator;
const print = std.debug.print;
const data = @embedFile("../inputs/day21.txt");
pub fn main() anyerror!void {
var gpa_impl = std.heap.GeneralPurposeAllocator(.{}){};
defer _ = gpa_impl.deinit();
const gpa = gpa_impl.allocator();
return main_with_allocator(gpa);
}
pub fn main_with_allocator(allocator: Allocator) anyerror!void {
print("Part 1: {d}\n", .{try part1(data)});
print("Part 2: {d}\n", .{try part2(allocator, data)});
}
const State = struct {
const Self = @This();
current_player: u1,
p1: u4, // [0..9]
p1_score: usize,
p2: u4, // [0..9]
p2_score: usize,
fn parse(input: []const u8) !Self {
var it = std.mem.tokenize(u8, input, "\n");
const p1_str = std.mem.trimLeft(u8, it.next().?, "Player 1 starting position: ");
const p1 = try std.fmt.parseInt(u4, p1_str, 10);
const p2_str = std.mem.trimLeft(u8, it.next().?, "Player 2 starting position: ");
const p2 = try std.fmt.parseInt(u4, p2_str, 10);
return Self{
.current_player = 0,
.p1 = p1 - 1,
.p1_score = 0,
.p2 = p2 - 1,
.p2_score = 0,
};
}
fn step_deterministic(self: Self, rolls: [3]usize) Self {
var out = self;
const movement = rolls[0] + rolls[1] + rolls[2];
switch (self.current_player) {
0 => {
out.p1 = @intCast(u4, (@as(usize, self.p1) + movement) % 10);
out.p1_score += out.p1 + 1;
},
1 => {
out.p2 = @intCast(u4, (@as(usize, self.p2) + movement) % 10);
out.p2_score += out.p2 + 1;
},
}
out.current_player = ~self.current_player;
return out;
}
fn step(self: *Self, die: *Die) void {
self.* = step_deterministic(self.*, [3]usize{ die.roll(), die.roll(), die.roll() });
}
fn check_win(self: Self, score: usize) ?u1 {
const last_player = ~self.current_player;
switch (last_player) {
0 => if (self.p1_score >= score) return last_player,
1 => if (self.p2_score >= score) return last_player,
}
return null;
}
fn until_win(self: *Self, die: *Die, score: usize) u1 {
while (true) {
self.step(die);
if (self.check_win(score)) |winner| return winner;
}
}
};
const Die = struct {
const Self = @This();
up_to: u7,
state: u7,
count: usize,
fn init(up_to: u7) Self {
return Self{
.up_to = up_to,
.state = up_to,
.count = 0,
};
}
fn roll(self: *Self) usize {
self.count += 1;
self.state += 1;
if (self.state > self.up_to) self.state = 1;
return @as(usize, self.state);
}
};
fn part1(input: []const u8) !usize {
var state = try State.parse(input);
var die = Die.init(100);
const winner = state.until_win(&die, 1000);
switch (~winner) {
0 => return state.p1_score * die.count,
1 => return state.p2_score * die.count,
}
}
const Map = std.AutoHashMap(State, u64);
fn put_or_add(hm: *Map, key: State, val: u64) !void {
if (hm.getPtr(key)) |p| {
p.* += val;
} else {
try hm.put(key, val);
}
}
fn part2(allocator: Allocator, input: []const u8) !u64 {
const state = try State.parse(input);
var states = Map.init(allocator);
defer states.deinit();
try states.put(state, 1);
var temp = Map.init(allocator);
defer temp.deinit();
var p1_win: u64 = 0;
var p2_win: u64 = 0;
while (states.count() > 0) {
temp.clearRetainingCapacity();
var it = states.iterator();
while (it.next()) |e| {
const current = e.key_ptr.*;
var step_universe: usize = 0;
while (step_universe < 3 * 3 * 3) : (step_universe += 1) {
const roll = [3]usize{
step_universe % 3 + 1,
(step_universe / 3) % 3 + 1,
(step_universe / 3 / 3) % 3 + 1,
};
const next = current.step_deterministic(roll);
if (next.check_win(21)) |winner| {
switch (winner) {
0 => p1_win += e.value_ptr.*,
1 => p2_win += e.value_ptr.*,
}
} else {
try put_or_add(&temp, next, e.value_ptr.*);
}
}
}
std.mem.swap(Map, &states, &temp);
}
return std.math.max(p1_win, p2_win);
}
test "dice" {
const input =
\\Player 1 starting position: 4
\\Player 2 starting position: 8
;
const allocator = std.testing.allocator;
try std.testing.expectEqual(@as(usize, 739785), try part1(input));
try std.testing.expectEqual(@as(u64, 444356092776315), try part2(allocator, input));
}
|
src/day21.zig
|
const std = @import("std");
const builtin = @import("builtin");
const CallingConvention = @import("std").builtin.CallingConvention;
const is_nvptx = builtin.cpu.arch == .nvptx64;
const PtxKernel = if (is_nvptx) CallingConvention.PtxKernel else CallingConvention.Unspecified;
pub export fn transposeCpu(data: []const u32, trans: []u32, num_cols: usize) callconv(PtxKernel) void {
var i: usize = 0;
while (i < num_cols) : (i += 1) {
var j: usize = 0;
while (j < num_cols) : (j += 1) {
trans[num_cols * i + j] = data[num_cols * j + i];
}
}
}
pub export fn transposePerRow(data: []const u32, trans: []u32, num_cols: usize) callconv(PtxKernel) void {
const i = getIdX();
var j: usize = 0;
while (j < num_cols) : (j += 1) {
trans[num_cols * i + j] = data[num_cols * j + i];
}
}
pub export fn transposePerCell(data: []const u32, trans: []u32, num_cols: usize) callconv(PtxKernel) void {
const i = getIdX();
const j = getIdY();
if (i >= num_cols or j >= num_cols) return;
trans[num_cols * i + j] = data[num_cols * j + i];
}
pub const block_size = 16;
// Stage1 can't parse addrspace, so we use pre-processing tricks to only
// set the addrspace in Stage2.
// In Cuda, the kernel will have access to shared memory. This memory
// can have a compile-known size or a dynamic size.
// In the case of dynamic size the corresponding Cuda code is:
// extern __shared__ int buffer[];
// In Zig, the only type with unknown size is "opaque".
// Also note that the extern keyword is technically not correct, because the variable
// isn't defined in another compilation unit.
// This seems to only work for Ptx target, not sure why.
// The generated .ll code will be:
// `@transpose_per_block_buffer = external dso_local addrspace(3) global %lesson5_kernel.SharedMem, align 8`
// Corresponding .ptx:
// `.extern .shared .align 8 .b8 transpose_per_block_buffer[]`
const SharedMem = opaque {};
// extern var transpose_per_block_buffer: SharedMem align(8) addrspace(.shared); // stage2
var transpose_per_block_buffer: [block_size][block_size]u32 = undefined; // stage1
/// Each threads copy one element to the shared buffer and then back to the output
/// The speed up comes from the fact that all threads in the block will read contiguous
/// data and then write contiguous data.
pub export fn transposePerBlock(data: []const u32, trans: []u32, num_cols: usize) callconv(PtxKernel) void {
if (!is_nvptx) return;
// var buffer = @ptrCast([*]addrspace(.shared) [block_size]u32, &transpose_per_block_buffer); // stage2
var buffer = @ptrCast([*][block_size]u32, &transpose_per_block_buffer); // stage1
const block_i = gridIdX() * block_size;
const block_j = gridIdY() * block_size;
const block_out_i = block_j;
const block_out_j = block_i;
const i = threadIdX();
const j = threadIdY();
// coalesced read
if (i + block_i < num_cols and j + block_j < num_cols) {
buffer[j][i] = data[num_cols * (block_j + j) + (block_i + i)];
}
syncThreads();
// coalesced write
if (i + block_out_i < num_cols and j + block_out_j < num_cols) {
trans[num_cols * (block_out_j + j) + (block_out_i + i)] = buffer[i][j];
}
}
pub const block_size_inline = block_size;
// pub var transpose_per_block_inlined_buffer: [16][block_size][block_size]u32 addrspace(.shared) = undefined; // stage2
pub var transpose_per_block_inlined_buffer: [16][block_size][block_size]u32 = undefined; // stage1
/// Each threads copy a `block_size` contiguous elements to the shared buffer
/// and copy non-contiguous element from the buffer to a contiguous slice of the output
pub export fn transposePerBlockInlined(data: []const u32, trans: []u32, num_cols: usize) callconv(PtxKernel) void {
var buffer = &transpose_per_block_inlined_buffer[threadIdX()];
const block_i = getIdX() * block_size;
const block_j = gridIdY() * block_size;
const block_out_i = block_j;
const block_out_j = block_i;
const i = threadIdY();
if (i + block_i >= num_cols) return;
var j: usize = 0;
// coalesced read
while (j < block_size and j + block_j < num_cols) : (j += 1) {
buffer[j][i] = data[num_cols * (block_j + j) + (block_i + i)];
}
syncThreads();
if (block_out_i + i >= num_cols) return;
// coalesced write
j = 0;
while (j < block_size and block_out_j + j < num_cols) : (j += 1) {
trans[num_cols * (block_out_j + j) + (block_out_i + i)] = buffer[i][j];
}
}
pub inline fn threadIdX() usize {
if (!is_nvptx) return 0;
var tid = asm volatile ("mov.u32 \t$0, %tid.x;"
: [ret] "=r" (-> u32),
);
return @intCast(usize, tid);
}
pub inline fn threadDimX() usize {
if (!is_nvptx) return 0;
var ntid = asm volatile ("mov.u32 \t$0, %ntid.x;"
: [ret] "=r" (-> u32),
);
return @intCast(usize, ntid);
}
pub inline fn gridIdX() usize {
if (!is_nvptx) return 0;
var ctaid = asm volatile ("mov.u32 \t$0, %ctaid.x;"
: [ret] "=r" (-> u32),
);
return @intCast(usize, ctaid);
}
pub inline fn threadIdY() usize {
if (!is_nvptx) return 0;
var tid = asm volatile ("mov.u32 \t$0, %tid.y;"
: [ret] "=r" (-> u32),
);
return @intCast(usize, tid);
}
pub inline fn threadDimY() usize {
if (!is_nvptx) return 0;
var ntid = asm volatile ("mov.u32 \t$0, %ntid.y;"
: [ret] "=r" (-> u32),
);
return @intCast(usize, ntid);
}
pub inline fn gridIdY() usize {
if (!is_nvptx) return 0;
var ctaid = asm volatile ("mov.u32 \t$0, %ctaid.y;"
: [ret] "=r" (-> u32),
);
return @intCast(usize, ctaid);
}
pub inline fn getIdX() usize {
return threadIdX() + threadDimX() * gridIdX();
}
pub inline fn getIdY() usize {
return threadIdY() + threadDimY() * gridIdY();
}
pub inline fn syncThreads() void {
// @"llvm.nvvm.barrier0"();
if (!is_nvptx) return;
asm volatile ("bar.sync \t0;");
}
|
CS344/src/lesson5_kernel.zig
|
const std = @import("std");
const root = @import("./dns.zig");
const dns = root;
const resolvconf = @import("./resolvconf.zig");
pub fn randomId() u16 {
const seed = @truncate(u64, @bitCast(u128, std.time.nanoTimestamp()));
var r = std.rand.DefaultPrng.init(seed);
return r.random.int(u16);
}
/// Open a socket to a random DNS resolver declared in the systems'
/// "/etc/resolv.conf" file.
pub fn openSocketAnyResolver() !std.net.StreamServer.Connection {
var out_buffer: [256]u8 = undefined;
const nameserver_address_string = (try resolvconf.randomNameserver(&out_buffer)).?;
var addr = try std.net.Address.resolveIp(nameserver_address_string, 53);
var flags: u32 = std.os.SOCK_DGRAM;
const fd = try std.os.socket(addr.any.family, flags, std.os.IPPROTO_UDP);
return std.net.StreamServer.Connection{
.address = addr,
.file = std.fs.File{ .handle = fd },
};
}
/// Send a DNS packet to socket.
pub fn sendPacket(conn: std.net.StreamServer.Connection, packet: root.Packet) !void {
// we hold this buffer because File won't use sendto()
// and we need sendto() for UDP sockets. (makes sense)
//
// this is a limitation of std.net.
var buffer: [1024]u8 = undefined;
const typ = std.io.FixedBufferStream([]u8);
var stream = typ{ .buffer = &buffer, .pos = 0 };
var serializer = std.io.Serializer(.Big, .Bit, typ.Writer).init(stream.writer());
try serializer.serialize(packet);
try serializer.flush();
var result = buffer[0..packet.size()];
const dest_len: u32 = switch (conn.address.any.family) {
std.os.AF_INET => @sizeOf(std.os.sockaddr_in),
std.os.AF_INET6 => @sizeOf(std.os.sockaddr_in6),
else => unreachable,
};
_ = try std.os.sendto(conn.file.handle, result, 0, &conn.address.any, dest_len);
}
/// Receive a DNS packet from a socket.
pub fn recvPacket(conn: std.net.StreamServer.Connection, ctx: *dns.DeserializationContext) !root.Packet {
var packet_buffer: [1024]u8 = undefined;
const read_bytes = try conn.file.read(&packet_buffer);
const packet_bytes = packet_buffer[0..read_bytes];
var pkt = dns.Packet{
.header = .{},
.questions = &[_]dns.Question{},
.answers = &[_]dns.Resource{},
.nameservers = &[_]dns.Resource{},
.additionals = &[_]dns.Resource{},
};
var stream = std.io.FixedBufferStream([]const u8){ .buffer = packet_bytes, .pos = 0 };
try pkt.readInto(stream.reader(), ctx);
return pkt;
}
|
src/pkg2/helpers.zig
|
const std = @import("std");
const linux = std.os.linux;
const prot = @import("../protocols.zig");
const renderer = @import("../renderer.zig");
const compositor = @import("../compositor.zig");
const Context = @import("../client.zig").Context;
const Object = @import("../client.zig").Object;
const Client = @import("../client.zig").Client;
const ShmBuffer = @import("../shm_buffer.zig").ShmBuffer;
const Buffer = @import("../buffer.zig").Buffer;
const Window = @import("../window.zig").Window;
const Region = @import("../region.zig").Region;
const Link = @import("../window.zig").Link;
fn commit(context: *Context, wl_surface: Object) anyerror!void {
const window = @intToPtr(*Window, wl_surface.container);
defer {
if (!window.synchronized) window.flip();
}
const wl_buffer_id = window.wl_buffer_id orelse return;
const wl_buffer = context.get(wl_buffer_id) orelse return;
const buffer = @intToPtr(*Buffer, wl_buffer.container);
buffer.beginAccess();
if (window.texture) |texture| {
window.texture = null;
try renderer.releaseTexture(texture);
}
// We need to set pending here (rather than in ack_configure) because
// we need to know the width and height of the new buffer
if (compositor.COMPOSITOR.resize) |resize| {
if (resize.window == window) {
window.pending().x += resize.offsetX(window.width, buffer.width());
window.pending().y += resize.offsetY(window.height, buffer.height());
}
}
window.width = buffer.width();
window.height = buffer.height();
window.texture = try buffer.makeTexture();
try buffer.endAccess();
try prot.wl_buffer_send_release(wl_buffer);
window.wl_buffer_id = null;
if (window.view) |view| {
if (window.xdg_toplevel_id != null) {
if (window.toplevel.prev == null and window.toplevel.next == null) {
view.remove(window);
view.push(window);
}
}
}
}
fn set_buffer_scale(context: *Context, wl_surface: Object, scale: i32) anyerror!void {
var pending = @intToPtr(*Window, wl_surface.container).pending();
pending.scale = scale;
}
fn damage(context: *Context, wl_surface: Object, x: i32, y: i32, width: i32, height: i32) anyerror!void {
// std.debug.warn("damage does nothing\n", .{});
}
fn attach(context: *Context, wl_surface: Object, optional_wl_buffer: ?Object, x: i32, y: i32) anyerror!void {
var window = @intToPtr(*Window, wl_surface.container);
// window.pending = true;
if (optional_wl_buffer) |wl_buffer| {
window.wl_buffer_id = wl_buffer.id;
} else {
window.wl_buffer_id = null;
}
}
fn frame(context: *Context, wl_surface: Object, new_id: u32) anyerror!void {
var window = @intToPtr(*Window, wl_surface.container);
try window.callbacks.writeItem(new_id);
var callback = prot.new_wl_callback(new_id, context, 0);
try context.register(callback);
}
// TODO: Should we store a *Region instead of a wl_region id?
fn set_opaque_region(context: *Context, wl_surface: Object, optional_wl_region: ?Object) anyerror!void {
var window = @intToPtr(*Window, wl_surface.container);
if (optional_wl_region) |wl_region| {
var region = @intToPtr(*Region, wl_region.container);
region.window = window;
// If we set a second pending input region before the first pending input region has been
// flipped, we need to deinit the origin pending region
if (window.pending().opaque_region) |old_pending_region| {
if (old_pending_region != region and old_pending_region != window.current().opaque_region) {
try old_pending_region.deinit();
}
}
window.pending().opaque_region = region;
} else {
if (window.pending().opaque_region) |old_pending_region| {
if (old_pending_region != window.current().opaque_region) {
try old_pending_region.deinit();
}
}
window.pending().opaque_region = null;
}
}
// TODO: Should we store a *Region instead of a wl_region id?
fn set_input_region(context: *Context, wl_surface: Object, optional_wl_region: ?Object) anyerror!void {
var window = @intToPtr(*Window, wl_surface.container);
if (optional_wl_region) |wl_region| {
var region = @intToPtr(*Region, wl_region.container);
region.window = window;
// If we set a second pending input region before the first pending input region has been
// flipped, we need to deinit the original pending region
if (window.pending().input_region) |old_pending_region| {
if (old_pending_region != region and old_pending_region != window.current().input_region) {
try old_pending_region.deinit();
}
}
window.pending().input_region = region;
} else {
if (window.pending().input_region) |old_pending_region| {
if (old_pending_region != window.current().input_region) {
try old_pending_region.deinit();
}
}
window.pending().input_region = null;
}
}
fn destroy(context: *Context, wl_surface: Object) anyerror!void {
var window = @intToPtr(*Window, wl_surface.container);
// TODO: what about subsurfaces / popups?
try window.deinit();
try prot.wl_display_send_delete_id(context.client.wl_display, wl_surface.id);
try context.unregister(wl_surface);
}
pub fn init() void {
prot.WL_SURFACE = prot.wl_surface_interface{
.destroy = destroy,
.attach = attach,
.damage = damage,
.frame = frame,
.set_opaque_region = set_opaque_region,
.set_input_region = set_input_region,
.commit = commit,
.set_buffer_transform = set_buffer_transform,
.set_buffer_scale = set_buffer_scale,
.damage_buffer = damage_buffer,
};
}
fn set_buffer_transform(context: *Context, object: Object, transform: i32) anyerror!void {}
fn damage_buffer(context: *Context, object: Object, x: i32, y: i32, width: i32, height: i32) anyerror!void {}
|
src/implementations/wl_surface.zig
|
const graphics = @import("graphics.zig");
pub const Glyph = struct {
pub const Padding = 1;
// Glyph id used in the ttf file.
glyph_id: u16,
image: graphics.ImageTex,
// Top-left tex coords.
u0: f32,
v0: f32,
// Bot-right tex coords.
u1: f32,
v1: f32,
// for shaping, px amount from the current x,y pos to start drawing the glyph.
// x_offset includes left_side_bearing and glyph bitmap left padding.
// y_offset includes gap from font's max ascent to this glyph's ascent, and also the top bitmap padding.
// Scaled to screen coords for the font size this glyph was rendered to the bitmap.
x_offset: f32,
y_offset: f32,
// px pos and dim of glyph in bitmap.
x: u32,
y: u32,
width: u32,
height: u32,
// The dimensions we use when drawing with a quad.
// For outline glyphs this is simply the glyph width/height.
// For color glyphs this is scaled down from the glyph width/height to the bm font size.
dst_width: f32,
dst_height: f32,
// font size or px/em of the underlying bitmap data. Used to calculate scaling when rendering.
// A colored bitmap font could contain glyphs with different px/em, so this shouldn't be a shared value
// at the font level but rather on the per glyph level.
render_font_size: f32,
// for shaping, px amount this codepoint should occupy for this font_size.
advance_width: f32,
is_color_bitmap: bool,
pub fn init(glyph_id: u16, image: graphics.ImageTex) @This() {
return .{
.glyph_id = glyph_id,
.image = image,
.is_color_bitmap = false,
.u0 = 0,
.v0 = 0,
.u1 = 0,
.v1 = 0,
.x_offset = 0,
.y_offset = 0,
.render_font_size = 0,
.x = 0,
.y = 0,
.width = 0,
.height = 0,
.dst_width = 0,
.dst_height = 0,
.advance_width = 0,
};
}
};
|
graphics/src/backend/gpu/glyph.zig
|
const std = @import("std.zig");
const assert = std.debug.assert;
const expect = std.testing.expect;
const expectEqual = std.testing.expectEqual;
const mem = std.mem;
const math = std.math;
const ziggurat = @import("rand/ziggurat.zig");
const maxInt = std.math.maxInt;
/// Fast unbiased random numbers.
pub const DefaultPrng = Xoshiro256;
/// Cryptographically secure random numbers.
pub const DefaultCsprng = Gimli;
pub const Isaac64 = @import("rand/Isaac64.zig");
pub const Gimli = @import("rand/Gimli.zig");
pub const Pcg = @import("rand/Pcg.zig");
pub const Xoroshiro128 = @import("rand/Xoroshiro128.zig");
pub const Xoshiro256 = @import("rand/Xoshiro256.zig");
pub const Sfc64 = @import("rand/Sfc64.zig");
pub const Random = struct {
fillFn: fn (r: *Random, buf: []u8) void,
/// Read random bytes into the specified buffer until full.
pub fn bytes(r: *Random, buf: []u8) void {
r.fillFn(r, buf);
}
pub fn boolean(r: *Random) bool {
return r.int(u1) != 0;
}
/// Returns a random value from an enum, evenly distributed.
pub fn enumValue(r: *Random, comptime EnumType: type) EnumType {
if (comptime !std.meta.trait.is(.Enum)(EnumType)) {
@compileError("Random.enumValue requires an enum type, not a " ++ @typeName(EnumType));
}
// We won't use int -> enum casting because enum elements can have
// arbitrary values. Instead we'll randomly pick one of the type's values.
const values = std.enums.values(EnumType);
const index = r.uintLessThan(usize, values.len);
return values[index];
}
/// Returns a random int `i` such that `0 <= i <= maxInt(T)`.
/// `i` is evenly distributed.
pub fn int(r: *Random, comptime T: type) T {
const bits = @typeInfo(T).Int.bits;
const UnsignedT = std.meta.Int(.unsigned, bits);
const ByteAlignedT = std.meta.Int(.unsigned, @divTrunc(bits + 7, 8) * 8);
var rand_bytes: [@sizeOf(ByteAlignedT)]u8 = undefined;
r.bytes(rand_bytes[0..]);
// use LE instead of native endian for better portability maybe?
// TODO: endian portability is pointless if the underlying prng isn't endian portable.
// TODO: document the endian portability of this library.
const byte_aligned_result = mem.readIntSliceLittle(ByteAlignedT, &rand_bytes);
const unsigned_result = @truncate(UnsignedT, byte_aligned_result);
return @bitCast(T, unsigned_result);
}
/// Constant-time implementation off `uintLessThan`.
/// The results of this function may be biased.
pub fn uintLessThanBiased(r: *Random, comptime T: type, less_than: T) T {
comptime assert(@typeInfo(T).Int.signedness == .unsigned);
const bits = @typeInfo(T).Int.bits;
comptime assert(bits <= 64); // TODO: workaround: LLVM ERROR: Unsupported library call operation!
assert(0 < less_than);
if (bits <= 32) {
return @intCast(T, limitRangeBiased(u32, r.int(u32), less_than));
} else {
return @intCast(T, limitRangeBiased(u64, r.int(u64), less_than));
}
}
/// Returns an evenly distributed random unsigned integer `0 <= i < less_than`.
/// This function assumes that the underlying `fillFn` produces evenly distributed values.
/// Within this assumption, the runtime of this function is exponentially distributed.
/// If `fillFn` were backed by a true random generator,
/// the runtime of this function would technically be unbounded.
/// However, if `fillFn` is backed by any evenly distributed pseudo random number generator,
/// this function is guaranteed to return.
/// If you need deterministic runtime bounds, use `uintLessThanBiased`.
pub fn uintLessThan(r: *Random, comptime T: type, less_than: T) T {
comptime assert(@typeInfo(T).Int.signedness == .unsigned);
const bits = @typeInfo(T).Int.bits;
comptime assert(bits <= 64); // TODO: workaround: LLVM ERROR: Unsupported library call operation!
assert(0 < less_than);
// Small is typically u32
const small_bits = @divTrunc(bits + 31, 32) * 32;
const Small = std.meta.Int(.unsigned, small_bits);
// Large is typically u64
const Large = std.meta.Int(.unsigned, small_bits * 2);
// adapted from:
// http://www.pcg-random.org/posts/bounded-rands.html
// "Lemire's (with an extra tweak from me)"
var x: Small = r.int(Small);
var m: Large = @as(Large, x) * @as(Large, less_than);
var l: Small = @truncate(Small, m);
if (l < less_than) {
// TODO: workaround for https://github.com/ziglang/zig/issues/1770
// should be:
// var t: Small = -%less_than;
var t: Small = @bitCast(Small, -%@bitCast(std.meta.Int(.signed, small_bits), @as(Small, less_than)));
if (t >= less_than) {
t -= less_than;
if (t >= less_than) {
t %= less_than;
}
}
while (l < t) {
x = r.int(Small);
m = @as(Large, x) * @as(Large, less_than);
l = @truncate(Small, m);
}
}
return @intCast(T, m >> small_bits);
}
/// Constant-time implementation off `uintAtMost`.
/// The results of this function may be biased.
pub fn uintAtMostBiased(r: *Random, comptime T: type, at_most: T) T {
assert(@typeInfo(T).Int.signedness == .unsigned);
if (at_most == maxInt(T)) {
// have the full range
return r.int(T);
}
return r.uintLessThanBiased(T, at_most + 1);
}
/// Returns an evenly distributed random unsigned integer `0 <= i <= at_most`.
/// See `uintLessThan`, which this function uses in most cases,
/// for commentary on the runtime of this function.
pub fn uintAtMost(r: *Random, comptime T: type, at_most: T) T {
assert(@typeInfo(T).Int.signedness == .unsigned);
if (at_most == maxInt(T)) {
// have the full range
return r.int(T);
}
return r.uintLessThan(T, at_most + 1);
}
/// Constant-time implementation off `intRangeLessThan`.
/// The results of this function may be biased.
pub fn intRangeLessThanBiased(r: *Random, comptime T: type, at_least: T, less_than: T) T {
assert(at_least < less_than);
const info = @typeInfo(T).Int;
if (info.signedness == .signed) {
// Two's complement makes this math pretty easy.
const UnsignedT = std.meta.Int(.unsigned, info.bits);
const lo = @bitCast(UnsignedT, at_least);
const hi = @bitCast(UnsignedT, less_than);
const result = lo +% r.uintLessThanBiased(UnsignedT, hi -% lo);
return @bitCast(T, result);
} else {
// The signed implementation would work fine, but we can use stricter arithmetic operators here.
return at_least + r.uintLessThanBiased(T, less_than - at_least);
}
}
/// Returns an evenly distributed random integer `at_least <= i < less_than`.
/// See `uintLessThan`, which this function uses in most cases,
/// for commentary on the runtime of this function.
pub fn intRangeLessThan(r: *Random, comptime T: type, at_least: T, less_than: T) T {
assert(at_least < less_than);
const info = @typeInfo(T).Int;
if (info.signedness == .signed) {
// Two's complement makes this math pretty easy.
const UnsignedT = std.meta.Int(.unsigned, info.bits);
const lo = @bitCast(UnsignedT, at_least);
const hi = @bitCast(UnsignedT, less_than);
const result = lo +% r.uintLessThan(UnsignedT, hi -% lo);
return @bitCast(T, result);
} else {
// The signed implementation would work fine, but we can use stricter arithmetic operators here.
return at_least + r.uintLessThan(T, less_than - at_least);
}
}
/// Constant-time implementation off `intRangeAtMostBiased`.
/// The results of this function may be biased.
pub fn intRangeAtMostBiased(r: *Random, comptime T: type, at_least: T, at_most: T) T {
assert(at_least <= at_most);
const info = @typeInfo(T).Int;
if (info.signedness == .signed) {
// Two's complement makes this math pretty easy.
const UnsignedT = std.meta.Int(.unsigned, info.bits);
const lo = @bitCast(UnsignedT, at_least);
const hi = @bitCast(UnsignedT, at_most);
const result = lo +% r.uintAtMostBiased(UnsignedT, hi -% lo);
return @bitCast(T, result);
} else {
// The signed implementation would work fine, but we can use stricter arithmetic operators here.
return at_least + r.uintAtMostBiased(T, at_most - at_least);
}
}
/// Returns an evenly distributed random integer `at_least <= i <= at_most`.
/// See `uintLessThan`, which this function uses in most cases,
/// for commentary on the runtime of this function.
pub fn intRangeAtMost(r: *Random, comptime T: type, at_least: T, at_most: T) T {
assert(at_least <= at_most);
const info = @typeInfo(T).Int;
if (info.signedness == .signed) {
// Two's complement makes this math pretty easy.
const UnsignedT = std.meta.Int(.unsigned, info.bits);
const lo = @bitCast(UnsignedT, at_least);
const hi = @bitCast(UnsignedT, at_most);
const result = lo +% r.uintAtMost(UnsignedT, hi -% lo);
return @bitCast(T, result);
} else {
// The signed implementation would work fine, but we can use stricter arithmetic operators here.
return at_least + r.uintAtMost(T, at_most - at_least);
}
}
pub const scalar = @compileError("deprecated; use boolean() or int() instead");
pub const range = @compileError("deprecated; use intRangeLessThan()");
/// Return a floating point value evenly distributed in the range [0, 1).
pub fn float(r: *Random, comptime T: type) T {
// Generate a uniform value between [1, 2) and scale down to [0, 1).
// Note: The lowest mantissa bit is always set to 0 so we only use half the available range.
switch (T) {
f32 => {
const s = r.int(u32);
const repr = (0x7f << 23) | (s >> 9);
return @bitCast(f32, repr) - 1.0;
},
f64 => {
const s = r.int(u64);
const repr = (0x3ff << 52) | (s >> 12);
return @bitCast(f64, repr) - 1.0;
},
else => @compileError("unknown floating point type"),
}
}
/// Return a floating point value normally distributed with mean = 0, stddev = 1.
///
/// To use different parameters, use: floatNorm(...) * desiredStddev + desiredMean.
pub fn floatNorm(r: *Random, comptime T: type) T {
const value = ziggurat.next_f64(r, ziggurat.NormDist);
switch (T) {
f32 => return @floatCast(f32, value),
f64 => return value,
else => @compileError("unknown floating point type"),
}
}
/// Return an exponentially distributed float with a rate parameter of 1.
///
/// To use a different rate parameter, use: floatExp(...) / desiredRate.
pub fn floatExp(r: *Random, comptime T: type) T {
const value = ziggurat.next_f64(r, ziggurat.ExpDist);
switch (T) {
f32 => return @floatCast(f32, value),
f64 => return value,
else => @compileError("unknown floating point type"),
}
}
/// Shuffle a slice into a random order.
pub fn shuffle(r: *Random, comptime T: type, buf: []T) void {
if (buf.len < 2) {
return;
}
var i: usize = 0;
while (i < buf.len - 1) : (i += 1) {
const j = r.intRangeLessThan(usize, i, buf.len);
mem.swap(T, &buf[i], &buf[j]);
}
}
};
/// Convert a random integer 0 <= random_int <= maxValue(T),
/// into an integer 0 <= result < less_than.
/// This function introduces a minor bias.
pub fn limitRangeBiased(comptime T: type, random_int: T, less_than: T) T {
comptime assert(@typeInfo(T).Int.signedness == .unsigned);
const bits = @typeInfo(T).Int.bits;
const T2 = std.meta.Int(.unsigned, bits * 2);
// adapted from:
// http://www.pcg-random.org/posts/bounded-rands.html
// "Integer Multiplication (Biased)"
var m: T2 = @as(T2, random_int) * @as(T2, less_than);
return @intCast(T, m >> bits);
}
const SequentialPrng = struct {
const Self = @This();
random: Random,
next_value: u8,
pub fn init() Self {
return Self{
.random = Random{ .fillFn = fill },
.next_value = 0,
};
}
fn fill(r: *Random, buf: []u8) void {
const self = @fieldParentPtr(Self, "random", r);
for (buf) |*b| {
b.* = self.next_value;
}
self.next_value +%= 1;
}
};
test "Random int" {
try testRandomInt();
comptime try testRandomInt();
}
fn testRandomInt() !void {
var r = SequentialPrng.init();
try expect(r.random.int(u0) == 0);
r.next_value = 0;
try expect(r.random.int(u1) == 0);
try expect(r.random.int(u1) == 1);
try expect(r.random.int(u2) == 2);
try expect(r.random.int(u2) == 3);
try expect(r.random.int(u2) == 0);
r.next_value = 0xff;
try expect(r.random.int(u8) == 0xff);
r.next_value = 0x11;
try expect(r.random.int(u8) == 0x11);
r.next_value = 0xff;
try expect(r.random.int(u32) == 0xffffffff);
r.next_value = 0x11;
try expect(r.random.int(u32) == 0x11111111);
r.next_value = 0xff;
try expect(r.random.int(i32) == -1);
r.next_value = 0x11;
try expect(r.random.int(i32) == 0x11111111);
r.next_value = 0xff;
try expect(r.random.int(i8) == -1);
r.next_value = 0x11;
try expect(r.random.int(i8) == 0x11);
r.next_value = 0xff;
try expect(r.random.int(u33) == 0x1ffffffff);
r.next_value = 0xff;
try expect(r.random.int(i1) == -1);
r.next_value = 0xff;
try expect(r.random.int(i2) == -1);
r.next_value = 0xff;
try expect(r.random.int(i33) == -1);
}
test "Random boolean" {
try testRandomBoolean();
comptime try testRandomBoolean();
}
fn testRandomBoolean() !void {
var r = SequentialPrng.init();
try expect(r.random.boolean() == false);
try expect(r.random.boolean() == true);
try expect(r.random.boolean() == false);
try expect(r.random.boolean() == true);
}
test "Random enum" {
try testRandomEnumValue();
comptime try testRandomEnumValue();
}
fn testRandomEnumValue() !void {
const TestEnum = enum {
First,
Second,
Third,
};
var r = SequentialPrng.init();
r.next_value = 0;
try expect(r.random.enumValue(TestEnum) == TestEnum.First);
try expect(r.random.enumValue(TestEnum) == TestEnum.First);
try expect(r.random.enumValue(TestEnum) == TestEnum.First);
}
test "Random intLessThan" {
@setEvalBranchQuota(10000);
try testRandomIntLessThan();
comptime try testRandomIntLessThan();
}
fn testRandomIntLessThan() !void {
var r = SequentialPrng.init();
r.next_value = 0xff;
try expect(r.random.uintLessThan(u8, 4) == 3);
try expect(r.next_value == 0);
try expect(r.random.uintLessThan(u8, 4) == 0);
try expect(r.next_value == 1);
r.next_value = 0;
try expect(r.random.uintLessThan(u64, 32) == 0);
// trigger the bias rejection code path
r.next_value = 0;
try expect(r.random.uintLessThan(u8, 3) == 0);
// verify we incremented twice
try expect(r.next_value == 2);
r.next_value = 0xff;
try expect(r.random.intRangeLessThan(u8, 0, 0x80) == 0x7f);
r.next_value = 0xff;
try expect(r.random.intRangeLessThan(u8, 0x7f, 0xff) == 0xfe);
r.next_value = 0xff;
try expect(r.random.intRangeLessThan(i8, 0, 0x40) == 0x3f);
r.next_value = 0xff;
try expect(r.random.intRangeLessThan(i8, -0x40, 0x40) == 0x3f);
r.next_value = 0xff;
try expect(r.random.intRangeLessThan(i8, -0x80, 0) == -1);
r.next_value = 0xff;
try expect(r.random.intRangeLessThan(i3, -4, 0) == -1);
r.next_value = 0xff;
try expect(r.random.intRangeLessThan(i3, -2, 2) == 1);
}
test "Random intAtMost" {
@setEvalBranchQuota(10000);
try testRandomIntAtMost();
comptime try testRandomIntAtMost();
}
fn testRandomIntAtMost() !void {
var r = SequentialPrng.init();
r.next_value = 0xff;
try expect(r.random.uintAtMost(u8, 3) == 3);
try expect(r.next_value == 0);
try expect(r.random.uintAtMost(u8, 3) == 0);
// trigger the bias rejection code path
r.next_value = 0;
try expect(r.random.uintAtMost(u8, 2) == 0);
// verify we incremented twice
try expect(r.next_value == 2);
r.next_value = 0xff;
try expect(r.random.intRangeAtMost(u8, 0, 0x7f) == 0x7f);
r.next_value = 0xff;
try expect(r.random.intRangeAtMost(u8, 0x7f, 0xfe) == 0xfe);
r.next_value = 0xff;
try expect(r.random.intRangeAtMost(i8, 0, 0x3f) == 0x3f);
r.next_value = 0xff;
try expect(r.random.intRangeAtMost(i8, -0x40, 0x3f) == 0x3f);
r.next_value = 0xff;
try expect(r.random.intRangeAtMost(i8, -0x80, -1) == -1);
r.next_value = 0xff;
try expect(r.random.intRangeAtMost(i3, -4, -1) == -1);
r.next_value = 0xff;
try expect(r.random.intRangeAtMost(i3, -2, 1) == 1);
try expect(r.random.uintAtMost(u0, 0) == 0);
}
test "Random Biased" {
var r = DefaultPrng.init(0);
// Not thoroughly checking the logic here.
// Just want to execute all the paths with different types.
try expect(r.random.uintLessThanBiased(u1, 1) == 0);
try expect(r.random.uintLessThanBiased(u32, 10) < 10);
try expect(r.random.uintLessThanBiased(u64, 20) < 20);
try expect(r.random.uintAtMostBiased(u0, 0) == 0);
try expect(r.random.uintAtMostBiased(u1, 0) <= 0);
try expect(r.random.uintAtMostBiased(u32, 10) <= 10);
try expect(r.random.uintAtMostBiased(u64, 20) <= 20);
try expect(r.random.intRangeLessThanBiased(u1, 0, 1) == 0);
try expect(r.random.intRangeLessThanBiased(i1, -1, 0) == -1);
try expect(r.random.intRangeLessThanBiased(u32, 10, 20) >= 10);
try expect(r.random.intRangeLessThanBiased(i32, 10, 20) >= 10);
try expect(r.random.intRangeLessThanBiased(u64, 20, 40) >= 20);
try expect(r.random.intRangeLessThanBiased(i64, 20, 40) >= 20);
// uncomment for broken module error:
//expect(r.random.intRangeAtMostBiased(u0, 0, 0) == 0);
try expect(r.random.intRangeAtMostBiased(u1, 0, 1) >= 0);
try expect(r.random.intRangeAtMostBiased(i1, -1, 0) >= -1);
try expect(r.random.intRangeAtMostBiased(u32, 10, 20) >= 10);
try expect(r.random.intRangeAtMostBiased(i32, 10, 20) >= 10);
try expect(r.random.intRangeAtMostBiased(u64, 20, 40) >= 20);
try expect(r.random.intRangeAtMostBiased(i64, 20, 40) >= 20);
}
// Generator to extend 64-bit seed values into longer sequences.
//
// The number of cycles is thus limited to 64-bits regardless of the engine, but this
// is still plenty for practical purposes.
pub const SplitMix64 = struct {
s: u64,
pub fn init(seed: u64) SplitMix64 {
return SplitMix64{ .s = seed };
}
pub fn next(self: *SplitMix64) u64 {
self.s +%= 0x9e3779b97f4a7c15;
var z = self.s;
z = (z ^ (z >> 30)) *% 0xbf58476d1ce4e5b9;
z = (z ^ (z >> 27)) *% 0x94d049bb133111eb;
return z ^ (z >> 31);
}
};
test "splitmix64 sequence" {
var r = SplitMix64.init(0xaeecf86f7878dd75);
const seq = [_]u64{
0x5dbd39db0178eb44,
0xa9900fb66b397da3,
0x5c1a28b1aeebcf5c,
0x64a963238f776912,
0xc6d4177b21d1c0ab,
0xb2cbdbdb5ea35394,
};
for (seq) |s| {
try expect(s == r.next());
}
}
// Actual Random helper function tests, pcg engine is assumed correct.
test "Random float" {
var prng = DefaultPrng.init(0);
var i: usize = 0;
while (i < 1000) : (i += 1) {
const val1 = prng.random.float(f32);
try expect(val1 >= 0.0);
try expect(val1 < 1.0);
const val2 = prng.random.float(f64);
try expect(val2 >= 0.0);
try expect(val2 < 1.0);
}
}
test "Random shuffle" {
var prng = DefaultPrng.init(0);
var seq = [_]u8{ 0, 1, 2, 3, 4 };
var seen = [_]bool{false} ** 5;
var i: usize = 0;
while (i < 1000) : (i += 1) {
prng.random.shuffle(u8, seq[0..]);
seen[seq[0]] = true;
try expect(sumArray(seq[0..]) == 10);
}
// we should see every entry at the head at least once
for (seen) |e| {
try expect(e == true);
}
}
fn sumArray(s: []const u8) u32 {
var r: u32 = 0;
for (s) |e|
r += e;
return r;
}
test "Random range" {
var prng = DefaultPrng.init(0);
try testRange(&prng.random, -4, 3);
try testRange(&prng.random, -4, -1);
try testRange(&prng.random, 10, 14);
try testRange(&prng.random, -0x80, 0x7f);
}
fn testRange(r: *Random, start: i8, end: i8) !void {
try testRangeBias(r, start, end, true);
try testRangeBias(r, start, end, false);
}
fn testRangeBias(r: *Random, start: i8, end: i8, biased: bool) !void {
const count = @intCast(usize, @as(i32, end) - @as(i32, start));
var values_buffer = [_]bool{false} ** 0x100;
const values = values_buffer[0..count];
var i: usize = 0;
while (i < count) {
const value: i32 = if (biased) r.intRangeLessThanBiased(i8, start, end) else r.intRangeLessThan(i8, start, end);
const index = @intCast(usize, value - start);
if (!values[index]) {
i += 1;
values[index] = true;
}
}
}
test "CSPRNG" {
var secret_seed: [DefaultCsprng.secret_seed_length]u8 = undefined;
std.crypto.random.bytes(&secret_seed);
var csprng = DefaultCsprng.init(secret_seed);
const a = csprng.random.int(u64);
const b = csprng.random.int(u64);
const c = csprng.random.int(u64);
try expect(a ^ b ^ c != 0);
}
test {
std.testing.refAllDecls(@This());
}
|
lib/std/rand.zig
|
const index = @import("index.zig");
const std = @import("std");
const mem = std.mem;
const math = std.math;
pub const Fs = struct {
const Lookup = std.AutoHashMap([]const u8, usize);
const Files = std.SegmentedList(FileData, 16);
const FileData = std.ArrayList(u8);
allocator: *mem.Allocator,
files: Files,
lookup: Lookup,
pub fn init(allocator: *mem.Allocator) Fs {
return Fs{
.allocator = allocator,
.files = Files.init(allocator),
.lookup = Lookup.init(allocator),
};
}
pub fn deinit(fs: *Fs) void {
var iter = fs.files.iterator(0);
while (iter.next()) |data|
data.deinit();
var iter2 = fs.lookup.iterator();
while (iter2.next()) |kv|
fs.allocator.free(kv.key);
fs.files.deinit();
fs.lookup.deinit();
}
// TODO: Normalize path
pub fn open(fs: *Fs, path: []const u8, flags: index.Open.Flags) !File {
const data = if (fs.lookup.get(path)) |kv|
fs.files.at(kv.value)
else blk: {
if ((flags & index.Open.Create) == 0)
return error.NoFile;
const i = fs.files.count();
const path_copy = try mem.dupe(fs.allocator, u8, path);
errdefer fs.allocator.free(path_copy);
const res = try fs.files.addOne();
res.* = FileData.init(fs.allocator);
errdefer _ = fs.files.pop();
_ = try fs.lookup.put(path_copy, i);
break :blk res;
};
if ((flags & index.Open.Truncate) != 0)
try data.resize(0);
return File{
.data = data,
.flags = flags,
.pos_ = 0,
};
}
pub fn close(fs: *Fs, file: *File) void {
file.* = undefined;
}
};
pub const File = struct {
data: *Fs.FileData,
flags: index.Open.Flags,
pos_: usize,
pub fn read(file: *File, buf: []u8) ![]u8 {
if ((file.flags & index.Open.Read) == 0)
return error.FileCannotBeRead;
const start = math.min(file.pos_, file.data.len);
const len = math.min(buf.len, file.data.len - file.pos_);
mem.copy(u8, buf[0..len], file.data.toSlice()[start..][0..len]);
file.pos_ += len;
return buf[0..len];
}
pub fn write(file: *File, buf: []const u8) !void {
if ((file.flags & index.Open.Write) == 0)
return error.FileCannotBeWritten;
if (file.data.len < file.pos_ + buf.len) {
const len = file.data.len;
try file.data.resize(file.pos_ + buf.len);
mem.set(u8, file.data.toSlice()[len..], 0);
}
mem.copy(u8, file.data.toSlice()[file.pos_..], buf);
file.pos_ += buf.len;
}
pub fn seek(file: *File, p: u64) !void {
file.pos_ = try math.cast(usize, p);
}
pub fn pos(file: *File) error{}!u64 {
return u64(file.pos_);
}
pub fn size(file: *File) error{}!u64 {
return u64(file.data.len);
}
};
|
src/mem.zig
|
const root = @import("root");
const std = @import("std");
const builtin = @import("builtin");
const assert = std.debug.assert;
var argc_ptr: [*]usize = undefined;
const is_wasm = switch (builtin.arch) {
.wasm32, .wasm64 => true,
else => false,
};
comptime {
if (builtin.link_libc) {
@export("main", main, .Strong);
} else if (builtin.os == .windows) {
@export("WinMainCRTStartup", WinMainCRTStartup, .Strong);
} else if (is_wasm and builtin.os == .freestanding) {
@export("_start", wasm_freestanding_start, .Strong);
} else {
@export("_start", _start, .Strong);
}
}
fn enableSegfaultHandler() void {
const enable_segfault_handler: bool = if (@hasDecl(root, "enable_segfault_handler"))
root.enable_segfault_handler
else
std.debug.runtime_safety and std.debug.have_segfault_handling_support;
if (enable_segfault_handler) {
std.debug.attachSegfaultHandler();
}
}
extern fn wasm_freestanding_start() void {
_ = callMain();
}
nakedcc fn _start() noreturn {
if (builtin.os == builtin.Os.wasi) {
std.os.wasi.proc_exit(callMain());
}
switch (builtin.arch) {
.x86_64 => {
argc_ptr = asm ("lea (%%rsp), %[argc]"
: [argc] "=r" (-> [*]usize)
);
},
.i386 => {
argc_ptr = asm ("lea (%%esp), %[argc]"
: [argc] "=r" (-> [*]usize)
);
},
.aarch64, .aarch64_be => {
argc_ptr = asm ("mov %[argc], sp"
: [argc] "=r" (-> [*]usize)
);
},
else => @compileError("unsupported arch"),
}
// If LLVM inlines stack variables into _start, they will overwrite
// the command line argument data.
@noInlineCall(posixCallMainAndExit);
}
extern fn WinMainCRTStartup() noreturn {
@setAlignStack(16);
if (!builtin.single_threaded) {
_ = @import("start_windows_tls.zig");
}
enableSegfaultHandler();
std.os.windows.kernel32.ExitProcess(callMain());
}
// TODO https://github.com/ziglang/zig/issues/265
fn posixCallMainAndExit() noreturn {
if (builtin.os == builtin.Os.freebsd) {
@setAlignStack(16);
}
const argc = argc_ptr[0];
const argv = @ptrCast([*][*]u8, argc_ptr + 1);
const envp_optional = @ptrCast([*]?[*]u8, argv + argc + 1);
var envp_count: usize = 0;
while (envp_optional[envp_count]) |_| : (envp_count += 1) {}
const envp = @ptrCast([*][*]u8, envp_optional)[0..envp_count];
if (builtin.os == .linux) {
// Find the beginning of the auxiliary vector
const auxv = @ptrCast([*]std.elf.Auxv, envp.ptr + envp_count + 1);
std.os.linux.elf_aux_maybe = auxv;
// Initialize the TLS area
std.os.linux.tls.initTLS();
if (std.os.linux.tls.tls_image) |tls_img| {
const tls_addr = std.os.linux.tls.allocateTLS(tls_img.alloc_size);
const tp = std.os.linux.tls.copyTLS(tls_addr);
std.os.linux.tls.setThreadPointer(tp);
}
}
std.os.exit(callMainWithArgs(argc, argv, envp));
}
// This is marked inline because for some reason LLVM in release mode fails to inline it,
// and we want fewer call frames in stack traces.
inline fn callMainWithArgs(argc: usize, argv: [*][*]u8, envp: [][*]u8) u8 {
std.os.argv = argv[0..argc];
std.os.environ = envp;
enableSegfaultHandler();
return callMain();
}
extern fn main(c_argc: i32, c_argv: [*][*]u8, c_envp: [*]?[*]u8) i32 {
var env_count: usize = 0;
while (c_envp[env_count] != null) : (env_count += 1) {}
const envp = @ptrCast([*][*]u8, c_envp)[0..env_count];
return callMainWithArgs(@intCast(usize, c_argc), c_argv, envp);
}
// This is marked inline because for some reason LLVM in release mode fails to inline it,
// and we want fewer call frames in stack traces.
inline fn callMain() u8 {
switch (@typeId(@typeOf(root.main).ReturnType)) {
.NoReturn => {
root.main();
},
.Void => {
root.main();
return 0;
},
.Int => {
if (@typeOf(root.main).ReturnType.bit_count != 8) {
@compileError("expected return type of main to be 'u8', 'noreturn', 'void', or '!void'");
}
return root.main();
},
.ErrorUnion => {
root.main() catch |err| {
std.debug.warn("error: {}\n", @errorName(err));
if (builtin.os != builtin.Os.zen) {
if (@errorReturnTrace()) |trace| {
std.debug.dumpStackTrace(trace.*);
}
}
return 1;
};
return 0;
},
else => @compileError("expected return type of main to be 'u8', 'noreturn', 'void', or '!void'"),
}
}
const main_thread_tls_align = 32;
var main_thread_tls_bytes: [64]u8 align(main_thread_tls_align) = [1]u8{0} ** 64;
|
std/special/start.zig
|
const std = @import("std");
const ConstantOrBuffer = @import("trigger.zig").ConstantOrBuffer;
const Span = @import("basics.zig").Span;
inline fn sin(t: f32) f32 {
return std.math.sin(t * std.math.pi * 2.0);
}
pub const SineOsc = struct {
pub const num_outputs = 1;
pub const num_temps = 0;
pub const Params = struct {
sample_rate: f32,
freq: ConstantOrBuffer,
phase: ConstantOrBuffer,
};
t: f32,
pub fn init() SineOsc {
return .{
.t = 0.0,
};
}
pub fn paint(
self: *SineOsc,
span: Span,
outputs: [num_outputs][]f32,
temps: [num_temps][]f32,
note_id_changed: bool,
params: Params,
) void {
const output = outputs[0][span.start..span.end];
var i: usize = 0;
var t = self.t;
// it actually goes out of tune without this!...
defer self.t = t - std.math.trunc(t);
switch (params.freq) {
.constant => |freq| {
const t_step = freq / params.sample_rate;
switch (params.phase) {
.constant => |phase| {
// constant frequency, constant phase
while (i < output.len) : (i += 1) {
output[i] += sin(t + phase);
t += t_step;
}
},
.buffer => |phase| {
// constant frequency, controlled phase
const phase_slice = phase[span.start..span.end];
while (i < output.len) : (i += 1) {
output[i] += sin(t + phase_slice[i]);
t += t_step;
}
},
}
},
.buffer => |freq| {
const freq_slice = freq[span.start..span.end];
const inv_sample_rate = 1.0 / params.sample_rate;
switch (params.phase) {
.constant => |phase| {
// controlled frequency, constant phase
while (i < output.len) : (i += 1) {
output[i] += sin(t + phase);
t += freq_slice[i] * inv_sample_rate;
}
},
.buffer => |phase| {
// controlled frequency, controlled phase
const phase_slice = phase[span.start..span.end];
while (i < output.len) : (i += 1) {
output[i] += sin(t + phase_slice[i]);
t += freq_slice[i] * inv_sample_rate;
}
},
}
},
}
}
};
|
src/zang/mod_sineosc.zig
|
const expect = @import("std").testing.expect;
test "if statement" {
const a = true;
var x: u16 = 0;
if (a) {
x += 1;
} else {
x += 2;
}
expect(x == 1);
}
test "if statement expression" {
const a = true;
var x: u16 = 0;
x += if (a) 1 else 2;
expect(x == 1);
}
test "while" {
var i: u8 = 2;
while (i < 100) {
i *= 2;
}
expect(i == 128);
}
test "while with continue expression" {
var sum: u8 = 0;
var i: u8 = 1;
while (i <= 10) : (i += 1) {
sum += i;
}
expect(sum == 55);
}
test "while with continue" {
var sum: u8 = 0;
var i: u8 = 0;
while (i <= 3) : (i += 1) {
if (i == 2) continue;
sum += i;
}
expect(sum == 4);
}
test "while with break" {
var sum: u8 = 0;
var i: u8 = 0;
while (i <= 3) : (i += 1) {
if (i == 2) break;
sum += i;
}
expect(sum == 1);
}
test "for" {
//character literals are equivalent to integer literals
const string = [_]u8{ 'a', 'b', 'c' };
for (string) |character, index| {}
for (string) |character| {}
for (string) |_, index| {}
for (string) |_| {}
}
fn addFive(x: u32) u32 {
return x + 5;
}
test "function" {
const y = addFive(0);
expect(@TypeOf(y) == u32);
expect(y == 5);
}
fn fibonacci(n: u16) u16 {
if (n == 0 or n == 1) return n;
return fibonacci(n - 1) + fibonacci(n - 2);
}
test "function recursion" {
const x = fibonacci(10);
expect(x == 55);
}
test "defer" {
var x: i16 = 5;
{
defer x += 2;
expect(x == 5);
}
expect(x == 7);
}
test "multi defer" {
var x: f32 = 5;
{
defer x += 2;
defer x /= 2;
}
expect(x == 4.5);
}
const FileOpenError = error{
AccessDenied,
OutOfMemory,
FileNotFound,
};
const AllocationError = error{OutOfMemory};
test "coerce error from a subset to a superset" {
const err: FileOpenError = AllocationError.OutOfMemory;
expect(err == FileOpenError.OutOfMemory);
}
test "error union" {
const maybe_error: AllocationError!u16 = 10;
const no_error = maybe_error catch 0;
expect(@TypeOf(no_error) == u16);
expect(no_error == 10);
}
fn failingFunction() error{Oops}!void {
return error.Oops;
}
test "returning an error" {
failingFunction() catch |err| {
expect(err == error.Oops);
return;
};
}
fn failFn() error{Oops}!i32 {
try failingFunction();
return 12;
}
test "try" {
var v = failFn() catch |err| {
expect(err == error.Oops);
return;
};
expect(v == 12); // is never reached
}
var problems: u32 = 98;
fn failFnCounter() error{Oops}!void {
errdefer problems += 1;
try failingFunction();
}
test "errdefer" {
failFnCounter() catch |err| {
expect(err == error.Oops);
expect(problems == 99);
return;
};
}
fn createFile() !void {
return error.AccessDenied;
}
test "inferred error set" {
//type coercion successfully takes place
const x: error{AccessDenied}!void = createFile();
}
test "switch statement" {
var x: i8 = 10;
switch (x) {
-1...1 => {
x = -x;
},
10, 100 => {
//special considerations must be made
//when dividing signed integers
x = @divExact(x, 10);
},
else => {},
}
expect(x == 1);
}
test "switch expression" {
var x: i8 = 10;
x = switch (x) {
-1...1 => -x,
10, 100 => @divExact(x, 10),
else => x,
};
expect(x == 1);
}
test "out of bounds, no safety" {
@setRuntimeSafety(false);
const a = [3]u8{ 1, 2, 3 };
var index: u8 = 5;
const b = a[index];
}
fn asciiToUpper(x: u8) u8 {
return switch (x) {
'a'...'z' => x + 'A' - 'a',
'A'...'Z' => x,
else => unreachable,
};
}
test "unreachable switch" {
expect(asciiToUpper('a') == 'A');
expect(asciiToUpper('A') == 'A');
}
fn increment(num: *u8) void {
num.* += 1;
}
test "pointers" {
var x: u8 = 1;
increment(&x);
expect(x == 2);
}
test "usize" {
expect(@sizeOf(usize) == @sizeOf(*u8));
expect(@sizeOf(isize) == @sizeOf(*u8));
}
fn total(values: []const u8) usize {
var count: usize = 0;
for (values) |v| count += v;
return count;
}
test "slices" {
const array = [_]u8{ 1, 2, 3, 4, 5 };
const slice = array[0..3];
expect(total(slice) == 6);
}
test "slices 2" {
const array = [_]u8{ 1, 2, 3, 4, 5 };
const slice = array[0..3];
expect(@TypeOf(slice) == *const [3]u8);
}
test "slices 3" {
var array = [_]u8{ 1, 2, 3, 4, 5 };
var slice = array[0..];
}
const Value = enum(u2) { Zero, One, Two };
test "enum ordinal value" {
expect(@enumToInt(Value.Zero) == 0);
expect(@enumToInt(Value.One) == 1);
expect(@enumToInt(Value.Two) == 2);
}
const Value2 = enum(u32) {
Hundred = 100,
Thousand = 1000,
Million = 1000000,
Next,
};
test "set enum ordinal value" {
expect(@enumToInt(Value2.Hundred) == 100);
expect(@enumToInt(Value2.Thousand) == 1000);
expect(@enumToInt(Value2.Million) == 1000000);
expect(@enumToInt(Value2.Next) == 1000001);
}
const Suit = enum {
clubs,
spades,
diamonds,
hearts,
pub fn isClubs(self: Suit) bool {
return self == Suit.clubs;
}
};
test "enum method" {
expect(Suit.spades.isClubs() == Suit.isClubs(.spades));
}
const Mode = enum {
var count: u32 = 0;
on,
off,
};
test "hmm" {
Mode.count += 1;
expect(Mode.count == 1);
}
const Vec3 = struct {
x: f32, y: f32, z: f32
};
test "struct usage" {
const my_vector = Vec3{
.x = 0,
.y = 100,
.z = 50,
};
}
const Vec4 = struct {
x: f32, y: f32, z: f32 = 0, w: f32 = undefined
};
test "struct defaults" {
const my_vector = Vec4{
.x = 25,
.y = -50,
};
}
const Stuff = struct {
x: i32,
y: i32,
fn swap(self: *Stuff) void {
const tmp = self.x;
self.x = self.y;
self.y = tmp;
}
};
test "automatic dereference" {
var thing = Stuff{ .x = 10, .y = 20 };
thing.swap();
expect(thing.x == 20);
expect(thing.y == 10);
}
const Tag = enum { a, b, c };
const Tagged = union(Tag) { a: u8, b: f32, c: bool };
test "switch on tagged union" {
var value = Tagged{ .b = 1.5 };
switch (value) {
.a => |*byte| byte.* += 1,
.b => |*float| float.* *= 2,
.c => |*b| b.* = !b.*,
}
expect(value.b == 3);
}
test "integer widening" {
const a: u8 = 250;
const b: u16 = a;
const c: u32 = b;
expect(c == a);
}
test "@intCast" {
const x: u64 = 200;
const y = @intCast(u8, x);
expect(@TypeOf(y) == u8);
}
test "well defined overflow" {
var a: u8 = 255;
a +%= 1;
expect(a == 0);
}
test "float coercion" {
const a: f16 = 0;
const b: f32 = a;
const c: f128 = b;
expect(c == a);
}
test "int-float conversion" {
const a: i32 = 0;
const b = @intToFloat(f32, a);
const c = @floatToInt(i32, b);
expect(c == a);
}
test "labelled blocks" {
const count = blk: {
var sum: u32 = 0;
var i: u32 = 0;
while (i < 10) : (i += 1) sum += i;
break :blk sum;
};
expect(count == 45);
expect(@TypeOf(count) == u32);
}
test "nested continue" {
var count: usize = 0;
outer: for ([_]i32{ 1, 2, 3, 4, 5, 6, 7, 8 }) |_| {
for ([_]i32{ 1, 2, 3, 4, 5 }) |_| {
count += 1;
continue :outer;
}
}
expect(count == 8);
}
fn rangeHasNumber(begin: usize, end: usize, number: usize) bool {
var i = begin;
return while (i < end) : (i += 1) {
if (i == number) {
break true;
}
} else false;
}
test "while loop expression" {
expect(rangeHasNumber(0, 10, 3));
}
test "optional" {
var found_index: ?usize = null;
const data = [_]i32{ 1, 2, 3, 4, 5, 6, 7, 8, 12 };
for (data) |v, i| {
if (v == 10) found_index = i;
}
expect(found_index == null);
}
test "orelse" {
var a: ?f32 = null;
var b = a orelse 0;
expect(b == 0);
expect(@TypeOf(b) == f32);
}
test "orelse unreachable" {
const a: ?f32 = 5;
const b = a orelse unreachable;
const c = a.?;
expect(b == c);
expect(@TypeOf(c) == f32);
}
test "if optional payload capture" {
const a: ?i32 = 5;
if (a != null) {
const value = a.?;
}
const b: ?i32 = 5;
if (b) |value| {}
}
var numbers_left: u32 = 4;
fn eventuallyNullSequence() ?u32 {
if (numbers_left == 0) return null;
numbers_left -= 1;
return numbers_left;
}
test "while null capture" {
var sum: u32 = 0;
while (eventuallyNullSequence()) |value| {
sum += value;
}
expect(sum == 6); // 3 + 2 + 1
}
test "comptime blocks" {
var x = comptime fibonacci(10);
var y = comptime blk: {
break :blk fibonacci(10);
};
}
test "comptime_int" {
const a = 12;
const b = a + 10;
const c: u4 = a;
const d: f32 = b;
}
test "branching on types" {
const a = 5;
const b: if (a < 10) f32 else i32 = 5;
}
fn Matrix(
comptime T: type,
comptime width: comptime_int,
comptime height: comptime_int,
) type {
return [height][width]T;
}
test "returning a type" {
expect(Matrix(f32, 4, 4) == [4][4]f32);
}
fn addSmallInts(comptime T: type, a: T, b: T) T {
return switch (@typeInfo(T)) {
.ComptimeInt => a + b,
.Int => |info| if (info.bits <= 16)
a + b
else
@compileError("ints too large"),
else => @compileError("only ints accepted"),
};
}
test "typeinfo switch" {
const x = addSmallInts(u16, 20, 30);
expect(@TypeOf(x) == u16);
expect(x == 50);
}
fn getBiggerInt(comptime T: type) type {
return @Type(.{
.Int = .{
.bits = @typeInfo(T).Int.bits + 1,
.is_signed = @typeInfo(T).Int.is_signed,
},
});
}
test "@Type" {
expect(getBiggerInt(u8) == u9);
expect(getBiggerInt(i31) == i32);
}
fn Vec(
comptime count: comptime_int,
comptime T: type,
) type {
return struct {
data: [count]T,
const Self = @This();
fn abs(self: Self) Self {
var tmp = Self{ .data = undefined };
for (self.data) |elem, i| {
tmp.data[i] = if (elem < 0)
-elem
else
elem;
}
return tmp;
}
fn init(data: [count]T) Self {
return Self{ .data = data };
}
};
}
const eql = @import("std").mem.eql;
test "generic vector" {
const x = Vec(3, f32).init([_]f32{ 10, -10, 5 });
const y = x.abs();
expect(eql(f32, &y.data, &[_]f32{ 10, 10, 5 }));
}
fn plusOne(x: anytype) @TypeOf(x) {
return x + 1;
}
test "inferred function parameter" {
expect(plusOne(@as(u32, 1)) == 2);
}
test "++" {
const x: [4]u8 = undefined;
const y = x[0..];
const a: [6]u8 = undefined;
const b = a[0..];
const new = y ++ b;
expect(new.len == 10);
}
test "**" {
const pattern = [_]u8{ 0xCC, 0xAA };
const memory = pattern ** 3;
expect(eql(u8, &memory, &[_]u8{ 0xCC, 0xAA, 0xCC, 0xAA, 0xCC, 0xAA }));
}
test "inline for" {
const types = [_]type{ i32, f32, u8, bool };
var sum: usize = 0;
inline for (types) |T| sum += @sizeOf(T);
expect(sum == 10);
}
test "anonymous struct literal" {
const Point = struct { x: i32, y: i32 };
var pt: Point = .{
.x = 13,
.y = 67,
};
expect(pt.x == 13);
expect(pt.y == 67);
}
test "fully anonymous struct" {
dump(.{
.int = @as(u32, 1234),
.float = @as(f64, 12.34),
.b = true,
.s = "hi",
});
}
fn dump(args: anytype) void {
expect(args.int == 1234);
expect(args.float == 12.34);
expect(args.b);
expect(args.s[0] == 'h');
expect(args.s[1] == 'i');
}
test "tuple" {
const values = .{
@as(u32, 1234),
@as(f64, 12.34),
true,
"hi",
} ++ .{false} ** 2;
expect(values[0] == 1234);
expect(values[4] == false);
inline for (values) |v, i| {
if (i != 2) continue;
expect(v);
}
expect(values.len == 6);
expect(values.@"3"[0] == 'h');
}
test "sentinel termination" {
const terminated = [3:0]u8{ 3, 2, 1 };
expect(terminated.len == 3);
expect(@bitCast([4]u8, terminated)[3] == 0);
}
test "string literal" {
expect(@TypeOf("hello") == *const [5:0]u8);
}
test "C string" {
const c_string: [*:0]const u8 = "hello";
var array: [5]u8 = undefined;
var i: usize = 0;
while (c_string[i] != 0) : (i += 1) {
array[i] = c_string[i];
}
}
test "coercion" {
var a: [*:0]u8 = undefined;
const b: [*]u8 = a;
var c: [5:0]u8 = undefined;
const d: [5]u8 = c;
var e: [:10]f32 = undefined;
const f = e;
}
test "sentinel terminated slicing" {
var x = [_:0]u8{255} ** 3;
const y = x[0..3 :0];
}
const meta = @import("std").meta;
const Vector = meta.Vector;
test "vector add" {
const x: Vector(4, f32) = .{ 1, -10, 20, -1 };
const y: Vector(4, f32) = .{ 2, 10, 0, 1 };
const z = x + y;
expect(meta.eql(z, Vector(4, f32){ 3, 0, 20, 0 }));
}
test "vector indexing" {
const x: Vector(4, u8) = .{ 255, 0, 255, 0 };
expect(x[0] == 255);
}
test "vector * scalar" {
const x: Vector(3, f32) = .{ 12.5, 37.5, 2.5 };
const y = x * @splat(3, @as(f32, 2));
expect(meta.eql(y, Vector(3, f32){ 25, 75, 5 }));
}
const len = @import("std").mem.len;
test "vector looping" {
const x = Vector(4, u8){ 255, 0, 255, 0 };
var sum = blk: {
var tmp: u10 = 0;
var i: u8 = 0;
while (i < len(x)) : (i += 1) tmp += x[i];
break :blk tmp;
};
expect(sum == 510);
}
const arr: [4]f32 = @Vector(4, f32){ 1, 2, 3, 4 };
|
chapter-1-passing-tests.zig
|
const std = @import("std");
const mem = std.mem;
const assert = std.debug.assert;
const ArenaAllocator = std.heap.ArenaAllocator;
const Allocator = std.mem.Allocator;
const StringHashMap = std.hash_map.StringHashMap;
const fmt = std.fmt;
const builtin = @import("builtin");
const routez = @import("routez");
const RoutezServer = routez.Server;
const Request = routez.Request;
const Response = routez.Response;
const print = std.debug.print;
const global_allocator = std.heap.page_allocator;
const Address = std.net.Address;
const Storage = @import("feed_db.zig").Storage;
const ArrayList = std.ArrayList;
const Datetime = @import("datetime").datetime.Datetime;
const url_util = @import("url.zig");
const http = @import("http.zig");
const parse = @import("parse.zig");
const zuri = @import("zuri");
const log = std.log;
// Resources
// POST-REDIRECT-GET | https://andrewlock.net/post-redirect-get-using-tempdata-in-asp-net-core/
// Generating session ids | https://codeahoy.com/2016/04/13/generating-session-ids/
// https://cheatsheetseries.owasp.org/cheatsheets/Session_Management_Cheat_Sheet.html#references
// pub const io_mode = .evented;
// TODO: how to handle displaying untagged feeds?
const timestamp_fmt = "{d}.{d:0>2}.{d:0>2} {d:0>2}:{d:0>2}:{d:0>2} UTC";
const FormData = union(enum) {
success: []u64, // ids
html: struct {
ty: enum { view, no_pick } = .view,
url: []const u8,
tags: []const u8,
page: parse.Html.Page,
},
fail: struct {
url: []const u8 = "",
// tags?
ty: enum { empty_url, invalid_url, invalid_form, http_not_modified, http_fail, unknown } = .unknown,
msg: []const u8 = "Unknown problem occured. Try again.",
},
};
const Session = struct {
id: u64,
arena: std.heap.ArenaAllocator,
form_data: FormData,
pub fn deinit(self: *@This()) void {
self.arena.deinit();
}
};
const Sessions = struct {
const Self = @This();
allocator: Allocator,
list: ArrayList(Session),
random: std.rand.Random,
pub fn init(allocator: Allocator) Self {
var secret_seed: [std.rand.DefaultCsprng.secret_seed_length]u8 = undefined;
std.crypto.random.bytes(&secret_seed);
var csprng = std.rand.DefaultCsprng.init(secret_seed);
const random = csprng.random();
return .{
.allocator = allocator,
.list = ArrayList(Session).init(allocator),
.random = random,
};
}
pub fn new(self: *Self, arena: ArenaAllocator) !*Session {
var result = try self.list.addOne();
result.* = Session{
.id = self.random.int(u64),
.arena = arena,
.form_data = .{ .fail = .{} },
};
return result;
}
pub fn getIndex(self: *Self, token: u64) ?u64 {
for (self.list.items) |s, i| {
if (s.id == token) return i;
}
return null;
}
pub fn deinit(self: *Self) void {
for (self.list.items) |*session| {
session.deinit();
}
self.list.deinit();
}
};
const Server = struct {
const g = struct {
var storage: *Storage = undefined;
var sessions: *Sessions = undefined;
};
const Self = @This();
server: RoutezServer,
pub fn init(storage: *Storage, sessions: *Sessions) Self {
g.storage = storage;
g.sessions = sessions;
var server = RoutezServer.init(
global_allocator,
.{},
.{
routez.all("/", indexHandler),
routez.all("/tag/{tags}", tagHandler),
routez.all("/feed/add", feedAddHandler),
},
);
// Don't get errors about address in use
if (builtin.mode == .Debug) server.server.reuse_address = true;
return Server{
.server = server,
};
}
fn feedAddHandler(req: Request, res: Response) !void {
if (mem.eql(u8, req.method, "POST")) {
try feedAddPost(req, res);
} else if (mem.eql(u8, req.method, "GET")) {
try feedAddGet(req, res);
} else {
// TODO: response https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/405
}
}
fn getCookieToken(req: Request, allocator: Allocator) !?u64 {
const headers_opt = try req.headers.get(allocator, "cookie");
defer if (headers_opt) |headers| allocator.free(headers);
if (headers_opt) |headers| {
for (headers) |header| {
var iter = mem.split(u8, header.value, "=");
if (iter.next()) |key| {
if (mem.eql(u8, "token", key)) {
const value = iter.next() orelse continue;
return try fmt.parseUnsigned(u64, value, 10);
}
}
}
}
return null;
}
const form_start = "<form action='/feed/add' method='POST'>";
const form_end = "</form>";
const input_url_hidden = "<input type='hidden' name='feed_url' id='feed_url' value='{s}'>";
const input_url =
\\<div>
\\<label for="feed_url">Feed/Site url</label>
\\<input type="text" name="feed_url" id="feed_url" placeholder="Enter site or feed url" value="{s}">
\\</div>
;
const input_tags =
\\<div>
\\<label for="tags">Tags</label>
\\<input type="text" id="tags" name="tags" value="{s}">
\\</div>
;
const button_submit = "<button type='submit' name='{s}'>Add feed{s}</button>";
const form_start_same = form_start ++ input_url ++ input_tags;
const form_base = form_start_same ++ fmt.comptimePrint(button_submit, .{ "submit_feed", "" }) ++ form_end;
fn feedAddGet(req: Request, res: Response) !void {
var arena = std.heap.ArenaAllocator.init(global_allocator);
defer arena.deinit();
const token: ?u64 = try getCookieToken(req, global_allocator);
const session_index: ?usize = if (token) |t| g.sessions.getIndex(t) else null;
if (session_index == null) {
// TODO: empty string args when not debugging
try res.print(form_base, .{ "localhost:8080/many-links.html", "tag1, tag2, tag3" });
return;
}
var session = g.sessions.list.items[session_index.?];
switch (session.form_data) {
.success => |ids| {
if (ids.len > 0) {
for (ids) |id| {
try res.print("Added id {d}", .{id});
}
// TODO: print added links
try res.print(form_base, .{ "", "" });
}
session.deinit();
_ = g.sessions.list.swapRemove(session_index.?);
if (token) |_| res.headers.put("Set-Cookie", "token=; path=/feed/add; Max-Age=0") catch {};
},
.html => |data| {
switch (data.ty) {
.view => {
if (data.page.links.len > 0) {
try res.print("<p>{s} has several feeds</p>", .{data.url});
try printFormLinks(&arena, res, data.page.links, data.url, data.tags);
} else {
try res.print("<p>Found on feeds on {s}</p>", .{data.url});
try res.print(form_base, .{ data.url, data.tags });
}
},
.no_pick => {
try res.print("<p>{s} has several feeds</p>", .{data.url});
try res.write("<p>No feed(s) chosen. Please choose atleast one feed</p>");
try printFormLinks(&arena, res, data.page.links, data.url, data.tags);
},
}
},
.fail => |data| {
_ = data;
try res.print("<p>Failed to add {s}</p>", .{data.url});
try res.print("<p>{s}</p>", .{data.msg});
session.deinit();
_ = g.sessions.list.swapRemove(session_index.?);
if (token) |_| res.headers.put("Set-Cookie", "token=; path=/feed/add; Max-Age=0") catch {};
},
}
}
fn printFormLinks(arena: *ArenaAllocator, res: Response, links: []parse.Html.Link, initial_url: []const u8, tags: []const u8) !void {
try res.print(form_start ++ input_url_hidden ++ input_tags, .{ initial_url, tags });
const base_uri = try zuri.Uri.parse(initial_url, true);
try res.write("<ul>");
for (links) |link| {
const title = link.title orelse "";
const url = try url_util.makeWholeUrl(arena.allocator(), base_uri, link.href);
try res.print(
\\<li>
\\ <label>
\\ <input type='checkbox' name='picked_feed' value='{s}'>
\\ [{s}] {s}
\\ </label>
\\ <div>{s}</div>
\\</li>
, .{ url, link.media_type.toString(), title, url });
}
try res.write("</ul>");
// TODO: button
try res.write(fmt.comptimePrint(button_submit, .{ "submit_feed_links", "(s)" }) ++ form_end);
try res.write(form_end);
}
fn feedAddPost(req: Request, res: Response) !void {
var session = blk: {
const token = try getCookieToken(req, global_allocator);
const index_opt = if (token) |t| g.sessions.getIndex(t) else null;
if (index_opt) |index| {
break :blk &g.sessions.list.items[index];
}
var arena = std.heap.ArenaAllocator.init(global_allocator);
break :blk try g.sessions.new(arena);
};
errdefer {
session.deinit();
_ = g.sessions.list.pop();
}
var session_arena = session.arena;
// Get submitted form values
var is_submit_feed = false;
var is_submit_feed_links = false;
var tags_input: []const u8 = "";
var feed_url: []const u8 = "";
var page_index: ?usize = null;
var urls_list = try ArrayList([]const u8).initCapacity(session_arena.allocator(), 2);
const body_decoded = (try zuri.Uri.decode(session_arena.allocator(), req.body)) orelse req.body;
var iter = mem.split(u8, body_decoded, "&");
while (iter.next()) |key_value| {
var iter_key_value = mem.split(u8, key_value, "=");
const key = iter_key_value.next() orelse continue;
var value = iter_key_value.next() orelse continue;
if (mem.eql(u8, "feed_url", key)) {
feed_url = mem.trim(u8, value, "+");
} else if (mem.eql(u8, "picked_feed", key)) {
try urls_list.append(mem.trim(u8, value, "+"));
} else if (mem.eql(u8, "tags", key)) {
mem.replaceScalar(u8, @ptrCast(*[]u8, &value).*, '+', ' ');
tags_input = value;
} else if (mem.eql(u8, "submit_feed", key)) {
is_submit_feed = true;
} else if (mem.eql(u8, "submit_feed_links", key)) {
is_submit_feed_links = true;
} else if (mem.eql(u8, "page_index", key)) {
page_index = try fmt.parseUnsigned(usize, value, 10);
}
}
if (is_submit_feed) {
try submitFeed(&session_arena, session, feed_url, tags_input);
} else if (is_submit_feed_links) {
try submitFeedLinks(&session_arena, session, urls_list.items, feed_url, tags_input);
} else {
session.form_data = .{ .fail = .{ .url = feed_url, .ty = .invalid_form } };
}
try res.headers.put("Set-Cookie", try fmt.allocPrint(session_arena.allocator(), "token={d}; path=/feed/add", .{session.id}));
res.status_code = .Found;
try res.headers.put("Location", "/feed/add");
}
pub fn submitFeed(arena: *ArenaAllocator, session: *Session, first_url: []const u8, tags_input: []const u8) !void {
if (first_url.len == 0) {
session.form_data = .{ .fail = .{ .url = first_url, .ty = .empty_url } };
return;
}
const url = url_util.makeValidUrl(arena.allocator(), first_url) catch {
session.form_data = .{ .fail = .{ .url = first_url, .ty = .invalid_url } };
return;
};
var resp = try http.resolveRequest(arena, url, null, null);
const resp_ok = switch (resp) {
.ok => |ok| ok,
.not_modified => {
log.err("resolveRequest() fn returned .not_modified union value. This should not happen when adding new feed. Input url: {s}", .{url});
session.form_data = .{ .fail = .{ .url = url, .ty = .http_not_modified } };
return;
},
.fail => |msg| {
session.form_data = .{ .fail = .{ .url = url, .ty = .http_fail, .msg = msg } };
return;
},
};
const feed = switch (resp_ok.content_type) {
.html => {
const html_page = try parse.Html.parseLinks(global_allocator, resp_ok.body);
// TODO: if (html_page.links.len == 1) make request to add feed
session.form_data = .{ .html = .{ .url = url, .tags = tags_input, .page = html_page } };
return;
},
.xml => try parse.parse(arena, resp_ok.body),
.xml_atom => try parse.Atom.parse(arena, resp_ok.body),
.xml_rss => try parse.Rss.parse(arena, resp_ok.body),
.json, .json_feed => try parse.Json.parse(arena, resp_ok.body),
.unknown => parse.parse(arena, resp_ok.body) catch try parse.Json.parse(arena, resp_ok.body),
};
var ids = try ArrayList(u64).initCapacity(arena.allocator(), 1);
defer ids.deinit();
ids.appendAssumeCapacity(try addFeed(feed, resp_ok.headers, url, tags_input));
session.form_data = .{ .success = ids.toOwnedSlice() };
}
pub fn submitFeedLinks(
arena: *ArenaAllocator,
session: *Session,
try_urls: [][]const u8,
initial_url: ?[]const u8,
tags_input: []const u8,
) !void {
if (initial_url == null) {
session.form_data = .{ .fail = .{ .ty = .empty_url, .msg = "Can't do anything with no url" } };
return;
} else if (try_urls.len == 0) {
if (session.form_data == .html) {
session.form_data.html.ty = .no_pick;
} else {
session.form_data = .{ .fail = .{ .url = initial_url.?, .msg = "Invalid session" } };
}
return;
}
var added_ids = try ArrayList(u64).initCapacity(arena.allocator(), try_urls.len);
defer added_ids.deinit();
for (try_urls) |try_url| {
const url = try url_util.makeValidUrl(arena.allocator(), try_url);
var resp = try http.resolveRequest(arena, url, null, null);
const resp_ok = switch (resp) {
.ok => |ok| ok,
.not_modified => {
log.err("resolveRequest() fn returned .not_modified union value. This should not happen when adding new feed. Input url: {s}", .{url});
// TODO: send somekind or http error
continue;
},
.fail => |msg| {
log.err("Failed to resolve url {s}. Returned error message: {s}", .{ url, msg });
continue;
},
};
const feed = switch (resp_ok.content_type) {
.xml => try parse.parse(arena, resp_ok.body),
.xml_atom => try parse.Atom.parse(arena, resp_ok.body),
.xml_rss => try parse.Rss.parse(arena, resp_ok.body),
.json, .json_feed => try parse.Json.parse(arena, resp_ok.body),
.unknown => parse.parse(arena, resp_ok.body) catch try parse.Json.parse(arena, resp_ok.body),
.html => {
log.warn("Skipping adding {s} because it returned html content", .{try_url});
continue;
},
};
const feed_id = try addFeed(feed, resp_ok.headers, url, tags_input);
added_ids.appendAssumeCapacity(feed_id);
}
session.form_data = .{ .success = added_ids.toOwnedSlice() };
}
fn addFeed(feed: parse.Feed, headers: http.RespHeaders, url: []const u8, tags: []const u8) !u64 {
var savepoint = try g.storage.db.sql_db.savepoint("server_addFeed");
defer savepoint.rollback();
const query = "select id as feed_id, updated_timestamp from feed where location = ? limit 1;";
var feed_id: u64 = 0;
if (try g.storage.db.one(Storage.CurrentData, query, .{url})) |row| {
try g.storage.updateUrlFeed(.{
.current = row,
.headers = headers,
.feed = feed,
}, .{ .force = true });
try g.storage.addTags(row.feed_id, tags);
feed_id = row.feed_id;
} else {
feed_id = try g.storage.addFeed(feed, url);
try g.storage.addFeedUrl(feed_id, headers);
try g.storage.addItems(feed_id, feed.items);
try g.storage.addTags(feed_id, tags);
}
savepoint.commit();
return feed_id;
}
fn tagHandler(req: Request, res: Response, args: *const struct { tags: []const u8 }) !void {
_ = req;
var arena = std.heap.ArenaAllocator.init(global_allocator);
defer arena.deinit();
var all_tags = try g.storage.getAllTags();
var active_tags = try ArrayList([]const u8).initCapacity(arena.allocator(), 3);
defer active_tags.deinit();
// application/x-www-form-urlencoded encodes spaces as pluses (+)
var it = mem.split(u8, args.tags, "+");
while (it.next()) |tag| {
if (hasTag(all_tags, tag)) {
try active_tags.append(tag);
continue;
}
}
try res.write("<a href='/'>Home</a>");
try res.write("<p>Active tags:</p> ");
try res.write("<ul>");
if (active_tags.items.len == 1) {
try res.print("<li><a href='/'>{s}</a></li>", .{active_tags.items[0]});
} else {
var fb_alloc = std.heap.stackFallback(1024, arena.allocator());
for (active_tags.items) |a_tag| {
var alloc = fb_alloc.get();
const tags_slug = try tagsSlugRemove(fb_alloc.get(), a_tag, active_tags.items);
defer alloc.free(tags_slug);
try res.print("<li><a href='/tag/{s}'>{s}</a></li>", .{ tags_slug, a_tag });
}
}
try res.write("</ul>");
var recent_feeds = try g.storage.getRecentlyUpdatedFeedsByTags(active_tags.items);
try res.write("<p>Feeds</p>");
try printFeeds(res, recent_feeds);
try res.write("<p>All Tags</p>");
try printTags(arena.allocator(), res, all_tags, active_tags.items);
}
fn hasTag(all_tags: []Storage.TagCount, tag: []const u8) bool {
for (all_tags) |all_tag| {
if (mem.eql(u8, tag, all_tag.name)) return true;
}
return false;
}
fn printElapsedTime(res: Response, dt: Datetime, now: Datetime) !void {
const delta = now.sub(dt);
if (delta.days > 0) {
const months = @divFloor(delta.days, 30);
const years = @divFloor(delta.days, 365);
if (years > 0) {
try res.print("{d}Y", .{years});
} else if (months > 0) {
try res.print("{d}M", .{months});
} else {
try res.print("{d}d", .{delta.days});
}
} else if (delta.seconds > 0) {
const minutes = @divFloor(delta.seconds, 60);
const hours = @divFloor(minutes, 60);
if (hours > 0) {
try res.print("{d}h", .{hours});
} else if (delta.days > 0) {
try res.print("{d}m", .{minutes});
}
}
}
fn printFeeds(res: Response, recent_feeds: []Storage.RecentFeed) !void {
const now = Datetime.now();
try res.write("<ul>");
for (recent_feeds) |feed| {
try res.write("<li>");
if (feed.link) |link| {
try res.print("<a href=\"{s}\">{s}</a>", .{ link, feed.title });
} else {
try res.print("{s}", .{feed.title});
}
if (feed.updated_timestamp) |timestamp| {
try res.write(" | ");
const dt = Datetime.fromSeconds(@intToFloat(f64, timestamp));
var buf: [32]u8 = undefined;
const timestamp_str = fmt.bufPrint(&buf, timestamp_fmt, .{
dt.date.year, dt.date.month, dt.date.day,
dt.time.hour, dt.time.minute, dt.time.second,
});
try res.print("<span title='{s}'>", .{timestamp_str});
try printElapsedTime(res, dt, now);
try res.write("</span>");
}
// Get feed items
const items = try g.storage.getItems(feed.id);
try res.write("<ul>");
for (items) |item| {
try res.write("<li>");
if (item.link) |link| {
try res.print("<a href=\"{s}\">{s}</a>", .{ link, item.title });
} else {
try res.print("{s}", .{feed.title});
}
if (item.pub_date_utc) |timestamp| {
try res.write(" | ");
const dt = Datetime.fromSeconds(@intToFloat(f64, timestamp));
var buf: [32]u8 = undefined;
const timestamp_str = fmt.bufPrint(&buf, timestamp_fmt, .{
dt.date.year, dt.date.month, dt.date.day,
dt.time.hour, dt.time.minute, dt.time.second,
});
try res.print("<span title='{s}'>", .{timestamp_str});
try printElapsedTime(res, dt, now);
try res.write("</span>");
}
try res.write("</li>");
}
try res.write("</ul>");
try res.write("</li>");
}
try res.write("</ul>");
}
// Index displays most recenlty update feeds
fn indexHandler(req: Request, res: Response) !void {
_ = req;
// Get most recently update feeds
var recent_feeds = try g.storage.getRecentlyUpdatedFeeds();
try res.write("<p>Feeds</p>");
try printFeeds(res, recent_feeds);
// Get tags with count
var tags = try g.storage.getAllTags();
try res.write("<p>All Tags</p>");
try printTags(global_allocator, res, tags, &[_][]const u8{});
}
fn printTags(allocator: Allocator, res: Response, tags: []Storage.TagCount, active_tags: [][]const u8) !void {
var fb_alloc = std.heap.stackFallback(1024, allocator);
try res.write("<ul>");
for (tags) |tag| {
try printTag(fb_alloc.get(), res, tag, active_tags);
}
try res.write("</ul>");
}
fn printTag(allocator: Allocator, res: Response, tag: Storage.TagCount, active_tags: [][]const u8) !void {
var is_active = false;
for (active_tags) |a_tag| {
if (mem.eql(u8, tag.name, a_tag)) {
is_active = true;
break;
}
}
if (!is_active) {
// active_tags.len adds all the pluses (+)
var total = active_tags.len + tag.name.len;
for (active_tags) |t| total += t.len;
var arr_slug = try ArrayList(u8).initCapacity(allocator, total);
defer arr_slug.deinit();
for (active_tags) |a_tag| {
arr_slug.appendSliceAssumeCapacity(a_tag);
arr_slug.appendAssumeCapacity('+');
}
arr_slug.appendSliceAssumeCapacity(tag.name);
try res.print(
\\<li>
\\<a href='/tag/{s}'>{s} - {d}</a>
\\<a href='/tag/{s}'>Add</a>
\\</li>
, .{ tag.name, tag.name, tag.count, arr_slug.items });
} else {
const tags_slug = try tagsSlugRemove(allocator, tag.name, active_tags);
defer allocator.free(tags_slug);
try res.print(
\\<li>
\\<a href='/tag/{s}'>{s} - {d} [active]</a>
\\<a href='{s}'>Remove</a>
\\</li>
, .{ tag.name, tag.name, tag.count, tags_slug });
}
}
// caller owns the memory
fn tagsSlugRemove(allocator: Allocator, cmp_tag: []const u8, active_tags: [][]const u8) ![]const u8 {
var arr_tags = try ArrayList(u8).initCapacity(allocator, 2);
defer arr_tags.deinit();
var has_first = false;
for (active_tags) |path_tag| {
if (mem.eql(u8, cmp_tag, path_tag)) continue;
if (has_first) {
try arr_tags.append('+');
}
has_first = true;
try arr_tags.appendSlice(path_tag);
}
return arr_tags.toOwnedSlice();
}
};
const global = struct {
const ip = "127.0.0.1";
const port = 8282;
};
pub fn run(storage: *Storage) !void {
print("run server\n", .{});
var gen_alloc = std.heap.GeneralPurposeAllocator(.{}){};
var sessions = Sessions.init(gen_alloc.allocator());
defer sessions.deinit();
var server = Server.init(storage, &sessions);
var addr = try Address.parseIp(global.ip, global.port);
try server.server.listen(addr);
}
|
src/server.zig
|
const std = @import("std");
const builtin = std.builtin;
// Format reference: http://grub.gibibit.com/New_font_format
pub const PF2Font = struct {
name: []const u8,
family: []const u8,
weight: Weight,
slant: Slant,
pointSize: u16,
maxWidth: u16,
maxHeight: u16,
ascent: u16,
descent: u16,
chix: []const u8,
dataOffset: u32,
data: []const u8,
pub const Weight = enum {
bold,
normal,
};
pub const Slant = enum {
italic,
normal,
};
pub const signature = "PFF2";
pub const CharIndexEntry = packed struct {
codepoint: u32,
flags: u8,
offset: u32,
};
pub const RawDataEntry = packed struct {
width: u16,
height: u16,
xOffset: i16,
yOffset: i16,
deviceWidth: i16,
};
pub const CharEntry = struct {
width: u16,
height: u16,
xOffset: i16,
yOffset: i16,
deviceWidth: i16,
pixels: []const u8,
};
const Section = enum {
file,
name,
family,
weight,
slant,
pointSize,
maxWidth,
maxHeight,
ascent,
descent,
chix,
data,
};
fn parseSection(str: []const u8) !Section {
std.debug.assert(str.len == 4);
if (std.mem.eql(u8, str, "FILE")) {
return .file;
} else if (std.mem.eql(u8, str, "NAME")) {
return .name;
} else if (std.mem.eql(u8, str, "FAMI")) {
return .family;
} else if (std.mem.eql(u8, str, "WEIG")) {
return .weight;
} else if (std.mem.eql(u8, str, "SLAN")) {
return .slant;
} else if (std.mem.eql(u8, str, "PTSZ")) {
return .pointSize;
} else if (std.mem.eql(u8, str, "MAXW")) {
return .maxWidth;
} else if (std.mem.eql(u8, str, "MAXH")) {
return .maxHeight;
} else if (std.mem.eql(u8, str, "ASCE")) {
return .ascent;
} else if (std.mem.eql(u8, str, "DESC")) {
return .descent;
} else if (std.mem.eql(u8, str, "CHIX")) {
return .chix;
} else if (std.mem.eql(u8, str, "DATA")) {
return .data;
}
return error.InvalidSection;
}
pub fn fromConstMem(mem: []const u8) !PF2Font {
var offset: usize = 0;
var font: PF2Font = undefined;
while (offset < mem.len) {
var sectionType = try parseSection(mem[offset .. offset + 4]);
offset += 4;
var sectionLen = std.mem.readIntSlice(u32, mem[offset..], .Big);
offset += 4;
var section: []const u8 = undefined;
var sectionStartOffset = offset;
if (sectionType == .data) {
section = mem[offset..mem.len];
offset = mem.len;
} else {
section = mem[offset .. offset + sectionLen];
offset += sectionLen;
}
switch (sectionType) {
.file => {
if (!std.mem.eql(u8, section, signature)) {
return error.WrongSignature;
}
},
.name => font.name = section,
.family => font.family = section,
.weight => switch (section[0]) {
'b' => font.weight = .bold,
'n' => font.weight = .normal,
else => return error.WrongWeight,
},
.slant => switch (section[0]) {
'i' => font.slant = .italic,
'n' => font.slant = .normal,
else => return error.WrongSlant,
},
.pointSize => font.pointSize = std.mem.readIntSlice(u16, section, .Big),
.maxWidth => font.maxWidth = std.mem.readIntSlice(u16, section, .Big),
.maxHeight => font.maxHeight = std.mem.readIntSlice(u16, section, .Big),
.ascent => font.ascent = std.mem.readIntSlice(u16, section, .Big),
.descent => font.descent = std.mem.readIntSlice(u16, section, .Big),
.chix => font.chix = section,
.data => {
font.data = section;
font.dataOffset = @intCast(u32, sectionStartOffset);
},
}
}
return font;
}
pub fn findCharIndex(self: *const PF2Font, needle: u32) ?CharIndexEntry {
var i: usize = 0;
while (i < self.chix.len) : (i += 9) {
var codepoint = std.mem.readIntSlice(u32, self.chix[i..], .Big);
var result: CharIndexEntry = undefined;
result.codepoint = codepoint;
result.flags = self.chix[i + 4];
result.offset = std.mem.readIntSlice(u32, self.chix[i + 5 ..], .Big) - self.dataOffset;
if (needle == codepoint) {
return result;
}
}
return null;
}
pub fn getChar(self: *const PF2Font, needle: u32) ?CharEntry {
var chix = self.findCharIndex(needle) orelse return null;
var data = self.data[chix.offset..];
var width = std.mem.readIntSlice(u16, data, .Big);
var height = std.mem.readIntSlice(u16, data[2..], .Big);
var entry = CharEntry{
.width = width,
.height = height,
.xOffset = std.mem.readIntSlice(i16, data[4..], .Big),
.yOffset = std.mem.readIntSlice(i16, data[6..], .Big),
.deviceWidth = std.mem.readIntSlice(i16, data[8..], .Big),
.pixels = @ptrCast([*]const u8, self.data[chix.offset + @sizeOf(RawDataEntry) ..])[0 .. (width * height + 7) / 8],
};
return entry;
}
};
|
src/pf2.zig
|
const builtin = @import("builtin");
const TypeId = builtin.TypeId;
const std = @import("std");
const math = std.math;
const assert = std.debug.assert;
const warn = std.debug.warn;
const fepsilon = @import("fepsilon.zig").fepsilon;
// Set to true for debug output
const DBG = false;
/// Return true if x is approximately equal to y.
/// Based on `AlmostEqlRelativeAndAbs` at
/// https://randomascii.wordpress.com/2012/02/25/comparing-floating-point-numbers-2012-edition/
///
/// Note: It's possible to calculate max_diff at compile time by adding
/// a comptime attribute to digits parameter.
pub fn approxEql(x: var, y: var, digits: usize) bool {
assert(@typeOf(x) == @typeOf(y));
assert(@typeId(@typeOf(x)) == TypeId.Float);
assert(@typeId(@typeOf(y)) == TypeId.Float);
const T = @typeOf(x);
if (!DBG) {
if (digits == 0) return true;
if (x == y) return true;
if ((math.isNan(x) and math.isNan(y)) or (math.isNan(-x) and math.isNan(-y))) return true;
if ((math.isInf(x) and math.isInf(y)) or (math.isInf(-x) and math.isInf(-y))) return true;
var abs_diff = math.fabs(x - y);
if (math.isNan(abs_diff) or math.isInf(abs_diff)) return false;
var max_diff: T = math.pow(T, 10, -@intToFloat(T, digits - 1));
if (abs_diff <= max_diff) return true;
var largest = math.max(math.fabs(x), math.fabs(y));
var scaled_max_diff = largest * max_diff / 10;
return abs_diff <= scaled_max_diff;
} else {
var result: bool = undefined;
warn("approxEql: x={} y={} digits={}", T(x), T(y), digits);
defer {
warn(" result={}\n", result);
}
if (digits == 0) {
warn(" digits == 0");
result = true;
return result;
}
// Performance optimization if x and y are equal
if (x == y) {
warn(" x == y");
result = true;
return result;
}
// Check for nan and inf
if ((math.isNan(x) and math.isNan(y)) or (math.isNan(-x) and math.isNan(-y))) {
warn(" both nan");
result = true;
return true;
}
if ((math.isInf(x) and math.isInf(y)) or (math.isInf(-x) and math.isInf(-y))) {
warn(" both nan");
result = true;
return true;
}
// Determine the difference and check if max_diff is a nan or inf
var abs_diff = math.fabs(x - y);
warn(" abs_diff={}", abs_diff);
if (math.isNan(abs_diff) or math.isInf(abs_diff)) {
warn(" nan or inf");
result = false;
return result;
}
// Determine our basic max_diff based on digits
var max_diff: T = math.pow(T, 10, -@intToFloat(T, digits - 1));
warn(" max_diff={}", max_diff);
// Use max_diff unscalled to check for results close to zero.
if (abs_diff <= max_diff) {
warn(" close to 0");
result = true;
return result;
}
// Scale max_diff against largest of |x| and |y|.
// Also tired scaled_max_diff = largest * fepsilon(T),
// but that doesn't work large numbers near f32/f64_max.
var largest = math.max(math.fabs(x), math.fabs(y));
var scaled_max_diff = largest * max_diff / 10;
var scaled_epsilon = largest * fepsilon(T); // * 250;
warn(" scaled_max_diff={} scaled_epsilon={}", scaled_max_diff, scaled_epsilon);
// Compare and return result
//result = (abs_diff <= scaled_epsilon);
result = (abs_diff <= scaled_max_diff);
return result;
}
}
test "approxEql.nan.inf" {
if (DBG) warn("\n");
assert(approxEql(math.nan(f64), math.nan(f64), 17));
assert(approxEql(-math.nan(f64), -math.nan(f64), 17));
assert(approxEql(math.inf(f64), math.inf(f64), 17));
assert(approxEql(-math.inf(f64), -math.inf(f64), 17));
assert(!approxEql(math.nan(f64), f64(0), 17));
assert(!approxEql(math.inf(f64), f64(0), 17));
assert(!approxEql(f64(1), math.nan(f64), 17));
assert(!approxEql(f64(2), math.inf(f64), 17));
assert(approxEql(math.nan(f32), math.nan(f32), 17));
assert(approxEql(-math.nan(f32), -math.nan(f32), 17));
assert(approxEql(math.inf(f32), math.inf(f32), 17));
assert(approxEql(-math.inf(f32), -math.inf(f32), 17));
assert(!approxEql(math.nan(f32), f32(0), 17));
assert(!approxEql(math.inf(f32), f32(0), 17));
assert(!approxEql(f32(1), math.nan(f32), 17));
assert(!approxEql(f32(2), math.inf(f32), 17));
}
test "approxEql.same" {
if (DBG) warn("\n");
const T = f64;
var x: T = 0;
var y: T = 0;
assert(approxEql(x, y, 0));
assert(approxEql(x, y, 1));
assert(approxEql(x, y, 2));
assert(approxEql(x, y, 3));
assert(approxEql(x, y, 4));
assert(approxEql(x, y, 5));
assert(approxEql(x, y, 6));
assert(approxEql(x, y, 7));
assert(approxEql(x, y, 8));
assert(approxEql(x, y, 9));
assert(approxEql(x, y, 10));
assert(approxEql(x, y, 11));
assert(approxEql(x, y, 12));
assert(approxEql(x, y, 13));
assert(approxEql(x, y, 14));
assert(approxEql(x, y, 15));
assert(approxEql(x, y, 16));
assert(approxEql(x, y, 17));
assert(approxEql(T(123e-123), T(123e-123), 17));
assert(approxEql(T(-123e-123), T(-123e-123), 17));
assert(approxEql(T(-123e123), T(-123e123), 17));
assert(approxEql(T(123e123), T(123e123), 17));
}
test "approxEql.0.fepsilon*1" {
if (DBG) warn("\n");
const T = f64;
const et = fepsilon(T);
var x: T = 0;
var y: T = et * 1;
assert(y == et);
assert(approxEql(x, y, 0));
assert(approxEql(x, y, 1));
assert(approxEql(x, y, 2));
assert(approxEql(x, y, 3));
assert(approxEql(x, y, 4));
assert(approxEql(x, y, 5));
assert(approxEql(x, y, 6));
assert(approxEql(x, y, 7));
assert(approxEql(x, y, 8));
assert(approxEql(x, y, 9));
assert(approxEql(x, y, 10));
assert(approxEql(x, y, 11));
assert(approxEql(x, y, 12));
assert(approxEql(x, y, 13));
assert(approxEql(x, y, 14));
assert(approxEql(x, y, 15));
assert(approxEql(x, y, 16));
assert(!approxEql(x, y, 17));
}
test "approxEql.0.fepsilon*4" {
if (DBG) warn("\n");
const T = f64;
const et = fepsilon(T);
var x: T = 0;
var y: T = et * T(4);
assert(approxEql(x, y, 0));
assert(approxEql(x, y, 1));
assert(approxEql(x, y, 2));
assert(approxEql(x, y, 3));
assert(approxEql(x, y, 4));
assert(approxEql(x, y, 5));
assert(approxEql(x, y, 6));
assert(approxEql(x, y, 7));
assert(approxEql(x, y, 8));
assert(approxEql(x, y, 9));
assert(approxEql(x, y, 10));
assert(approxEql(x, y, 11));
assert(approxEql(x, y, 12));
assert(approxEql(x, y, 13));
assert(approxEql(x, y, 14));
assert(approxEql(x, y, 15));
assert(approxEql(x, y, 16));
assert(!approxEql(x, y, 17));
}
test "approxEql.0.fepsilon*5" {
if (DBG) warn("\n");
const T = f64;
const et = fepsilon(T);
var x: T = 0;
var y: T = et * T(5);
assert(approxEql(x, y, 0));
assert(approxEql(x, y, 1));
assert(approxEql(x, y, 2));
assert(approxEql(x, y, 3));
assert(approxEql(x, y, 4));
assert(approxEql(x, y, 5));
assert(approxEql(x, y, 6));
assert(approxEql(x, y, 7));
assert(approxEql(x, y, 8));
assert(approxEql(x, y, 9));
assert(approxEql(x, y, 10));
assert(approxEql(x, y, 11));
assert(approxEql(x, y, 12));
assert(approxEql(x, y, 13));
assert(approxEql(x, y, 14));
assert(approxEql(x, y, 15));
assert(!approxEql(x, y, 16));
assert(!approxEql(x, y, 17));
}
test "approxEql.0.fepsilon*45" {
if (DBG) warn("\n");
const T = f64;
const et = fepsilon(T);
var x: T = 0;
var y: T = et * T(45);
assert(approxEql(x, y, 0));
assert(approxEql(x, y, 1));
assert(approxEql(x, y, 2));
assert(approxEql(x, y, 3));
assert(approxEql(x, y, 4));
assert(approxEql(x, y, 5));
assert(approxEql(x, y, 6));
assert(approxEql(x, y, 7));
assert(approxEql(x, y, 8));
assert(approxEql(x, y, 9));
assert(approxEql(x, y, 10));
assert(approxEql(x, y, 11));
assert(approxEql(x, y, 12));
assert(approxEql(x, y, 13));
assert(approxEql(x, y, 14));
assert(approxEql(x, y, 15));
assert(!approxEql(x, y, 16));
assert(!approxEql(x, y, 17));
}
test "approxEql.0.fepsilon*46" {
if (DBG) warn("\n");
const T = f64;
const et = fepsilon(T);
var x: T = 0;
var y: T = et * T(46);
assert(approxEql(x, y, 0));
assert(approxEql(x, y, 1));
assert(approxEql(x, y, 2));
assert(approxEql(x, y, 3));
assert(approxEql(x, y, 4));
assert(approxEql(x, y, 5));
assert(approxEql(x, y, 6));
assert(approxEql(x, y, 7));
assert(approxEql(x, y, 8));
assert(approxEql(x, y, 9));
assert(approxEql(x, y, 10));
assert(approxEql(x, y, 11));
assert(approxEql(x, y, 12));
assert(approxEql(x, y, 13));
assert(approxEql(x, y, 14));
assert(!approxEql(x, y, 15));
assert(!approxEql(x, y, 16));
assert(!approxEql(x, y, 17));
}
test "approxEql.0.fepsilon*450" {
if (DBG) warn("\n");
const T = f64;
const et = fepsilon(T);
var x: T = 0;
var y: T = et * T(450);
assert(approxEql(x, y, 0));
assert(approxEql(x, y, 1));
assert(approxEql(x, y, 2));
assert(approxEql(x, y, 3));
assert(approxEql(x, y, 4));
assert(approxEql(x, y, 5));
assert(approxEql(x, y, 6));
assert(approxEql(x, y, 7));
assert(approxEql(x, y, 8));
assert(approxEql(x, y, 9));
assert(approxEql(x, y, 10));
assert(approxEql(x, y, 11));
assert(approxEql(x, y, 12));
assert(approxEql(x, y, 13));
assert(approxEql(x, y, 14));
assert(!approxEql(x, y, 15));
assert(!approxEql(x, y, 16));
assert(!approxEql(x, y, 17));
}
test "approxEql.0.fepsilon*451" {
if (DBG) warn("\n");
const T = f64;
const et = fepsilon(T);
var x: T = 0;
var y: T = et * T(451);
assert(approxEql(x, y, 0));
assert(approxEql(x, y, 1));
assert(approxEql(x, y, 2));
assert(approxEql(x, y, 3));
assert(approxEql(x, y, 4));
assert(approxEql(x, y, 5));
assert(approxEql(x, y, 6));
assert(approxEql(x, y, 7));
assert(approxEql(x, y, 8));
assert(approxEql(x, y, 9));
assert(approxEql(x, y, 10));
assert(approxEql(x, y, 11));
assert(approxEql(x, y, 12));
assert(approxEql(x, y, 13));
assert(!approxEql(x, y, 14));
assert(!approxEql(x, y, 15));
assert(!approxEql(x, y, 16));
assert(!approxEql(x, y, 17));
}
/// Sum from start to end with a step of (end - start)/count for
/// count times. So if start == 0 and end == 1 and count == 10 then
/// the step is 0.1 and because of the imprecision of floating point
/// errors are introduced.
fn sum(comptime T: type, start: T, end: T, count: usize) T {
var step = (end - start) / @intToFloat(T, count);
var r: T = start;
var j: usize = 0;
while (j < count) : (j += 1) {
r += step;
}
return r;
}
test "approxEql.sum.near0.f64" {
if (DBG) warn("\n");
const T = f64;
var x: T = 1;
var end: T = sum(T, 0, x, 10000);
if (DBG) warn("x={} end={}\n", x, end);
assert(x != end);
// "close to 0" is used and returned true
assert(approxEql(x, end, 0));
assert(approxEql(x, end, 1));
assert(approxEql(x, end, 2));
assert(approxEql(x, end, 3));
assert(approxEql(x, end, 4));
assert(approxEql(x, end, 5));
assert(approxEql(x, end, 6));
assert(approxEql(x, end, 7));
assert(approxEql(x, end, 8));
assert(approxEql(x, end, 9));
assert(approxEql(x, end, 10));
assert(approxEql(x, end, 11));
assert(approxEql(x, end, 12));
assert(approxEql(x, end, 13));
assert(approxEql(x, end, 14));
// "< 10" is used and either scaled_epsilon or scaled_max_diff returned false
assert(!approxEql(x, end, 15));
assert(!approxEql(x, end, 16));
assert(!approxEql(x, end, 17));
}
test "approxEql.sum.near0.f32" {
if (DBG) warn("\n");
const T = f32;
var x: T = 1;
var end: T = sum(T, 0, x, 1000);
if (DBG) warn("x={} end={}\n", x, end);
assert(x != end);
assert(approxEql(x, end, 0));
assert(approxEql(x, end, 1));
assert(approxEql(x, end, 2));
assert(approxEql(x, end, 3));
assert(approxEql(x, end, 4));
assert(approxEql(x, end, 5));
assert(approxEql(x, end, 6));
// "< 10" is used and either scaled_epsilon or scaled_max_diff returned false
assert(!approxEql(x, end, 7));
assert(!approxEql(x, end, 8));
assert(!approxEql(x, end, 9));
assert(!approxEql(x, end, 10));
assert(!approxEql(x, end, 11));
assert(!approxEql(x, end, 12));
assert(!approxEql(x, end, 13));
assert(!approxEql(x, end, 14));
assert(!approxEql(x, end, 15));
assert(!approxEql(x, end, 16));
assert(!approxEql(x, end, 17));
}
test "approxEql.sum.large.f64" {
if (DBG) warn("\n");
const T = f64;
var x: T = math.f64_max / T(2);
var end: T = sum(T, x / T(2), x, 1000);
if (DBG) warn("x={} end={}\n", x, end);
assert(x != end);
// ">=10" is used abs_diff=4.939e294 and using scaled_epsilon=1.99e292 would have failed all
// asserts by 0 digits. But largest_times_diff=8.98e306 and gave good results.
assert(approxEql(x, end, 0));
assert(approxEql(x, end, 1));
assert(approxEql(x, end, 2));
assert(approxEql(x, end, 3));
assert(approxEql(x, end, 4));
assert(approxEql(x, end, 5));
assert(approxEql(x, end, 6));
assert(approxEql(x, end, 7));
assert(approxEql(x, end, 8));
assert(approxEql(x, end, 9));
assert(approxEql(x, end, 10));
assert(approxEql(x, end, 11));
assert(approxEql(x, end, 12));
assert(approxEql(x, end, 13));
assert(!approxEql(x, end, 14));
assert(!approxEql(x, end, 15));
assert(!approxEql(x, end, 16));
assert(!approxEql(x, end, 17));
}
test "approxEql.sum.large.f32" {
if (DBG) warn("\n");
const T = f32;
var x: T = math.f32_max / T(2);
var end: T = sum(T, x / T(2), x, 100);
if (DBG) warn("x={} end={}\n", x, end);
assert(x != end);
// abs_diff=7.09e31 and using scaled_epsilon=2.02e31 would have failed all
// asserts by 0 digits. But largest_times_diff=1.70e37 and gave good results.
assert(approxEql(x, end, 0));
assert(approxEql(x, end, 1));
assert(approxEql(x, end, 2));
assert(approxEql(x, end, 3));
assert(approxEql(x, end, 4));
assert(approxEql(x, end, 5));
assert(approxEql(x, end, 6));
assert(!approxEql(x, end, 7));
assert(!approxEql(x, end, 8));
assert(!approxEql(x, end, 9));
assert(!approxEql(x, end, 10));
assert(!approxEql(x, end, 11));
assert(!approxEql(x, end, 12));
assert(!approxEql(x, end, 13));
assert(!approxEql(x, end, 14));
assert(!approxEql(x, end, 15));
assert(!approxEql(x, end, 16));
assert(!approxEql(x, end, 17));
}
/// Subtract from start down to end with a step of (start - end)/count
/// for count times. So if start == 1 and end == 0 and count == 10 then
/// the step is 0.1 and because of the imprecision of floating point
/// errors are introduced.
fn sub(comptime T: type, start: T, end: T, count: usize) T {
var step = (start - end) / @intToFloat(T, count);
var r: T = start;
var j: usize = 0;
while (j < count) : (j += 1) {
r -= step;
}
return r;
}
test "approxEql.sub.near0.f64" {
if (DBG) warn("\n");
const T = f64;
var x: T = 0;
var end: T = sub(T, 1, x, 10000);
if (DBG) warn("x={} end={}\n", x, end);
assert(x != end);
// Either scaled_epsilon or scaled_max_diff worked
assert(approxEql(x, end, 0));
assert(approxEql(x, end, 1));
assert(approxEql(x, end, 2));
assert(approxEql(x, end, 3));
assert(approxEql(x, end, 4));
assert(approxEql(x, end, 5));
assert(approxEql(x, end, 6));
assert(approxEql(x, end, 7));
assert(approxEql(x, end, 8));
assert(approxEql(x, end, 9));
assert(approxEql(x, end, 10));
assert(approxEql(x, end, 11));
assert(approxEql(x, end, 12));
assert(approxEql(x, end, 13));
assert(approxEql(x, end, 14));
assert(!approxEql(x, end, 15));
assert(!approxEql(x, end, 16));
assert(!approxEql(x, end, 17));
}
test "approxEql.sub.near0.f32" {
if (DBG) warn("\n");
const T = f32;
var x: T = 0;
var end: T = sub(T, 1, x, 1000);
if (DBG) warn("x={} end={}\n", x, end);
assert(x != end);
// Either scaled_epsilon or scaled_max_diff worked
assert(approxEql(x, end, 0));
assert(approxEql(x, end, 1));
assert(approxEql(x, end, 2));
assert(approxEql(x, end, 3));
assert(approxEql(x, end, 4));
assert(approxEql(x, end, 5));
assert(approxEql(x, end, 6));
assert(!approxEql(x, end, 7));
assert(!approxEql(x, end, 8));
assert(!approxEql(x, end, 9));
assert(!approxEql(x, end, 10));
assert(!approxEql(x, end, 11));
assert(!approxEql(x, end, 12));
assert(!approxEql(x, end, 13));
assert(!approxEql(x, end, 14));
assert(!approxEql(x, end, 15));
assert(!approxEql(x, end, 16));
assert(!approxEql(x, end, 17));
}
test "approxEql.atan32" {
const espilon: f32 = 0.000001;
if (DBG) warn("\natan(f64(0.2))={}\n", math.atan(f64(0.2)));
if (DBG) warn("atan(f32(0.2))={}\n", math.atan(f32(0.2)));
assert(math.approxEq(f32, math.atan(f32(0.2)), 0.197396, espilon));
assert(math.approxEq(f32, math.atan(f32(-0.2)), -0.197396, espilon));
assert(math.approxEq(f32, math.atan(f32(0.3434)), 0.330783, espilon));
assert(math.approxEq(f32, math.atan(f32(0.8923)), 0.728545, espilon));
assert(math.approxEq(f32, math.atan(f32(1.5)), 0.982794, espilon));
const digits = 7;
assert(approxEql(math.atan(f32(0.2)), f32(0.197396), digits));
assert(approxEql(math.atan(f32(-0.2)), f32(-0.197396), digits));
assert(approxEql(math.atan(f32(0.3434)), f32(0.330783), digits));
assert(approxEql(math.atan(f32(0.8923)), f32(0.728545), digits));
assert(approxEql(math.atan(f32(1.5)), f32(0.982794), digits));
}
test "approxEql.123e12.3.digits" {
if (DBG) warn("\n");
assert(!approxEql(f32(122.0e12), f32(123e12), 3));
assert(approxEql(f32(123.0e12), f32(123e12), 3));
assert(!approxEql(f32(124.0e12), f32(123e12), 3));
}
test "approxEql.123e12.4.digits" {
if (DBG) warn("\n");
assert(!approxEql(f32(122.9e12), f32(123.0e12), 4));
assert(approxEql(f32(123.0e12), f32(123.0e12), 4));
assert(!approxEql(f32(123.1e12), f32(123.0e12), 4));
}
test "approxEql.993e12.3.digits" {
if (DBG) warn("\n");
assert(!approxEql(f32(992.0e12), f32(993e12), 3));
assert(approxEql(f32(993.0e12), f32(993e12), 3));
assert(!approxEql(f32(994.0e12), f32(993e12), 3));
}
test "approxEql.993e12.4.digits" {
if (DBG) warn("\n");
assert(!approxEql(f32(992.9e12), f32(993.0e12), 4));
assert(approxEql(f32(993.0e12), f32(993.0e12), 4));
assert(!approxEql(f32(993.1e12), f32(993.0e12), 4));
}
|
approxeql.zig
|
//--------------------------------------------------------------------------------
// Section: Types (4)
//--------------------------------------------------------------------------------
const IID_IWindowsDevicesAllJoynBusAttachmentInterop_Value = @import("../../zig.zig").Guid.initString("fd89c65b-b50e-4a19-9d0c-b42b783281cd");
pub const IID_IWindowsDevicesAllJoynBusAttachmentInterop = &IID_IWindowsDevicesAllJoynBusAttachmentInterop_Value;
pub const IWindowsDevicesAllJoynBusAttachmentInterop = extern struct {
pub const VTable = extern struct {
base: IInspectable.VTable,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_Win32Handle: fn(
self: *const IWindowsDevicesAllJoynBusAttachmentInterop,
value: ?*u64,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
};
vtable: *const VTable,
pub fn MethodMixin(comptime T: type) type { return struct {
pub usingnamespace IInspectable.MethodMixin(T);
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IWindowsDevicesAllJoynBusAttachmentInterop_get_Win32Handle(self: *const T, value: ?*u64) callconv(.Inline) HRESULT {
return @ptrCast(*const IWindowsDevicesAllJoynBusAttachmentInterop.VTable, self.vtable).get_Win32Handle(@ptrCast(*const IWindowsDevicesAllJoynBusAttachmentInterop, self), value);
}
};}
pub usingnamespace MethodMixin(@This());
};
const IID_IWindowsDevicesAllJoynBusAttachmentFactoryInterop_Value = @import("../../zig.zig").Guid.initString("4b8f7505-b239-4e7b-88af-f6682575d861");
pub const IID_IWindowsDevicesAllJoynBusAttachmentFactoryInterop = &IID_IWindowsDevicesAllJoynBusAttachmentFactoryInterop_Value;
pub const IWindowsDevicesAllJoynBusAttachmentFactoryInterop = extern struct {
pub const VTable = extern struct {
base: IInspectable.VTable,
CreateFromWin32Handle: fn(
self: *const IWindowsDevicesAllJoynBusAttachmentFactoryInterop,
win32handle: u64,
enableAboutData: u8,
riid: ?*const Guid,
ppv: ?*?*anyopaque,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
};
vtable: *const VTable,
pub fn MethodMixin(comptime T: type) type { return struct {
pub usingnamespace IInspectable.MethodMixin(T);
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IWindowsDevicesAllJoynBusAttachmentFactoryInterop_CreateFromWin32Handle(self: *const T, win32handle: u64, enableAboutData: u8, riid: ?*const Guid, ppv: ?*?*anyopaque) callconv(.Inline) HRESULT {
return @ptrCast(*const IWindowsDevicesAllJoynBusAttachmentFactoryInterop.VTable, self.vtable).CreateFromWin32Handle(@ptrCast(*const IWindowsDevicesAllJoynBusAttachmentFactoryInterop, self), win32handle, enableAboutData, riid, ppv);
}
};}
pub usingnamespace MethodMixin(@This());
};
const IID_IWindowsDevicesAllJoynBusObjectInterop_Value = @import("../../zig.zig").Guid.initString("d78aa3d5-5054-428f-99f2-ec3a5de3c3bc");
pub const IID_IWindowsDevicesAllJoynBusObjectInterop = &IID_IWindowsDevicesAllJoynBusObjectInterop_Value;
pub const IWindowsDevicesAllJoynBusObjectInterop = extern struct {
pub const VTable = extern struct {
base: IInspectable.VTable,
AddPropertyGetHandler: fn(
self: *const IWindowsDevicesAllJoynBusObjectInterop,
context: ?*anyopaque,
interfaceName: ?HSTRING,
callback: isize,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
AddPropertySetHandler: fn(
self: *const IWindowsDevicesAllJoynBusObjectInterop,
context: ?*anyopaque,
interfaceName: ?HSTRING,
callback: isize,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_Win32Handle: fn(
self: *const IWindowsDevicesAllJoynBusObjectInterop,
value: ?*u64,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
};
vtable: *const VTable,
pub fn MethodMixin(comptime T: type) type { return struct {
pub usingnamespace IInspectable.MethodMixin(T);
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IWindowsDevicesAllJoynBusObjectInterop_AddPropertyGetHandler(self: *const T, context: ?*anyopaque, interfaceName: ?HSTRING, callback: isize) callconv(.Inline) HRESULT {
return @ptrCast(*const IWindowsDevicesAllJoynBusObjectInterop.VTable, self.vtable).AddPropertyGetHandler(@ptrCast(*const IWindowsDevicesAllJoynBusObjectInterop, self), context, interfaceName, callback);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IWindowsDevicesAllJoynBusObjectInterop_AddPropertySetHandler(self: *const T, context: ?*anyopaque, interfaceName: ?HSTRING, callback: isize) callconv(.Inline) HRESULT {
return @ptrCast(*const IWindowsDevicesAllJoynBusObjectInterop.VTable, self.vtable).AddPropertySetHandler(@ptrCast(*const IWindowsDevicesAllJoynBusObjectInterop, self), context, interfaceName, callback);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IWindowsDevicesAllJoynBusObjectInterop_get_Win32Handle(self: *const T, value: ?*u64) callconv(.Inline) HRESULT {
return @ptrCast(*const IWindowsDevicesAllJoynBusObjectInterop.VTable, self.vtable).get_Win32Handle(@ptrCast(*const IWindowsDevicesAllJoynBusObjectInterop, self), value);
}
};}
pub usingnamespace MethodMixin(@This());
};
const IID_IWindowsDevicesAllJoynBusObjectFactoryInterop_Value = @import("../../zig.zig").Guid.initString("6174e506-8b95-4e36-95c0-b88fed34938c");
pub const IID_IWindowsDevicesAllJoynBusObjectFactoryInterop = &IID_IWindowsDevicesAllJoynBusObjectFactoryInterop_Value;
pub const IWindowsDevicesAllJoynBusObjectFactoryInterop = extern struct {
pub const VTable = extern struct {
base: IInspectable.VTable,
CreateFromWin32Handle: fn(
self: *const IWindowsDevicesAllJoynBusObjectFactoryInterop,
win32handle: u64,
riid: ?*const Guid,
ppv: ?*?*anyopaque,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
};
vtable: *const VTable,
pub fn MethodMixin(comptime T: type) type { return struct {
pub usingnamespace IInspectable.MethodMixin(T);
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IWindowsDevicesAllJoynBusObjectFactoryInterop_CreateFromWin32Handle(self: *const T, win32handle: u64, riid: ?*const Guid, ppv: ?*?*anyopaque) callconv(.Inline) HRESULT {
return @ptrCast(*const IWindowsDevicesAllJoynBusObjectFactoryInterop.VTable, self.vtable).CreateFromWin32Handle(@ptrCast(*const IWindowsDevicesAllJoynBusObjectFactoryInterop, self), win32handle, riid, ppv);
}
};}
pub usingnamespace MethodMixin(@This());
};
//--------------------------------------------------------------------------------
// Section: Functions (0)
//--------------------------------------------------------------------------------
//--------------------------------------------------------------------------------
// Section: Unicode Aliases (0)
//--------------------------------------------------------------------------------
const thismodule = @This();
pub usingnamespace switch (@import("../../zig.zig").unicode_mode) {
.ansi => struct {
},
.wide => struct {
},
.unspecified => if (@import("builtin").is_test) struct {
} else struct {
},
};
//--------------------------------------------------------------------------------
// Section: Imports (4)
//--------------------------------------------------------------------------------
const Guid = @import("../../zig.zig").Guid;
const HRESULT = @import("../../foundation.zig").HRESULT;
const HSTRING = @import("../../system/win_rt.zig").HSTRING;
const IInspectable = @import("../../system/win_rt.zig").IInspectable;
test {
@setEvalBranchQuota(
@import("std").meta.declarations(@This()).len * 3
);
// reference all the pub declarations
if (!@import("builtin").is_test) return;
inline for (@import("std").meta.declarations(@This())) |decl| {
if (decl.is_pub) {
_ = decl;
}
}
}
|
win32/system/win_rt/all_joyn.zig
|
const std = @import("std");
const fmt = std.fmt;
const testing = std.testing;
/// Parses Redis Set values.
pub const SetParser = struct {
// TODO: prevent users from unmarshaling structs out of strings
pub fn isSupported(comptime T: type) bool {
return switch (@typeInfo(T)) {
.Array => true,
else => false,
};
}
pub fn isSupportedAlloc(comptime T: type) bool {
// HashMap
if (@typeInfo(T) == .Struct and @hasDecl(T, "Entry")) {
return void == std.meta.fieldInfo(T.Entry, .value_ptr).field_type;
}
return switch (@typeInfo(T)) {
.Pointer => true,
else => isSupported(T),
};
}
pub fn parse(comptime T: type, comptime rootParser: type, msg: anytype) !T {
return parseImpl(T, rootParser, .{}, msg);
}
pub fn parseAlloc(comptime T: type, comptime rootParser: type, allocator: std.mem.Allocator, msg: anytype) !T {
// HASHMAP
if (@typeInfo(T) == .Struct and @hasDecl(T, "Entry")) {
const isManaged = @typeInfo(@TypeOf(T.deinit)).Fn.args.len == 1;
// TODO: write real implementation
var buf: [100]u8 = undefined;
var end: usize = 0;
for (buf) |*elem, i| {
const ch = try msg.readByte();
elem.* = ch;
if (ch == '\r') {
end = i;
break;
}
}
try msg.skipBytes(1, .{});
const size = try fmt.parseInt(usize, buf[0..end], 10);
var hmap = T.init(allocator);
errdefer {
if (isManaged) {
hmap.deinit();
} else {
hmap.deinit(allocator.ptr);
}
}
const KeyType = std.meta.fieldInfo(T.Entry, .key_ptr).field_type;
var foundNil = false;
var foundErr = false;
var hashMapError = false;
var i: usize = 0;
while (i < size) : (i += 1) {
if (foundNil or foundErr or hashMapError) {
rootParser.parse(void, msg) catch |err| switch (err) {
error.GotErrorReply => {
foundErr = true;
},
else => return err,
};
} else {
var key = rootParser.parseAlloc(KeyType, allocator, msg) catch |err| switch (err) {
error.GotNilReply => {
foundNil = true;
continue;
},
error.GotErrorReply => {
foundErr = true;
continue;
},
else => return err,
};
// If we got here then no error occurred and we can add the key.
(if (isManaged) hmap.put(key.*, {}) else hmap.put(allocator.ptr, key.*, {})) catch {
hashMapError = true;
continue;
};
}
}
if (foundErr) return error.GotErrorReply;
if (foundNil) return error.GotNilReply;
if (hashMapError) return error.DecodeError; // TODO: find a way to save and return the precise error?
return hmap;
}
return parseImpl(T, rootParser, .{ .ptr = allocator }, msg);
}
pub fn parseImpl(comptime T: type, comptime rootParser: type, allocator: anytype, msg: anytype) !T {
// Indirectly delegate all cases to the list parser.
// TODO: fix this. Delegating with the same top-level T looks
// like a loop to the compiler. Solution would be to make the
// tag comptime known.
//
// return if (@hasField(@TypeOf(allocator), "ptr"))
// rootParser.parseAllocFromTag(T, '*', allocator.ptr, msg)
// else
// rootParser.parseFromTag(T, '*', msg);
const ListParser = @import("./t_list.zig").ListParser;
return if (@hasField(@TypeOf(allocator), "ptr"))
ListParser.parseAlloc(T, rootParser, allocator.ptr, msg)
else
ListParser.parse(T, rootParser, msg);
// return error.DecodeError;
}
};
test "set" {
const parser = @import("../parser.zig").RESP3Parser;
const allocator = std.heap.page_allocator;
const arr = try SetParser.parse([3]i32, parser, MakeSet().reader());
try testing.expectEqualSlices(i32, &[3]i32{ 1, 2, 3 }, &arr);
const sli = try SetParser.parseAlloc([]i64, parser, allocator, MakeSet().reader());
defer allocator.free(sli);
try testing.expectEqualSlices(i64, &[3]i64{ 1, 2, 3 }, sli);
var hmap = try SetParser.parseAlloc(std.AutoHashMap(i64, void), parser, allocator, MakeSet().reader());
defer hmap.deinit();
if (hmap.remove(1)) {} else unreachable;
if (hmap.remove(2)) {} else unreachable;
if (hmap.remove(3)) {} else unreachable;
try testing.expectEqual(@as(usize, 0), hmap.count());
}
fn MakeSet() std.io.FixedBufferStream([]const u8) {
return std.io.fixedBufferStream("~3\r\n:1\r\n:2\r\n:3\r\n"[1..]);
}
|
src/parser/t_set.zig
|
const std = @import("std");
pub const Timings = &[_][]const u8{
&[_]u8{4}, // 0x00 - NOP
&[_]u8{}, // 0x01
&[_]u8{}, // 0x02
&[_]u8{}, // 0x03
&[_]u8{}, // 0x04
&[_]u8{}, // 0x05
&[_]u8{ 4, 3 }, // 0x06 - LD B,n
&[_]u8{}, // 0x07
&[_]u8{}, // 0x08
&[_]u8{}, // 0x09
&[_]u8{}, // 0x0A
&[_]u8{}, // 0x0B
&[_]u8{}, // 0x0C
&[_]u8{}, // 0x0D
&[_]u8{ 4, 3 }, // 0x0E - LD C,n
&[_]u8{}, // 0x0F
&[_]u8{}, // 0x10
&[_]u8{}, // 0x11
&[_]u8{}, // 0x12
&[_]u8{}, // 0x13
&[_]u8{}, // 0x14
&[_]u8{}, // 0x15
&[_]u8{ 4, 3 }, // 0x16 - LD D,n
&[_]u8{}, // 0x17
&[_]u8{}, // 0x18
&[_]u8{}, // 0x19
&[_]u8{}, // 0x1A
&[_]u8{}, // 0x1B
&[_]u8{}, // 0x1C
&[_]u8{}, // 0x1D
&[_]u8{ 4, 3 }, // 0x1E - LD E,n
&[_]u8{}, // 0x1F
&[_]u8{}, // 0x20
&[_]u8{}, // 0x21
&[_]u8{}, // 0x22
&[_]u8{}, // 0x23
&[_]u8{}, // 0x24
&[_]u8{}, // 0x25
&[_]u8{ 4, 3 }, // 0x26 - LD H,n
&[_]u8{}, // 0x27
&[_]u8{}, // 0x28
&[_]u8{}, // 0x29
&[_]u8{}, // 0x2A
&[_]u8{}, // 0x2B
&[_]u8{}, // 0x2C
&[_]u8{}, // 0x2D
&[_]u8{ 4, 3 }, // 0x2E - LD L,n
&[_]u8{}, // 0x2F
&[_]u8{}, // 0x30
&[_]u8{}, // 0x31
&[_]u8{}, // 0x32
&[_]u8{}, // 0x33
&[_]u8{}, // 0x34
&[_]u8{}, // 0x35
&[_]u8{}, // 0x36
&[_]u8{}, // 0x37
&[_]u8{}, // 0x38
&[_]u8{}, // 0x39
&[_]u8{}, // 0x3A
&[_]u8{}, // 0x3B
&[_]u8{}, // 0x3C
&[_]u8{}, // 0x3D
&[_]u8{ 4, 3 }, // 0x3E - LD A,n
&[_]u8{}, // 0x3F
&[_]u8{4}, // 0x40 - LD B,B
&[_]u8{4}, // 0x41 - LD B,C
&[_]u8{4}, // 0x42 - LD B,D
&[_]u8{4}, // 0x43 - LD B,E
&[_]u8{4}, // 0x44 - LD B,H
&[_]u8{4}, // 0x45 - LD B,L
&[_]u8{ 4, 3 }, // 0x46 - LD B, (HL)
&[_]u8{4}, // 0x47 - LD B,A
&[_]u8{4}, // 0x48 - LD C,B
&[_]u8{4}, // 0x49 - LD C,C
&[_]u8{4}, // 0x4A - LD C,D
&[_]u8{4}, // 0x4B - LD C,E
&[_]u8{4}, // 0x4C - LD C,H
&[_]u8{4}, // 0x4D - LD C,L
&[_]u8{ 4, 3 }, // 0x4E - LD C, (HL)
&[_]u8{4}, // 0x4F - LD C,A
&[_]u8{4}, // 0x50 - LD D,B
&[_]u8{4}, // 0x51 - LD D,C
&[_]u8{4}, // 0x52 - LD D,D
&[_]u8{4}, // 0x53 - LD D,E
&[_]u8{4}, // 0x54 - LD D,H
&[_]u8{4}, // 0x55 - LD D,L
&[_]u8{ 4, 3 }, // 0x56 - LD D, (HL)
&[_]u8{4}, // 0x57 - LD D,A
&[_]u8{4}, // 0x58 - LD E,B
&[_]u8{4}, // 0x59 - LD E,C
&[_]u8{4}, // 0x5A - LD E,D
&[_]u8{4}, // 0x5B - LD E,E
&[_]u8{4}, // 0x5C - LD E,H
&[_]u8{4}, // 0x5D - LD E,L
&[_]u8{ 4, 3 }, // 0x5E - LD E, (HL)
&[_]u8{4}, // 0x5F - LD E,A
&[_]u8{4}, // 0x60 - LD H,B
&[_]u8{4}, // 0x61 - LD H,C
&[_]u8{4}, // 0x62 - LD H,D
&[_]u8{4}, // 0x63 - LD H,E
&[_]u8{4}, // 0x64 - LD H,H
&[_]u8{4}, // 0x65 - LD H,L
&[_]u8{ 4, 3 }, // 0x66 LD H, (HL)
&[_]u8{4}, // 0x67 - LD H,A
&[_]u8{4}, // 0x68 - LD L,B
&[_]u8{4}, // 0x69 - LD L,C
&[_]u8{4}, // 0x6A - LD L,D
&[_]u8{4}, // 0x6B - LD L,E
&[_]u8{4}, // 0x6C - LD L,H
&[_]u8{4}, // 0x6D - LD L,L
&[_]u8{ 4, 3 }, // 0x6E - LD L, (HL)
&[_]u8{4}, // 0x6F - LD L,A
&[_]u8{ 4, 3 }, // 0x70 - LD (HL), B
&[_]u8{ 4, 3 }, // 0x71 - LD (HL), C
&[_]u8{ 4, 3 }, // 0x72 - LD (HL), D
&[_]u8{ 4, 3 }, // 0x73 - LD (HL), E
&[_]u8{ 4, 3 }, // 0x74 - LD (HL), H
&[_]u8{ 4, 3 }, // 0x75 - LD (HL), L
&[_]u8{}, // 0x76
&[_]u8{ 4, 3 }, // 0x77 - LD (HL), A
&[_]u8{4}, // 0x78 - LD A,B
&[_]u8{4}, // 0x79 - LD A,C
&[_]u8{4}, // 0x7A - LD A,D
&[_]u8{4}, // 0x7B - LD A,E
&[_]u8{4}, // 0x7C - LD A,H
&[_]u8{4}, // 0x7D - LD A,L
&[_]u8{ 4, 3 }, // 0x7E
&[_]u8{4}, // 0x7F - LD A,A
&[_]u8{}, // 0x80
&[_]u8{}, // 0x81
&[_]u8{}, // 0x82
&[_]u8{}, // 0x83
&[_]u8{}, // 0x84
&[_]u8{}, // 0x85
&[_]u8{}, // 0x86
&[_]u8{}, // 0x87
&[_]u8{}, // 0x88
&[_]u8{}, // 0x89
&[_]u8{}, // 0x8A
&[_]u8{}, // 0x8B
&[_]u8{}, // 0x8C
&[_]u8{}, // 0x8D
&[_]u8{}, // 0x8E
&[_]u8{}, // 0x8F
&[_]u8{}, // 0x90
&[_]u8{}, // 0x91
&[_]u8{}, // 0x92
&[_]u8{}, // 0x93
&[_]u8{}, // 0x94
&[_]u8{}, // 0x95
&[_]u8{}, // 0x96
&[_]u8{}, // 0x97
&[_]u8{}, // 0x98
&[_]u8{}, // 0x99
&[_]u8{}, // 0x9A
&[_]u8{}, // 0x9B
&[_]u8{}, // 0x9C
&[_]u8{}, // 0x9D
&[_]u8{}, // 0x9E
&[_]u8{}, // 0x9F
&[_]u8{}, // 0xA0
&[_]u8{}, // 0xA1
&[_]u8{}, // 0xA2
&[_]u8{}, // 0xA3
&[_]u8{}, // 0xA4
&[_]u8{}, // 0xA5
&[_]u8{}, // 0xA6
&[_]u8{}, // 0xA7
&[_]u8{}, // 0xA8
&[_]u8{}, // 0xA9
&[_]u8{}, // 0xAA
&[_]u8{}, // 0xAB
&[_]u8{}, // 0xAC
&[_]u8{}, // 0xAD
&[_]u8{}, // 0xAE
&[_]u8{}, // 0xAF
&[_]u8{}, // 0xB0
&[_]u8{}, // 0xB1
&[_]u8{}, // 0xB2
&[_]u8{}, // 0xB3
&[_]u8{}, // 0xB4
&[_]u8{}, // 0xB5
&[_]u8{}, // 0xB6
&[_]u8{}, // 0xB7
&[_]u8{}, // 0xB8
&[_]u8{}, // 0xB9
&[_]u8{}, // 0xBA
&[_]u8{}, // 0xBB
&[_]u8{}, // 0xBC
&[_]u8{}, // 0xBD
&[_]u8{}, // 0xBE
&[_]u8{}, // 0xBF
&[_]u8{}, // 0xC0
&[_]u8{}, // 0xC1
&[_]u8{}, // 0xC2
&[_]u8{}, // 0xC3
&[_]u8{}, // 0xC4
&[_]u8{}, // 0xC5
&[_]u8{}, // 0xC6
&[_]u8{}, // 0xC7
&[_]u8{}, // 0xC8
&[_]u8{}, // 0xC9
&[_]u8{}, // 0xCA
&[_]u8{}, // 0xCB
&[_]u8{}, // 0xCC
&[_]u8{}, // 0xCD
&[_]u8{}, // 0xCE
&[_]u8{}, // 0xCF
&[_]u8{}, // 0xD0
&[_]u8{}, // 0xD1
&[_]u8{}, // 0xD2
&[_]u8{}, // 0xD3
&[_]u8{}, // 0xD4
&[_]u8{}, // 0xD5
&[_]u8{}, // 0xD6
&[_]u8{}, // 0xD7
&[_]u8{}, // 0xD8
&[_]u8{}, // 0xD9
&[_]u8{}, // 0xDA
&[_]u8{}, // 0xDB
&[_]u8{}, // 0xDC
&[_]u8{}, // 0xDD
&[_]u8{}, // 0xDE
&[_]u8{}, // 0xDF
&[_]u8{}, // 0xE0
&[_]u8{}, // 0xE1
&[_]u8{}, // 0xE2
&[_]u8{}, // 0xE3
&[_]u8{}, // 0xE4
&[_]u8{}, // 0xE5
&[_]u8{}, // 0xE6
&[_]u8{}, // 0xE7
&[_]u8{}, // 0xE8
&[_]u8{}, // 0xE9
&[_]u8{}, // 0xEA
&[_]u8{}, // 0xEB
&[_]u8{}, // 0xEC
&[_]u8{}, // 0xED
&[_]u8{}, // 0xEE
&[_]u8{}, // 0xEF
&[_]u8{}, // 0xF0
&[_]u8{}, // 0xF1
&[_]u8{}, // 0xF2
&[_]u8{}, // 0xF3
&[_]u8{}, // 0xF4
&[_]u8{}, // 0xF5
&[_]u8{}, // 0xF6
&[_]u8{}, // 0xF7
&[_]u8{}, // 0xF8
&[_]u8{}, // 0xF9
&[_]u8{}, // 0xFA
&[_]u8{}, // 0xFB
&[_]u8{}, // 0xFC
&[_]u8{}, // 0xFD
&[_]u8{}, // 0xFE
&[_]u8{}, // 0xFF
};
comptime {
std.debug.assert(Timings.len == 256);
}
|
lib/cpu/z80/timings.zig
|
const std = @import("std");
const builtin = @import("builtin");
const normalize = @import("divdf3.zig").normalize;
const wideMultiply = @import("divdf3.zig").wideMultiply;
pub fn __divtf3(a: f128, b: f128) callconv(.C) f128 {
@setRuntimeSafety(builtin.is_test);
const Z = std.meta.Int(false, 128);
const SignedZ = std.meta.Int(true, 128);
const significandBits = std.math.floatMantissaBits(f128);
const exponentBits = std.math.floatExponentBits(f128);
const signBit = (@as(Z, 1) << (significandBits + exponentBits));
const maxExponent = ((1 << exponentBits) - 1);
const exponentBias = (maxExponent >> 1);
const implicitBit = (@as(Z, 1) << significandBits);
const quietBit = implicitBit >> 1;
const significandMask = implicitBit - 1;
const absMask = signBit - 1;
const exponentMask = absMask ^ significandMask;
const qnanRep = exponentMask | quietBit;
const infRep = @bitCast(Z, std.math.inf(f128));
const aExponent = @truncate(u32, (@bitCast(Z, a) >> significandBits) & maxExponent);
const bExponent = @truncate(u32, (@bitCast(Z, b) >> significandBits) & maxExponent);
const quotientSign: Z = (@bitCast(Z, a) ^ @bitCast(Z, b)) & signBit;
var aSignificand: Z = @bitCast(Z, a) & significandMask;
var bSignificand: Z = @bitCast(Z, b) & significandMask;
var scale: i32 = 0;
// Detect if a or b is zero, denormal, infinity, or NaN.
if (aExponent -% 1 >= maxExponent -% 1 or bExponent -% 1 >= maxExponent -% 1) {
const aAbs: Z = @bitCast(Z, a) & absMask;
const bAbs: Z = @bitCast(Z, b) & absMask;
// NaN / anything = qNaN
if (aAbs > infRep) return @bitCast(f128, @bitCast(Z, a) | quietBit);
// anything / NaN = qNaN
if (bAbs > infRep) return @bitCast(f128, @bitCast(Z, b) | quietBit);
if (aAbs == infRep) {
// infinity / infinity = NaN
if (bAbs == infRep) {
return @bitCast(f128, qnanRep);
}
// infinity / anything else = +/- infinity
else {
return @bitCast(f128, aAbs | quotientSign);
}
}
// anything else / infinity = +/- 0
if (bAbs == infRep) return @bitCast(f128, quotientSign);
if (aAbs == 0) {
// zero / zero = NaN
if (bAbs == 0) {
return @bitCast(f128, qnanRep);
}
// zero / anything else = +/- zero
else {
return @bitCast(f128, quotientSign);
}
}
// anything else / zero = +/- infinity
if (bAbs == 0) return @bitCast(f128, infRep | quotientSign);
// one or both of a or b is denormal, the other (if applicable) is a
// normal number. Renormalize one or both of a and b, and set scale to
// include the necessary exponent adjustment.
if (aAbs < implicitBit) scale +%= normalize(f128, &aSignificand);
if (bAbs < implicitBit) scale -%= normalize(f128, &bSignificand);
}
// Set the implicit significand bit. If we fell through from the
// denormal path it was already set by normalize( ), but setting it twice
// won't hurt anything.
aSignificand |= implicitBit;
bSignificand |= implicitBit;
var quotientExponent: i32 = @bitCast(i32, aExponent -% bExponent) +% scale;
// Align the significand of b as a Q63 fixed-point number in the range
// [1, 2.0) and get a Q64 approximate reciprocal using a small minimax
// polynomial approximation: reciprocal = 3/4 + 1/sqrt(2) - b/2. This
// is accurate to about 3.5 binary digits.
const q63b = @truncate(u64, bSignificand >> 49);
var recip64 = @as(u64, 0x7504f333F9DE6484) -% q63b;
// 0x7504f333F9DE6484 / 2^64 + 1 = 3/4 + 1/sqrt(2)
// Now refine the reciprocal estimate using a Newton-Raphson iteration:
//
// x1 = x0 * (2 - x0 * b)
//
// This doubles the number of correct binary digits in the approximation
// with each iteration.
var correction64: u64 = undefined;
correction64 = @truncate(u64, ~(@as(u128, recip64) *% q63b >> 64) +% 1);
recip64 = @truncate(u64, @as(u128, recip64) *% correction64 >> 63);
correction64 = @truncate(u64, ~(@as(u128, recip64) *% q63b >> 64) +% 1);
recip64 = @truncate(u64, @as(u128, recip64) *% correction64 >> 63);
correction64 = @truncate(u64, ~(@as(u128, recip64) *% q63b >> 64) +% 1);
recip64 = @truncate(u64, @as(u128, recip64) *% correction64 >> 63);
correction64 = @truncate(u64, ~(@as(u128, recip64) *% q63b >> 64) +% 1);
recip64 = @truncate(u64, @as(u128, recip64) *% correction64 >> 63);
correction64 = @truncate(u64, ~(@as(u128, recip64) *% q63b >> 64) +% 1);
recip64 = @truncate(u64, @as(u128, recip64) *% correction64 >> 63);
// The reciprocal may have overflowed to zero if the upper half of b is
// exactly 1.0. This would sabatoge the full-width final stage of the
// computation that follows, so we adjust the reciprocal down by one bit.
recip64 -%= 1;
// We need to perform one more iteration to get us to 112 binary digits;
// The last iteration needs to happen with extra precision.
const q127blo: u64 = @truncate(u64, bSignificand << 15);
var correction: u128 = undefined;
var reciprocal: u128 = undefined;
// NOTE: This operation is equivalent to __multi3, which is not implemented
// in some architechure
var r64q63: u128 = undefined;
var r64q127: u128 = undefined;
var r64cH: u128 = undefined;
var r64cL: u128 = undefined;
var dummy: u128 = undefined;
wideMultiply(u128, recip64, q63b, &dummy, &r64q63);
wideMultiply(u128, recip64, q127blo, &dummy, &r64q127);
correction = -%(r64q63 + (r64q127 >> 64));
const cHi = @truncate(u64, correction >> 64);
const cLo = @truncate(u64, correction);
wideMultiply(u128, recip64, cHi, &dummy, &r64cH);
wideMultiply(u128, recip64, cLo, &dummy, &r64cL);
reciprocal = r64cH + (r64cL >> 64);
// Adjust the final 128-bit reciprocal estimate downward to ensure that it
// is strictly smaller than the infinitely precise exact reciprocal. Because
// the computation of the Newton-Raphson step is truncating at every step,
// this adjustment is small; most of the work is already done.
reciprocal -%= 2;
// The numerical reciprocal is accurate to within 2^-112, lies in the
// interval [0.5, 1.0), and is strictly smaller than the true reciprocal
// of b. Multiplying a by this reciprocal thus gives a numerical q = a/b
// in Q127 with the following properties:
//
// 1. q < a/b
// 2. q is in the interval [0.5, 2.0)
// 3. The error in q is bounded away from 2^-113 (actually, we have a
// couple of bits to spare, but this is all we need).
// We need a 128 x 128 multiply high to compute q.
var quotient: u128 = undefined;
var quotientLo: u128 = undefined;
wideMultiply(u128, aSignificand << 2, reciprocal, "ient, "ientLo);
// Two cases: quotient is in [0.5, 1.0) or quotient is in [1.0, 2.0).
// In either case, we are going to compute a residual of the form
//
// r = a - q*b
//
// We know from the construction of q that r satisfies:
//
// 0 <= r < ulp(q)*b
//
// If r is greater than 1/2 ulp(q)*b, then q rounds up. Otherwise, we
// already have the correct result. The exact halfway case cannot occur.
// We also take this time to right shift quotient if it falls in the [1,2)
// range and adjust the exponent accordingly.
var residual: u128 = undefined;
var qb: u128 = undefined;
if (quotient < (implicitBit << 1)) {
wideMultiply(u128, quotient, bSignificand, &dummy, &qb);
residual = (aSignificand << 113) -% qb;
quotientExponent -%= 1;
} else {
quotient >>= 1;
wideMultiply(u128, quotient, bSignificand, &dummy, &qb);
residual = (aSignificand << 112) -% qb;
}
const writtenExponent = quotientExponent +% exponentBias;
if (writtenExponent >= maxExponent) {
// If we have overflowed the exponent, return infinity.
return @bitCast(f128, infRep | quotientSign);
} else if (writtenExponent < 1) {
if (writtenExponent == 0) {
// Check whether the rounded result is normal.
const round = @boolToInt((residual << 1) > bSignificand);
// Clear the implicit bit.
var absResult = quotient & significandMask;
// Round.
absResult += round;
if ((absResult & ~significandMask) > 0) {
// The rounded result is normal; return it.
return @bitCast(f128, absResult | quotientSign);
}
}
// Flush denormals to zero. In the future, it would be nice to add
// code to round them correctly.
return @bitCast(f128, quotientSign);
} else {
const round = @boolToInt((residual << 1) >= bSignificand);
// Clear the implicit bit
var absResult = quotient & significandMask;
// Insert the exponent
absResult |= @intCast(Z, writtenExponent) << significandBits;
// Round
absResult +%= round;
// Insert the sign and return
return @bitCast(f128, absResult | quotientSign);
}
}
test "import divtf3" {
_ = @import("divtf3_test.zig");
}
|
lib/std/special/compiler_rt/divtf3.zig
|
const std = @import("std");
const builtin = @import("builtin");
const riscv = std.Target.riscv;
pub const arch = comptime Arch.default();
pub const Arch = struct {
features: std.Target.Cpu.Feature.Set,
XLEN: type = u32,
XLENi: type = i32,
XLENd: type = u64,
XLENb: u8 = 32,
vendorId: u32 = 0,
archId: u32 = 0xF0000000,
implementationId: u32 = 0,
pub fn default() Arch {
var a = Arch {
.features = riscv.featureSet(&[_]riscv.Feature{ .c, .m })
};
return a;
}
};
pub const Memory = struct {
readFn: fn(usize, usize) u8,
writeFn: fn(usize, usize, u8) void,
userData: usize,
pub inline fn read(self: *Memory, address: usize) u8 {
return self.readFn(self.userData, address);
}
pub inline fn readi(self: *Memory, address: usize) i8 {
return @bitCast(i8, self.readFn(self.userData, address));
}
pub fn readIntLittle(self: *Memory, comptime T: type, address: usize) T {
const bytes = @divExact(@typeInfo(T).Int.bits, 8);
var data: [bytes]u8 = undefined;
var i: usize = 0;
while (i < data.len) : (i += 1) {
data[i] = self.read(address + i);
}
return std.mem.readIntLittle(T, &data);
}
pub inline fn write(self: *Memory, address: usize, value: u8) void {
self.writeFn(self.userData, address, value);
}
pub fn writeIntLittle(self: *Memory, comptime T: type, address: usize, value: T) void {
const bytes = @divExact(@typeInfo(T).Int.bits, 8);
var data: [bytes]u8 = undefined;
std.mem.writeIntLittle(T, &data, value);
for (data) |byte, i| {
self.write(address + i, byte);
}
}
fn readSlice(userdata: usize, addr: usize) u8 {
const slice = @intToPtr(*[]u8, userdata);
return slice.*[addr];
}
fn writeSlice(userdata: usize, addr: usize, value: u8) void {
var slice = @intToPtr(*[]u8, userdata);
slice.*[addr] = value;
}
pub fn fromSlice(slice: *[]u8) Memory {
return .{
.readFn = Memory.readSlice,
.writeFn = Memory.writeSlice,
.userData = @ptrToInt(slice)
};
}
};
pub const Hart = struct {
/// x0-31 registers
x: [32]arch.XLEN = [1]arch.XLEN{0} ** 32,
csr: [4096]arch.XLEN = [1]arch.XLEN{0} ** 4096,
ecallFn: ?fn(hart: *Hart) void = null,
pc: arch.XLEN = 0,
memory: Memory,
pub fn init(memory: Memory, pc: arch.XLEN, hartId: arch.XLEN) Hart {
var hart = Hart {
.memory = memory,
.pc = pc
};
hart.csr[0xF11] = arch.vendorId;
hart.csr[0xF12] = arch.archId;
hart.csr[0xF13] = arch.implementationId;
hart.csr[0xF14] = hartId;
// TODO: set misa, mstatus
return hart;
}
inline fn set_reg(self: *Hart, idx: u5, value: arch.XLEN) void {
if (idx != 0) self.x[idx] = value;
}
inline fn get_reg(self: *Hart, idx: u5) arch.XLEN {
return if (idx == 0) 0 else self.x[idx];
}
inline fn seti_reg(self: *Hart, idx: u5, value: arch.XLENi) void {
if (idx != 0) self.x[idx] = @bitCast(arch.XLEN, value);
}
inline fn geti_reg(self: *Hart, idx: u5) arch.XLENi {
return if (idx == 0) 0 else @bitCast(arch.XLENi, self.x[idx]);
}
fn invalidInstruction(self: *Hart) void {
@setCold(true);
const instr = self.memory.readIntLittle(u32, self.pc);
const opcode = @intCast(u7, instr & 0x7F);
std.log.err("Invalid instruction : {x}\n\tOperation Code: {b}\n\tPC: 0x{x}", .{instr, opcode, self.pc});
std.process.exit(1);
}
pub fn cycle(self: *Hart) void {
const instr = self.memory.readIntLittle(u32, self.pc);
const opcode = @intCast(u7, instr & 0x7F);
const rd = @intCast(u5, (instr & 0xF80) >> 7);
// Was it a compressed instruction ('C' extension) ? If yes, increment pc by 4, otherwise by 2
var compressed: bool = false;
// Was a jump taken ? If yes, do not increment pc
var jumped: bool = false;
//std.log.debug("instr = {x}", .{instr});
std.log.debug("opcode = {b}, pc = {x}", .{opcode, self.pc});
if (opcode == 0b0010011) { // OP-IMM
// I-type format
const imm = @bitCast(i12, @intCast(u12, instr >> 20));
const rs1 = @intCast(u5, (instr >> 15) & 0b11111);
const funct = (instr >> 12) & 0b111;
if (funct == 0b000) { // ADDI
std.log.debug("ADDI x{}, x{}, {}", .{rd, rs1, imm});
self.seti_reg(rd, self.geti_reg(rs1) +% imm);
} else if (funct == 0b001) { // SLLI
if ((@bitCast(u12, imm) & 0x800) == 0) { // SLLI
std.log.debug("SLLI x{}, x{}, {}", .{rd, rs1, imm});
self.set_reg(rd, self.get_reg(rs1) << @intCast(u5, imm));
} else {
self.invalidInstruction();
}
} else if (funct == 0b011) { // SLTIU
std.log.debug("SLTIU x{}, x{}, {}", .{rd, rs1, imm});
const immU = @bitCast(u12, imm);
self.set_reg(rd, if (self.get_reg(rs1) < immU) 1 else 0);
} else if (funct == 0b100) { // XORI
std.log.debug("XORI x{}, x{}, 0x{x}", .{rd, rs1, imm});
self.set_reg(rd, self.get_reg(rs1) ^ @bitCast(u12, imm));
} else if (funct == 0b101) { // SRLI / SRAI
if ((@bitCast(u12, imm) & 0x400) == 0) { // SRLI
std.log.debug("SRLI x{}, x{}, {}", .{rd, rs1, imm});
self.set_reg(rd, self.get_reg(rs1) >> @intCast(u5, imm));
} else {
std.log.debug("SRAI x{}, x{}, {}", .{rd, rs1, imm});
const shift = @truncate(u5, instr >> 20);
const val = self.geti_reg(rs1);
if (val < 0) {
//std.log.notice("val < 0 = {} = {}", .{val, @bitCast(u32, val)});
self.set_reg(rd, ~(~(self.get_reg(rs1)) >> shift));
} else {
self.seti_reg(rd, val >> shift);
}
}
} else if (funct == 0b110) { // ORI
const immU = @bitCast(u32, @intCast(i32, imm));
std.log.debug("ORI x{}, x{}, 0x{x}", .{rd, rs1, immU});
self.set_reg(rd, self.get_reg(rs1) | immU);
} else if (funct == 0b111) { // ANDI
const immU = @bitCast(u32, @intCast(i32, imm));
std.log.debug("ANDI x{}, x{}, 0x{x}", .{rd, rs1, immU});
self.set_reg(rd, self.get_reg(rs1) & immU);
} else {
std.log.err("OP-IMM funct = {b}", .{funct});
self.invalidInstruction();
}
} else if (opcode == 0b0011011) { // OP-IMM-32
const imm = @bitCast(i12, @intCast(u12, instr >> 20));
const rs1 = @intCast(u5, (instr >> 15) & 0b11111);
const funct = (instr >> 12) & 0b111;
if (funct == 0b000) { // ADDIW
std.log.debug("ADDI x{}, x{}, {}", .{rd, rs1, imm});
self.seti_reg(rd, @truncate(i32, self.geti_reg(rs1)) +% imm);
} else {
std.log.err("OP-IMM-32 funct = {b}", .{funct});
self.invalidInstruction();
}
} else if (opcode == 0b0110011) { // OP
const rs1 = @intCast(u5, (instr >> 15) & 0b11111);
const rs2 = @intCast(u5, (instr >> 20) & 0b11111);
const funct = (((instr >> 25) & 0x7F) << 3) | ((instr >> 12) & 0b111);
if (funct == 0b000) { // ADD
std.log.debug("ADD x{}, x{}, x{}", .{rd, rs1, rs2});
self.set_reg(rd, self.get_reg(rs1) +% self.get_reg(rs2));
} else if (funct == 0b001) { // SLL
std.log.debug("SLL x{}, x{}, x{}", .{rd, rs1, rs2});
const shift = @truncate(u5, self.get_reg(rs2));
self.set_reg(rd, self.get_reg(rs1) << shift);
} else if (funct == 0b011) { // SLTU
std.log.debug("SLTU x{}, x{}, x{}", .{rd, rs1, rs2});
self.set_reg(rd, if (self.get_reg(rs1) < self.get_reg(rs2)) 1 else 0);
} else if (funct == 0b100) { // XOR
std.log.debug("XOR x{}, x{}, x{}", .{rd, rs1, rs2});
self.set_reg(rd, self.get_reg(rs1) ^ self.get_reg(rs2));
} else if (funct == 0b101) { // SRL
std.log.debug("SRL x{}, x{}, x{}", .{rd, rs1, rs2});
const shift = @truncate(u5, self.get_reg(rs2));
self.set_reg(rd, self.get_reg(rs1) >> shift);
} else if (funct == 0b110) { // OR
std.log.debug("OR x{}, x{}, x{}", .{rd, rs1, rs2});
self.set_reg(rd, self.get_reg(rs1) | self.get_reg(rs2));
} else if (funct == 0b111) { // AND
std.log.debug("AND x{}, x{}, x{}", .{rd, rs1, rs2});
self.set_reg(rd, self.get_reg(rs1) & self.get_reg(rs2));
} else if (comptime riscv.featureSetHas(arch.features, .m) and funct == 0b1000) { // MUL
std.log.debug("MUL x{}, x{}, x{}", .{rd, rs1, rs2});
self.set_reg(rd, self.get_reg(rs1) *% self.get_reg(rs2));
} else if (comptime riscv.featureSetHas(arch.features, .m) and funct == 0b1011) { // MULHU
std.log.debug("MULHU x{}, x{}, x{}", .{rd, rs1, rs2});
const multiplier = @intCast(arch.XLENd, self.get_reg(rs1));
const multiplicand = @intCast(arch.XLENd, self.get_reg(rs2));
const result = @intCast(arch.XLEN, ((multiplier * multiplicand) & (std.math.maxInt(arch.XLEN) << arch.XLENb)) >> arch.XLENb);
self.set_reg(rd, result);
} else if (funct == 0b0100000000) { // SUB
std.log.debug("SUB x{}, x{}, x{}", .{rd, rs1, rs2});
self.set_reg(rd, self.get_reg(rs1) -% self.get_reg(rs2));
} else {
self.invalidInstruction();
}
} else if (opcode == 0b0000011) { // LOAD
// I-type format
const offset = @bitCast(i12, @intCast(u12, instr >> 20));
const rs1 = @truncate(u5, (instr >> 15));
const funct = (instr >> 12) & 0b111;
const addr = @bitCast(u32, self.geti_reg(rs1) +% offset);
if (funct == 0) { // LB
std.log.debug("LB x{}, x{}, {}", .{rd, rs1, offset});
self.seti_reg(rd, @intCast(i32, self.memory.readi(addr)));
} else if (funct == 1) { // LH
std.log.debug("LH x{}, x{}, {}", .{rd, rs1, offset});
self.seti_reg(rd, @intCast(i32, self.memory.readIntLittle(i16, addr)));
} else if (funct == 2) { // LW
std.log.debug("LW x{}, x{}, {}", .{rd, rs1, offset});
self.set_reg(rd, self.memory.readIntLittle(u32, addr));
} else if (funct == 4) { // LBU
std.log.debug("LBU x{}, x{}, 0x{x}", .{rd, rs1, offset});
self.set_reg(rd, self.memory.read(addr));
} else if (funct == 5) { // LHU
std.log.debug("LHU x{}, x{}, 0x{x}", .{rd, rs1, offset});
self.set_reg(rd, self.memory.readIntLittle(u16, addr));
} else {
self.invalidInstruction();
}
} else if (opcode == 0b0100011) { // STORE
const funct = (instr >> 12) & 0b111;
const rs1 = @intCast(u5, (instr >> 15) & 0b11111);
const rs2 = @intCast(u5, (instr >> 20) & 0b11111);
const imm11_5 = (instr >> 25) & 0b1111111;
const imm4_0 = (instr >> 7) & 0b11111;
const offset = @bitCast(i12, @intCast(u12, (imm11_5 << 5) | imm4_0));
const addr = @bitCast(u32, @bitCast(i32, self.get_reg(rs1)) +% offset);
if (funct == 0) { // SB
std.log.debug("SB {}(x{}), x{}", .{offset, rs1, rs2});
self.memory.write(addr, @intCast(u8, self.get_reg(rs2) & 0xFF));
} else if (funct == 1) { // SH
std.log.debug("SH {}(x{}), x{}", .{offset, rs1, rs2});
self.memory.writeIntLittle(u16, addr, @intCast(u16, self.get_reg(rs2) & 0xFFFF));
} else if (funct == 2) { // SW
std.log.debug("SW {}(x{}), x{}", .{offset, rs1, rs2});
self.memory.writeIntLittle(u32, addr, self.get_reg(rs2));
} else {
self.invalidInstruction();
}
} else if (opcode == 0b1100011) { // BRANCH
const funct = (instr >> 12) & 0b111;
const rs1 = @intCast(u5, (instr >> 15) & 0b11111);
const rs2 = @intCast(u5, (instr >> 20) & 0b11111);
const imm11 = (instr >> 7) & 0b1;
const imm12 = (instr >> 30) & 0b1;
const imm4_1 = (instr >> 8) & 0b1111;
const imm10_5 = (instr >> 25) & 0b111111;
const offset = @bitCast(i13, @intCast(u13, (imm12 << 12) | (imm11 << 11) | (imm10_5 << 5) | (imm4_1 << 1)));
const newPc = @intCast(u32, @intCast(i33, self.pc) + @intCast(i33, offset));
if (funct == 0b000) { // BEQ
std.log.debug("BEQ x{}, x{}, 0x{x}", .{rs1, rs2, newPc});
if (self.get_reg(rs1) == self.get_reg(rs2)) {
self.pc = newPc;
jumped = true;
}
} else if (funct == 0b001) { // BNE
std.log.debug("BNE x{}, x{}, 0x{x}", .{rs1, rs2, newPc});
if (self.get_reg(rs1) != self.get_reg(rs2)) {
self.pc = newPc;
jumped = true;
}
} else if (funct == 0b100) { // BLT
std.log.debug("BLT x{}, x{}, 0x{x}", .{rs1, rs2, newPc});
if (self.geti_reg(rs1) < self.geti_reg(rs2)) {
self.pc = newPc;
jumped = true;
}
} else if (funct == 0b101) { // BGE
std.log.debug("BGE x{}, x{}, 0x{x}", .{rs1, rs2, newPc});
if (self.geti_reg(rs1) > self.geti_reg(rs2)) {
self.pc = newPc;
jumped = true;
}
} else if (funct == 0b110) { // BLTU
std.log.debug("BLTU x{}, x{}, 0x{x} ({} < {} ?)", .{rs1, rs2, newPc, self.get_reg(rs1), self.get_reg(rs2)});
if (self.get_reg(rs1) < self.get_reg(rs2)) {
self.pc = newPc;
jumped = true;
}
} else if (funct == 0b111) { // BGEU
std.log.debug("BGEU x{}, x{}, 0x{x}", .{rs1, rs2, newPc});
if (self.get_reg(rs1) > self.get_reg(rs2)) {
self.pc = newPc;
jumped = true;
}
} else {
self.invalidInstruction();
}
} else if (comptime riscv.featureSetHas(arch.features, .c) and (opcode & 0x3) == 0b01) {
const funct = (instr >> 13) & 0b111;
if (funct == 0b000) { // C.ADDI
const imm5 = (instr >> 12) & 0b1;
const imm = @bitCast(i6, @intCast(u6, ((instr >> 2) & 0b11111) + (imm5 << 5)));
std.log.debug("C.ADDI x{}, x{}, {}", .{rd, rd, imm});
self.seti_reg(rd, self.geti_reg(rd) +% imm);
} else if (funct == 0b010) { // C.LI
const imm40 = (instr >> 2) & 0b11111;
const imm5 = (instr >> 11) & 0b1;
const imm = @bitCast(i6, @intCast(u6, (imm5 << 4) | imm40));
std.log.debug("C.LI x{}, {} = ADDI x{}, x0, {}", .{rd, imm, rd, imm});
self.seti_reg(rd, imm);
} else if (funct == 0b011) {
if (rd == 2) { // C.ADDI16SP
const imm9 = (instr >> 12) & 0b1;
const imm5 = (instr >> 2) & 0b1;
const imm87 = (instr >> 3) & 0b11;
const imm6 = (instr >> 5) & 0b1;
const imm4 = (instr >> 6) & 0b1;
const imm = @bitCast(i10, @intCast(u10, (imm9 << 9) | (imm87 << 7) | (imm6 << 6) | (imm5 << 5) | (imm4 << 4)));
std.log.debug("C.ADDI16SP {} = ADDI x2, x2, {}", .{imm, imm});
self.seti_reg(2, self.geti_reg(2) + imm);
} else { // C.LUI
const imm40 = (instr >> 2) & 0b11111;
const imm5 = (instr >> 11) & 0b1;
const imm = ((imm5 << 4) | imm40) << 12;
std.log.debug("C.LUI x{}, {}", .{rd, imm});
self.set_reg(rd, imm);
}
} else if (funct == 0b100) {
const funct2 = (instr >> 10) & 0b11;
const imm5 = (instr >> 12) & 0b1;
const imm40 = (instr >> 2) & 0b11111;
const imm = @intCast(u6, (imm5 << 5) | imm40);
const rD = @intCast(u5, (instr >> 7) & 0b111) + 8;
if (funct2 == 0b00 and imm != 0) { // C.SRLI
std.log.debug("C.SRLI x{}, 0x{x} = SRLI x{}, x{}, {}", .{rD, imm, rD, rD, imm});
self.set_reg(rD, self.get_reg(rD) >> @intCast(u5, imm));
} else if (funct2 == 0b10) { // C.ANDI
const val = @bitCast(u32, @intCast(i32, @bitCast(i6, imm)));
std.log.debug("C.ANDI x{}, 0x{x}", .{rD, val});
self.set_reg(rD, self.get_reg(rD) & val);
} else if (funct2 == 0b11) {
const functs = (instr >> 5) & 0b11;
const rs2 = @intCast(u5, (instr >> 2) & 0b111) + 8;
if (imm5 == 0 and functs == 0b00) { // C.SUB
std.log.debug("C.SUB x{}, x{} = SUB x{}, x{}, x{}", .{rD, rs2, rD, rD, rs2});
self.set_reg(rD, self.get_reg(rD) -% self.get_reg(rs2));
} else if (functs == 0b01) {
if (imm5 == 1) {
std.log.debug("C.ADDW TODO", .{});
self.invalidInstruction();
} else {
std.log.debug("C.XOR x{}, x{} = XOR x{}, x{}, x{}", .{rD, rs2, rD, rD, rs2});
self.set_reg(rD, self.get_reg(rD) ^ self.get_reg(rs2));
}
} else if (functs == 0b10) { // C.OR
std.log.debug("C.OR x{}, x{} = OR x{}, x{}, x{}", .{rD, rs2, rD, rD, rs2});
self.set_reg(rD, self.get_reg(rD) | self.get_reg(rs2));
} else if (functs == 0b11) { // C.AND
std.log.debug("C.AND x{}, x{} = AND x{}, x{}, x{}", .{rD, rs2, rD, rD, rs2});
self.set_reg(rD, self.get_reg(rD) & self.get_reg(rs2));
} else {
std.log.err("Unknown compressed opcode, op = 01, funct = {b}, functs = {b}", .{funct, functs});
self.invalidInstruction();
}
} else {
std.log.err("Unknown compressed opcode, op = 01, funct = {b}, funct2 = {b}", .{funct, funct2});
self.invalidInstruction();
}
} else if (funct == 0b101) { // C.J
const imm11 = (instr >> 12) & 0b1;
const imm4 = (instr >> 11) & 0b1;
const imm98 = (instr >> 9) & 0b11;
const imm10 = (instr >> 8) & 0b1;
const imm6 = (instr >> 7) & 0b1;
const imm7 = (instr >> 6) & 0b1;
const imm31 = (instr >> 3) & 0b111;
const imm5 = (instr >> 2) & 0b1;
const imm = @bitCast(i12, @intCast(u12, (imm11 << 11) | (imm10 << 10) | (imm98 << 8) |
(imm7 << 7) | (imm6 << 6) | (imm5 << 5) | (imm4 << 4) | (imm31 << 1)));
const newPc = @intCast(u32, @intCast(i33, self.pc) + @intCast(i33, imm));
std.log.debug("C.J 0x{x} = JAL x0, 0x{x}", .{newPc, newPc});
self.pc = newPc;
jumped = true;
} else if (funct == 0b111) { // C.BNEZ
const rs1 = (rd & 0b111) + 8; // @intCast(u5, (instr >> 7) & 0b111) + 8;
const imm5 = (instr >> 2) & 0b1;
const imm21 = (instr >> 3) & 0b11;
const imm76 = (instr >> 5) & 0b11;
const imm43 = (instr >> 10) & 0b11;
const imm8 = (instr >> 12) & 0b1;
const imm = @bitCast(i8, @intCast(u8, (imm76 << 6) | (imm5 << 5) | (imm43 << 3) | (imm21 << 1)));
const newPc = @intCast(u32, @intCast(i33, self.pc) + @intCast(i33, imm));
std.log.debug("C.BNEZ x{}, 0x{x} = BNE x{}, x0, 0x{x}", .{rs1, newPc, rs1, newPc});
if (self.get_reg(rs1) != 0) {
jumped = true;
self.pc = newPc;
}
} else if (funct == 0b110) { // C.BEQZ
const rs1 = (rd & 0b111) + 8; // @intCast(u5, (instr >> 7) & 0b111) + 8;
const imm5 = (instr >> 2) & 0b1;
const imm21 = (instr >> 3) & 0b11;
const imm76 = (instr >> 5) & 0b11;
const imm43 = (instr >> 10) & 0b11;
const imm8 = (instr >> 12) & 0b1;
const imm = @bitCast(i8, @intCast(u8, (imm76 << 6) | (imm5 << 5) | (imm43 << 3) | (imm21 << 1)));
const newPc = @intCast(u32, @intCast(i33, self.pc) + @intCast(i33, imm));
std.log.debug("C.BEQZ x{}, 0x{x} = BEQ x{}, x0, 0x{x}", .{rs1, newPc, rs1, newPc});
if (self.get_reg(rs1) == 0) {
jumped = true;
self.pc = newPc;
}
}else {
std.log.err("Unknown compressed opcode, op = 01, funct = {b}", .{funct});
self.invalidInstruction();
}
compressed = true;
} else if (comptime riscv.featureSetHas(arch.features, .c) and (opcode & 0x3) == 0b00) {
const funct = (instr >> 13) & 0b111;
if (funct == 0b000) { // C.ADDI4SPN
const imm3 = (instr >> 5) & 0b1;
const imm2 = (instr >> 6) & 0b1;
const imm96 = (instr >> 7) & 0b1111;
const imm54 = (instr >> 11) & 0b11;
const imm = (imm96 << 6) | (imm54 << 4) | (imm3 << 3) | (imm2 << 2);
const rD = @intCast(u5, (instr >> 2) & 0b111) + 8;
std.log.debug("C.ADDI4SPN x{}, {} = ADDI x{}, x2, {}", .{rD, imm, rD, imm});
self.set_reg(rD, self.get_reg(2) +% imm);
} else if (funct == 0b010) { // C.LW
const rs1 = @intCast(u5, (instr >> 7) & 0b111) + 8;
const rD = @intCast(u5, (instr >> 2) & 0b111) + 8;
const imm2 = (instr >> 6) & 0b1;
const imm6 = (instr >> 5) & 0b1;
const imm53 = (instr >> 10) & 0b111;
const imm = (imm6 << 6) | (imm53 << 3) | (imm2 << 2);
const addr = self.get_reg(rs1) + imm;
std.log.debug("C.LW x{}, {}(x{})", .{rD, imm, rs1});
self.set_reg(rD, self.memory.readIntLittle(u32, addr));
} else if (funct == 0b110) { // C.SW
const rs1 = rd + 8; // @intCast(u5, (instr >> 7) & 0b111) + 8;
const rs2 = @intCast(u5, (instr >> 2) & 0b111) + 8;
const imm2 = (instr >> 6) & 0b1;
const imm6 = (instr >> 5) & 0b1;
const imm53 = (instr >> 10) & 0b111;
const imm = (imm6 << 6) | (imm53 << 3) | (imm2 << 2);
const addr = self.get_reg(rs1) + imm;
std.log.debug("C.SW x{}, {}(x{})", .{rs2, imm, rs1});
self.memory.writeIntLittle(u32, addr, self.get_reg(rs2));
} else {
std.log.err("Unknown compressed opcode, op = 00, funct = {b}", .{funct});
self.invalidInstruction();
}
compressed = true;
} else if (comptime riscv.featureSetHas(arch.features, .c) and (opcode & 0x3) == 0b10) {
const funct = (instr >> 13) & 0b111;
if (funct == 0b000) { // C.SLLI
const imm5 = (instr >> 12) & 0b1;
const imm40 = (instr >> 2) & 0b11111;
const imm = @intCast(u5, (imm5 << 5) | imm40);
const rD = @intCast(u5, (instr >> 7) & 0b111) + 8;
std.log.debug("C.SLLI x{}, {} = SLLI x{}, x{}, {}", .{rD, imm, rD, rD, imm});
self.set_reg(rD, self.get_reg(rD) << imm);
} else if (funct == 0b110) { // C.SWSP
const rs2 = @intCast(u5, (instr >> 2) & 0b11111);
const imm76 = (instr >> 7) & 0b11;
const imm52 = (instr >> 9) & 0b1111;
const imm = (imm76 << 6) | (imm52 << 2);
std.log.debug("C.SWSP x{}, {} = SW x{}, {}(x2)", .{rs2, imm, rs2, imm});
self.memory.writeIntLittle(u32, self.get_reg(2) + imm, self.get_reg(rs2));
} else if (funct == 0b010) { // C.LWSP
const imm76 = (instr >> 2) & 0b11;
const imm5 = (instr >> 12) & 0b1;
const imm42 = (instr >> 4) & 0b111;
const imm = (imm76 << 6) | (imm5 << 5) | (imm42 << 2);
std.log.debug("C.LWSP x{}, {} {b} {b} {b} = LW x{}, {}(x2)", .{rd, imm, imm76, imm5, imm42, rd, imm});
self.set_reg(rd, self.memory.readIntLittle(u32, self.get_reg(2) + imm));
} else if (funct == 0b100) {
const funct4 = (instr >> 12) & 0b1;
if (funct4 == 0) { // C.MV
const rs2 = @intCast(u5, (instr >> 2) & 0b11111);
if (rs2 == 0) {
const rs1 = rd; // = @intCast(u5, (instr >> 7) & 0b11111)
if (rs1 != 0) { // C.JR
std.log.debug("C.JR x{} = JALR x0, 0(x{})", .{rs1, rs1});
self.pc = self.get_reg(rs1);
jumped = true;
} else {
std.log.err("Invalid compressed opcode, op = 10, funct = {b}", .{funct});
self.invalidInstruction();
}
} else { // C.MV
std.log.debug("C.MV x{}, x{} = ADD x{}, x0, x{}", .{rd, rs2, rd, rs2});
self.set_reg(rd, self.get_reg(rs2));
}
} else {
const rs2 = @intCast(u5, (instr >> 2) & 0b11111);
if (rs2 == 0) {
const rs1 = rd; // = @intCast(u5, (instr >> 7) & 0b11111)
if (rs1 == 0) {
std.log.err("TODO: C.EBREAK", .{});
@breakpoint();
//std.process.exit(0);
} else {
std.log.err("TODO: C.JALR", .{});
}
} else { // C.ADD
std.log.debug("C.ADD x{}, x{} = ADD x{}, x{}, x{}", .{rd, rs2, rd, rd, rs2});
self.set_reg(rd, self.get_reg(rd) +% self.get_reg(rs2));
}
}
} else {
std.log.err("Unknown compressed opcode, op = 10, funct = {b}", .{funct});
self.invalidInstruction();
}
compressed = true;
} else if (opcode == 0b1101111) { // JAL
const imm10_1 = (instr >> 21) & 0b1111111111;
const imm11 = (instr >> 19) & 0b1;
const imm19_12 = (instr >> 12) & 0b11111111;
const imm20 = (instr >> 30) & 0b1;
const imm = @bitCast(i21, @intCast(u21, (imm20 << 20) | (imm19_12 << 12) | (imm11 << 11) | (imm10_1 << 1)));
const newPc = @intCast(u32, @intCast(i33, self.pc) + @intCast(i33, imm));
std.log.debug("JAL x{}, 0x{x}", .{rd, imm});
self.set_reg(rd, self.pc + 4);
self.pc = newPc;
jumped = true;
} else if (opcode == 0b1100111) { // JALR
const imm = @bitCast(i12, @intCast(u12, (instr >> 20)));
const rs1 = @intCast(u5, (instr >> 15) & 0b11111);
const newPc = @intCast(u32, self.geti_reg(rs1) +% imm);
std.log.debug("JALR x{}, {}(x{})", .{rd, imm, rs1});
self.set_reg(rd, self.pc + 4);
self.pc = newPc;
jumped = true;
} else if (opcode == 0b0010111) { // AUIPC
// U-type format
const offset = @bitCast(i32, @intCast(u32, instr & 0xFFFFF000));
std.log.debug("AUIPC x{}, {}", .{rd, offset});
self.seti_reg(rd, @bitCast(arch.XLENi, self.pc) +% offset);
} else if (opcode == 0b0110111) { // LUI
// U-type format
const imm = @intCast(u32, instr & 0xFFFFF000);
std.log.debug("LUI x{}, 0x{x}", .{rd, (imm>>12)});
self.set_reg(rd, imm);
} else if (opcode == 0b1110011) { // SYSTEM
const bit = @truncate(u1, (instr >> 20));
if (bit == 0) { // ECALL
std.log.debug("ECALL", .{});
if (self.ecallFn) |func| {
func(self);
} else {
std.log.warn("Missing ECALL handler", .{});
}
} else { // EBREAK
std.log.notice("EBREAK", .{});
@breakpoint(); // TODO: pause and print info on the emulated CPU
}
}
else {
self.invalidInstruction();
}
self.pc += if (jumped) @as(arch.XLEN, 0) else if (compressed) @as(arch.XLEN, 2) else @as(arch.XLEN, 4);
}
};
|
src/cpu.zig
|
const os = @import("root").os;
const std = @import("std");
pub const paging = @import("paging.zig");
pub const thread = @import("thread.zig");
pub const InterruptFrame = interrupts.InterruptFrame;
pub const InterruptState = interrupts.InterruptState;
pub const get_and_disable_interrupts = interrupts.get_and_disable_interrupts;
pub const set_interrupts = interrupts.set_interrupts;
const interrupts = @import("interrupts.zig");
const pmm = os.memory.pmm;
const bf = os.lib.bitfields;
const assert = std.debug.assert;
pub fn msr(comptime T: type, comptime name: []const u8) type {
return struct {
pub fn read() T {
return asm volatile(
"MRS %[out], " ++ name
: [out]"=r"(-> T)
);
}
pub fn write(val: T) void {
asm volatile(
"MSR " ++ name ++ ", %[in]"
:
: [in]"r"(val)
);
}
};
}
pub fn spin_hint() void {
asm volatile("YIELD");
}
pub fn allowed_mapping_levels() usize {
return 2;
}
pub fn platform_init() !void {
try os.platform.acpi.init_acpi();
try os.platform.pci.init_pci();
}
pub fn ap_init() noreturn {
os.memory.paging.kernel_context.apply();
interrupts.install_vector_table();
const cpu = os.platform.thread.get_current_cpu();
interrupts.set_interrupt_stack(cpu.int_stack);
asm volatile(
\\BR %[dest]
:
: [stack] "{SP}" (cpu.sched_stack)
, [dest] "r" (ap_init_stage2)
);
unreachable;
}
fn ap_init_stage2() noreturn {
_ = @atomicRmw(usize, &os.platform.smp.cpus_left, .Sub, 1, .AcqRel);
// Wait for tasks
asm volatile("SVC #'B'");
unreachable;
}
pub fn clock() usize {
return asm volatile("MRS %[out], CNTPCT_EL0" : [out] "=r" (-> usize));
}
pub fn debugputch(val: u8) void {
}
pub fn bsp_pre_scheduler_init() void {
const cpu = os.platform.thread.get_current_cpu();
interrupts.set_interrupt_stack(cpu.int_stack);
interrupts.install_vector_table();
}
pub fn platform_early_init() void {
os.platform.smp.prepare();
os.memory.paging.init();
}
pub fn await_interrupt() void {
asm volatile(
\\ MSR DAIFCLR, 0x2
\\ WFI
\\ MSR DAIFSET, 0x2
:
:
: "memory"
);
}
pub fn prepare_paging() !void {
}
|
src/platform/aarch64/aarch64.zig
|
pub const Mnemonic = enum {
pub const count: usize = @enumToInt(Mnemonic._mnemonic_final);
pub const first: Mnemonic = Mnemonic.AAA;
pub const last: Mnemonic = Mnemonic.XTEST;
AAA,
AAD,
AAM,
AAS,
ADC,
ADCX,
ADD,
ADDPD,
ADDPS,
ADDSD,
ADDSS,
ADDSUBPD,
ADDSUBPS,
ADOX,
AESDEC,
AESDECLAST,
AESENC,
AESENCLAST,
AESIMC,
AESKEYGENASSIST,
AND,
ANDN,
ANDNPD,
ANDNPS,
ANDPD,
ANDPS,
ARPL,
BEXTR,
BLCFILL,
BLCI,
BLCIC,
BLCMSK,
BLCS,
BLENDPD,
BLENDPS,
BLENDVPD,
BLENDVPS,
BLSFILL,
BLSI,
BLSIC,
BLSMSK,
BLSR,
BNDCL,
BNDCN,
BNDCU,
BNDLDX,
BNDMK,
BNDMOV,
BNDSTX,
BOUND,
BSF,
BSR,
BSWAP,
BT,
BTC,
BTR,
BTS,
BZHI,
CALL,
CBW,
CDQ,
CDQE,
CLAC,
CLC,
CLD,
CLDEMOTE,
CLFLUSH,
CLFLUSHOPT,
CLI,
CLRSSBSY,
CLTS,
CLWB,
CMC,
CMOVA,
CMOVAE,
CMOVB,
CMOVBE,
CMOVC,
CMOVE,
CMOVG,
CMOVGE,
CMOVL,
CMOVLE,
CMOVNA,
CMOVNAE,
CMOVNB,
CMOVNBE,
CMOVNC,
CMOVNE,
CMOVNG,
CMOVNGE,
CMOVNL,
CMOVNLE,
CMOVNO,
CMOVNP,
CMOVNS,
CMOVNZ,
CMOVO,
CMOVP,
CMOVPE,
CMOVPO,
CMOVS,
CMOVZ,
CMP,
CMPPD,
CMPPS,
CMPS,
CMPSB,
CMPSD,
CMPSQ,
CMPSS,
CMPSW,
CMPXCHG,
CMPXCHG16B,
CMPXCHG8B,
COMISD,
COMISS,
CPUID,
CQO,
CRC32,
CVTDQ2PD,
CVTDQ2PS,
CVTPD2DQ,
CVTPD2PI,
CVTPD2PS,
CVTPI2PD,
CVTPI2PS,
CVTPS2DQ,
CVTPS2PD,
CVTPS2PI,
CVTSD2SI,
CVTSD2SS,
CVTSI2SD,
CVTSI2SS,
CVTSS2SD,
CVTSS2SI,
CVTTPD2DQ,
CVTTPD2PI,
CVTTPS2DQ,
CVTTPS2PI,
CVTTSD2SI,
CVTTSS2SI,
CWD,
CWDE,
DAA,
DAS,
DEC,
DIV,
DIVPD,
DIVPS,
DIVSD,
DIVSS,
DPPD,
DPPS,
EMMS,
ENDBR32,
ENDBR64,
ENTER,
ENTERD,
ENTERQ,
ENTERW,
EXTRACTPS,
EXTRQ,
F2XM1,
FABS,
FADD,
FADDP,
FBLD,
FBSTP,
FCHS,
FCLEX,
FCMOVB,
FCMOVBE,
FCMOVE,
FCMOVNB,
FCMOVNBE,
FCMOVNE,
FCMOVNU,
FCMOVU,
FCOM,
FCOMI,
FCOMIP,
FCOMP,
FCOMPP,
FCOS,
FDECSTP,
FDIV,
FDIVP,
FDIVR,
FDIVRP,
FFREE,
FIADD,
FICOM,
FICOMP,
FIDIV,
FIDIVR,
FILD,
FIMUL,
FINCSTP,
FINIT,
FIST,
FISTP,
FISTTP,
FISUB,
FISUBR,
FLD,
FLD1,
FLDCW,
FLDENV,
FLDENVD,
FLDENVW,
FLDL2E,
FLDL2T,
FLDLG2,
FLDLN2,
FLDPI,
FLDZ,
FMUL,
FMULP,
FNCLEX,
FNINIT,
FNOP,
FNSAVE,
FNSAVED,
FNSAVEW,
FNSTCW,
FNSTENV,
FNSTENVD,
FNSTENVW,
FNSTSW,
FPATAN,
FPREM,
FPREM1,
FPTAN,
FRNDINT,
FRSTOR,
FRSTORD,
FRSTORW,
FSAVE,
FSAVED,
FSAVEW,
FSCALE,
FSIN,
FSINCOS,
FSQRT,
FST,
FSTCW,
FSTENV,
FSTENVD,
FSTENVW,
FSTP,
FSTSW,
FSUB,
FSUBP,
FSUBR,
FSUBRP,
FTST,
FUCOM,
FUCOMI,
FUCOMIP,
FUCOMP,
FUCOMPP,
FWAIT,
FXAM,
FXCH,
FXRSTOR,
FXRSTOR64,
FXSAVE,
FXSAVE64,
FXTRACT,
FYL2X,
FYL2XP1,
GF2P8AFFINEINVQB,
GF2P8AFFINEQB,
GF2P8MULB,
HADDPD,
HADDPS,
HLT,
HSUBPD,
HSUBPS,
IBTS,
ICEBP,
IDIV,
IMUL,
IN,
INC,
INCSSPD,
INCSSPQ,
INS,
INSB,
INSD,
INSERTPS,
INSERTQ,
INSW,
INT,
INT1,
INT3,
INTO,
INVD,
INVLPG,
INVPCID,
IRET,
IRETD,
IRETQ,
IRETW,
JA,
JAE,
JB,
JBE,
JC,
JCXZ,
JE,
JECXZ,
JG,
JGE,
JL,
JLE,
JMP,
JNA,
JNAE,
JNB,
JNBE,
JNC,
JNE,
JNG,
JNGE,
JNL,
JNLE,
JNO,
JNP,
JNS,
JNZ,
JO,
JP,
JPE,
JPO,
JRCXZ,
JS,
JZ,
KADDB,
KADDD,
KADDQ,
KADDW,
KANDB,
KANDD,
KANDNB,
KANDND,
KANDNQ,
KANDNW,
KANDQ,
KANDW,
KMOVB,
KMOVD,
KMOVQ,
KMOVW,
KNOTB,
KNOTD,
KNOTQ,
KNOTW,
KORB,
KORD,
KORQ,
KORTESTB,
KORTESTD,
KORTESTQ,
KORTESTW,
KORW,
KSHIFTLB,
KSHIFTLD,
KSHIFTLQ,
KSHIFTLW,
KSHIFTRB,
KSHIFTRD,
KSHIFTRQ,
KSHIFTRW,
KTESTB,
KTESTD,
KTESTQ,
KTESTW,
KUNPCKBW,
KUNPCKDQ,
KUNPCKWD,
KXNORB,
KXNORD,
KXNORQ,
KXNORW,
KXORB,
KXORD,
KXORQ,
KXORW,
LAHF,
LAR,
LDDQU,
LDMXCSR,
LDS,
LEA,
LEAVE,
LEAVED,
LEAVEQ,
LEAVEW,
LES,
LFENCE,
LFS,
LGDT,
LGS,
LIDT,
LLDT,
LLWPCB,
LMSW,
LOADALL,
LOADALLD,
LOCK,
LODS,
LODSB,
LODSD,
LODSQ,
LODSW,
LOOP,
LOOPD,
LOOPE,
LOOPED,
LOOPEW,
LOOPNE,
LOOPNED,
LOOPNEW,
LOOPW,
LSL,
LSS,
LTR,
LWPINS,
LWPVAL,
LZCNT,
MASKMOVDQU,
MASKMOVQ,
MAXPD,
MAXPS,
MAXSD,
MAXSS,
MFENCE,
MINPD,
MINPS,
MINSD,
MINSS,
MONITOR,
MOV,
MOVAPD,
MOVAPS,
MOVBE,
MOVD,
MOVDDUP,
MOVDIR64B,
MOVDIRI,
MOVDQ2Q,
MOVDQA,
MOVDQU,
MOVHLPS,
MOVHPD,
MOVHPS,
MOVLHPS,
MOVLPD,
MOVLPS,
MOVMSKPD,
MOVMSKPS,
MOVNTDQ,
MOVNTDQA,
MOVNTI,
MOVNTPD,
MOVNTPS,
MOVNTQ,
MOVNTSD,
MOVNTSS,
MOVQ,
MOVQ2DQ,
MOVS,
MOVSB,
MOVSD,
MOVSHDUP,
MOVSLDUP,
MOVSQ,
MOVSS,
MOVSW,
MOVSX,
MOVSXD,
MOVUPD,
MOVUPS,
MOVZX,
MPSADBW,
MUL,
MULPD,
MULPS,
MULSD,
MULSS,
MULX,
MWAIT,
NEG,
NOP,
NOT,
OR,
ORPD,
ORPS,
OUT,
OUTS,
OUTSB,
OUTSD,
OUTSW,
PABSB,
PABSD,
PABSW,
PACKSSDW,
PACKSSWB,
PACKUSDW,
PACKUSWB,
PADDB,
PADDD,
PADDQ,
PADDSB,
PADDSW,
PADDUSB,
PADDUSW,
PADDW,
PALIGNR,
PAND,
PANDN,
PAUSE,
PAVGB,
PAVGW,
PBLENDVB,
PBLENDW,
PCLMULQDQ,
PCMPEQB,
PCMPEQD,
PCMPEQQ,
PCMPEQW,
PCMPESTRI,
PCMPESTRM,
PCMPGTB,
PCMPGTD,
PCMPGTW,
PCMPISTRI,
PCMPISTRM,
PCOMMIT,
PDEP,
PEXT,
PEXTRB,
PEXTRD,
PEXTRQ,
PEXTRW,
PHADDD,
PHADDSW,
PHADDW,
PHMINPOSUW,
PHSUBD,
PHSUBSW,
PHSUBW,
PINSRB,
PINSRD,
PINSRQ,
PINSRW,
PMADDUBSW,
PMADDWD,
PMAXSB,
PMAXSD,
PMAXSW,
PMAXUB,
PMAXUD,
PMAXUW,
PMINSB,
PMINSD,
PMINSW,
PMINUB,
PMINUD,
PMINUW,
PMOVMSKB,
PMOVSXBD,
PMOVSXBQ,
PMOVSXBW,
PMOVSXDQ,
PMOVSXWD,
PMOVSXWQ,
PMOVZXBD,
PMOVZXBQ,
PMOVZXBW,
PMOVZXDQ,
PMOVZXWD,
PMOVZXWQ,
PMULDQ,
PMULHRSW,
PMULHUW,
PMULHW,
PMULLD,
PMULLW,
PMULUDQ,
POP,
POPA,
POPAD,
POPAW,
POPCNT,
POPD,
POPF,
POPFD,
POPFQ,
POPFW,
POPQ,
POPW,
POR,
PREFETCH,
PREFETCHNTA,
PREFETCHT0,
PREFETCHT1,
PREFETCHT2,
PREFETCHW,
PSADBW,
PSHUFB,
PSHUFD,
PSHUFHW,
PSHUFLW,
PSHUFW,
PSIGNB,
PSIGND,
PSIGNW,
PSLLD,
PSLLDQ,
PSLLQ,
PSLLW,
PSRAD,
PSRAW,
PSRLD,
PSRLDQ,
PSRLQ,
PSRLW,
PSUBB,
PSUBD,
PSUBQ,
PSUBSB,
PSUBSW,
PSUBUSB,
PSUBUSW,
PSUBW,
PTEST,
PTWRITE,
PUNPCKHBW,
PUNPCKHDQ,
PUNPCKHQDQ,
PUNPCKHWD,
PUNPCKLBW,
PUNPCKLDQ,
PUNPCKLQDQ,
PUNPCKLWD,
PUSH,
PUSHA,
PUSHAD,
PUSHAW,
PUSHD,
PUSHF,
PUSHFD,
PUSHFQ,
PUSHFW,
PUSHQ,
PUSHW,
PXOR,
RCL,
RCPPS,
RCPSS,
RCR,
RDFSBASE,
RDGSBASE,
RDMSR,
RDPID,
RDPKRU,
RDPMC,
RDRAND,
RDSEED,
RDSSPD,
RDSSPQ,
RDTSC,
RDTSCP,
REP,
REPE,
REPNE,
REPNZ,
REPZ,
RET,
RETD,
RETF,
RETFD,
RETFQ,
RETFW,
RETN,
RETND,
RETNQ,
RETNW,
RETQ,
RETW,
ROL,
ROR,
RORX,
ROUNDPD,
ROUNDPS,
ROUNDSD,
ROUNDSS,
RSM,
RSQRTPS,
RSQRTSS,
RSTORSSP,
SAHF,
SAL,
SALC,
SAR,
SARX,
SAVEPREVSSP,
SBB,
SCAS,
SCASB,
SCASD,
SCASQ,
SCASW,
SETA,
SETAE,
SETB,
SETBE,
SETC,
SETE,
SETG,
SETGE,
SETL,
SETLE,
SETNA,
SETNAE,
SETNB,
SETNBE,
SETNC,
SETNE,
SETNG,
SETNGE,
SETNL,
SETNLE,
SETNO,
SETNP,
SETNS,
SETNZ,
SETO,
SETP,
SETPE,
SETPO,
SETS,
SETSSBSY,
SETZ,
SFENCE,
SGDT,
SHA1MSG1,
SHA1MSG2,
SHA1NEXTE,
SHA1RNDS4,
SHA256MSG1,
SHA256MSG2,
SHA256RNDS2,
SHL,
SHLD,
SHLX,
SHR,
SHRD,
SHRX,
SHUFPD,
SHUFPS,
SIDT,
SLDT,
SLWPCB,
SMSW,
SQRTPD,
SQRTPS,
SQRTSD,
SQRTSS,
STAC,
STC,
STD,
STI,
STMXCSR,
STOREALL,
STOS,
STOSB,
STOSD,
STOSQ,
STOSW,
STR,
SUB,
SUBPD,
SUBPS,
SUBSD,
SUBSS,
SWAPGS,
SYSCALL,
SYSENTER,
SYSEXIT,
SYSEXITQ,
SYSRET,
SYSRETQ,
T1MSKC,
TEST,
TPAUSE,
TZCNT,
TZMSK,
UCOMISD,
UCOMISS,
UD0,
UD1,
UD2,
UMONITOR,
UMOV,
UMWAIT,
UNPCKHPD,
UNPCKHPS,
UNPCKLPD,
UNPCKLPS,
VADDPD,
VADDPS,
VADDSD,
VADDSS,
VADDSUBPD,
VADDSUBPS,
VALIGND,
VALIGNQ,
VANDNPD,
VANDNPS,
VANDPD,
VANDPS,
VBLENDMPD,
VBLENDMPS,
VBLENDPD,
VBLENDPS,
VBLENDVPD,
VBLENDVPS,
VBROADCASTF128,
VBROADCASTF32X2,
VBROADCASTF32X4,
VBROADCASTF32X8,
VBROADCASTF64X2,
VBROADCASTF64X4,
VBROADCASTSD,
VBROADCASTSS,
VCMPPD,
VCMPPS,
VCMPSD,
VCMPSS,
VCOMISD,
VCOMISS,
VCOMPRESSPD,
VCOMPRESSPS,
VCVTDQ2PD,
VCVTDQ2PS,
VCVTPD2DQ,
VCVTPD2PS,
VCVTPD2QQ,
VCVTPD2UDQ,
VCVTPD2UQQ,
VCVTPH2PS,
VCVTPS2DQ,
VCVTPS2PD,
VCVTPS2PH,
VCVTPS2QQ,
VCVTPS2UDQ,
VCVTPS2UQQ,
VCVTQQ2PD,
VCVTQQ2PS,
VCVTSD2SI,
VCVTSD2SS,
VCVTSD2USI,
VCVTSI2SD,
VCVTSI2SS,
VCVTSS2SD,
VCVTSS2SI,
VCVTSS2USI,
VCVTTPD2DQ,
VCVTTPD2QQ,
VCVTTPD2UDQ,
VCVTTPD2UQQ,
VCVTTPS2DQ,
VCVTTPS2QQ,
VCVTTPS2UDQ,
VCVTTPS2UQQ,
VCVTTSD2SI,
VCVTTSD2USI,
VCVTTSS2SI,
VCVTTSS2USI,
VCVTUDQ2PD,
VCVTUDQ2PS,
VCVTUQQ2PD,
VCVTUQQ2PS,
VCVTUSI2SD,
VCVTUSI2SS,
VDBPSADBW,
VDIVPD,
VDIVPS,
VDIVSD,
VDIVSS,
VDPPD,
VDPPS,
VERR,
VERW,
VEXPANDPD,
VEXPANDPS,
VEXTRACTF128,
VEXTRACTF32X4,
VEXTRACTF32X8,
VEXTRACTF64X2,
VEXTRACTF64X4,
VEXTRACTI128,
VEXTRACTI32X4,
VEXTRACTI32X8,
VEXTRACTI64X2,
VEXTRACTI64X4,
VEXTRACTPS,
VFIXUPIMMPD,
VFIXUPIMMPS,
VFIXUPIMMSD,
VFIXUPIMMSS,
VFMADD132PD,
VFMADD132PS,
VFMADD132SD,
VFMADD132SS,
VFMADD213PD,
VFMADD213PS,
VFMADD213SD,
VFMADD213SS,
VFMADD231PD,
VFMADD231PS,
VFMADD231SD,
VFMADD231SS,
VFMADDPD,
VFMADDPS,
VFMADDSD,
VFMADDSS,
VFMADDSUB132PD,
VFMADDSUB132PS,
VFMADDSUB213PD,
VFMADDSUB213PS,
VFMADDSUB231PD,
VFMADDSUB231PS,
VFMADDSUBPD,
VFMADDSUBPS,
VFMSUB132PD,
VFMSUB132PS,
VFMSUB132SD,
VFMSUB132SS,
VFMSUB213PD,
VFMSUB213PS,
VFMSUB213SD,
VFMSUB213SS,
VFMSUB231PD,
VFMSUB231PS,
VFMSUB231SD,
VFMSUB231SS,
VFMSUBADD132PD,
VFMSUBADD132PS,
VFMSUBADD213PD,
VFMSUBADD213PS,
VFMSUBADD231PD,
VFMSUBADD231PS,
VFMSUBADDPD,
VFMSUBADDPS,
VFMSUBPD,
VFMSUBPS,
VFMSUBSD,
VFMSUBSS,
VFNMADD132PD,
VFNMADD132PS,
VFNMADD132SD,
VFNMADD132SS,
VFNMADD213PD,
VFNMADD213PS,
VFNMADD213SD,
VFNMADD213SS,
VFNMADD231PD,
VFNMADD231PS,
VFNMADD231SD,
VFNMADD231SS,
VFNMADDPD,
VFNMADDPS,
VFNMADDSD,
VFNMADDSS,
VFNMSUB132PD,
VFNMSUB132PS,
VFNMSUB132SD,
VFNMSUB132SS,
VFNMSUB213PD,
VFNMSUB213PS,
VFNMSUB213SD,
VFNMSUB213SS,
VFNMSUB231PD,
VFNMSUB231PS,
VFNMSUB231SD,
VFNMSUB231SS,
VFNMSUBPD,
VFNMSUBPS,
VFNMSUBSD,
VFNMSUBSS,
VFPCLASSPD,
VFPCLASSPS,
VFPCLASSSD,
VFPCLASSSS,
VFRCZPD,
VFRCZPS,
VFRCZSD,
VFRCZSS,
VGATHERDPD,
VGATHERDPS,
VGATHERQPD,
VGATHERQPS,
VGETEXPPD,
VGETEXPPS,
VGETEXPSD,
VGETEXPSS,
VGETMANTPD,
VGETMANTPS,
VGETMANTSD,
VGETMANTSS,
VGF2P8AFFINEINVQB,
VGF2P8AFFINEQB,
VGF2P8MULB,
VHADDPD,
VHADDPS,
VHSUBPD,
VHSUBPS,
VINSERTF128,
VINSERTF32X4,
VINSERTF32X8,
VINSERTF64X2,
VINSERTF64X4,
VINSERTI128,
VINSERTI32X4,
VINSERTI32X8,
VINSERTI64X2,
VINSERTI64X4,
VINSERTPS,
VLDDQU,
VLDMXCSR,
VMASKMOVD,
VMASKMOVDQU,
VMASKMOVPD,
VMASKMOVPS,
VMASKMOVQ,
VMAXPD,
VMAXPS,
VMAXSD,
VMAXSS,
VMINPD,
VMINPS,
VMINSD,
VMINSS,
VMOVAPD,
VMOVAPS,
VMOVD,
VMOVDDUP,
VMOVDQA,
VMOVDQA32,
VMOVDQA64,
VMOVDQU,
VMOVDQU16,
VMOVDQU32,
VMOVDQU64,
VMOVDQU8,
VMOVHLPS,
VMOVHPD,
VMOVHPS,
VMOVLHPS,
VMOVLPD,
VMOVLPS,
VMOVMSKPD,
VMOVMSKPS,
VMOVNTDQ,
VMOVNTDQA,
VMOVNTPD,
VMOVNTPS,
VMOVQ,
VMOVSD,
VMOVSHDUP,
VMOVSLDUP,
VMOVSS,
VMOVUPD,
VMOVUPS,
VMPSADBW,
VMULPD,
VMULPS,
VMULSD,
VMULSS,
VORPD,
VORPS,
VPABSB,
VPABSD,
VPABSQ,
VPABSW,
VPACKSSDW,
VPACKSSWB,
VPACKUSDW,
VPACKUSWB,
VPADDB,
VPADDD,
VPADDQ,
VPADDSB,
VPADDSW,
VPADDUSB,
VPADDUSW,
VPADDW,
VPALIGNR,
VPAND,
VPANDD,
VPANDN,
VPANDND,
VPANDNQ,
VPANDQ,
VPAVGB,
VPAVGW,
VPBLENDD,
VPBLENDMB,
VPBLENDMD,
VPBLENDMQ,
VPBLENDMW,
VPBLENDVB,
VPBLENDW,
VPBROADCASTB,
VPBROADCASTD,
VPBROADCASTI128,
VPBROADCASTI32X2,
VPBROADCASTI32X4,
VPBROADCASTI32X8,
VPBROADCASTI64X2,
VPBROADCASTI64X4,
VPBROADCASTMB2Q,
VPBROADCASTMW2D,
VPBROADCASTQ,
VPBROADCASTW,
VPCLMULQDQ,
VPCMOV,
VPCMPB,
VPCMPD,
VPCMPEQB,
VPCMPEQD,
VPCMPEQQ,
VPCMPEQW,
VPCMPESTRI,
VPCMPESTRM,
VPCMPGTB,
VPCMPGTD,
VPCMPGTQ,
VPCMPGTW,
VPCMPISTRI,
VPCMPISTRM,
VPCMPQ,
VPCMPUB,
VPCMPUD,
VPCMPUQ,
VPCMPUW,
VPCMPW,
VPCOMB,
VPCOMD,
VPCOMPRESSB,
VPCOMPRESSD,
VPCOMPRESSQ,
VPCOMPRESSW,
VPCOMQ,
VPCOMUB,
VPCOMUD,
VPCOMUQ,
VPCOMUW,
VPCOMW,
VPCONFLICTD,
VPCONFLICTQ,
VPDPBUSD,
VPDPBUSDS,
VPDPWSSD,
VPDPWSSDS,
VPERM2F128,
VPERM2I128,
VPERMB,
VPERMD,
VPERMI2B,
VPERMI2D,
VPERMI2PD,
VPERMI2PS,
VPERMI2Q,
VPERMI2W,
VPERMIL2PD,
VPERMIL2PS,
VPERMILPD,
VPERMILPS,
VPERMPD,
VPERMPS,
VPERMQ,
VPERMT2B,
VPERMT2D,
VPERMT2PD,
VPERMT2PS,
VPERMT2Q,
VPERMT2W,
VPERMW,
VPEXPANDB,
VPEXPANDD,
VPEXPANDQ,
VPEXPANDW,
VPEXTRB,
VPEXTRD,
VPEXTRQ,
VPEXTRW,
VPGATHERDD,
VPGATHERDQ,
VPGATHERQD,
VPGATHERQQ,
VPHADDBD,
VPHADDBQ,
VPHADDBW,
VPHADDD,
VPHADDDQ,
VPHADDSW,
VPHADDUBD,
VPHADDUBQ,
VPHADDUBW,
VPHADDUDQ,
VPHADDUWD,
VPHADDUWQ,
VPHADDW,
VPHADDWD,
VPHADDWQ,
VPHMINPOSUW,
VPHSUBBW,
VPHSUBD,
VPHSUBDQ,
VPHSUBSW,
VPHSUBW,
VPHSUBWD,
VPINSRB,
VPINSRD,
VPINSRQ,
VPINSRW,
VPLZCNTD,
VPLZCNTQ,
VPMACSDD,
VPMACSDQH,
VPMACSDQL,
VPMACSSDD,
VPMACSSDQH,
VPMACSSDQL,
VPMACSSWD,
VPMACSSWW,
VPMACSWD,
VPMACSWW,
VPMADCSSWD,
VPMADCSWD,
VPMADD52HUQ,
VPMADD52LUQ,
VPMADDUBSW,
VPMADDWD,
VPMAXSB,
VPMAXSD,
VPMAXSQ,
VPMAXSW,
VPMAXUB,
VPMAXUD,
VPMAXUQ,
VPMAXUW,
VPMINSB,
VPMINSD,
VPMINSQ,
VPMINSW,
VPMINUB,
VPMINUD,
VPMINUQ,
VPMINUW,
VPMOVB2M,
VPMOVD2M,
VPMOVDB,
VPMOVDW,
VPMOVM2B,
VPMOVM2D,
VPMOVM2Q,
VPMOVM2W,
VPMOVMSKB,
VPMOVQ2M,
VPMOVQB,
VPMOVQD,
VPMOVQW,
VPMOVSDB,
VPMOVSDW,
VPMOVSQB,
VPMOVSQD,
VPMOVSQW,
VPMOVSWB,
VPMOVSXBD,
VPMOVSXBQ,
VPMOVSXBW,
VPMOVSXDQ,
VPMOVSXWD,
VPMOVSXWQ,
VPMOVUSDB,
VPMOVUSDW,
VPMOVUSQB,
VPMOVUSQD,
VPMOVUSQW,
VPMOVUSWB,
VPMOVW2M,
VPMOVWB,
VPMOVZXBD,
VPMOVZXBQ,
VPMOVZXBW,
VPMOVZXDQ,
VPMOVZXWD,
VPMOVZXWQ,
VPMULDQ,
VPMULHRSW,
VPMULHUW,
VPMULHW,
VPMULLD,
VPMULLQ,
VPMULLW,
VPMULTISHIFTQB,
VPMULUDQ,
VPOPCNTB,
VPOPCNTD,
VPOPCNTQ,
VPOPCNTW,
VPOR,
VPORD,
VPORQ,
VPPERM,
VPROLD,
VPROLQ,
VPROLVD,
VPROLVQ,
VPRORD,
VPRORQ,
VPRORVD,
VPRORVQ,
VPROTB,
VPROTD,
VPROTQ,
VPROTW,
VPSADBW,
VPSCATTERDD,
VPSCATTERDQ,
VPSCATTERQD,
VPSCATTERQQ,
VPSHAB,
VPSHAD,
VPSHAQ,
VPSHAW,
VPSHLB,
VPSHLD,
VPSHLDD,
VPSHLDQ,
VPSHLDVD,
VPSHLDVQ,
VPSHLDVW,
VPSHLDW,
VPSHLQ,
VPSHLW,
VPSHRDD,
VPSHRDQ,
VPSHRDVD,
VPSHRDVQ,
VPSHRDVW,
VPSHRDW,
VPSHUFB,
VPSHUFBITQMB,
VPSHUFD,
VPSHUFHW,
VPSHUFLW,
VPSIGNB,
VPSIGND,
VPSIGNW,
VPSLLD,
VPSLLDQ,
VPSLLQ,
VPSLLVD,
VPSLLVQ,
VPSLLVW,
VPSLLW,
VPSRAD,
VPSRAQ,
VPSRAVD,
VPSRAVQ,
VPSRAVW,
VPSRAW,
VPSRLD,
VPSRLDQ,
VPSRLQ,
VPSRLVD,
VPSRLVQ,
VPSRLVW,
VPSRLW,
VPSUBB,
VPSUBD,
VPSUBQ,
VPSUBSB,
VPSUBSW,
VPSUBUSB,
VPSUBUSW,
VPSUBW,
VPTERNLOGD,
VPTERNLOGQ,
VPTEST,
VPTESTMB,
VPTESTMD,
VPTESTMQ,
VPTESTMW,
VPTESTNMB,
VPTESTNMD,
VPTESTNMQ,
VPTESTNMW,
VPUNPCKHBW,
VPUNPCKHDQ,
VPUNPCKHQDQ,
VPUNPCKHWD,
VPUNPCKLBW,
VPUNPCKLDQ,
VPUNPCKLQDQ,
VPUNPCKLWD,
VPXOR,
VPXORD,
VPXORQ,
VRANGEPD,
VRANGEPS,
VRANGESD,
VRANGESS,
VRCP14PD,
VRCP14PS,
VRCP14SD,
VRCP14SS,
VRCPPS,
VRCPSS,
VREDUCEPD,
VREDUCEPS,
VREDUCESD,
VREDUCESS,
VRNDSCALEPD,
VRNDSCALEPS,
VRNDSCALESD,
VRNDSCALESS,
VROUNDPD,
VROUNDPS,
VROUNDSD,
VROUNDSS,
VRSQRT14PD,
VRSQRT14PS,
VRSQRT14SD,
VRSQRT14SS,
VRSQRTPS,
VRSQRTSS,
VSCALEFPD,
VSCALEFPS,
VSCALEFSD,
VSCALEFSS,
VSCATTERDPD,
VSCATTERDPS,
VSCATTERQPD,
VSCATTERQPS,
VSHUFF32X4,
VSHUFF64X2,
VSHUFI32X4,
VSHUFI64X2,
VSHUFPD,
VSHUFPS,
VSQRTPD,
VSQRTPS,
VSQRTSD,
VSQRTSS,
VSTMXCSR,
VSUBPD,
VSUBPS,
VSUBSD,
VSUBSS,
VTESTPD,
VTESTPS,
VUCOMISD,
VUCOMISS,
VUNPCKHPD,
VUNPCKHPS,
VUNPCKLPD,
VUNPCKLPS,
VXORPD,
VXORPS,
VZEROALL,
VZEROUPPER,
WAIT,
WBINVD,
WRFSBASE,
WRGSBASE,
WRMSR,
WRPKRU,
WRSSD,
WRSSQ,
WRUSSD,
WRUSSQ,
XABORT,
XACQUIRE,
XADD,
XBEGIN,
XBTS,
XCHG,
XEND,
XGETBV,
XLAT,
XLATB,
XOR,
XORPD,
XORPS,
XRELEASE,
XRSTOR,
XRSTOR64,
XRSTORS,
XRSTORS64,
XSAVE,
XSAVE64,
XSAVEC,
XSAVEC64,
XSAVEOPT,
XSAVEOPT64,
XSAVES,
XSAVES64,
XSETBV,
XTEST,
// Reserved/Undefined opcodes
FFREEP,
FSTPNOUFLOW,
RESRV_ADC,
RESRV_ADD,
RESRV_AND,
RESRV_CMP,
RESRV_FCOM,
RESRV_FCOMP,
RESRV_FCOMP2,
RESRV_FSTP,
RESRV_FSTP2,
RESRV_FXCH,
RESRV_FXCH2,
RESRV_OR,
RESRV_SAL,
RESRV_SBB,
RESRV_SHL,
RESRV_SUB,
RESRV_TEST,
RESRV_XOR,
RESRV_NOP_0F0D_0,
RESRV_NOP_0F0D_1,
RESRV_NOP_0F0D_2,
RESRV_NOP_0F0D_3,
RESRV_NOP_0F0D_4,
RESRV_NOP_0F0D_5,
RESRV_NOP_0F0D_6,
RESRV_NOP_0F0D_7,
RESRV_NOP_0F18_0,
RESRV_NOP_0F18_1,
RESRV_NOP_0F18_2,
RESRV_NOP_0F18_3,
RESRV_NOP_0F18_4,
RESRV_NOP_0F18_5,
RESRV_NOP_0F18_6,
RESRV_NOP_0F18_7,
RESRV_NOP_0F19_0,
RESRV_NOP_0F19_1,
RESRV_NOP_0F19_2,
RESRV_NOP_0F19_3,
RESRV_NOP_0F19_4,
RESRV_NOP_0F19_5,
RESRV_NOP_0F19_6,
RESRV_NOP_0F19_7,
RESRV_NOP_0F1A_0,
RESRV_NOP_0F1A_1,
RESRV_NOP_0F1A_2,
RESRV_NOP_0F1A_3,
RESRV_NOP_0F1A_4,
RESRV_NOP_0F1A_5,
RESRV_NOP_0F1A_6,
RESRV_NOP_0F1A_7,
RESRV_NOP_0F1B_0,
RESRV_NOP_0F1B_1,
RESRV_NOP_0F1B_2,
RESRV_NOP_0F1B_3,
RESRV_NOP_0F1B_4,
RESRV_NOP_0F1B_5,
RESRV_NOP_0F1B_6,
RESRV_NOP_0F1B_7,
RESRV_NOP_0F1C_0,
RESRV_NOP_0F1C_1,
RESRV_NOP_0F1C_2,
RESRV_NOP_0F1C_3,
RESRV_NOP_0F1C_4,
RESRV_NOP_0F1C_5,
RESRV_NOP_0F1C_6,
RESRV_NOP_0F1C_7,
RESRV_NOP_0F1D_0,
RESRV_NOP_0F1D_1,
RESRV_NOP_0F1D_2,
RESRV_NOP_0F1D_3,
RESRV_NOP_0F1D_4,
RESRV_NOP_0F1D_5,
RESRV_NOP_0F1D_6,
RESRV_NOP_0F1D_7,
RESRV_NOP_0F1E_0,
RESRV_NOP_0F1E_1,
RESRV_NOP_0F1E_2,
RESRV_NOP_0F1E_3,
RESRV_NOP_0F1E_4,
RESRV_NOP_0F1E_5,
RESRV_NOP_0F1E_6,
RESRV_NOP_0F1E_7,
RESRV_NOP_0F1F_0,
RESRV_NOP_0F1F_1,
RESRV_NOP_0F1F_2,
RESRV_NOP_0F1F_3,
RESRV_NOP_0F1F_4,
RESRV_NOP_0F1F_5,
RESRV_NOP_0F1F_6,
RESRV_NOP_0F1F_7,
// 3DNow!
FEMMS,
PAVGUSB,
PF2ID,
PFACC,
PFADD,
PFCMPEQ,
PFCMPGE,
PFCMPGT,
PFMAX,
PFMIN,
PFMUL,
PFRCP,
PFRCPIT1,
PFRCPIT2,
PFRCPV,
PFRSQIT1,
PFRSQRT,
PFRSQRTV,
PFSUB,
PFSUBR,
PI2FD,
PMULHRW,
// 3DNOW!+
PF2IW,
PFNACC,
PFPNACC,
PI2FW,
PSWAPD,
// Cyrix EMMI (Extended Multi-Media Instructions)
PADDSIW,
PAVEB,
PDISTIB,
PMACHRIW,
PMAGW,
PMULHRIW,
PMVGEZB,
PMVLZB,
PMVNZB,
PMVZB,
PSUBSIW,
// AMD specific
CLGI,
INVLPGA,
SKINIT,
STGI,
VMLOAD,
VMMCALL,
VMRUN,
VMSAVE,
// Intel VT-x /VMX
INVEPT,
INVVPID,
VMCALL,
VMCLEAR,
VMFUNC,
VMLAUNCH,
VMPTRLD,
VMPTRST,
VMREAD,
VMRESUME,
VMWRITE,
VMXOFF,
VMXON,
// Xeon Phi
PREFETCHWT1,
// SGX
ENCLS,
ENCLU,
ENCLV,
// SMX
GETSEC,
_mnemonic_final,
};
|
src/x86/mnemonic.zig
|
// This code was generated by a tool.
// IUP Metadata Code Generator
// https://github.com/batiati/IUPMetadata
//
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
const std = @import("std");
const ascii = std.ascii;
const testing = std.testing;
const Impl = @import("../impl.zig").Impl;
const CallbackHandler = @import("../callback_handler.zig").CallbackHandler;
const iup = @import("iup.zig");
const interop = @import("interop.zig");
const ChildrenIterator = iup.ChildrenIterator;
pub const Handle = interop.Handle;
{{Imports}}
///
/// IUP contains several user interface elements.
/// The library’s main characteristic is the use of native elements.
/// This means that the drawing and management of a button or text box is done by the native interface system, not by IUP.
/// This makes the application’s appearance more similar to other applications in that system. On the other hand, the application’s appearance can vary from one system to another.
///
/// But this is valid only for the standard elements, many additional elements are drawn by IUP.
/// Composition elements are not visible, so they are independent from the native system.
///
/// Each element has an unique creation function, and all of its management is done by means of attributes and callbacks, using functions common to all the elements. This simple but powerful approach is one of the advantages of using IUP.
/// Elements are automatically destroyed when the dialog is destroyed.
pub const Element = union(enum) {
{{UnionDecl}}
Unknown: *Handle,
pub fn fromType(comptime T: type, handle: anytype) Element {
switch (T) {
{{FromType}}
else => @compileError("Type " ++ @typeName(T) ++ " cannot be converted to a Element"),
}
}
pub fn fromRef(reference: anytype) Element {
const referenceType = @TypeOf(reference);
const typeInfo = @typeInfo(referenceType);
if (comptime typeInfo == .Pointer) {
const childType = typeInfo.Pointer.child;
switch(childType) {
{{FromRef}}
else => @compileError("Type " ++ @typeName(referenceType) ++ " cannot be converted to a Element"),
}
} else {
@compileError("Reference to a element expected");
}
}
pub fn fromClassName(className: []const u8, handle: anytype) Element {
{{FromClassName}}
return . { .Unknown = @ptrCast(*Handle, handle) };
}
pub fn getHandle(self: Element) *Handle {
switch (self) {
{{GetHandle}}
.Unknown => |value| return @ptrCast(*Handle, value),
}
}
pub fn children(self: Element) ChildrenIterator {
switch (self) {
{{Children}}
else => return ChildrenIterator.NoChildren,
}
}
pub fn eql(self: Element, other: Element) bool {
return @ptrToInt(self.getHandle()) == @ptrToInt(other.getHandle());
}
pub fn deinit(self: Element) void {
switch (self) {
{{Deinit}}
else => unreachable
}
}
pub fn setAttribute(self: Element, attribute: [:0]const u8, value: [:0]const u8) void {
interop.setStrAttribute(self.getHandle(), attribute, .{}, value);
}
pub fn getAttribute(self: Element, attribute: [:0]const u8) [:0]const u8 {
return interop.getStrAttribute(self.getHandle(), attribute, .{});
}
pub fn setTag(self: Element, comptime T: type, attribute: [:0]const u8, value: ?*T) void {
interop.setPtrAttribute(T, self.getHandle(), attribute, .{}, value);
}
pub fn getTag(self: Element, comptime T: type, attribute: [:0]const u8) ?*T {
return interop.getPtrAttribute(T, self.getHandle(), attribute, .{});
}
};
test "retrieve element fromType" {
try iup.MainLoop.open();
defer iup.MainLoop.close();
var handle = try iup.Label.init().unwrap();
defer handle.deinit();
var fromType = Element.fromType(iup.Label, handle);
try testing.expect(fromType == .Label);
try testing.expect(@ptrToInt(fromType.Label) == @ptrToInt(handle));
}
test "retrieve element fromRef" {
try iup.MainLoop.open();
defer iup.MainLoop.close();
var handle = try iup.Label.init().unwrap();
defer handle.deinit();
var fromRef = Element.fromRef(handle);
try testing.expect(fromRef == .Label);
try testing.expect(@ptrToInt(fromRef.Label) == @ptrToInt(handle));
}
test "retrieve element fromClassName" {
try iup.MainLoop.open();
defer iup.MainLoop.close();
var handle = try iup.Label.init().unwrap();
defer handle.deinit();
var fromClassName = Element.fromClassName(Label.CLASS_NAME, handle);
try testing.expect(fromClassName == .Label);
try testing.expect(@ptrToInt(fromClassName.Label) == @ptrToInt(handle));
}
test "getHandle" {
try iup.MainLoop.open();
defer iup.MainLoop.close();
var handle = try iup.Label.init().unwrap();
defer handle.deinit();
var element = Element { .Label = handle };
var value = element.getHandle();
try testing.expect(@ptrToInt(handle) == @ptrToInt(value));
}
test "children" {
try iup.MainLoop.open();
defer iup.MainLoop.close();
var parent = try iup.HBox.init().unwrap();
var child1 = try iup.HBox.init().unwrap();
var child2 = try iup.HBox.init().unwrap();
try parent.appendChild(child1);
try parent.appendChild(child2);
var element = Element { .HBox = parent };
var children = element.children();
if (children.next()) |ret1| {
try testing.expect(ret1 == .HBox);
try testing.expect(ret1.HBox == child1);
} else {
try testing.expect(false);
}
if (children.next()) |ret2| {
try testing.expect(ret2 == .HBox);
try testing.expect(ret2.HBox == child2);
} else {
try testing.expect(false);
}
var ret3 = children.next();
try testing.expect(ret3 == null);
}
test "eql" {
try iup.MainLoop.open();
defer iup.MainLoop.close();
var l1 = Element.fromRef(try iup.Label.init().unwrap());
defer l1.deinit();
var l2 = Element.fromRef(try iup.Label.init().unwrap());
defer l2.deinit();
var l1_copy = l1;
try testing.expect(l1.eql(l1));
try testing.expect(l2.eql(l2));
try testing.expect(l1.eql(l1_copy));
try testing.expect(!l1.eql(l2));
try testing.expect(!l2.eql(l1));
}
|
src/IupMetadata/CodeGenerators/Zig/templates/elements.zig
|
const wapc = @import("wapc");
const std = @import("std");
const mem = std.mem;
const json = std.json;
const testing = std.testing;
const fmt = std.fmt;
const RndGen = std.rand.DefaultPrng;
extern "wapc" fn __console_log(ptr: [*]u8, len: usize) void;
export fn __guest_call(operation_size: usize, payload_size: usize) bool {
return wapc.handleCall(std.heap.page_allocator, operation_size, payload_size, &functions);
}
const functions = [_]wapc.Function{
wapc.Function{ .name = "hello", .invoke = sayHello },
wapc.Function{ .name = "zigCallJs", .invoke = zigCallJs },
};
// example of receiving and sending json objects
const HelloRequest = struct { name: []u8 };
const HelloResponse = struct { msg: []u8 };
fn sayHello(allocator: mem.Allocator, payload: []u8) !?[]u8 {
// parse request payload
var stream = json.TokenStream.init(payload);
const parse_options = .{ .allocator = allocator };
const res = try json.parse(HelloRequest, &stream, parse_options);
defer json.parseFree(HelloRequest, res, parse_options);
// build response
var message = std.ArrayList(u8).init(allocator);
defer message.deinit();
try message.appendSlice("Hello, ");
try message.appendSlice(res.name);
try message.appendSlice("!");
const resp = HelloResponse{ .msg = message.items };
// serialize response
var buffer = std.ArrayList(u8).init(allocator);
const options = json.StringifyOptions{};
try json.stringify(resp, options, buffer.writer());
return buffer.items;
}
var rnd = RndGen.init(0);
// ignore incoming payload and send no payload out
fn zigCallJs(allocator: mem.Allocator, _: []u8) !?[]u8 {
var message = std.ArrayList(u8).init(allocator);
defer message.deinit();
try message.appendSlice("Hello from zig ");
var buf = try allocator.alloc(u8, 11);
defer allocator.free(buf);
try message.appendSlice(try fmt.bufPrint(buf, "{}", .{rnd.random().int(i32)}));
try message.appendSlice("!");
// example call from zig to js
const resp = try wapc.hostCall(allocator, "app", "window", "alert", message.items);
allocator.free(resp);
return null;
}
|
main.zig
|
const Allocator = std.mem.Allocator;
const Buffer = std.ArrayList(u8);
const BodyReader = @import("../readers/readers.zig").BodyReader;
const Data = @import("../events/events.zig").Data;
const Event = @import("../events/events.zig").Event;
const Method = @import("http").Method;
const Request = @import("../events/events.zig").Request;
const Response = @import("../events/events.zig").Response;
const SMError = @import("errors.zig").SMError;
const State = @import("states.zig").State;
const StatusCode = @import("http").StatusCode;
const std = @import("std");
const Version = @import("http").Version;
const MaximumResponseSize = 64_000;
const ReaderLookahead = 32;
pub fn ServerSM(comptime Reader: type) type {
return struct {
const Self = @This();
allocator: *Allocator,
body_reader: ?BodyReader,
expected_request: ?Request,
state: State,
reader: std.io.PeekStream(.{ .Static = ReaderLookahead }, Reader),
pub fn init(allocator: *Allocator, reader: Reader) Self {
return .{ .allocator = allocator, .body_reader = null, .expected_request = null, .state = State.Idle, .reader = std.io.peekStream(ReaderLookahead, reader) };
}
pub fn deinit(self: *Self) void {
self.body_reader = null;
self.expected_request = null;
self.state = State.Idle;
}
pub fn expectEvent(self: *Self, event: Event) void {
switch (event) {
.Request => |request| {
self.expected_request = request;
},
else => {},
}
}
pub fn nextEvent(self: *Self, options: anytype) !Event {
return switch (self.state) {
.Idle => {
var event = self.readResponse() catch |err| {
self.state = .Error;
return err;
};
self.state = .SendBody;
return event;
},
.SendBody => {
var event = self.readData(options) catch |err| {
self.state = .Error;
return err;
};
if (event == .EndOfMessage) {
self.state = .Done;
}
return event;
},
.Done => {
self.state = .Closed;
return .ConnectionClosed;
},
.Closed => .ConnectionClosed,
.Error => error.RemoteProtocolError,
};
}
fn readResponse(self: *Self) !Event {
var raw_response = try self.readRawResponse();
var response = Response.parse(self.allocator, raw_response) catch |err| {
self.allocator.free(raw_response);
return err;
};
errdefer response.deinit();
self.body_reader = try BodyReader.frame(self.expected_request.?.method, response.statusCode, response.headers);
return Event{ .Response = response };
}
fn readData(self: *Self, options: anytype) !Event {
if (!@hasField(@TypeOf(options), "buffer")) {
@panic("You must provide a buffer to read into.");
}
return try self.body_reader.?.read(&self.reader, options.buffer);
}
fn readRawResponse(self: *Self) ![]u8 {
var response_buffer = std.ArrayList(u8).init(self.allocator);
errdefer response_buffer.deinit();
var buffer: [ReaderLookahead]u8 = undefined;
var count = try self.reader.read(&buffer);
if (count == 0) {
return error.EndOfStream;
}
var index = std.mem.indexOf(u8, &buffer, "\r\n\r\n");
if (index != null) {
const response = buffer[0 .. index.? + 4];
try response_buffer.appendSlice(response);
if (response.len < count) {
try self.reader.putBack(buffer[response.len..count]);
}
return response_buffer.toOwnedSlice();
}
try response_buffer.appendSlice(buffer[0..count]);
try self.reader.putBack(buffer[count - 3 .. count]);
while (true) {
if (response_buffer.items.len > MaximumResponseSize) {
return error.ResponseTooLarge;
}
count = try self.reader.read(&buffer);
if (count == 0) {
return error.EndOfStream;
}
index = std.mem.indexOf(u8, &buffer, "\r\n\r\n");
if (index != null) {
const response_end = index.? + 4;
try response_buffer.appendSlice(buffer[3..response_end]);
var body = buffer[response_end..count];
try self.reader.putBack(body);
break;
}
try response_buffer.appendSlice(buffer[3..count]);
try self.reader.putBack(buffer[count - 3 .. count]);
}
return response_buffer.toOwnedSlice();
}
};
}
const expect = std.testing.expect;
const expectEqualStrings = std.testing.expectEqualStrings;
const expectError = std.testing.expectError;
const Headers = @import("http").Headers;
const TestServerSM = ServerSM(std.io.FixedBufferStream([]const u8).Reader);
test "NextEvent - Can retrieve a Response event when state is Idle" {
const content = "HTTP/1.1 200 OK\r\nServer: Apache\r\nContent-Length: 0\r\n\r\n";
var reader = std.io.fixedBufferStream(content).reader();
var server = TestServerSM.init(std.testing.allocator, reader);
defer server.deinit();
var request = Request.default(std.testing.allocator);
defer request.deinit();
server.expectEvent(Event{ .Request = request });
var event = try server.nextEvent(.{});
try expect(event.Response.statusCode == .Ok);
try expect(event.Response.version == .Http11);
try expect(server.state == .SendBody);
event.Response.deinit();
var buffer: [100]u8 = undefined;
event = try server.nextEvent(.{ .buffer = &buffer });
try expect(event == .EndOfMessage);
}
test "NextEvent - Can retrieve a Response and Data when state is Idle" {
const content = "HTTP/1.1 200 OK\r\nServer: Apache\r\nContent-Length: 14\r\n\r\nGotta go fast!";
var reader = std.io.fixedBufferStream(content).reader();
var server = TestServerSM.init(std.testing.allocator, reader);
defer server.deinit();
var request = Request.default(std.testing.allocator);
defer request.deinit();
server.expectEvent(Event{ .Request = request });
var event = try server.nextEvent(.{});
try expect(event.Response.statusCode == .Ok);
try expect(event.Response.version == .Http11);
try expect(server.state == .SendBody);
event.Response.deinit();
var buffer: [100]u8 = undefined;
event = try server.nextEvent(.{ .buffer = &buffer });
try expectEqualStrings(event.Data.bytes, "Gotta go fast!");
try expectEqualStrings(buffer[0..14], "Gotta go fast!");
try expect(server.state == .SendBody);
event = try server.nextEvent(.{ .buffer = &buffer });
try expect(event == .EndOfMessage);
try expect(server.state == .Done);
}
test "NextEvent - When the response size is above the limit - Returns ResponseTooLarge" {
const content = "HTTP/1.1 200 OK\r\nCookie: " ++ "a" ** 65_000 ++ "\r\n\r\n";
var reader = std.io.fixedBufferStream(content).reader();
var server = TestServerSM.init(std.testing.allocator, reader);
defer server.deinit();
var request = Request.default(std.testing.allocator);
defer request.deinit();
server.expectEvent(Event{ .Request = request });
const failure = server.nextEvent(.{});
try expectError(error.ResponseTooLarge, failure);
}
test "NextEvent - When fail to read from the reader - Returns reader' error" {
const FailingReader = struct {
const Self = @This();
const ReadError = error{Failed};
const Reader = std.io.Reader(*Self, ReadError, read);
fn reader(self: *Self) Reader {
return .{ .context = self };
}
pub fn read(self: *Self, _: []u8) ReadError!usize {
_ = self;
return error.Failed;
}
};
var failing_reader = FailingReader{};
var server = ServerSM(FailingReader.Reader).init(std.testing.allocator, failing_reader.reader());
defer server.deinit();
var request = Request.default(std.testing.allocator);
defer request.deinit();
server.expectEvent(Event{ .Request = request });
const failure = server.nextEvent(.{});
try expectError(error.Failed, failure);
}
test "NextEvent - Cannot retrieve a response event if the data is invalid" {
const content = "INVALID RESPONSE\r\n\r\n";
var reader = std.io.fixedBufferStream(content).reader();
var server = TestServerSM.init(std.testing.allocator, reader);
defer server.deinit();
var event = server.nextEvent(.{});
try expectError(error.Invalid, event);
try expect(server.state == .Error);
}
test "NextEvent - Retrieve a ConnectionClosed event when state is Done" {
const content = "";
var reader = std.io.fixedBufferStream(content).reader();
var server = TestServerSM.init(std.testing.allocator, reader);
server.state = .Done;
defer server.deinit();
var event = try server.nextEvent(.{});
try expect(event == .ConnectionClosed);
try expect(server.state == .Closed);
}
test "NextEvent - Retrieve a ConnectionClosed event when state is Closed" {
const content = "";
var reader = std.io.fixedBufferStream(content).reader();
var server = TestServerSM.init(std.testing.allocator, reader);
server.state = .Closed;
defer server.deinit();
var event = try server.nextEvent(.{});
try expect(event == .ConnectionClosed);
try expect(server.state == .Closed);
}
|
src/state_machines/server.zig
|
const std = @import("std");
const process = std.process;
const stdx = @import("stdx");
const string = stdx.string;
const ds = stdx.ds;
const graphics = @import("graphics");
const Color = graphics.Color;
const sdl = @import("sdl");
const v8 = @import("v8");
const build_options = @import("build_options");
const v8x = @import("v8x.zig");
const js_env = @import("js_env.zig");
const runtime = @import("runtime.zig");
const RuntimeContext = runtime.RuntimeContext;
const RuntimeConfig = runtime.RuntimeConfig;
const log = stdx.log.scoped(.main);
const Environment = @import("env.zig").Environment;
// Cosmic main. Common entry point for cli and gui (for dev mode).
pub fn main() !void {
// Fast temporary memory allocator.
var arena = std.heap.ArenaAllocator.init(std.heap.page_allocator);
defer arena.deinit();
const alloc = arena.allocator();
const args = try process.argsAlloc(alloc);
defer process.argsFree(alloc, args);
var env = Environment{};
defer env.deinit(alloc);
try runMain(alloc, args, &env);
}
const Flags = struct {
help: bool = false,
include_test_api: bool = false,
};
fn parseFlags(alloc: std.mem.Allocator, args: []const []const u8, flags: *Flags) []const []const u8 {
var rest_args = std.ArrayList([]const u8).init(alloc);
for (args) |arg| {
if (std.mem.startsWith(u8, arg, "-")) {
if (std.mem.eql(u8, arg, "-h")) {
flags.help = true;
} else if (std.mem.eql(u8, arg, "--help")) {
flags.help = true;
} else if (std.mem.eql(u8, arg, "--test-api")) {
flags.include_test_api = true;
}
} else {
const arg_dupe = alloc.dupe(u8, arg) catch unreachable;
rest_args.append(arg_dupe) catch unreachable;
}
}
return rest_args.toOwnedSlice();
}
// main is extracted with cli args and options to facilitate testing.
pub fn runMain(alloc: std.mem.Allocator, orig_args: []const []const u8, env: *Environment) !void {
var flags = Flags{};
const args = parseFlags(alloc, orig_args, &flags);
defer {
for (args) |arg| {
alloc.free(arg);
}
alloc.free(args);
}
if (args.len == 1) {
printUsage(env, main_usage);
env.exit(0);
return;
}
// Skip exe path arg.
var arg_idx: usize = 1;
const cmd = nextArg(args, &arg_idx).?;
if (string.eq(cmd, "dev")) {
if (flags.help) {
printUsage(env, dev_usage);
env.exit(0);
} else {
const src_path = nextArg(args, &arg_idx) orelse {
env.abortFmt("Expected path to main source file.", .{});
return;
};
env.include_test_api = flags.include_test_api;
try runAndExit(src_path, true, env);
}
} else if (string.eq(cmd, "run")) {
if (flags.help) {
printUsage(env, run_usage);
env.exit(0);
} else {
const src_path = nextArg(args, &arg_idx) orelse {
env.abortFmt("Expected path to main source file.", .{});
return;
};
env.include_test_api = flags.include_test_api;
try runAndExit(src_path, false, env);
}
} else if (string.eq(cmd, "test")) {
if (flags.help) {
printUsage(env, test_usage);
env.exit(0);
} else {
const src_path = nextArg(args, &arg_idx) orelse {
env.abortFmt("Expected path to main source file.", .{});
return;
};
try testAndExit(src_path, env);
}
} else if (string.eq(cmd, "http")) {
if (flags.help) {
printUsage(env, http_usage);
env.exit(0);
} else {
const public_path = nextArg(args, &arg_idx) orelse {
env.abortFmt("Expected public directory path.", .{});
return;
};
const abs_path = try std.fs.path.resolve(alloc, &.{ public_path });
defer alloc.free(abs_path);
try std.os.chdir(abs_path);
const host_port_str = nextArg(args, &arg_idx) orelse ":";
const host_port = stdx.net.parseHostPort(host_port_str) catch return error.ParseHostPort;
const host = host_port.host orelse "127.0.0.1";
const port = host_port.port orelse 8081;
env.main_script_origin = "(in-memory: http-main.js)";
env.main_script_override = http_main;
env.user_ctx_json = try std.fmt.allocPrint(alloc,
\\{{ "host": "{s}", "port": {}, "https": false }}
, .{ host, port });
try runAndExit("http-main.js", false, env);
}
} else if (string.eq(cmd, "https")) {
if (flags.help) {
printUsage(env, https_usage);
env.exit(0);
} else {
const public_path = nextArg(args, &arg_idx) orelse {
env.abortFmt("Expected public directory path.", .{});
return;
};
const public_key_path = nextArg(args, &arg_idx) orelse {
env.abortFmt("Expected public key path.", .{});
return;
};
const private_key_path = nextArg(args, &arg_idx) orelse {
env.abortFmt("Expected private key path.", .{});
return;
};
const abs_path = try std.fs.path.resolve(alloc, &.{ public_path });
defer alloc.free(abs_path);
try std.os.chdir(abs_path);
const host_port_str = nextArg(args, &arg_idx) orelse ":";
const host_port = stdx.net.parseHostPort(host_port_str) catch return error.ParseHostPort;
const host = host_port.host orelse "127.0.0.1";
const port = host_port.port orelse 8081;
env.main_script_origin = "(in-memory: http-main.js)";
env.main_script_override = http_main;
env.user_ctx_json = try std.fmt.allocPrint(alloc,
\\{{ "host": "{s}", "port": {}, "https": true, "certPath": "{s}", "keyPath": "{s}" }}
, .{ host, port, public_key_path, private_key_path });
try runAndExit("http-main.js", false, env);
}
} else if (string.eq(cmd, "help")) {
printUsage(env, main_usage);
env.exit(0);
} else if (string.eq(cmd, "version")) {
version(env);
env.exit(0);
} else if (string.eq(cmd, "shell")) {
if (flags.help) {
printUsage(env, shell_usage);
env.exit(0);
} else {
repl(alloc, env);
env.exit(0);
}
} else {
// Assume param is a js file.
const src_path = cmd;
env.include_test_api = flags.include_test_api;
try runAndExit(src_path, false, env);
}
}
fn testAndExit(src_path: []const u8, env: *Environment) !void {
const alloc = stdx.heap.getDefaultAllocator();
defer stdx.heap.deinitDefaultAllocator();
const passed = runtime.runTestMain(alloc, src_path, env) catch |err| {
stdx.heap.deinitDefaultAllocator();
if (err == error.FileNotFound) {
env.abortFmt("File not found: {s}", .{src_path});
} else {
env.abortFmt("Encountered error: {}", .{err});
}
return;
};
stdx.heap.deinitDefaultAllocator();
if (passed) {
env.exit(0);
} else {
env.exit(1);
}
}
fn runAndExit(src_path: []const u8, dev_mode: bool, env: *Environment) !void {
const alloc = stdx.heap.getDefaultAllocator();
runtime.runUserMain(alloc, src_path, dev_mode, env) catch |err| {
stdx.heap.deinitDefaultAllocator();
switch (err) {
error.FileNotFound => env.abortFmt("File not found: {s}", .{src_path}),
error.MainScriptError => {},
else => env.abortFmt("Encountered error: {}", .{err}),
}
return err;
};
stdx.heap.deinitDefaultAllocator();
env.exit(0);
}
fn repl(alloc: std.mem.Allocator, env: *Environment) void {
const ShellContext = struct {
env: *Environment,
alloc: std.mem.Allocator,
rt: *RuntimeContext,
done: bool,
input_script: ?[]const u8,
};
const S = struct {
fn runPrompt(ctx: *ShellContext) void {
var input_buf = std.ArrayList(u8).init(ctx.alloc);
defer input_buf.deinit();
const env_ = ctx.env;
env_.printFmt(
\\Cosmic ({s})
\\exit with Ctrl+D or "exit()"
\\
\\
, .{build_options.VersionName});
while (true) {
env_.printFmt("> ", .{});
if (getInput(&input_buf)) |input| {
if (string.eq(input, "exit()")) {
break;
}
ctx.input_script = ctx.alloc.dupe(u8, input) catch unreachable;
ctx.rt.wakeUpEventPoller();
// Busy wait until eval is done.
while (ctx.input_script != null) {}
} else {
env_.printFmt("\n", .{});
break;
}
}
ctx.done = true;
}
};
const main_alloc = stdx.heap.getDefaultAllocator();
defer stdx.heap.deinitDefaultAllocator();
const config = RuntimeConfig{
.is_test_runner = false,
.is_dev_mode = false,
};
var rt: RuntimeContext = undefined;
runtime.initGlobalRuntime(main_alloc, &rt, config, env);
defer runtime.deinitGlobalRuntime(main_alloc, &rt);
var ctx = ShellContext{
.env = env,
.alloc = alloc,
.done = false,
.rt = &rt,
.input_script = null,
};
// Starts a new thread for the input prompt since the runtime is not always event driven.
const thread = std.Thread.spawn(.{}, S.runPrompt, .{ &ctx }) catch unreachable;
_ = thread.setName("Prompt") catch {};
while (!ctx.done) {
// Keep polling indefinitely until exit signal from prompt.
const Timeout = 4 * 1e9;
const wait_res = rt.main_wakeup.timedWait(Timeout);
rt.main_wakeup.reset();
if (wait_res) |_| {
} else |err| {
if (err == error.Timeout) {
continue;
} else {
stdx.panicFmt("unknown error: {}", .{err});
}
}
runtime.processMainEventLoop(&rt);
if (ctx.input_script) |script| {
// log.info("input: {s}", .{script});
const res = rt.runScriptGetResult("(eval)", script);
defer res.deinit();
if (res.success) {
env.printFmt("{s}\n", .{res.result.?});
} else {
env.errorFmt("{s}\n", .{res.err.?});
}
alloc.free(script);
ctx.input_script = null;
}
}
}
// TODO: We'll need to support extended key bindings/ncurses (eg. up arrow for last command) per platform.
// (Low priority since there will be a repl in the GUI)
fn getInput(input_buf: *std.ArrayList(u8)) ?[]const u8 {
input_buf.clearRetainingCapacity();
std.io.getStdIn().reader().readUntilDelimiterArrayList(input_buf, '\n', 1e9) catch |err| {
if (err == error.EndOfStream) {
return null;
} else {
unreachable;
}
};
return input_buf.items;
}
fn printUsage(env: *Environment, usage: []const u8) void {
env.printFmt("{s}", .{usage});
}
fn version(env: *Environment) void {
env.printFmt("cosmic {s}\nv8 {s}\n", .{ build_options.VersionName, v8.getVersion() });
}
fn nextArg(args: []const []const u8, idx: *usize) ?[]const u8 {
if (idx.* >= args.len) return null;
defer idx.* += 1;
return args[idx.*];
}
const main_usage =
\\Usage: cosmic [command] [options]
\\
\\Main:
\\
\\ dev Runs a JS source file in dev mode.
\\ run Runs a JS source file.
\\ test Runs a JS source file with the test runner.
\\ shell Starts a shell session.
\\ exe TODO: Packages source files into a single binary executable.
\\
\\Tools:
\\
\\ http Starts an HTTP server over a directory.
\\ https Starts an HTTPS server over a directory.
\\
\\Help:
\\
\\ help Print main usage.
\\ version Print version.
\\ [command] -h Print command-specific usage.
\\ [command] --help
\\
;
const common_run_usage_flags =
\\ --test-api Include the cs.test api.
;
const run_usage = std.fmt.comptimePrint(
\\Usage: cosmic run [src-path]
\\ cosmic [src-path]
\\
\\Flags:
\\{s}
\\
\\Run a js file.
\\
, .{common_run_usage_flags});
const dev_usage = std.fmt.comptimePrint(
\\Usage: cosmic dev [src-path]
\\
\\Flags:
\\{s}
\\
\\Run a js file in dev mode.
\\Dev mode enables hot reloading of your scripts whenever they are modified.
\\It also includes a HUD for viewing debug output and running commands.
\\
, .{common_run_usage_flags});
const test_usage =
\\Usage: cosmic test [src-path]
\\
\\Run a js file with the test runner.
\\Test runner also includes an additional API module `cs.test`
\\which is not available during normal execution with `cosmic run`.
\\A short test report will be printed at the end.
\\Any test failure will result in a non 0 exit code.
\\
;
const shell_usage =
\\Usage: cosmic shell
\\
\\Starts the runtime with an interactive shell.
\\TODO: Support window API in the shell.
\\
;
const http_usage =
\\Usage: cosmic http [dir-path] [addr=127.0.0.1:8081]
\\
\\Starts an HTTP server binding to the address [addr] and serve files from the public directory root at [dir-path].
\\[addr] contains a host and port separated by `:`. The host is optional and defaults to `127.0.0.1`.
\\The port is optional and defaults to 8081.
\\
;
const https_usage =
\\Usage: cosmic https [dir-path] [public-key-path] [private-key-path] [port=127.0.0.1:8081]
\\
\\Starts an HTTPS server binding to the address [addr] and serve files from the public directory root at [dir-path].
\\Paths to public and private keys must be absolute or relative to the public root path.
\\[addr] contains a host and port separated by `:`. The host is optional and defaults to `127.0.0.1`.
\\The port is optional and defaults to 8081.
\\
;
const http_main =
\\let s
\\if (user.https) {
\\ s = cs.http.serveHttps(user.host, user.port, user.certPath, user.keyPath)
\\ const addr = s.getBindAddress()
\\ puts(`HTTPS server started. Binded to ${addr.host}:${addr.port}.`)
\\} else {
\\ s = cs.http.serveHttp(user.host, user.port)
\\ const addr = s.getBindAddress()
\\ puts(`HTTP server started. Binded to ${addr.host}:${addr.port}.`)
\\}
\\s.setHandler((req, resp) => {
\\ if (req.method != 'GET') {
\\ return false
\\ }
\\ const path = req.path.substring(1)
\\ const content = cs.files.read(path)
\\ if (content != null) {
\\ resp.setStatus(200)
\\ if (path.endsWith('.html')) {
\\ resp.setHeader('content-type', 'text/html; charset=utf-8')
\\ } else if (path.endsWith('.css')) {
\\ resp.setHeader('content-type', 'text/css; charset=utf-8')
\\ } else if (path.endsWith('.js')) {
\\ resp.setHeader('content-type', 'text/javascript; charset=utf-8')
\\ } else if (path.endsWith('.png')) {
\\ resp.setHeader('content-type', 'image/png')
\\ } else if (path.endsWith('.ttf')) {
\\ resp.setHeader('content-type', 'font/ttf')
\\ } else {
\\ resp.setHeader('content-type', 'text/plain; charset=utf-8')
\\ }
\\ resp.sendBytes(content)
\\ puts(`GET ${req.path} [200]`)
\\ return true
\\ } else {
\\ puts(`GET ${req.path} [404]`)
\\ return false
\\ }
\\})
;
|
runtime/main.zig
|
const sdl = @import("sdl");
const std = @import("std");
const stdx = @import("stdx");
const t = stdx.testing;
const platform = @import("platform.zig");
const KeyDownEvent = platform.KeyDownEvent;
const KeyUpEvent = platform.KeyUpEvent;
const KeyCode = platform.KeyCode;
const MouseDownEvent = platform.MouseDownEvent;
const MouseUpEvent = platform.MouseUpEvent;
const MouseButton = platform.MouseButton;
const MouseMoveEvent = platform.MouseMoveEvent;
const log = stdx.log.scoped(.input_sdl);
// Converts sdl events into canonical events.
const ButtonMap = b: {
var arr: [6]MouseButton = undefined;
arr[sdl.SDL_BUTTON_LEFT] = .Left;
arr[sdl.SDL_BUTTON_RIGHT] = .Right;
arr[sdl.SDL_BUTTON_MIDDLE] = .Middle;
arr[sdl.SDL_BUTTON_X1] = .X1;
arr[sdl.SDL_BUTTON_X2] = .X2;
break :b arr;
};
test "ButtonMap" {
try t.eq(ButtonMap[sdl.SDL_BUTTON_LEFT], .Left);
try t.eq(ButtonMap[sdl.SDL_BUTTON_RIGHT], .Right);
try t.eq(ButtonMap[sdl.SDL_BUTTON_MIDDLE], .Middle);
try t.eq(ButtonMap[sdl.SDL_BUTTON_X1], .X1);
try t.eq(ButtonMap[sdl.SDL_BUTTON_X2], .X2);
}
pub fn initMouseDownEvent(event: sdl.SDL_MouseButtonEvent) MouseDownEvent {
return MouseDownEvent.init(
ButtonMap[event.button],
@intCast(i16, event.x),
@intCast(i16, event.y),
event.clicks,
);
}
pub fn initMouseUpEvent(event: sdl.SDL_MouseButtonEvent) MouseUpEvent {
return MouseUpEvent.init(
ButtonMap[event.button],
@intCast(i16, event.x),
@intCast(i16, event.y),
event.clicks,
);
}
pub fn initMouseMoveEvent(event: sdl.SDL_MouseMotionEvent) MouseMoveEvent {
return MouseMoveEvent.init(@intCast(i16, event.x), @intCast(i16, event.y));
}
pub fn initMouseScrollEvent(cur_x: i16, cur_y: i16, event: sdl.SDL_MouseWheelEvent) platform.MouseScrollEvent {
return platform.MouseScrollEvent.init(
cur_x,
cur_y,
-event.preciseY * 20,
);
}
pub fn initKeyDownEvent(e: sdl.SDL_KeyboardEvent) KeyDownEvent {
const code = toCanonicalKeyCode(e.keysym.sym);
const shift = e.keysym.mod & (sdl.KMOD_LSHIFT | sdl.KMOD_RSHIFT);
const ctrl = e.keysym.mod & (sdl.KMOD_LCTRL | sdl.KMOD_RCTRL);
const alt = e.keysym.mod & (sdl.KMOD_LALT | sdl.KMOD_RALT);
const meta = e.keysym.mod & (sdl.KMOD_LGUI | sdl.KMOD_RGUI);
return KeyDownEvent.init(code, e.repeat == 1, shift > 0, ctrl > 0, alt > 0, meta > 0);
}
pub fn initKeyUpEvent(e: sdl.SDL_KeyboardEvent) KeyUpEvent {
const code = toCanonicalKeyCode(e.keysym.sym);
const shift = e.keysym.mod & (sdl.KMOD_LSHIFT | sdl.KMOD_RSHIFT);
const ctrl = e.keysym.mod & (sdl.KMOD_LCTRL | sdl.KMOD_RCTRL);
const alt = e.keysym.mod & (sdl.KMOD_LALT | sdl.KMOD_RALT);
const meta = e.keysym.mod & (sdl.KMOD_LGUI | sdl.KMOD_RGUI);
return KeyUpEvent.init(code, shift > 0, ctrl > 0, alt > 0, meta > 0);
}
const MaxLowerRangeCodes = 123;
const LowerRangeMap = b: {
var map: [MaxLowerRangeCodes]KeyCode = undefined;
for (map) |*it| {
it.* = .Unknown;
}
map[sdl.SDLK_UNKNOWN] = .Unknown;
map[sdl.SDLK_RETURN] = .Enter;
map[sdl.SDLK_ESCAPE] = .Escape;
map[sdl.SDLK_BACKSPACE] = .Backspace;
map[sdl.SDLK_TAB] = .Tab;
map[sdl.SDLK_SPACE] = .Space;
map[sdl.SDLK_COMMA] = .Comma;
map[sdl.SDLK_MINUS] = .Minus;
map[sdl.SDLK_PERIOD] = .Period;
map[sdl.SDLK_SLASH] = .Slash;
map[sdl.SDLK_SEMICOLON] = .Semicolon;
map[sdl.SDLK_EQUALS] = .Equal;
map[sdl.SDLK_LEFTBRACKET] = .BracketLeft;
map[sdl.SDLK_BACKSLASH] = .Backslash;
map[sdl.SDLK_RIGHTBRACKET] = .BracketRight;
map[sdl.SDLK_BACKQUOTE] = .Backquote;
for (map[sdl.SDLK_0 .. sdl.SDLK_9 + 1]) |*it, i| {
it.* = @intToEnum(KeyCode, @enumToInt(KeyCode.Digit0) + i);
}
for (map[sdl.SDLK_a .. sdl.SDLK_z + 1]) |*it, i| {
it.* = @intToEnum(KeyCode, @enumToInt(KeyCode.A) + i);
}
break :b map;
};
const UpperRangeMap = b: {
var map: [256]KeyCode = undefined;
const S = struct {
fn toUpperOffset(code: sdl.SDL_Keycode) u8 {
const ucode = @bitCast(u32, code);
return @intCast(u8, ucode & ~(@as(u32, 1) << 30));
}
};
for (map) |*it| {
it.* = .Unknown;
}
const offset = S.toUpperOffset;
for (map[offset(sdl.SDLK_F1) .. offset(sdl.SDLK_F12) + 1]) |*it, i| {
it.* = @intToEnum(KeyCode, @enumToInt(KeyCode.F1) + i);
}
map[offset(sdl.SDLK_CAPSLOCK)] = .CapsLock;
map[offset(sdl.SDLK_PRINTSCREEN)] = .PrintScreen;
map[offset(sdl.SDLK_SCROLLLOCK)] = .ScrollLock;
map[offset(sdl.SDLK_PAUSE)] = .Pause;
map[offset(sdl.SDLK_INSERT)] = .Insert;
map[offset(sdl.SDLK_HOME)] = .Home;
map[offset(sdl.SDLK_PAGEUP)] = .PageUp;
map[offset(sdl.SDLK_DELETE)] = .Delete;
map[offset(sdl.SDLK_END)] = .End;
map[offset(sdl.SDLK_PAGEDOWN)] = .PageDown;
map[offset(sdl.SDLK_RIGHT)] = .ArrowRight;
map[offset(sdl.SDLK_LEFT)] = .ArrowLeft;
map[offset(sdl.SDLK_DOWN)] = .ArrowDown;
map[offset(sdl.SDLK_UP)] = .ArrowUp;
map[offset(sdl.SDLK_LGUI)] = .Meta;
map[offset(sdl.SDLK_LCTRL)] = .ControlLeft;
map[offset(sdl.SDLK_RCTRL)] = .ControlRight;
map[offset(sdl.SDLK_APPLICATION)] = .ContextMenu;
map[offset(sdl.SDLK_LALT)] = .AltLeft;
map[offset(sdl.SDLK_RALT)] = .AltRight;
break :b map;
};
fn toCanonicalKeyCode(code: sdl.SDL_Keycode) KeyCode {
const ucode = @bitCast(u32, code);
if (code < MaxLowerRangeCodes) {
return LowerRangeMap[ucode];
} else if (code <= 1073742055) {
// Remove most significant bit.
const offset = ucode & ~(@as(u32, 1) << 30);
return UpperRangeMap[offset];
} else {
return .Unknown;
}
}
test "toCanonicalKeyCode" {
const S = struct {
fn case(code: sdl.SDL_Keycode, exp: KeyCode) !void {
try t.eq(toCanonicalKeyCode(code), exp);
}
};
const case = S.case;
try case(sdl.SDLK_UNKNOWN, .Unknown);
try case(sdl.SDLK_RETURN, .Enter);
try case(sdl.SDLK_ESCAPE, .Escape);
try case(sdl.SDLK_BACKSPACE, .Backspace);
try case(sdl.SDLK_TAB, .Tab);
try case(sdl.SDLK_SPACE, .Space);
// Not sure why these are in SDL since the same keycode is returned for both shift mod and without.
// pub const SDLK_EXCLAIM: c_int = 33;
// pub const SDLK_QUOTEDBL: c_int = 34;
// pub const SDLK_HASH: c_int = 35;
// pub const SDLK_PERCENT: c_int = 37;
// pub const SDLK_DOLLAR: c_int = 36;
// pub const SDLK_AMPERSAND: c_int = 38;
// pub const SDLK_QUOTE: c_int = 39;
// pub const SDLK_LEFTPAREN: c_int = 40;
// pub const SDLK_RIGHTPAREN: c_int = 41;
// pub const SDLK_ASTERISK: c_int = 42;
// pub const SDLK_PLUS: c_int = 43;
try case(sdl.SDLK_COMMA, .Comma);
try case(sdl.SDLK_MINUS, .Minus);
try case(sdl.SDLK_PERIOD, .Period);
try case(sdl.SDLK_SLASH, .Slash);
try case(sdl.SDLK_0, .Digit0);
try case(sdl.SDLK_1, .Digit1);
try case(sdl.SDLK_2, .Digit2);
try case(sdl.SDLK_3, .Digit3);
try case(sdl.SDLK_4, .Digit4);
try case(sdl.SDLK_5, .Digit5);
try case(sdl.SDLK_6, .Digit6);
try case(sdl.SDLK_7, .Digit7);
try case(sdl.SDLK_8, .Digit8);
try case(sdl.SDLK_9, .Digit9);
// pub const SDLK_COLON: c_int = 58;
try case(sdl.SDLK_SEMICOLON, .Semicolon);
// pub const SDLK_LESS: c_int = 60;
try case(sdl.SDLK_EQUALS, .Equal);
// pub const SDLK_GREATER: c_int = 62;
// pub const SDLK_QUESTION: c_int = 63;
// pub const SDLK_AT: c_int = 64;
try case(sdl.SDLK_LEFTBRACKET, .BracketLeft);
try case(sdl.SDLK_BACKSLASH, .Backslash);
try case(sdl.SDLK_RIGHTBRACKET, .BracketRight);
// pub const SDLK_CARET: c_int = 94;
// pub const SDLK_UNDERSCORE: c_int = 95;
try case(sdl.SDLK_BACKQUOTE, .Backquote);
try case(sdl.SDLK_a, .A);
try case(sdl.SDLK_b, .B);
try case(sdl.SDLK_c, .C);
try case(sdl.SDLK_d, .D);
try case(sdl.SDLK_e, .E);
try case(sdl.SDLK_f, .F);
try case(sdl.SDLK_g, .G);
try case(sdl.SDLK_h, .H);
try case(sdl.SDLK_i, .I);
try case(sdl.SDLK_j, .J);
try case(sdl.SDLK_k, .K);
try case(sdl.SDLK_l, .L);
try case(sdl.SDLK_m, .M);
try case(sdl.SDLK_n, .N);
try case(sdl.SDLK_o, .O);
try case(sdl.SDLK_p, .P);
try case(sdl.SDLK_q, .Q);
try case(sdl.SDLK_r, .R);
try case(sdl.SDLK_s, .S);
try case(sdl.SDLK_t, .T);
try case(sdl.SDLK_u, .U);
try case(sdl.SDLK_v, .V);
try case(sdl.SDLK_w, .W);
try case(sdl.SDLK_x, .X);
try case(sdl.SDLK_y, .Y);
try case(sdl.SDLK_z, .Z);
try case(sdl.SDLK_CAPSLOCK, .CapsLock);
try case(sdl.SDLK_F1, .F1);
try case(sdl.SDLK_F2, .F2);
try case(sdl.SDLK_F3, .F3);
try case(sdl.SDLK_F4, .F4);
try case(sdl.SDLK_F5, .F5);
try case(sdl.SDLK_F6, .F6);
try case(sdl.SDLK_F7, .F7);
try case(sdl.SDLK_F8, .F8);
try case(sdl.SDLK_F9, .F9);
try case(sdl.SDLK_F10, .F10);
try case(sdl.SDLK_F11, .F11);
try case(sdl.SDLK_F12, .F12);
try case(sdl.SDLK_PRINTSCREEN, .PrintScreen);
try case(sdl.SDLK_SCROLLLOCK, .ScrollLock);
try case(sdl.SDLK_PAUSE, .Pause);
try case(sdl.SDLK_INSERT, .Insert);
try case(sdl.SDLK_HOME, .Home);
try case(sdl.SDLK_PAGEUP, .PageUp);
try case(sdl.SDLK_DELETE, .Delete);
try case(sdl.SDLK_END, .End);
try case(sdl.SDLK_PAGEDOWN, .PageDown);
try case(sdl.SDLK_RIGHT, .ArrowRight);
try case(sdl.SDLK_LEFT, .ArrowLeft);
try case(sdl.SDLK_DOWN, .ArrowDown);
try case(sdl.SDLK_UP, .ArrowUp);
try case(sdl.SDLK_LGUI, .Meta);
try case(sdl.SDLK_LCTRL, .ControlLeft);
try case(sdl.SDLK_RCTRL, .ControlRight);
try case(sdl.SDLK_LALT, .AltLeft);
try case(sdl.SDLK_RALT, .AltRight);
// pub const SDLK_NUMLOCKCLEAR: c_int = 1073741907;
// pub const SDLK_KP_DIVIDE: c_int = 1073741908;
// pub const SDLK_KP_MULTIPLY: c_int = 1073741909;
// pub const SDLK_KP_MINUS: c_int = 1073741910;
// pub const SDLK_KP_PLUS: c_int = 1073741911;
// pub const SDLK_KP_ENTER: c_int = 1073741912;
// pub const SDLK_KP_1: c_int = 1073741913;
// pub const SDLK_KP_2: c_int = 1073741914;
// pub const SDLK_KP_3: c_int = 1073741915;
// pub const SDLK_KP_4: c_int = 1073741916;
// pub const SDLK_KP_5: c_int = 1073741917;
// pub const SDLK_KP_6: c_int = 1073741918;
// pub const SDLK_KP_7: c_int = 1073741919;
// pub const SDLK_KP_8: c_int = 1073741920;
// pub const SDLK_KP_9: c_int = 1073741921;
// pub const SDLK_KP_0: c_int = 1073741922;
// pub const SDLK_KP_PERIOD: c_int = 1073741923;
// pub const SDLK_APPLICATION: c_int = 1073741925;
// pub const SDLK_POWER: c_int = 1073741926;
// pub const SDLK_KP_EQUALS: c_int = 1073741927;
// pub const SDLK_F13: c_int = 1073741928;
// pub const SDLK_F14: c_int = 1073741929;
// pub const SDLK_F15: c_int = 1073741930;
// pub const SDLK_F16: c_int = 1073741931;
// pub const SDLK_F17: c_int = 1073741932;
// pub const SDLK_F18: c_int = 1073741933;
// pub const SDLK_F19: c_int = 1073741934;
// pub const SDLK_F20: c_int = 1073741935;
// pub const SDLK_F21: c_int = 1073741936;
// pub const SDLK_F22: c_int = 1073741937;
// ub const SDLK_F23: c_int = 1073741938;
// pub const SDLK_F24: c_int = 1073741939;
// pub const SDLK_EXECUTE: c_int = 1073741940;
// pub const SDLK_HELP: c_int = 1073741941;
// pub const SDLK_MENU: c_int = 1073741942;
// pub const SDLK_SELECT: c_int = 1073741943;
// pub const SDLK_STOP: c_int = 1073741944;
// pub const SDLK_AGAIN: c_int = 1073741945;
// pub const SDLK_UNDO: c_int = 1073741946;
// pub const SDLK_CUT: c_int = 1073741947;
// pub const SDLK_COPY: c_int = 1073741948;
// pub const SDLK_PASTE: c_int = 1073741949;
// pub const SDLK_FIND: c_int = 1073741950;
// pub const SDLK_MUTE: c_int = 1073741951;
// pub const SDLK_VOLUMEUP: c_int = 1073741952;
// pub const SDLK_VOLUMEDOWN: c_int = 1073741953;
// pub const SDLK_KP_COMMA: c_int = 1073741957;
// pub const SDLK_KP_EQUALSAS400: c_int = 1073741958;
// pub const SDLK_ALTERASE: c_int = 1073741977;
// pub const SDLK_SYSREQ: c_int = 1073741978;
// pub const SDLK_CANCEL: c_int = 1073741979;
// pub const SDLK_CLEAR: c_int = 1073741980;
// pub const SDLK_PRIOR: c_int = 1073741981;
// pub const SDLK_RETURN2: c_int = 1073741982;
// pub const SDLK_SEPARATOR: c_int = 1073741983;
// pub const SDLK_OUT: c_int = 1073741984;
// pub const SDLK_OPER: c_int = 1073741985;
// pub const SDLK_CLEARAGAIN: c_int = 1073741986;
// pub const SDLK_CRSEL: c_int = 1073741987;
// pub const SDLK_EXSEL: c_int = 1073741988;
// pub const SDLK_KP_00: c_int = 1073742000;
// pub const SDLK_KP_000: c_int = 1073742001;
// pub const SDLK_THOUSANDSSEPARATOR: c_int = 1073742002;
// pub const SDLK_DECIMALSEPARATOR: c_int = 1073742003;
// pub const SDLK_CURRENCYUNIT: c_int = 1073742004;
// pub const SDLK_CURRENCYSUBUNIT: c_int = 1073742005;
// pub const SDLK_KP_LEFTPAREN: c_int = 1073742006;
// pub const SDLK_KP_RIGHTPAREN: c_int = 1073742007;
// pub const SDLK_KP_LEFTBRACE: c_int = 1073742008;
// pub const SDLK_KP_RIGHTBRACE: c_int = 1073742009;
// pub const SDLK_KP_TAB: c_int = 1073742010;
// pub const SDLK_KP_BACKSPACE: c_int = 1073742011;
// pub const SDLK_KP_A: c_int = 1073742012;
// pub const SDLK_KP_B: c_int = 1073742013;
// pub const SDLK_KP_C: c_int = 1073742014;
// pub const SDLK_KP_D: c_int = 1073742015;
// pub const SDLK_KP_E: c_int = 1073742016;
// pub const SDLK_KP_F: c_int = 1073742017;
// pub const SDLK_KP_XOR: c_int = 1073742018;
// pub const SDLK_KP_POWER: c_int = 1073742019;
// pub const SDLK_KP_PERCENT: c_int = 1073742020;
// pub const SDLK_KP_LESS: c_int = 1073742021;
// pub const SDLK_KP_GREATER: c_int = 1073742022;
// pub const SDLK_KP_AMPERSAND: c_int = 1073742023;
// pub const SDLK_KP_DBLAMPERSAND: c_int = 1073742024;
// pub const SDLK_KP_VERTICALBAR: c_int = 1073742025;
// pub const SDLK_KP_DBLVERTICALBAR: c_int = 1073742026;
// pub const SDLK_KP_COLON: c_int = 1073742027;
// pub const SDLK_KP_HASH: c_int = 1073742028;
// pub const SDLK_KP_SPACE: c_int = 1073742029;
// pub const SDLK_KP_AT: c_int = 1073742030;
// pub const SDLK_KP_EXCLAM: c_int = 1073742031;
// pub const SDLK_KP_MEMSTORE: c_int = 1073742032;
// pub const SDLK_KP_MEMRECALL: c_int = 1073742033;
// pub const SDLK_KP_MEMCLEAR: c_int = 1073742034;
// pub const SDLK_KP_MEMADD: c_int = 1073742035;
// pub const SDLK_KP_MEMSUBTRACT: c_int = 1073742036;
// pub const SDLK_KP_MEMMULTIPLY: c_int = 1073742037;
// pub const SDLK_KP_MEMDIVIDE: c_int = 1073742038;
// pub const SDLK_KP_PLUSMINUS: c_int = 1073742039;
// pub const SDLK_KP_CLEAR: c_int = 1073742040;
// pub const SDLK_KP_CLEARENTRY: c_int = 1073742041;
// pub const SDLK_KP_BINARY: c_int = 1073742042;
// pub const SDLK_KP_OCTAL: c_int = 1073742043;
// pub const SDLK_KP_DECIMAL: c_int = 1073742044;
// pub const SDLK_KP_HEXADECIMAL: c_int = 1073742045;
// pub const SDLK_LCTRL: c_int = 1073742048;
// pub const SDLK_LSHIFT: c_int = 1073742049;
// pub const SDLK_LALT: c_int = 1073742050;
// pub const SDLK_LGUI: c_int = 1073742051;
// pub const SDLK_RCTRL: c_int = 1073742052;
// pub const SDLK_RSHIFT: c_int = 1073742053;
// pub const SDLK_RALT: c_int = 1073742054;
// pub const SDLK_RGUI: c_int = 1073742055;
// pub const SDLK_MODE: c_int = 1073742081;
// pub const SDLK_AUDIONEXT: c_int = 1073742082;
// pub const SDLK_AUDIOPREV: c_int = 1073742083;
// pub const SDLK_AUDIOSTOP: c_int = 1073742084;
// pub const SDLK_AUDIOPLAY: c_int = 1073742085;
// pub const SDLK_AUDIOMUTE: c_int = 1073742086;
// pub const SDLK_MEDIASELECT: c_int = 1073742087;
// pub const SDLK_WWW: c_int = 1073742088;
// pub const SDLK_MAIL: c_int = 1073742089;
// pub const SDLK_CALCULATOR: c_int = 1073742090;
// pub const SDLK_COMPUTER: c_int = 1073742091;
// pub const SDLK_AC_SEARCH: c_int = 1073742092;
// pub const SDLK_AC_HOME: c_int = 1073742093;
// pub const SDLK_AC_BACK: c_int = 1073742094;
// pub const SDLK_AC_FORWARD: c_int = 1073742095;
// pub const SDLK_AC_STOP: c_int = 1073742096;
// pub const SDLK_AC_REFRESH: c_int = 1073742097;
// pub const SDLK_AC_BOOKMARKS: c_int = 1073742098;
// pub const SDLK_BRIGHTNESSDOWN: c_int = 1073742099;
// pub const SDLK_BRIGHTNESSUP: c_int = 1073742100;
// pub const SDLK_DISPLAYSWITCH: c_int = 1073742101;
// pub const SDLK_KBDILLUMTOGGLE: c_int = 1073742102;
// pub const SDLK_KBDILLUMDOWN: c_int = 1073742103;
// pub const SDLK_KBDILLUMUP: c_int = 1073742104;
// pub const SDLK_EJECT: c_int = 1073742105;
// pub const SDLK_SLEEP: c_int = 1073742106;
// pub const SDLK_APP1: c_int = 1073742107;
// pub const SDLK_APP2: c_int = 1073742108;
// pub const SDLK_AUDIOREWIND: c_int = 1073742109;
// pub const SDLK_AUDIOFASTFORWARD: c_int = 1073742110;
}
|
platform/input_sdl.zig
|
const std = @import("std");
const DW = std.dwarf;
const assert = std.debug.assert;
const testing = std.testing;
/// General purpose registers in the SPARCv9 instruction set
pub const Register = enum(u6) {
// zig fmt: off
g0, g1, g2, g3, g4, g5, g6, g7,
o0, o1, o2, o3, o4, o5, o6, o7,
l0, l1, l2, l3, l4, l5, l6, l7,
@"i0", @"i1", @"i2", @"i3", @"i4", @"i5", @"i6", @"i7",
sp = 46, // stack pointer (o6)
fp = 62, // frame pointer (i6)
// zig fmt: on
pub fn id(self: Register) u5 {
return @truncate(u5, @enumToInt(self));
}
pub fn enc(self: Register) u5 {
// For integer registers, enc() == id().
return self.id();
}
pub fn dwarfLocOp(reg: Register) u8 {
return @as(u8, reg.id()) + DW.OP.reg0;
}
};
test "Register.id" {
// SP
try testing.expectEqual(@as(u5, 14), Register.o6.id());
try testing.expectEqual(Register.o6.id(), Register.sp.id());
// FP
try testing.expectEqual(@as(u5, 30), Register.@"i6".id());
try testing.expectEqual(Register.@"i6".id(), Register.fp.id());
// x0
try testing.expectEqual(@as(u5, 0), Register.g0.id());
try testing.expectEqual(@as(u5, 8), Register.o0.id());
try testing.expectEqual(@as(u5, 16), Register.l0.id());
try testing.expectEqual(@as(u5, 24), Register.@"i0".id());
}
test "Register.enc" {
// x0
try testing.expectEqual(@as(u5, 0), Register.g0.enc());
try testing.expectEqual(@as(u5, 8), Register.o0.enc());
try testing.expectEqual(@as(u5, 16), Register.l0.enc());
try testing.expectEqual(@as(u5, 24), Register.@"i0".enc());
// For integer registers, enc() == id().
try testing.expectEqual(Register.g0.enc(), Register.g0.id());
try testing.expectEqual(Register.o0.enc(), Register.o0.id());
try testing.expectEqual(Register.l0.enc(), Register.l0.id());
try testing.expectEqual(Register.@"i0".enc(), Register.@"i0".id());
}
/// Scalar floating point registers in the SPARCv9 instruction set
pub const FloatingPointRegister = enum(u7) {
// SPARCv9 has 64 f32 registers, 32 f64 registers, and 16 f128 registers,
// which are aliased in this way:
//
// | %d0 | %d2 |
// %q0 | %f0 | %f1 | %f2 | %f3 |
// | %d4 | %d6 |
// %q4 | %f4 | %f5 | %f6 | %f7 |
// ...
// | %d60 | %d62 |
// %q60 | %f60 | %f61 | %f62 | %f63 |
//
// Though, since the instructions uses five-bit addressing, only %f0-%f31
// is usable with f32 instructions.
// zig fmt: off
// 32-bit registers
@"f0", @"f1", @"f2", @"f3", @"f4", @"f5", @"f6", @"f7",
@"f8", @"f9", @"f10", @"f11", @"f12", @"f13", @"f14", @"f15",
@"f16", @"f17", @"f18", @"f19", @"f20", @"f21", @"f22", @"f23",
@"f24", @"f25", @"f26", @"f27", @"f28", @"f29", @"f30", @"f31",
// 64-bit registers
d0, d2, d4, d6, d8, d10, d12, d14,
d16, d18, d20, d22, d24, d26, d28, d30,
d32, d34, d36, d38, d40, d42, d44, d46,
d48, d50, d52, d54, d56, d58, d60, d62,
// 128-bit registers
q0, q4, q8, q12, q16, q20, q24, q28,
q32, q36, q40, q44, q48, q52, q56, q60,
// zig fmt: on
pub fn id(self: FloatingPointRegister) u6 {
return switch (self.size()) {
32 => @truncate(u6, @enumToInt(self)),
64 => @truncate(u6, (@enumToInt(self) - 32) * 2),
128 => @truncate(u6, (@enumToInt(self) - 64) * 4),
else => unreachable,
};
}
pub fn enc(self: FloatingPointRegister) u5 {
// Floating point registers use an encoding scheme to map from the 6-bit
// ID to 5-bit encoded value.
// (See section 5.1.4.1 of SPARCv9 ISA specification)
const reg_id = self.id();
return @truncate(u5, reg_id | (reg_id >> 5));
}
/// Returns the bit-width of the register.
pub fn size(self: FloatingPointRegister) u8 {
return switch (@enumToInt(self)) {
0...31 => 32,
32...63 => 64,
64...79 => 128,
else => unreachable,
};
}
};
test "FloatingPointRegister.id" {
// Low region
try testing.expectEqual(@as(u6, 0), FloatingPointRegister.q0.id());
try testing.expectEqual(FloatingPointRegister.q0.id(), FloatingPointRegister.d0.id());
try testing.expectEqual(FloatingPointRegister.d0.id(), FloatingPointRegister.@"f0".id());
try testing.expectEqual(@as(u6, 28), FloatingPointRegister.q28.id());
try testing.expectEqual(FloatingPointRegister.q28.id(), FloatingPointRegister.d28.id());
try testing.expectEqual(FloatingPointRegister.d28.id(), FloatingPointRegister.@"f28".id());
// High region
try testing.expectEqual(@as(u6, 32), FloatingPointRegister.q32.id());
try testing.expectEqual(FloatingPointRegister.q32.id(), FloatingPointRegister.d32.id());
try testing.expectEqual(@as(u6, 60), FloatingPointRegister.q60.id());
try testing.expectEqual(FloatingPointRegister.q60.id(), FloatingPointRegister.d60.id());
}
test "FloatingPointRegister.enc" {
// f registers
try testing.expectEqual(@as(u5, 0), FloatingPointRegister.@"f0".enc());
try testing.expectEqual(@as(u5, 1), FloatingPointRegister.@"f1".enc());
try testing.expectEqual(@as(u5, 31), FloatingPointRegister.@"f31".enc());
// d registers
try testing.expectEqual(@as(u5, 0), FloatingPointRegister.d0.enc());
try testing.expectEqual(@as(u5, 1), FloatingPointRegister.d32.enc());
try testing.expectEqual(@as(u5, 31), FloatingPointRegister.d62.enc());
// q registers
try testing.expectEqual(@as(u5, 0), FloatingPointRegister.q0.enc());
try testing.expectEqual(@as(u5, 1), FloatingPointRegister.q32.enc());
try testing.expectEqual(@as(u5, 29), FloatingPointRegister.q60.enc());
}
/// Represents an instruction in the SPARCv9 instruction set
pub const Instruction = union(enum) {
// Some of the instruction formats have several minor formats, here I
// name them with letters since there's no official naming scheme.
// TODO: need to rename the minor formats to a more descriptive name.
// I am using regular structs instead of packed ones to avoid
// endianness-dependent behavior when constructing the actual
// assembly instructions.
// See also: https://github.com/ziglang/zig/issues/10113
// TODO: change it back to packed structs once the issue is resolved.
// Format 1 (op = 1): CALL
format_1: struct {
op: u2 = 0b01,
disp30: u30,
},
// Format 2 (op = 0): SETHI & Branches (Bicc, BPcc, BPr, FBfcc, FBPfcc)
format_2a: struct {
op: u2 = 0b00,
rd: u5,
op2: u3,
imm22: u22,
},
format_2b: struct {
op: u2 = 0b00,
a: u1,
cond: u4,
op2: u3,
disp22: u22,
},
format_2c: struct {
op: u2 = 0b00,
a: u1,
cond: u4,
op2: u3,
cc1: u1,
cc0: u1,
p: u1,
disp19: u19,
},
format_2d: struct {
op: u2 = 0b00,
a: u1,
fixed: u1 = 0b0,
rcond: u3,
op2: u3,
d16hi: u2,
p: u1,
rs1: u5,
d16lo: u14,
},
// Format 3 (op = 2 or 3): Arithmetic, Logical, MOVr, MEMBAR, Load, and Store
format_3a: struct {
op: u2,
rd: u5,
op3: u6,
rs1: u5,
i: u1 = 0b0,
reserved: u8 = 0b00000000,
rs2: u5,
},
format_3b: struct {
op: u2,
rd: u5,
op3: u6,
rs1: u5,
i: u1 = 0b1,
simm13: u13,
},
format_3c: struct {
op: u2,
reserved1: u5 = 0b00000,
op3: u6,
rs1: u5,
i: u1 = 0b0,
reserved2: u8 = 0b00000000,
rs2: u5,
},
format_3d: struct {
op: u2,
reserved: u5 = 0b00000,
op3: u6,
rs1: u5,
i: u1 = 0b1,
simm13: u13,
},
format_3e: struct {
op: u2,
rd: u5,
op3: u6,
rs1: u5,
i: u1 = 0b0,
rcond: u3,
reserved: u5 = 0b00000,
rs2: u5,
},
format_3f: struct {
op: u2,
rd: u5,
op3: u6,
rs1: u5,
i: u1 = 0b1,
rcond: u3,
simm10: u10,
},
format_3g: struct {
op: u2,
rd: u5,
op3: u6,
rs1: u5,
// See Errata 58 of SPARCv9 specification
// https://sparc.org/errata-for-v9/#58
i: u1 = 0b1,
reserved: u8 = 0b00000000,
rs2: u5,
},
format_3h: struct {
op: u2 = 0b10,
fixed1: u5 = 0b00000,
op3: u6 = 0b101000,
fixed2: u5 = 0b01111,
i: u1 = 0b1,
reserved: u6 = 0b000000,
cmask: u3,
mmask: u4,
},
format_3i: struct {
op: u2,
rd: u5,
op3: u6,
rs1: u5,
i: u1 = 0b0,
imm_asi: u8,
rs2: u5,
},
format_3j: struct {
op: u2,
impl_dep1: u5,
op3: u6,
impl_dep2: u19,
},
format_3k: struct {
op: u2,
rd: u5,
op3: u6,
rs1: u5,
i: u1 = 0b0,
x: u1,
reserved: u7 = 0b0000000,
rs2: u5,
},
format_3l: struct {
op: u2,
rd: u5,
op3: u6,
rs1: u5,
i: u1 = 0b1,
x: u1 = 0b0,
reserved: u7 = 0b0000000,
shcnt32: u5,
},
format_3m: struct {
op: u2,
rd: u5,
op3: u6,
rs1: u5,
i: u1 = 0b1,
x: u1 = 0b1,
reserved: u6 = 0b000000,
shcnt64: u6,
},
format_3n: struct {
op: u2,
rd: u5,
op3: u6,
reserved: u5 = 0b00000,
opf: u9,
rs2: u5,
},
format_3o: struct {
op: u2,
fixed: u3 = 0b000,
cc1: u1,
cc0: u1,
op3: u6,
rs1: u5,
opf: u9,
rs2: u5,
},
format_3p: struct {
op: u2,
rd: u5,
op3: u6,
rs1: u5,
opf: u9,
rs2: u5,
},
format_3q: struct {
op: u2,
rd: u5,
op3: u6,
rs1: u5,
reserved: u14 = 0b00000000000000,
},
format_3r: struct {
op: u2,
fcn: u5,
op3: u6,
reserved: u19 = 0b0000000000000000000,
},
format_3s: struct {
op: u2,
rd: u5,
op3: u6,
reserved: u19 = 0b0000000000000000000,
},
//Format 4 (op = 2): MOVcc, FMOVr, FMOVcc, and Tcc
format_4a: struct {
op: u2 = 0b10,
rd: u5,
op3: u6,
rs1: u5,
i: u1 = 0b0,
cc1: u1,
cc0: u1,
reserved: u6 = 0b000000,
rs2: u5,
},
format_4b: struct {
op: u2 = 0b10,
rd: u5,
op3: u6,
rs1: u5,
i: u1 = 0b1,
cc1: u1,
cc0: u1,
simm11: u11,
},
format_4c: struct {
op: u2 = 0b10,
rd: u5,
op3: u6,
cc2: u1,
cond: u4,
i: u1 = 0b0,
cc1: u1,
cc0: u1,
reserved: u6 = 0b000000,
rs2: u5,
},
format_4d: struct {
op: u2 = 0b10,
rd: u5,
op3: u6,
cc2: u1,
cond: u4,
i: u1 = 0b1,
cc1: u1,
cc0: u1,
simm11: u11,
},
format_4e: struct {
op: u2 = 0b10,
rd: u5,
op3: u6,
rs1: u5,
i: u1 = 0b1,
cc1: u1,
cc0: u1,
reserved: u4 = 0b0000,
sw_trap: u7,
},
format_4f: struct {
op: u2 = 0b10,
rd: u5,
op3: u6,
rs1: u5,
fixed: u1 = 0b0,
rcond: u3,
opf_low: u5,
rs2: u5,
},
format_4g: struct {
op: u2 = 0b10,
rd: u5,
op3: u6,
fixed: u1 = 0b0,
cond: u4,
opf_cc: u3,
opf_low: u6,
rs2: u5,
},
pub const CCR = enum(u3) {
fcc0,
fcc1,
fcc2,
fcc3,
icc,
reserved1,
xcc,
reserved2,
};
pub const RCondition = enum(u3) {
reserved1,
eq_zero,
le_zero,
lt_zero,
reserved2,
ne_zero,
gt_zero,
ge_zero,
};
pub const ASI = enum(u8) {
asi_nucleus = 0x04,
asi_nucleus_little = 0x0c,
asi_as_if_user_primary = 0x10,
asi_as_if_user_secondary = 0x11,
asi_as_if_user_primary_little = 0x18,
asi_as_if_user_secondary_little = 0x19,
asi_primary = 0x80,
asi_secondary = 0x81,
asi_primary_nofault = 0x82,
asi_secondary_nofault = 0x83,
asi_primary_little = 0x88,
asi_secondary_little = 0x89,
asi_primary_nofault_little = 0x8a,
asi_secondary_nofault_little = 0x8b,
};
pub const ShiftWidth = enum(u1) {
shift32,
shift64,
};
pub const MemOrderingConstraint = packed struct {
store_store: bool = false,
load_store: bool = false,
store_load: bool = false,
load_load: bool = false,
};
pub const MemCompletionConstraint = packed struct {
sync: bool = false,
mem_issue: bool = false,
lookaside: bool = false,
};
// TODO: Need to define an enum for `cond` values
// This is kinda challenging since the cond values have different meanings
// depending on whether it's operating on integer or FP CCR.
pub const Condition = u4;
pub fn toU32(self: Instruction) u32 {
// TODO: Remove this once packed structs work.
return switch (self) {
.format_1 => |v| (@as(u32, v.op) << 30) | @as(u32, v.disp30),
.format_2a => |v| (@as(u32, v.op) << 30) | (@as(u32, v.rd) << 25) | (@as(u32, v.op2) << 22) | @as(u32, v.imm22),
.format_2b => |v| (@as(u32, v.op) << 30) | (@as(u32, v.a) << 29) | (@as(u32, v.cond) << 25) | (@as(u32, v.op2) << 22) | @as(u32, v.disp22),
.format_2c => |v| (@as(u32, v.op) << 30) | (@as(u32, v.a) << 29) | (@as(u32, v.cond) << 25) | (@as(u32, v.op2) << 22) | (@as(u32, v.cc1) << 21) | (@as(u32, v.cc0) << 20) | (@as(u32, v.p) << 19) | @as(u32, v.disp19),
.format_2d => |v| (@as(u32, v.op) << 30) | (@as(u32, v.a) << 29) | (@as(u32, v.fixed) << 28) | (@as(u32, v.rcond) << 25) | (@as(u32, v.op2) << 22) | (@as(u32, v.d16hi) << 20) | (@as(u32, v.p) << 19) | (@as(u32, v.rs1) << 14) | @as(u32, v.d16lo),
.format_3a => |v| (@as(u32, v.op) << 30) | (@as(u32, v.rd) << 25) | (@as(u32, v.op3) << 19) | (@as(u32, v.rs1) << 14) | (@as(u32, v.i) << 13) | (@as(u32, v.reserved) << 5) | @as(u32, v.rs2),
.format_3b => |v| (@as(u32, v.op) << 30) | (@as(u32, v.rd) << 25) | (@as(u32, v.op3) << 19) | (@as(u32, v.rs1) << 14) | (@as(u32, v.i) << 13) | @as(u32, v.simm13),
.format_3c => |v| (@as(u32, v.op) << 30) | (@as(u32, v.reserved1) << 25) | (@as(u32, v.op3) << 19) | (@as(u32, v.rs1) << 14) | (@as(u32, v.i) << 13) | (@as(u32, v.reserved2) << 5) | @as(u32, v.rs2),
.format_3d => |v| (@as(u32, v.op) << 30) | (@as(u32, v.reserved) << 25) | (@as(u32, v.op3) << 19) | (@as(u32, v.rs1) << 14) | (@as(u32, v.i) << 13) | @as(u32, v.simm13),
.format_3e => |v| (@as(u32, v.op) << 30) | (@as(u32, v.rd) << 25) | (@as(u32, v.op3) << 19) | (@as(u32, v.rs1) << 14) | (@as(u32, v.i) << 13) | (@as(u32, v.rcond) << 10) | (@as(u32, v.reserved) << 5) | @as(u32, v.rs2),
.format_3f => |v| (@as(u32, v.op) << 30) | (@as(u32, v.rd) << 25) | (@as(u32, v.op3) << 19) | (@as(u32, v.rs1) << 14) | (@as(u32, v.i) << 13) | (@as(u32, v.rcond) << 10) | @as(u32, v.simm10),
.format_3g => |v| (@as(u32, v.op) << 30) | (@as(u32, v.rd) << 25) | (@as(u32, v.op3) << 19) | (@as(u32, v.rs1) << 14) | (@as(u32, v.i) << 13) | (@as(u32, v.reserved) << 5) | @as(u32, v.rs2),
.format_3h => |v| (@as(u32, v.op) << 30) | (@as(u32, v.fixed1) << 25) | (@as(u32, v.op3) << 19) | (@as(u32, v.fixed2) << 14) | (@as(u32, v.i) << 13) | (@as(u32, v.reserved) << 7) | (@as(u32, v.cmask) << 4) | @as(u32, v.mmask),
.format_3i => |v| (@as(u32, v.op) << 30) | (@as(u32, v.rd) << 25) | (@as(u32, v.op3) << 19) | (@as(u32, v.rs1) << 14) | (@as(u32, v.i) << 13) | (@as(u32, v.imm_asi) << 5) | @as(u32, v.rs2),
.format_3j => |v| (@as(u32, v.op) << 30) | (@as(u32, v.impl_dep1) << 25) | (@as(u32, v.op3) << 19) | @as(u32, v.impl_dep2),
.format_3k => |v| (@as(u32, v.op) << 30) | (@as(u32, v.rd) << 25) | (@as(u32, v.op3) << 19) | (@as(u32, v.rs1) << 14) | (@as(u32, v.i) << 13) | (@as(u32, v.x) << 12) | (@as(u32, v.reserved) << 5) | @as(u32, v.rs2),
.format_3l => |v| (@as(u32, v.op) << 30) | (@as(u32, v.rd) << 25) | (@as(u32, v.op3) << 19) | (@as(u32, v.rs1) << 14) | (@as(u32, v.i) << 13) | (@as(u32, v.x) << 12) | (@as(u32, v.reserved) << 5) | @as(u32, v.shcnt32),
.format_3m => |v| (@as(u32, v.op) << 30) | (@as(u32, v.rd) << 25) | (@as(u32, v.op3) << 19) | (@as(u32, v.rs1) << 14) | (@as(u32, v.i) << 13) | (@as(u32, v.x) << 12) | (@as(u32, v.reserved) << 6) | @as(u32, v.shcnt64),
.format_3n => |v| (@as(u32, v.op) << 30) | (@as(u32, v.rd) << 25) | (@as(u32, v.op3) << 19) | (@as(u32, v.reserved) << 14) | (@as(u32, v.opf) << 5) | @as(u32, v.rs2),
.format_3o => |v| (@as(u32, v.op) << 30) | (@as(u32, v.fixed) << 27) | (@as(u32, v.cc1) << 26) | (@as(u32, v.cc0) << 25) | (@as(u32, v.op3) << 19) | (@as(u32, v.rs1) << 14) | (@as(u32, v.opf) << 5) | @as(u32, v.rs2),
.format_3p => |v| (@as(u32, v.op) << 30) | (@as(u32, v.rd) << 25) | (@as(u32, v.op3) << 19) | (@as(u32, v.rs1) << 14) | (@as(u32, v.opf) << 5) | @as(u32, v.rs2),
.format_3q => |v| (@as(u32, v.op) << 30) | (@as(u32, v.rd) << 25) | (@as(u32, v.op3) << 19) | (@as(u32, v.rs1) << 14) | @as(u32, v.reserved),
.format_3r => |v| (@as(u32, v.op) << 30) | (@as(u32, v.fcn) << 25) | (@as(u32, v.op3) << 19) | @as(u32, v.reserved),
.format_3s => |v| (@as(u32, v.op) << 30) | (@as(u32, v.rd) << 25) | (@as(u32, v.op3) << 19) | @as(u32, v.reserved),
.format_4a => |v| (@as(u32, v.op) << 30) | (@as(u32, v.rd) << 25) | (@as(u32, v.op3) << 19) | (@as(u32, v.rs1) << 14) | (@as(u32, v.i) << 13) | (@as(u32, v.cc1) << 12) | (@as(u32, v.cc0) << 11) | (@as(u32, v.reserved) << 5) | @as(u32, v.rs2),
.format_4b => |v| (@as(u32, v.op) << 30) | (@as(u32, v.rd) << 25) | (@as(u32, v.op3) << 19) | (@as(u32, v.rs1) << 14) | (@as(u32, v.i) << 13) | (@as(u32, v.cc1) << 12) | (@as(u32, v.cc0) << 11) | @as(u32, v.simm11),
.format_4c => |v| (@as(u32, v.op) << 30) | (@as(u32, v.rd) << 25) | (@as(u32, v.op3) << 19) | (@as(u32, v.cc2) << 18) | (@as(u32, v.cond) << 14) | (@as(u32, v.i) << 13) | (@as(u32, v.cc1) << 12) | (@as(u32, v.cc0) << 11) | (@as(u32, v.reserved) << 5) | @as(u32, v.rs2),
.format_4d => |v| (@as(u32, v.op) << 30) | (@as(u32, v.rd) << 25) | (@as(u32, v.op3) << 19) | (@as(u32, v.cc2) << 18) | (@as(u32, v.cond) << 14) | (@as(u32, v.i) << 13) | (@as(u32, v.cc1) << 12) | (@as(u32, v.cc0) << 11) | @as(u32, v.simm11),
.format_4e => |v| (@as(u32, v.op) << 30) | (@as(u32, v.rd) << 25) | (@as(u32, v.op3) << 19) | (@as(u32, v.rs1) << 14) | (@as(u32, v.i) << 13) | (@as(u32, v.cc1) << 12) | (@as(u32, v.cc0) << 11) | (@as(u32, v.reserved) << 7) | @as(u32, v.sw_trap),
.format_4f => |v| (@as(u32, v.op) << 30) | (@as(u32, v.rd) << 25) | (@as(u32, v.op3) << 19) | (@as(u32, v.rs1) << 14) | (@as(u32, v.fixed) << 13) | (@as(u32, v.rcond) << 10) | (@as(u32, v.opf_low) << 5) | @as(u32, v.rs2),
.format_4g => |v| (@as(u32, v.op) << 30) | (@as(u32, v.rd) << 25) | (@as(u32, v.op3) << 19) | (@as(u32, v.fixed) << 18) | (@as(u32, v.cond) << 14) | (@as(u32, v.opf_cc) << 11) | (@as(u32, v.opf_low) << 5) | @as(u32, v.rs2),
};
}
// SPARCv9 Instruction formats.
// See section 6.2 of the SPARCv9 ISA manual.
fn format1(disp: i32) Instruction {
const udisp = @bitCast(u32, disp);
// In SPARC, branch target needs to be aligned to 4 bytes.
assert(udisp % 4 == 0);
// Discard the last two bits since those are implicitly zero.
const udisp_truncated = @truncate(u30, udisp >> 2);
return Instruction{
.format_1 = .{
.disp30 = udisp_truncated,
},
};
}
fn format2a(op2: u3, imm: u22, rd: Register) Instruction {
return Instruction{
.format_2a = .{
.rd = rd.enc(),
.op2 = op2,
.imm22 = imm,
},
};
}
fn format2b(op2: u3, cond: Condition, annul: bool, disp: i24) Instruction {
const udisp = @bitCast(u24, disp);
// In SPARC, branch target needs to be aligned to 4 bytes.
assert(udisp % 4 == 0);
// Discard the last two bits since those are implicitly zero.
const udisp_truncated = @truncate(u22, udisp >> 2);
return Instruction{
.format_2b = .{
.a = @boolToInt(annul),
.cond = cond,
.op2 = op2,
.disp22 = udisp_truncated,
},
};
}
fn format2c(op2: u3, cond: Condition, annul: bool, pt: bool, ccr: CCR, disp: i21) Instruction {
const udisp = @bitCast(u21, disp);
// In SPARC, branch target needs to be aligned to 4 bytes.
assert(udisp % 4 == 0);
// Discard the last two bits since those are implicitly zero.
const udisp_truncated = @truncate(u19, udisp >> 2);
const ccr_cc1 = @truncate(u1, @enumToInt(ccr) >> 1);
const ccr_cc0 = @truncate(u1, @enumToInt(ccr));
return Instruction{
.format_2c = .{
.a = @boolToInt(annul),
.cond = cond,
.op2 = op2,
.cc1 = ccr_cc1,
.cc0 = ccr_cc0,
.p = @boolToInt(pt),
.disp19 = udisp_truncated,
},
};
}
fn format2d(op2: u3, rcond: RCondition, annul: bool, pt: bool, rs1: Register, disp: i18) Instruction {
const udisp = @bitCast(u18, disp);
// In SPARC, branch target needs to be aligned to 4 bytes.
assert(udisp % 4 == 0);
// Discard the last two bits since those are implicitly zero,
// and split it into low and high parts.
const udisp_truncated = @truncate(u16, udisp >> 2);
const udisp_hi = @truncate(u2, (udisp_truncated & 0b1100_0000_0000_0000) >> 14);
const udisp_lo = @truncate(u14, udisp_truncated & 0b0011_1111_1111_1111);
return Instruction{
.format_2d = .{
.a = @boolToInt(annul),
.rcond = @enumToInt(rcond),
.op2 = op2,
.p = @boolToInt(pt),
.rs1 = rs1.enc(),
.d16hi = udisp_hi,
.d16lo = udisp_lo,
},
};
}
fn format3a(op: u2, op3: u6, rs1: Register, rs2: Register, rd: Register) Instruction {
return Instruction{
.format_3a = .{
.op = op,
.rd = rd.enc(),
.op3 = op3,
.rs1 = rs1.enc(),
.rs2 = rs2.enc(),
},
};
}
fn format3b(op: u2, op3: u6, rs1: Register, imm: i13, rd: Register) Instruction {
return Instruction{
.format_3b = .{
.op = op,
.rd = rd.enc(),
.op3 = op3,
.rs1 = rs1.enc(),
.simm13 = @bitCast(u13, imm),
},
};
}
fn format3c(op: u2, op3: u6, rs1: Register, rs2: Register) Instruction {
return Instruction{
.format_3c = .{
.op = op,
.op3 = op3,
.rs1 = rs1.enc(),
.rs2 = rs2.enc(),
},
};
}
fn format3d(op: u2, op3: u6, rs1: Register, imm: i13) Instruction {
return Instruction{
.format_3d = .{
.op = op,
.op3 = op3,
.rs1 = rs1.enc(),
.simm13 = @bitCast(u13, imm),
},
};
}
fn format3e(op: u2, op3: u6, rcond: RCondition, rs1: Register, rs2: Register, rd: Register) Instruction {
return Instruction{
.format_3e = .{
.op = op,
.rd = rd.enc(),
.op3 = op3,
.rs1 = rs1.enc(),
.rcond = @enumToInt(rcond),
.rs2 = rs2.enc(),
},
};
}
fn format3f(op: u2, op3: u6, rcond: RCondition, rs1: Register, imm: i10, rd: Register) Instruction {
return Instruction{
.format_3f = .{
.op = op,
.rd = rd.enc(),
.op3 = op3,
.rs1 = rs1.enc(),
.rcond = @enumToInt(rcond),
.simm10 = @bitCast(u10, imm),
},
};
}
fn format3g(op: u2, op3: u6, rs1: Register, rs2: Register, rd: Register) Instruction {
return Instruction{
.format_3g = .{
.op = op,
.rd = rd.enc(),
.op3 = op3,
.rs1 = rs1.enc(),
.rs2 = rs2.enc(),
},
};
}
fn format3h(cmask: MemCompletionConstraint, mmask: MemOrderingConstraint) Instruction {
return Instruction{
.format_3h = .{
.cmask = @bitCast(u3, cmask),
.mmask = @bitCast(u4, mmask),
},
};
}
fn format3i(op: u2, op3: u6, rs1: Register, rs2: Register, rd: Register, asi: ASI) Instruction {
return Instruction{
.format_3i = .{
.op = op,
.rd = rd.enc(),
.op3 = op3,
.rs1 = rs1.enc(),
.imm_asi = @enumToInt(asi),
.rs2 = rs2.enc(),
},
};
}
fn format3j(op: u2, op3: u6, impl_dep1: u5, impl_dep2: u19) Instruction {
return Instruction{
.format_3j = .{
.op = op,
.impl_dep1 = impl_dep1,
.op3 = op3,
.impl_dep2 = impl_dep2,
},
};
}
fn format3k(op: u2, op3: u6, sw: ShiftWidth, rs1: Register, rs2: Register, rd: Register) Instruction {
return Instruction{
.format_3k = .{
.op = op,
.rd = rd.enc(),
.op3 = op3,
.rs1 = rs1.enc(),
.x = @enumToInt(sw),
.rs2 = rs2.enc(),
},
};
}
fn format3l(op: u2, op3: u6, rs1: Register, shift_count: u5, rd: Register) Instruction {
return Instruction{
.format_3l = .{
.op = op,
.rd = rd.enc(),
.op3 = op3,
.rs1 = rs1.enc(),
.shcnt32 = shift_count,
},
};
}
fn format3m(op: u2, op3: u6, rs1: Register, shift_count: u6, rd: Register) Instruction {
return Instruction{
.format_3m = .{
.op = op,
.rd = rd.enc(),
.op3 = op3,
.rs1 = rs1.enc(),
.shcnt64 = shift_count,
},
};
}
fn format3n(op: u2, op3: u6, opf: u9, rs2: Register, rd: Register) Instruction {
return Instruction{
.format_3n = .{
.op = op,
.rd = rd.enc(),
.op3 = op3,
.opf = opf,
.rs2 = rs2.enc(),
},
};
}
fn format3o(op: u2, op3: u6, opf: u9, ccr: CCR, rs1: Register, rs2: Register) Instruction {
const ccr_cc1 = @truncate(u1, @enumToInt(ccr) >> 1);
const ccr_cc0 = @truncate(u1, @enumToInt(ccr));
return Instruction{
.format_3o = .{
.op = op,
.cc1 = ccr_cc1,
.cc0 = ccr_cc0,
.op3 = op3,
.rs1 = rs1.enc(),
.opf = opf,
.rs2 = rs2.enc(),
},
};
}
fn format3p(op: u2, op3: u6, opf: u9, rs1: Register, rs2: Register, rd: Register) Instruction {
return Instruction{
.format_3p = .{
.op = op,
.rd = rd.enc(),
.op3 = op3,
.rs1 = rs1.enc(),
.opf = opf,
.rs2 = rs2.enc(),
},
};
}
fn format3q(op: u2, op3: u6, rs1: Register, rd: Register) Instruction {
return Instruction{
.format_3q = .{
.op = op,
.rd = rd.enc(),
.op3 = op3,
.rs1 = rs1.enc(),
},
};
}
fn format3r(op: u2, op3: u6, fcn: u5) Instruction {
return Instruction{
.format_3r = .{
.op = op,
.fcn = fcn,
.op3 = op3,
},
};
}
fn format3s(op: u2, op3: u6, rd: Register) Instruction {
return Instruction{
.format_3s = .{
.op = op,
.rd = rd.enc(),
.op3 = op3,
},
};
}
fn format4a(op3: u6, ccr: CCR, rs1: Register, rs2: Register, rd: Register) Instruction {
const ccr_cc1 = @truncate(u1, @enumToInt(ccr) >> 1);
const ccr_cc0 = @truncate(u1, @enumToInt(ccr));
return Instruction{
.format_4a = .{
.rd = rd.enc(),
.op3 = op3,
.rs1 = rs1.enc(),
.cc1 = ccr_cc1,
.cc0 = ccr_cc0,
.rs2 = rs2.enc(),
},
};
}
fn format4b(op3: u6, ccr: CCR, rs1: Register, imm: i11, rd: Register) Instruction {
const ccr_cc1 = @truncate(u1, @enumToInt(ccr) >> 1);
const ccr_cc0 = @truncate(u1, @enumToInt(ccr));
return Instruction{
.format_4b = .{
.rd = rd.enc(),
.op3 = op3,
.rs1 = rs1.enc(),
.cc1 = ccr_cc1,
.cc0 = ccr_cc0,
.simm11 = @bitCast(u11, imm),
},
};
}
fn format4c(op3: u6, cond: Condition, ccr: CCR, rs2: Register, rd: Register) Instruction {
const ccr_cc2 = @truncate(u1, @enumToInt(ccr) >> 2);
const ccr_cc1 = @truncate(u1, @enumToInt(ccr) >> 1);
const ccr_cc0 = @truncate(u1, @enumToInt(ccr));
return Instruction{
.format_4c = .{
.rd = rd.enc(),
.op3 = op3,
.cc2 = ccr_cc2,
.cond = cond,
.cc1 = ccr_cc1,
.cc0 = ccr_cc0,
.rs2 = rs2.enc(),
},
};
}
fn format4d(op3: u6, cond: Condition, ccr: CCR, imm: i11, rd: Register) Instruction {
const ccr_cc2 = @truncate(u1, @enumToInt(ccr) >> 2);
const ccr_cc1 = @truncate(u1, @enumToInt(ccr) >> 1);
const ccr_cc0 = @truncate(u1, @enumToInt(ccr));
return Instruction{
.format_4d = .{
.rd = rd.enc(),
.op3 = op3,
.cc2 = ccr_cc2,
.cond = cond,
.cc1 = ccr_cc1,
.cc0 = ccr_cc0,
.simm11 = @bitCast(u11, imm),
},
};
}
fn format4e(op3: u6, ccr: CCR, rs1: Register, rd: Register, sw_trap: u7) Instruction {
const ccr_cc1 = @truncate(u1, @enumToInt(ccr) >> 1);
const ccr_cc0 = @truncate(u1, @enumToInt(ccr));
return Instruction{
.format_4e = .{
.rd = rd.enc(),
.op3 = op3,
.rs1 = rs1.enc(),
.cc1 = ccr_cc1,
.cc0 = ccr_cc0,
.sw_trap = sw_trap,
},
};
}
fn format4f(
op3: u6,
opf_low: u5,
rcond: RCondition,
rs1: Register,
rs2: Register,
rd: Register,
) Instruction {
return Instruction{
.format_4f = .{
.rd = rd.enc(),
.op3 = op3,
.rs1 = rs1.enc(),
.rcond = @enumToInt(rcond),
.opf_low = opf_low,
.rs2 = rs2.enc(),
},
};
}
fn format4g(op3: u6, opf_low: u6, opf_cc: u3, cond: Condition, rs2: Register, rd: Register) Instruction {
return Instruction{
.format_4g = .{
.rd = rd.enc(),
.op3 = op3,
.cond = cond,
.opf_cc = opf_cc,
.opf_low = opf_low,
.rs2 = rs2.enc(),
},
};
}
// SPARCv9 Instruction definition.
// See appendix A of the SPARCv9 ISA manual.
pub fn add(comptime s2: type, rs1: Register, rs2: s2, rd: Register) Instruction {
return switch (s2) {
Register => format3a(0b10, 0b00_0000, rs1, rs2, rd),
i13 => format3b(0b10, 0b00_0000, rs1, rs2, rd),
else => unreachable,
};
}
pub fn jmpl(comptime s2: type, rs1: Register, rs2: s2, rd: Register) Instruction {
return switch (s2) {
Register => format3a(0b10, 0b11_1000, rs1, rs2, rd),
i13 => format3b(0b10, 0b11_1000, rs1, rs2, rd),
else => unreachable,
};
}
pub fn ldub(comptime s2: type, rs1: Register, rs2: s2, rd: Register) Instruction {
return switch (s2) {
Register => format3a(0b11, 0b00_0001, rs1, rs2, rd),
i13 => format3b(0b11, 0b00_0001, rs1, rs2, rd),
else => unreachable,
};
}
pub fn lduh(comptime s2: type, rs1: Register, rs2: s2, rd: Register) Instruction {
return switch (s2) {
Register => format3a(0b11, 0b00_0010, rs1, rs2, rd),
i13 => format3b(0b11, 0b00_0010, rs1, rs2, rd),
else => unreachable,
};
}
pub fn lduw(comptime s2: type, rs1: Register, rs2: s2, rd: Register) Instruction {
return switch (s2) {
Register => format3a(0b11, 0b00_0000, rs1, rs2, rd),
i13 => format3b(0b11, 0b00_0000, rs1, rs2, rd),
else => unreachable,
};
}
pub fn ldx(comptime s2: type, rs1: Register, rs2: s2, rd: Register) Instruction {
return switch (s2) {
Register => format3a(0b11, 0b00_1011, rs1, rs2, rd),
i13 => format3b(0b11, 0b00_1011, rs1, rs2, rd),
else => unreachable,
};
}
pub fn @"or"(comptime s2: type, rs1: Register, rs2: s2, rd: Register) Instruction {
return switch (s2) {
Register => format3a(0b10, 0b00_0010, rs1, rs2, rd),
i13 => format3b(0b10, 0b00_0010, rs1, rs2, rd),
else => unreachable,
};
}
pub fn nop() Instruction {
return sethi(0, .g0);
}
pub fn @"return"(comptime s2: type, rs1: Register, rs2: s2) Instruction {
return switch (s2) {
Register => format3c(0b10, 0b11_1001, rs1, rs2),
i13 => format3d(0b10, 0b11_1001, rs1, rs2),
else => unreachable,
};
}
pub fn save(comptime s2: type, rs1: Register, rs2: s2, rd: Register) Instruction {
return switch (s2) {
Register => format3a(0b10, 0b11_1100, rs1, rs2, rd),
i13 => format3b(0b10, 0b11_1100, rs1, rs2, rd),
else => unreachable,
};
}
pub fn restore(comptime s2: type, rs1: Register, rs2: s2, rd: Register) Instruction {
return switch (s2) {
Register => format3a(0b10, 0b11_1101, rs1, rs2, rd),
i13 => format3b(0b10, 0b11_1101, rs1, rs2, rd),
else => unreachable,
};
}
pub fn sethi(imm: u22, rd: Register) Instruction {
return format2a(0b100, imm, rd);
}
pub fn stb(comptime s2: type, rs1: Register, rs2: s2, rd: Register) Instruction {
return switch (s2) {
Register => format3a(0b11, 0b00_0101, rs1, rs2, rd),
i13 => format3b(0b11, 0b00_0101, rs1, rs2, rd),
else => unreachable,
};
}
pub fn sth(comptime s2: type, rs1: Register, rs2: s2, rd: Register) Instruction {
return switch (s2) {
Register => format3a(0b11, 0b00_0110, rs1, rs2, rd),
i13 => format3b(0b11, 0b00_0110, rs1, rs2, rd),
else => unreachable,
};
}
pub fn stw(comptime s2: type, rs1: Register, rs2: s2, rd: Register) Instruction {
return switch (s2) {
Register => format3a(0b11, 0b00_0100, rs1, rs2, rd),
i13 => format3b(0b11, 0b00_0100, rs1, rs2, rd),
else => unreachable,
};
}
pub fn stx(comptime s2: type, rs1: Register, rs2: s2, rd: Register) Instruction {
return switch (s2) {
Register => format3a(0b11, 0b00_1110, rs1, rs2, rd),
i13 => format3b(0b11, 0b00_1110, rs1, rs2, rd),
else => unreachable,
};
}
pub fn sub(comptime s2: type, rs1: Register, rs2: s2, rd: Register) Instruction {
return switch (s2) {
Register => format3a(0b10, 0b00_0100, rs1, rs2, rd),
i13 => format3b(0b10, 0b00_0100, rs1, rs2, rd),
else => unreachable,
};
}
pub fn trap(comptime s2: type, cond: Condition, ccr: CCR, rs1: Register, rs2: s2) Instruction {
// Tcc instructions abuse the rd field to store the conditionals.
return switch (s2) {
Register => format4a(0b11_1010, ccr, rs1, rs2, @intToEnum(Register, cond)),
u7 => format4e(0b11_1010, ccr, rs1, @intToEnum(Register, cond), rs2),
else => unreachable,
};
}
};
test "Serialize formats" {
const Testcase = struct {
inst: Instruction,
expected: u32,
};
// Note that the testcases might or might not be a valid instruction
// This is mostly just to check the behavior of the format packed structs
// since currently stage1 doesn't properly implement it in all cases
const testcases = [_]Testcase{
.{
.inst = Instruction.format1(4),
.expected = 0b01_000000000000000000000000000001,
},
.{
.inst = Instruction.format2a(4, 0, .g0),
.expected = 0b00_00000_100_0000000000000000000000,
},
.{
.inst = Instruction.format2b(6, 3, true, -4),
.expected = 0b00_1_0011_110_1111111111111111111111,
},
.{
.inst = Instruction.format2c(3, 0, false, true, .xcc, 8),
.expected = 0b00_0_0000_011_1_0_1_0000000000000000010,
},
.{
.inst = Instruction.format2d(7, .eq_zero, false, true, .o0, 20),
.expected = 0b00_0_0_001_111_00_1_01000_00000000000101,
},
.{
.inst = Instruction.format3a(3, 5, .g0, .o1, .l2),
.expected = 0b11_10010_000101_00000_0_00000000_01001,
},
.{
.inst = Instruction.format3b(3, 5, .g0, -1, .l2),
.expected = 0b11_10010_000101_00000_1_1111111111111,
},
.{
.inst = Instruction.format3c(3, 5, .g0, .o1),
.expected = 0b11_00000_000101_00000_0_00000000_01001,
},
.{
.inst = Instruction.format3d(3, 5, .g0, 0),
.expected = 0b11_00000_000101_00000_1_0000000000000,
},
.{
.inst = Instruction.format3e(3, 5, .ne_zero, .g0, .o1, .l2),
.expected = 0b11_10010_000101_00000_0_101_00000_01001,
},
.{
.inst = Instruction.format3f(3, 5, .ne_zero, .g0, -1, .l2),
.expected = 0b11_10010_000101_00000_1_101_1111111111,
},
.{
.inst = Instruction.format3g(3, 5, .g0, .o1, .l2),
.expected = 0b11_10010_000101_00000_1_00000000_01001,
},
.{
.inst = Instruction.format3h(.{}, .{}),
.expected = 0b10_00000_101000_01111_1_000000_000_0000,
},
.{
.inst = Instruction.format3i(3, 5, .g0, .o1, .l2, .asi_primary_little),
.expected = 0b11_10010_000101_00000_0_10001000_01001,
},
.{
.inst = Instruction.format3j(3, 5, 31, 0),
.expected = 0b11_11111_000101_0000000000000000000,
},
.{
.inst = Instruction.format3k(3, 5, .shift32, .g0, .o1, .l2),
.expected = 0b11_10010_000101_00000_0_0_0000000_01001,
},
.{
.inst = Instruction.format3l(3, 5, .g0, 31, .l2),
.expected = 0b11_10010_000101_00000_1_0_0000000_11111,
},
.{
.inst = Instruction.format3m(3, 5, .g0, 63, .l2),
.expected = 0b11_10010_000101_00000_1_1_000000_111111,
},
.{
.inst = Instruction.format3n(3, 5, 0, .o1, .l2),
.expected = 0b11_10010_000101_00000_000000000_01001,
},
.{
.inst = Instruction.format3o(3, 5, 0, .xcc, .o1, .l2),
.expected = 0b11_000_1_0_000101_01001_000000000_10010,
},
.{
.inst = Instruction.format3p(3, 5, 0, .g0, .o1, .l2),
.expected = 0b11_10010_000101_00000_000000000_01001,
},
.{
.inst = Instruction.format3q(3, 5, .g0, .o1),
.expected = 0b11_01001_000101_00000_00000000000000,
},
.{
.inst = Instruction.format3r(3, 5, 4),
.expected = 0b11_00100_000101_0000000000000000000,
},
.{
.inst = Instruction.format3s(3, 5, .g0),
.expected = 0b11_00000_000101_0000000000000000000,
},
.{
.inst = Instruction.format4a(8, .xcc, .g0, .o1, .l2),
.expected = 0b10_10010_001000_00000_0_1_0_000000_01001,
},
.{
.inst = Instruction.format4b(8, .xcc, .g0, -1, .l2),
.expected = 0b10_10010_001000_00000_1_1_0_11111111111,
},
.{
.inst = Instruction.format4c(8, 0, .xcc, .g0, .o1),
.expected = 0b10_01001_001000_1_0000_0_1_0_000000_00000,
},
.{
.inst = Instruction.format4d(8, 0, .xcc, 0, .l2),
.expected = 0b10_10010_001000_1_0000_1_1_0_00000000000,
},
.{
.inst = Instruction.format4e(8, .xcc, .g0, .o1, 0),
.expected = 0b10_01001_001000_00000_1_1_0_0000_0000000,
},
.{
.inst = Instruction.format4f(8, 4, .eq_zero, .g0, .o1, .l2),
.expected = 0b10_10010_001000_00000_0_001_00100_01001,
},
.{
.inst = Instruction.format4g(8, 4, 2, 0, .o1, .l2),
.expected = 0b10_10010_001000_0_0000_010_000100_01001,
},
};
for (testcases) |case| {
const actual = case.inst.toU32();
testing.expectEqual(case.expected, actual) catch |err| {
std.debug.print("error: {x}\n", .{err});
std.debug.print("case: {x}\n", .{case});
return err;
};
}
}
|
src/arch/sparcv9/bits.zig
|
const Archive = @This();
const builtin = @import("builtin");
const std = @import("std");
const fmt = std.fmt;
const fs = std.fs;
const mem = std.mem;
const log = std.log.scoped(.archive);
const Allocator = std.mem.Allocator;
file: fs.File,
name: []const u8,
// We need to differentiate between inferred and output archive type, as other ar
// programs "just handle" any valid archive for parsing, regarldess of what a
// user has specified - the user specification should only matter for writing
// archives.
inferred_archive_type: ArchiveType,
output_archive_type: ArchiveType,
files: std.ArrayListUnmanaged(ArchivedFile),
symbols: std.ArrayListUnmanaged(Symbol),
// Use it so we can easily lookup files indices when inserting!
// TODO: A trie is probably a lot better here
file_name_to_index: std.StringArrayHashMapUnmanaged(u64),
file_offset_to_index: std.AutoArrayHashMapUnmanaged(u64, u64),
modifiers: Modifiers,
stat: fs.File.Stat,
pub const ArchiveType = enum {
ambiguous,
gnu,
gnuthin,
gnu64,
bsd,
darwin64, // darwin_32 *is* bsd
coff, // (windows)
};
pub const Operation = enum {
insert,
delete,
move,
print_contents,
quick_append,
ranlib,
print_names,
extract,
print_symbols,
};
// All archive files start with this magic string
pub const magic_string = "!<arch>\n";
pub const magic_thin = "!<thin>\n";
// GNU constants
pub const gnu_first_line_buffer_length = 60;
pub const gnu_string_table_seek_pos = magic_string.len + gnu_first_line_buffer_length;
// BSD constants
pub const bsd_name_length_signifier = "#1/";
pub const bsd_symdef_magic = "__.SYMDEF";
// The format (unparsed) of the archive per-file header
// NOTE: The reality is more complex than this as different mechanisms
// have been devised for storing the names of files which exceed 16 byte!
pub const Header = extern struct {
ar_name: [16]u8,
ar_date: [12]u8,
ar_uid: [6]u8,
ar_gid: [6]u8,
ar_mode: [8]u8,
ar_size: [10]u8,
ar_fmag: [2]u8,
};
pub const Modifiers = extern struct {
// Supress warning for file creation
create: bool = false,
// Only insert files with more recent timestamps than archive
update_only: bool = false,
use_real_timestamps_and_ids: bool = false,
verbose: bool = false,
};
pub const Contents = struct {
bytes: []u8,
length: u64,
mode: u64,
timestamp: u128, // file modified time
uid: u32,
gid: u32,
// TODO: dellocation
pub fn write(self: *const Contents, out_stream: anytype, stderr: anytype) !void {
try out_stream.writeAll(self.bytes);
_ = stderr;
}
};
// An internal represantion of files being archived
pub const ArchivedFile = struct {
name: []const u8,
contents: Contents,
};
pub const Symbol = struct {
name: []const u8,
file_offset: u32,
};
pub fn getDefaultArchiveTypeFromHost() ArchiveType {
// TODO: Set this based on the current platform you are using the tool
// on!
return .gnu;
}
pub fn create(
file: fs.File,
name: []const u8,
output_archive_type: ArchiveType,
modifiers: Modifiers,
) !Archive {
return Archive{
.file = file,
.name = name,
.inferred_archive_type = .ambiguous,
.output_archive_type = output_archive_type,
.files = .{},
.symbols = .{},
.file_name_to_index = .{},
.file_offset_to_index = .{},
.modifiers = modifiers,
.stat = try file.stat(),
};
}
// TODO: This needs to be integrated into the workflow
// used for parsing. (use same error handling workflow etc.)
/// Use same naming scheme for objects (as found elsewhere in the file).
pub fn finalize(self: *Archive, allocator: *Allocator) !void {
// Overwrite all contents
try self.file.seekTo(0);
if (self.output_archive_type == .ambiguous) {
// Set output archive type of one we might just have parsed...
self.output_archive_type = self.inferred_archive_type;
}
if (self.output_archive_type == .ambiguous) {
// if output archive type is still ambiguous (none was inferred, and
// none was set) then we need to infer it from the host platform!
self.output_archive_type = getDefaultArchiveTypeFromHost();
}
const writer = self.file.writer();
try writer.writeAll(if (self.output_archive_type == .gnuthin) magic_thin else magic_string);
const header_names = try allocator.alloc([16]u8, self.files.items.len);
switch (self.output_archive_type) {
.gnu, .gnuthin, .gnu64 => {
// GNU format: Create string table
var string_table = std.ArrayList(u8).init(allocator);
defer string_table.deinit();
// Generate the complete string table
for (self.files.items) |file, index| {
const is_the_name_allowed = (file.name.len < 16) and (self.output_archive_type != .gnuthin);
// If the file is small enough to fit in header, then just write it there
// Otherwise, add it to string table and add a reference to its location
const name = if (is_the_name_allowed) try mem.concat(allocator, u8, &.{ file.name, "/" }) else try std.fmt.allocPrint(allocator, "/{}", .{blk: {
// Get the position of the file in string table
const pos = string_table.items.len;
// Now add the file name to string table
try string_table.appendSlice(file.name);
try string_table.appendSlice("/\n");
break :blk pos;
}});
defer allocator.free(name);
// Edit the header
_ = try std.fmt.bufPrint(&(header_names[index]), "{s: <16}", .{name});
}
// Write the string table itself
{
if (string_table.items.len != 0) {
if (string_table.items.len % 2 != 0)
try string_table.append('\n');
try writer.print("//{s}{: <10}`\n{s}", .{ " " ** 46, string_table.items.len, string_table.items });
}
}
},
.bsd, .darwin64 => {
// BSD format: Just write the length of the name in header
for (self.files.items) |file, index| {
_ = try std.fmt.bufPrint(&(header_names[index]), "#1/{: <13}", .{file.name.len});
}
},
else => unreachable,
}
// Write the files
for (self.files.items) |file, index| {
// Write the header
// For now, we just write a garbage value to header.name and resolve it later
var headerBuffer: [@sizeOf(Header)]u8 = undefined;
_ = try std.fmt.bufPrint(
&headerBuffer,
"{s: <16}{: <12}{: <6}{: <6}{o: <8}{: <10}`\n",
.{ &header_names[index], file.contents.timestamp, file.contents.uid, file.contents.gid, file.contents.mode, file.contents.length },
);
// TODO: handle errors
_ = try writer.write(&headerBuffer);
// Write the name of the file in the data section
if (self.output_archive_type == .bsd) {
try writer.writeAll(file.name);
}
if (self.output_archive_type != .gnuthin)
try file.contents.write(writer, null);
}
// Truncate the file size
try self.file.setEndPos(try self.file.getPos());
}
pub fn deleteFiles(self: *Archive, file_names: [][]const u8) !void {
// For the list of given file names, find the entry in self.files
// and remove it from self.files.
for (file_names) |file_name| {
for (self.files.items) |file, index| {
if (std.mem.eql(u8, file.name, file_name)) {
_ = self.files.orderedRemove(index);
break;
}
}
}
}
pub fn extract(self: *Archive, file_names: [][]const u8) !void {
if (self.inferred_archive_type == .gnuthin) {
// TODO: better error
return error.ExtractingFromThin;
}
for (self.files.items) |archived_file| {
for (file_names) |file_name| {
if (std.mem.eql(u8, archived_file.name, file_name)) {
const file = try std.fs.cwd().createFile(archived_file.name, .{});
defer file.close();
try file.writeAll(archived_file.contents.bytes);
break;
}
}
}
}
pub fn insertFiles(self: *Archive, allocator: *Allocator, file_names: [][]const u8) !void {
for (file_names) |file_name| {
// Open the file and read all of its contents
const file = try std.fs.cwd().openFile(file_name, .{ .read = true });
defer file.close();
// We only need to do this because file stats don't include
// guid and uid - maybe the right solution is to integrate that into
// the std so we can call file.stat() on all platforms.
var gid: u32 = 0;
var uid: u32 = 0;
var mtime: i128 = 0;
var size: u64 = undefined;
var mode: u64 = undefined;
// FIXME: Currently windows doesnt support the Stat struct
if (builtin.os.tag == .windows) {
const file_stats = try file.stat();
// Convert timestamp from ns to s
mtime = file_stats.mtime;
size = file_stats.size;
mode = file_stats.mode;
} else {
const file_stats = try std.os.fstat(file.handle);
gid = file_stats.gid;
uid = file_stats.uid;
const mtime_full = file_stats.mtime();
mtime = mtime_full.tv_sec * std.time.ns_per_s + mtime_full.tv_nsec;
size = @intCast(u64, file_stats.size);
mode = file_stats.mode;
}
if (!self.modifiers.use_real_timestamps_and_ids) {
gid = 0;
uid = 0;
mtime = 0;
}
const timestamp = @intCast(u128, @divFloor(mtime, std.time.ns_per_s));
if (self.modifiers.update_only) {
// TODO: Write a test that checks for this functionality still working!
if (self.stat.mtime >= mtime) {
continue;
}
}
const archived_file = ArchivedFile{
.name = fs.path.basename(file_name),
.contents = Contents{
.bytes = try file.readToEndAlloc(allocator, std.math.maxInt(usize)),
.length = size,
.mode = if (builtin.os.tag != .windows) mode & ~@as(u64, std.os.S.IFREG) else 0,
.timestamp = timestamp,
.gid = gid,
.uid = uid,
},
};
// A trie-based datastructure would be better for this!
const getOrPutResult = try self.file_name_to_index.getOrPut(allocator, archived_file.name);
if (getOrPutResult.found_existing) {
const existing_index = getOrPutResult.value_ptr.*;
self.files.items[existing_index] = archived_file;
} else {
getOrPutResult.value_ptr.* = self.files.items.len;
try self.files.append(allocator, archived_file);
}
}
}
pub fn parse(self: *Archive, allocator: *Allocator, stderr: anytype) !void {
const reader = self.file.reader();
{
// Is the magic header found at the start of the archive?
var magic: [magic_string.len]u8 = undefined;
const bytes_read = try reader.read(&magic);
if (bytes_read == 0) {
// Archive is empty and that is ok!
return;
}
if (bytes_read < magic_string.len) {
try stderr.print("File too short to be an archive\n", .{});
return error.NotArchive;
}
const is_thin_archive = mem.eql(u8, &magic, magic_thin);
if (is_thin_archive)
self.inferred_archive_type = .gnuthin;
if (!(mem.eql(u8, &magic, magic_string) or is_thin_archive)) {
try stderr.print("Invalid magic string: expected '{s}' or '{s}', found '{s}'\n", .{ magic_string, magic_thin, magic });
return error.NotArchive;
}
}
var gnu_symbol_table_contents: []u8 = undefined;
var string_table_contents: []u8 = undefined;
var has_gnu_symbol_table = false;
{
// https://www.freebsd.org/cgi/man.cgi?query=ar&sektion=5
// Process string/symbol tables and/or try to infer archive type!
var starting_seek_pos = magic_string.len;
while (true) {
var first_line_buffer: [gnu_first_line_buffer_length]u8 = undefined;
const has_line_to_process = result: {
const chars_read = reader.read(&first_line_buffer) catch |err| switch (err) {
else => |e| return e,
};
if (chars_read < first_line_buffer.len) {
break :result false;
}
break :result true;
};
if (has_line_to_process) {
if (mem.eql(u8, first_line_buffer[0..2], "//"[0..2])) {
switch (self.inferred_archive_type) {
.ambiguous => self.inferred_archive_type = .gnu,
.gnu, .gnuthin, .gnu64 => {},
else => {
try stderr.print("Came across gnu-style string table in {} archive\n", .{self.inferred_archive_type});
return error.NotArchive;
},
}
const string_table_num_bytes_string = first_line_buffer[48..58];
const string_table_num_bytes = try fmt.parseInt(u32, mem.trim(u8, string_table_num_bytes_string, " "), 10);
string_table_contents = try allocator.alloc(u8, string_table_num_bytes);
// TODO: actually error handle not expected number of bytes being read!
_ = try reader.read(string_table_contents);
// starting_seek_pos = starting_seek_pos + first_line_buffer.len + table_size;
break;
} else if (!has_gnu_symbol_table and first_line_buffer[0] == '/') {
has_gnu_symbol_table = true;
switch (self.inferred_archive_type) {
.ambiguous => self.inferred_archive_type = .gnu,
.gnu, .gnuthin, .gnu64 => {},
else => {
try stderr.print("Came across gnu-style symbol table in {} archive\n", .{self.inferred_archive_type});
return error.NotArchive;
},
}
const symbol_table_num_bytes_string = first_line_buffer[48..58];
const symbol_table_num_bytes = try fmt.parseInt(u32, mem.trim(u8, symbol_table_num_bytes_string, " "), 10);
const num_symbols = try reader.readInt(u32, .Big);
var num_bytes_remaining = symbol_table_num_bytes - @sizeOf(u32);
const number_array = try allocator.alloc(u32, num_symbols);
for (number_array) |_, number_index| {
number_array[number_index] = try reader.readInt(u32, .Big);
}
defer allocator.free(number_array);
num_bytes_remaining = num_bytes_remaining - (@sizeOf(u32) * num_symbols);
gnu_symbol_table_contents = try allocator.alloc(u8, num_bytes_remaining);
// TODO: actually error handle not expected number of bytes being read!
_ = try reader.read(gnu_symbol_table_contents);
var current_symbol_string = gnu_symbol_table_contents;
var current_byte: u32 = 0;
while (current_byte < gnu_symbol_table_contents.len) {
var symbol_length: u32 = 0;
var skip_length: u32 = 0;
var found_zero = false;
for (current_symbol_string) |byte| {
if (found_zero and byte != 0) {
break;
}
current_byte = current_byte + 1;
if (byte == 0) {
found_zero = true;
}
skip_length = skip_length + 1;
if (!found_zero) {
symbol_length = symbol_length + 1;
}
}
const symbol = Symbol{
.name = current_symbol_string[0..symbol_length],
.file_offset = number_array[self.symbols.items.len],
};
try self.symbols.append(allocator, symbol);
current_symbol_string = current_symbol_string[skip_length..];
}
starting_seek_pos = starting_seek_pos + first_line_buffer.len + symbol_table_num_bytes;
} else {
try reader.context.seekTo(starting_seek_pos);
break;
}
}
}
}
var is_first = true;
while (true) {
const file_offset = try reader.context.getPos();
const archive_header = reader.readStruct(Header) catch |err| switch (err) {
error.EndOfStream => break,
else => |e| return e,
};
// the lifetime of the archive headers will matched that of the parsed files (for now)
// so we can take a reference to the strings stored there directly!
var trimmed_archive_name = mem.trim(u8, &archive_header.ar_name, " ");
// Check against gnu naming properties
const ends_with_gnu_slash = (trimmed_archive_name[trimmed_archive_name.len - 1] == '/');
var gnu_offset_value: u32 = 0;
const starts_with_gnu_offset = trimmed_archive_name[0] == '/';
if (starts_with_gnu_offset) {
gnu_offset_value = try fmt.parseInt(u32, trimmed_archive_name[1..trimmed_archive_name.len], 10);
}
const must_be_gnu = ends_with_gnu_slash or starts_with_gnu_offset or has_gnu_symbol_table;
// TODO: if modifiers.use_real_timestamps_and_ids is disabled, do we ignore this from existing archive?
// Check against llvm ar
const timestamp = try fmt.parseInt(u128, mem.trim(u8, &archive_header.ar_date, " "), 10);
const uid = try fmt.parseInt(u32, mem.trim(u8, &archive_header.ar_uid, " "), 10);
const gid = try fmt.parseInt(u32, mem.trim(u8, &archive_header.ar_gid, " "), 10);
// Check against bsd naming properties
const starts_with_bsd_name_length = (trimmed_archive_name.len >= 2) and mem.eql(u8, trimmed_archive_name[0..2], bsd_name_length_signifier[0..2]);
const could_be_bsd = starts_with_bsd_name_length;
// TODO: Have a proper mechanism for erroring on the wrong types of archive.
switch (self.inferred_archive_type) {
.ambiguous => {
if (must_be_gnu) {
self.inferred_archive_type = .gnu;
} else if (could_be_bsd) {
self.inferred_archive_type = .bsd;
} else {
return error.TODO;
}
},
.gnu, .gnuthin, .gnu64 => {
if (!must_be_gnu) {
try stderr.print("Error parsing archive header name - format of {s} wasn't gnu compatible\n", .{trimmed_archive_name});
return error.BadArchive;
}
},
.bsd, .darwin64 => {
if (must_be_gnu) {
try stderr.print("Error parsing archive header name - format of {s} wasn't bsd compatible\n", .{trimmed_archive_name});
return error.BadArchive;
}
},
else => {
if (must_be_gnu) {
return error.TODO;
}
return error.TODO;
},
}
if (ends_with_gnu_slash) {
// slice-off the slash
trimmed_archive_name = trimmed_archive_name[0 .. trimmed_archive_name.len - 1];
}
if (starts_with_gnu_offset) {
const name_offset_in_string_table = try fmt.parseInt(u32, mem.trim(u8, trimmed_archive_name[1..trimmed_archive_name.len], " "), 10);
// Navigate to the start of the string in the string table
const string_start = string_table_contents[name_offset_in_string_table..string_table_contents.len];
// Find the end of the string (which is always a newline)
const end_string_index = mem.indexOf(u8, string_start, "\n");
if (end_string_index == null) {
try stderr.print("Error parsing name in string table, couldn't find terminating character\n", .{});
return error.NotArchive;
}
const string_full = string_start[0..end_string_index.?];
// String must have a forward slash before the newline, so check that
// is there and remove it as well!
if (string_full[string_full.len - 1] != '/') {
try stderr.print("Error parsing name in string table, didn't find '/' before terminating newline\n", .{});
return error.NotArchive;
}
// Referencing the slice directly is fine as same bumb allocator is
// used as for the rest of the datastructure!
trimmed_archive_name = string_full[0 .. string_full.len - 1];
}
var seek_forward_amount = try fmt.parseInt(u32, mem.trim(u8, &archive_header.ar_size, " "), 10);
// Make sure that these allocations get properly disposed of later!
if (starts_with_bsd_name_length) {
trimmed_archive_name = trimmed_archive_name[bsd_name_length_signifier.len..trimmed_archive_name.len];
const archive_name_length = fmt.parseInt(u32, trimmed_archive_name, 10) catch {
try stderr.print("Error parsing bsd-style string length\n", .{});
return error.NotArchive;
};
if (is_first) {
// TODO: make sure this does a check on self.inferred_archive_type!
// This could be the symbol table! So parse that here!
const current_seek_pos = try reader.context.getPos();
var symbol_magic_check_buffer: [bsd_symdef_magic.len]u8 = undefined;
// TODO: handle not reading enough characters!
_ = try reader.read(&symbol_magic_check_buffer);
if (mem.eql(u8, bsd_symdef_magic, &symbol_magic_check_buffer)) {
// We have a symbol table!
// TODO: parse symbol table, we just skip it for now...
seek_forward_amount = seek_forward_amount - @as(u32, symbol_magic_check_buffer.len);
try reader.context.seekBy(seek_forward_amount);
continue;
}
try reader.context.seekTo(current_seek_pos);
}
is_first = false;
const archive_name_buffer = try allocator.alloc(u8, archive_name_length);
// TODO: proper error handling and length checking here!
_ = try reader.read(archive_name_buffer);
seek_forward_amount = seek_forward_amount - archive_name_length;
// strip null characters from name - TODO find documentation on this
// could not find documentation on this being needed, but some archivers
// seems to insert these (for alignment reasons?)
trimmed_archive_name = mem.trim(u8, archive_name_buffer, "\x00");
} else {
const archive_name_buffer = try allocator.alloc(u8, trimmed_archive_name.len);
mem.copy(u8, archive_name_buffer, trimmed_archive_name);
trimmed_archive_name = archive_name_buffer;
}
const parsed_file = ArchivedFile{
.name = trimmed_archive_name,
.contents = Contents{
.bytes = try allocator.alloc(u8, seek_forward_amount),
.length = seek_forward_amount,
.mode = try fmt.parseInt(u32, mem.trim(u8, &archive_header.ar_size, " "), 10),
.timestamp = timestamp,
.uid = uid,
.gid = gid,
},
};
if (self.inferred_archive_type == .gnuthin) {
var thin_file = try std.fs.cwd().openFile(trimmed_archive_name, .{});
defer thin_file.close();
try thin_file.reader().readNoEof(parsed_file.contents.bytes);
} else {
try reader.readNoEof(parsed_file.contents.bytes);
}
try self.file_name_to_index.put(allocator, trimmed_archive_name, self.files.items.len);
try self.file_offset_to_index.put(allocator, file_offset, self.files.items.len);
try self.files.append(allocator, parsed_file);
}
}
pub const MRIParser = struct {
script: []const u8,
archive: ?Archive,
file_name: ?[]const u8,
const CommandType = enum {
open,
create,
createthin,
addmod,
list,
delete,
extract,
save,
clear,
end,
};
const Self = @This();
pub fn init(allocator: *Allocator, file: fs.File) !Self {
const self = Self{
.script = try file.readToEndAlloc(allocator, std.math.maxInt(usize)),
.archive = null,
.file_name = null,
};
return self;
}
// Returns the next token
fn getToken(iter: *mem.SplitIterator(u8)) ?[]const u8 {
while (iter.next()) |tok| {
if (mem.startsWith(u8, tok, "*")) break;
if (mem.startsWith(u8, tok, ";")) break;
return tok;
}
return null;
}
// Returns a slice of tokens
fn getTokenLine(allocator: *Allocator, iter: *mem.SplitIterator(u8)) ![][]const u8 {
var list = std.ArrayList([]const u8).init(allocator);
while (getToken(iter)) |tok| {
try list.append(tok);
}
return list.toOwnedSlice();
}
pub fn execute(self: *Self, allocator: *Allocator, stdout: fs.File.Writer, stderr: fs.File.Writer) !void {
// Split the file into lines
var parser = mem.split(u8, self.script, "\n");
while (parser.next()) |line| {
// Split the line by spaces
var line_parser = mem.split(u8, line, " ");
if (getToken(&line_parser)) |tok| {
var command_name = try allocator.dupe(u8, tok);
defer allocator.free(command_name);
_ = std.ascii.lowerString(command_name, tok);
if (std.meta.stringToEnum(CommandType, command_name)) |command| {
if (self.archive) |archive| {
switch (command) {
.addmod => {
const file_names = try getTokenLine(allocator, &line_parser);
defer allocator.free(file_names);
try self.archive.?.insertFiles(allocator, file_names);
},
.list => {
// TODO: verbose output
for (archive.files.items) |parsed_file| {
try stdout.print("{s}\n", .{parsed_file.name});
}
},
.delete => {
const file_names = try getTokenLine(allocator, &line_parser);
try self.archive.?.deleteFiles(file_names);
},
.extract => {
const file_names = try getTokenLine(allocator, &line_parser);
try self.archive.?.extract(file_names);
},
.save => {
try self.archive.?.finalize(allocator);
},
.clear => {
// This is a bit of a hack but its reliable.
// Instead of clearing out unsaved changes, we re-open the current file, which overwrites the changes.
const file = try fs.cwd().openFile(self.file_name.?, .{ .write = true });
self.archive = Archive.create(file, self.file_name.?);
try self.archive.?.parse(allocator, stderr);
},
.end => return,
else => {
try stderr.print(
"Archive `{s}` is currently open.\nThe command `{s}` can only be executed when no current archive is active.\n",
.{ self.file_name.?, command_name },
);
return error.ArchiveAlreadyOpen;
},
}
} else {
switch (command) {
.open => {
const file_name = getToken(&line_parser).?;
const file = try fs.cwd().openFile(file_name, .{ .write = true });
self.archive = Archive.create(file, file_name);
self.file_name = file_name;
try self.archive.?.parse(allocator, stderr);
},
.create, .createthin => {
// TODO: Thin archives creation
const file_name = getToken(&line_parser).?;
const file = try fs.cwd().createFile(file_name, .{ .read = true });
self.archive = Archive.create(file, file_name);
self.file_name = file_name;
try self.archive.?.parse(allocator, stderr);
},
.end => return,
else => {
try stderr.print("No currently active archive found.\nThe command `{s}` can only be executed when there is an opened archive.\n", .{command_name});
return error.NoCurrentArchive;
},
}
}
}
}
}
}
};
|
src/archive/Archive.zig
|
// Function Return Payload (from ARMv8-M Architecture Reference Manual) LR value on entry from Secure BLXNS
pub const FNC_RETURN: usize = 0xFEFFFFFF; // bit [0] ignored when processing a branch
/// These EXC_RETURN mask values are used to evaluate the LR on exception entry.
pub const EXC_RETURN = struct {
pub const PREFIX: usize = 0xFF000000; // bits [31:24] set to indicate an EXC_RETURN value
pub const S: usize = 0x00000040; // bit [6] stack used to push registers: 0=Non-secure 1=Secure
pub const DCRS: usize = 0x00000020; // bit [5] stacking rules for called registers: 0=skipped 1=saved
pub const FTYPE: usize = 0x00000010; // bit [4] allocate stack for floating-point context: 0=done 1=skipped
pub const MODE: usize = 0x00000008; // bit [3] processor mode for return: 0=Handler mode 1=Thread mode
pub const SPSEL: usize = 0x00000004; // bit [2] stack pointer used to restore context: 0=MSP 1=PSP
pub const ES: usize = 0x00000001; // bit [0] security state exception was taken to: 0=Non-secure 1=Secure
};
/// Cortex-M SysTick timer.
///
/// The availability of SysTick(s) depends on the hardware configuration.
/// A PE implementing Armv8-M may include up to two instances of SysTick, each
/// for Secure and Non-Secure. Secure code can access the Non-Secure instance
/// via `sys_tick_ns` (`0xe002e010`).
pub const SysTick = struct {
base: usize,
const Self = @This();
/// Construct a `SysTick` object using the specified MMIO base address.
pub fn withBase(base: usize) Self {
return Self{ .base = base };
}
/// SysTick Control and Status Register
pub fn regCsr(self: Self) *volatile u32 {
return @intToPtr(*volatile u32, self.base);
}
pub const CSR_COUNTFLAG: u32 = 1 << 16;
pub const CSR_CLKSOURCE: u32 = 1 << 2;
pub const CSR_TICKINT: u32 = 1 << 1;
pub const CSR_ENABLE: u32 = 1 << 0;
/// SysTick Reload Value Register
pub fn regRvr(self: Self) *volatile u32 {
return @intToPtr(*volatile u32, self.base + 0x4);
}
/// SysTick Current Value Register
pub fn regCvr(self: Self) *volatile u32 {
return @intToPtr(*volatile u32, self.base + 0x8);
}
/// SysTick Calibration Value Register
pub fn regCalib(self: Self) *volatile u32 {
return @intToPtr(*volatile u32, self.base + 0xc);
}
};
/// Represents the SysTick instance corresponding to the current security mode.
pub const sys_tick = SysTick.withBase(0xe000e010);
/// Represents the Non-Secure SysTick instance. This register is only accessible
/// by Secure mode (Armv8-M or later).
pub const sys_tick_ns = SysTick.withBase(0xe002e010);
/// Nested Vectored Interrupt Controller.
pub const Nvic = struct {
base: usize,
const Self = @This();
/// Construct an `Nvic` object using the specified MMIO base address.
pub fn withBase(base: usize) Self {
return Self{ .base = base };
}
// Register Accessors
// -----------------------------------------------------------------------
/// Interrupt Set Enable Register.
pub fn regIser(self: Self) *volatile [16]u32 {
return @intToPtr(*volatile [16]u32, self.base);
}
/// Interrupt Clear Enable Register.
pub fn regIcer(self: Self) *volatile [16]u32 {
return @intToPtr(*volatile [16]u32, self.base + 0x80);
}
/// Interrupt Set Pending Register.
pub fn regIspr(self: Self) *volatile [16]u32 {
return @intToPtr(*volatile [16]u32, self.base + 0x100);
}
/// Interrupt Clear Pending Register.
pub fn regIcpr(self: Self) *volatile [16]u32 {
return @intToPtr(*volatile [16]u32, self.base + 0x180);
}
/// Interrupt Active Bit Register.
pub fn regIabr(self: Self) *volatile [16]u32 {
return @intToPtr(*volatile [16]u32, self.base + 0x200);
}
/// Interrupt Target Non-Secure Register (Armv8-M or later). RAZ/WI from
/// Non-Secure.
pub fn regItns(self: Self) *volatile [16]u32 {
return @intToPtr(*volatile [16]u32, self.base + 0x280);
}
/// Interrupt Priority Register.
pub fn regIpri(self: Self) *volatile [512]u8 {
return @intToPtr(*volatile [512]u8, self.base + 0x300);
}
// Helper functions
// -----------------------------------------------------------------------
// Note: Interrupt numbers are different from exception numbers.
// An exception number `Interrupt_IRQn(i)` corresponds to an interrupt
// number `i`.
/// Enable the interrupt number `irq`.
pub fn enableIrq(self: Self, irq: usize) void {
self.regIser()[irq >> 5] = @as(u32, 1) << @truncate(u5, irq);
}
/// Disable the interrupt number `irq`.
pub fn disableIrq(self: Self, irq: usize) void {
self.regIcer()[irq >> 5] = @as(u32, 1) << @truncate(u5, irq);
}
/// Set the priority of the interrupt number `irq` to `pri`.
pub fn setIrqPriority(self: Self, irq: usize, pri: u8) void {
self.regIpri()[irq] = pri;
}
/// Set the target state of the interrupt number `irq` to Non-Secure (Armv8-M or later).
pub fn targetIrqToNonSecure(self: Self, irq: usize) void {
self.regItns()[irq >> 5] |= @as(u32, 1) << @truncate(u5, irq);
}
};
/// Represents the Nested Vectored Interrupt Controller instance corresponding
/// to the current security mode.
pub const nvic = Nvic.withBase(0xe000e100);
/// Represents the Non-Secure Nested Vectored Interrupt Controller instance.
/// This register is only accessible by Secure mode (Armv8-M or later).
pub const nvic_ns = Nvic.withBase(0xe002e100);
/// System Control Block.
pub const Scb = struct {
base: usize,
const Self = @This();
/// Construct an `Nvic` object using the specified MMIO base address.
pub fn withBase(base: usize) Self {
return Self{ .base = base };
}
// Register Accessors
// -----------------------------------------------------------------------
/// System Handler Control and State Register
pub fn regShcsr(self: Self) *volatile u32 {
return @intToPtr(*volatile u32, self.base + 0x124);
}
pub const SHCSR_MEMFAULTACT: u32 = 1 << 0;
pub const SHCSR_BUSFAULTACT: u32 = 1 << 1;
pub const SHCSR_HARDFAULTACT: u32 = 1 << 2;
pub const SHCSR_USGFAULTACT: u32 = 1 << 3;
pub const SHCSR_SECUREFAULTACT: u32 = 1 << 4;
pub const SHCSR_NMIACT: u32 = 1 << 5;
pub const SHCSR_SVCCALLACT: u32 = 1 << 7;
pub const SHCSR_MONITORACT: u32 = 1 << 8;
pub const SHCSR_PENDSVACT: u32 = 1 << 10;
pub const SHCSR_SYSTICKACT: u32 = 1 << 11;
pub const SHCSR_USGFAULTPENDED: u32 = 1 << 12;
pub const SHCSR_MEMFAULTPENDED: u32 = 1 << 13;
pub const SHCSR_BUSFAULTPENDED: u32 = 1 << 14;
pub const SHCSR_SYSCALLPENDED: u32 = 1 << 15;
pub const SHCSR_MEMFAULTENA: u32 = 1 << 16;
pub const SHCSR_BUSFAULTENA: u32 = 1 << 17;
pub const SHCSR_USGFAULTENA: u32 = 1 << 18;
pub const SHCSR_SECUREFAULTENA: u32 = 1 << 19;
pub const SHCSR_SECUREFAULTPENDED: u32 = 1 << 20;
pub const SHCSR_HARDFAULTPENDED: u32 = 1 << 21;
/// Application Interrupt and Reset Control Register
pub fn regAircr(self: Self) *volatile u32 {
return @intToPtr(*volatile u32, self.base + 0x10c);
}
pub const AIRCR_VECTCLRACTIVE: u32 = 1 << 1;
pub const AIRCR_SYSRESETREQ: u32 = 1 << 2;
pub const AIRCR_SYSRESETREQS: u32 = 1 << 3;
pub const AIRCR_DIT: u32 = 1 << 4;
pub const AIRCR_IESB: u32 = 1 << 5;
pub const AIRCR_PRIGROUP_SHIFT: u5 = 8;
pub const AIRCR_PRIGROUP_MASK: u32 = 0b111 << AIRCR_PRIGROUP_SHIFT;
pub const AIRCR_BFHFNMINS: u32 = 1 << 13;
pub const AIRCR_PRIS: u32 = 1 << 14;
pub const AIRCR_ENDIANNESS: u32 = 1 << 15;
pub const AIRCR_VECTKEY_SHIFT: u5 = 16;
pub const AIRCR_VECTKEY_MASK: u32 = 0xffff << AIRCR_VECTKEY_SHIFT;
pub const AIRCR_VECTKEY_MAGIC: u32 = 0x05fa;
pub fn setPriorityGrouping(self: Self, subpriority_msb: u3) void {
self.regAircr().* = self.regAircr().* & ~(AIRCR_PRIGROUP_MASK | AIRCR_VECTKEY_MASK) | (@as(u32, subpriority_msb) << AIRCR_PRIGROUP_SHIFT) | (AIRCR_VECTKEY_MAGIC << AIRCR_VECTKEY_SHIFT);
}
/// Vector Table Offset Register
pub fn regVtor(self: Self) *volatile u32 {
return @intToPtr(*volatile u32, self.base + 0x108);
}
/// System Handler Priority Register 1
pub fn regShpr1(self: Self) *volatile u32 {
return @intToPtr(*volatile u32, self.base + 0x118);
}
/// System Handler Priority Register 2
pub fn regShpr2(self: Self) *volatile u32 {
return @intToPtr(*volatile u32, self.base + 0x11c);
}
/// System Handler Priority Register 3
pub fn regShpr3(self: Self) *volatile u32 {
return @intToPtr(*volatile u32, self.base + 0x120);
}
};
/// Represents the System Control Block instance corresponding to the current
/// security mode.
pub const scb = Scb.withBase(0xe000ec00);
/// Represents the System Control Block instance for Non-Secure mode.
/// This register is only accessible by Secure mode (Armv8-M or later).
pub const scb_ns = Scb.withBase(0xe002ec00);
/// Exception numbers defined by Arm-M.
pub const irqs = struct {
pub const Reset_IRQn: usize = 1;
pub const Nmi_IRQn: usize = 2;
pub const SecureHardFault_IRQn: usize = 3;
pub const MemManageFault_IRQn: usize = 4;
pub const BusFault_IRQn: usize = 5;
pub const UsageFault_IRQn: usize = 6;
pub const SecureFault_IRQn: usize = 7;
pub const SvCall_IRQn: usize = 11;
pub const DebugMonitor_IRQn: usize = 12;
pub const PendSv_IRQn: usize = 14;
pub const SysTick_IRQn: usize = 15;
pub const InterruptBase_IRQn: usize = 16;
pub fn interruptIRQn(i: usize) usize {
return @This().InterruptBase_IRQn + i;
}
/// Get the descriptive name of an exception number. Returns `null` for a value
/// outside the range `[Reset_IRQn, SysTick_IRQn]`.
pub fn getName(i: usize) ?[]const u8 {
switch (i) {
Reset_IRQn => return "Reset",
Nmi_IRQn => return "Nmi",
SecureHardFault_IRQn => return "SecureHardFault",
MemManageFault_IRQn => return "MemManageFault",
BusFault_IRQn => return "BusFault",
UsageFault_IRQn => return "UsageFault",
SecureFault_IRQn => return "SecureFault",
SvCall_IRQn => return "SvCall",
DebugMonitor_IRQn => return "DebugMonitor",
PendSv_IRQn => return "PendSv",
SysTick_IRQn => return "SysTick",
else => return null,
}
}
};
pub inline fn getIpsr() usize {
return asm ("mrs %[out], ipsr"
: [out] "=r" (-> usize)
);
}
pub inline fn isHandlerMode() bool {
return getIpsr() != 0;
}
/// Read the current main stack pointer.
pub inline fn getMsp() usize {
return asm ("mrs %[out], msp"
: [out] "=r" (-> usize)
);
}
/// Read the current process stack pointer.
pub inline fn getPsp() usize {
return asm ("mrs %[out], psp"
: [out] "=r" (-> usize)
);
}
/// Read the current main stack pointer limit.
pub inline fn getMspLimit() usize {
return asm ("mrs %[out], msplim"
: [out] "=r" (-> usize)
);
}
/// Read the current process stack pointer limit.
pub inline fn getPspLimit() usize {
return asm ("mrs %[out], psplim"
: [out] "=r" (-> usize)
);
}
/// Write the current main stack pointer.
pub inline fn setMsp(value: usize) void {
return asm volatile ("msr msp, %[value]"
:
: [value] "r" (value)
);
}
/// Write the current process stack pointer.
pub inline fn setPsp(value: usize) void {
return asm volatile ("msr psp, %[value]"
:
: [value] "r" (value)
);
}
/// Write the current main stack pointer limit.
pub inline fn setMspLimit(value: usize) void {
return asm volatile ("msr msplim, %[value]"
:
: [value] "r" (value)
);
}
/// Write the current process stack pointer limit.
pub inline fn setPspLimit(value: usize) void {
return asm volatile ("msr psplim, %[value]"
:
: [value] "r" (value)
);
}
/// Read the current non-Secure main stack pointer.
pub inline fn getMspNs() usize {
return asm ("mrs %[out], msp_ns"
: [out] "=r" (-> usize)
);
}
/// Read the current non-Secure process stack pointer.
pub inline fn getPspNs() usize {
return asm ("mrs %[out], psp_ns"
: [out] "=r" (-> usize)
);
}
/// Read the current non-Secure main stack pointer limit.
pub inline fn getMspLimitNs() usize {
return asm ("mrs %[out], msplim_ns"
: [out] "=r" (-> usize)
);
}
/// Read the current non-Secure process stack pointer limit.
pub inline fn getPspLimitNs() usize {
return asm ("mrs %[out], psplim_ns"
: [out] "=r" (-> usize)
);
}
/// Write the current non-Secure main stack pointer.
pub inline fn setMspNs(value: usize) void {
return asm volatile ("msr msp_ns, %[value]"
:
: [value] "r" (value)
);
}
/// Write the current non-Secure process stack pointer.
pub inline fn setPspNs(value: usize) void {
return asm volatile ("msr psp_ns, %[value]"
:
: [value] "r" (value)
);
}
/// Write the current non-Secure main stack pointer limit.
pub inline fn setMspLimitNs(value: usize) void {
return asm volatile ("msr msplim_ns, %[value]"
:
: [value] "r" (value)
);
}
/// Write the current non-Secure process stack pointer limit.
pub inline fn setPspLimitNs(value: usize) void {
return asm volatile ("msr psplim_ns, %[value]"
:
: [value] "r" (value)
);
}
/// Read the control register.
pub inline fn getControl() usize {
return asm ("mrs %[out], control"
: [out] "=r" (-> usize)
);
}
/// Write the control register.
pub inline fn setControl(value: usize) void {
return asm volatile ("msr control, %[value]"
:
: [value] "r" (value)
);
}
/// Read the non-Secure control register.
pub inline fn getControlNs() usize {
return asm ("mrs %[out], control_ns"
: [out] "=r" (-> usize)
);
}
/// Write the non-Secure control register.
pub inline fn setControlNs(value: usize) void {
return asm volatile ("msr control_ns, %[value]"
:
: [value] "r" (value)
);
}
pub const control = struct {
/// Secure Floating-point active.
pub const SPFA: usize = 1 << 3;
/// Floating-point context active.
pub const FPCA: usize = 1 << 2;
/// Stack-pointer select.
pub const SPSEL: usize = 1 << 1;
/// Not privileged.
pub const nPRIV: usize = 1 << 0;
pub const set = setControl;
pub const get = getControl;
};
/// Set `FAULTMASK`, disabling all interrupts.
pub inline fn setFaultmask() void {
asm volatile ("cpsid f");
}
/// Clear `FAULTMASK`, re-enabling all interrupts.
pub inline fn clearFaultmask() void {
asm volatile ("cpsie f");
}
/// Memory Protection Unit.
pub const Mpu = struct {
base: usize,
const Self = @This();
/// Construct an `Mpu` object using the specified MMIO base address.
pub fn withBase(base: usize) Self {
return Self{ .base = base };
}
// Register Accessors
// -----------------------------------------------------------------------
/// MPU Type Register
pub fn regType(self: Self) *volatile u32 {
return @intToPtr(*volatile u32, self.base + 0x00);
}
/// MPU Control Register
pub fn regCtrl(self: Self) *volatile u32 {
return @intToPtr(*volatile u32, self.base + 0x04);
}
/// Privileged default enable.
pub const CTRL_PRIVDEFENA: u32 = 1 << 2;
/// HardFault, NMI enable.
pub const CTRL_HFNMIENA: u32 = 1 << 1;
/// Enable.
pub const CTRL_ENABLE: u32 = 1 << 0;
/// MPU Region Number Register
pub fn regRnr(self: Self) *volatile u32 {
return @intToPtr(*volatile u32, self.base + 0x08);
}
/// MPU Region Base Address Register
pub fn regRbar(self: Self) *volatile u32 {
return @intToPtr(*volatile u32, self.base + 0x0c);
}
/// MPU Region Limit Address Register
pub fn regRlar(self: Self) *volatile u32 {
return @intToPtr(*volatile u32, self.base + 0x10);
}
/// MPU Region Base Address Register Alias `n` (where 1 ≤ `n` ≤ 3)
pub fn regRbarA(self: Self, n: usize) *volatile u32 {
return @intToPtr(*volatile u32, self.base + 0x14 + (n - 1) * 8);
}
/// MPU Region Limit Address Register Alias `n` (where 1 ≤ `n` ≤ 3)
pub fn regRlarA(self: Self, n: usize) *volatile u32 {
return @intToPtr(*volatile u32, self.base + 0x18 + (n - 1) * 8);
}
/// MPU Memory Attribute Indirection Register `n` (where 0 ≤ `n` ≤ 1)
pub fn regMair(self: Self, n: usize) *volatile u32 {
return @intToPtr(*volatile u32, self.base + 0x30 + n * 4);
}
pub const RBAR_BASE_MASK: u32 = 0xffffffe0;
pub const RBAR_SH_NON_SHAREABLE: u32 = 0b00 << 3;
pub const RBAR_SH_OUTER_SHAREABLE: u32 = 0b10 << 3;
pub const RBAR_SH_INNER_SHAREABLE: u32 = 0b11 << 3;
pub const RBAR_AP_RW_PRIV: u32 = 0b00 << 1;
pub const RBAR_AP_RW_ANY: u32 = 0b01 << 1;
pub const RBAR_AP_RO_PRIV: u32 = 0b10 << 1;
pub const RBAR_AP_RO_ANY: u32 = 0b11 << 1;
pub const RBAR_XN: u32 = 1;
pub const RLAR_LIMIT_MASK: u32 = 0xffffffe0;
pub const RLAR_PXN: u32 = 1 << 4;
pub const RLAR_ATTR_MASK: u32 = 0b111 << 1;
pub const RLAR_EN: u32 = 1;
};
/// Represents theMemory Protection Unit instance corresponding to the current
/// security mode.
pub const mpu = Mpu.withBase(0xe000ed90);
/// Data Watchpoint and Trace unit.
pub const Dwt = struct {
base: usize,
const Self = @This();
/// Construct an `Dwt` object using the specified MMIO base address.
pub fn withBase(base: usize) Self {
return Self{ .base = base };
}
/// Control Register
pub fn regCtrl(self: Self) *volatile u32 {
return @intToPtr(*volatile u32, self.base + 0x000);
}
pub const CTRL_NUMCOMP_SHIFT: u5 = 28;
/// Number of comparators. Number of DWT comparators implemented.
pub const CTRL_NUMCOMP_MASK: u32 = 0xf << CTRL_NUMCOMP_SHIFT;
/// No trace packets. Indicates whether the implementation does not support
/// trace.
pub const CTRL_NOTRCPKT: u32 = 1 << 27;
/// No External Triggers. Shows whether the implementation does not support
/// external triggers.
pub const CTRL_NOEXTTRIG: u32 = 1 << 26;
/// No cycle count. Indicates whether the implementation does not include
/// a cycle counter.
pub const CTRL_NOCYCCNT: u32 = 1 << 25;
/// No profile counters. Indicates whether the implementation does not
/// include the profiling counters.
pub const CTRL_NOPRFCNT: u32 = 1 << 24;
/// Cycle counter disabled secure. Controls whether the cycle counter is
/// disabled in Secure state.
pub const CTRL_CYCDISS: u32 = 1 << 23;
/// Cycle event enable. Enables Event Counter packet generation on POSTCNT
/// underflow.
pub const CTRL_CYCEVTENA: u32 = 1 << 22;
/// Fold event enable. Enables DWT_FOLDCNT counter.
pub const CTRL_FOLDEVTENA: u32 = 1 << 21;
/// LSU event enable. Enables DWT_LSUCNT counter.
pub const CTRL_LSUEVTENA: u32 = 1 << 20;
/// Sleep event enable. Enable DWT_SLEEPCNT counter.
pub const CTRL_SLEEPEVTENA: u32 = 1 << 19;
/// Exception event enable. Enables DWT_EXCCNT counter.
pub const CTRL_EXCEVTENA: u32 = 1 << 18;
/// CPI event enable. Enables DWT_CPICNT counter.
pub const CTRL_CPIEVTENA: u32 = 1 << 17;
/// Exception trace enable. Enables generation of Exception Trace packets.
pub const CTRL_EXCEVTENA: u32 = 1 << 16;
/// PC sample enable. Enables use of POSTCNT counter as a timer for Periodic
/// PC Sample packet generation.
pub const CTRL_PCSAMPLENA: u32 = 1 << 12;
pub const CTRL_SYNCTAP_SHIFT: u5 = 10;
/// Synchronization tap. Selects the position of the synchronization packet
/// request counter tap on the CYCCNT counter. This determines the rate of
/// Synchronization packet requests made by the DWT.
pub const CTRL_SYNCTAP_MASK: u5 = 0x3 << CTRL_SYNCTAP_SHIFT;
/// Cycle count tap. Selects the position of the POSTCNT tap on the CYCCNT counter.
pub const CTRL_CYCTAP: u32 = 1 << 9;
pub const CTRL_POSTINIT_SHIFT: u5 = 5;
/// POSTCNT initial. Initial value for the POSTCNT counter.
pub const CTRL_POSTINIT_MASK: u5 = 0xf << CTRL_POSTINIT_SHIFT;
pub const CTRL_POSTPRESET_SHIFT: u5 = 1;
/// POSTCNT preset. Reload value for the POSTCNT counter.
pub const CTRL_POSTPRESET_MASK: u5 = 0xf << CTRL_POSTPRESET_SHIFT;
/// CYCCNT enable. Enables CYCCNT.
pub const CTRL_CYCCNTENA: u32 = 1 << 0;
// TODO: DWT_(CYC|CPI|EXC|SLEEP|LSU|FOLD)CNT, DWT_PCSR
/// Comparator Register n
pub fn regComp(self: Self, n: usize) *volatile u32 {
return @intToPtr(*volatile u32, self.base + 0x020 + n * 0x10);
}
/// Comparator Function Register n
pub fn regFunction(self: Self, n: usize) *volatile u32 {
return @intToPtr(*volatile u32, self.base + 0x028 + n * 0x10);
}
/// Comparator Value Mask Register n
pub fn regVmask(self: Self, n: usize) *volatile u32 {
return @intToPtr(*volatile u32, self.base + 0x02c + n * 0x10);
}
};
/// Represents the Data Watchpoint and Trace unit.
pub const dwt = Dwt.withBase(0xe0001000);
/// Debug Control Block.
pub const Dcb = struct {
base: usize,
const Self = @This();
/// Construct an `Dcb` object using the specified MMIO base address.
pub fn withBase(base: usize) Self {
return Self{ .base = base };
}
/// Halting Control and Status Register
pub fn regDhcsr(self: Self) *volatile u32 {
return @intToPtr(*volatile u32, self.base + 0x000);
}
/// Core Register Select Register
pub fn regDhrsr(self: Self) *volatile u32 {
return @intToPtr(*volatile u32, self.base + 0x004);
}
/// Core Register Data Register
pub fn regDcrdr(self: Self) *volatile u32 {
return @intToPtr(*volatile u32, self.base + 0x008);
}
/// Exception and Monitor Control Register
pub fn regDemcr(self: Self) *volatile u32 {
return @intToPtr(*volatile u32, self.base + 0x00c);
}
pub const DEMCR_TRCENA: u32 = 1 << 24;
/// Set Clear Exception and Monitor Control Register
pub fn regDscemcr(self: Self) *volatile u32 {
return @intToPtr(*volatile u32, self.base + 0x010);
}
/// Authentication Control Register
pub fn regDauthCtrl(self: Self) *volatile u32 {
return @intToPtr(*volatile u32, self.base + 0x014);
}
/// Security Control and Status Register
pub fn regDscsr(self: Self) *volatile u32 {
return @intToPtr(*volatile u32, self.base + 0x018);
}
};
/// Represents the Debug Control Block.
pub const dcb = Dcb.withBase(0xe000edf0);
/// Represents the Non-Secure Debug Control Block instance. This register
/// is only accessible by Secure mode (Armv8-M or later).
pub const dcb_ns = Dcb.withBase(0xe002edf0);
/// Debug Identification Block
pub const Dib = struct {
base: usize,
const Self = @This();
/// Construct an `Dib` object using the specified MMIO base address.
pub fn withBase(base: usize) Self {
return Self{ .base = base };
}
/// Software Lock Access Register
pub fn regDlar(self: Self) *volatile u32 {
return @intToPtr(*volatile u32, self.base + 0x000);
}
pub const DLAR_KEY_MAGIC: u32 = 0xC5ACCE55;
};
/// Represents the Debug Identification Block.
pub const dic = Dib.withBase(0xe000efb0);
/// Represents the Non-Secure Debug Identification Block instance. This register
/// is only accessible by Secure mode (Armv8-M or later).
pub const dic_ns = Dib.withBase(0xe002efb0);
|
src/drivers/arm_m.zig
|
const builtin = @import("builtin");
const std = @import("std");
const testing = std.testing;
const fmt = std.fmt;
const FixBuf = @import("../types/fixbuf.zig").FixBuf;
const perfectHash = @import("../lib/perfect_hash.zig").perfectHash;
// // TODO: decide what tho do with this weird trait.
// inline fn isFragmentType(comptime T: type) bool {
// const tid = @typeInfo(T);
// return (tid == .Struct or tid == .Enum or tid == .Union) and
// @hasDecl(T, "Redis") and @hasDecl(T.Redis, "Parser") and @hasDecl(T.Redis.Parser, "TokensPerFragment");
// }
pub const MapParser = struct {
// Understanding if we want to support a given type is more complex
// than with other parsers as this is the only parser where we have
// to care about the container layout (at the "toplevel") and also
// the layout of each field-value pair.
pub fn isSupported(comptime T: type) bool {
return switch (@typeInfo(T)) {
.Array => |arr| switch (@typeInfo(arr.child)) {
.Array => |child| child.len == 2,
// .Struct, .Union => isFVType(), TODO
else => false,
},
.Struct => true,
else => false,
};
}
pub fn isSupportedAlloc(comptime T: type) bool {
return switch (@typeInfo(T)) {
.Pointer => |ptr| switch (@typeInfo(ptr.child)) {
.Pointer => false, // TODO: decide if we want to support it or not.
.Array => |child| child.len == 2,
else => false,
},
else => isSupported(T),
};
}
pub fn parse(comptime T: type, comptime rootParser: type, msg: anytype) !T {
return parseImpl(T, rootParser, .{}, msg);
}
pub fn parseAlloc(comptime T: type, comptime rootParser: type, allocator: *std.mem.Allocator, msg: anytype) !T {
return parseImpl(T, rootParser, .{ .ptr = allocator }, msg);
}
pub fn parseImpl(comptime T: type, comptime rootParser: type, allocator: anytype, msg: anytype) !T {
// TODO: write real implementation
var buf: [100]u8 = undefined;
var end: usize = 0;
for (buf) |*elem, i| {
const ch = try msg.readByte();
elem.* = ch;
if (ch == '\r') {
end = i;
break;
}
}
try msg.skipBytes(1, .{});
const size = try fmt.parseInt(usize, buf[0..end], 10);
// TODO: remove some redundant code
// HASHMAP
if (@hasField(@TypeOf(allocator), "ptr")) {
if (@typeInfo(T) == .Struct and @hasDecl(T, "Entry")) {
const isManaged = @typeInfo(@TypeOf(T.deinit)).Fn.args.len == 1;
var hmap = T.init(allocator.ptr);
errdefer {
if (isManaged) {
hmap.deinit();
} else {
hmap.deinit(allocator.ptr);
}
}
var foundNil = false;
var foundErr = false;
var hashMapError = false;
var i: usize = 0;
while (i < size) : (i += 1) {
if (foundErr or foundNil) {
// field
rootParser.parse(void, msg) catch |err| switch (err) {
error.GotErrorReply => {
foundErr = true;
},
else => return err,
};
// value
rootParser.parse(void, msg) catch |err| switch (err) {
error.GotErrorReply => {
foundErr = true;
},
else => return err,
};
} else {
// Differently from the Lists case, here we can't `continue` immediately on fail
// because then we would lose count of how many tokens we consumed.
var key = rootParser.parseAlloc(std.meta.fieldInfo(T.Entry, "key").field_type, allocator.ptr, msg) catch |err| switch (err) {
error.GotNilReply => blk: {
foundNil = true;
break :blk undefined;
},
error.GotErrorReply => blk: {
foundErr = true;
break :blk undefined;
},
else => return err,
};
var val = rootParser.parseAlloc(std.meta.fieldInfo(T.Entry, "value").field_type, allocator.ptr, msg) catch |err| switch (err) {
error.GotNilReply => blk: {
foundNil = true;
break :blk undefined;
},
error.GotErrorReply => blk: {
foundErr = true;
break :blk undefined;
},
else => return err,
};
if (!foundErr and !foundNil) {
(if (isManaged) hmap.put(key, val) else hmap.put(allocator.ptr, key, val)) catch |err| {
hashMapError = true;
continue;
};
}
}
}
// Error takes precedence over Nil
if (foundErr) return error.GotErrorReply;
if (foundNil) return error.GotNilReply;
if (hashMapError) return error.DecodeError; // TODO: find a way to save and return the precise error?
return hmap;
}
}
switch (@typeInfo(T)) {
else => unreachable,
.Struct => |stc| {
var foundNil = false;
var foundErr = false;
if (stc.fields.len != size) {
// The user requested a struct but the list reply from Redis
// contains a different number of field-value pairs.
var i: usize = 0;
while (i < size) : (i += 1) {
// Discard all the items
rootParser.parse(void, msg) catch |err| switch (err) {
error.GotErrorReply => {
foundErr = true;
},
else => return err,
};
}
// GotErrorReply takes precedence over LengthMismatch
if (foundErr) return error.GotErrorReply;
return error.LengthMismatch;
}
// At comptime we create an array of strings corresponding
// to this struct's field names.
// This will be later used to match the hashmap's structure
// with the struct itself.
// TODO: implement a radix tree or something that makes this
// not stupidly inefficient.
comptime var max_len = 0;
comptime var fieldNames: [stc.fields.len][]const u8 = undefined;
comptime {
for (stc.fields) |f, i| {
if (f.name.len > max_len) max_len = f.name.len;
fieldNames[i] = f.name;
}
}
const Buf = FixBuf(max_len);
var result: T = undefined;
// Iterating over `stc.fields.len` vs `size` is the same,
// as the two numbers must coincide to be able to reach this
// part of the code, but the number of struct fields has the
// advantage of being a comptime-known number, allowing the
// compiler to unroll the while loop, if advantageous to do so.
var i: usize = 0;
// upper: (renable label when fixed in Zig)
while (i < stc.fields.len) : (i += 1) {
if (foundNil or foundErr) {
// field
rootParser.parse(void, msg) catch |err| switch (err) {
error.GotErrorReply => {
foundErr = true;
},
else => return err,
};
// value
rootParser.parse(void, msg) catch |err| switch (err) {
error.GotErrorReply => {
foundErr = true;
},
else => return err,
};
} else {
const hash_field = rootParser.parse(Buf, msg) catch |err| switch (err) {
error.GotNilReply => blk: {
foundNil = true;
break :blk undefined;
},
error.GotErrorReply => blk: {
foundErr = true;
break :blk undefined;
},
else => return err,
};
inline for (stc.fields) |f| {
if (std.mem.eql(u8, f.name, hash_field.toSlice())) {
@field(result, f.name) = (if (@hasField(@TypeOf(allocator), "ptr"))
rootParser.parseAlloc(f.field_type, allocator.ptr, msg)
else
rootParser.parse(f.field_type, msg)) catch |err| switch (err) {
error.GotNilReply => blk: {
foundNil = true;
break :blk undefined;
},
error.GotErrorReply => blk: {
foundErr = true;
break :blk undefined;
},
else => return err,
};
// TODO: re-enable when fixed in zig
// continue :upper; // only for performance reasons, it's a poor man's "else"
}
}
}
}
if (foundErr) return error.GotErrorReply;
if (foundNil) return error.GotNilReply;
return result;
},
.Array => |arr| {
if (arr.len != size) {
// The user requested an array but the map reply from Redis
// contains a different amount of items.
var foundErr = false;
var i: usize = 0;
while (i < size) : (i += 1) {
// Discard all the items
rootParser.parse(void, msg) catch |err| switch (err) {
error.GotErrorReply => {
foundErr = true;
},
else => return err,
};
}
// GotErrorReply takes precedence over LengthMismatch
if (foundErr) return error.GotErrorReply;
}
// Given what we declared in isSupported,
// we know the array has a child type of [2]X.
var foundNil = false;
var foundErr = false;
var result: T = undefined;
for (result) |*couple| {
if (@hasField(@TypeOf(allocator), "ptr")) {
couple[0] = rootParser.parseAlloc(@TypeOf(couple[0]), allocator.ptr, msg) catch |err| switch (err) {
error.GotNilReply => blk: {
foundNil = true;
break :blk undefined;
},
error.GotErrorReply => blk: {
foundErr = true;
break :blk undefined;
},
else => return err,
};
couple[1] = rootParser.parseAlloc(@TypeOf(couple[0]), allocator.ptr, msg) catch |err| switch (err) {
error.GotNilReply => blk: {
foundNil = true;
break :blk undefined;
},
error.GotErrorReply => blk: {
foundErr = true;
break :blk undefined;
},
else => return err,
};
} else {
couple[0] = try rootParser.parse(@TypeOf(couple[0]), ptr, msg) catch |err| switch (err) {
error.GotNilReply => blk: {
foundNil = true;
break :blk undefined;
},
error.GotErrorReply => blk: {
foundErr = true;
break :blk undefined;
},
else => return err,
};
couple[1] = try rootParser.parse(@TypeOf(couple[0]), ptr, msg) catch |err| switch (err) {
error.GotNilReply => blk: {
foundNil = true;
break :blk undefined;
},
error.GotErrorReply => blk: {
foundErr = true;
break :blk undefined;
},
else => return err,
};
}
}
// Error takes precedence over Nil
if (foundErr) return error.GotErrorReply;
if (foundNil) return error.GotNilReply;
return result;
},
.Pointer => |ptr| {
if (!@hasField(@TypeOf(allocator), "ptr")) {
@compileError("To decode a slice you need to use sendAlloc / pipeAlloc / transAlloc!");
}
// Given what we declared in isSupportedAlloc,
// we know the array has a child type of [2]X.
var foundNil = false;
var foundErr = false;
var result = try allocator.ptr.alloc(ptr.child, size); // TODO: recover from OOM?
errdefer allocator.ptr.free(result);
for (result) |*couple| {
couple[0] = rootParser.parseAlloc(@TypeOf(couple[0]), allocator.ptr, msg) catch |err| switch (err) {
error.GotNilReply => blk: {
foundNil = true;
break :blk undefined;
},
error.GotErrorReply => blk: {
foundErr = true;
break :blk undefined;
},
else => return err,
};
couple[1] = rootParser.parseAlloc(@TypeOf(couple[0]), allocator.ptr, msg) catch |err| switch (err) {
error.GotNilReply => blk: {
foundNil = true;
break :blk undefined;
},
error.GotErrorReply => blk: {
foundErr = true;
break :blk undefined;
},
else => return err,
};
}
// Error takes precedence over Nil
if (foundErr) return error.GotErrorReply;
if (foundNil) return error.GotNilReply;
return result;
},
}
}
fn decodeMap(comptime T: type, result: [][2]T, rootParser: anytype, allocator: anytype, msg: anytype) !void {
var foundNil = false;
var foundErr = false;
for (result) |*pair| {
if (foundNil or foundErr) {
// field
rootParser.parse(void, msg) catch |err| switch (err) {
error.GotErrorReply => {
foundErr = true;
},
else => return err,
};
// value
rootParser.parse(void, msg) catch |err| switch (err) {
error.GotErrorReply => {
foundErr = true;
},
else => return err,
};
} else {
pair.*[0] = (if (@hasField(@TypeOf(allocator), "ptr"))
rootParser.parseAlloc(T, allocator.ptr, msg)
else
rootParser.parse(T, msg)) catch |err| switch (err) {
error.GotNilReply => blk: {
foundNil = true;
break :blk undefined;
},
error.GotErrorReply => blk: {
foundErr = true;
break :blk undefined;
},
else => return err,
};
pair.*[1] = (if (@hasField(@TypeOf(allocator), "ptr"))
rootParser.parseAlloc(T, allocator.ptr, msg)
else
rootParser.parse(T, msg)) catch |err| switch (err) {
error.GotNilReply => blk: {
foundNil = true;
break :blk undefined;
},
error.GotErrorReply => blk: {
foundErr = true;
break :blk undefined;
},
else => return err,
};
}
}
// Error takes precedence over Nil
if (foundErr) return error.GotErrorReply;
if (foundNil) return error.GotNilReply;
return;
}
};
|
src/parser/t_map.zig
|
const std = @import("std");
const warn = std.debug.warn;
const utils = @import("utils.zig");
const ReverseSliceIterator = @import("utils.zig").ReverseSliceIterator;
// TODO: fix entity_mask. it should come from EntityTraitsDefinition.
pub fn SparseSet(comptime SparseT: type) type {
return struct {
const Self = @This();
const page_size: usize = 32768;
const entity_per_page = page_size / @sizeOf(SparseT);
sparse: std.ArrayList(?[]SparseT),
dense: std.ArrayList(SparseT),
entity_mask: SparseT,
allocator: ?*std.mem.Allocator,
pub fn initPtr(allocator: *std.mem.Allocator) *Self {
var set = allocator.create(Self) catch unreachable;
set.sparse = std.ArrayList(?[]SparseT).init(allocator);
set.dense = std.ArrayList(SparseT).init(allocator);
set.entity_mask = std.math.maxInt(SparseT);
set.allocator = allocator;
return set;
}
pub fn init(allocator: *std.mem.Allocator) Self {
return Self{
.sparse = std.ArrayList(?[]SparseT).init(allocator),
.dense = std.ArrayList(SparseT).init(allocator),
.entity_mask = std.math.maxInt(SparseT),
.allocator = null,
};
}
pub fn deinit(self: *Self) void {
self.sparse.expandToCapacity();
for (self.sparse.items) |array, i| {
if (array) |arr| {
self.sparse.allocator.free(arr);
}
}
self.dense.deinit();
self.sparse.deinit();
if (self.allocator) |allocator| {
allocator.destroy(self);
}
}
pub fn page(self: Self, sparse: SparseT) usize {
return (sparse & self.entity_mask) / entity_per_page;
}
fn offset(self: Self, sparse: SparseT) usize {
return sparse & (entity_per_page - 1);
}
fn assure(self: *Self, pos: usize) []SparseT {
if (pos >= self.sparse.items.len) {
const start_pos = self.sparse.items.len;
self.sparse.resize(pos + 1) catch unreachable;
self.sparse.expandToCapacity();
std.mem.set(?[]SparseT, self.sparse.items[start_pos..], null);
}
if (self.sparse.items[pos]) |arr| {
return arr;
}
var new_page = self.sparse.allocator.alloc(SparseT, entity_per_page) catch unreachable;
std.mem.set(SparseT, new_page, std.math.maxInt(SparseT));
self.sparse.items[pos] = new_page;
return self.sparse.items[pos].?;
}
/// Increases the capacity of a sparse sets index array
pub fn reserve(self: *Self, cap: usize) void {
self.sparse.resize(cap) catch unreachable;
}
/// Returns the number of dense elements that a sparse set has currently allocated space for
pub fn capacity(self: *Self) usize {
return self.dense.capacity;
}
/// Returns the number of dense elements in a sparse set
pub fn len(self: Self) usize {
return self.dense.items.len;
}
pub fn empty(self: *Self) bool {
return self.dense.items.len == 0;
}
pub fn data(self: Self) []const SparseT {
return self.dense.items;
}
pub fn dataPtr(self: Self) *const []SparseT {
return &self.dense.items;
}
pub fn contains(self: Self, sparse: SparseT) bool {
const curr = self.page(sparse);
return curr < self.sparse.items.len and self.sparse.items[curr] != null and self.sparse.items[curr].?[self.offset(sparse)] != std.math.maxInt(SparseT);
}
/// Returns the position of an entity in a sparse set
pub fn index(self: Self, sparse: SparseT) SparseT {
std.debug.assert(self.contains(sparse));
return self.sparse.items[self.page(sparse)].?[self.offset(sparse)];
}
/// Assigns an entity to a sparse set
pub fn add(self: *Self, sparse: SparseT) void {
std.debug.assert(!self.contains(sparse));
// assure(page(entt))[offset(entt)] = packed.size()
self.assure(self.page(sparse))[self.offset(sparse)] = @intCast(SparseT, self.dense.items.len);
_ = self.dense.append(sparse) catch unreachable;
}
/// Removes an entity from a sparse set
pub fn remove(self: *Self, sparse: SparseT) void {
std.debug.assert(self.contains(sparse));
const curr = self.page(sparse);
const pos = self.offset(sparse);
const last_dense = self.dense.items[self.dense.items.len - 1];
self.dense.items[self.sparse.items[curr].?[pos]] = last_dense;
self.sparse.items[self.page(last_dense)].?[self.offset(last_dense)] = self.sparse.items[curr].?[pos];
self.sparse.items[curr].?[pos] = std.math.maxInt(SparseT);
_ = self.dense.pop();
}
/// Swaps two entities in the internal packed and sparse arrays
pub fn swap(self: *Self, lhs: SparseT, rhs: SparseT) void {
var from = &self.sparse.items[self.page(lhs)].?[self.offset(lhs)];
var to = &self.sparse.items[self.page(rhs)].?[self.offset(rhs)];
std.mem.swap(SparseT, &self.dense.items[from.*], &self.dense.items[to.*]);
std.mem.swap(SparseT, from, to);
}
/// Sort elements according to the given comparison function
pub fn sort(self: *Self, context: anytype, comptime lessThan: fn (@TypeOf(context), SparseT, SparseT) bool) void {
std.sort.insertionSort(SparseT, self.dense.items, context, lessThan);
for (self.dense.items) |sparse, i| {
const item = @intCast(SparseT, i);
self.sparse.items[self.page(self.dense.items[self.page(item)])].?[self.offset(self.dense.items[self.page(item)])] = @intCast(SparseT, i);
}
}
/// Sort elements according to the given comparison function. Use this when a data array needs to stay in sync with the SparseSet
/// by passing in a "swap_context" that contains a "swap" method with a sig of fn(ctx,SparseT,SparseT)void
pub fn arrange(self: *Self, length: usize, context: anytype, comptime lessThan: fn (@TypeOf(context), SparseT, SparseT) bool, swap_context: anytype) void {
std.sort.insertionSort(SparseT, self.dense.items[0..length], context, lessThan);
for (self.dense.items[0..length]) |sparse, pos| {
var curr = @intCast(SparseT, pos);
var next = self.index(self.dense.items[curr]);
while (curr != next) {
swap_context.swap(self.dense.items[curr], self.dense.items[next]);
self.sparse.items[self.page(self.dense.items[curr])].?[self.offset(self.dense.items[curr])] = curr;
curr = next;
next = self.index(self.dense.items[curr]);
}
}
}
/// Sort entities according to their order in another sparse set. Other is the master in this case.
pub fn respect(self: *Self, other: *Self) void {
var pos = @as(SparseT, 0);
var i = @as(SparseT, 0);
while (i < other.dense.items.len) : (i += 1) {
if (self.contains(other.dense.items[i])) {
if (other.dense.items[i] != self.dense.items[pos]) {
self.swap(self.dense.items[pos], other.dense.items[i]);
}
pos += 1;
}
}
}
pub fn clear(self: *Self) void {
self.sparse.expandToCapacity();
for (self.sparse.items) |array, i| {
if (array) |arr| {
self.sparse.allocator.free(arr);
self.sparse.items[i] = null;
}
}
self.sparse.items.len = 0;
self.dense.items.len = 0;
}
pub fn reverseIterator(self: *Self) ReverseSliceIterator(SparseT) {
return ReverseSliceIterator(SparseT).init(self.dense.items);
}
};
}
fn printSet(set: *SparseSet(u32, u8)) void {
std.debug.warn("\nsparse -----\n", .{});
for (set.sparse.items) |sparse| {
std.debug.warn("{}\t", .{sparse});
}
std.debug.warn("\ndense -----\n", .{});
for (set.dense.items) |dense| {
std.debug.warn("{}\t", .{dense});
}
std.debug.warn("\n\n", .{});
}
test "add/remove/clear" {
var set = SparseSet(u32).initPtr(std.testing.allocator);
defer set.deinit();
set.add(4);
set.add(3);
std.testing.expectEqual(set.len(), 2);
std.testing.expectEqual(set.index(4), 0);
std.testing.expectEqual(set.index(3), 1);
set.remove(4);
std.testing.expectEqual(set.len(), 1);
set.clear();
std.testing.expectEqual(set.len(), 0);
}
test "grow" {
var set = SparseSet(u32).initPtr(std.testing.allocator);
defer set.deinit();
var i = @as(usize, std.math.maxInt(u8));
while (i > 0) : (i -= 1) {
set.add(@intCast(u32, i));
}
std.testing.expectEqual(set.len(), std.math.maxInt(u8));
}
test "swap" {
var set = SparseSet(u32).initPtr(std.testing.allocator);
defer set.deinit();
set.add(4);
set.add(3);
std.testing.expectEqual(set.index(4), 0);
std.testing.expectEqual(set.index(3), 1);
set.swap(4, 3);
std.testing.expectEqual(set.index(3), 0);
std.testing.expectEqual(set.index(4), 1);
}
test "data() synced" {
var set = SparseSet(u32).initPtr(std.testing.allocator);
defer set.deinit();
set.add(0);
set.add(1);
set.add(2);
set.add(3);
var data = set.data();
std.testing.expectEqual(data[1], 1);
std.testing.expectEqual(set.len(), data.len);
set.remove(0);
set.remove(1);
std.testing.expectEqual(set.len(), set.data().len);
}
test "iterate" {
var set = SparseSet(u32).initPtr(std.testing.allocator);
defer set.deinit();
set.add(0);
set.add(1);
set.add(2);
set.add(3);
var i: u32 = @intCast(u32, set.len()) - 1;
var iter = set.reverseIterator();
while (iter.next()) |entity| {
std.testing.expectEqual(i, entity);
if (i > 0) i -= 1;
}
}
test "respect 1" {
var set1 = SparseSet(u32).initPtr(std.testing.allocator);
defer set1.deinit();
var set2 = SparseSet(u32).initPtr(std.testing.allocator);
defer set2.deinit();
set1.add(3);
set1.add(4);
set1.add(5);
set1.add(6);
set1.add(7);
set2.add(8);
set2.add(6);
set2.add(4);
set1.respect(set2);
std.testing.expectEqual(set1.dense.items[0], set2.dense.items[1]);
std.testing.expectEqual(set1.dense.items[1], set2.dense.items[2]);
}
const desc_u32 = std.sort.desc(u32);
test "respect 2" {
var set = SparseSet(u32).initPtr(std.testing.allocator);
defer set.deinit();
set.add(5);
set.add(2);
set.add(4);
set.add(1);
set.add(3);
set.sort({}, desc_u32);
for (set.dense.items) |item, i| {
if (i < set.dense.items.len - 1) {
std.debug.assert(item > set.dense.items[i + 1]);
}
}
}
|
src/ecs/ecs/sparse_set.zig
|
const builtin = @import("builtin");
const std = @import("std");
const EXIT_FAILURE = 1;
pub fn initIface() !void {
try switch (builtin.os.tag) {
.linux => linuxIface(),
.freebsd => freebsdIface(),
.netbsd => netbsdIface(),
else => {},
};
}
fn linuxIface() !void {
var arena = std.heap.ArenaAllocator.init(std.heap.page_allocator);
defer arena.deinit();
const alloc = &arena.allocator;
std.debug.print("Configuring Linux interfaces.\n", .{});
// Temp test code
const iface_name: []const u8 = "tap1"; //temp
const iface_ip4: []const u8 = "10.0.0.12"; //temp
const iface_ip6: []const u8 = "fd00:42c6:3eb2::a"; //temp
const tap_clear = try std.ChildProcess.init(&[_][]const u8{ "ip", "link", "delete", iface_name }, alloc);
const tap_setup = try std.ChildProcess.init(&[_][]const u8{ "ip", "tuntap", "add", iface_name, "mode", "tap" }, alloc);
const tap_up = try std.ChildProcess.init(&[_][]const u8{ "ip", "link", "set", "dev", iface_name, "up" }, alloc);
const tap_ip4 = try std.ChildProcess.init(&[_][]const u8{ "ip", "a", "add", iface_ip4, "dev", iface_name }, alloc);
const tap_ip6 = try std.ChildProcess.init(&[_][]const u8{ "ip", "-6", "a", "add", iface_ip6, "dev", iface_name }, alloc);
const tap_route = try std.ChildProcess.init(&[_][]const u8{ "ip", "-6", "route", "add", "64:ff9b::/96", "dev", iface_name }, alloc);
defer tap_clear.deinit();
defer tap_setup.deinit();
defer tap_up.deinit();
defer tap_ip4.deinit();
defer tap_ip6.deinit();
defer tap_route.deinit();
// TODO: Handle more errors
_ = try tap_clear.spawnAndWait();
const setup_term = try tap_setup.spawnAndWait();
if (setup_term.Exited == 1) {
std.debug.print("Error: Program needs to runs commands that require SuperUser access\n", .{});
std.process.exit(EXIT_FAILURE);
}
_ = try tap_up.spawnAndWait();
_ = try tap_ip4.spawnAndWait();
_ = try tap_ip6.spawnAndWait();
_ = try tap_route.spawnAndWait();
}
fn freebsdIface() !void {
//std.debug.print("Configuring FreeBSD interfaces.\n", .{});
std.debug.print("FreeBSD support is planned but not implemented yet\n", .{});
}
fn netbsdIface() !void {
//std.debug.print("Configuring NetBSD interfaces.\n", .{});
std.debug.print("NetBSD support is planned but not implemented yet\n", .{});
}
pub fn openInterface() !void {
std.debug.print("Attaching to Interface...\n", .{});
const c = @cImport({
@cInclude("cFunctions.h");
});
const iface_fd = try std.fs.openFileAbsoluteZ("/dev/net/tun", std.fs.File.OpenFlags{
.read = true,
.write = true,
});
if (c.get_iface_fd(iface_fd.handle) < 0) { // TODO: Use Zig error handling
std.debug.print("Failed to attach to interface\n", .{});
iface_fd.close();
std.process.exit(EXIT_FAILURE);
}
std.debug.print("{}\n", .{iface_fd.handle});
}
pub fn zigOpenInterface() !void {
const c = @cImport({
@cInclude("sys/ioctl.h");
@cInclude("net/if.h");
@cInclude("linux/if_tun.h");
@cInclude("fcntl.h");
@cInclude("unistd.h");
});
const iface_fd = try std.fs.openFileAbsoluteZ("/dev/net/tun", std.fs.File.OpenFlags{
.read = true,
.write = true,
});
errdefer iface_fd.close();
const if_name = "tap1"; // TEMP
var iface: c.ifreq = std.mem.zeroes(c.ifreq); // TODO: Make this work lol, Zig doesn't see the members of the struct because they are members of a union within the struct.
iface.ifr_name = if_name;
iface.ifr_flags = c.IFF_NO_PI | c.IFF_TAP;
try c.ioctl(iface_fd, c.TUNSETIFF, @ptrCast(*void, &iface));
}
|
src/interface.zig
|
const std = @import("std");
const assert = std.debug.assert;
const warn = std.debug.warn;
const mem = std.mem;
const math = std.math;
const Queue = std.atomic.Queue;
const Timer = std.os.time.Timer;
const builtin = @import("builtin");
const AtomicOrder = builtin.AtomicOrder;
const AtomicRmwOp = builtin.AtomicRmwOp;
const linux = switch(builtin.os) {
builtin.Os.linux => std.os.linux,
else => @compileError("Only builtin.os.linux is supported"),
};
pub use switch(builtin.arch) {
builtin.Arch.x86_64 => @import("../zig/std/os/linux/x86_64.zig"),
else => @compileError("unsupported arch"),
};
pub fn futex_wait(pVal: *u32, expected_value: u32) void {
//warn("futex_wait: {*}\n", pVal);
_ = syscall4(SYS_futex, @ptrToInt(pVal), linux.FUTEX_WAIT, expected_value, 0);
}
pub fn futex_wake(pVal: *u32, num_threads_to_wake: u32) void {
//warn("futex_wake: {*}\n", pVal);
_ = syscall4(SYS_futex, @ptrToInt(pVal), linux.FUTEX_WAKE, num_threads_to_wake, 0);
}
const ThreadContext = struct {
const Self = @This();
mode: bool,
counter: u128,
pub fn init(pSelf: *Self, mode: bool) void {
pSelf.mode = mode;
pSelf.counter = 0;
}
};
var gProducer_context: ThreadContext = undefined;
var gConsumer_context: ThreadContext = undefined;
const naive = true;
const consumeSignal = 0;
const produceSignal = 1;
var produce: u32 = consumeSignal;
var gCounter: u64 = 0;
var gProducerWaitCount: u64 = 0;
var gConsumerWaitCount: u64 = 0;
var gProducerWakeCount: u64 = 0;
var gConsumerWakeCount: u64 = 0;
const max_counter = 10000000;
const stallCountWait: u32 = 10000;
const stallCountWake: u32 = 2000;
fn stallWhileNotDesiredVal(stallCount: u64, pValue: *u32, desiredValue: u32) u32 {
var count = stallCount;
var val = @atomicLoad(u32, pValue, AtomicOrder.Acquire);
while ((val != desiredValue) and (count > 0)) {
val = @atomicLoad(u32, pValue, AtomicOrder.Acquire);
count -= 1;
}
return val;
}
fn stallWhileDesiredVal(stallCount: u64, pValue: *u32, desiredValue: u32) u32 {
var count = stallCount;
var val = @atomicLoad(u32, pValue, AtomicOrder.Acquire);
while ((val == desiredValue) and (count > 0)) {
val = @atomicLoad(u32, pValue, AtomicOrder.Acquire);
count -= 1;
}
return val;
}
fn producer(pContext: *ThreadContext) void {
if (pContext.mode == naive) {
while (pContext.counter < max_counter) {
// Wait for the produce to be the produceSignal
while (@atomicLoad(@typeOf(produce), &produce, AtomicOrder.Acquire) == consumeSignal) {
gProducerWaitCount += 1;
futex_wait(&produce, consumeSignal);
}
// Produce
_ = @atomicRmw(@typeOf(gCounter), &gCounter, AtomicRmwOp.Add, 1, AtomicOrder.Monotonic);
pContext.counter += 1;
// Tell consumer to consume and then wake consumer up
_ = @atomicRmw(@typeOf(produce), &produce, AtomicRmwOp.Xchg, consumeSignal, AtomicOrder.Release);
gProducerWakeCount += 1;
futex_wake(&produce, 1);
}
} else {
while (pContext.counter < max_counter) {
// Wait for the produce to be the produceSignal,
// @noInlineCall not necessary to workaround Issue #1388
var produce_val = stallWhileDesiredVal(stallCountWait, &produce, consumeSignal);
while (produce_val == consumeSignal) {
gProducerWaitCount += 1;
futex_wait(&produce, consumeSignal);
produce_val = @atomicLoad(@typeOf(produce), &produce, AtomicOrder.Acquire);
}
// Produce
_ = @atomicRmw(@typeOf(gCounter), &gCounter, AtomicRmwOp.Add, 1, AtomicOrder.Monotonic);
pContext.counter += 1;
// Tell consumer to consume
_ = @atomicRmw(@typeOf(produce), &produce, AtomicRmwOp.Xchg, consumeSignal, AtomicOrder.Release);
// Wake up consumer if needed
produce_val = stallWhileDesiredVal(stallCountWake, &produce, consumeSignal);
if (produce_val == consumeSignal) {
gProducerWakeCount += 1;
futex_wake(&produce, 1);
}
}
}
}
fn consumer(pContext: *ThreadContext) void {
if (pContext.mode == naive) {
while (pContext.counter < max_counter) {
// Tell producer to produce
_ = @atomicRmw(@typeOf(produce), &produce, AtomicRmwOp.Xchg, produceSignal, AtomicOrder.Release);
// Wakeup produce incase it was waiting
gConsumerWakeCount += 1;
futex_wake(&produce, 1);
// Wait for producer to produce
while (@atomicLoad(@typeOf(produce), &produce, AtomicOrder.Acquire) == produceSignal) {
gConsumerWaitCount += 1;
futex_wait(&produce, produceSignal);
}
// Consume
_ = @atomicRmw(@typeOf(gCounter), &gCounter, AtomicRmwOp.Add, 1, AtomicOrder.Monotonic);
pContext.counter += 1;
}
} else {
while (pContext.counter < max_counter) {
// Tell producer to produce
_ = @atomicRmw(@typeOf(produce), &produce, AtomicRmwOp.Xchg, produceSignal, AtomicOrder.Release);
// Wake up producer if needed
// @noInlineCall not necessary to workaround Issue #1388
var produce_val = stallWhileDesiredVal(stallCountWake, &produce, produceSignal);
if (produce_val == produceSignal) {
gConsumerWakeCount += 1;
futex_wake(&produce, 1);
}
// Wait for producer to produce
produce_val = stallWhileDesiredVal(stallCountWait, &produce, produceSignal);
while (produce_val == produceSignal) {
gConsumerWaitCount += 1;
futex_wait(&produce, produceSignal);
produce_val = @atomicLoad(@typeOf(produce), &produce, AtomicOrder.Acquire);
}
// Consume
_ = @atomicRmw(@typeOf(gCounter), &gCounter, AtomicRmwOp.Add, 1, AtomicOrder.Monotonic);
pContext.counter += 1;
}
}
}
test "Futex" {
warn("\ntest Futex:+ gCounter={} gProducerWaitCount={} gConsumerWaitCount={} gProducerWakeCount={} gConsuerWakeCount={}\n",
gCounter, gProducerWaitCount, gConsumerWaitCount, gProducerWakeCount, gConsumerWakeCount);
defer warn("test Futex:- gCounter={} gProducerWaitCount={} gConsumerWaitCount={} gProducerWakeCount={} gConsuerWakeCount={}\n",
gCounter, gProducerWaitCount, gConsumerWaitCount, gProducerWakeCount, gConsumerWakeCount);
gProducer_context.init(!naive);
gConsumer_context.init(!naive);
var timer = try Timer.start();
var start_time = timer.read();
var producerThread = try std.os.spawnThread(&gProducer_context, producer);
var consumerThread = try std.os.spawnThread(&gConsumer_context, consumer);
producerThread.wait();
consumerThread.wait();
var end_time = timer.read();
var duration = end_time - start_time;
warn("test Futex: time={.6}\n", @intToFloat(f64, end_time - start_time) / @intToFloat(f64, std.os.time.ns_per_s));
assert(gCounter == max_counter * 2);
}
|
futex.zig
|
const std = @import("std");
const build_options = @import("build_options");
const ascii = std.ascii;
const debug = std.debug;
const fmt = std.fmt;
const heap = std.heap;
const io = std.io;
const mem = std.mem;
const net = std.net;
const os = std.os;
const time = std.time;
const Atomic = std.atomic.Atomic;
const assert = std.debug.assert;
const IO_Uring = std.os.linux.IO_Uring;
const io_uring_cqe = std.os.linux.io_uring_cqe;
const io_uring_sqe = std.os.linux.io_uring_sqe;
pub const createSocket = @import("io.zig").createSocket;
const RegisteredFileDescriptors = @import("io.zig").RegisteredFileDescriptors;
const Callback = @import("callback.zig").Callback;
const logger = std.log.scoped(.main);
/// HTTP types and stuff
const c = @cImport({
@cInclude("picohttpparser.h");
});
pub const Method = enum(u4) {
get,
head,
post,
put,
delete,
connect,
options,
trace,
patch,
pub fn toString(self: Method) []const u8 {
switch (self) {
.get => return "GET",
.head => return "HEAD",
.post => return "POST",
.put => return "PUT",
.delete => return "DELETE",
.connect => return "CONNECT",
.options => return "OPTIONS",
.trace => return "TRACE",
.patch => return "PATCH",
}
}
fn fromString(s: []const u8) !Method {
if (ascii.eqlIgnoreCase(s, "GET")) {
return .get;
} else if (ascii.eqlIgnoreCase(s, "HEAD")) {
return .head;
} else if (ascii.eqlIgnoreCase(s, "POST")) {
return .post;
} else if (ascii.eqlIgnoreCase(s, "PUT")) {
return .put;
} else if (ascii.eqlIgnoreCase(s, "DELETE")) {
return .delete;
} else if (ascii.eqlIgnoreCase(s, "CONNECT")) {
return .connect;
} else if (ascii.eqlIgnoreCase(s, "OPTIONS")) {
return .options;
} else if (ascii.eqlIgnoreCase(s, "TRACE")) {
return .trace;
} else if (ascii.eqlIgnoreCase(s, "PATCH")) {
return .patch;
} else {
return error.InvalidMethod;
}
}
};
pub const StatusCode = enum(u10) {
// informational
continue_ = 100,
switching_protocols = 101,
// success
ok = 200,
created = 201,
accepted = 202,
no_content = 204,
partial_content = 206,
// redirection
moved_permanently = 301,
found = 302,
not_modified = 304,
temporary_redirect = 307,
permanent_redirect = 308,
// client error
bad_request = 400,
unauthorized = 401,
forbidden = 403,
not_found = 404,
method_not_allowed = 405,
not_acceptable = 406,
gone = 410,
too_many_requests = 429,
// server error
internal_server_error = 500,
bad_gateway = 502,
service_unavailable = 503,
gateway_timeout = 504,
pub fn toString(self: StatusCode) []const u8 {
switch (self) {
// informational
.continue_ => return "Continue",
.switching_protocols => return "Switching Protocols",
.ok => return "OK",
.created => return "Created",
.accepted => return "Accepted",
.no_content => return "No Content",
.partial_content => return "Partial Content",
// redirection
.moved_permanently => return "Moved Permanently",
.found => return "Found",
.not_modified => return "Not Modified",
.temporary_redirect => return "Temporary Redirected",
.permanent_redirect => return "Permanent Redirect",
// client error
.bad_request => return "Bad Request",
.unauthorized => return "Unauthorized",
.forbidden => return "Forbidden",
.not_found => return "Not Found",
.method_not_allowed => return "Method Not Allowed",
.not_acceptable => return "Not Acceptable",
.gone => return "Gone",
.too_many_requests => return "Too Many Requests",
// server error
.internal_server_error => return "Internal Server Error",
.bad_gateway => return "Bad Gateway",
.service_unavailable => return "Service Unavailable",
.gateway_timeout => return "Gateway Timeout",
}
}
};
pub const Header = struct {
name: []const u8,
value: []const u8,
};
pub const Headers = struct {
storage: [RawRequest.max_headers]Header,
view: []Header,
fn create(req: RawRequest) !Headers {
assert(req.num_headers < RawRequest.max_headers);
var res = Headers{
.storage = undefined,
.view = undefined,
};
const num_headers = req.copyHeaders(&res.storage);
res.view = res.storage[0..num_headers];
return res;
}
pub fn get(self: Headers, name: []const u8) ?Header {
for (self.view) |item| {
if (ascii.eqlIgnoreCase(name, item.name)) {
return item;
}
}
return null;
}
};
/// Request type contains fields populated by picohttpparser and provides
/// helpers methods for easier use with Zig.
const RawRequest = struct {
const Self = @This();
const max_headers = 100;
method: [*c]u8 = undefined,
method_len: usize = undefined,
path: [*c]u8 = undefined,
path_len: usize = undefined,
minor_version: c_int = 0,
headers: [max_headers]c.phr_header = undefined,
num_headers: usize = max_headers,
fn getMethod(self: Self) []const u8 {
return self.method[0..self.method_len];
}
fn getPath(self: Self) []const u8 {
return self.path[0..self.path_len];
}
fn getMinorVersion(self: Self) usize {
return @intCast(usize, self.minor_version);
}
fn copyHeaders(self: Self, headers: []Header) usize {
assert(headers.len >= self.num_headers);
var i: usize = 0;
while (i < self.num_headers) : (i += 1) {
const hdr = self.headers[i];
const name = hdr.name[0..hdr.name_len];
const value = hdr.value[0..hdr.value_len];
headers[i].name = name;
headers[i].value = value;
}
return self.num_headers;
}
fn getContentLength(self: Self) !?usize {
var i: usize = 0;
while (i < self.num_headers) : (i += 1) {
const hdr = self.headers[i];
const name = hdr.name[0..hdr.name_len];
const value = hdr.value[0..hdr.value_len];
if (!std.ascii.eqlIgnoreCase(name, "Content-Length")) {
continue;
}
return try fmt.parseInt(usize, value, 10);
}
return null;
}
};
const ParseRequestResult = struct {
raw_request: RawRequest,
consumed: usize,
};
fn parseRequest(previous_buffer_len: usize, buffer: []const u8) !?ParseRequestResult {
var req = RawRequest{};
const res = c.phr_parse_request(
buffer.ptr,
buffer.len,
&req.method,
&req.method_len,
&req.path,
&req.path_len,
&req.minor_version,
&req.headers,
&req.num_headers,
previous_buffer_len,
);
if (res == -1) {
// TODO(vincent): don't panic, proper cleanup instead
std.debug.panic("parse error\n", .{});
}
if (res == -2) {
return null;
}
return ParseRequestResult{
.raw_request = req,
.consumed = @intCast(usize, res),
};
}
/// Contains peer information for a request.
pub const Peer = struct {
addr: net.Address,
};
/// Contains request data.
/// This is what the handler will receive.
pub const Request = struct {
method: Method,
path: []const u8,
minor_version: usize,
headers: Headers,
body: ?[]const u8,
fn create(req: RawRequest, body: ?[]const u8) !Request {
return Request{
.method = try Method.fromString(req.getMethod()),
.path = req.getPath(),
.minor_version = req.getMinorVersion(),
.headers = try Headers.create(req),
.body = body,
};
}
};
/// The response returned by the handler.
pub const Response = union(enum) {
/// The response is a simple buffer.
response: struct {
status_code: StatusCode,
headers: []Header,
data: []const u8,
},
/// The response is a static file that will be read from the filesystem.
send_file: struct {
status_code: StatusCode,
headers: []Header,
path: []const u8,
},
};
pub fn RequestHandler(comptime Context: type) type {
return fn (Context, mem.Allocator, Peer, Request) anyerror!Response;
}
const ClientState = struct {
const RequestState = struct {
parse_result: ParseRequestResult = .{
.raw_request = .{},
.consumed = 0,
},
content_length: ?usize = null,
/// this is a view into the client buffer
body: ?[]const u8 = null,
};
/// Holds state used to send a response to the client.
const ResponseState = struct {
/// keeps track of the number of bytes that we written on the socket
written: usize = 0,
/// status code and header are overwritable in the handler
status_code: StatusCode = .ok,
headers: []Header = &[_]Header{},
/// state used when we need to send a static file from the filesystem.
file: struct {
path: [:0]u8 = undefined,
fd: os.fd_t = -1,
statx_buf: os.linux.Statx = undefined,
} = .{},
};
gpa: mem.Allocator,
/// peer information associated with this client
peer: Peer,
fd: os.socket_t,
// Buffer and allocator used for small allocations (nul-terminated path, integer to int conversions etc).
temp_buffer: [128]u8 = undefined,
temp_buffer_fba: heap.FixedBufferAllocator = undefined,
// TODO(vincent): prevent going over the max_buffer_size somehow ("limiting" allocator ?)
// TODO(vincent): right now we always use clearRetainingCapacity() which may keep a lot of memory
// allocated for no reason.
// Implement some sort of statistics to determine if we should release memory, for example:
// * max size used by the last 100 requests for reads or writes
// * duration without any request before releasing everything
buffer: std.ArrayList(u8),
request_state: RequestState = .{},
response_state: ResponseState = .{},
// non-null if the client was able to acquire a registered file descriptor.
registered_fd: ?i32 = null,
pub fn init(self: *ClientState, allocator: mem.Allocator, peer_addr: net.Address, client_fd: os.socket_t, max_buffer_size: usize) !void {
self.* = .{
.gpa = allocator,
.peer = .{
.addr = peer_addr,
},
.fd = client_fd,
.buffer = undefined,
};
self.temp_buffer_fba = heap.FixedBufferAllocator.init(&self.temp_buffer);
self.buffer = try std.ArrayList(u8).initCapacity(self.gpa, max_buffer_size);
}
pub fn deinit(self: *ClientState) void {
self.buffer.deinit();
}
fn refreshBody(self: *ClientState) void {
const consumed = self.request_state.parse_result.consumed;
if (consumed > 0) {
self.request_state.body = self.buffer.items[consumed..];
}
}
pub fn reset(self: *ClientState) void {
self.request_state = .{};
self.response_state = .{};
self.buffer.clearRetainingCapacity();
}
fn writeResponsePreambule(self: *ClientState, content_length: ?usize) !void {
var writer = self.buffer.writer();
try writer.print("HTTP/1.1 {d} {s}\n", .{
@enumToInt(self.response_state.status_code),
self.response_state.status_code.toString(),
});
for (self.response_state.headers) |header| {
try writer.print("{s}: {s}\n", .{ header.name, header.value });
}
if (content_length) |n| {
try writer.print("Content-Length: {d}\n", .{n});
}
try writer.print("\n", .{});
}
};
pub const ServerOptions = struct {
max_ring_entries: u13 = 512,
max_buffer_size: usize = 4096,
max_connections: usize = 128,
};
/// The HTTP server.
///
/// This struct does nothing by itself, the caller must drive it to achieve anything.
/// After initialization the caller must, in a loop:
/// * call maybeAccept
/// * call submit
/// * call processCompletions
///
/// Then the server will accept connections and process requests.
///
/// NOTE: this is _not_ thread safe ! You must create on Server object per thread.
pub fn Server(comptime Context: type) type {
return struct {
const Self = @This();
const CallbackType = Callback(*Self, *ClientState);
/// allocator used to allocate each client state
root_allocator: mem.Allocator,
/// uring dedicated to this server object.
ring: IO_Uring,
/// options controlling the behaviour of the server.
options: ServerOptions,
/// indicates if the server should continue running.
/// This is _not_ owned by the server but by the caller.
running: *Atomic(bool),
/// This field lets us keep track of the number of pending operations which is necessary to implement drain() properly.
///
/// Note that this is different than the number of SQEs pending in the submission queue or CQEs pending in the completion queue.
/// For example an accept operation which has been consumed by the kernel but hasn't accepted any connection yet must be considered
/// pending for us but it's not pending in either the submission or completion queue.
/// Another example is a timeout: once accepted and until expired it won't be available in the completion queue.
pending: usize = 0,
/// Listener state
listener: struct {
/// server file descriptor used for accept(2) operation.
/// Must have had bind(2) and listen(2) called on it before being passed to `init()`.
server_fd: os.socket_t,
/// indicates if an accept operation is pending.
accept_waiting: bool = false,
/// the timeout data for the link_timeout operation linked to the previous accept.
///
/// Each accept operation has a following timeout linked to it; this works in such a way
/// that if the timeout has expired the accept operation is cancelled and if the accept has finished
/// before the timeout then the timeout operation is cancelled.
///
/// This is useful to run the main loop for a bounded duration.
timeout: os.linux.kernel_timespec = .{
.tv_sec = 0,
.tv_nsec = 0,
},
// Next peer we're accepting.
// Will be valid after a successful CQE for an accept operation.
peer_addr: net.Address = net.Address{
.any = undefined,
},
peer_addr_size: u32 = @sizeOf(os.sockaddr),
},
/// CQEs storage
cqes: []io_uring_cqe = undefined,
/// List of client states.
/// A new state is created for each socket accepted and destroyed when the socket is closed for any reason.
clients: std.ArrayList(*ClientState),
/// Free list of callback objects necessary for working with the uring.
/// See the documentation of Callback.Pool.
callbacks: CallbackType.Pool,
/// Set of registered file descriptors for use with the uring.
///
/// TODO(vincent): make use of this somehow ? right now it crashes the kernel.
registered_fds: RegisteredFileDescriptors,
user_context: Context,
handler: RequestHandler(Context),
/// initializes a Server object.
pub fn init(
self: *Self,
/// General purpose allocator which will:
/// * allocate all client states (including request/response bodies).
/// * allocate the callback pool
/// Depending on the workload the allocator can be hit quite often (for example if all clients close their connection).
allocator: mem.Allocator,
/// controls the behaviour of the server (max number of connections, max buffer size, etc).
options: ServerOptions,
/// owned by the caller and indicates if the server should shutdown properly.
running: *Atomic(bool),
/// must be a socket properly initialized with listen(2) and bind(2) which will be used for accept(2) operations.
server_fd: os.socket_t,
/// user provided context that will be passed to the request handlers.
user_context: Context,
/// user provied request handler.
comptime handler: RequestHandler(Context),
) !void {
// TODO(vincent): probe for available features for io_uring ?
self.* = .{
.root_allocator = allocator,
.ring = try std.os.linux.IO_Uring.init(options.max_ring_entries, 0),
.options = options,
.running = running,
.listener = .{
.server_fd = server_fd,
},
.cqes = try allocator.alloc(io_uring_cqe, options.max_ring_entries),
.clients = try std.ArrayList(*ClientState).initCapacity(allocator, options.max_connections),
.callbacks = undefined,
.registered_fds = .{},
.user_context = user_context,
.handler = handler,
};
self.callbacks = try CallbackType.Pool.init(allocator, self, options.max_ring_entries);
try self.registered_fds.register(&self.ring);
}
pub fn deinit(self: *Self) void {
for (self.clients.items) |client| {
client.deinit();
self.root_allocator.destroy(client);
}
self.clients.deinit();
self.callbacks.deinit();
self.root_allocator.free(self.cqes);
self.ring.deinit();
}
/// Runs the main loop until the `running` boolean is false.
///
/// `accept_timeout` controls how much time the loop can wait for an accept operation to finish.
/// This duration is the lower bound duration before the main loop can stop when `running` is false;
pub fn run(self: *Self, accept_timeout: u63) !void {
// TODO(vincent): we don't properly shutdown the peer sockets; we should do that.
// This can be done using standard close(2) calls I think.
while (self.running.load(.SeqCst)) {
// first step: (maybe) submit and accept with a link_timeout linked to it.
//
// Nothing is submitted if:
// * a previous accept operation is already waiting.
// * the number of connected clients reached the predefined limit.
try self.maybeAccept(accept_timeout);
// second step: submit to the kernel all previous queued SQE.
//
// SQEs might be queued by the maybeAccept call above or by the processCompletions call below, but
// obviously in that case its SQEs queued from the _previous iteration_ that are submitted to the kernel.
//
// Additionally we wait for at least 1 CQE to be available, if none is available the thread will be put to sleep by the kernel.
// Note that this doesn't work if the uring is setup with busy-waiting.
const submitted = try self.submit(1);
// third step: process all available CQEs.
//
// This asks the kernel to wait for at least `submitted` CQE to be available.
// Since we successfully submitted that many SQEs it is guaranteed we will _at some point_
// get that many CQEs but there's no guarantee they will be available instantly; if the
// kernel lags in processing the SQEs we can have a delay in getting the CQEs.
// This is further accentuated by the number of pending SQEs we can have.
//
// One example would be submitting a lot of fdatasync operations on slow devices.
_ = try self.processCompletions(submitted);
}
try self.drain();
}
fn maybeAccept(self: *Self, timeout: u63) !void {
if (!self.running.load(.SeqCst)) {
// we must stop: stop accepting connections.
return;
}
if (self.listener.accept_waiting or self.clients.items.len >= self.options.max_connections) {
return;
}
// Queue an accept and link it to a timeout.
var sqe = try self.submitAccept();
sqe.flags |= os.linux.IOSQE_IO_LINK;
self.listener.timeout.tv_sec = 0;
self.listener.timeout.tv_nsec = timeout;
_ = try self.submitAcceptLinkTimeout();
self.listener.accept_waiting = true;
}
/// Continuously submit SQEs and process completions until there are
/// no more pending operations.
///
/// This must be called when shutting down.
fn drain(self: *Self) !void {
// This call is only useful if pending > 0.
//
// It is currently impossible to have pending == 0 after an iteration of the main loop because:
// * if no accept waiting maybeAccept `pending` will increase by 2.
// * if an accept is waiting but we didn't get a connection, `pending` must still be >= 1.
// * if an accept is waiting and we got a connection, the previous processCompletions call
// increased `pending` while doing request processing.
// * if no accept waiting and too many connections, the previous processCompletions call
// increased `pending` while doing request processing.
//
// But to be extra sure we do this submit call outside the drain loop to ensure we have flushed all queued SQEs
// submitted in the last processCompletions call in the main loop.
_ = try self.submit(0);
while (self.pending > 0) {
_ = try self.submit(0);
_ = try self.processCompletions(self.pending);
}
}
/// Submits all pending SQE to the kernel, if any.
/// Waits for `nr` events to be completed before returning (0 means don't wait).
///
/// This also increments `pending` by the number of events submitted.
///
/// Returns the number of events submitted.
fn submit(self: *Self, nr: u32) !usize {
const n = try self.ring.submit_and_wait(nr);
self.pending += n;
return n;
}
/// Process all ready CQEs, if any.
/// Waits for `nr` events to be completed before processing begins (0 means don't wait).
///
/// This also decrements `pending` by the number of events processed.
///
/// Returnsd the number of events processed.
fn processCompletions(self: *Self, nr: usize) !usize {
// TODO(vincent): how should we handle EAGAIN and EINTR ? right now they will shutdown the server.
const cqe_count = try self.ring.copy_cqes(self.cqes, @intCast(u32, nr));
for (self.cqes[0..cqe_count]) |cqe| {
debug.assert(cqe.user_data != 0);
// We know that a SQE/CQE is _always_ associated with a pointer of type Callback.
var cb = @intToPtr(*CallbackType, cqe.user_data);
defer self.callbacks.put(cb);
// Call the provided function with the proper context.
//
// Note that while the callback function signature can return an error we don't bubble them up
// simply because we can't shutdown the server due to a processing error.
cb.call(cb.server, cb.client_context, cqe) catch |err| {
self.handleCallbackError(cb.client_context, err);
};
}
self.pending -= cqe_count;
return cqe_count;
}
fn handleCallbackError(self: *Self, client_opt: ?*ClientState, err: anyerror) void {
if (err == error.Canceled) return;
if (client_opt) |client| {
switch (err) {
error.ConnectionResetByPeer => {
logger.info("ctx#{s:<4} client fd={d} disconnected", .{ self.user_context, client.fd });
},
error.UnexpectedEOF => {
logger.debug("ctx#{s:<4} unexpected eof", .{self.user_context});
},
else => {
logger.err("ctx#{s:<4} unexpected error {s}", .{ self.user_context, err });
},
}
_ = self.submitClose(client, client.fd, onCloseClient) catch {};
} else {
logger.err("ctx#{s:<4} unexpected error {s}", .{ self.user_context, err });
}
}
fn submitAccept(self: *Self) !*io_uring_sqe {
if (build_options.debug_accepts) {
logger.debug("ctx#{s:<4} submitting accept on {d}", .{
self.user_context,
self.listener.server_fd,
});
}
var tmp = try self.callbacks.get(onAccept, .{});
return try self.ring.accept(
@ptrToInt(tmp),
self.listener.server_fd,
&self.listener.peer_addr.any,
&self.listener.peer_addr_size,
0,
);
}
fn submitAcceptLinkTimeout(self: *Self) !*io_uring_sqe {
if (build_options.debug_accepts) {
logger.debug("ctx#{s:<4} submitting link timeout", .{self.user_context});
}
var tmp = try self.callbacks.get(onAcceptLinkTimeout, .{});
return self.ring.link_timeout(
@ptrToInt(tmp),
&self.listener.timeout,
0,
);
}
fn submitStandaloneClose(self: *Self, fd: os.fd_t, comptime cb: anytype) !*io_uring_sqe {
logger.debug("ctx#{s:<4} submitting close of {d}", .{
self.user_context,
fd,
});
var tmp = try self.callbacks.get(cb, .{});
return self.ring.close(
@ptrToInt(tmp),
fd,
);
}
fn submitClose(self: *Self, client: *ClientState, fd: os.fd_t, comptime cb: anytype) !*io_uring_sqe {
logger.debug("ctx#{s:<4} addr={s} submitting close of {d}", .{
self.user_context,
client.peer.addr,
fd,
});
var tmp = try self.callbacks.get(cb, .{client});
return self.ring.close(
@ptrToInt(tmp),
fd,
);
}
fn onAccept(self: *Self, cqe: os.linux.io_uring_cqe) !void {
defer self.listener.accept_waiting = false;
switch (cqe.err()) {
.SUCCESS => {},
.INTR => {
logger.debug("ctx#{s:<4} ON ACCEPT interrupted", .{self.user_context});
return error.Canceled;
},
.CANCELED => {
if (build_options.debug_accepts) {
logger.debug("ctx#{s:<4} ON ACCEPT timed out", .{self.user_context});
}
return error.Canceled;
},
else => |err| {
logger.err("ctx#{s:<4} ON ACCEPT unexpected errno={}", .{ self.user_context, err });
return error.Unexpected;
},
}
logger.debug("ctx#{s:<4} ON ACCEPT accepting connection from {s}", .{ self.user_context, self.listener.peer_addr });
const client_fd = @intCast(os.socket_t, cqe.res);
var client = try self.root_allocator.create(ClientState);
errdefer self.root_allocator.destroy(client);
try client.init(
self.root_allocator,
self.listener.peer_addr,
client_fd,
self.options.max_buffer_size,
);
errdefer client.deinit();
try self.clients.append(client);
_ = try self.submitRead(client, client_fd, 0, onReadRequest);
}
fn onAcceptLinkTimeout(self: *Self, cqe: os.linux.io_uring_cqe) !void {
switch (cqe.err()) {
.CANCELED => {
if (build_options.debug_accepts) {
logger.debug("ctx#{s:<4} ON LINK TIMEOUT operation finished, timeout canceled", .{self.user_context});
}
},
.ALREADY => {
if (build_options.debug_accepts) {
logger.debug("ctx#{s:<4} ON LINK TIMEOUT operation already finished before timeout expired", .{self.user_context});
}
},
.TIME => {
if (build_options.debug_accepts) {
logger.debug("ctx#{s:<4} ON LINK TIMEOUT timeout finished before accept", .{self.user_context});
}
},
else => |err| {
logger.err("ctx#{s:<4} ON LINK TIMEOUT unexpected errno={}", .{ self.user_context, err });
return error.Unexpected;
},
}
}
fn onCloseClient(self: *Self, client: *ClientState, cqe: os.linux.io_uring_cqe) !void {
logger.debug("ctx#{s:<4} addr={s} ON CLOSE CLIENT fd={}", .{
self.user_context,
client.peer.addr,
client.fd,
});
// Cleanup resources
releaseRegisteredFileDescriptor(self, client);
client.deinit();
self.root_allocator.destroy(client);
// Remove client from list
const maybe_pos: ?usize = for (self.clients.items) |item, i| {
if (item == client) {
break i;
}
} else blk: {
break :blk null;
};
if (maybe_pos) |pos| _ = self.clients.orderedRemove(pos);
switch (cqe.err()) {
.SUCCESS => {},
else => |err| {
logger.err("ctx#{s:<4} unexpected errno={}", .{ self.user_context, err });
return error.Unexpected;
},
}
}
fn onClose(self: *Self, cqe: os.linux.io_uring_cqe) !void {
logger.debug("ctx#{s:<4} ON CLOSE", .{self.user_context});
switch (cqe.err()) {
.SUCCESS => {},
else => |err| {
logger.err("ctx#{s:<4} unexpected errno={}", .{ self.user_context, err });
return error.Unexpected;
},
}
}
fn onReadRequest(self: *Self, client: *ClientState, cqe: io_uring_cqe) !void {
switch (cqe.err()) {
.SUCCESS => {},
.PIPE => {
logger.err("ctx#{s:<4} addr={s} broken pipe", .{ self.user_context, client.peer.addr });
return error.BrokenPipe;
},
.CONNRESET => {
logger.debug("ctx#{s:<4} addr={s} connection reset by peer", .{ self.user_context, client.peer.addr });
return error.ConnectionResetByPeer;
},
else => |err| {
logger.err("ctx#{s:<4} addr={s} unexpected errno={}", .{ self.user_context, client.peer.addr, err });
return error.Unexpected;
},
}
if (cqe.res <= 0) {
return error.UnexpectedEOF;
}
const read = @intCast(usize, cqe.res);
logger.debug("ctx#{s:<4} addr={s} ON READ REQUEST read of {d} bytes succeeded", .{ self.user_context, client.peer.addr, read });
const previous_len = client.buffer.items.len;
try client.buffer.appendSlice(client.temp_buffer[0..read]);
if (try parseRequest(previous_len, client.buffer.items)) |result| {
client.request_state.parse_result = result;
try processRequest(self, client);
} else {
// Not enough data, read more.
logger.debug("ctx#{s:<4} addr={s} HTTP request incomplete, submitting read", .{ self.user_context, client.peer.addr });
_ = try self.submitRead(
client,
client.fd,
0,
onReadRequest,
);
}
}
fn onWriteResponseBuffer(self: *Self, client: *ClientState, cqe: io_uring_cqe) !void {
switch (cqe.err()) {
.SUCCESS => {},
.PIPE => {
logger.err("ctx#{s:<4} addr={s} broken pipe", .{ self.user_context, client.peer.addr });
return error.BrokenPipe;
},
.CONNRESET => {
logger.err("ctx#{s:<4} addr={s} connection reset by peer", .{ self.user_context, client.peer.addr });
return error.ConnectionResetByPeer;
},
else => |err| {
logger.err("ctx#{s:<4} addr={s} unexpected errno={}", .{ self.user_context, client.peer.addr, err });
return error.Unexpected;
},
}
const written = @intCast(usize, cqe.res);
if (written < client.buffer.items.len) {
// Short write, write the remaining data
// Remove the already written data
try client.buffer.replaceRange(0, written, &[0]u8{});
_ = try self.submitWrite(client, client.fd, 0, onWriteResponseBuffer);
return;
}
logger.debug("ctx#{s:<4} addr={s} ON WRITE RESPONSE done", .{
self.user_context,
client.peer.addr,
});
// Response written, read the next request
client.request_state = .{};
client.buffer.clearRetainingCapacity();
_ = try self.submitRead(client, client.fd, 0, onReadRequest);
}
fn onCloseResponseFile(self: *Self, client: *ClientState, cqe: os.linux.io_uring_cqe) !void {
logger.debug("ctx#{s:<4} addr={s} ON CLOSE RESPONSE FILE fd={}", .{
self.user_context,
client.peer.addr,
client.response_state.file.fd,
});
switch (cqe.err()) {
.SUCCESS => {},
else => |err| {
logger.err("ctx#{s:<4} unexpected errno={}", .{ self.user_context, err });
return error.Unexpected;
},
}
}
fn onWriteResponseFile(self: *Self, client: *ClientState, cqe: io_uring_cqe) !void {
debug.assert(client.buffer.items.len > 0);
switch (cqe.err()) {
.SUCCESS => {},
else => |err| {
logger.err("ctx#{s:<4} addr={s} ON WRITE RESPONSE FILE unexpected errno={}", .{ self.user_context, client.peer.addr, err });
return error.Unexpected;
},
}
if (cqe.res <= 0) {
return error.UnexpectedEOF;
}
const written = @intCast(usize, cqe.res);
logger.debug("ctx#{s:<4} addr={s} ON WRITE RESPONSE FILE write of {d} bytes to {d} succeeded", .{
self.user_context,
client.peer.addr,
written,
client.fd,
});
client.response_state.written += written;
if (written < client.buffer.items.len) {
// Short write, write the remaining data
// Remove the already written data
try client.buffer.replaceRange(0, written, &[0]u8{});
_ = try self.submitWrite(client, client.fd, 0, onWriteResponseFile);
return;
}
if (client.response_state.written < client.response_state.file.statx_buf.size) {
// More data to read from the file, submit another read
client.buffer.clearRetainingCapacity();
if (client.registered_fd) |registered_fd| {
var sqe = try self.submitRead(client, registered_fd, 0, onReadResponseFile);
sqe.flags |= os.linux.IOSQE_FIXED_FILE;
} else {
_ = try self.submitRead(client, client.response_state.file.fd, 0, onReadResponseFile);
}
return;
}
logger.debug("ctx#{s:<4} addr={s} ON WRITE RESPONSE FILE done", .{
self.user_context,
client.peer.addr,
});
// Response file written, read the next request
releaseRegisteredFileDescriptor(self, client);
// Close the response file descriptor
_ = try self.submitClose(client, client.response_state.file.fd, onCloseResponseFile);
client.response_state.file.fd = -1;
// Reset the client state
client.reset();
_ = try self.submitRead(client, client.fd, 0, onReadRequest);
}
fn onReadResponseFile(self: *Self, client: *ClientState, cqe: io_uring_cqe) !void {
debug.assert(client.buffer.items.len > 0);
switch (cqe.err()) {
.SUCCESS => {},
else => |err| {
logger.err("ctx#{s:<4} addr={s} ON READ RESPONSE FILE unexpected errno={}", .{ self.user_context, client.peer.addr, err });
return error.Unexpected;
},
}
if (cqe.res <= 0) {
return error.UnexpectedEOF;
}
const read = @intCast(usize, cqe.res);
logger.debug("ctx#{s:<4} addr={s} ON READ RESPONSE FILE read of {d} bytes from {d} succeeded", .{
self.user_context,
client.peer.addr,
read,
client.response_state.file.fd,
});
try client.buffer.appendSlice(client.temp_buffer[0..read]);
_ = try self.submitWrite(client, client.fd, 0, onWriteResponseFile);
}
fn onStatxResponseFile(self: *Self, client: *ClientState, cqe: io_uring_cqe) !void {
switch (cqe.err()) {
.SUCCESS => {
debug.assert(client.buffer.items.len == 0);
},
.CANCELED => {
return error.Canceled;
},
else => |err| {
logger.err("ctx#{s:<4} addr={s} ON STATX RESPONSE FILE unexpected errno={}", .{ self.user_context, client.peer.addr, err });
return error.Unexpected;
},
}
logger.debug("ctx#{s:<4} addr={s} ON STATX RESPONSE FILE path=\"{s}\" fd={}, size={s}", .{
self.user_context,
client.peer.addr,
client.response_state.file.path,
client.response_state.file.fd,
fmt.fmtIntSizeBin(client.response_state.file.statx_buf.size),
});
// Prepare the preambule + headers.
// This will be written to the socket on the next write operation following
// the first read operation for this file.
client.response_state.status_code = .ok;
try client.writeResponsePreambule(client.response_state.file.statx_buf.size);
// Now read the response file
if (client.registered_fd) |registered_fd| {
var sqe = try self.submitRead(client, registered_fd, 0, onReadResponseFile);
sqe.flags |= os.linux.IOSQE_FIXED_FILE;
} else {
_ = try self.submitRead(client, client.response_state.file.fd, 0, onReadResponseFile);
}
}
fn onReadBody(self: *Self, client: *ClientState, cqe: io_uring_cqe) !void {
assert(client.request_state.content_length != null);
assert(client.request_state.body != null);
switch (cqe.err()) {
.SUCCESS => {},
.PIPE => {
logger.err("ctx#{s:<4} addr={s} broken pipe", .{ self.user_context, client.peer.addr });
return error.BrokenPipe;
},
.CONNRESET => {
logger.err("ctx#{s:<4} addr={s} connection reset by peer", .{ self.user_context, client.peer.addr });
return error.ConnectionResetByPeer;
},
else => |err| {
logger.err("ctx#{s:<4} addr={s} unexpected errno={}", .{ self.user_context, client.peer.addr, err });
return error.Unexpected;
},
}
if (cqe.res <= 0) {
return error.UnexpectedEOF;
}
const read = @intCast(usize, cqe.res);
logger.debug("ctx#{s:<4} addr={s} ON READ BODY read of {d} bytes succeeded", .{ self.user_context, client.peer.addr, read });
try client.buffer.appendSlice(client.temp_buffer[0..read]);
client.refreshBody();
const content_length = client.request_state.content_length.?;
const body = client.request_state.body.?;
if (body.len < content_length) {
logger.debug("ctx#{s:<4} addr={s} buffer len={d} bytes, content length={d} bytes", .{
self.user_context,
client.peer.addr,
body.len,
content_length,
});
// Not enough data, read more.
_ = try self.submitRead(client, client.fd, 0, onReadBody);
return;
}
// Request is complete: call handler
try self.callHandler(client);
}
fn onOpenResponseFile(self: *Self, client: *ClientState, cqe: io_uring_cqe) !void {
debug.assert(client.buffer.items.len == 0);
switch (cqe.err()) {
.SUCCESS => {},
.NOENT => {
client.temp_buffer_fba.reset();
logger.warn("ctx#{s:<4} addr={s} no such file or directory, path=\"{s}\"", .{
self.user_context,
client.peer.addr,
fmt.fmtSliceEscapeLower(client.response_state.file.path),
});
try self.submitWriteNotFound(client);
return;
},
else => |err| {
logger.err("ctx#{s:<4} addr={s} unexpected errno={}", .{ self.user_context, client.peer.addr, err });
return error.Unexpected;
},
}
client.response_state.file.fd = @intCast(os.fd_t, cqe.res);
logger.debug("ctx#{s:<4} addr={s} ON OPEN RESPONSE FILE fd={}", .{ self.user_context, client.peer.addr, client.response_state.file.fd });
client.temp_buffer_fba.reset();
// Try to acquire a registered file descriptor.
// NOTE(vincent): constantly updating the registered file descriptors crashes the kernel
// client.registered_fd = self.registered_fds.acquire(client.response_state.file.fd);
// if (client.registered_fd != null) {
// try self.registered_fds.update(self.ring);
// }
}
fn releaseRegisteredFileDescriptor(self: *Self, client: *ClientState) void {
if (client.registered_fd) |registered_fd| {
self.registered_fds.release(registered_fd);
self.registered_fds.update(&self.ring) catch |err| {
logger.err("ctx#{s:<4} unable to update registered file descriptors, err={}", .{
self.user_context,
err,
});
};
client.registered_fd = null;
}
}
fn callHandler(self: *Self, client: *ClientState) !void {
// Create a request for the handler.
// This doesn't own any data and it only lives for the duration of this function call.
const req = try Request.create(
client.request_state.parse_result.raw_request,
client.request_state.body,
);
// Call the user provided handler to get a response.
const response = try self.handler(
self.user_context,
client.gpa,
client.peer,
req,
);
// TODO(vincent): cleanup in case of errors ?
// errdefer client.reset();
// At this point the request data is no longer needed so we can clear the buffer.
client.buffer.clearRetainingCapacity();
// Process the response:
// * `response` contains a simple buffer that we can write to the socket straight away.
// * `send_file` contains a file path that we need to open and statx before we can read/write it to the socket.
switch (response) {
.response => |res| {
client.response_state.status_code = res.status_code;
client.response_state.headers = res.headers;
try client.writeResponsePreambule(res.data.len);
try client.buffer.appendSlice(res.data);
_ = try self.submitWrite(client, client.fd, 0, onWriteResponseBuffer);
},
.send_file => |res| {
client.response_state.status_code = res.status_code;
client.response_state.headers = res.headers;
client.response_state.file.path = try client.temp_buffer_fba.allocator().dupeZ(u8, res.path);
var sqe = try self.submitOpenFile(
client,
client.response_state.file.path,
os.linux.O.RDONLY | os.linux.O.NOFOLLOW,
0644,
onOpenResponseFile,
);
sqe.flags |= os.linux.IOSQE_IO_LINK;
_ = try self.submitStatxFile(
client,
client.response_state.file.path,
os.linux.AT.SYMLINK_NOFOLLOW,
os.linux.STATX_SIZE,
&client.response_state.file.statx_buf,
onStatxResponseFile,
);
},
}
}
fn submitWriteNotFound(self: *Self, client: *ClientState) !void {
logger.debug("ctx#{s:<4} addr={s} returning 404 Not Found", .{
self.user_context,
client.peer.addr,
});
const static_response = "Not Found";
client.response_state.status_code = .not_found;
try client.writeResponsePreambule(static_response.len);
try client.buffer.appendSlice(static_response);
_ = try self.submitWrite(client, client.fd, 0, onWriteResponseBuffer);
}
fn processRequest(self: *Self, client: *ClientState) !void {
// Try to find the content length. If there's one we switch to reading the body.
const content_length = try client.request_state.parse_result.raw_request.getContentLength();
if (content_length) |n| {
logger.debug("ctx#{s:<4} addr={s} content length: {d}", .{ self.user_context, client.peer.addr, content_length });
client.request_state.content_length = n;
client.refreshBody();
if (client.request_state.body) |body| {
logger.debug("ctx#{s:<4} addr={s} body incomplete, usable={d} bytes, content length: {d} bytes", .{
self.user_context,
client.peer.addr,
body.len,
n,
});
_ = try self.submitRead(client, client.fd, 0, onReadBody);
return;
}
// Request is complete: call handler
try self.callHandler(client);
return;
}
// Otherwise it's a simple call to the handler.
try self.callHandler(client);
}
fn submitRead(self: *Self, client: *ClientState, fd: os.socket_t, offset: u64, comptime cb: anytype) !*io_uring_sqe {
logger.debug("ctx#{s:<4} addr={s} submitting read from {d}, offset {d}", .{
self.user_context,
client.peer.addr,
fd,
offset,
});
var tmp = try self.callbacks.get(cb, .{client});
return self.ring.read(
@ptrToInt(tmp),
fd,
&client.temp_buffer,
offset,
);
}
fn submitWrite(self: *Self, client: *ClientState, fd: os.fd_t, offset: u64, comptime cb: anytype) !*io_uring_sqe {
logger.debug("ctx#{s:<4} addr={s} submitting write of {s} to {d}, offset {d}, data=\"{s}\"", .{
self.user_context,
client.peer.addr,
fmt.fmtIntSizeBin(client.buffer.items.len),
fd,
offset,
fmt.fmtSliceEscapeLower(client.buffer.items),
});
var tmp = try self.callbacks.get(cb, .{client});
return self.ring.write(
@ptrToInt(tmp),
fd,
client.buffer.items,
offset,
);
}
fn submitOpenFile(self: *Self, client: *ClientState, path: [:0]const u8, flags: u32, mode: os.mode_t, comptime cb: anytype) !*io_uring_sqe {
logger.debug("ctx#{s:<4} addr={s} submitting open, path=\"{s}\"", .{
self.user_context,
client.peer.addr,
fmt.fmtSliceEscapeLower(path),
});
var tmp = try self.callbacks.get(cb, .{client});
return try self.ring.openat(
@ptrToInt(tmp),
os.linux.AT.FDCWD,
path,
flags,
mode,
);
}
fn submitStatxFile(self: *Self, client: *ClientState, path: [:0]const u8, flags: u32, mask: u32, buf: *os.linux.Statx, comptime cb: anytype) !*io_uring_sqe {
logger.debug("ctx#{s:<4} addr={s} submitting statx, path=\"{s}\"", .{
self.user_context,
client.peer.addr,
fmt.fmtSliceEscapeLower(path),
});
var tmp = try self.callbacks.get(cb, .{client});
return self.ring.statx(
@ptrToInt(tmp),
os.linux.AT.FDCWD,
path,
flags,
mask,
buf,
);
}
};
}
|
src/lib.zig
|
const build_options = @import("build_options");
const utils = @import("utils");
const georgios = @import("georgios");
const keyboard = georgios.keyboard;
const Key = keyboard.Key;
const Event = keyboard.Event;
const kernel = @import("root").kernel;
const print = kernel.print;
const key_to_char = kernel.keys.key_to_char;
const putil = @import("util.zig");
const interrupts = @import("interrupts.zig");
const segments = @import("segments.zig");
const scan_codes = @import("ps2_scan_codes.zig");
var modifiers = keyboard.Modifiers{};
var buffer = utils.CircularBuffer(Event, 128, .DiscardNewest){};
const intel8042 = struct {
const data_port: u16 = 0x60;
const command_status_port: u16 = 0x64;
pub fn get_kb_byte() callconv(.Inline) u8 {
return putil.in8(data_port);
}
};
/// Number of bytes into the current pattern.
var byte_count: u8 = 0;
const Pattern = enum {
TwoBytePrintScreen,
PrintScreenPressed,
PrintScreenReleased,
Pause,
};
/// Current multibyte patterns that are possible.
var pattern: Pattern = undefined;
pub fn keyboard_event_occured(
interrupt_number: u32, interrupt_stack: *const interrupts.Stack) void {
_ = interrupt_number;
_ = interrupt_stack;
var event: ?Event = null;
const byte = intel8042.get_kb_byte();
// print.format("[{:x}]", .{byte});
var reset = false;
switch (byte_count) {
0 => switch (byte) {
// Towards Two Bytes or PrintScreen
0xe0 => pattern = .TwoBytePrintScreen,
// Towards Pause
0xe1 => pattern = .Pause,
// Reached One Byte
else => {
const entry = scan_codes.one_byte[byte];
if (entry.key) |key| {
event = Event.new(key, entry.shifted_key, entry.kind.?, &modifiers);
}
reset = true;
},
},
1 => switch (pattern) {
.TwoBytePrintScreen => switch (byte) {
// Towards PrintScreen Pressed
0x2a => pattern = .PrintScreenPressed,
// Towards PrintScreen Released
0xb7 => pattern = .PrintScreenReleased,
// Reached Two Bytes
else => {
const entry = scan_codes.two_byte[byte];
if (entry.key) |key| {
event = Event.new(key, entry.shifted_key, entry.kind.?, &modifiers);
}
reset = true;
},
},
// Towards Pause
.Pause => reset = byte != 0x1d,
else => reset = true,
},
2 => switch (pattern) {
// Towards PrintScreen Pressed and Released
.PrintScreenPressed, .PrintScreenReleased => reset = byte != 0xe0,
// Towards Pause
.Pause => reset = byte != 0x45,
else => reset = true,
},
3 => switch (pattern) {
.PrintScreenPressed => {
if (byte == 0x37) {
// Reached PrintScreen Pressed
event = Event.new(.Key_PrintScreen, null, .Pressed, &modifiers);
}
reset = true;
},
.PrintScreenReleased => {
if (byte == 0xaa) {
// Reached PrintScreen Released
event = Event.new(.Key_PrintScreen, null, .Released, &modifiers);
}
reset = true;
},
// Towards Pause
.Pause => reset = byte != 0xe1,
else => reset = true,
},
4 => switch (pattern) {
// Towards Pause
.Pause => reset = byte != 0x9d,
else => reset = true,
},
5 => switch (pattern) {
// Towards Pause
.Pause => {
if (byte == 0xc5) {
// Reached Pause
event = Event.new(.Key_Pause, null, .Hit, &modifiers);
}
reset = true;
},
else => reset = true,
},
else => reset = true,
}
if (reset) {
byte_count = 0;
} else {
byte_count += 1;
}
if (event != null) {
const e = &event.?;
modifiers.update(e);
// print.format("<{}: {}>", .{@tagName(e.key), @tagName(e.kind)});
if (e.kind == .Pressed) {
if (key_to_char(e.key)) |c| {
e.char = c;
}
}
buffer.push(e.*);
kernel.threading_mgr.keyboard_event_occured();
}
}
pub fn get_key() ?Event {
putil.disable_interrupts();
defer putil.enable_interrupts();
return buffer.pop();
}
pub fn init() void {
interrupts.IrqInterruptHandler(1, keyboard_event_occured).set(
"IRQ1: Keyboard", segments.kernel_code_selector, interrupts.kernel_flags);
interrupts.load();
interrupts.pic.allow_irq(1, true);
}
pub fn anykey() void {
if (build_options.wait_for_anykey) {
while (true) {
if (get_key()) |key| {
if (key.kind == .Released) {
break;
}
}
}
}
}
|
kernel/platform/ps2.zig
|
const std = @import("std");
const states = @import("state.zig");
const Node = std.zig.ast.Node;
const Tree = std.zig.ast.Tree;
const State = states.State;
pub fn appendNamespace(
allocator: *std.mem.Allocator,
namespace: []const u8,
element: []const u8,
) ![]const u8 {
return try std.mem.join(allocator, ".", &[_][]const u8{ namespace, element });
}
/// Check if the right hand side of the declaration is an @import, and if it is
/// recurse build() into that file, with an updated namespace, etc.
fn recurseIfImport(
state: *State,
tree: *Tree,
namespace: []const u8,
decl: *Node.VarDecl,
init_node: *Node,
zig_src: []const u8,
) anyerror!void {
var builtin_call = @fieldParentPtr(Node.BuiltinCall, "base", init_node);
var call_tok = tree.tokenSlice(builtin_call.builtin_token);
var decl_name = tree.tokenSlice(decl.name_token);
// if the builtin call isnt @import, but its something else, e.g
// @intCast() or smth else, we add it as a node.
if (!std.mem.eql(u8, call_tok, "@import")) {
try state.addNode(tree, namespace, decl_name, decl.doc_comments);
return;
}
var it = builtin_call.params.iterator(0);
var arg1_ptrd = it.next().?;
// the builtin_call.params has *Node, and SegmentedList returns
// **Node... weird.
var arg1_node = arg1_ptrd.*;
if (arg1_node.id != .StringLiteral) return;
// here we properly extract the main argument of @import and do our
// big think moments until we reach proper arguments for build().
var arg1 = @fieldParentPtr(Node.StringLiteral, "base", arg1_node);
var token = tree.tokenSlice(arg1.token);
token = token[1 .. token.len - 1];
var ns = try appendNamespace(state.allocator, namespace, decl_name);
var dirname = std.fs.path.dirname(zig_src).?;
var basename = std.fs.path.basename(zig_src);
var name_it = std.mem.tokenize(basename, ".");
var name = name_it.next().?;
var path = try std.fs.path.join(
state.allocator,
&[_][]const u8{ dirname, token },
);
// the fallback to {dirname, name, token} exists since @import() calls
// can point to the relative path of the current file plus the file's name
// itself. take for example std.valgrind,
// that is currently at std/valgrind.zig.
// it contains @import("callgrind.zig"), but it isn't at std/callgrind.zig,
// but at std/valgrind/callgrind.zig
_ = std.fs.cwd().openFile(path, .{}) catch |err| {
if (err == error.FileNotFound) {
path = try std.fs.path.join(
state.allocator,
&[_][]const u8{ dirname, name, token },
);
} else {
return err;
}
};
try build(state, ns, path);
}
fn processStruct(
state: *State,
tree: *Tree,
namespace: []const u8,
fields_and_decls: *Node.Root.DeclList,
) !void {
// we are inside a struct, so we must iterate through its definitions.
var it = fields_and_decls.iterator(0);
while (it.next()) |node_ptr| {
var node = node_ptr.*;
switch (node.id) {
.ContainerField => blk: {
var field = @fieldParentPtr(Node.ContainerField, "base", node);
var field_name = tree.tokenSlice(field.name_token);
try state.addNode(tree, namespace, field_name, field.doc_comments);
},
.FnProto => blk: {
var proto = @fieldParentPtr(Node.FnProto, "base", node);
var fn_name = tree.tokenSlice(proto.name_token.?);
try state.addNode(tree, namespace, fn_name, proto.doc_comments);
},
else => continue,
}
}
}
/// Build the state map, given the current state, the namespace of the current
/// file, e.g "std.os", and the current source path. this function shall be
/// called first with the path to the root std.zig file, usually found at
/// $LIB/zig/std/std.zig.
pub fn build(
state: *State,
namespace: []const u8,
zig_src_path: []const u8,
) anyerror!void {
std.debug.warn("{} {}\n", .{ namespace, zig_src_path });
var file = try std.fs.cwd().openFile(zig_src_path, .{});
defer file.close();
const total_bytes = try file.getEndPos();
var data = try state.allocator.alloc(u8, total_bytes);
_ = try file.read(data);
var tree = try std.zig.parse(state.allocator, data);
defer tree.deinit();
var root = tree.root_node;
// evaluate that tree and go through it.
// the Tree is traversed in a simple manner:
// - if we find a public function, add it to the state
// - if we find a public var declaration on top level, we check the right
// hand side for an @import, if that's the case, we recurse into its
// definitions.
var idx: usize = 0;
while (root.iterate(idx)) |child| : (idx += 1) {
switch (child.id) {
.FnProto => blk: {
var proto = @fieldParentPtr(Node.FnProto, "base", child);
_ = proto.visib_token orelse continue;
var fn_name = tree.tokenSlice(proto.name_token.?);
try state.addNode(tree, namespace, fn_name, proto.doc_comments);
},
.VarDecl => blk: {
var decl = @fieldParentPtr(Node.VarDecl, "base", child);
_ = decl.visib_token orelse continue;
var init_node = decl.init_node.?;
var decl_name = tree.tokenSlice(decl.name_token);
switch (init_node.id) {
.BuiltinCall => try recurseIfImport(
state,
tree,
namespace,
decl,
init_node,
zig_src_path,
),
.ContainerDecl => blk: {
var con_decl = @fieldParentPtr(Node.ContainerDecl, "base", init_node);
var kind_token = tree.tokenSlice(con_decl.kind_token);
try state.addNode(tree, namespace, decl_name, decl.doc_comments);
if (std.mem.eql(u8, kind_token, "struct")) {
try processStruct(
state,
tree,
try appendNamespace(state.allocator, namespace, decl_name),
&con_decl.fields_and_decls,
);
} else {
try state.addNode(tree, namespace, decl_name, decl.doc_comments);
}
},
else => try state.addNode(tree, namespace, decl_name, decl.doc_comments),
}
},
else => continue,
}
}
}
|
src/build_map.zig
|
const std = @import("std");
const Allocator = std.mem.Allocator;
const Peer = @import("../Peer.zig");
const Handshake = @import("Handshake.zig");
const Message = @import("message.zig").Message;
const TcpClient = @This();
/// peer we are connected to
peer: Peer,
/// bit representation of the pieces we have
bitfield: ?Bitfield,
/// hash of meta info
hash: [20]u8,
/// unique id we represent ourselves with to our peer
id: [20]u8,
/// socket that handles our tcp connection and read/write from/to
socket: std.net.Stream,
/// determines if we are choked by the peer, this is true by default
choked: bool = true,
/// Bitfield represents a slice of bits that represents the pieces
/// that have already been downloaded. The struct contains helper methods
/// to check and set pieces.
const Bitfield = struct {
buffer: []u8,
/// hasPiece checks if the specified index contains a bit of 1
pub fn hasPiece(self: Bitfield, index: usize) bool {
var buffer = self.buffer;
const byte_index = index / 8;
const offset = index % 8;
if (byte_index < 0 or byte_index > buffer.len) return false;
return buffer[byte_index] >> (7 - @intCast(u3, offset)) & 1 != 0;
}
/// Sets a bit inside the bitfield to 1
pub fn setPiece(self: *Bitfield, index: usize) void {
//var buffer = self.buffer;
const byte_index = index / 8;
const offset = index % 8;
// if out of bounds, simply don't write the bit
if (byte_index >= 0 and byte_index < self.buffer.len) {
self.buffer[byte_index] |= @as(u8, 1) << (7 - @intCast(u3, offset));
}
}
};
/// initiates a new Client, to connect call connect()
pub fn init(peer: Peer, hash: [20]u8, peer_id: [20]u8) TcpClient {
return .{
.peer = peer,
.hash = hash,
.id = peer_id,
.socket = undefined,
.bitfield = null,
};
}
/// Creates a connection with the peer,
/// this fails if we cannot receive a proper handshake
pub fn connect(self: *TcpClient) !void {
self.socket = try std.net.tcpConnectToAddress(self.peer.address);
errdefer self.socket.close();
// initialize our handshake
try self.validateHandshake();
}
/// Sends a 'Request' message to the peer
pub fn sendRequest(self: TcpClient, index: u32, begin: u32, length: u32) !void {
try (Message{ .request = .{
.index = index,
.begin = begin,
.length = length,
} }).serialize(self.socket.writer());
}
/// Sends a message to the peer.
pub fn send(self: TcpClient, message: Message) !void {
try message.serialize(self.socket.writer());
}
/// Sends the 'Have' message to the peer indicating we have the piece
/// at given 'index'.
pub fn sendHave(self: TcpClient, index: u32) !void {
try (Message{ .have = index }).serialize(self.socket.writer());
}
/// Closes the connection and frees any memory that has been allocated
/// Use after calling `close()` is illegal behaviour.
pub fn close(self: *TcpClient, gpa: *Allocator) void {
self.socket.close();
if (self.bitfield) |bit_field| {
gpa.free(bit_field.buffer);
}
self.* = undefined;
}
/// Initiates and validates the handshake with the peer
/// This must be called first before sending anything else, calling it twice is illegal.
fn validateHandshake(self: TcpClient) !void {
const hand_shake: Handshake = .{
.hash = self.hash,
.peer_id = self.id,
};
try hand_shake.serialize(self.socket.writer());
const result = try Handshake.deserialize(self.socket.reader());
if (!std.mem.eql(u8, &self.hash, &result.hash)) return error.IncorrectHash;
}
|
src/net/Tcp_client.zig
|
const std = @import("std");
pub const TokenType = enum {
unknown,
multiply,
divide,
mod,
add,
subtract,
negate,
less,
less_equal,
greater,
greater_equal,
equal,
not_equal,
not,
assign,
bool_and,
bool_or,
left_paren,
right_paren,
left_brace,
right_brace,
semicolon,
comma,
kw_if,
kw_else,
kw_while,
kw_print,
kw_putc,
identifier,
integer,
string,
eof,
// More efficient implementation can be done with `std.enums.directEnumArray`.
pub fn toString(self: @This()) []const u8 {
return switch (self) {
.unknown => "UNKNOWN",
.multiply => "Op_multiply",
.divide => "Op_divide",
.mod => "Op_mod",
.add => "Op_add",
.subtract => "Op_subtract",
.negate => "Op_negate",
.less => "Op_less",
.less_equal => "Op_lessequal",
.greater => "Op_greater",
.greater_equal => "Op_greaterequal",
.equal => "Op_equal",
.not_equal => "Op_notequal",
.not => "Op_not",
.assign => "Op_assign",
.bool_and => "Op_and",
.bool_or => "Op_or",
.left_paren => "LeftParen",
.right_paren => "RightParen",
.left_brace => "LeftBrace",
.right_brace => "RightBrace",
.semicolon => "Semicolon",
.comma => "Comma",
.kw_if => "Keyword_if",
.kw_else => "Keyword_else",
.kw_while => "Keyword_while",
.kw_print => "Keyword_print",
.kw_putc => "Keyword_putc",
.identifier => "Identifier",
.integer => "Integer",
.string => "String",
.eof => "End_of_input",
};
}
};
pub const TokenValue = union(enum) {
intlit: i32,
string: []const u8,
};
pub const Token = struct {
line: usize,
col: usize,
typ: TokenType = .unknown,
value: ?TokenValue = null,
};
// Error conditions described in the task.
pub const LexerError = error{
EmptyCharacterConstant,
UnknownEscapeSequence,
MulticharacterConstant,
EndOfFileInComment,
EndOfFileInString,
EndOfLineInString,
UnrecognizedCharacter,
InvalidNumber,
};
pub const Lexer = struct {
content: []const u8,
line: usize,
col: usize,
offset: usize,
start: bool,
const Self = @This();
pub fn init(content: []const u8) Lexer {
return Lexer{
.content = content,
.line = 1,
.col = 1,
.offset = 0,
.start = true,
};
}
pub fn buildToken(self: Self) Token {
return Token{ .line = self.line, .col = self.col };
}
pub fn buildTokenT(self: Self, typ: TokenType) Token {
return Token{ .line = self.line, .col = self.col, .typ = typ };
}
pub fn curr(self: Self) u8 {
return self.content[self.offset];
}
// Alternative implementation is to return `Token` value from `next()` which is
// arguably more idiomatic version.
pub fn next(self: *Self) ?u8 {
// We use `start` in order to make the very first invocation of `next()` to return
// the very first character. It should be possible to avoid this variable.
if (self.start) {
self.start = false;
} else {
const newline = self.curr() == '\n';
self.offset += 1;
if (newline) {
self.col = 1;
self.line += 1;
} else {
self.col += 1;
}
}
if (self.offset >= self.content.len) {
return null;
} else {
return self.curr();
}
}
pub fn peek(self: Self) ?u8 {
if (self.offset + 1 >= self.content.len) {
return null;
} else {
return self.content[self.offset + 1];
}
}
fn divOrComment(self: *Self) LexerError!?Token {
var result = self.buildToken();
if (self.peek()) |peek_ch| {
if (peek_ch == '*') {
_ = self.next(); // peeked character
while (self.next()) |ch| {
if (ch == '*') {
if (self.peek()) |next_ch| {
if (next_ch == '/') {
_ = self.next(); // peeked character
return null;
}
}
}
}
return LexerError.EndOfFileInComment;
}
}
result.typ = .divide;
return result;
}
fn identifierOrKeyword(self: *Self) !Token {
var result = self.buildToken();
const init_offset = self.offset;
while (self.peek()) |ch| : (_ = self.next()) {
switch (ch) {
'_', 'a'...'z', 'A'...'Z', '0'...'9' => {},
else => break,
}
}
const final_offset = self.offset + 1;
if (std.mem.eql(u8, self.content[init_offset..final_offset], "if")) {
result.typ = .kw_if;
} else if (std.mem.eql(u8, self.content[init_offset..final_offset], "else")) {
result.typ = .kw_else;
} else if (std.mem.eql(u8, self.content[init_offset..final_offset], "while")) {
result.typ = .kw_while;
} else if (std.mem.eql(u8, self.content[init_offset..final_offset], "print")) {
result.typ = .kw_print;
} else if (std.mem.eql(u8, self.content[init_offset..final_offset], "putc")) {
result.typ = .kw_putc;
} else {
result.typ = .identifier;
result.value = TokenValue{ .string = self.content[init_offset..final_offset] };
}
return result;
}
fn string(self: *Self) !Token {
var result = self.buildToken();
result.typ = .string;
const init_offset = self.offset;
while (self.next()) |ch| {
switch (ch) {
'"' => break,
'\n' => return LexerError.EndOfLineInString,
'\\' => {
switch (self.peek() orelse return LexerError.EndOfFileInString) {
'n', '\\' => _ = self.next(), // peeked character
else => return LexerError.UnknownEscapeSequence,
}
},
else => {},
}
} else {
return LexerError.EndOfFileInString;
}
const final_offset = self.offset + 1;
result.value = TokenValue{ .string = self.content[init_offset..final_offset] };
return result;
}
/// Choose either `ifyes` or `ifno` token type depending on whether the peeked
/// character is `by`.
fn followed(self: *Self, by: u8, ifyes: TokenType, ifno: TokenType) Token {
var result = self.buildToken();
if (self.peek()) |ch| {
if (ch == by) {
_ = self.next(); // peeked character
result.typ = ifyes;
} else {
result.typ = ifno;
}
} else {
result.typ = ifno;
}
return result;
}
/// Raise an error if there's no next `by` character but return token with `typ` otherwise.
fn consecutive(self: *Self, by: u8, typ: TokenType) LexerError!Token {
const result = self.buildTokenT(typ);
if (self.peek()) |ch| {
if (ch == by) {
_ = self.next(); // peeked character
return result;
} else {
return LexerError.UnrecognizedCharacter;
}
} else {
return LexerError.UnrecognizedCharacter;
}
}
fn integerLiteral(self: *Self) LexerError!Token {
var result = self.buildTokenT(.integer);
const init_offset = self.offset;
while (self.peek()) |ch| {
switch (ch) {
'0'...'9' => _ = self.next(), // peeked character
'_', 'a'...'z', 'A'...'Z' => return LexerError.InvalidNumber,
else => break,
}
}
const final_offset = self.offset + 1;
result.value = TokenValue{
.intlit = std.fmt.parseInt(i32, self.content[init_offset..final_offset], 10) catch {
return LexerError.InvalidNumber;
},
};
return result;
}
// This is a beautiful way of how Zig allows to remove bilerplate and at the same time
// to not lose any error completeness guarantees.
fn nextOrEmpty(self: *Self) LexerError!u8 {
return self.next() orelse LexerError.EmptyCharacterConstant;
}
fn integerChar(self: *Self) LexerError!Token {
var result = self.buildTokenT(.integer);
switch (try self.nextOrEmpty()) {
'\'', '\n' => return LexerError.EmptyCharacterConstant,
'\\' => {
switch (try self.nextOrEmpty()) {
'n' => result.value = TokenValue{ .intlit = '\n' },
'\\' => result.value = TokenValue{ .intlit = '\\' },
else => return LexerError.EmptyCharacterConstant,
}
switch (try self.nextOrEmpty()) {
'\'' => {},
else => return LexerError.MulticharacterConstant,
}
},
else => {
result.value = TokenValue{ .intlit = self.curr() };
switch (try self.nextOrEmpty()) {
'\'' => {},
else => return LexerError.MulticharacterConstant,
}
},
}
return result;
}
};
pub fn lex(allocator: std.mem.Allocator, content: []u8) !std.ArrayList(Token) {
var tokens = std.ArrayList(Token).init(allocator);
var lexer = Lexer.init(content);
while (lexer.next()) |ch| {
switch (ch) {
' ' => {},
'*' => try tokens.append(lexer.buildTokenT(.multiply)),
'%' => try tokens.append(lexer.buildTokenT(.mod)),
'+' => try tokens.append(lexer.buildTokenT(.add)),
'-' => try tokens.append(lexer.buildTokenT(.subtract)),
'<' => try tokens.append(lexer.followed('=', .less_equal, .less)),
'>' => try tokens.append(lexer.followed('=', .greater_equal, .greater)),
'=' => try tokens.append(lexer.followed('=', .equal, .assign)),
'!' => try tokens.append(lexer.followed('=', .not_equal, .not)),
'(' => try tokens.append(lexer.buildTokenT(.left_paren)),
')' => try tokens.append(lexer.buildTokenT(.right_paren)),
'{' => try tokens.append(lexer.buildTokenT(.left_brace)),
'}' => try tokens.append(lexer.buildTokenT(.right_brace)),
';' => try tokens.append(lexer.buildTokenT(.semicolon)),
',' => try tokens.append(lexer.buildTokenT(.comma)),
'&' => try tokens.append(try lexer.consecutive('&', .bool_and)),
'|' => try tokens.append(try lexer.consecutive('|', .bool_or)),
'/' => {
if (try lexer.divOrComment()) |token| try tokens.append(token);
},
'_', 'a'...'z', 'A'...'Z' => try tokens.append(try lexer.identifierOrKeyword()),
'"' => try tokens.append(try lexer.string()),
'0'...'9' => try tokens.append(try lexer.integerLiteral()),
'\'' => try tokens.append(try lexer.integerChar()),
else => {},
}
}
try tokens.append(lexer.buildTokenT(.eof));
return tokens;
}
pub fn main() !void {
var arena = std.heap.ArenaAllocator.init(std.heap.page_allocator);
defer arena.deinit();
const allocator = arena.allocator();
var arg_it = std.process.args();
_ = try arg_it.next(allocator) orelse unreachable; // program name
const file_name = arg_it.next(allocator);
// We accept both files and standard input.
var file_handle = blk: {
if (file_name) |file_name_delimited| {
const fname: []const u8 = try file_name_delimited;
break :blk try std.fs.cwd().openFile(fname, .{});
} else {
break :blk std.io.getStdIn();
}
};
defer file_handle.close();
const input_content = try file_handle.readToEndAlloc(allocator, std.math.maxInt(usize));
const tokens = try lex(allocator, input_content);
const pretty_output = try tokenListToString(allocator, tokens);
_ = try std.io.getStdOut().write(pretty_output);
}
fn tokenListToString(allocator: std.mem.Allocator, token_list: std.ArrayList(Token)) ![]u8 {
var result = std.ArrayList(u8).init(allocator);
var w = result.writer();
for (token_list.items) |token| {
const common_args = .{ token.line, token.col, token.typ.toString() };
if (token.value) |value| {
const init_fmt = "{d:>5}{d:>7} {s:<15}";
switch (value) {
.string => |str| _ = try w.write(try std.fmt.allocPrint(
allocator,
init_fmt ++ "{s}\n",
common_args ++ .{str},
)),
.intlit => |i| _ = try w.write(try std.fmt.allocPrint(
allocator,
init_fmt ++ "{d}\n",
common_args ++ .{i},
)),
}
} else {
_ = try w.write(try std.fmt.allocPrint(allocator, "{d:>5}{d:>7} {s}\n", common_args));
}
}
return result.items;
}
const testing = std.testing;
test "tokenListToString" {
var arena = std.heap.ArenaAllocator.init(std.heap.page_allocator);
defer arena.deinit();
const allocator = arena.allocator();
const str: []const u8 = "\"Hello, World!\\n\"";
const tok_array = [6]Token{
Token{ .line = 4, .col = 1, .typ = .kw_print },
Token{ .line = 4, .col = 6, .typ = .left_paren },
Token{ .line = 4, .col = 7, .typ = .string, .value = TokenValue{ .string = str } },
Token{ .line = 4, .col = 24, .typ = .right_paren },
Token{ .line = 4, .col = 25, .typ = .semicolon },
Token{ .line = 5, .col = 1, .typ = .eof },
};
var token_list = std.ArrayList(Token).init(allocator);
(try token_list.addManyAsArray(6)).* = tok_array;
const expected =
\\ 4 1 Keyword_print
\\ 4 6 LeftParen
\\ 4 7 String "Hello, World!\n"
\\ 4 24 RightParen
\\ 4 25 Semicolon
\\ 5 1 End_of_input
\\
;
const result = try tokenListToString(allocator, token_list);
try testing.expectFmt(expected, "{s}", .{result});
}
test "lexer" {
const test_str =
\\abc
\\de
;
var lexer = Lexer.init(test_str);
try testing.expectEqual(@as(u8, 'a'), lexer.next().?);
try testing.expectEqual(@as(u8, 'b'), lexer.next().?);
try testing.expectEqual(@as(u8, 'b'), lexer.curr());
try testing.expectEqual(@as(u8, 'c'), lexer.peek().?);
try testing.expectEqual(@as(u8, 'c'), lexer.next().?);
try testing.expectEqual(@as(u8, '\n'), lexer.peek().?);
try testing.expectEqual(@as(u8, '\n'), lexer.next().?);
try testing.expectEqual(@as(u8, 'd'), lexer.next().?);
try testing.expectEqual(@as(u8, 'e'), lexer.next().?);
try testing.expect(null == lexer.next());
}
fn squishSpaces(allocator: std.mem.Allocator, str: []const u8) ![]u8 {
var result = std.ArrayList(u8).init(allocator);
var was_space = false;
for (str) |ch| {
switch (ch) {
' ' => {
if (!was_space) {
was_space = true;
try result.append(ch);
}
},
else => {
was_space = false;
try result.append(ch);
},
}
}
return result.items;
}
test "examples" {
var arena = std.heap.ArenaAllocator.init(std.heap.page_allocator);
defer arena.deinit();
const allocator = arena.allocator();
{
const example_input_path = "examples/input0.txt";
var file_input = try std.fs.cwd().openFile(example_input_path, std.fs.File.OpenFlags{});
defer std.fs.File.close(file_input);
const content_input = try std.fs.File.readToEndAlloc(file_input, allocator, std.math.maxInt(usize));
const example_output_path = "examples/lexed0.txt";
var file_output = try std.fs.cwd().openFile(example_output_path, std.fs.File.OpenFlags{});
defer std.fs.File.close(file_output);
const content_output = try std.fs.File.readToEndAlloc(file_output, allocator, std.math.maxInt(usize));
const tokens = try lex(allocator, content_input);
const pretty_output = try tokenListToString(allocator, tokens);
const stripped_expected = try squishSpaces(allocator, content_output);
const stripped_result = try squishSpaces(allocator, pretty_output);
try testing.expectFmt(stripped_expected, "{s}", .{stripped_result});
}
{
const example_input_path = "examples/input1.txt";
var file_input = try std.fs.cwd().openFile(example_input_path, std.fs.File.OpenFlags{});
defer std.fs.File.close(file_input);
const content_input = try std.fs.File.readToEndAlloc(file_input, allocator, std.math.maxInt(usize));
const example_output_path = "examples/lexed1.txt";
var file_output = try std.fs.cwd().openFile(example_output_path, std.fs.File.OpenFlags{});
defer std.fs.File.close(file_output);
const content_output = try std.fs.File.readToEndAlloc(file_output, allocator, std.math.maxInt(usize));
const tokens = try lex(allocator, content_input);
const pretty_output = try tokenListToString(allocator, tokens);
const stripped_expected = try squishSpaces(allocator, content_output);
const stripped_result = try squishSpaces(allocator, pretty_output);
try testing.expectFmt(stripped_expected, "{s}", .{stripped_result});
}
{
const example_input_path = "examples/input2.txt";
var file_input = try std.fs.cwd().openFile(example_input_path, std.fs.File.OpenFlags{});
defer std.fs.File.close(file_input);
const content_input = try std.fs.File.readToEndAlloc(file_input, allocator, std.math.maxInt(usize));
const example_output_path = "examples/lexed2.txt";
var file_output = try std.fs.cwd().openFile(example_output_path, std.fs.File.OpenFlags{});
defer std.fs.File.close(file_output);
const content_output = try std.fs.File.readToEndAlloc(file_output, allocator, std.math.maxInt(usize));
const tokens = try lex(allocator, content_input);
const pretty_output = try tokenListToString(allocator, tokens);
const stripped_expected = try squishSpaces(allocator, content_output);
const stripped_result = try squishSpaces(allocator, pretty_output);
try testing.expectFmt(stripped_expected, "{s}", .{stripped_result});
}
{
const example_input_path = "examples/input3.txt";
var file_input = try std.fs.cwd().openFile(example_input_path, std.fs.File.OpenFlags{});
defer std.fs.File.close(file_input);
const content_input = try std.fs.File.readToEndAlloc(file_input, allocator, std.math.maxInt(usize));
const example_output_path = "examples/lexed3.txt";
var file_output = try std.fs.cwd().openFile(example_output_path, std.fs.File.OpenFlags{});
defer std.fs.File.close(file_output);
const content_output = try std.fs.File.readToEndAlloc(file_output, allocator, std.math.maxInt(usize));
const tokens = try lex(allocator, content_input);
const pretty_output = try tokenListToString(allocator, tokens);
const stripped_expected = try squishSpaces(allocator, content_output);
const stripped_result = try squishSpaces(allocator, pretty_output);
try testing.expectFmt(stripped_expected, "{s}", .{stripped_result});
}
{
const example_input_path = "examples/input4.txt";
var file_input = try std.fs.cwd().openFile(example_input_path, std.fs.File.OpenFlags{});
defer std.fs.File.close(file_input);
const content_input = try std.fs.File.readToEndAlloc(file_input, allocator, std.math.maxInt(usize));
const example_output_path = "examples/lexed4.txt";
var file_output = try std.fs.cwd().openFile(example_output_path, std.fs.File.OpenFlags{});
defer std.fs.File.close(file_output);
const content_output = try std.fs.File.readToEndAlloc(file_output, allocator, std.math.maxInt(usize));
const tokens = try lex(allocator, content_input);
const pretty_output = try tokenListToString(allocator, tokens);
const stripped_expected = try squishSpaces(allocator, content_output);
const stripped_result = try squishSpaces(allocator, pretty_output);
try testing.expectFmt(stripped_expected, "{s}", .{stripped_result});
}
{
const example_input_path = "examples/input5.txt";
var file_input = try std.fs.cwd().openFile(example_input_path, std.fs.File.OpenFlags{});
defer std.fs.File.close(file_input);
const content_input = try std.fs.File.readToEndAlloc(file_input, allocator, std.math.maxInt(usize));
const example_output_path = "examples/lexed5.txt";
var file_output = try std.fs.cwd().openFile(example_output_path, std.fs.File.OpenFlags{});
defer std.fs.File.close(file_output);
const content_output = try std.fs.File.readToEndAlloc(file_output, allocator, std.math.maxInt(usize));
const tokens = try lex(allocator, content_input);
const pretty_output = try tokenListToString(allocator, tokens);
const stripped_expected = try squishSpaces(allocator, content_output);
const stripped_result = try squishSpaces(allocator, pretty_output);
try testing.expectFmt(stripped_expected, "{s}", .{stripped_result});
}
{
const example_input_path = "examples/input6.txt";
var file_input = try std.fs.cwd().openFile(example_input_path, std.fs.File.OpenFlags{});
defer std.fs.File.close(file_input);
const content_input = try std.fs.File.readToEndAlloc(file_input, allocator, std.math.maxInt(usize));
const example_output_path = "examples/lexed6.txt";
var file_output = try std.fs.cwd().openFile(example_output_path, std.fs.File.OpenFlags{});
defer std.fs.File.close(file_output);
const content_output = try std.fs.File.readToEndAlloc(file_output, allocator, std.math.maxInt(usize));
const tokens = try lex(allocator, content_input);
const pretty_output = try tokenListToString(allocator, tokens);
const stripped_expected = try squishSpaces(allocator, content_output);
const stripped_result = try squishSpaces(allocator, pretty_output);
try testing.expectFmt(stripped_expected, "{s}", .{stripped_result});
}
{
const example_input_path = "examples/input7.txt";
var file_input = try std.fs.cwd().openFile(example_input_path, std.fs.File.OpenFlags{});
defer std.fs.File.close(file_input);
const content_input = try std.fs.File.readToEndAlloc(file_input, allocator, std.math.maxInt(usize));
const example_output_path = "examples/lexed7.txt";
var file_output = try std.fs.cwd().openFile(example_output_path, std.fs.File.OpenFlags{});
defer std.fs.File.close(file_output);
const content_output = try std.fs.File.readToEndAlloc(file_output, allocator, std.math.maxInt(usize));
const tokens = try lex(allocator, content_input);
const pretty_output = try tokenListToString(allocator, tokens);
const stripped_expected = try squishSpaces(allocator, content_output);
const stripped_result = try squishSpaces(allocator, pretty_output);
try testing.expectFmt(stripped_expected, "{s}", .{stripped_result});
}
{
const example_input_path = "examples/input8.txt";
var file_input = try std.fs.cwd().openFile(example_input_path, std.fs.File.OpenFlags{});
defer std.fs.File.close(file_input);
const content_input = try std.fs.File.readToEndAlloc(file_input, allocator, std.math.maxInt(usize));
const example_output_path = "examples/lexed8.txt";
var file_output = try std.fs.cwd().openFile(example_output_path, std.fs.File.OpenFlags{});
defer std.fs.File.close(file_output);
const content_output = try std.fs.File.readToEndAlloc(file_output, allocator, std.math.maxInt(usize));
const tokens = try lex(allocator, content_input);
const pretty_output = try tokenListToString(allocator, tokens);
const stripped_expected = try squishSpaces(allocator, content_output);
const stripped_result = try squishSpaces(allocator, pretty_output);
try testing.expectFmt(stripped_expected, "{s}", .{stripped_result});
}
{
const example_input_path = "examples/input9.txt";
var file_input = try std.fs.cwd().openFile(example_input_path, std.fs.File.OpenFlags{});
defer std.fs.File.close(file_input);
const content_input = try std.fs.File.readToEndAlloc(file_input, allocator, std.math.maxInt(usize));
const example_output_path = "examples/lexed9.txt";
var file_output = try std.fs.cwd().openFile(example_output_path, std.fs.File.OpenFlags{});
defer std.fs.File.close(file_output);
const content_output = try std.fs.File.readToEndAlloc(file_output, allocator, std.math.maxInt(usize));
const tokens = try lex(allocator, content_input);
const pretty_output = try tokenListToString(allocator, tokens);
const stripped_expected = try squishSpaces(allocator, content_output);
const stripped_result = try squishSpaces(allocator, pretty_output);
try testing.expectFmt(stripped_expected, "{s}", .{stripped_result});
}
{
const example_input_path = "examples/input10.txt";
var file_input = try std.fs.cwd().openFile(example_input_path, std.fs.File.OpenFlags{});
defer std.fs.File.close(file_input);
const content_input = try std.fs.File.readToEndAlloc(file_input, allocator, std.math.maxInt(usize));
const example_output_path = "examples/lexed10.txt";
var file_output = try std.fs.cwd().openFile(example_output_path, std.fs.File.OpenFlags{});
defer std.fs.File.close(file_output);
const content_output = try std.fs.File.readToEndAlloc(file_output, allocator, std.math.maxInt(usize));
const tokens = try lex(allocator, content_input);
const pretty_output = try tokenListToString(allocator, tokens);
const stripped_expected = try squishSpaces(allocator, content_output);
const stripped_result = try squishSpaces(allocator, pretty_output);
try testing.expectFmt(stripped_expected, "{s}", .{stripped_result});
}
{
const example_input_path = "examples/input11.txt";
var file_input = try std.fs.cwd().openFile(example_input_path, std.fs.File.OpenFlags{});
defer std.fs.File.close(file_input);
const content_input = try std.fs.File.readToEndAlloc(file_input, allocator, std.math.maxInt(usize));
const example_output_path = "examples/lexed11.txt";
var file_output = try std.fs.cwd().openFile(example_output_path, std.fs.File.OpenFlags{});
defer std.fs.File.close(file_output);
const content_output = try std.fs.File.readToEndAlloc(file_output, allocator, std.math.maxInt(usize));
const tokens = try lex(allocator, content_input);
const pretty_output = try tokenListToString(allocator, tokens);
const stripped_expected = try squishSpaces(allocator, content_output);
const stripped_result = try squishSpaces(allocator, pretty_output);
try testing.expectFmt(stripped_expected, "{s}", .{stripped_result});
}
{
const example_input_path = "examples/input12.txt";
var file_input = try std.fs.cwd().openFile(example_input_path, std.fs.File.OpenFlags{});
defer std.fs.File.close(file_input);
const content_input = try std.fs.File.readToEndAlloc(file_input, allocator, std.math.maxInt(usize));
const example_output_path = "examples/lexed12.txt";
var file_output = try std.fs.cwd().openFile(example_output_path, std.fs.File.OpenFlags{});
defer std.fs.File.close(file_output);
const content_output = try std.fs.File.readToEndAlloc(file_output, allocator, std.math.maxInt(usize));
const tokens = try lex(allocator, content_input);
const pretty_output = try tokenListToString(allocator, tokens);
const stripped_expected = try squishSpaces(allocator, content_output);
const stripped_result = try squishSpaces(allocator, pretty_output);
try testing.expectFmt(stripped_expected, "{s}", .{stripped_result});
}
{
const example_input_path = "examples/input13.txt";
var file_input = try std.fs.cwd().openFile(example_input_path, std.fs.File.OpenFlags{});
defer std.fs.File.close(file_input);
const content_input = try std.fs.File.readToEndAlloc(file_input, allocator, std.math.maxInt(usize));
const example_output_path = "examples/lexed13.txt";
var file_output = try std.fs.cwd().openFile(example_output_path, std.fs.File.OpenFlags{});
defer std.fs.File.close(file_output);
const content_output = try std.fs.File.readToEndAlloc(file_output, allocator, std.math.maxInt(usize));
const tokens = try lex(allocator, content_input);
const pretty_output = try tokenListToString(allocator, tokens);
const stripped_expected = try squishSpaces(allocator, content_output);
const stripped_result = try squishSpaces(allocator, pretty_output);
try testing.expectFmt(stripped_expected, "{s}", .{stripped_result});
}
{
const example_input_path = "examples/input14.txt";
var file_input = try std.fs.cwd().openFile(example_input_path, std.fs.File.OpenFlags{});
defer std.fs.File.close(file_input);
const content_input = try std.fs.File.readToEndAlloc(file_input, allocator, std.math.maxInt(usize));
const example_output_path = "examples/lexed14.txt";
var file_output = try std.fs.cwd().openFile(example_output_path, std.fs.File.OpenFlags{});
defer std.fs.File.close(file_output);
const content_output = try std.fs.File.readToEndAlloc(file_output, allocator, std.math.maxInt(usize));
const tokens = try lex(allocator, content_input);
const pretty_output = try tokenListToString(allocator, tokens);
const stripped_expected = try squishSpaces(allocator, content_output);
const stripped_result = try squishSpaces(allocator, pretty_output);
try testing.expectFmt(stripped_expected, "{s}", .{stripped_result});
}
}
|
lexer.zig
|
usingnamespace @import("root").preamble;
const log = lib.output.log.scoped(.{
.prefix = "x86_64 Paging",
.filter = .info,
}).write;
const paging_common = @import("../paging.zig");
pub var page_sizes: []const usize = undefined;
const pages_4K = [_]usize{
0x1000, // 4K << 0
0x200000, // 4K << 9
0x40000000, // 4K << 18
0x8000000000, // 4K << 27
0x1000000000000, // 4K << 36
};
const pages_16K = [_]usize{
0x4000, // 16K << 0
0x2000000, // 16K << 11
0x1000000000, // 16K << 22
0x800000000000, // 16K << 33
0x400000000000000, // 16K << 44
};
const pages_64K = [_]usize{
0x10000, // 64K << 0
0x20000000, // 64K << 13
0x40000000000, // 64K << 26
0x80000000000000, // 64K << 39
};
const mair_index = u3;
fn MAIRContext() type {
const mair_encoding = u8;
const mair_value = u64;
const MAIR = os.platform.msr(mair_value, "MAIR_EL1");
// Current limitation: Outer = Inner and only non-transient
// Device nGnRnE
const device_uncacheable_encoding = 0b0000_00_00;
// Device GRE
const device_write_combining_encoding = 0b0000_11_00;
// Normal memory, inner and outer non-cacheable
const memory_uncacheable_encoding = 0b0100_0100;
// Normal memory inner and outer writethrough, non-transient
const memory_writethrough_encoding = 0b1011_1011;
// Normal memory, inner and outer write-back, non-transient
const memory_write_back_encoding = 0b1111_1111;
return struct {
// The value of the MAIR itself
value: mair_value,
// Cache the indices for each memory type
device_uncacheable: ?mair_index,
device_write_combining: ?mair_index,
memory_uncacheable: ?mair_index,
memory_writethrough: ?mair_index,
memory_write_back: ?mair_index,
pub fn init_from_mair_value(value: mair_value) @This() {
return .{
.value = value,
.device_uncacheable = find_mair_index(value, device_uncacheable_encoding),
.device_write_combining = find_mair_index(value, device_write_combining_encoding),
.memory_uncacheable = find_mair_index(value, memory_uncacheable_encoding),
.memory_writethrough = find_mair_index(value, memory_writethrough_encoding),
.memory_write_back = find_mair_index(value, memory_write_back_encoding),
};
}
fn encoding_at_index(value: mair_value, idx: mair_index) mair_encoding {
return @truncate(u8, value >> (@as(u6, idx) * 8));
}
fn memory_type_at_index(self: *const @This(), idx: mair_index) MemoryType {
const val = encoding_at_index(self.value, idx);
return switch (val) {
device_uncacheable_encoding => .DeviceUncacheable,
device_write_combining_encoding => .DeviceWriteCombining,
memory_uncacheable_encoding => .MemoryUncacheable,
memory_writethrough_encoding => .MemoryWritethrough,
memory_write_back_encoding => .MemoryWriteBack,
else => {
log(null, "Index: {d}, value = 0x{X}", .{ idx, val });
@panic("Unknown MAIR value!");
},
};
}
fn find_mair_index(pat: mair_value, enc: mair_encoding) ?mair_index {
var idx: mair_index = 0;
while (true) : (idx += 1) {
if (encoding_at_index(pat, idx) == enc)
return idx;
if (idx == 7)
return null;
}
}
pub fn find_memtype(self: *const @This(), memtype: MemoryType) ?mair_index {
var idx: mair_index = 0;
while (true) : (idx += 1) {
if (self.memory_type_at_index(idx) == memtype)
return idx;
if (idx == 7)
return null;
}
}
pub fn get_active() @This() {
return init_from_mair_value(MAIR.read());
}
pub fn make_default() @This() {
const default = comptime init_from_mair_value(0 | memory_write_back_encoding << 0 | device_write_combining_encoding << 8 | memory_writethrough_encoding << 16 | device_uncacheable_encoding << 24 | memory_uncacheable_encoding << 32);
return default;
}
};
}
const SCTLR = os.platform.msr(u64, "SCTLR_EL1");
const TCR = os.platform.msr(u64, "TCR_EL1");
const ID_AA64MMFR0 = os.platform.msr(u64, "ID_AA64MMFR0_EL1");
const Half = enum {
Upper,
Lower,
};
fn half(vaddr: u64) Half {
if (std.math.maxInt(u64) / 2 < vaddr)
return .Upper;
return .Lower;
}
const PageSizeContext = struct {
extrabits: u2,
pub fn get_active(h: Half, tcr: u64) @This() {
const val = switch (h) {
.Upper => @truncate(u5, tcr >> 16),
.Lower => @truncate(u5, tcr),
};
return switch (val) {
0 => .{ .extrabits = 2 },
8 => .{ .extrabits = 1 },
16 => .{ .extrabits = 0 },
else => @panic("Unknown paging mode!"),
};
}
pub fn offset_bits(self: *const @This()) u64 {
return switch (self.extrabits) {
0 => 16,
1 => 8,
2 => 0,
3 => @panic("3 extrabits??"),
};
}
pub fn granule(self: *const @This(), h: Half) u64 {
switch (self.extrabits) {
0 => if (h == .Upper) return 0b10 else return 0b00,
1 => if (h == .Upper) return 0b01 else return 0b10,
2 => if (h == .Upper) return 0b11 else return 0b01,
3 => @panic("3 extrabits??"),
}
}
pub fn make_default() @This() {
const id = ID_AA64MMFR0.read();
if (((id >> 28) & 0x0F) == 0b0000) return .{ .extrabits = 0 };
if (((id >> 20) & 0x0F) == 0b0001) return .{ .extrabits = 1 };
if (((id >> 24) & 0x0F) == 0b0000) return .{ .extrabits = 2 };
@panic("Cannot find valid page size");
}
pub fn basebits(self: *const @This()) u6 {
return 9 + @as(u6, self.extrabits) * 2;
}
pub fn firstbits(self: *const @This()) u6 {
// log2(@sizeOf(PTE)) = log2(8) = 3
return self.basebits() + 3;
}
pub fn page_size(self: *const @This(), level: u6) usize {
return @as(usize, 1) << self.firstbits() + self.basebits() * level;
}
};
const ttbr_value = u64;
const ttbr0 = os.platform.msr(ttbr_value, "TTBR0_EL1");
const ttbr1 = os.platform.msr(ttbr_value, "TTBR1_EL1");
const level_type = u3;
pub fn make_page_table() !u64 {
const pt = try os.memory.pmm.allocPhys(page_sizes[0]);
const pt_bytes = os.platform.phys_slice(u8).init(pt, page_sizes[0]);
@memset(pt_bytes.to_slice_writeback().ptr, 0x00, page_sizes[0]);
return pt;
}
var pszc: PageSizeContext = undefined;
pub fn init() void {
pszc = PageSizeContext.make_default();
switch (pszc.page_size(0)) {
0x1000 => {
page_sizes = pages_4K[0..];
},
0x4000 => {
page_sizes = pages_16K[0..];
},
0x10000 => {
page_sizes = pages_64K[0..];
},
else => unreachable,
}
}
pub fn page_size(level: u6) usize {
return pszc.page_size(level);
}
pub const PagingContext = struct {
mair: MAIRContext(),
br0: u64,
br1: u64,
wb_virt_base: u64 = undefined,
wc_virt_base: u64 = undefined,
uc_virt_base: u64 = undefined,
max_phys: u64 = undefined,
pub fn apply(self: *@This()) void {
var aa64mmfr0 = ID_AA64MMFR0.read();
aa64mmfr0 &= 0x0F;
if (aa64mmfr0 > 5)
aa64mmfr0 = 5;
// Make sure MMU is enabled
const sctlr: u64 = 0x100D;
// zig fmt: off
const tcr: u64 = 0 | pszc.offset_bits() // T0SZ
| pszc.offset_bits() << 16 // T1SZ
| (1 << 8) // TTBR0 Inner WB RW-Allocate
| (1 << 10) // TTBR0 Outer WB RW-Allocate
| (1 << 24) // TTBR1 Inner WB RW-Allocate
| (1 << 26) // TTBR1 Outer WB RW-Allocate
| (2 << 12) // TTBR0 Inner shareable
| (2 << 28) // TTBR1 Inner shareable
| (aa64mmfr0 << 32) // intermediate address size
| (pszc.granule(.Lower) << 14) // TTBR0 granule
| (pszc.granule(.Upper) << 30) // TTBR1 granule
| (1 << 56) // Fault on TTBR1 access from EL0
| (0 << 55) // Don't fault on TTBR0 access from EL0
;
// zig fmt: on
asm volatile (
// First, make sure we're not
// doing this on a page boundary
\\ .balign 0x20
\\ MSR TCR_EL1, %[tcr]
\\ MSR SCTLR_EL1, %[sctlr]
\\ MSR TTBR0_EL1, %[ttbr0]
\\ MSR TTBR1_EL1, %[ttbr1]
\\ MSR MAIR_EL1, %[mair]
\\ TLBI VMALLE1
\\ DSB ISH
\\ ISB
:
: [tcr] "r" (tcr),
[sctlr] "r" (sctlr),
[ttbr0] "r" (self.br0),
[ttbr1] "r" (self.br1),
[mair] "r" (self.mair.value)
);
}
pub fn read_current() void {
const tcr = TCR.read();
const curr = &os.memory.paging.kernel_context;
curr.mair = MAIRContext().get_active();
curr.br0 = ttbr0.read();
curr.br1 = ttbr1.read();
const upper = PageSizeContext.get_active(.Upper, tcr);
const lower = PageSizeContext.get_active(.Lower, tcr);
if (lower.basebits() != upper.basebits())
@panic("Cannot use different page sizes in upper/lower half!");
}
pub fn make_default() !@This() {
// 32TB ought to be enough for anyone...
const max_phys = 0x200000000000;
const curr_base = os.memory.paging.kernel_context.wb_virt_base;
return @This(){
.mair = MAIRContext().make_default(),
.br0 = try make_page_table(),
.br1 = try make_page_table(),
.wb_virt_base = curr_base,
.wc_virt_base = curr_base + max_phys,
.uc_virt_base = curr_base + max_phys * 2,
.max_phys = max_phys,
};
}
pub fn make_userspace() !@This() {
var result = os.memory.paging.kernel_context;
result.br0 = try make_page_table();
errdefer result.deinit();
return result;
}
pub fn deinit(self: *@This()) void {
log(.err, "TODO: PagingContext deinit", .{});
}
pub fn can_map_at_level(self: *const @This(), level: level_type) bool {
return page_sizes[level] < 0x1000000000;
}
pub fn check_phys(self: *const @This(), phys: u64) void {
if (comptime (std.debug.runtime_safety)) {
if (phys > self.max_phys) {
log(null, "Physaddr: 0x{X}", .{phys});
@panic("Physical address out of range");
}
}
}
pub fn physToWriteBackVirt(self: *const @This(), phys: u64) u64 {
self.check_phys(phys);
return self.wb_virt_base + phys;
}
pub fn physToWriteCombiningVirt(self: *const @This(), phys: u64) u64 {
self.check_phys(phys);
return self.wc_virt_base + phys;
}
pub fn physToUncachedVirt(self: *const @This(), phys: u64) u64 {
self.check_phys(phys);
return self.uc_virt_base + phys;
}
pub fn make_heap_base(self: *const @This()) u64 {
// Just after last physical memory mapping
return self.uc_virt_base + self.max_phys;
}
pub fn root_table(self: *@This(), virt: u64) TablePTE {
const h = half(virt);
return .{
.phys = if (h == .Lower) self.br0 else self.br1,
.curr_level = 4,
.context = self,
.perms = os.memory.paging.rwx(),
.underlying = null,
};
}
fn decode(self: *@This(), enc: *EncodedPTE, level: level_type) PTE {
var pte = PTEEncoding{ .raw = enc.* };
if (!pte.present.read())
return .Empty;
if (pte.walk.read() and level != 0)
return .{ .Table = self.decode_table(enc, level) };
return .{ .Mapping = self.decode_mapping(enc, level) };
}
fn decode_mapping(self: *@This(), enc: *EncodedPTE, level: level_type) MappingPTE {
const map = MappingEncoding{ .raw = enc.* };
const memtype: MemoryType = self.mair.memory_type_at_index(map.attr_index.read());
return .{
.context = self,
.phys = enc.* & phys_bitmask,
.level = level,
.memtype = memtype,
.underlying = @ptrCast(*MappingEncoding, enc),
.perms = .{
.writable = !map.no_write.read(),
.executable = !map.uxn_or_xn.read(),
.userspace = map.user.read(),
},
};
}
fn decode_table(self: *@This(), enc: *EncodedPTE, level: level_type) TablePTE {
const tbl = TableEncoding{ .raw = enc.* };
return .{
.context = self,
.phys = enc.* & phys_bitmask,
.curr_level = level,
.underlying = @ptrCast(*TableEncoding, enc),
.perms = .{
.writable = !tbl.no_write.read(),
.executable = !tbl.uxn_or_xn.read(),
.userspace = !tbl.no_user.read(),
},
};
}
pub fn encode_empty(self: *const @This(), level: level_type) EncodedPTE {
return 0;
}
pub fn encode_table(self: *const @This(), pte: TablePTE) !EncodedPTE {
var tbl = TableEncoding{ .raw = pte.phys };
tbl.present.write(true);
tbl.walk.write(true);
tbl.nonsecure.write(false);
tbl.no_write.write(!pte.perms.writable);
tbl.uxn_or_xn.write(!pte.perms.executable);
tbl.no_user.write(!pte.perms.userspace);
// We don't want to ever execute something userspace, and it's res0 if user is 0
tbl.pxn.write(pte.perms.userspace);
return tbl.raw;
}
pub fn encode_mapping(self: *const @This(), pte: MappingPTE) !EncodedPTE {
var map = MappingEncoding{ .raw = pte.phys };
map.present.write(true);
map.access.write(true);
map.nonsecure.write(false);
map.walk.write(pte.level == 0);
map.no_write.write(!pte.perms.writable);
map.uxn_or_xn.write(!pte.perms.executable);
map.user.write(pte.perms.userspace);
// We don't want to ever execute something userspace, and it's res0 if user is 0
map.pxn.write(pte.perms.userspace);
map.shareability.write(2);
const attr_idx = self.mair.find_memtype(pte.memtype.?) orelse @panic("Could not find MAIR index");
map.attr_index.write(attr_idx);
return map.raw;
}
pub fn domain(self: *const @This(), level: level_type, virtaddr: u64) os.platform.virt_slice {
return .{
.ptr = virtaddr & ~(page_sizes[level] - 1),
.len = page_sizes[level],
};
}
pub fn invalidate(self: *const @This(), virt: u64) void {
asm volatile (
\\TLBI VAE1, %[virt]
:
: [virt] "r" (virt >> pszc.basebits())
: "memory"
);
}
pub fn invalidateOtherCPUs(self: *const @This(), virt: usize, size: usize) void {
log(.err, "idfk we should probably invalidate tlbs here on other cpus, but I think we've just been played for absolute fools", .{});
}
};
pub const MemoryType = enum {
DeviceUncacheable,
DeviceWriteCombining,
MemoryUncacheable,
MemoryWritethrough,
MemoryWriteBack,
};
const phys_bitmask = 0x0000FFFFFFFFF000;
const bf = lib.util.bitfields;
const PTEEncoding = extern union {
raw: u64,
present: bf.Boolean(u64, 0),
walk: bf.Boolean(u64, 1),
};
const MappingEncoding = extern union {
raw: u64,
present: bf.Boolean(u64, 0),
walk: bf.Boolean(u64, 1),
attr_index: bf.Bitfield(u64, 2, 3),
nonsecure: bf.Boolean(u64, 5),
user: bf.Boolean(u64, 6),
no_write: bf.Boolean(u64, 7),
shareability: bf.Bitfield(u64, 8, 2),
access: bf.Boolean(u64, 10),
pxn: bf.Boolean(u64, 53),
uxn_or_xn: bf.Boolean(u64, 54),
};
const TableEncoding = extern union {
raw: u64,
present: bf.Boolean(u64, 0),
walk: bf.Boolean(u64, 1),
pxn: bf.Boolean(u64, 59),
uxn_or_xn: bf.Boolean(u64, 60),
no_user: bf.Boolean(u64, 61),
no_write: bf.Boolean(u64, 62),
nonsecure: bf.Boolean(u64, 63),
};
fn virt_index_at_level(vaddr: u64, level: u6) u9 {
const shamt = 12 + level * 9;
return @truncate(u9, (vaddr >> shamt));
}
const MappingPTE = struct {
phys: u64,
level: u3,
memtype: ?MemoryType,
context: *PagingContext,
perms: os.memory.paging.Perms,
underlying: *MappingEncoding,
pub fn mapped_bytes(self: *const @This()) os.platform.PhysBytes {
return .{
.ptr = self.phys,
.len = page_sizes[self.level],
};
}
pub fn get_type(self: *const @This()) ?MemoryType {
return self.memtype;
}
};
const EncodedPTE = u64;
const TablePTE = struct {
phys: u64,
curr_level: level_type,
context: *PagingContext,
perms: os.memory.paging.Perms,
underlying: ?*TableEncoding,
pub fn get_children(self: *const @This()) []EncodedPTE {
return os.platform.phys_slice(EncodedPTE).init(self.phys, 512).to_slice_writeback();
}
pub fn skip_to(self: *const @This(), virt: u64) []EncodedPTE {
return self.get_children()[virt_index_at_level(virt, self.curr_level - 1)..];
}
pub fn child_domain(self: *const @This(), virt: u64) os.platform.virt_slice {
return self.context.domain(self.curr_level - 1, virt);
}
pub fn decode_child(self: *const @This(), pte: *EncodedPTE) PTE {
return self.context.decode(pte, self.curr_level - 1);
}
pub fn level(self: *const @This()) level_type {
return self.curr_level;
}
pub fn addPerms(self: *const @This(), perms: os.memory.paging.Perms) void {
if (perms.executable)
self.underlying.?.uxn_or_xn.write(false);
if (perms.writable)
self.underlying.?.no_write.write(false);
if (perms.userspace)
self.underlying.?.no_user.write(false);
if (!perms.userspace and perms.executable)
self.underlying.?.pxn.write(false);
}
pub fn make_child_table(self: *const @This(), enc: *u64, perms: os.memory.paging.Perms) !TablePTE {
const pmem = try make_page_table();
errdefer os.memory.pmm.freePhys(pmem, page_sizes[0]);
var result: TablePTE = .{
.phys = pmem,
.context = self.context,
.curr_level = self.curr_level - 1,
.perms = perms,
.underlying = @ptrCast(*TableEncoding, enc),
};
enc.* = try self.context.encode_table(result);
return result;
}
pub fn make_child_mapping(
self: *const @This(),
enc: *u64,
phys: ?u64,
perms: os.memory.paging.Perms,
memtype: MemoryType,
) !MappingPTE {
const psz = page_sizes[self.level() - 1];
const pmem = phys orelse try os.memory.pmm.allocPhys(psz);
errdefer if (phys == null) os.memory.pmm.freePhys(pmem, psz);
var result: MappingPTE = .{
.level = self.level() - 1,
.memtype = memtype,
.context = self.context,
.perms = perms,
.underlying = @ptrCast(*MappingEncoding, enc),
.phys = pmem,
};
enc.* = try self.context.encode_mapping(result);
return result;
}
};
const EmptyPte = struct {};
pub const PTE = union(paging_common.PTEType) {
Mapping: MappingPTE,
Table: TablePTE,
Empty: EmptyPte,
};
|
subprojects/flork/src/platform/aarch64/paging.zig
|
const Builder = @import("std").build.Builder;
const Build = @import("std").build;
const Builtin = @import("std").builtin;
const Zig = @import("std").zig;
usingnamespace @import("libbuild.zig");
pub fn build(b: *Builder) void {
const target = b.standardTargetOptions(.{});
const mode = b.standardReleaseOptions();
const examples = b.option(bool, "examples", "Compile examples?") orelse false;
const tests = b.option(bool, "tests", "Compile tests?") orelse false;
const tools = b.option(bool, "tools", "Compile tools?") orelse false;
strip = b.option(bool, "strip", "Strip the exe?") orelse false;
var exe: *Build.LibExeObjStep = undefined;
var run_cmd: *Build.RunStep = undefined;
var run_step: *Build.Step = undefined;
const enginepath = "./";
const lib = buildEngine(b, target, mode, enginepath);
if (tests) {
exe = buildExe(b, target, mode, "src/tests/leaktest.zig", "test-leak", lib, enginepath);
exe = buildExe(b, target, mode, "src/tests/atlaspacker.zig", "test-atlaspacker", lib, enginepath);
exe = buildExe(b, target, mode, "src/tests/list.zig", "test-list", lib, enginepath);
exe = buildExe(b, target, mode, "src/tests/font.zig", "test-font", lib, enginepath);
}
if (tools) {
exe = buildExePrimitive(b, target, mode, "tools/assetpacker.zig", "tool-assetpacker", lib, enginepath);
}
if (examples) {
exe = buildExe(b, target, mode, "examples/ecs.zig", "ecs", lib, enginepath);
exe = buildExe(b, target, mode, "examples/pong.zig", "pong", lib, enginepath);
exe = buildExe(b, target, mode, "examples/packer.zig", "packer", lib, enginepath);
exe = buildExe(b, target, mode, "examples/collision.zig", "collision", lib, enginepath);
exe = buildExe(b, target, mode, "examples/simpleshooter.zig", "simpleshooter", lib, enginepath);
exe = buildExe(b, target, mode, "examples/shapedraw.zig", "shapedraw", lib, enginepath);
exe = buildExe(b, target, mode, "examples/textures.zig", "textures", lib, enginepath);
exe = buildExe(b, target, mode, "examples/flipbook.zig", "flipbook", lib, enginepath);
exe = buildExe(b, target, mode, "examples/particlesystem.zig", "particlesystem", lib, enginepath);
exe = buildExe(b, target, mode, "examples/custombatch.zig", "custombatch", lib, enginepath);
exe = buildExe(b, target, mode, "examples/logging.zig", "logging", lib, enginepath);
exe = buildExePrimitive(b, target, mode, "examples/primitive-simpleshooter.zig", "primitive-simpleshooter", lib, enginepath);
exe = buildExePrimitive(b, target, mode, "examples/primitive-window.zig", "primitive-window", lib, enginepath);
exe = buildExePrimitive(b, target, mode, "examples/primitive-renderer.zig", "primitive-renderer", lib, enginepath);
exe = buildExePrimitive(b, target, mode, "examples/primitive-triangle.zig", "primitive-triangle", lib, enginepath);
}
}
|
build.zig
|
const std = @import("std");
const Allocator = std.mem.Allocator;
const List = std.ArrayList;
const Map = std.AutoHashMap;
const StrMap = std.StringHashMap;
const BitSet = std.DynamicBitSet;
const Str = []const u8;
const util = @import("util.zig");
const gpa = util.gpa;
const data = @embedFile("../data/day05.txt");
const Coordinates = struct {
x: isize,
y: isize,
};
const Line = struct {
a: Coordinates,
b: Coordinates,
};
const VentMap = struct {
array: [1000][1000]usize = std.mem.zeroes([1000][1000]usize),
count: usize = 0,
pub fn mark(self: *VentMap, x: usize, y: usize) !void {
self.array[x][y] += 1;
if (self.array[x][y] == 2) self.count += 1;
}
};
pub fn main() !void {
var arena = std.heap.ArenaAllocator.init(gpa);
const allocator = arena.allocator();
var lines = blk: {
var arraylist = std.ArrayList(Line).init(allocator);
errdefer arraylist.deinit();
var lines_iter = tokenize(u8, data, "\n");
while (lines_iter.next()) |line_str| {
var coords_iter = tokenize(u8, line_str, " ->,");
try arraylist.append(Line{
.a = .{ .x = try parseInt(isize, coords_iter.next().?, 10), .y = try parseInt(isize, coords_iter.next().?, 10) },
.b = .{ .x = try parseInt(isize, coords_iter.next().?, 10), .y = try parseInt(isize, coords_iter.next().?, 10) },
});
}
break :blk arraylist.toOwnedSlice();
};
defer allocator.free(lines);
var map = VentMap{};
for (lines) |line| {
if (line.a.y == line.b.y) {
var x = line.a.x;
var end = line.b.x;
var i: i2 = if (x < end) 1 else -1;
while (x - i != end) : (x += i) {
try map.mark(@intCast(usize, x), @intCast(usize, line.a.y));
}
} else if (line.a.x == line.b.x) {
var y = line.a.y;
var end = line.b.y;
var i: i2 = if (y < end) 1 else -1;
while (y - i != end) : (y += i) {
try map.mark(@intCast(usize, line.a.x), @intCast(usize, y));
}
}
}
print("Part 1: {d}\n", .{map.count});
for (lines) |line| {
if (line.a.x != line.b.x and line.a.y != line.b.y) {
var x = line.a.x;
var end_x = line.b.x;
var x_i: i2 = if (x < end_x) 1 else -1;
var y = line.a.y;
var end_y = line.b.y;
var y_i: i2 = if (y < end_y) 1 else -1;
while (x - x_i != end_x) : ({
x += x_i;
y += y_i;
}) {
try map.mark(@intCast(usize, x), @intCast(usize, y));
}
}
}
print("Part 2: {d}\n", .{map.count});
}
// Useful stdlib functions
const tokenize = std.mem.tokenize;
const split = std.mem.split;
const indexOf = std.mem.indexOfScalar;
const indexOfAny = std.mem.indexOfAny;
const indexOfStr = std.mem.indexOfPosLinear;
const lastIndexOf = std.mem.lastIndexOfScalar;
const lastIndexOfAny = std.mem.lastIndexOfAny;
const lastIndexOfStr = std.mem.lastIndexOfLinear;
const trim = std.mem.trim;
const sliceMin = std.mem.min;
const sliceMax = std.mem.max;
const parseInt = std.fmt.parseInt;
const parseFloat = std.fmt.parseFloat;
const min = std.math.min;
const min3 = std.math.min3;
const max = std.math.max;
const max3 = std.math.max3;
const print = std.debug.print;
const assert = std.debug.assert;
const sort = std.sort.sort;
const asc = std.sort.asc;
const desc = std.sort.desc;
|
src/day05.zig
|
const std = @import("std");
pub fn Bitset(comptime S: type) type {
return struct {
const Self = @This();
pub const Elem = S;
pub const Bits = std.meta.IntType(false, @typeInfo(S).Enum.fields.len);
bits: Bits,
pub const empty = Self{ .bits = 0 };
pub fn singleton(elem: Elem) Self {
return .{ .bits = @as(Bits, 1) << @enumToInt(elem) };
}
pub fn init_with(comptime elements: anytype) Self {
var b = empty;
inline for (elements) |elem| {
b.set(@as(Elem, elem), true);
}
return b;
}
pub fn set(self: *Self, elem: Elem, val: bool) void {
if (val)
self.bits |= @as(Bits, 1) << @enumToInt(elem)
else
self.bits &= ~(@as(Bits, 1) << @enumToInt(elem));
}
pub fn get(self: *const Self, elem: Elem) bool {
return self.bits & (@as(Bits, 1) << @enumToInt(elem)) != 0;
}
pub fn toggle(self: *Self, elem: Elem) void {
self.bits ^= @as(Bits, 1) << @enumToInt(elem);
}
pub fn setAll(self: *Self, other: *const Self, val: bool) void {
if (val)
self.bits |= other.bits
else
self.bits &= ~other.bits;
}
pub fn any(self: *const Self, other: *const Self) bool {
return self.bits & other.bits != 0;
}
pub fn all(self: *const Self, other: *const Self) bool {
return self.bits & other.bits == other.bits;
}
};
}
const expect = std.testing.expect;
const expectEqual = std.testing.expectEqual;
const Tag = enum { One, Two, Three };
test "init_with" {
const TestSet = Bitset(Tag);
const some = TestSet.init_with(.{ .Three, .One });
const all = TestSet.init_with(.{ .One, .Two, .Three });
const empty = TestSet.init_with(.{});
expectEqual(some.bits, 0b101);
expectEqual(all.bits, 0b111);
expectEqual(empty.bits, 0b000);
}
test "single-element operations" {
const TestSet = Bitset(Tag);
var s = TestSet.empty;
s.set(.One, true);
expectEqual(s.bits, 0b001);
s.set(.Three, false);
expectEqual(s.bits, 0b001);
s.toggle(.Two);
expectEqual(s.bits, 0b011);
s.toggle(.One);
expectEqual(s.bits, 0b010);
expect(!s.get(.Three));
expect(s.get(.Two));
}
test "operations between sets" {
const TestSet = Bitset(Tag);
var s = TestSet.init_with(.{ .One, .Three });
const t = TestSet.init_with(.{ .Two, .Three });
s.setAll(&t, true);
expectEqual(s.bits, 0b111);
s.setAll(&t, false);
expectEqual(s.bits, 0b001);
}
|
src/util.zig
|
const std = @import("std");
const Image = @import("image.zig").Image;
const Allocator = std.mem.Allocator;
const BmpError = error {
InvalidHeader,
InvalidCompression,
UnsupportedFormat
};
pub fn read(allocator: *Allocator, reader: anytype, seekable: anytype) !Image {
const signature = try reader.readBytesNoEof(2);
if (!std.mem.eql(u8, &signature, "BM")) {
return BmpError.UnsupportedFormat;
}
const size = try reader.readIntLittle(u32);
_ = size;
_ = try reader.readBytesNoEof(4); // skip the reserved bytes
const offset = try reader.readIntLittle(u32);
const dibSize = try reader.readIntLittle(u32);
if (dibSize == 40 or dibSize == 108) { // BITMAPV4HEADER
const width = @intCast(usize, try reader.readIntLittle(i32));
const height = @intCast(usize, try reader.readIntLittle(i32));
const colorPlanes = try reader.readIntLittle(u16);
const bpp = try reader.readIntLittle(u16);
_ = colorPlanes;
const compression = try reader.readIntLittle(u32);
const imageSize = try reader.readIntLittle(u32);
const horzRes = try reader.readIntLittle(i32);
const vertRes = try reader.readIntLittle(i32);
const colorsNum = try reader.readIntLittle(u32);
const importantColors = try reader.readIntLittle(u32);
_ = compression; _ = imageSize; _ = horzRes; _ = vertRes; _ = colorsNum; _ = importantColors;
try seekable.seekTo(offset);
const imgReader = (std.io.BufferedReader(16*1024, @TypeOf(reader)) {
.unbuffered_reader = reader
}).reader(); // the input is only buffered now as when seeking the file, the buffer isn't emptied
const bytesPerPixel = @intCast(usize, bpp/8);
var data = try allocator.alloc(u8, @intCast(usize, width*height*bytesPerPixel));
var i: usize = height-1;
var j: usize = 0;
const bytesPerLine = width * bytesPerPixel;
if (bytesPerPixel == 1) {
const skipAhead: usize = @mod(width, 4);
while (i >= 0) {
j = 0;
while (j < width) {
const pos = j + i*bytesPerLine;
data[pos] = try imgReader.readByte();
j += 1;
}
try imgReader.skipBytes(skipAhead, .{});
if (i == 0) break;
i -= 1;
}
return Image {
.allocator = allocator, .data = data,
.width = width, .height = height,
.format = @import("image.zig").ImageFormat.GRAY8
};
} else if (bytesPerPixel == 3) {
const skipAhead: usize = @mod(width, 4);
while (i >= 0) {
const pos = i * bytesPerLine;
_ = try imgReader.readAll(data[pos..(pos+bytesPerLine)]);
try imgReader.skipBytes(skipAhead, .{});
if (i == 0) break;
i -= 1;
}
return Image {
.allocator = allocator, .data = data,
.width = width, .height = height,
.format = @import("image.zig").ImageFormat.BGR24
};
} else {
return BmpError.UnsupportedFormat;
}
} else {
return BmpError.InvalidHeader;
}
}
|
didot-image/bmp.zig
|
const internal = @import("./internal.zig");
const string = []const u8;
const Top = @This();
pub const Port = struct {
IP: ?string = null,
PrivatePort: i32,
PublicPort: ?i32 = null,
Type: enum {
tcp,
udp,
sctp,
},
};
pub const MountPoint = struct {
Type: string,
Name: string,
Source: string,
Destination: string,
Driver: string,
Mode: string,
RW: bool,
Propagation: string,
};
pub const DeviceMapping = struct {
PathOnHost: string,
PathInContainer: string,
CgroupPermissions: string,
};
pub const DeviceRequest = struct {
Driver: string,
Count: i32,
DeviceIDs: []const string,
Capabilities: []const []const string,
Options: struct {},
};
pub const ThrottleDevice = struct {
Path: string,
Rate: i32,
};
pub const Mount = struct {
Target: string,
Source: string,
Type: enum {
bind,
volume,
tmpfs,
npipe,
},
ReadOnly: bool,
Consistency: string,
BindOptions: struct {
Propagation: enum {
private,
rprivate,
shared,
rshared,
slave,
rslave,
},
NonRecursive: bool,
},
VolumeOptions: struct {
NoCopy: bool,
Labels: struct {},
DriverConfig: struct {
Name: string,
Options: struct {},
},
},
TmpfsOptions: struct {
SizeBytes: i32,
Mode: i32,
},
};
pub const RestartPolicy = struct {
Name: enum {
@"",
no,
always,
@"unless-stopped",
@"on-failure",
},
MaximumRetryCount: i32,
};
pub const Resources = struct {
CpuShares: i32,
Memory: i32,
CgroupParent: string,
BlkioWeight: i32,
BlkioWeightDevice: []const struct {
Path: string,
Weight: i32,
},
BlkioDeviceReadBps: []const ThrottleDevice,
BlkioDeviceWriteBps: []const ThrottleDevice,
BlkioDeviceReadIOps: []const ThrottleDevice,
BlkioDeviceWriteIOps: []const ThrottleDevice,
CpuPeriod: i32,
CpuQuota: i32,
CpuRealtimePeriod: i32,
CpuRealtimeRuntime: i32,
CpusetCpus: string,
CpusetMems: string,
Devices: []const DeviceMapping,
DeviceCgroupRules: []const string,
DeviceRequests: []const DeviceRequest,
KernelMemory: i32,
KernelMemoryTCP: i32,
MemoryReservation: i32,
MemorySwap: i32,
MemorySwappiness: i32,
NanoCpus: i32,
OomKillDisable: bool,
Init: bool,
PidsLimit: i32,
Ulimits: []const struct {
Name: string,
Soft: i32,
Hard: i32,
},
CpuCount: i32,
CpuPercent: i32,
IOMaximumIOps: i32,
IOMaximumBandwidth: i32,
};
pub const Limit = struct {
NanoCPUs: i32,
MemoryBytes: i32,
Pids: i32,
};
pub const ResourceObject = struct {
NanoCPUs: i32,
MemoryBytes: i32,
GenericResources: GenericResources,
};
pub const GenericResources = []const struct {
NamedResourceSpec: struct {
Kind: string,
Value: string,
},
DiscreteResourceSpec: struct {
Kind: string,
Value: i32,
},
};
pub const HealthConfig = struct {
Test: []const string,
Interval: i32,
Timeout: i32,
Retries: i32,
StartPeriod: i32,
};
pub const Health = struct {
Status: enum {
none,
starting,
healthy,
unhealthy,
},
FailingStreak: i32,
Log: []const HealthcheckResult,
};
pub const HealthcheckResult = struct {
Start: string,
End: string,
ExitCode: i32,
Output: string,
};
pub const HostConfig = internal.AllOf(&.{
Resources,
struct {
Binds: []const string,
ContainerIDFile: string,
LogConfig: struct {
Type: enum {
@"json-file",
syslog,
journald,
gelf,
fluentd,
awslogs,
splunk,
etwlogs,
none,
},
Config: struct {},
},
NetworkMode: string,
PortBindings: PortMap,
RestartPolicy: RestartPolicy,
AutoRemove: bool,
VolumeDriver: string,
VolumesFrom: []const string,
Mounts: []const Mount,
CapAdd: []const string,
CapDrop: []const string,
CgroupnsMode: enum {
private,
host,
},
Dns: []const string,
DnsOptions: []const string,
DnsSearch: []const string,
ExtraHosts: []const string,
GroupAdd: []const string,
IpcMode: string,
Cgroup: string,
Links: []const string,
OomScoreAdj: i32,
PidMode: string,
Privileged: bool,
PublishAllPorts: bool,
ReadonlyRootfs: bool,
SecurityOpt: []const string,
StorageOpt: struct {},
Tmpfs: struct {},
UTSMode: string,
UsernsMode: string,
ShmSize: i32,
Sysctls: struct {},
Runtime: string,
ConsoleSize: []const i32,
Isolation: enum {
default,
process,
hyperv,
},
MaskedPaths: []const string,
ReadonlyPaths: []const string,
},
});
pub const ContainerConfig = struct {
Hostname: string,
Domainname: string,
User: string,
AttachStdin: bool,
AttachStdout: bool,
AttachStderr: bool,
ExposedPorts: struct {},
Tty: bool,
OpenStdin: bool,
StdinOnce: bool,
Env: []const string,
Cmd: []const string,
Healthcheck: HealthConfig,
ArgsEscaped: bool,
Image: string,
Volumes: struct {},
WorkingDir: string,
Entrypoint: []const string,
NetworkDisabled: bool,
MacAddress: string,
OnBuild: []const string,
Labels: struct {},
StopSignal: string,
StopTimeout: i32,
Shell: []const string,
};
pub const NetworkingConfig = struct {
EndpointsConfig: struct {},
};
pub const NetworkSettings = struct {
Bridge: string,
SandboxID: string,
HairpinMode: bool,
LinkLocalIPv6Address: string,
LinkLocalIPv6PrefixLen: i32,
Ports: PortMap,
SandboxKey: string,
SecondaryIPAddresses: []const Address,
SecondaryIPv6Addresses: []const Address,
EndpointID: string,
Gateway: string,
GlobalIPv6Address: string,
GlobalIPv6PrefixLen: i32,
IPAddress: string,
IPPrefixLen: i32,
IPv6Gateway: string,
MacAddress: string,
Networks: struct {},
};
pub const Address = struct {
Addr: string,
PrefixLen: i32,
};
pub const PortMap = struct {};
pub const PortBinding = struct {
HostIp: string,
HostPort: string,
};
pub const GraphDriverData = struct {
Name: string,
Data: struct {},
};
pub const Image = struct {
Id: string,
RepoTags: ?[]const string = null,
RepoDigests: ?[]const string = null,
Parent: string,
Comment: string,
Created: string,
Container: string,
ContainerConfig: ?ContainerConfig = null,
DockerVersion: string,
Author: string,
Config: ?ContainerConfig = null,
Architecture: string,
Os: string,
OsVersion: ?string = null,
Size: i32,
VirtualSize: i32,
GraphDriver: GraphDriverData,
RootFS: struct {
Type: string,
Layers: ?[]const string = null,
BaseLayer: ?string = null,
},
Metadata: ?struct {
LastTagTime: string,
} = null,
};
pub const ImageSummary = struct {
Id: string,
ParentId: string,
RepoTags: []const string,
RepoDigests: []const string,
Created: i32,
Size: i32,
SharedSize: i32,
VirtualSize: i32,
Labels: struct {},
Containers: i32,
};
pub const AuthConfig = struct {
username: string,
password: string,
email: string,
serveraddress: string,
};
pub const ProcessConfig = struct {
privileged: bool,
user: string,
tty: bool,
entrypoint: string,
arguments: []const string,
};
pub const Volume = struct {
Name: string,
Driver: string,
Mountpoint: string,
CreatedAt: ?string = null,
Status: ?struct {} = null,
Labels: struct {},
Scope: enum {
local,
global,
},
Options: struct {},
UsageData: ?struct {
Size: i32,
RefCount: i32,
} = null,
};
pub const Network = struct {
Name: string,
Id: string,
Created: string,
Scope: string,
Driver: string,
EnableIPv6: bool,
IPAM: IPAM,
Internal: bool,
Attachable: bool,
Ingress: bool,
Containers: struct {},
Options: struct {},
Labels: struct {},
};
pub const IPAM = struct {
Driver: string,
Config: []const struct {},
Options: struct {},
};
pub const NetworkContainer = struct {
Name: string,
EndpointID: string,
MacAddress: string,
IPv4Address: string,
IPv6Address: string,
};
pub const BuildInfo = struct {
id: string,
stream: string,
@"error": string,
errorDetail: ErrorDetail,
status: string,
progress: string,
progressDetail: ProgressDetail,
aux: ImageID,
};
pub const BuildCache = struct {
ID: string,
Parent: string,
Type: string,
Description: string,
InUse: bool,
Shared: bool,
Size: i32,
CreatedAt: string,
LastUsedAt: string,
UsageCount: i32,
};
pub const ImageID = struct {
ID: string,
};
pub const CreateImageInfo = struct {
id: string,
@"error": string,
status: string,
progress: string,
progressDetail: ProgressDetail,
};
pub const PushImageInfo = struct {
@"error": string,
status: string,
progress: string,
progressDetail: ProgressDetail,
};
pub const ErrorDetail = struct {
code: i32,
message: string,
};
pub const ProgressDetail = struct {
current: i32,
total: i32,
};
pub const ErrorResponse = struct {
message: string,
};
pub const IdResponse = struct {
Id: string,
};
pub const EndpointSettings = struct {
IPAMConfig: EndpointIPAMConfig,
Links: []const string,
Aliases: []const string,
NetworkID: string,
EndpointID: string,
Gateway: string,
IPAddress: string,
IPPrefixLen: i32,
IPv6Gateway: string,
GlobalIPv6Address: string,
GlobalIPv6PrefixLen: i32,
MacAddress: string,
DriverOpts: struct {},
};
pub const EndpointIPAMConfig = struct {
IPv4Address: string,
IPv6Address: string,
LinkLocalIPs: []const string,
};
pub const PluginMount = struct {
Name: string,
Description: string,
Settable: []const string,
Source: string,
Destination: string,
Type: string,
Options: []const string,
};
pub const PluginDevice = struct {
Name: string,
Description: string,
Settable: []const string,
Path: string,
};
pub const PluginEnv = struct {
Name: string,
Description: string,
Settable: []const string,
Value: string,
};
pub const PluginInterfaceType = struct {
Prefix: string,
Capability: string,
Version: string,
};
pub const PluginPrivilege = struct {
Name: string,
Description: string,
Value: []const string,
};
pub const Plugin = struct {
Id: ?string = null,
Name: string,
Enabled: bool,
Settings: struct {
Mounts: []const PluginMount,
Env: []const string,
Args: []const string,
Devices: []const PluginDevice,
},
PluginReference: ?string = null,
Config: struct {
DockerVersion: ?string = null,
Description: string,
Documentation: string,
Interface: struct {
Types: []const PluginInterfaceType,
Socket: string,
ProtocolScheme: ?enum {
@"",
@"moby.plugins.http/v1",
} = null,
},
Entrypoint: []const string,
WorkDir: string,
User: ?struct {
UID: i32,
GID: i32,
} = null,
Network: struct {
Type: string,
},
Linux: struct {
Capabilities: []const string,
AllowAllDevices: bool,
Devices: []const PluginDevice,
},
PropagatedMount: string,
IpcHost: bool,
PidHost: bool,
Mounts: []const PluginMount,
Env: []const PluginEnv,
Args: struct {
Name: string,
Description: string,
Settable: []const string,
Value: []const string,
},
rootfs: ?struct {
type: string,
diff_ids: []const string,
} = null,
},
};
pub const ObjectVersion = struct {
Index: i32,
};
pub const NodeSpec = struct {
Name: string,
Labels: struct {},
Role: enum {
worker,
manager,
},
Availability: enum {
active,
pause,
drain,
},
};
pub const Node = struct {
ID: string,
Version: ObjectVersion,
CreatedAt: string,
UpdatedAt: string,
Spec: NodeSpec,
Description: NodeDescription,
Status: NodeStatus,
ManagerStatus: ManagerStatus,
};
pub const NodeDescription = struct {
Hostname: string,
Platform: Platform,
Resources: ResourceObject,
Engine: EngineDescription,
TLSInfo: TLSInfo,
};
pub const Platform = struct {
Architecture: string,
OS: string,
};
pub const EngineDescription = struct {
EngineVersion: string,
Labels: struct {},
Plugins: []const struct {
Type: string,
Name: string,
},
};
pub const TLSInfo = struct {
TrustRoot: string,
CertIssuerSubject: string,
CertIssuerPublicKey: string,
};
pub const NodeStatus = struct {
State: NodeState,
Message: string,
Addr: string,
};
pub const NodeState = enum {
unknown,
down,
ready,
disconnected,
};
pub const ManagerStatus = struct {
Leader: bool,
Reachability: Reachability,
Addr: string,
};
pub const Reachability = enum {
unknown,
@"unreachable",
reachable,
};
pub const SwarmSpec = struct {
Name: string,
Labels: struct {},
Orchestration: struct {
TaskHistoryRetentionLimit: i32,
},
Raft: struct {
SnapshotInterval: i32,
KeepOldSnapshots: i32,
LogEntriesForSlowFollowers: i32,
ElectionTick: i32,
HeartbeatTick: i32,
},
Dispatcher: struct {
HeartbeatPeriod: i32,
},
CAConfig: struct {
NodeCertExpiry: i32,
ExternalCAs: []const struct {
Protocol: enum {
cfssl,
},
URL: string,
Options: struct {},
CACert: string,
},
SigningCACert: string,
SigningCAKey: string,
ForceRotate: i32,
},
EncryptionConfig: struct {
AutoLockManagers: bool,
},
TaskDefaults: struct {
LogDriver: struct {
Name: string,
Options: struct {},
},
},
};
pub const ClusterInfo = struct {
ID: string,
Version: ObjectVersion,
CreatedAt: string,
UpdatedAt: string,
Spec: SwarmSpec,
TLSInfo: TLSInfo,
RootRotationInProgress: bool,
DataPathPort: i32,
DefaultAddrPool: []const string,
SubnetSize: i32,
};
pub const JoinTokens = struct {
Worker: string,
Manager: string,
};
pub const Swarm = internal.AllOf(&.{
ClusterInfo,
struct {
JoinTokens: JoinTokens,
},
});
pub const TaskSpec = struct {
PluginSpec: struct {
Name: string,
Remote: string,
Disabled: bool,
PluginPrivilege: []const PluginPrivilege,
},
ContainerSpec: struct {
Image: string,
Labels: struct {},
Command: []const string,
Args: []const string,
Hostname: string,
Env: []const string,
Dir: string,
User: string,
Groups: []const string,
Privileges: struct {
CredentialSpec: struct {
Config: string,
File: string,
Registry: string,
},
SELinuxContext: struct {
Disable: bool,
User: string,
Role: string,
Type: string,
Level: string,
},
},
TTY: bool,
OpenStdin: bool,
ReadOnly: bool,
Mounts: []const Mount,
StopSignal: string,
StopGracePeriod: i32,
HealthCheck: HealthConfig,
Hosts: []const string,
DNSConfig: struct {
Nameservers: []const string,
Search: []const string,
Options: []const string,
},
Secrets: []const struct {
File: struct {
Name: string,
UID: string,
GID: string,
Mode: i32,
},
SecretID: string,
SecretName: string,
},
Configs: []const struct {
File: struct {
Name: string,
UID: string,
GID: string,
Mode: i32,
},
Runtime: struct {},
ConfigID: string,
ConfigName: string,
},
Isolation: enum {
default,
process,
hyperv,
},
Init: bool,
Sysctls: struct {},
CapabilityAdd: []const string,
CapabilityDrop: []const string,
Ulimits: []const struct {
Name: string,
Soft: i32,
Hard: i32,
},
},
NetworkAttachmentSpec: struct {
ContainerID: string,
},
Resources: struct {
Limits: Limit,
Reservation: ResourceObject,
},
RestartPolicy: struct {
Condition: enum {
none,
@"on-failure",
any,
},
Delay: i32,
MaxAttempts: i32,
Window: i32,
},
Placement: struct {
Constraints: []const string,
Preferences: []const struct {
Spread: struct {
SpreadDescriptor: string,
},
},
MaxReplicas: i32,
Platforms: []const Platform,
},
ForceUpdate: i32,
Runtime: string,
Networks: []const NetworkAttachmentConfig,
LogDriver: struct {
Name: string,
Options: struct {},
},
};
pub const TaskState = enum {
new,
allocated,
pending,
assigned,
accepted,
preparing,
ready,
starting,
running,
complete,
shutdown,
failed,
rejected,
remove,
orphaned,
};
pub const Task = struct {
ID: string,
Version: ObjectVersion,
CreatedAt: string,
UpdatedAt: string,
Name: string,
Labels: struct {},
Spec: TaskSpec,
ServiceID: string,
Slot: i32,
NodeID: string,
AssignedGenericResources: GenericResources,
Status: struct {
Timestamp: string,
State: TaskState,
Message: string,
Err: string,
ContainerStatus: struct {
ContainerID: string,
PID: i32,
ExitCode: i32,
},
},
DesiredState: TaskState,
JobIteration: ObjectVersion,
};
pub const ServiceSpec = struct {
Name: string,
Labels: struct {},
TaskTemplate: TaskSpec,
Mode: struct {
Replicated: struct {
Replicas: i32,
},
Global: struct {},
ReplicatedJob: struct {
MaxConcurrent: i32,
TotalCompletions: i32,
},
GlobalJob: struct {},
},
UpdateConfig: struct {
Parallelism: i32,
Delay: i32,
FailureAction: enum {
@"continue",
pause,
rollback,
},
Monitor: i32,
MaxFailureRatio: f64,
Order: enum {
@"stop-first",
@"start-first",
},
},
RollbackConfig: struct {
Parallelism: i32,
Delay: i32,
FailureAction: enum {
@"continue",
pause,
},
Monitor: i32,
MaxFailureRatio: f64,
Order: enum {
@"stop-first",
@"start-first",
},
},
Networks: []const NetworkAttachmentConfig,
EndpointSpec: EndpointSpec,
};
pub const EndpointPortConfig = struct {
Name: string,
Protocol: enum {
tcp,
udp,
sctp,
},
TargetPort: i32,
PublishedPort: i32,
PublishMode: enum {
ingress,
host,
},
};
pub const EndpointSpec = struct {
Mode: enum {
vip,
dnsrr,
},
Ports: []const EndpointPortConfig,
};
pub const Service = struct {
ID: string,
Version: ObjectVersion,
CreatedAt: string,
UpdatedAt: string,
Spec: ServiceSpec,
Endpoint: struct {
Spec: EndpointSpec,
Ports: []const EndpointPortConfig,
VirtualIPs: []const struct {
NetworkID: string,
Addr: string,
},
},
UpdateStatus: struct {
State: enum {
updating,
paused,
completed,
},
StartedAt: string,
CompletedAt: string,
Message: string,
},
ServiceStatus: struct {
RunningTasks: i32,
DesiredTasks: i32,
CompletedTasks: i32,
},
JobStatus: struct {
JobIteration: ObjectVersion,
LastExecution: string,
},
};
pub const ImageDeleteResponseItem = struct {
Untagged: string,
Deleted: string,
};
pub const ServiceUpdateResponse = struct {
Warnings: []const string,
};
pub const ContainerSummary = struct {
Id: string,
Names: []const string,
Image: string,
ImageID: string,
Command: string,
Created: i32,
Ports: []const Port,
SizeRw: i32,
SizeRootFs: i32,
Labels: struct {},
State: string,
Status: string,
HostConfig: struct {
NetworkMode: string,
},
NetworkSettings: struct {
Networks: struct {},
},
Mounts: []const Mount,
};
pub const Driver = struct {
Name: string,
Options: ?struct {} = null,
};
pub const SecretSpec = struct {
Name: string,
Labels: struct {},
Data: string,
Driver: Driver,
Templating: Driver,
};
pub const Secret = struct {
ID: string,
Version: ObjectVersion,
CreatedAt: string,
UpdatedAt: string,
Spec: SecretSpec,
};
pub const ConfigSpec = struct {
Name: string,
Labels: struct {},
Data: string,
Templating: Driver,
};
pub const Config = struct {
ID: string,
Version: ObjectVersion,
CreatedAt: string,
UpdatedAt: string,
Spec: ConfigSpec,
};
pub const ContainerState = struct {
Status: enum {
created,
running,
paused,
restarting,
removing,
exited,
dead,
},
Running: bool,
Paused: bool,
Restarting: bool,
OOMKilled: bool,
Dead: bool,
Pid: i32,
ExitCode: i32,
Error: string,
StartedAt: string,
FinishedAt: string,
Health: Health,
};
pub const SystemVersion = struct {
Platform: struct {
Name: string,
},
Components: []const struct {
Name: string,
Version: string,
Details: ?struct {} = null,
},
Version: string,
ApiVersion: string,
MinAPIVersion: string,
GitCommit: string,
GoVersion: string,
Os: string,
Arch: string,
KernelVersion: string,
Experimental: bool,
BuildTime: string,
};
pub const SystemInfo = struct {
ID: string,
Containers: i32,
ContainersRunning: i32,
ContainersPaused: i32,
ContainersStopped: i32,
Images: i32,
Driver: string,
DriverStatus: []const []const string,
DockerRootDir: string,
Plugins: PluginsInfo,
MemoryLimit: bool,
SwapLimit: bool,
KernelMemory: bool,
CpuCfsPeriod: bool,
CpuCfsQuota: bool,
CPUShares: bool,
CPUSet: bool,
PidsLimit: bool,
OomKillDisable: bool,
IPv4Forwarding: bool,
BridgeNfIptables: bool,
BridgeNfIp6tables: bool,
Debug: bool,
NFd: i32,
NGoroutines: i32,
SystemTime: string,
LoggingDriver: string,
CgroupDriver: enum {
cgroupfs,
systemd,
none,
},
CgroupVersion: enum {
@"1",
@"2",
},
NEventsListener: i32,
KernelVersion: string,
OperatingSystem: string,
OSVersion: string,
OSType: string,
Architecture: string,
NCPU: i32,
MemTotal: i32,
IndexServerAddress: string,
RegistryConfig: RegistryServiceConfig,
GenericResources: GenericResources,
HttpProxy: string,
HttpsProxy: string,
NoProxy: string,
Name: string,
Labels: []const string,
ExperimentalBuild: bool,
ServerVersion: string,
ClusterStore: string,
ClusterAdvertise: string,
Runtimes: struct {},
DefaultRuntime: string,
Swarm: SwarmInfo,
LiveRestoreEnabled: bool,
Isolation: enum {
default,
hyperv,
process,
},
InitBinary: string,
ContainerdCommit: Commit,
RuncCommit: Commit,
InitCommit: Commit,
SecurityOptions: []const string,
ProductLicense: string,
DefaultAddressPools: []const struct {
Base: string,
Size: i32,
},
Warnings: []const string,
};
pub const PluginsInfo = struct {
Volume: []const string,
Network: []const string,
Authorization: []const string,
Log: []const string,
};
pub const RegistryServiceConfig = struct {
AllowNondistributableArtifactsCIDRs: []const string,
AllowNondistributableArtifactsHostnames: []const string,
InsecureRegistryCIDRs: []const string,
IndexConfigs: struct {},
Mirrors: []const string,
};
pub const IndexInfo = struct {
Name: string,
Mirrors: []const string,
Secure: bool,
Official: bool,
};
pub const Runtime = struct {
path: string,
runtimeArgs: []const string,
};
pub const Commit = struct {
ID: string,
Expected: string,
};
pub const SwarmInfo = struct {
NodeID: string,
NodeAddr: string,
LocalNodeState: LocalNodeState,
ControlAvailable: bool,
Error: string,
RemoteManagers: []const PeerNode,
Nodes: i32,
Managers: i32,
Cluster: ClusterInfo,
};
pub const LocalNodeState = enum {
@"",
inactive,
pending,
active,
@"error",
locked,
};
pub const PeerNode = struct {
NodeID: string,
Addr: string,
};
pub const NetworkAttachmentConfig = struct {
Target: string,
Aliases: []const string,
DriverOpts: struct {},
};
pub const EventActor = struct {
ID: string,
Attributes: struct {},
};
pub const EventMessage = struct {
Type: enum {
builder,
config,
container,
daemon,
image,
network,
node,
plugin,
secret,
service,
volume,
},
Action: string,
Actor: EventActor,
scope: enum {
local,
swarm,
},
time: i32,
timeNano: i32,
};
pub const OCIDescriptor = struct {
mediaType: string,
digest: string,
size: i32,
};
pub const OCIPlatform = struct {
architecture: string,
os: string,
@"os.version": string,
@"os.features": []const string,
variant: string,
};
pub const DistributionInspect = struct {
Descriptor: OCIDescriptor,
Platforms: []const OCIPlatform,
};
pub const @"/containers/json" = struct {
pub usingnamespace internal.Fn(
.get,
internal.name(Top, @This()),
void,
struct { all: bool = false, limit: i32, size: bool = false, filters: string },
void,
union(enum) {
@"200": []const ContainerSummary,
@"400": ErrorResponse,
@"500": ErrorResponse,
},
);
};
pub const @"/containers/create" = struct {
pub usingnamespace internal.Fn(
.post,
internal.name(Top, @This()),
void,
struct { name: string },
struct { body: internal.AllOf(&.{ ContainerConfig, struct { HostConfig: HostConfig, NetworkingConfig: NetworkingConfig } }) },
union(enum) {
@"201": struct { Id: string, Warnings: []const string },
@"400": ErrorResponse,
@"404": ErrorResponse,
@"409": ErrorResponse,
@"500": ErrorResponse,
},
);
};
pub const @"/containers/{id}/json" = struct {
pub usingnamespace internal.Fn(
.get,
internal.name(Top, @This()),
struct { id: string },
struct { size: bool = false },
void,
union(enum) {
@"200": struct { Id: string, Created: string, Path: string, Args: []const string, State: ContainerState, Image: string, ResolvConfPath: string, HostnamePath: string, HostsPath: string, LogPath: string, Name: string, RestartCount: i32, Driver: string, Platform: string, MountLabel: string, ProcessLabel: string, AppArmorProfile: string, ExecIDs: []const string, HostConfig: HostConfig, GraphDriver: GraphDriverData, SizeRw: i32, SizeRootFs: i32, Mounts: []const MountPoint, Config: ContainerConfig, NetworkSettings: NetworkSettings },
@"404": ErrorResponse,
@"500": ErrorResponse,
},
);
};
pub const @"/containers/{id}/top" = struct {
pub usingnamespace internal.Fn(
.get,
internal.name(Top, @This()),
struct { id: string },
struct { ps_args: string = "-ef" },
void,
union(enum) {
@"200": struct { Titles: []const string, Processes: []const []const string },
@"404": ErrorResponse,
@"500": ErrorResponse,
},
);
};
pub const @"/containers/{id}/logs" = struct {
pub usingnamespace internal.Fn(
.get,
internal.name(Top, @This()),
struct { id: string },
struct { follow: bool = false, stdout: bool = false, stderr: bool = false, since: i32 = 0, until: i32 = 0, timestamps: bool = false, tail: string = "all" },
void,
union(enum) {
@"200": string,
@"404": ErrorResponse,
@"500": ErrorResponse,
},
);
};
pub const @"/containers/{id}/changes" = struct {
pub usingnamespace internal.Fn(
.get,
internal.name(Top, @This()),
struct { id: string },
void,
void,
union(enum) {
@"200": []const struct { Path: string, Kind: i32 },
@"404": ErrorResponse,
@"500": ErrorResponse,
},
);
};
pub const @"/containers/{id}/export" = struct {
pub usingnamespace internal.Fn(
.get,
internal.name(Top, @This()),
struct { id: string },
void,
void,
union(enum) {
@"200": []const u8,
@"404": ErrorResponse,
@"500": ErrorResponse,
},
);
};
pub const @"/containers/{id}/stats" = struct {
pub usingnamespace internal.Fn(
.get,
internal.name(Top, @This()),
struct { id: string },
struct { stream: bool = true, @"one-shot": bool = false },
void,
union(enum) {
@"200": struct {},
@"404": ErrorResponse,
@"500": ErrorResponse,
},
);
};
pub const @"/containers/{id}/resize" = struct {
pub usingnamespace internal.Fn(
.post,
internal.name(Top, @This()),
struct { id: string },
struct { h: i32, w: i32 },
void,
union(enum) {
@"200": []const u8,
@"404": ErrorResponse,
@"500": ErrorResponse,
},
);
};
pub const @"/containers/{id}/start" = struct {
pub usingnamespace internal.Fn(
.post,
internal.name(Top, @This()),
struct { id: string },
struct { detachKeys: string },
void,
union(enum) {
@"204": void,
@"304": void,
@"404": ErrorResponse,
@"500": ErrorResponse,
},
);
};
pub const @"/containers/{id}/stop" = struct {
pub usingnamespace internal.Fn(
.post,
internal.name(Top, @This()),
struct { id: string },
struct { t: i32 },
void,
union(enum) {
@"204": void,
@"304": void,
@"404": ErrorResponse,
@"500": ErrorResponse,
},
);
};
pub const @"/containers/{id}/restart" = struct {
pub usingnamespace internal.Fn(
.post,
internal.name(Top, @This()),
struct { id: string },
struct { t: i32 },
void,
union(enum) {
@"204": void,
@"404": ErrorResponse,
@"500": ErrorResponse,
},
);
};
pub const @"/containers/{id}/kill" = struct {
pub usingnamespace internal.Fn(
.post,
internal.name(Top, @This()),
struct { id: string },
struct { signal: string = "SIGKILL" },
void,
union(enum) {
@"204": void,
@"404": ErrorResponse,
@"409": ErrorResponse,
@"500": ErrorResponse,
},
);
};
pub const @"/containers/{id}/update" = struct {
pub usingnamespace internal.Fn(
.post,
internal.name(Top, @This()),
struct { id: string },
void,
struct { update: internal.AllOf(&.{ Resources, struct { RestartPolicy: RestartPolicy } }) },
union(enum) {
@"200": struct { Warnings: []const string },
@"404": ErrorResponse,
@"500": ErrorResponse,
},
);
};
pub const @"/containers/{id}/rename" = struct {
pub usingnamespace internal.Fn(
.post,
internal.name(Top, @This()),
struct { id: string },
struct { name: string },
void,
union(enum) {
@"204": void,
@"404": ErrorResponse,
@"409": ErrorResponse,
@"500": ErrorResponse,
},
);
};
pub const @"/containers/{id}/pause" = struct {
pub usingnamespace internal.Fn(
.post,
internal.name(Top, @This()),
struct { id: string },
void,
void,
union(enum) {
@"204": void,
@"404": ErrorResponse,
@"500": ErrorResponse,
},
);
};
pub const @"/containers/{id}/unpause" = struct {
pub usingnamespace internal.Fn(
.post,
internal.name(Top, @This()),
struct { id: string },
void,
void,
union(enum) {
@"204": void,
@"404": ErrorResponse,
@"500": ErrorResponse,
},
);
};
pub const @"/containers/{id}/attach" = struct {
pub usingnamespace internal.Fn(
.post,
internal.name(Top, @This()),
struct { id: string },
struct { detachKeys: string, logs: bool = false, stream: bool = false, stdin: bool = false, stdout: bool = false, stderr: bool = false },
void,
union(enum) {
@"101": void,
@"200": void,
@"400": ErrorResponse,
@"404": ErrorResponse,
@"500": ErrorResponse,
},
);
};
pub const @"/containers/{id}/attach/ws" = struct {
pub usingnamespace internal.Fn(
.get,
internal.name(Top, @This()),
struct { id: string },
struct { detachKeys: string, logs: bool = false, stream: bool = false, stdin: bool = false, stdout: bool = false, stderr: bool = false },
void,
union(enum) {
@"101": void,
@"200": void,
@"400": ErrorResponse,
@"404": ErrorResponse,
@"500": ErrorResponse,
},
);
};
pub const @"/containers/{id}/wait" = struct {
pub usingnamespace internal.Fn(
.post,
internal.name(Top, @This()),
struct { id: string },
struct { condition: string = "not-running" },
void,
union(enum) {
@"200": struct { StatusCode: i32, Error: ?struct { Message: string } = null },
@"404": ErrorResponse,
@"500": ErrorResponse,
},
);
};
pub const @"/containers/{id}" = struct {
pub usingnamespace internal.Fn(
.delete,
internal.name(Top, @This()),
struct { id: string },
struct { v: bool = false, force: bool = false, link: bool = false },
void,
union(enum) {
@"204": void,
@"400": ErrorResponse,
@"404": ErrorResponse,
@"409": ErrorResponse,
@"500": ErrorResponse,
},
);
};
pub const @"/containers/{id}/archive" = struct {
pub usingnamespace internal.Fn(
.head,
internal.name(Top, @This()),
struct { id: string },
struct { path: string },
void,
union(enum) {
@"200": void,
@"400": ErrorResponse,
@"404": ErrorResponse,
@"500": ErrorResponse,
},
);
pub usingnamespace internal.Fn(
.get,
internal.name(Top, @This()),
struct { id: string },
struct { path: string },
void,
union(enum) {
@"200": void,
@"400": ErrorResponse,
@"404": ErrorResponse,
@"500": ErrorResponse,
},
);
pub usingnamespace internal.Fn(
.put,
internal.name(Top, @This()),
struct { id: string },
struct { path: string, noOverwriteDirNonDir: string, copyUIDGID: string },
struct { inputStream: string },
union(enum) {
@"200": void,
@"400": ErrorResponse,
@"403": ErrorResponse,
@"404": ErrorResponse,
@"500": ErrorResponse,
},
);
};
pub const @"/containers/prune" = struct {
pub usingnamespace internal.Fn(
.post,
internal.name(Top, @This()),
void,
struct { filters: string },
void,
union(enum) {
@"200": struct { ContainersDeleted: []const string, SpaceReclaimed: i32 },
@"500": ErrorResponse,
},
);
};
pub const @"/images/json" = struct {
pub usingnamespace internal.Fn(
.get,
internal.name(Top, @This()),
void,
struct { all: bool = false, filters: string, digests: bool = false },
void,
union(enum) {
@"200": []const ImageSummary,
@"500": ErrorResponse,
},
);
};
pub const @"/build" = struct {
pub usingnamespace internal.Fn(
.post,
internal.name(Top, @This()),
void,
struct { dockerfile: string = "Dockerfile", t: string, extrahosts: string, remote: string, q: bool = false, nocache: bool = false, cachefrom: string, pull: string, rm: bool = true, forcerm: bool = false, memory: i32, memswap: i32, cpushares: i32, cpusetcpus: string, cpuperiod: i32, cpuquota: i32, buildargs: string, shmsize: i32, squash: bool, labels: string, networkmode: string, platform: string = "", target: string = "", outputs: string = "" },
struct { inputStream: string },
union(enum) {
@"200": void,
@"400": ErrorResponse,
@"500": ErrorResponse,
},
);
};
pub const @"/build/prune" = struct {
pub usingnamespace internal.Fn(
.post,
internal.name(Top, @This()),
void,
struct { @"keep-storage": i32, all: bool, filters: string },
void,
union(enum) {
@"200": struct { CachesDeleted: []const string, SpaceReclaimed: i32 },
@"500": ErrorResponse,
},
);
};
pub const @"/images/create" = struct {
pub usingnamespace internal.Fn(
.post,
internal.name(Top, @This()),
void,
struct { fromImage: string, fromSrc: string, repo: string, tag: string, message: string, changes: []const string, platform: string = "" },
struct { inputImage: string },
union(enum) {
@"200": void,
@"404": ErrorResponse,
@"500": ErrorResponse,
},
);
};
pub const @"/images/{name}/json" = struct {
pub usingnamespace internal.Fn(
.get,
internal.name(Top, @This()),
struct { name: string },
void,
void,
union(enum) {
@"200": Image,
@"404": ErrorResponse,
@"500": ErrorResponse,
},
);
};
pub const @"/images/{name}/history" = struct {
pub usingnamespace internal.Fn(
.get,
internal.name(Top, @This()),
struct { name: string },
void,
void,
union(enum) {
@"200": []const struct { Id: string, Created: i32, CreatedBy: string, Tags: []const string, Size: i32, Comment: string },
@"404": ErrorResponse,
@"500": ErrorResponse,
},
);
};
pub const @"/images/{name}/push" = struct {
pub usingnamespace internal.Fn(
.post,
internal.name(Top, @This()),
struct { name: string },
struct { tag: string },
void,
union(enum) {
@"200": void,
@"404": ErrorResponse,
@"500": ErrorResponse,
},
);
};
pub const @"/images/{name}/tag" = struct {
pub usingnamespace internal.Fn(
.post,
internal.name(Top, @This()),
struct { name: string },
struct { repo: string, tag: string },
void,
union(enum) {
@"201": void,
@"400": ErrorResponse,
@"404": ErrorResponse,
@"409": ErrorResponse,
@"500": ErrorResponse,
},
);
};
pub const @"/images/{name}" = struct {
pub usingnamespace internal.Fn(
.delete,
internal.name(Top, @This()),
struct { name: string },
struct { force: bool = false, noprune: bool = false },
void,
union(enum) {
@"200": []const ImageDeleteResponseItem,
@"404": ErrorResponse,
@"409": ErrorResponse,
@"500": ErrorResponse,
},
);
};
pub const @"/images/search" = struct {
pub usingnamespace internal.Fn(
.get,
internal.name(Top, @This()),
void,
struct { term: string, limit: i32, filters: string },
void,
union(enum) {
@"200": []const struct { description: string, is_official: bool, is_automated: bool, name: string, star_count: i32 },
@"500": ErrorResponse,
},
);
};
pub const @"/images/prune" = struct {
pub usingnamespace internal.Fn(
.post,
internal.name(Top, @This()),
void,
struct { filters: string },
void,
union(enum) {
@"200": struct { ImagesDeleted: []const ImageDeleteResponseItem, SpaceReclaimed: i32 },
@"500": ErrorResponse,
},
);
};
pub const @"/auth" = struct {
pub usingnamespace internal.Fn(
.post,
internal.name(Top, @This()),
void,
void,
struct { authConfig: AuthConfig },
union(enum) {
@"200": struct { Status: string, IdentityToken: ?string = null },
@"204": void,
@"500": ErrorResponse,
},
);
};
pub const @"/info" = struct {
pub usingnamespace internal.Fn(
.get,
internal.name(Top, @This()),
void,
void,
void,
union(enum) {
@"200": SystemInfo,
@"500": ErrorResponse,
},
);
};
pub const @"/version" = struct {
pub usingnamespace internal.Fn(
.get,
internal.name(Top, @This()),
void,
void,
void,
union(enum) {
@"200": SystemVersion,
@"500": ErrorResponse,
},
);
};
pub const @"/_ping" = struct {
pub usingnamespace internal.Fn(
.get,
internal.name(Top, @This()),
void,
void,
void,
union(enum) {
@"200": string,
@"500": ErrorResponse,
},
);
pub usingnamespace internal.Fn(
.head,
internal.name(Top, @This()),
void,
void,
void,
union(enum) {
@"200": string,
@"500": ErrorResponse,
},
);
};
pub const @"/commit" = struct {
pub usingnamespace internal.Fn(
.post,
internal.name(Top, @This()),
void,
struct { container: string, repo: string, tag: string, comment: string, author: string, pause: bool = true, changes: string },
struct { containerConfig: ContainerConfig },
union(enum) {
@"201": IdResponse,
@"404": ErrorResponse,
@"500": ErrorResponse,
},
);
};
pub const @"/events" = struct {
pub usingnamespace internal.Fn(
.get,
internal.name(Top, @This()),
void,
struct { since: string, until: string, filters: string },
void,
union(enum) {
@"200": EventMessage,
@"400": ErrorResponse,
@"500": ErrorResponse,
},
);
};
pub const @"/system/df" = struct {
pub usingnamespace internal.Fn(
.get,
internal.name(Top, @This()),
void,
void,
void,
union(enum) {
@"200": struct { LayersSize: i32, Images: []const ImageSummary, Containers: []const ContainerSummary, Volumes: []const Volume, BuildCache: []const BuildCache },
@"500": ErrorResponse,
},
);
};
pub const @"/images/{name}/get" = struct {
pub usingnamespace internal.Fn(
.get,
internal.name(Top, @This()),
struct { name: string },
void,
void,
union(enum) {
@"200": string,
@"500": ErrorResponse,
},
);
};
pub const @"/images/get" = struct {
pub usingnamespace internal.Fn(
.get,
internal.name(Top, @This()),
void,
struct { names: []const string },
void,
union(enum) {
@"200": string,
@"500": ErrorResponse,
},
);
};
pub const @"/images/load" = struct {
pub usingnamespace internal.Fn(
.post,
internal.name(Top, @This()),
void,
struct { quiet: bool = false },
struct { imagesTarball: string },
union(enum) {
@"200": void,
@"500": ErrorResponse,
},
);
};
pub const @"/containers/{id}/exec" = struct {
pub usingnamespace internal.Fn(
.post,
internal.name(Top, @This()),
struct { id: string },
void,
struct { execConfig: struct { AttachStdin: bool, AttachStdout: bool, AttachStderr: bool, DetachKeys: string, Tty: bool, Env: []const string, Cmd: []const string, Privileged: bool, User: string, WorkingDir: string } },
union(enum) {
@"201": IdResponse,
@"404": ErrorResponse,
@"409": ErrorResponse,
@"500": ErrorResponse,
},
);
};
pub const @"/exec/{id}/start" = struct {
pub usingnamespace internal.Fn(
.post,
internal.name(Top, @This()),
struct { id: string },
void,
struct { execStartConfig: struct { Detach: bool, Tty: bool } },
union(enum) {
@"200": void,
@"404": ErrorResponse,
@"409": ErrorResponse,
},
);
};
pub const @"/exec/{id}/resize" = struct {
pub usingnamespace internal.Fn(
.post,
internal.name(Top, @This()),
struct { id: string },
struct { h: i32, w: i32 },
void,
union(enum) {
@"200": void,
@"400": ErrorResponse,
@"404": ErrorResponse,
@"500": ErrorResponse,
},
);
};
pub const @"/exec/{id}/json" = struct {
pub usingnamespace internal.Fn(
.get,
internal.name(Top, @This()),
struct { id: string },
void,
void,
union(enum) {
@"200": struct { CanRemove: bool, DetachKeys: string, ID: string, Running: bool, ExitCode: i32, ProcessConfig: ProcessConfig, OpenStdin: bool, OpenStderr: bool, OpenStdout: bool, ContainerID: string, Pid: i32 },
@"404": ErrorResponse,
@"500": ErrorResponse,
},
);
};
pub const @"/volumes" = struct {
pub usingnamespace internal.Fn(
.get,
internal.name(Top, @This()),
void,
struct { filters: string },
void,
union(enum) {
@"200": struct { Volumes: []const Volume, Warnings: []const string },
@"500": ErrorResponse,
},
);
};
pub const @"/volumes/create" = struct {
pub usingnamespace internal.Fn(
.post,
internal.name(Top, @This()),
void,
void,
struct { volumeConfig: struct { Name: string, Driver: string, DriverOpts: struct {}, Labels: struct {} } },
union(enum) {
@"201": Volume,
@"500": ErrorResponse,
},
);
};
pub const @"/volumes/{name}" = struct {
pub usingnamespace internal.Fn(
.get,
internal.name(Top, @This()),
struct { name: string },
void,
void,
union(enum) {
@"200": Volume,
@"404": ErrorResponse,
@"500": ErrorResponse,
},
);
pub usingnamespace internal.Fn(
.delete,
internal.name(Top, @This()),
struct { name: string },
struct { force: bool = false },
void,
union(enum) {
@"204": void,
@"404": ErrorResponse,
@"409": ErrorResponse,
@"500": ErrorResponse,
},
);
};
pub const @"/volumes/prune" = struct {
pub usingnamespace internal.Fn(
.post,
internal.name(Top, @This()),
void,
struct { filters: string },
void,
union(enum) {
@"200": struct { VolumesDeleted: []const string, SpaceReclaimed: i32 },
@"500": ErrorResponse,
},
);
};
pub const @"/networks" = struct {
pub usingnamespace internal.Fn(
.get,
internal.name(Top, @This()),
void,
struct { filters: string },
void,
union(enum) {
@"200": []const Network,
@"500": ErrorResponse,
},
);
};
pub const @"/networks/{id}" = struct {
pub usingnamespace internal.Fn(
.get,
internal.name(Top, @This()),
struct { id: string },
struct { verbose: bool = false, scope: string },
void,
union(enum) {
@"200": Network,
@"404": ErrorResponse,
@"500": ErrorResponse,
},
);
pub usingnamespace internal.Fn(
.delete,
internal.name(Top, @This()),
struct { id: string },
void,
void,
union(enum) {
@"204": void,
@"403": ErrorResponse,
@"404": ErrorResponse,
@"500": ErrorResponse,
},
);
};
pub const @"/networks/create" = struct {
pub usingnamespace internal.Fn(
.post,
internal.name(Top, @This()),
void,
void,
struct { networkConfig: struct { Name: string, CheckDuplicate: ?bool = null, Driver: ?string = null, Internal: ?bool = null, Attachable: ?bool = null, Ingress: ?bool = null, IPAM: ?IPAM = null, EnableIPv6: ?bool = null, Options: ?struct {} = null, Labels: ?struct {} = null } },
union(enum) {
@"201": struct { Id: string, Warning: string },
@"403": ErrorResponse,
@"404": ErrorResponse,
@"500": ErrorResponse,
},
);
};
pub const @"/networks/{id}/connect" = struct {
pub usingnamespace internal.Fn(
.post,
internal.name(Top, @This()),
struct { id: string },
void,
struct { container: struct { Container: string, EndpointConfig: EndpointSettings } },
union(enum) {
@"200": void,
@"403": ErrorResponse,
@"404": ErrorResponse,
@"500": ErrorResponse,
},
);
};
pub const @"/networks/{id}/disconnect" = struct {
pub usingnamespace internal.Fn(
.post,
internal.name(Top, @This()),
struct { id: string },
void,
struct { container: struct { Container: string, Force: bool } },
union(enum) {
@"200": void,
@"403": ErrorResponse,
@"404": ErrorResponse,
@"500": ErrorResponse,
},
);
};
pub const @"/networks/prune" = struct {
pub usingnamespace internal.Fn(
.post,
internal.name(Top, @This()),
void,
struct { filters: string },
void,
union(enum) {
@"200": struct { NetworksDeleted: []const string },
@"500": ErrorResponse,
},
);
};
pub const @"/plugins" = struct {
pub usingnamespace internal.Fn(
.get,
internal.name(Top, @This()),
void,
struct { filters: string },
void,
union(enum) {
@"200": []const Plugin,
@"500": ErrorResponse,
},
);
};
pub const @"/plugins/privileges" = struct {
pub usingnamespace internal.Fn(
.get,
internal.name(Top, @This()),
void,
struct { remote: string },
void,
union(enum) {
@"200": []const PluginPrivilege,
@"500": ErrorResponse,
},
);
};
pub const @"/plugins/pull" = struct {
pub usingnamespace internal.Fn(
.post,
internal.name(Top, @This()),
void,
struct { remote: string, name: string },
struct { body: []const PluginPrivilege },
union(enum) {
@"204": void,
@"500": ErrorResponse,
},
);
};
pub const @"/plugins/{name}/json" = struct {
pub usingnamespace internal.Fn(
.get,
internal.name(Top, @This()),
struct { name: string },
void,
void,
union(enum) {
@"200": Plugin,
@"404": ErrorResponse,
@"500": ErrorResponse,
},
);
};
pub const @"/plugins/{name}" = struct {
pub usingnamespace internal.Fn(
.delete,
internal.name(Top, @This()),
struct { name: string },
struct { force: bool = false },
void,
union(enum) {
@"200": Plugin,
@"404": ErrorResponse,
@"500": ErrorResponse,
},
);
};
pub const @"/plugins/{name}/enable" = struct {
pub usingnamespace internal.Fn(
.post,
internal.name(Top, @This()),
struct { name: string },
struct { timeout: i32 = 0 },
void,
union(enum) {
@"200": void,
@"404": ErrorResponse,
@"500": ErrorResponse,
},
);
};
pub const @"/plugins/{name}/disable" = struct {
pub usingnamespace internal.Fn(
.post,
internal.name(Top, @This()),
struct { name: string },
void,
void,
union(enum) {
@"200": void,
@"404": ErrorResponse,
@"500": ErrorResponse,
},
);
};
pub const @"/plugins/{name}/upgrade" = struct {
pub usingnamespace internal.Fn(
.post,
internal.name(Top, @This()),
struct { name: string },
struct { remote: string },
struct { body: []const PluginPrivilege },
union(enum) {
@"204": void,
@"404": ErrorResponse,
@"500": ErrorResponse,
},
);
};
pub const @"/plugins/create" = struct {
pub usingnamespace internal.Fn(
.post,
internal.name(Top, @This()),
void,
struct { name: string },
struct { tarContext: string },
union(enum) {
@"204": void,
@"500": ErrorResponse,
},
);
};
pub const @"/plugins/{name}/push" = struct {
pub usingnamespace internal.Fn(
.post,
internal.name(Top, @This()),
struct { name: string },
void,
void,
union(enum) {
@"200": void,
@"404": ErrorResponse,
@"500": ErrorResponse,
},
);
};
pub const @"/plugins/{name}/set" = struct {
pub usingnamespace internal.Fn(
.post,
internal.name(Top, @This()),
struct { name: string },
void,
struct { body: []const string },
union(enum) {
@"204": void,
@"404": ErrorResponse,
@"500": ErrorResponse,
},
);
};
pub const @"/nodes" = struct {
pub usingnamespace internal.Fn(
.get,
internal.name(Top, @This()),
void,
struct { filters: string },
void,
union(enum) {
@"200": []const Node,
@"500": ErrorResponse,
@"503": ErrorResponse,
},
);
};
pub const @"/nodes/{id}" = struct {
pub usingnamespace internal.Fn(
.get,
internal.name(Top, @This()),
struct { id: string },
void,
void,
union(enum) {
@"200": Node,
@"404": ErrorResponse,
@"500": ErrorResponse,
@"503": ErrorResponse,
},
);
pub usingnamespace internal.Fn(
.delete,
internal.name(Top, @This()),
struct { id: string },
struct { force: bool = false },
void,
union(enum) {
@"200": void,
@"404": ErrorResponse,
@"500": ErrorResponse,
@"503": ErrorResponse,
},
);
};
pub const @"/nodes/{id}/update" = struct {
pub usingnamespace internal.Fn(
.post,
internal.name(Top, @This()),
struct { id: string },
struct { version: i32 },
struct { body: NodeSpec },
union(enum) {
@"200": void,
@"400": ErrorResponse,
@"404": ErrorResponse,
@"500": ErrorResponse,
@"503": ErrorResponse,
},
);
};
pub const @"/swarm" = struct {
pub usingnamespace internal.Fn(
.get,
internal.name(Top, @This()),
void,
void,
void,
union(enum) {
@"200": Swarm,
@"404": ErrorResponse,
@"500": ErrorResponse,
@"503": ErrorResponse,
},
);
};
pub const @"/swarm/init" = struct {
pub usingnamespace internal.Fn(
.post,
internal.name(Top, @This()),
void,
void,
struct { body: struct { ListenAddr: string, AdvertiseAddr: string, DataPathAddr: string, DataPathPort: i32, DefaultAddrPool: []const string, ForceNewCluster: bool, SubnetSize: i32, Spec: SwarmSpec } },
union(enum) {
@"200": string,
@"400": ErrorResponse,
@"500": ErrorResponse,
@"503": ErrorResponse,
},
);
};
pub const @"/swarm/join" = struct {
pub usingnamespace internal.Fn(
.post,
internal.name(Top, @This()),
void,
void,
struct { body: struct { ListenAddr: string, AdvertiseAddr: string, DataPathAddr: string, RemoteAddrs: []const string, JoinToken: string } },
union(enum) {
@"200": void,
@"400": ErrorResponse,
@"500": ErrorResponse,
@"503": ErrorResponse,
},
);
};
pub const @"/swarm/leave" = struct {
pub usingnamespace internal.Fn(
.post,
internal.name(Top, @This()),
void,
struct { force: bool = false },
void,
union(enum) {
@"200": void,
@"500": ErrorResponse,
@"503": ErrorResponse,
},
);
};
pub const @"/swarm/update" = struct {
pub usingnamespace internal.Fn(
.post,
internal.name(Top, @This()),
void,
struct { version: i32, rotateWorkerToken: bool = false, rotateManagerToken: bool = false, rotateManagerUnlockKey: bool = false },
struct { body: SwarmSpec },
union(enum) {
@"200": void,
@"400": ErrorResponse,
@"500": ErrorResponse,
@"503": ErrorResponse,
},
);
};
pub const @"/swarm/unlockkey" = struct {
pub usingnamespace internal.Fn(
.get,
internal.name(Top, @This()),
void,
void,
void,
union(enum) {
@"200": struct { UnlockKey: string },
@"500": ErrorResponse,
@"503": ErrorResponse,
},
);
};
pub const @"/swarm/unlock" = struct {
pub usingnamespace internal.Fn(
.post,
internal.name(Top, @This()),
void,
void,
struct { body: struct { UnlockKey: string } },
union(enum) {
@"200": void,
@"500": ErrorResponse,
@"503": ErrorResponse,
},
);
};
pub const @"/services" = struct {
pub usingnamespace internal.Fn(
.get,
internal.name(Top, @This()),
void,
struct { filters: string, status: bool },
void,
union(enum) {
@"200": []const Service,
@"500": ErrorResponse,
@"503": ErrorResponse,
},
);
};
pub const @"/services/create" = struct {
pub usingnamespace internal.Fn(
.post,
internal.name(Top, @This()),
void,
void,
struct { body: internal.AllOf(&.{ ServiceSpec, struct {} }) },
union(enum) {
@"201": struct { ID: string, Warning: string },
@"400": ErrorResponse,
@"403": ErrorResponse,
@"409": ErrorResponse,
@"500": ErrorResponse,
@"503": ErrorResponse,
},
);
};
pub const @"/services/{id}" = struct {
pub usingnamespace internal.Fn(
.get,
internal.name(Top, @This()),
struct { id: string },
struct { insertDefaults: bool = false },
void,
union(enum) {
@"200": Service,
@"404": ErrorResponse,
@"500": ErrorResponse,
@"503": ErrorResponse,
},
);
pub usingnamespace internal.Fn(
.delete,
internal.name(Top, @This()),
struct { id: string },
void,
void,
union(enum) {
@"200": void,
@"404": ErrorResponse,
@"500": ErrorResponse,
@"503": ErrorResponse,
},
);
};
pub const @"/services/{id}/update" = struct {
pub usingnamespace internal.Fn(
.post,
internal.name(Top, @This()),
struct { id: string },
struct { version: i32, registryAuthFrom: enum { spec, @"previous-spec" } = "spec", rollback: string },
struct { body: internal.AllOf(&.{ ServiceSpec, struct {} }) },
union(enum) {
@"200": ServiceUpdateResponse,
@"400": ErrorResponse,
@"404": ErrorResponse,
@"500": ErrorResponse,
@"503": ErrorResponse,
},
);
};
pub const @"/services/{id}/logs" = struct {
pub usingnamespace internal.Fn(
.get,
internal.name(Top, @This()),
struct { id: string },
struct { details: bool = false, follow: bool = false, stdout: bool = false, stderr: bool = false, since: i32 = 0, timestamps: bool = false, tail: string = "all" },
void,
union(enum) {
@"200": string,
@"404": ErrorResponse,
@"500": ErrorResponse,
@"503": ErrorResponse,
},
);
};
pub const @"/tasks" = struct {
pub usingnamespace internal.Fn(
.get,
internal.name(Top, @This()),
void,
struct { filters: string },
void,
union(enum) {
@"200": []const Task,
@"500": ErrorResponse,
@"503": ErrorResponse,
},
);
};
pub const @"/tasks/{id}" = struct {
pub usingnamespace internal.Fn(
.get,
internal.name(Top, @This()),
struct { id: string },
void,
void,
union(enum) {
@"200": Task,
@"404": ErrorResponse,
@"500": ErrorResponse,
@"503": ErrorResponse,
},
);
};
pub const @"/tasks/{id}/logs" = struct {
pub usingnamespace internal.Fn(
.get,
internal.name(Top, @This()),
struct { id: string },
struct { details: bool = false, follow: bool = false, stdout: bool = false, stderr: bool = false, since: i32 = 0, timestamps: bool = false, tail: string = "all" },
void,
union(enum) {
@"200": string,
@"404": ErrorResponse,
@"500": ErrorResponse,
@"503": ErrorResponse,
},
);
};
pub const @"/secrets" = struct {
pub usingnamespace internal.Fn(
.get,
internal.name(Top, @This()),
void,
struct { filters: string },
void,
union(enum) {
@"200": []const Secret,
@"500": ErrorResponse,
@"503": ErrorResponse,
},
);
};
pub const @"/secrets/create" = struct {
pub usingnamespace internal.Fn(
.post,
internal.name(Top, @This()),
void,
void,
struct { body: internal.AllOf(&.{ SecretSpec, struct {} }) },
union(enum) {
@"201": IdResponse,
@"409": ErrorResponse,
@"500": ErrorResponse,
@"503": ErrorResponse,
},
);
};
pub const @"/secrets/{id}" = struct {
pub usingnamespace internal.Fn(
.get,
internal.name(Top, @This()),
struct { id: string },
void,
void,
union(enum) {
@"200": Secret,
@"404": ErrorResponse,
@"500": ErrorResponse,
@"503": ErrorResponse,
},
);
pub usingnamespace internal.Fn(
.delete,
internal.name(Top, @This()),
struct { id: string },
void,
void,
union(enum) {
@"204": void,
@"404": ErrorResponse,
@"500": ErrorResponse,
@"503": ErrorResponse,
},
);
};
pub const @"/secrets/{id}/update" = struct {
pub usingnamespace internal.Fn(
.post,
internal.name(Top, @This()),
struct { id: string },
struct { version: i32 },
struct { body: SecretSpec },
union(enum) {
@"200": void,
@"400": ErrorResponse,
@"404": ErrorResponse,
@"500": ErrorResponse,
@"503": ErrorResponse,
},
);
};
pub const @"/configs" = struct {
pub usingnamespace internal.Fn(
.get,
internal.name(Top, @This()),
void,
struct { filters: string },
void,
union(enum) {
@"200": []const Config,
@"500": ErrorResponse,
@"503": ErrorResponse,
},
);
};
pub const @"/configs/create" = struct {
pub usingnamespace internal.Fn(
.post,
internal.name(Top, @This()),
void,
void,
struct { body: internal.AllOf(&.{ ConfigSpec, struct {} }) },
union(enum) {
@"201": IdResponse,
@"409": ErrorResponse,
@"500": ErrorResponse,
@"503": ErrorResponse,
},
);
};
pub const @"/configs/{id}" = struct {
pub usingnamespace internal.Fn(
.get,
internal.name(Top, @This()),
struct { id: string },
void,
void,
union(enum) {
@"200": Config,
@"404": ErrorResponse,
@"500": ErrorResponse,
@"503": ErrorResponse,
},
);
pub usingnamespace internal.Fn(
.delete,
internal.name(Top, @This()),
struct { id: string },
void,
void,
union(enum) {
@"204": void,
@"404": ErrorResponse,
@"500": ErrorResponse,
@"503": ErrorResponse,
},
);
};
pub const @"/configs/{id}/update" = struct {
pub usingnamespace internal.Fn(
.post,
internal.name(Top, @This()),
struct { id: string },
struct { version: i32 },
struct { body: ConfigSpec },
union(enum) {
@"200": void,
@"400": ErrorResponse,
@"404": ErrorResponse,
@"500": ErrorResponse,
@"503": ErrorResponse,
},
);
};
pub const @"/distribution/{name}/json" = struct {
pub usingnamespace internal.Fn(
.get,
internal.name(Top, @This()),
struct { name: string },
void,
void,
union(enum) {
@"200": DistributionInspect,
@"401": ErrorResponse,
@"500": ErrorResponse,
},
);
};
pub const @"/session" = struct {
pub usingnamespace internal.Fn(
.post,
internal.name(Top, @This()),
void,
void,
void,
union(enum) {
@"101": void,
@"400": ErrorResponse,
@"500": ErrorResponse,
},
);
};
|
src/direct.zig
|
const std = @import("std");
const Allocator = std.mem.Allocator;
const assert = std.debug.assert;
const eql = std.meta.eql;
const panic = std.debug.panic;
const strings_module = @import("strings.zig");
const Strings = strings_module.Strings;
const InternedString = strings_module.InternedString;
const Entity = @import("ecs.zig").Entity;
const List = @import("list.zig").List;
pub fn DistinctEntity(comptime unique_id: []const u8) type {
assert(unique_id.len > 0);
return struct {
entity: Entity,
const Self = @This();
pub fn init(entity: Entity) Self {
return Self{ .entity = entity };
}
};
}
pub fn DistinctList(comptime unique_id: []const u8, comptime T: type) type {
assert(unique_id.len > 0);
return struct {
values: List(T, .{}),
const Self = @This();
pub fn init(allocator: Allocator) Self {
return Self{ .values = List(T, .{}).init(allocator) };
}
pub fn fromSlice(allocator: Allocator, values: []const T) !Self {
const list = try List(T, .{}).fromSlice(allocator, values);
return Self{ .values = list };
}
pub fn withCapacity(allocator: Allocator, capacity: u64) !Self {
const list = try List(T, .{}).withCapacity(allocator, capacity);
return Self{ .values = list };
}
pub fn append(self: *Self, value: T) !void {
try self.values.append(value);
}
pub fn appendSlice(self: *Self, values: []const T) !void {
return self.values.appendSlice(values);
}
pub fn appendAssumeCapacity(self: *Self, entity: T) void {
self.values.appendAssumeCapacity(entity);
}
pub fn slice(self: Self) []const T {
return self.values.slice();
}
pub fn mutSlice(self: Self) []T {
return self.values.mutSlice();
}
pub fn shrink(self: *Self, n: u64) void {
self.values.len -= n;
}
pub fn last(self: Self) T {
return self.values.last();
}
pub fn len(self: Self) u64 {
return self.values.len;
}
};
}
pub fn DistinctEntityMap(comptime unique_id: []const u8) type {
assert(unique_id.len > 0);
return struct {
const Map = std.AutoHashMap(InternedString, Entity);
const Self = @This();
map: Map,
strings: *Strings,
pub fn init(allocator: Allocator, strings: *Strings) Self {
return Self{ .map = Map.init(allocator), .strings = strings };
}
pub fn iterator(self: *const Self) Map.Iterator {
return self.map.iterator();
}
pub fn putInterned(self: *Self, interned: InternedString, entity: Entity) !void {
try self.map.putNoClobber(interned, entity);
}
pub fn putName(self: *Self, value: Name, entity: Entity) !void {
try self.map.putNoClobber(value.entity.get(Literal).interned, entity);
}
pub fn findString(self: Self, string: []const u8) Entity {
const interned = self.strings.lookup.get(string).?;
return self.map.get(interned).?;
}
pub fn findLiteral(self: Self, literal: Literal) Entity {
return self.map.get(literal.interned).?;
}
pub fn hasLiteral(self: Self, literal: Literal) ?Entity {
return self.map.get(literal.interned);
}
pub fn putLiteral(self: *Self, literal: Literal, entity: Entity) !void {
try self.map.putNoClobber(literal.interned, entity);
}
pub fn findName(self: Self, name: Name) Entity {
return self.hasName(name).?;
}
pub fn hasName(self: Self, name: Name) ?Entity {
const interned = name.entity.get(Literal).interned;
return self.map.get(interned);
}
pub fn count(self: Self) usize {
return self.map.count();
}
};
}
pub fn DistinctEntitySet(comptime unique_id: []const u8) type {
assert(unique_id.len > 0);
return struct {
entities: List(Entity, .{}),
const Self = @This();
pub fn init(allocator: Allocator) Self {
return Self{ .entities = List(Entity, .{}).init(allocator) };
}
pub fn put(self: *Self, entity: Entity) !void {
for (self.entities.slice()) |e| {
if (eql(entity, e)) return;
}
try self.entities.append(entity);
}
pub fn slice(self: Self) []const Entity {
return self.entities.slice();
}
};
}
pub const Position = struct {
column: u64,
row: u64,
pub fn init(column: u64, row: u64) Position {
return Position{ .column = column, .row = row };
}
};
pub const Span = struct {
begin: Position,
end: Position,
pub fn init(begin: Position, end: Position) Span {
return Span{ .begin = begin, .end = end };
}
};
pub const TokenKind = enum(u8) {
symbol,
int,
float,
string,
char,
left_paren,
right_paren,
left_bracket,
right_bracket,
left_brace,
right_brace,
plus,
plus_equal,
minus,
times,
times_equal,
slash,
dot,
greater_than,
greater_equal,
greater_greater,
less_than,
less_equal,
less_less,
equal,
equal_equal,
colon,
colon_equal,
bang_equal,
ampersand,
bar,
percent,
caret,
comma,
import,
fn_,
if_,
else_,
while_,
for_,
in,
underscore,
new_line,
struct_,
attribute_export,
attribute_import,
};
pub const Literal = struct {
interned: InternedString,
pub fn init(interned: InternedString) Literal {
return Literal{ .interned = interned };
}
};
pub const AstKind = enum(u8) {
symbol,
int,
float,
string,
array_literal,
char,
function,
binary_op,
plus_equal,
times_equal,
define,
assign,
call,
import,
overload_set,
if_,
while_,
for_,
local,
intrinsic,
underscore,
cast,
pointer,
array,
struct_,
construct,
field,
assign_field,
range,
index,
};
pub const BinaryOp = enum(u8) {
add,
subtract,
multiply,
divide,
remainder,
less_than,
less_equal,
greater_than,
greater_equal,
equal,
not_equal,
bit_or,
bit_xor,
bit_and,
left_shift,
right_shift,
dot,
};
pub const Intrinsic = enum(u8) {
add,
subtract,
multiply,
divide,
remainder,
bit_and,
bit_or,
bit_xor,
left_shift,
right_shift,
equal,
not_equal,
less_than,
less_equal,
greater_than,
greater_equal,
store,
load,
add_ptr_i32,
subtract_ptr_i32,
subtract_ptr_ptr,
v128_load,
v128_store,
};
pub const WasmInstructionKind = enum(u8) {
i64_const,
i32_const,
f64_const,
f32_const,
i64_add,
i32_add,
i32_add_mod_16,
i32_add_mod_8,
f64_add,
f32_add,
i64_sub,
i32_sub,
i32_sub_mod_16,
i32_sub_mod_8,
f64_sub,
f32_sub,
i64_mul,
i32_mul,
i32_mul_mod_16,
i32_mul_mod_8,
f64_mul,
f32_mul,
i64_div,
i32_div,
u64_div,
u32_div,
f64_div,
f32_div,
i64_lt,
i32_lt,
u64_lt,
u32_lt,
f64_lt,
f32_lt,
i64_le,
i32_le,
u64_le,
u32_le,
f64_le,
f32_le,
i64_gt,
i32_gt,
u64_gt,
u32_gt,
f64_gt,
f32_gt,
i64_ge,
i32_ge,
u64_ge,
u32_ge,
f64_ge,
f32_ge,
i64_eq,
i32_eq,
f64_eq,
f32_eq,
i64_ne,
i32_ne,
f64_ne,
f32_ne,
i64_or,
i32_or,
i64_xor,
i32_xor,
i64_and,
i32_and,
i64_shl,
i32_shl,
u64_shl,
u32_shl,
i64_shr,
i32_shr,
u64_shr,
u32_shr,
i64_rem,
i32_rem,
u64_rem,
u32_rem,
i32_eqz,
call,
local_get,
local_set,
if_,
else_,
end,
block,
loop,
br_if,
br,
i32_store,
i64_store,
f32_store,
f64_store,
i32_load,
i32_load8_u,
i64_load,
f32_load,
f64_load,
v128_load,
v128_store,
i64x2_add,
i32x4_add,
i16x8_add,
i8x16_add,
f64x2_add,
f32x4_add,
i64x2_sub,
i32x4_sub,
i16x8_sub,
i8x16_sub,
f64x2_sub,
f32x4_sub,
i64x2_mul,
i32x4_mul,
i16x8_mul,
i8x16_mul,
f64x2_mul,
f32x4_mul,
f64x2_div,
f32x4_div,
field,
assign_field,
};
pub const Builtins = struct {
Type: Entity,
Module: Entity,
I64: Entity,
I32: Entity,
I16: Entity,
I8: Entity,
U64: Entity,
U32: Entity,
U16: Entity,
U8: Entity,
F64: Entity,
F32: Entity,
Void: Entity,
Ptr: Entity,
Array: Entity,
Range: Entity,
IntLiteral: Entity,
FloatLiteral: Entity,
I64X2: Entity,
I32X4: Entity,
I16X8: Entity,
I8X16: Entity,
U64X2: Entity,
U32X4: Entity,
U16X8: Entity,
U8X16: Entity,
F64X2: Entity,
F32X4: Entity,
Cast: Entity,
};
pub const Error = struct {
header: []const u8,
body: []const u8,
span: Span,
hint: []const u8,
module: Entity,
};
pub const Scopes = struct {
const Map = std.AutoHashMap(InternedString, Entity);
const Self = @This();
scopes: List(Map, .{}),
strings: *Strings,
allocator: Allocator,
pub fn init(allocator: Allocator, strings: *Strings) Self {
return Self{
.scopes = List(Map, .{}).init(allocator),
.strings = strings,
.allocator = allocator,
};
}
pub fn pushScope(self: *Self) !u64 {
const index = self.scopes.len;
try self.scopes.append(Map.init(self.allocator));
return index;
}
pub fn putInterned(self: *Self, interned: InternedString, entity: Entity) !void {
assert(self.scopes.len > 0);
const scopes = self.scopes.mutSlice();
try scopes[scopes.len - 1].putNoClobber(interned, entity);
}
pub fn putName(self: *Self, value: Name, entity: Entity) !void {
try self.putInterned(value.entity.get(Literal).interned, entity);
}
pub fn putLiteral(self: *Self, literal: Literal, entity: Entity) !void {
try self.putInterned(literal.interned, entity);
}
pub fn findString(self: Self, string: []const u8) Entity {
const interned = self.strings.lookup.get(string).?;
const scopes = self.scopes.mutSlice();
var i: usize = scopes.len;
while (i > 0) : (i -= 1) {
if (scopes[i - 1].get(interned)) |entity| {
return entity;
}
}
panic("\nscopes could not find string {s}\n", .{string});
}
pub fn findLiteral(self: Self, literal: Literal) Entity {
return self.hasLiteral(literal).?;
}
pub fn findName(self: Self, name: Name) Entity {
return self.hasName(name).?;
}
pub fn hasLiteral(self: Self, literal: Literal) ?Entity {
const interned = literal.interned;
const scopes = self.scopes.mutSlice();
var i: usize = scopes.len;
while (i > 0) : (i -= 1) {
if (scopes[i - 1].get(interned)) |entity| {
return entity;
}
}
return null;
}
pub fn hasName(self: Self, name: Name) ?Entity {
return self.hasLiteral(name.entity.get(Literal));
}
pub fn slice(self: Self) []const Map {
return self.scopes.slice();
}
};
fn DistinctMap(comptime unique_id: []const u8, comptime K: type, comptime V: type) type {
assert(unique_id.len > 0);
return struct {
const Map = std.AutoHashMap(K, V);
const Self = @This();
map: Map,
pub fn init(allocator: Allocator) Self {
return Self{ .map = Map.init(allocator) };
}
pub fn getOrPut(self: *Self, key: K) !Map.GetOrPutResult {
return try self.map.getOrPut(key);
}
};
}
pub const DataSegment = struct {
entities: List(Entity, .{}),
end: i32,
pub fn init(allocator: Allocator) DataSegment {
return .{ .entities = List(Entity, .{}).init(allocator), .end = 0 };
}
};
pub const Name = DistinctEntity("Name");
pub const ReturnTypeAst = DistinctEntity("Return Type Ast");
pub const ReturnType = DistinctEntity("Return Type");
pub const Value = DistinctEntity("Value");
pub const Callable = DistinctEntity("Callable");
pub const TypeAst = DistinctEntity("Type Ast");
pub const Type = DistinctEntity("Type");
pub const Parameters = DistinctList("Parameters", Entity);
pub const Body = DistinctList("Body", Entity);
pub const Arguments = DistinctList("Arguments", Entity);
pub const NamedArguments = DistinctEntityMap("Named Arguments");
pub const OrderedNamedArguments = DistinctList("Ordered Named Arguments", Entity);
pub const Overloads = DistinctList("Overloads", Entity);
pub const Fields = DistinctList("Fields", Entity);
pub const TopLevel = DistinctEntityMap("Top Level");
pub const Path = DistinctEntity("Path");
pub const Module = DistinctEntity("Module");
pub const Functions = DistinctList("Functions", Entity);
pub const WasmInstructions = DistinctList("Wasm Instructions", Entity);
pub const Locals = DistinctEntitySet("Locals");
pub const Conditional = DistinctEntity("Conditional");
pub const Then = DistinctList("Then", Entity);
pub const Else = DistinctList("Else", Entity);
pub const DependentEntities = DistinctList("Dependent Entities", Entity);
pub const IntLiterals = DistinctList("Int Literals", Entity);
pub const Local = DistinctEntity("Local");
pub const Field = DistinctEntity("Field");
pub const Constant = DistinctEntity("Constant");
pub const Scope = DistinctEntityMap("Scope");
pub const ActiveScopes = DistinctList("Active Scopes", u64);
pub const Label = struct { value: u64 };
pub const Mutable = struct { value: bool };
pub const AnalyzedParameters = struct { value: bool };
pub const AnalyzedBody = struct { value: bool };
pub const AnalyzedFields = struct { value: bool };
pub const AnalyzedExpression = struct { value: bool };
pub const WasmName = DistinctList("Wasm Name", u8);
pub const Imports = DistinctList("Imports", Entity);
pub const ForeignImports = DistinctList("Foreign Imports", Entity);
pub const ForeignExports = DistinctList("Foreign Exports", Entity);
pub const ForeignModule = DistinctEntity("Foreign Module");
pub const ForeignName = DistinctEntity("Foreign Name");
pub const Memoized = DistinctMap("Memoized", Entity, Entity);
pub const ParentType = DistinctEntity("Parent Type");
pub const ValueType = DistinctEntity("Value Type");
pub const LoopVariable = DistinctEntity("Loop Variable");
pub const Iterator = DistinctEntity("Iterator");
pub const First = DistinctEntity("First");
pub const Last = DistinctEntity("Last");
pub const Values = DistinctList("Values", Entity);
pub const UsesMemory = struct { value: bool };
pub const Size = struct { bytes: i32 };
pub const Length = struct { value: i32 };
pub const Location = struct { value: i32 };
pub const ModuleSource = struct { string: []const u8 };
pub const ModulePath = struct { string: []const u8 };
|
src/components.zig
|
const std = @import("std");
const testing = std.testing;
const meta = std.meta;
const unicode = std.unicode;
const assert = std.debug.assert;
const Allocator = std.mem.Allocator;
const math = std.math;
const Uuid = @import("uuid6");
const serde = @import("serde.zig");
const nbt = @import("nbt.zig");
const VarNum = @import("varnum.zig").VarNum;
pub const VarInt = VarNum(i32);
pub const VarLong = VarNum(i64);
pub const chunk = @import("chunk.zig");
pub const PROTOCOL_VERSION = 757;
pub const PStringError = error{
StringTooLarge,
};
pub const PSTRING_ARRAY_MAX_LEN = 64;
// todo: uh, probably want just separate types for the stack vs heap versions. can do fancy auto stuff later once those are around
pub fn PStringMax(comptime max_len_opt: ?usize) type {
return struct {
pub const IsArray = max_len_opt != null and max_len_opt.? <= PSTRING_ARRAY_MAX_LEN;
pub const UserType = if (IsArray) [max_len_opt.? * 4:0]u8 else []const u8;
pub fn characterCount(self: UserType) !i32 {
return @intCast(i32, try unicode.utf8CountCodepoints(if (IsArray) std.mem.sliceTo(&self, 0) else self));
}
pub fn write(self: UserType, writer: anytype) !void {
try VarInt.write(try characterCount(self), writer);
try writer.writeAll(if (IsArray) std.mem.sliceTo(&self, 0) else self);
}
pub fn deserialize(alloc: Allocator, reader: anytype) !UserType {
const len = try VarInt.deserialize(alloc, reader);
if (max_len_opt) |max_len| {
if (len > max_len) {
return error.StringTooLarge;
}
}
var data = if (IsArray) std.BoundedArray(u8, max_len_opt.? * 4 + 1){} else try std.ArrayList(u8).initCapacity(alloc, @intCast(usize, len));
defer if (!IsArray) data.deinit();
var i: usize = 0;
while (i < len) : (i += 1) {
const first_byte = try reader.readByte();
const codepoint_len = try unicode.utf8ByteSequenceLength(first_byte);
try data.ensureUnusedCapacity(codepoint_len);
data.appendAssumeCapacity(first_byte);
if (codepoint_len > 0) {
var codepoint_buf: [3]u8 = undefined;
try reader.readNoEof(codepoint_buf[0 .. codepoint_len - 1]);
data.appendSliceAssumeCapacity(codepoint_buf[0 .. codepoint_len - 1]);
}
}
if (IsArray) {
assert(data.len < data.buffer.len);
data.buffer[data.len] = 0;
return @bitCast([max_len_opt.? * 4:0]u8, data.buffer);
} else {
return data.toOwnedSlice();
}
}
pub fn deinit(self: UserType, alloc: Allocator) void {
if (IsArray) {
_ = self;
_ = alloc;
} else {
alloc.free(self);
}
}
pub fn size(self: UserType) usize {
var len = characterCount(self) catch unreachable;
return VarInt.size(len) + if (IsArray) std.mem.sliceTo(&self, 0).len else self.len;
}
};
}
test "pstring" {
//var reader = std.io.fixedBufferStream();
const DataType = PStringMax(10);
var result = try testPacket(DataType, testing.allocator, &[_]u8{10} ++ "你好,我们没有时间。");
//std.debug.print("result len: {}, {}\n", .{ std.mem.sliceTo(&result, 0).len, DataType.characterCount(result) });
try testing.expectEqual(@as(usize, 30), std.mem.sliceTo(&result, 0).len);
try testing.expectEqual(@as(i32, 10), try DataType.characterCount(result));
try testing.expectEqualStrings("你好,我们没有时间。", std.mem.sliceTo(&result, 0));
try testing.expectEqual(@as(usize, 31), DataType.size(result));
const DataType2 = PStringMax(PSTRING_ARRAY_MAX_LEN + 1);
try testing.expect(!DataType2.IsArray);
var result2 = try testPacket(DataType2, testing.allocator, &[_]u8{10} ++ "你好,我们没有时间。");
defer DataType2.deinit(result2, testing.allocator);
try testing.expectEqual(@as(usize, 30), result2.len);
try testing.expectEqual(@as(i32, 10), try DataType2.characterCount(result2));
try testing.expectEqualStrings("你好,我们没有时间。", result2);
try testing.expectEqual(@as(usize, 31), DataType2.size(result2));
}
pub const PString = PStringMax(32767);
pub const Identifier = PStringMax(32767);
pub const ChatString = PStringMax(262144);
pub fn intoAngle(val: f32) u8 {
var new_val: isize = @floatToInt(isize, (val / 360.0) * 256.0);
while (new_val < 0) new_val += 256;
while (new_val >= 256) new_val -= 256;
return @intCast(u8, new_val);
}
pub const UuidS = struct {
pub const UserType = Uuid;
pub fn write(self: UserType, writer: anytype) !void {
try writer.writeAll(&self.bytes);
}
pub fn deserialize(alloc: Allocator, reader: anytype) !UserType {
_ = alloc;
var uuid: Uuid = undefined;
try reader.readNoEof(&uuid.bytes);
return uuid;
}
pub fn deinit(self: UserType, alloc: Allocator) void {
_ = self;
_ = alloc;
}
pub fn size(self: UserType) usize {
_ = self;
return @sizeOf(UserType);
}
};
// referenced https://github.com/AdoptOpenJDK/openjdk-jdk8u/blob/9a91972c76ddda5c1ce28b50ca38cbd8a30b7a72/jdk/src/share/classes/java/util/UUID.java#L153-L175
pub fn uuidFromUsername(username: []const u8) !Uuid {
var username_buf: [16 + ("OfflinePlayer:").len]u8 = undefined;
const padded_username = try std.fmt.bufPrint(&username_buf, "OfflinePlayer:{s}", .{username});
var uuid: Uuid = undefined;
std.crypto.hash.Md5.hash(padded_username, &uuid.bytes, .{});
uuid.setVersion(3);
uuid.setVariant(.rfc4122);
return uuid;
}
pub const DimensionCodecDimensionTypeElement = struct {
piglin_safe: bool,
natural: bool,
ambient_light: f32,
fixed_time: ?i64 = null,
infiniburn: []const u8,
respawn_anchor_works: bool,
has_skylight: bool,
bed_works: bool,
effects: []const u8,
has_raids: bool,
min_y: i32,
height: i32,
logical_height: i32,
coordinate_scale: f32,
ultrawarm: bool,
has_ceiling: bool,
};
pub const DimensionCodec = struct {
@"minecraft:dimension_type": struct { @"type": []const u8 = "minecraft:dimension_type", value: []DimensionType },
@"minecraft:worldgen/biome": struct {
@"type": []const u8 = "minecraft:worldgen/biome",
value: []Biome,
},
pub const DimensionType = struct {
name: []const u8,
id: i32,
element: DimensionCodecDimensionTypeElement,
};
pub const Biome = struct {
name: []const u8,
id: i32,
element: Element,
pub const Element = struct {
precipitation: []const u8,
depth: f32,
temperature: f32,
scale: f32,
downfall: f32,
category: []const u8,
temperature_modifier: ?[]const u8 = null,
effects: Effects,
particle: ?Particle,
pub const Effects = struct {
sky_color: i32,
water_fog_color: i32,
fog_color: i32,
water_color: i32,
foliage_color: ?i32 = null,
grass_color: ?i32 = null,
grass_color_modifier: ?[]const u8 = null,
music: ?Music = null,
ambient_sound: ?[]const u8 = null,
additions_sound: ?SoundAdditions = null,
mood_sound: ?MoodSound = null,
pub const Music = struct {
replace_curent_music: bool,
sound: []const u8,
max_delay: i32,
min_delay: i32,
};
pub const SoundAdditions = struct {
sound: []const u8,
tick_chance: f64,
};
pub const MoodSound = struct {
sound: []const u8,
tick_delay: i32,
offset: f64,
block_search_extent: i32,
};
};
pub const Particle = struct {
probability: f32,
options: []const u8,
};
};
};
};
pub const DEFAULT_DIMENSION_TYPE_ELEMENT: DimensionCodecTypeElementS.UserType = .{
.piglin_safe = false,
.natural = true,
.ambient_light = 0.0,
.infiniburn = "minecraft:infiniburn_overworld",
.respawn_anchor_works = false,
.has_skylight = true,
.bed_works = true,
.effects = "minecraft:overworld",
.has_raids = true,
.min_y = chunk.MIN_Y,
.height = chunk.MAX_HEIGHT,
.logical_height = 256,
.coordinate_scale = 1.0,
.ultrawarm = false,
.has_ceiling = false,
.fixed_time = null,
};
pub const DEFUALT_DIMENSION_CODEC: DimensionCodecS.UserType = .{
.@"minecraft:dimension_type" = .{
.@"type" = "minecraft:dimension_type",
.value = &[_]meta.Child(DimensionCodecS.Specs[0].Specs[1].UserType){
.{
.name = "minecraft:overworld",
.id = 0,
.element = .{
.piglin_safe = false,
.natural = true,
.ambient_light = 0.0,
.infiniburn = "minecraft:infiniburn_overworld",
.respawn_anchor_works = false,
.has_skylight = true,
.bed_works = true,
.effects = "minecraft:overworld",
.has_raids = true,
.min_y = chunk.MIN_Y,
.height = chunk.MAX_HEIGHT,
.logical_height = 256,
.coordinate_scale = 1.0,
.ultrawarm = false,
.has_ceiling = false,
.fixed_time = null,
},
},
},
},
.@"minecraft:worldgen/biome" = .{
.@"type" = "minecraft:worldgen/biome",
.value = &[_]meta.Child(DimensionCodecS.Specs[1].Specs[1].UserType){
.{
.name = "minecraft:plains",
.id = 1,
.element = .{
.precipitation = "rain",
.effects = .{
.sky_color = 0x78A7FF,
.water_fog_color = 0x050533,
.fog_color = 0xC0D8FF,
.water_color = 0x3F76E4,
.mood_sound = .{
.tick_delay = 6000,
.offset = 2.0,
.sound = "minecraft:ambient.cave",
.block_search_extent = 8,
},
.foliage_color = null,
.grass_color = null,
.grass_color_modifier = null,
.music = null,
.ambient_sound = null,
.additions_sound = null,
},
.depth = 0.125,
.temperature = 0.8,
.scale = 0.05,
.downfall = 0.4,
.category = "plains",
.temperature_modifier = null,
.particle = null,
},
},
},
},
};
pub const Slot = Ds.Spec(?SlotData);
pub const SlotData = struct {
item_id: VarInt,
item_count: i8,
nbt: nbt.DynamicCompound,
};
pub const Ingredient = serde.PrefixedArray(Ds, VarInt, Slot);
pub const CraftingShaped = struct {
// a whole custom type all cause group was put in between width+height and ingredients
width: VarInt.UserType,
height: VarInt.UserType,
group: PString.UserType,
ingredients: []Ingredient.UserType,
result: Slot.UserType,
pub const UserType = @This();
pub fn write(self: UserType, writer: anytype) !void {
try VarInt.write(self.width, writer);
try VarInt.write(self.height, writer);
try PString.write(self.group, writer);
for (self.ingredients) |elem| {
try Ingredient.write(elem, writer);
}
try Slot.write(self.result, writer);
}
pub fn deserialize(alloc: Allocator, reader: anytype) !UserType {
var self: UserType = undefined;
self.width = try VarInt.deserialize(alloc, reader);
self.height = try VarInt.deserialize(alloc, reader);
self.group = try PString.deserialize(alloc, reader);
errdefer PString.deinit(self.group, alloc);
const total = @intCast(usize, self.width * self.height);
self.ingredients = try alloc.alloc(Ingredient.UserType, total);
errdefer alloc.free(self.ingredients);
for (self.ingredients) |*elem, i| {
errdefer {
var ind: usize = 0;
while (ind < i) : (ind += 1) {
Ingredient.deinit(self.ingredients[i], alloc);
}
}
elem.* = try Ingredient.deserialize(alloc, reader);
}
self.result = try Slot.deserialize(alloc, reader);
return self;
}
pub fn deinit(self: UserType, alloc: Allocator) void {
PString.deinit(self.group, alloc);
for (self.ingredients) |elem| {
Ingredient.deinit(elem, alloc);
}
alloc.free(self.ingredients);
Slot.deinit(self.result);
}
pub fn size(self: UserType) usize {
var total_size: usize = VarInt.size(self.width) + VarInt.size(self.height) + PString.size(self.group) + Slot.size(self.result);
var j: i32 = 0;
while (j < self.height) : (j += 1) {
var i: i32 = 0;
while (i < self.width) : (i += 1) {
total_size += Ingredient.size(self.ingredients[@intCast(usize, i) + @intCast(usize, j * self.width)]);
}
}
return total_size;
}
};
pub const Recipe = struct {
type: Identifier.UserType,
recipe_id: Identifier.UserType,
data: RecipeData.UserType,
pub const RecipeData = serde.Union(Ds, union(enum) {
crafting_shapeless: struct {
group: PString,
ingredients: serde.PrefixedArray(Ds, VarInt, Ingredient),
result: Slot,
},
crafting_shaped: CraftingShaped,
crafting_special_armor_dye: void,
crafting_special_book_cloning: void,
crafting_special_map_cloning: void,
crafting_special_map_extending: void,
crafting_special_firework_rocket: void,
crafting_special_firework_star: void,
crafting_special_firework_star_fade: void,
crafting_special_repair_item: void,
crafting_special_tipped_arrow: void,
crafting_special_banned_duplicate: void,
crafting_special_banner_add_pattern: void,
crafting_special_shield_decoration: void,
crafting_special_shulker_box_coloring: void,
crafting_special_suspicious_stew: void,
smelting: Smelting,
blasting: Smelting,
smoking: Smelting,
campfire_cooking: Smelting,
stonecutting: struct {
group: PString,
ingredient: Ingredient,
result: Slot,
},
smithing: struct {
base: Ingredient,
addition: Ingredient,
result: Slot,
},
none: void,
pub const Smelting = struct {
group: PString,
ingredient: Ingredient,
result: Slot,
experience: f32,
cooking_time: VarInt,
};
});
// TODO since we're not using pascal case for the variant names here anymore, we could probably automate the string to enum conversion
const IdentifierMap = std.ComptimeStringMap(meta.Tag(RecipeData.UserType), .{
.{ "crafting_shapeless", .crafting_shapeless },
.{ "crafting_shaped", .crafting_shaped },
.{ "crafting_special_armordye", .crafting_special_armor_dye },
.{ "crafting_special_bookcloning", .crafting_special_book_cloning },
.{ "crafting_special_mapcloning", .crafting_special_map_cloning },
.{ "crafting_special_mapextending", .crafting_special_map_extending },
.{ "crafting_special_firework_rocket", .crafting_special_firework_rocket },
.{ "crafting_special_firework_star", .crafting_special_firework_star },
.{ "crafting_special_firework_star_fade", .crafting_special_firework_star_fade },
.{ "crafting_special_repairitem", .crafting_special_repair_item },
.{ "crafting_special_tippedarrow", .crafting_special_tipped_arrow },
.{ "crafting_special_bannerduplicate", .crafting_special_banned_duplicate },
.{ "crafting_special_banneraddpattern", .crafting_special_banner_add_pattern },
.{ "crafting_special_shielddecoration", .crafting_special_shield_decoration },
.{ "crafting_special_shulkerboxcoloring", .crafting_special_shulker_box_coloring },
.{ "crafting_special_suspiciousstew", .crafting_special_suspicious_stew },
.{ "smelting", .smelting },
.{ "blasting", .blasting },
.{ "smoking", .smoking },
.{ "campfire_cooking", .campfire_cooking },
.{ "stonecutting", .stonecutting },
.{ "smithing", .smithing },
});
pub const UserType = @This();
pub fn write(self: anytype, writer: anytype) !void {
try Identifier.write(self.type, writer);
try Identifier.write(self.recipe_id, writer);
try RecipeData.write(self.data, writer);
}
pub fn deserialize(alloc: Allocator, reader: anytype) !UserType {
var self: UserType = undefined;
self.type = try Identifier.deserialize(alloc, reader);
errdefer Identifier.deinit(self.type, alloc);
self.recipe_id = try Identifier.deserialize(alloc, reader);
errdefer Identifier.deinit(self.recipe_id, alloc);
const tag: meta.Tag(RecipeData.UserType) = IdentifierMap.get(self.type) orelse .none;
self.data = try RecipeData.deserialize(alloc, reader, @enumToInt(tag));
return self;
}
pub fn deinit(self: UserType, alloc: Allocator) void {
Identifier.deinit(self.type, alloc);
Identifier.deinit(self.recipe_id, alloc);
RecipeData.deinit(self.data, alloc);
}
pub fn size(self: anytype) usize {
return RecipeData.size(self.data) + Identifier.size(self.type) + Identifier.size(self.recipe_id);
}
};
pub const Difficulty = enum(u8) {
Peaceful = 0,
Easy = 1,
Normal = 2,
Hard = 3,
};
pub const Gamemode = enum(u8) {
Survival = 0,
Creative = 1,
Adventure = 2,
Spectator = 3,
};
pub const PreviousGamemode = enum(i8) {
None = -1,
Survival = 0,
Creative = 1,
Adventure = 2,
Spectator = 3,
};
pub const CommandNode = struct {
// TODO: complete implementation https://wiki.vg/Command_Data
flags: CommandNodeFlags,
children: serde.PrefixedArray(Ds, VarInt, VarInt),
redirect_node: ?VarInt,
//name: ?PStringMax(32767),
//parser: ?Identifier,
//properties: ?
};
pub const CommandNodeFlags = packed struct {
node_type: enum(u2) {
Root = 0,
Literal = 1,
Argument = 2,
},
is_executable: bool,
has_redirect: bool,
has_suggestions_type: bool,
};
pub const DimensionCodecS = nbt.NbtSpec.Spec(DimensionCodec);
pub const DimensionCodecTypeElementS = nbt.NbtSpec.Spec(DimensionCodecDimensionTypeElement);
pub const Tags = serde.PrefixedArray(Ds, VarInt, struct {
tag_type: Identifier,
tags: serde.PrefixedArray(Ds, VarInt, TagEntries),
});
pub const TagEntries = Ds.Spec(struct {
tag_name: Identifier,
entries: serde.PrefixedArray(Ds, VarInt, VarInt),
});
pub const PlayerInfo = serde.TaggedUnion(Ds, VarInt, union(PlayerInfoAction) {
pub const PlayerInfoAction = enum(i32) {
add_player = 0,
update_gamemode = 1,
update_latency = 2,
update_display_name = 3,
remove_player = 4,
};
add_player: PlayerInfoVariant(struct {
name: PStringMax(16),
properties: serde.PrefixedArray(Ds, VarInt, PlayerProperty),
gamemode: Gamemode,
ping: VarInt,
display_name: ?ChatString,
}),
update_gamemode: PlayerInfoVariant(Gamemode),
update_latency: PlayerInfoVariant(VarInt),
update_display_name: PlayerInfoVariant(?ChatString),
remove_player: PlayerInfoVariant(void),
pub fn PlayerInfoVariant(comptime T: type) type {
return serde.PrefixedArray(Ds, VarInt, struct {
uuid: UuidS,
data: T,
});
}
});
pub const PlayerProperty = Ds.Spec(struct {
name: PStringMax(32767),
value: PStringMax(32767),
signature: ?PStringMax(32767),
});
pub const BitSet = struct {
pub const UserType = std.DynamicBitSetUnmanaged;
const mask_size = @bitSizeOf(std.DynamicBitSetUnmanaged.MaskInt);
const ratio = 64 / mask_size;
pub fn write(self: UserType, writer: anytype) !void {
const total_masks = (self.bit_length + (mask_size - 1)) / mask_size;
const total_longs = (total_masks + (ratio - 1)) / ratio;
try VarInt.write(@intCast(i32, total_longs), writer);
var i: usize = 0;
while (i < total_masks) : (i += ratio) {
var current_long: u64 = 0;
blk: {
comptime var j = 0;
inline while (j < ratio) : (j += 1) {
if (i + j < total_masks) {
current_long = (current_long << @truncate(u6, mask_size)) | self.masks[i];
} else {
break :blk;
}
}
}
try writer.writeIntBig(i64, @bitCast(i64, current_long)); // might not need to bit cast
}
}
pub fn deserialize(alloc: Allocator, reader: anytype) !UserType {
const len = @intCast(usize, try VarInt.deserialize(alloc, reader));
var bitset = UserType.initEmpty(alloc, len * 64);
errdefer bitset.deinit(alloc);
//const total_masks = (len + (mask_size - 1)) / mask_size;
var i: usize = 0;
while (i < len) : (i += 1) {
var long = @bitCast(u64, try reader.readIntBig(i64));
comptime var j = 0;
inline while (j < ratio) : (j += 1) {
bitset.masks[i + j] = @truncate(UserType.MaskInt, long);
long = long << mask_size;
}
}
return bitset;
}
pub fn deinit(self: UserType, alloc: Allocator) void {
self.deinit(alloc);
}
pub fn size(self: UserType) usize {
const total_masks = (self.bit_length + (mask_size - 1)) / mask_size;
const total_longs = (total_masks + (ratio - 1)) / ratio;
return total_longs * @sizeOf(i64) + VarInt.size(@intCast(i32, total_longs));
}
};
pub const Position = packed struct {
y: i12,
z: i26,
x: i26,
};
test "packed position" {
const pos = Position{
.x = 5,
.z = -12,
.y = -1,
};
const x = @intCast(u64, @bitCast(u26, pos.x));
const z = @intCast(u64, @bitCast(u26, pos.z));
const y = @intCast(u64, @bitCast(u12, pos.y));
const expected: u64 = ((x & 0x3FFFFFF) << 38) | ((z & 0x3FFFFFF) << 12) | (y & 0xFFF);
try testing.expectEqual(expected, @bitCast(u64, pos));
}
pub const ChatMode = enum(i32) {
Enabled = 0,
CommandsOnly = 1,
Hidden = 2,
};
pub const DisplayedSkinParts = packed struct {
cape: bool,
jacket: bool,
left_sleeve: bool,
right_sleeve: bool,
left_pants_leg: bool,
right_pants_leg: bool,
hat: bool,
};
pub const MainHand = enum(i32) {
Left = 0,
Right = 1,
};
pub const Hand = enum(i32) {
Main = 0,
Off = 1,
};
pub const ClientStatus = enum(i32) {
PerformRespawn = 0,
RequestStats = 1,
};
pub const EntityActionId = enum(i32) {
StartSneaking = 0,
StopSneaking = 1,
LeaveBed = 2,
StartSprinting = 3,
StopSprinting = 4,
StartJumpWithHorse = 5,
StopJumpWithHorse = 6,
OpenHorseInventory = 7,
StartFlyingWithElytra = 8,
};
pub const PlayerDiggingStatus = enum(i32) {
Started = 0,
Cancelled = 1,
Finished = 2,
DropItemStack = 3,
DropItem = 4,
ShootArrowOrFinishEating = 5,
SwapItemInHand = 6,
};
pub const BlockFace = enum(u8) {
Bottom = 0,
Top = 1,
North = 2,
South = 3,
West = 4,
East = 5,
};
pub const ChatPosition = enum(u8) {
Chat = 0,
SystemMessage = 1,
GameInfo = 2,
};
pub const ClientSettings = Ds.Spec(struct {
locale: PStringMax(16),
view_distance: i8,
chat_mode: serde.Enum(Ds, VarInt, ChatMode),
chat_colors: bool,
displayed_skin_parts: DisplayedSkinParts,
main_hand: serde.Enum(Ds, VarInt, MainHand),
enable_text_filtering: bool,
allow_server_listings: bool,
});
pub const Ds = serde.DefaultSpec;
pub const H = struct {
pub const SB = serde.TaggedUnion(Ds, VarInt, union(PacketIds) {
pub const PacketIds = enum(i32) {
handshake = 0x00,
legacy = 0xFE,
};
handshake: struct {
protocol_version: VarInt,
server_address: PStringMax(255),
server_port: u16,
next_state: serde.Enum(Ds, VarInt, NextState),
},
legacy: void,
pub const NextState = enum(i32) {
Status = 0x01,
Login = 0x02,
};
});
};
pub const S = struct {
pub const SB = serde.TaggedUnion(Ds, VarInt, union(PacketIds) {
pub const PacketIds = enum(i32) {
request = 0x00,
ping = 0x01,
};
request: void,
ping: i64,
});
pub const CB = serde.TaggedUnion(Ds, VarInt, union(PacketIds) {
pub const PacketIds = enum(i32) {
response = 0x00,
pong = 0x01,
};
response: PStringMax(32767),
pong: i64,
});
};
pub const L = struct {
pub const SB = serde.TaggedUnion(Ds, VarInt, union(PacketIds) {
pub const PacketIds = enum(i32) {
login_start = 0x00,
encryption_response = 0x01,
login_plugin_response = 0x02,
};
login_start: PStringMax(16),
encryption_response: struct {
shared_secret: serde.PrefixedArray(Ds, VarInt, u8),
verify_token: serde.PrefixedArray(Ds, VarInt, u8),
},
login_plugin_response: struct {
message_id: VarInt,
data: ?serde.Remaining,
},
});
pub const CB = serde.TaggedUnion(Ds, VarInt, union(PacketIds) {
pub const PacketIds = enum(i32) {
disconnect = 0x00,
encryption_request = 0x01,
login_success = 0x02,
set_compression = 0x03,
login_plugin_request = 0x04,
};
disconnect: ChatString,
encryption_request: struct {
server_id: PStringMax(20),
public_key: serde.PrefixedArray(Ds, VarInt, u8),
verify_token: serde.PrefixedArray(Ds, VarInt, u8),
},
login_success: struct {
uuid: UuidS,
username: PStringMax(16),
},
set_compression: VarInt,
login_plugin_request: struct {
message_id: VarInt,
channel: Identifier,
data: serde.Remaining,
},
});
};
pub const P = struct {
pub const SB = serde.TaggedUnion(Ds, VarInt, union(PacketIds) {
pub const PacketIds = enum(i32) {
teleport_confirm = 0x00,
chat_message = 0x03,
client_status = 0x04,
client_settings = 0x05,
close_window = 0x09,
plugin_message = 0x0A,
keep_alive = 0x0F,
player_position = 0x11,
player_position_and_rotation = 0x12,
player_rotation = 0x13,
player_movement = 0x14,
player_abilities = 0x19,
player_digging = 0x1A,
entity_action = 0x1B,
held_item_change = 0x25,
creative_inventory_action = 0x28,
animation = 0x2C,
player_block_placement = 0x2E,
use_item = 0x2F,
};
teleport_confirm: VarInt,
chat_message: PStringMax(256),
client_status: serde.Enum(Ds, VarInt, ClientStatus),
client_settings: ClientSettings,
close_window: u8,
plugin_message: struct {
channel: Identifier,
data: serde.Remaining,
},
keep_alive: i64,
player_position: struct {
x: f64,
y: f64,
z: f64,
on_ground: bool,
},
player_position_and_rotation: struct {
x: f64,
y: f64,
z: f64,
yaw: f32,
pitch: f32,
on_ground: bool,
},
player_rotation: struct {
yaw: f32,
pitch: f32,
on_ground: bool,
},
player_movement: bool,
player_abilities: packed struct {
// spec just says for flying but im going to assume it includes the other stuff
invulnerable: bool,
flying: bool,
allow_flying: bool,
creative_mode: bool,
},
player_digging: struct {
status: serde.Enum(Ds, VarInt, PlayerDiggingStatus),
location: Position,
face: BlockFace,
},
entity_action: struct {
entity_id: VarInt,
action_id: serde.Enum(Ds, VarInt, EntityActionId),
jump_boost: VarInt,
},
held_item_change: i16,
creative_inventory_action: struct {
slot: i16,
clicked_item: Slot,
},
animation: serde.Enum(Ds, VarInt, Hand),
player_block_placement: struct {
hand: serde.Enum(Ds, VarInt, Hand),
location: Position,
face: BlockFace,
cursor_position_x: f32,
cursor_position_y: f32,
cursor_position_z: f32,
inside_block: bool,
},
use_item: serde.Enum(Ds, VarInt, Hand),
});
pub const CB = serde.TaggedUnion(Ds, VarInt, union(PacketIds) {
pub const PacketIds = enum(i32) {
spawn_player = 0x04,
server_difficulty = 0x0E,
chat_message = 0x0F,
declare_commands = 0x12,
plugin_message = 0x18,
disconnect = 0x1A,
entity_status = 0x1B,
keep_alive = 0x21,
chunk_data_and_update_light = 0x22,
join_game = 0x26,
entity_position = 0x29,
entity_position_and_rotation = 0x2A,
entity_rotation = 0x2B,
player_abilities = 0x32,
player_info = 0x36,
player_position_and_look = 0x38,
unlock_recipes = 0x39,
destroy_entities = 0x3A,
entity_head_look = 0x3E,
world_border_center = 0x42,
world_border_lerp_size = 0x43,
world_border_size = 0x44,
world_border_warning_delay = 0x45,
world_border_warning_reach = 0x46,
held_item_change = 0x48,
update_view_position = 0x49,
entity_teleport = 0x62,
spawn_position = 0x4B,
declare_recipes = 0x66,
tags = 0x67,
};
spawn_player: struct {
entity_id: VarInt,
player_uuid: UuidS,
x: f64,
y: f64,
z: f64,
yaw: u8,
pitch: u8,
},
server_difficulty: struct {
difficulty: Difficulty,
difficulty_locked: bool,
},
chat_message: struct {
message: ChatString,
position: ChatPosition,
sender: UuidS,
},
declare_commands: struct {
nodes: serde.PrefixedArray(Ds, VarInt, CommandNode),
root_index: VarInt,
},
plugin_message: struct {
channel: Identifier,
data: serde.Remaining,
},
disconnect: ChatString,
entity_status: struct {
entity_id: i32,
entity_status: i8,
},
keep_alive: i64,
chunk_data_and_update_light: struct {
chunk_x: i32,
chunk_z: i32,
heightmaps: nbt.Named(struct {
MOTION_BLOCKING: []i64,
WORLD_SURFACE: ?[]i64,
}, ""),
data: serde.SizePrefixedArray(Ds, VarInt, chunk.ChunkSection),
block_entities: serde.PrefixedArray(Ds, VarInt, chunk.BlockEntity),
trust_edges: bool,
sky_light_mask: BitSet,
block_light_mask: BitSet,
empty_sky_light_mask: BitSet,
empty_block_light_mask: BitSet,
sky_light_arrays: serde.PrefixedArray(Ds, VarInt, serde.PrefixedArray(Ds, VarInt, u8)),
block_light_arrays: serde.PrefixedArray(Ds, VarInt, serde.PrefixedArray(Ds, VarInt, u8)),
},
join_game: struct {
entity_id: i32,
is_hardcore: bool,
gamemode: Gamemode,
previous_gamemode: PreviousGamemode,
dimension_names: serde.PrefixedArray(Ds, VarInt, Identifier),
dimension_codec: nbt.Named(DimensionCodecS, ""),
dimension: nbt.Named(DimensionCodecTypeElementS, ""),
dimension_name: Identifier,
hashed_seed: i64,
max_players: VarInt,
view_distance: VarInt,
simulation_distance: VarInt,
reduced_debug_info: bool,
enable_respawn_screen: bool,
is_debug: bool,
is_flat: bool,
},
entity_position: struct {
entity_id: VarInt,
dx: i16,
dy: i16,
dz: i16,
on_ground: bool,
},
entity_position_and_rotation: struct {
entity_id: VarInt,
dx: i16,
dy: i16,
dz: i16,
yaw: u8,
pitch: u8,
on_ground: bool,
},
entity_rotation: struct {
entity_id: VarInt,
yaw: u8,
pitch: u8,
on_ground: bool,
},
player_abilities: struct {
flags: packed struct {
invulnerable: bool,
flying: bool,
allow_flying: bool,
creative_mode: bool,
},
flying_speed: f32,
field_of_view_modifier: f32,
},
player_info: PlayerInfo,
player_position_and_look: struct {
x: f64,
y: f64,
z: f64,
yaw: f32,
pitch: f32,
relative: packed struct {
x: bool,
y: bool,
z: bool,
y_rot: bool,
x_rot: bool,
},
teleport_id: VarInt,
dismount_vehicle: bool,
},
unlock_recipes: serde.TaggedUnion(Ds, VarInt, union(UnlockRecipesAction) {
pub const UnlockRecipesAction = enum(i32) {
Init = 0,
Add = 1,
Remove = 2,
};
pub fn UnlockRecipesVariant(comptime T: type) type {
return struct {
crafting_recipe_book_open: bool,
crafting_recipe_book_filter_active: bool,
smelting_recipe_book_open: bool,
smelting_recipe_book_filter_active: bool,
blast_furnace_recipe_book_open: bool,
blast_furnace_recipe_book_filter_active: bool,
smoker_recipe_book_open: bool,
smoker_recipe_book_filter_active: bool,
recipe_ids: serde.PrefixedArray(Ds, VarInt, Identifier),
recipe_ids_2: T,
};
}
Init: UnlockRecipesVariant(serde.PrefixedArray(Ds, VarInt, Identifier)),
Add: UnlockRecipesVariant(void),
Remove: UnlockRecipesVariant(void),
}),
destroy_entities: serde.PrefixedArray(Ds, VarInt, VarInt),
entity_head_look: struct {
entity_id: VarInt,
yaw: u8,
},
world_border_center: struct {
x: f64,
z: f64,
},
world_border_lerp_size: struct {
old_diameter: f64,
new_diameter: f64,
speed: VarLong,
},
world_border_size: f64,
world_border_warning_delay: VarInt,
world_border_warning_reach: VarInt,
held_item_change: i8,
update_view_position: struct {
chunk_x: VarInt,
chunk_z: VarInt,
},
entity_teleport: struct {
entity_id: VarInt,
x: f64,
y: f64,
z: f64,
yaw: u8,
pitch: u8,
on_ground: bool,
},
spawn_position: struct {
location: Position,
angle: f32,
},
declare_recipes: serde.PrefixedArray(Ds, VarInt, Recipe),
tags: Tags,
});
};
fn testPacket(comptime PacketType: type, alloc: Allocator, data: []const u8) !PacketType.UserType {
var stream = std.io.fixedBufferStream(data);
var result = try PacketType.deserialize(alloc, stream.reader());
errdefer PacketType.deinit(result, alloc);
var buffer = std.ArrayList(u8).init(alloc);
defer buffer.deinit();
try PacketType.write(result, buffer.writer());
try testing.expectEqualSlices(u8, data, buffer.items);
return result;
}
test "protocol" {
const alloc = testing.allocator;
var packet: P.SB.UserType = undefined;
packet = try testPacket(P.SB, alloc, &[_]u8{ 0x0A, 2, 'h', 'i', 't', 'h', 'e', 'r', 'e' });
try testing.expectEqualStrings("hi", packet.plugin_message.channel);
try testing.expectEqualSlices(u8, "there", packet.plugin_message.data);
P.SB.deinit(packet, alloc);
}
|
src/mcproto.zig
|
const std = @import("std");
// source: https://github.com/raysan5/raylib/blob/cba412cc313e4f95eafb3fba9303400e65c98984/src/str.c#L1615
pub fn nextCodepoint(str: []const u8, bytesprocessed: *i32) i32 {
var code: i32 = 0x3f; // codepoint (defaults to '?');
var octet: i32 = @intCast(i32, str[0]); // the first UTF8 octet
bytesprocessed.* = 1;
if (octet <= 0x7f) {
// Only one octet (ASCII range x00-7F)
code = str[0];
} else if ((octet & 0xe0) == 0xc0) {
// Two octets
// [0]xC2-DF [1]UTF8-tail(x80-BF)
var octet1 = str[1];
if ((octet1 == 0) or ((octet1 >> 6) != 2)) {
bytesprocessed.* = 2;
return code;
} // Unexpected sequence
if ((octet >= 0xc2) and (octet <= 0xdf)) {
code = ((octet & 0x1f) << 6) | (octet1 & 0x3f);
bytesprocessed.* = 2;
}
} else if ((octet & 0xf0) == 0xe0) {
// Three octets
var octet1 = str[1];
var octet2: u8 = 0;
if ((octet1 == 0) or ((octet1 >> 6) != 2)) {
bytesprocessed.* = 2;
return code;
} // Unexpected sequence
octet2 = str[2];
if ((octet2 == 0) or ((octet2 >> 6) != 2)) {
bytesprocessed.* = 3;
return code;
} // Unexpected sequence
//
// [0]xE0 [1]xA0-BF [2]UTF8-tail(x80-BF)
// [0]xE1-EC [1]UTF8-tail [2]UTF8-tail(x80-BF)
// [0]xED [1]x80-9F [2]UTF8-tail(x80-BF)
// [0]xEE-EF [1]UTF8-tail [2]UTF8-tail(x80-BF)
//
if (((octet == 0xe0) and !((octet1 >= 0xa0) and (octet1 <= 0xbf))) or
((octet == 0xed) and !((octet1 >= 0x80) and (octet1 <= 0x9f))))
{
bytesprocessed.* = 2;
return code;
}
if ((octet >= 0xe0) and (0 <= 0xef)) {
code = ((octet & 0xf) << 12) | ((octet1 & 0x3f) << 6) | (octet2 & 0x3f);
bytesprocessed.* = 3;
}
} else if ((octet & 0xf8) == 0xf0) {
// Four octets
if (octet > 0xf4)
return code;
var octet1 = str[1];
var octet2: u8 = 0;
var octet3: u8 = 0;
if ((octet1 == 0) or ((octet1 >> 6) != 2)) {
bytesprocessed.* = 2;
return code;
} // Unexpected sequence
octet2 = str[2];
if ((octet2 == 0) or ((octet2 >> 6) != 2)) {
bytesprocessed.* = 3;
return code;
} // Unexpected sequence
octet3 = str[3];
if ((octet3 == 0) or ((octet3 >> 6) != 2)) {
bytesprocessed.* = 4;
return code;
} // Unexpected sequence
//
// [0]xF0 [1]x90-BF [2]UTF8-tail [3]UTF8-tail
// [0]xF1-F3 [1]UTF8-tail [2]UTF8-tail [3]UTF8-tail
// [0]xF4 [1]x80-8F [2]UTF8-tail [3]UTF8-tail
//
if (((octet == 0xf0) and !((octet1 >= 0x90) and (octet1 <= 0xbf))) or
((octet == 0xf4) and !((octet1 >= 0x80) and (octet1 <= 0x8f))))
{
bytesprocessed.* = 2;
return code;
} // Unexpected sequence
if (octet >= 0xf0) {
code = ((octet & 0x7) << 18) | ((octet1 & 0x3f) << @truncate(u3, 12)) |
((octet2 & 0x3f) << 6) | (octet3 & 0x3f);
bytesprocessed.* = 4;
}
}
// codepoints after U+10ffff are invalid
if (code > 0x10ffff) code = 0x3f;
return code;
}
|
src/core/utf8.zig
|
const std = @import("std");
const builtin = @import("builtin");
const os = builtin.os;
const fmt = std.fmt;
const mem = std.mem;
const testing = std.testing;
const io = std.io;
const heap = std.heap;
const fs = std.fs;
const clap = @import("clap");
const version = "0.1.0";
const maxLineLength = 4096;
pub fn main() anyerror!void {
var buffer: [maxLineLength]u8 = undefined;
var fba = heap.FixedBufferAllocator.init(&buffer);
const allocator = fba.allocator();
const config: Config = parseArgs(allocator) catch |err| switch (err) {
error.EarlyExit => return,
error.FileNotFound => return,
error.BadArgs => return,
else => @panic("Unknown error"),
};
defer config.deinit();
const stdout = io.getStdOut();
if (config.file) |file| {
try dumpInput(config, file, stdout, allocator);
} else {
const stdin = io.getStdIn();
try dumpInput(config, stdin, stdout, allocator);
}
}
const errors = error {
EarlyExit,
FileNotFound,
BadArgs,
};
const Config = struct {
lines: u32,
file: ?fs.File,
line: ?[]const u8 = null,
token: ?[]const u8 = null,
ignoreExtras: bool,
pub fn deinit(self: @This()) void {
if (self.file) |f| {
f.close();
}
}
};
fn parseArgs(allocator: mem.Allocator) !Config {
const params = comptime [_]clap.Param(clap.Help) {
clap.parseParam("<N> The number of lines to skip") catch unreachable,
clap.parseParam("[<FILE>] The file to read or stdin if not given") catch unreachable,
clap.parseParam("-l, --line <STR> Skip until N lines matching this") catch unreachable,
clap.parseParam("-t, --token <STR> Skip lines until N tokens found") catch unreachable,
clap.parseParam("-i, --ignore-extras Only count the first token on each line") catch unreachable,
clap.parseParam("-h, --help Display this help and exit") catch unreachable,
clap.parseParam("-v, --version Display the version") catch unreachable,
};
var diag = clap.Diagnostic{};
var args = clap.parse(clap.Help, ¶ms, .{ .diagnostic = &diag }) catch |err| {
diag.report(io.getStdErr().writer(), err) catch {};
return error.BadArgs;
};
defer args.deinit();
if (args.flag("--version")) {
std.debug.print("skip version {s}\n", .{ version });
return error.EarlyExit;
}
if (args.flag("--help")) {
try io.getStdErr().writer().print("skip <N> [<FILE>] [-h|--help] [-v|--version]\n", .{});
try clap.help(io.getStdErr().writer(), ¶ms);
return error.EarlyExit;
}
if (args.option("--line")) |_| {
if (args.option("--token")) |_| {
try io.getStdErr().writer().print("Error: only specify one of --line or --token, not both\n", .{});
return error.BadArgs;
}
}
var line: ?[]const u8 = null;
if (args.option("--line")) |match| {
line = try allocator.dupe(u8, match);
}
var token: ?[]const u8 = null;
if (args.option("--token")) |match| {
token = try allocator.dupe(u8, match);
}
var ignoreExtras: bool = false;
if (args.flag("--ignore-extras")) {
if (token) |_| {
ignoreExtras = true;
} else {
try io.getStdErr().writer().print("Error: --ignore-extras requires --token\n", .{});
return error.BadArgs;
}
}
var n: u32 = 0;
var file: ?fs.File = null;
if (args.positionals().len == 0) {
std.debug.print("Number of lines to skip not given. Try skip --help\n", .{});
return error.EarlyExit;
}
if (args.positionals().len >= 1) {
n = try fmt.parseInt(u32, args.positionals()[0], 10);
}
if (args.positionals().len >= 2) {
const filename = args.positionals()[1];
file = fs.cwd().openFile(filename, .{ .read = true, .write = false }) catch |err| switch (err) {
error.FileNotFound => {
try io.getStdErr().writer().print("Error: File not found: {s}\n", .{ filename });
return err;
},
else => return err,
};
}
return Config {
.lines = n,
.file = file,
.line = line,
.token = token,
.ignoreExtras = ignoreExtras,
};
}
fn dumpInput(config: Config, in: fs.File, out: fs.File, allocator: mem.Allocator) !void {
const writer = out.writer();
const reader = in.reader();
var it: LineIterator = lineIterator(reader, allocator);
var c: usize = 0;
while (c < config.lines) {
const line = it.next();
if (line) |memory| {
if (config.line) |match| {
if (mem.eql(u8, match, memory)) {
c += 1;
}
} else {
if (config.token) |token| {
const occurances = mem.count(u8, memory, token);
if (config.ignoreExtras and occurances > 0) {
c += 1;
} else {
c += occurances;
}
} else {
c += 1;
}
}
allocator.free(memory);
} else return;
}
try pumpIterator(&it, writer, allocator);
}
test "dumpInput skip 1 line" {
const file = try fs.cwd().openFile("src/test/two-lines.txt", .{ .read = true, .write = false });
defer file.close();
const tempFile = "zig-cache/test.txt";
const output = try fs.cwd().createFile(tempFile, .{});
defer output.close();
const config = Config{
.lines = 1,
.file = file,
.ignoreExtras = false,
};
try dumpInput(config, file, output, testing.allocator);
const result = try fs.cwd().openFile(tempFile, .{ .read = true });
defer result.close();
var rit = lineIterator(result.reader(), testing.allocator);
const line1 = rit.next().?;
defer testing.allocator.free(line1);
try testing.expectEqualStrings("line 2", line1);
const eof = rit.next();
try testing.expect(eof == null);
}
test "dumpInput skip 2 line 'alpha'" {
const file = try fs.cwd().openFile("src/test/four-lines.txt", .{ .read = true, .write = false });
defer file.close();
const tempFile = "zig-cache/test.txt";
const output = try fs.cwd().createFile(tempFile, .{});
defer output.close();
const config = Config{
.lines = 2,
.file = file,
.line = "alpha",
.ignoreExtras = false,
};
try dumpInput(config, file, output, testing.allocator);
const result = try fs.cwd().openFile(tempFile, .{ .read = true });
defer result.close();
var rit = lineIterator(result.reader(), testing.allocator);
const line1 = rit.next().?;
defer testing.allocator.free(line1);
try testing.expectEqualStrings("gamma", line1);
const eof = rit.next();
try testing.expect(eof == null);
}
fn pumpIterator(it: *LineIterator, writer: fs.File.Writer, allocator: mem.Allocator) !void {
while (it.next()) |line| {
defer allocator.free(line);
try writer.print("{s}\n", .{ windowsSafe(line) });
}
}
test "pumpIterator" {
const file = try fs.cwd().openFile("src/test/two-lines.txt", .{ .read = true, .write = false });
defer file.close();
const tempFile = "zig-cache/test.txt";
const output = try fs.cwd().createFile(tempFile, .{});
defer output.close();
var reader = file.reader();
var it = lineIterator(reader, testing.allocator);
var writer = output.writer();
try pumpIterator(&it, writer, testing.allocator);
const result = try fs.cwd().openFile(tempFile, .{ .read = true });
defer result.close();
var rit = lineIterator(result.reader(), testing.allocator);
const line1 = rit.next().?;
defer testing.allocator.free(line1);
try testing.expectEqualStrings("line 1", line1);
const line2 = rit.next().?;
defer testing.allocator.free(line2);
try testing.expectEqualStrings("line 2", line2);
const eof = rit.next();
try testing.expect(eof == null);
}
const LineIterator = struct {
reader: io.BufferedReader(maxLineLength, fs.File.Reader),
delimiter: u8,
allocator: mem.Allocator,
const Self = @This();
/// Caller owns returned memory
pub fn next(self: *Self) ?[]u8 {
return self.reader.reader().readUntilDelimiterOrEofAlloc(self.allocator, self.delimiter, maxLineLength) catch null;
}
};
fn lineIterator(reader: fs.File.Reader, allocator: mem.Allocator) LineIterator {
return LineIterator {
.reader = io.bufferedReader(reader),
.delimiter = '\n',
.allocator = allocator
};
}
test "lineIterator returns lines in buffer" {
const file = try fs.cwd().openFile("src/test/two-lines.txt", .{ .read = true, .write = false });
defer file.close();
var reader = file.reader();
var it = lineIterator(reader, testing.allocator);
const line1 = it.next().?;
defer testing.allocator.free(line1);
try testing.expectEqualStrings("line 1", line1);
const line2 = it.next().?;
defer testing.allocator.free(line2);
try testing.expectEqualStrings("line 2", line2);
const eof = it.next();
try testing.expect(eof == null);
}
fn windowsSafe(line: []const u8) []const u8 {
// trim annoying windows-only carriage return character
if (os.tag == .windows) {
return mem.trimRight(u8, line, "\r");
}
return line;
}
test "windowsSafe strips carriage return on windows" {
const input = "line\n\r";
const result = windowsSafe(input);
if (os.tag == .windows) {
// strips the carriage return if windows
try testing.expectEqualSlices(u8, "line\n", result);
} else {
// doesn't change the line if not windows
try testing.expectEqualSlices(u8, input, result);
}
}
|
src/main.zig
|
const std = @import("std");
pub const gpu = @import("gpu/build.zig");
const gpu_dawn = @import("gpu-dawn/build.zig");
pub const glfw = @import("glfw/build.zig");
pub fn build(b: *std.build.Builder) void {
const mode = b.standardReleaseOptions();
const target = b.standardTargetOptions(.{});
const gpu_dawn_options = gpu_dawn.Options{
.from_source = b.option(bool, "dawn-from-source", "Build Dawn from source") orelse false,
};
const options = Options{ .gpu_dawn_options = gpu_dawn_options };
const main_tests = b.addTest("src/main.zig");
main_tests.setBuildMode(mode);
main_tests.setTarget(target);
main_tests.addPackage(pkg);
main_tests.addPackage(gpu.pkg);
main_tests.addPackage(glfw.pkg);
link(b, main_tests, options);
const test_step = b.step("test", "Run library tests");
test_step.dependOn(&main_tests.step);
const example = b.addExecutable("hello-triangle", "examples/main.zig");
example.setTarget(target);
example.setBuildMode(mode);
example.addPackage(pkg);
example.addPackage(gpu.pkg);
example.addPackage(glfw.pkg);
link(b, example, options);
example.install();
const example_run_cmd = example.run();
example_run_cmd.step.dependOn(b.getInstallStep());
const example_run_step = b.step("run-example", "Run the example");
example_run_step.dependOn(&example_run_cmd.step);
}
pub const Options = struct {
glfw_options: glfw.Options = .{},
gpu_dawn_options: gpu_dawn.Options = .{},
};
pub const pkg = std.build.Pkg{
.name = "mach",
.path = .{ .path = thisDir() ++ "/src/main.zig" },
.dependencies = &.{ gpu.pkg, glfw.pkg },
};
pub fn link(b: *std.build.Builder, step: *std.build.LibExeObjStep, options: Options) void {
const gpu_options = gpu.Options{
.glfw_options = @bitCast(@import("gpu/libs/mach-glfw/build.zig").Options, options.glfw_options),
.gpu_dawn_options = @bitCast(@import("gpu/libs/mach-gpu-dawn/build.zig").Options, options.gpu_dawn_options),
};
const main_abs = std.fs.path.join(b.allocator, &.{ thisDir(), "src/main.zig" }) catch unreachable;
const lib = b.addStaticLibrary("mach", main_abs);
lib.setBuildMode(step.build_mode);
lib.setTarget(step.target);
lib.addPackage(gpu.pkg);
lib.addPackage(glfw.pkg);
glfw.link(b, lib, options.glfw_options);
gpu.link(b, lib, gpu_options);
lib.install();
glfw.link(b, step, options.glfw_options);
gpu.link(b, step, gpu_options);
}
fn thisDir() []const u8 {
return std.fs.path.dirname(@src().file) orelse ".";
}
|
build.zig
|
const std = @import("std");
const Builder = std.build.Builder;
const LibExeObjStep = std.build.LibExeObjStep;
const Pkg = std.build.Pkg;
pub const EngineConfig = struct {
windowModule: []const u8 = "didot-glfw",
physicsModule: []const u8 = "didot-ode",
/// Whether or not to automatically set the window module depending on the target platform.
/// didot-glfw will be used for Windows and didot-x11 will be used for Linux.
autoWindow: bool = true
};
/// hacky workaround some compiler bug
var graphics_deps: [3]Pkg = undefined;
pub fn addEngineToExe(step: *LibExeObjStep, comptime config: EngineConfig) !void {
var allocator = step.builder.allocator;
const zlm = Pkg {
.name = "zlm",
.path = "zlm/zlm.zig"
};
const image = Pkg {
.name = "didot-image",
.path = "didot-image/image.zig"
};
var windowModule = config.windowModule;
if (config.autoWindow) {
const target = step.target.toTarget().os.tag;
switch (target) {
.linux => {
windowModule = "didot-x11";
},
else => {}
}
}
const windowPath = try std.mem.concat(allocator, u8, &[_][]const u8{windowModule, "/window.zig"});
if (std.mem.eql(u8, windowModule, "didot-glfw")) {
step.linkSystemLibrary("glfw");
step.linkSystemLibrary("c");
}
if (std.mem.eql(u8, windowModule, "didot-x11")) {
step.linkSystemLibrary("X11");
step.linkSystemLibrary("c");
}
const window = Pkg {
.name = "didot-window",
.path = windowPath,
.dependencies = &[_]Pkg{zlm}
};
graphics_deps[0] = window;
graphics_deps[1] = image;
graphics_deps[2] = zlm;
const graphics = Pkg {
.name = "didot-graphics",
.path = "didot-opengl/graphics.zig",
.dependencies = &graphics_deps
};
step.linkSystemLibrary("GL");
const models = Pkg {
.name = "didot-models",
.path = "didot-models/models.zig",
.dependencies = &[_]Pkg{zlm,graphics}
};
const objects = Pkg {
.name = "didot-objects",
.path = "didot-objects/objects.zig",
.dependencies = &[_]Pkg{zlm,graphics}
};
const physics = Pkg {
.name = "didot-physics",
.path = config.physicsModule ++ "/physics.zig",
.dependencies = &[_]Pkg{objects}
};
try @import(config.physicsModule ++ "/build.zig").build(step);
const app = Pkg {
.name = "didot-app",
.path = "didot-app/app.zig",
.dependencies = &[_]Pkg{objects,graphics}
};
step.addPackage(zlm);
step.addPackage(image);
step.addPackage(window);
step.addPackage(graphics);
step.addPackage(objects);
step.addPackage(models);
step.addPackage(app);
//step.addPackage(physics);
}
pub fn build(b: *Builder) !void {
const target = b.standardTargetOptions(.{});
var mode = b.standardReleaseOptions();
const stripExample = b.option(bool, "strip-example", "Attempt to minify examples by stripping them and changing release mode.") orelse false;
const exe = b.addExecutable("didot-example-scene", "examples/kart-and-cubes/example-scene.zig");
exe.setTarget(target);
exe.setBuildMode(if (stripExample) @import("builtin").Mode.ReleaseSmall else mode);
try addEngineToExe(exe, .{
//.windowModule = "didot-x11"
.autoWindow = false
});
exe.single_threaded = stripExample;
exe.strip = stripExample;
exe.install();
if (@hasField(LibExeObjStep, "emit_docs") and false) {
const otest = b.addTest("didot.zig");
otest.emit_docs = true;
//otest.emit_bin = false;
otest.setOutputDir("docs");
try addEngineToExe(otest, .{
.autoWindow = false
});
const test_step = b.step("doc", "Test and document Didot");
test_step.dependOn(&otest.step);
} else {
const no_doc = b.addSystemCommand(&[_][]const u8{"echo", "Please build with the latest version of Zig to be able to emit documentation."});
const no_doc_step = b.step("doc", "Test and document Didot");
no_doc_step.dependOn(&no_doc.step);
}
const run_cmd = exe.run();
run_cmd.step.dependOn(b.getInstallStep());
const run_step = b.step("example", "Test Didot with kart-and-cubes example");
run_step.dependOn(&run_cmd.step);
}
|
build.zig
|
const std = @import("std");
const Image = @import("image.zig").Image;
const printError = @import("../application/print_error.zig").printError;
const ImageHeader = struct {
size: i32,
width: i32,
height: i32,
planes: i16,
bit_count: i16,
compression: i32,
size_image: i32,
xpels_per_meter: i32,
ypels_per_meter: i32,
clr_used: i32,
clr_important: i32,
pub fn read(reader: anytype) !ImageHeader {
var header: ImageHeader = undefined;
header.size = try reader.readIntLittle(i32);
header.width = try reader.readIntLittle(i32);
header.height = try reader.readIntLittle(i32);
header.planes = try reader.readIntLittle(i16);
header.bit_count = try reader.readIntLittle(i16);
header.compression = try reader.readIntLittle(i32);
header.size_image = try reader.readIntLittle(i32);
header.xpels_per_meter = try reader.readIntLittle(i32);
header.ypels_per_meter = try reader.readIntLittle(i32);
header.clr_used = try reader.readIntLittle(i32);
header.clr_important = try reader.readIntLittle(i32);
return header;
}
pub fn write(self: *const ImageHeader, writer: anytype) !void {
try writer.writeIntLittle(i32, self.size);
try writer.writeIntLittle(i32, self.width);
try writer.writeIntLittle(i32, self.height);
try writer.writeIntLittle(i16, self.planes);
try writer.writeIntLittle(i16, self.bit_count);
try writer.writeIntLittle(i32, self.compression);
try writer.writeIntLittle(i32, self.size_image);
try writer.writeIntLittle(i32, self.xpels_per_meter);
try writer.writeIntLittle(i32, self.ypels_per_meter);
try writer.writeIntLittle(i32, self.clr_used);
try writer.writeIntLittle(i32, self.clr_important);
}
};
pub fn check_header(reader: anytype) !bool {
const bmp_signature = [_]u8{ "B", "M" };
const has_header: bool = try reader.isBytes(&bmp_signature);
try reader.skipByes(4 + 2 + 2 + 4);
return has_header;
}
// Without header
// Use check_header to read and check bmp file signature
pub fn parse(reader: anytype, allocator: std.mem.Allocator) !Image {
// Assumes basic 40-byte Windows Image Header
var image_header: ImageHeader = try ImageHeader.read(reader);
const flip: bool = image_header.height >= 0;
// Bmp from ico have height multiplyed by 2. Recalc height from image size
image_header.height = @divExact(image_header.size_image, image_header.width * 4);
var image: Image = undefined;
image.width = @intCast(usize, image_header.width);
image.height = @intCast(usize, image_header.height);
image.data = allocator.alloc(u8, image.width * image.height * 4) catch unreachable;
_ = try reader.readAll(image.data);
if (flip)
image.flip();
return image;
}
pub fn write(writer: anytype, image: Image) !void {
// File Header (14 Bytes)
try writer.writeAll("BM"); // type
try writer.writeIntLittle(u32, 122 + @intCast(u32, image.data.len)); // size
try writer.writeAll("\x00" ** 4); // reserved
try writer.writeIntLittle(u32, 122); // offset
// Image Header (40 Bytes)
var image_header: ImageHeader = .{
.size = 108,
.width = @intCast(i32, image.width),
.height = -@intCast(i32, image.height),
.planes = 1,
.bit_count = 32,
.compression = 3,
.size_image = @intCast(i32, image.data.len),
.xpels_per_meter = 0,
.ypels_per_meter = 0,
.clr_used = 0,
.clr_important = 0,
};
try image_header.write(writer);
// Color Table (68 Bytes)
try writer.writeAll("\x00\x00\xFF\x00"); // Red
try writer.writeAll("\x00\xFF\x00\x00"); // Green
try writer.writeAll("\xFF\x00\x00\x00"); // Blue
try writer.writeAll("\x00\x00\x00\xFF"); // Alpha
try writer.writeAll("\x20\x6E\x69\x57"); // "Win "
try writer.writeAll("\x00" ** 48);
// Pixel Data
try writer.writeAll(image.data);
}
|
src/image/bmp.zig
|
const std = @import("std");
const tools = @import("tools");
const with_trace = false;
const with_dissassemble = false;
const assert = std.debug.assert;
fn trace(comptime fmt: []const u8, args: anytype) void {
if (with_trace) std.debug.print(fmt, args);
}
const Computer = tools.IntCode_Computer;
const Vec2 = tools.Vec2;
const MapTile = u2;
const MapTiles = struct {
const unknown: MapTile = 0;
const empty: MapTile = 1;
const wall: MapTile = 2;
const oxygen: MapTile = 3;
fn tochar(m: MapTile) u8 {
const symbols = [_]u8{ '?', ' ', '#', 'O' };
return symbols[m];
}
};
pub fn run(input: []const u8, allocator: std.mem.Allocator) ![2][]const u8 {
var arena = std.heap.ArenaAllocator.init(allocator);
defer arena.deinit();
const int_count = blk: {
var int_count: usize = 0;
var it = std.mem.split(u8, input, ",");
while (it.next()) |_| int_count += 1;
break :blk int_count;
};
const boot_image = try allocator.alloc(Computer.Data, int_count);
defer allocator.free(boot_image);
{
var it = std.mem.split(u8, input, ",");
var i: usize = 0;
while (it.next()) |n_text| : (i += 1) {
const trimmed = std.mem.trim(u8, n_text, " \n\r\t");
boot_image[i] = try std.fmt.parseInt(Computer.Data, trimmed, 10);
}
}
if (with_dissassemble)
Computer.disassemble(boot_image);
const map_size = 100;
const Map = tools.Map(MapTile, map_size, map_size, true);
var map = Map{ .default_tile = MapTiles.unknown };
var robot_cpu = Computer{
.name = "Robot",
.memory = try arena.allocator().alloc(Computer.Data, 2048),
};
var robot_pos = Vec2{ .x = 0, .y = 0 };
robot_cpu.boot(boot_image);
trace("starting {}\n", .{robot_cpu.name});
_ = async robot_cpu.run();
const Move = struct {
cmd: Computer.Data,
dir: Vec2,
};
const moves = [_]Move{
.{ .cmd = 1, .dir = Vec2{ .x = 0, .y = -1 } },
.{ .cmd = 3, .dir = Vec2{ .x = -1, .y = 0 } },
.{ .cmd = 2, .dir = Vec2{ .x = 0, .y = 1 } },
.{ .cmd = 4, .dir = Vec2{ .x = 1, .y = 0 } },
};
const RobotOut = struct {
const wall: Computer.Data = 0;
const empty: Computer.Data = 1;
const target: Computer.Data = 2;
};
const Node = struct {
state: Computer,
pos: Vec2,
moves: u32,
};
const Agenda = std.ArrayList(Node);
var agenda = Agenda.init(allocator);
defer agenda.deinit();
try agenda.ensureTotalCapacity(100000);
try agenda.append(Node{
.state = robot_cpu,
.pos = robot_pos,
.moves = 1,
});
var target: ?Vec2 = null;
var moves_to_target: u32 = undefined;
// part1: dist to target
while (agenda.items.len > 0) {
const node = agenda.orderedRemove(0);
for (moves) |m| {
const newpos = Vec2{ .x = node.pos.x + m.dir.x, .y = node.pos.y + m.dir.y };
const tile = map.get(newpos) orelse MapTiles.unknown;
if (tile != MapTiles.unknown)
continue;
const cpu = &robot_cpu;
cpu.* = node.state;
cpu.memory = try arena.allocator().alloc(Computer.Data, 2048);
std.mem.copy(Computer.Data, cpu.memory, node.state.memory);
assert(!cpu.is_halted() and cpu.io_mode == .input);
cpu.io_port = m.cmd;
trace("wrting input to {} = {}\n", .{ cpu.name, cpu.io_port });
trace("resuming {}\n", .{cpu.name});
resume cpu.io_runframe;
assert(!cpu.is_halted() and cpu.io_mode == .output);
trace("{} outputs {}\n", .{ cpu.name, cpu.io_port });
switch (cpu.io_port) {
RobotOut.wall => {
map.set(newpos, MapTiles.wall);
var storage: [5000]u8 = undefined;
trace("{} depth={}\n", .{ map.printToBuf(newpos, null, MapTiles.tochar, &storage), node.moves });
continue;
},
RobotOut.empty => {
map.set(newpos, MapTiles.empty);
trace("resuming {}\n", .{cpu.name});
resume cpu.io_runframe;
try agenda.append(Node{
.state = cpu.*,
.pos = newpos,
.moves = node.moves + 1,
});
},
RobotOut.target => {
map.set(newpos, MapTiles.oxygen);
var storage: [5000]u8 = undefined;
trace("{} target depth={}\n", .{ map.printToBuf(newpos, null, MapTiles.tochar, &storage), node.moves });
target = newpos;
moves_to_target = node.moves;
},
else => unreachable,
}
}
}
// part2: seconds for diffusion O2
var seconds: u32 = 0;
var changed = true;
while (changed) {
changed = false;
var map_init = map;
var pos = map.bbox.min;
while (pos.y < map.bbox.max.y) : (pos.y += 1) {
pos.x = map.bbox.min.x;
while (pos.x < map.bbox.max.x) : (pos.x += 1) {
const offset = map.offsetof(pos);
const sq = &map.map[offset];
if (sq.* != MapTiles.empty)
continue;
for (moves) |m| {
const neighbour_pos = Vec2{ .x = pos.x + m.dir.x, .y = pos.y + m.dir.y };
const neighbour_mapoffset = map.offsetof(neighbour_pos);
if (map_init.map[neighbour_mapoffset] == MapTiles.oxygen) {
sq.* = MapTiles.oxygen;
changed = true;
}
}
}
}
if (changed)
seconds += 1;
var storage: [5000]u8 = undefined;
trace("{} seconds={}\n", .{ map.printToBuf(target.?, null, MapTiles.tochar, &storage), seconds });
}
return [_][]const u8{
try std.fmt.allocPrint(allocator, "{}", .{moves_to_target}),
try std.fmt.allocPrint(allocator, "{}", .{seconds}),
};
}
pub const main = tools.defaultMain("2019/day15.txt", run);
|
2019/day15.zig
|
const std = @import("std");
const assert = std.debug.assert;
const pagez = @import("pagez.zig");
const Point = pagez.Point;
const Position = pagez.Position;
const Size = pagez.Size;
fn to16bitColor(r: u8, g: u8, b: u8) [4]u8 {
assert(r < 32);
assert(g < 64);
assert(b < 32);
var color: [4]u8 = undefined;
color[0] = b >> 1;
color[1] = ((b & 0x1) << 7) & ((r & 0xE) << 3);
color[2] = ((r & 0x2) << 2) & ((g & 0xA) >> 4);
color[3] = g & 0xF;
return color;
}
pub fn black() [4]u8 {
return [4]u8{ 0, 0, 0, 0 };
}
pub fn white() [4]u8 {
return if (pagez.bytes_per_pixel == 4) [4]u8{ 255, 255, 255, 255 } else [4]u8{ 0xFF, 0xFF, 0, 0 };
}
pub fn gray() [4]u8 {
return if (pagez.bytes_per_pixel == 4) [4]u8{ 0x7F, 0x7F, 0x7F, 255 } else to16bitColor(16, 32, 16);
}
pub fn blue() [4]u8 {
return if (pagez.bytes_per_pixel == 4) [4]u8{ 255, 0, 0, 255 } else [4]u8{ 0xF8, 0x00, 0, 0 };
}
pub fn green() [4]u8 {
return if (pagez.bytes_per_pixel == 4) [4]u8{ 0, 255, 0, 255 } else [4]u8{ 0x00, 0x2F, 0, 0 };
}
pub fn red() [4]u8 {
return if (pagez.bytes_per_pixel == 4) [4]u8{ 0, 0, 255, 255 } else [4]u8{ 0x02, 0xB0, 0, 0 };
}
pub fn yellow() [4]u8 {
return if (pagez.bytes_per_pixel == 4) [4]u8{ 0, 255, 255, 255 } else [4]u8{ 0x0F, 0xFF, 0, 0 };
}
pub fn magenta() [4]u8 {
return if (pagez.bytes_per_pixel == 4) [4]u8{ 255, 0, 255, 255 } else [4]u8{ 0xF0, 0xFF, 0, 0 };
}
pub fn cyan() [4]u8 {
return if (pagez.bytes_per_pixel == 4) [4]u8{ 255, 255, 0, 255 } else [4]u8{ 0xF8, 0x0F, 0, 0 };
}
pub fn calcOffset(pos: Position) usize {
return (@as(usize, pagez.display_size.x) * @as(usize, pos.y) + @as(usize, pos.x)) *% @as(usize, pagez.bytes_per_pixel);
}
pub fn colorAt(pos: Position) []u8 {
const offset = calcOffset(pos);
var color: [4]u8 = undefined;
var i: u8 = 0;
while (i < pagez.bytes_per_pixel) : (i += 1) color[i] = pagez.bitmap[offset + i];
return color[0..pagez.bytes_per_pixel];
}
pub fn pixel(color: [4]u8, pos: Position) void {
const offset = calcOffset(pos);
var i: u8 = 0;
while (i < pagez.bytes_per_pixel) : (i += 1) pagez.bitmap[offset + i] = color[i];
}
pub fn box(color: [4]u8, pos: Position, size: Size) void {
const bytes: u16 = pagez.bytes_per_pixel;
const offset = calcOffset(pos);
var dx: u16 = 0;
var dy: u16 = 0;
while (dy < size.y) : (dy += 1) {
const y_offset: u32 = dy * pagez.display_size.x * @as(u32, bytes);
while (dx < size.x * bytes) : (dx += bytes) {
var i: u8 = 0;
while (i < bytes) : (i += 1) pagez.bitmap[offset + y_offset + dx + i] = color[i];
}
dx = 0;
}
}
|
libs/core/gui.zig
|
const std = @import("std");
const c = @import("c.zig");
const android = @import("android-bind.zig");
const build_options = @import("build_options");
pub const egl = @import("egl.zig");
pub const JNI = @import("jni.zig").JNI;
const app_log = std.log.scoped(.app_glue);
// Export the flat functions for now
// pub const native = android;
pub usingnamespace android;
const AndroidApp = @import("root").AndroidApp;
pub var sdk_version: c_int = 0;
/// Actual application entry point
export fn ANativeActivity_onCreate(activity: *android.ANativeActivity, savedState: ?[*]u8, savedStateSize: usize) callconv(.C) void {
{
var sdk_ver_str: [92]u8 = undefined;
const len = android.__system_property_get("ro.build.version.sdk", &sdk_ver_str);
if (len <= 0) {
sdk_version = 0;
} else {
const str = sdk_ver_str[0..@intCast(usize, len)];
sdk_version = std.fmt.parseInt(c_int, str, 10) catch 0;
}
}
app_log.debug("Starting on Android Version {}\n", .{
sdk_version,
});
const app = std.heap.c_allocator.create(AndroidApp) catch {
app_log.err("Could not create new AndroidApp: OutOfMemory!\n", .{});
return;
};
activity.callbacks.* = makeNativeActivityGlue(AndroidApp);
app.* = AndroidApp.init(
std.heap.c_allocator,
activity,
if (savedState) |state|
state[0..savedStateSize]
else
null,
) catch |err| {
std.err("Failed to restore app state: {}\n", .{err});
std.heap.c_allocator.destroy(app);
return;
};
app.start() catch |err| {
std.log.err("Failed to start app state: {}\n", .{err});
app.deinit();
std.heap.c_allocator.destroy(app);
return;
};
activity.instance = app;
app_log.debug("Successfully started the app.\n", .{});
}
// // Required by C code for now…
threadlocal var errno: c_int = 0;
export fn __errno_location() *c_int {
return &errno;
}
var recursive_panic = false;
// Android Panic implementation
pub fn panic(message: []const u8, stack_trace: ?*std.builtin.StackTrace) noreturn {
var logger = LogWriter{ .log_level = android.ANDROID_LOG_ERROR };
if (@atomicLoad(bool, &recursive_panic, .SeqCst)) {
logger.writer().print("RECURSIVE PANIC: {s}\n", .{message}) catch {};
while (true) {
std.time.sleep(std.time.ns_per_week);
}
}
@atomicStore(bool, &recursive_panic, true, .SeqCst);
logger.writer().print("PANIC: {s}\n", .{message}) catch {};
const maybe_debug_info = std.debug.getSelfDebugInfo() catch null;
// dumpStackTrace(maybe_debug_info);
{
var count: usize = 0;
var it = std.debug.StackIterator.init(null, null);
while (it.next()) |return_address| {
printSymbolInfoAt(count, maybe_debug_info, return_address);
count += 1;
}
}
_ = stack_trace;
// if (stack_trace) |st| {
// logger.writer().print("{}\n", .{st}) catch {};
// }
// if (std.debug.getSelfDebugInfo()) |debug_info| {
// std.debug.writeCurrentStackTrace(logger.writer(), debug_info, .no_color, null) catch |err| {
// logger.writer().print("failed to write stack trace: {s}\n", .{err}) catch {};
// };
// } else |err| {
// logger.writer().print("failed to get debug info: {s}\n", .{err}) catch {};
// }
logger.writer().writeAll("<-- end of stack trace -->\n") catch {};
std.os.exit(1);
}
const LogWriter = struct {
log_level: c_int,
line_buffer: [8192]u8 = undefined,
line_len: usize = 0,
const Error = error{};
const Writer = std.io.Writer(*LogWriter, Error, write);
fn write(self: *LogWriter, buffer: []const u8) Error!usize {
for (buffer) |char| {
switch (char) {
'\n' => {
self.flush();
},
else => {
if (self.line_len >= self.line_buffer.len - 1) {
self.flush();
}
self.line_buffer[self.line_len] = char;
self.line_len += 1;
},
}
}
return buffer.len;
}
fn flush(self: *LogWriter) void {
if (self.line_len > 0) {
// var buf = std.mem.zeroes([129]u8);
// const msg = std.fmt.bufPrint(&buf, "PRINT({})\x00", .{self.line_len}) catch "PRINT(???)";
// _ = android.__android_log_write(
// self.log_level,
// build_options.app_name.ptr,
// msg.ptr,
// );
std.debug.assert(self.line_len < self.line_buffer.len - 1);
self.line_buffer[self.line_len] = 0;
_ = android.__android_log_write(
self.log_level,
build_options.app_name.ptr,
&self.line_buffer,
);
}
self.line_len = 0;
}
fn writer(self: *LogWriter) Writer {
return Writer{ .context = self };
}
};
// Android Logging implementation
pub fn log(
comptime message_level: std.log.Level,
comptime scope: @Type(.EnumLiteral),
comptime format: []const u8,
args: anytype,
) void {
const level = switch (message_level) {
// => .ANDROID_LOG_VERBOSE,
.debug => android.ANDROID_LOG_DEBUG,
.info => android.ANDROID_LOG_INFO,
.warn => android.ANDROID_LOG_WARN,
.err => android.ANDROID_LOG_ERROR,
};
var logger = LogWriter{
.log_level = level,
};
defer logger.flush();
logger.writer().print("{s}: " ++ format, .{@tagName(scope)} ++ args) catch {};
}
/// Returns a wrapper implementation for the given App type which implements all
/// ANativeActivity callbacks.
fn makeNativeActivityGlue(comptime App: type) android.ANativeActivityCallbacks {
const T = struct {
fn invoke(activity: *android.ANativeActivity, comptime func: []const u8, args: anytype) void {
if (@hasDecl(App, func)) {
if (activity.instance) |instance| {
const result = @call(.{}, @field(App, func), .{@ptrCast(*App, @alignCast(@alignOf(App), instance))} ++ args);
switch (@typeInfo(@TypeOf(result))) {
.ErrorUnion => result catch |err| app_log.emerg("{s} returned error {s}", .{ func, @errorName(err) }),
.Void => {},
.ErrorSet => app_log.emerg("{s} returned error {s}", .{ func, @errorName(result) }),
else => @compileError("callback must return void!"),
}
}
} else {
app_log.debug("ANativeActivity callback {s} not available on {s}", .{ func, @typeName(App) });
}
}
// return value must be created with malloc(), so we pass the c_allocator to App.onSaveInstanceState
fn onSaveInstanceState(activity: *android.ANativeActivity, outSize: *usize) callconv(.C) ?[*]u8 {
outSize.* = 0;
if (@hasDecl(App, "onSaveInstanceState")) {
if (activity.instance) |instance| {
const optional_slice = @ptrCast(*App, @alignCast(@alignOf(App), instance)).onSaveInstanceState(std.heap.c_allocator);
if (optional_slice) |slice| {
outSize.* = slice.len;
return slice.ptr;
}
}
} else {
app_log.debug("ANativeActivity callback onSaveInstanceState not available on {s}", .{@typeName(App)});
}
return null;
}
fn onDestroy(activity: *android.ANativeActivity) callconv(.C) void {
if (activity.instance) |instance| {
const app = @ptrCast(*App, @alignCast(@alignOf(App), instance));
app.deinit();
std.heap.c_allocator.destroy(app);
}
}
fn onStart(activity: *android.ANativeActivity) callconv(.C) void {
invoke(activity, "onStart", .{});
}
fn onResume(activity: *android.ANativeActivity) callconv(.C) void {
invoke(activity, "onResume", .{});
}
fn onPause(activity: *android.ANativeActivity) callconv(.C) void {
invoke(activity, "onPause", .{});
}
fn onStop(activity: *android.ANativeActivity) callconv(.C) void {
invoke(activity, "onStop", .{});
}
fn onConfigurationChanged(activity: *android.ANativeActivity) callconv(.C) void {
invoke(activity, "onConfigurationChanged", .{});
}
fn onLowMemory(activity: *android.ANativeActivity) callconv(.C) void {
invoke(activity, "onLowMemory", .{});
}
fn onWindowFocusChanged(activity: *android.ANativeActivity, hasFocus: c_int) callconv(.C) void {
invoke(activity, "onWindowFocusChanged", .{(hasFocus != 0)});
}
fn onNativeWindowCreated(activity: *android.ANativeActivity, window: *android.ANativeWindow) callconv(.C) void {
invoke(activity, "onNativeWindowCreated", .{window});
}
fn onNativeWindowResized(activity: *android.ANativeActivity, window: *android.ANativeWindow) callconv(.C) void {
invoke(activity, "onNativeWindowResized", .{window});
}
fn onNativeWindowRedrawNeeded(activity: *android.ANativeActivity, window: *android.ANativeWindow) callconv(.C) void {
invoke(activity, "onNativeWindowRedrawNeeded", .{window});
}
fn onNativeWindowDestroyed(activity: *android.ANativeActivity, window: *android.ANativeWindow) callconv(.C) void {
invoke(activity, "onNativeWindowDestroyed", .{window});
}
fn onInputQueueCreated(activity: *android.ANativeActivity, input_queue: *android.AInputQueue) callconv(.C) void {
invoke(activity, "onInputQueueCreated", .{input_queue});
}
fn onInputQueueDestroyed(activity: *android.ANativeActivity, input_queue: *android.AInputQueue) callconv(.C) void {
invoke(activity, "onInputQueueDestroyed", .{input_queue});
}
fn onContentRectChanged(activity: *android.ANativeActivity, rect: *const android.ARect) callconv(.C) void {
invoke(activity, "onContentRectChanged", .{rect});
}
};
return android.ANativeActivityCallbacks{
.onStart = T.onStart,
.onResume = T.onResume,
.onSaveInstanceState = T.onSaveInstanceState,
.onPause = T.onPause,
.onStop = T.onStop,
.onDestroy = T.onDestroy,
.onWindowFocusChanged = T.onWindowFocusChanged,
.onNativeWindowCreated = T.onNativeWindowCreated,
.onNativeWindowResized = T.onNativeWindowResized,
.onNativeWindowRedrawNeeded = T.onNativeWindowRedrawNeeded,
.onNativeWindowDestroyed = T.onNativeWindowDestroyed,
.onInputQueueCreated = T.onInputQueueCreated,
.onInputQueueDestroyed = T.onInputQueueDestroyed,
.onContentRectChanged = T.onContentRectChanged,
.onConfigurationChanged = T.onConfigurationChanged,
.onLowMemory = T.onLowMemory,
};
}
inline fn printSymbolInfoAt(st_index: usize, maybe_debug_info: ?*std.debug.DebugInfo, int_addr: usize) void {
var symbol_name_buffer: [1024]u8 = undefined;
var symbol_name: ?[]const u8 = null;
if (maybe_debug_info) |di| {
if (di.getModuleForAddress(int_addr)) |module| {
if (module.getSymbolAtAddress(int_addr)) |symbol| {
// symbol_name_buffer
symbol_name = std.fmt.bufPrint(
&symbol_name_buffer,
"{s} {s} {s}",
.{
symbol.symbol_name,
symbol.compile_unit_name,
fmtMaybeLineInfo(symbol.line_info),
},
) catch symbol_name;
} else |_| {}
} else |_| {}
}
std.log.info("#{d:0>2}: 0x{X:0>8} {s}", .{
st_index,
int_addr,
symbol_name,
});
}
fn realFmtMaybeLineInfo(self: ?std.debug.LineInfo, comptime fmt: []const u8, options: std.fmt.FormatOptions, writer: anytype) !void {
_ = fmt;
_ = options;
if (self) |li| {
try writer.print("{s}:{d}:{d}", .{
li.file_name,
li.line,
li.column,
});
} else {
try writer.writeAll("<no line info>");
}
}
fn fmtMaybeLineInfo(li: ?std.debug.LineInfo) std.fmt.Formatter(realFmtMaybeLineInfo) {
return std.fmt.Formatter(realFmtMaybeLineInfo){
.data = li,
};
}
|
src/android-support.zig
|
const std = @import("std");
const os = std.os;
const fs = std.fs;
const proto = @import("protocol.zig");
const wire = @import("wire.zig");
const Header = @import("wire.zig").Header;
const WireBuffer = @import("wire.zig").WireBuffer;
const Connection = @import("connection.zig").Connection;
// TODO: think up a better name for this
pub const Connector = struct {
file: fs.File = undefined,
// TODO: we're going to run into trouble real fast if we reallocate the buffers
// and we have a bunch of copies of Connector everywhere. I think we just
// need to store a pointer to the Connection
rx_buffer: WireBuffer = undefined,
tx_buffer: WireBuffer = undefined,
connection: *Connection = undefined,
channel: u16,
const Self = @This();
pub fn sendHeader(self: *Self, size: u64, class: u16) !void {
self.tx_buffer.writeHeader(self.channel, size, class);
_ = try std.os.write(self.file.handle, self.tx_buffer.extent());
self.tx_buffer.reset();
}
pub fn sendBody(self: *Self, body: []const u8) !void {
self.tx_buffer.writeBody(self.channel, body);
_ = try std.os.write(self.file.handle, self.tx_buffer.extent());
self.tx_buffer.reset();
}
pub fn sendHeartbeat(self: *Self) !void {
self.tx_buffer.writeHeartbeat();
_ = try std.os.write(self.file.handle, self.tx_buffer.extent());
self.tx_buffer.reset();
std.log.debug("Heartbeat ->", .{});
}
pub fn awaitHeader(conn: *Connector) !Header {
while (true) {
if (!conn.rx_buffer.frameReady()) {
// TODO: do we need to retry read (if n isn't as high as we expect)?
const n = try os.read(conn.file.handle, conn.rx_buffer.remaining());
conn.rx_buffer.incrementEnd(n);
if (conn.rx_buffer.isFull()) conn.rx_buffer.shift();
continue;
}
while (conn.rx_buffer.frameReady()) {
const frame_header = try conn.rx_buffer.readFrameHeader();
switch (frame_header.@"type") {
.Method => {
const method_header = try conn.rx_buffer.readMethodHeader();
if (method_header.class == 10 and method_header.method == 50) {
try proto.Connection.closeOkAsync(conn);
return error.ConnectionClose;
}
if (method_header.class == 20 and method_header.method == 40) {
try proto.Channel.closeOkAsync(conn);
return error.ChannelClose;
}
std.log.debug("awaitHeader: unexpected method {}.{}\n", .{ method_header.class, method_header.method });
return error.ImplementAsyncHandle;
},
.Heartbeat => {
std.log.debug("\t<- Heartbeat", .{});
try conn.rx_buffer.readEOF();
try conn.sendHeartbeat();
},
.Header => {
return conn.rx_buffer.readHeader(frame_header.size);
},
.Body => {
_ = try conn.rx_buffer.readBody(frame_header.size);
},
}
}
}
unreachable;
}
pub fn awaitBody(conn: *Connector) ![]u8 {
while (true) {
if (!conn.rx_buffer.frameReady()) {
// TODO: do we need to retry read (if n isn't as high as we expect)?
const n = try os.read(conn.file.handle, conn.rx_buffer.remaining());
conn.rx_buffer.incrementEnd(n);
if (conn.rx_buffer.isFull()) conn.rx_buffer.shift();
continue;
}
while (conn.rx_buffer.frameReady()) {
const frame_header = try conn.rx_buffer.readFrameHeader();
switch (frame_header.@"type") {
.Method => {
const method_header = try conn.rx_buffer.readMethodHeader();
if (method_header.class == 10 and method_header.method == 50) {
try proto.Connection.closeOkAsync(conn);
return error.ConnectionClose;
}
if (method_header.class == 20 and method_header.method == 40) {
try proto.Channel.closeOkAsync(conn);
return error.ChannelClose;
}
std.log.debug("awaitBody: unexpected method {}.{}\n", .{ method_header.class, method_header.method });
return error.ImplementAsyncHandle;
},
.Heartbeat => {
std.log.debug("\t<- Heartbeat", .{});
try conn.rx_buffer.readEOF();
try conn.sendHeartbeat();
},
.Header => {
_ = try conn.rx_buffer.readHeader(frame_header.size);
},
.Body => {
return conn.rx_buffer.readBody(frame_header.size);
},
}
}
}
unreachable;
}
pub fn awaitMethod(conn: *Self, comptime T: type) !T {
while (true) {
if (!conn.rx_buffer.frameReady()) {
// TODO: do we need to retry read (if n isn't as high as we expect)?
const n = try os.read(conn.file.handle, conn.rx_buffer.remaining());
conn.rx_buffer.incrementEnd(n);
if (conn.rx_buffer.isFull()) conn.rx_buffer.shift();
continue;
}
while (conn.rx_buffer.frameReady()) {
const frame_header = try conn.rx_buffer.readFrameHeader();
switch (frame_header.@"type") {
.Method => {
const method_header = try conn.rx_buffer.readMethodHeader();
if (T.CLASS == method_header.class and T.METHOD == method_header.method) {
return T.read(conn);
} else {
if (method_header.class == 10 and method_header.method == 50) {
_ = try proto.Connection.Close.read(conn);
try proto.Connection.closeOkAsync(conn);
return error.ConnectionClose;
}
if (method_header.class == 20 and method_header.method == 40) {
_ = try proto.Channel.Close.read(conn);
try proto.Channel.closeOkAsync(conn);
return error.ChannelClose;
}
std.log.debug("awaitBody: unexpected method {}.{}\n", .{ method_header.class, method_header.method });
return error.ImplementAsyncHandle;
}
},
.Heartbeat => {
std.log.debug("\t<- Heartbeat", .{});
try conn.rx_buffer.readEOF();
try conn.sendHeartbeat();
},
.Header => {
_ = try conn.rx_buffer.readHeader(frame_header.size);
},
.Body => {
_ = try conn.rx_buffer.readBody(frame_header.size);
},
}
}
}
unreachable;
}
};
|
src/connector.zig
|
const std = @import("std.zig");
const debug = std.debug;
const assert = debug.assert;
const testing = std.testing;
const mem = std.mem;
const Allocator = mem.Allocator;
/// A contiguous, growable list of items in memory.
/// This is a wrapper around an array of T values. Initialize with `init`.
pub fn ArrayList(comptime T: type) type {
return ArrayListAligned(T, null);
}
pub fn ArrayListAligned(comptime T: type, comptime alignment: ?u29) type {
if (alignment) |a| {
if (a == @alignOf(T)) {
return ArrayListAligned(T, null);
}
}
return struct {
const Self = @This();
/// Content of the ArrayList
items: Slice,
capacity: usize,
allocator: *Allocator,
pub const Slice = if (alignment) |a| ([]align(a) T) else []T;
pub const SliceConst = if (alignment) |a| ([]align(a) const T) else []const T;
/// Deinitialize with `deinit` or use `toOwnedSlice`.
pub fn init(allocator: *Allocator) Self {
return Self{
.items = &[_]T{},
.capacity = 0,
.allocator = allocator,
};
}
/// Initialize with capacity to hold at least num elements.
/// Deinitialize with `deinit` or use `toOwnedSlice`.
pub fn initCapacity(allocator: *Allocator, num: usize) !Self {
var self = Self.init(allocator);
const new_memory = try self.allocator.allocAdvanced(T, alignment, num, .at_least);
self.items.ptr = new_memory.ptr;
self.capacity = new_memory.len;
return self;
}
/// Release all allocated memory.
pub fn deinit(self: Self) void {
self.allocator.free(self.allocatedSlice());
}
pub const span = @compileError("deprecated: use `items` field directly");
pub const toSlice = @compileError("deprecated: use `items` field directly");
pub const toSliceConst = @compileError("deprecated: use `items` field directly");
pub const at = @compileError("deprecated: use `list.items[i]`");
pub const ptrAt = @compileError("deprecated: use `&list.items[i]`");
pub const setOrError = @compileError("deprecated: use `if (i >= list.items.len) return error.OutOfBounds else list.items[i] = item`");
pub const set = @compileError("deprecated: use `list.items[i] = item`");
pub const swapRemoveOrError = @compileError("deprecated: use `if (i >= list.items.len) return error.OutOfBounds else list.swapRemove(i)`");
/// ArrayList takes ownership of the passed in slice. The slice must have been
/// allocated with `allocator`.
/// Deinitialize with `deinit` or use `toOwnedSlice`.
pub fn fromOwnedSlice(allocator: *Allocator, slice: Slice) Self {
return Self{
.items = slice,
.capacity = slice.len,
.allocator = allocator,
};
}
pub fn toUnmanaged(self: Self) ArrayListAlignedUnmanaged(T, alignment) {
return .{ .items = self.items, .capacity = self.capacity };
}
/// The caller owns the returned memory. ArrayList becomes empty.
pub fn toOwnedSlice(self: *Self) Slice {
const allocator = self.allocator;
const result = allocator.shrink(self.allocatedSlice(), self.items.len);
self.* = init(allocator);
return result;
}
/// Insert `item` at index `n` by moving `list[n .. list.len]` to make room.
/// This operation is O(N).
pub fn insert(self: *Self, n: usize, item: T) !void {
try self.ensureCapacity(self.items.len + 1);
self.items.len += 1;
mem.copyBackwards(T, self.items[n + 1 .. self.items.len], self.items[n .. self.items.len - 1]);
self.items[n] = item;
}
/// Insert slice `items` at index `i` by moving `list[i .. list.len]` to make room.
/// This operation is O(N).
pub fn insertSlice(self: *Self, i: usize, items: SliceConst) !void {
try self.ensureCapacity(self.items.len + items.len);
self.items.len += items.len;
mem.copyBackwards(T, self.items[i + items.len .. self.items.len], self.items[i .. self.items.len - items.len]);
mem.copy(T, self.items[i .. i + items.len], items);
}
/// Replace range of elements `list[start..start+len]` with `new_items`
/// grows list if `len < new_items.len`. may allocate
/// shrinks list if `len > new_items.len`
pub fn replaceRange(self: *Self, start: usize, len: usize, new_items: SliceConst) !void {
const after_range = start + len;
const range = self.items[start..after_range];
if (range.len == new_items.len)
mem.copy(T, range, new_items)
else if (range.len < new_items.len) {
const first = new_items[0..range.len];
const rest = new_items[range.len..];
mem.copy(T, range, first);
try self.insertSlice(after_range, rest);
} else {
mem.copy(T, range, new_items);
const after_subrange = start + new_items.len;
for (self.items[after_range..]) |item, i| {
self.items[after_subrange..][i] = item;
}
self.items.len -= len - new_items.len;
}
}
/// Extend the list by 1 element. Allocates more memory as necessary.
pub fn append(self: *Self, item: T) !void {
const new_item_ptr = try self.addOne();
new_item_ptr.* = item;
}
/// Extend the list by 1 element, but asserting `self.capacity`
/// is sufficient to hold an additional item.
pub fn appendAssumeCapacity(self: *Self, item: T) void {
const new_item_ptr = self.addOneAssumeCapacity();
new_item_ptr.* = item;
}
/// Remove the element at index `i` from the list and return its value.
/// Asserts the array has at least one item.
/// This operation is O(N).
pub fn orderedRemove(self: *Self, i: usize) T {
const newlen = self.items.len - 1;
if (newlen == i) return self.pop();
const old_item = self.items[i];
for (self.items[i..newlen]) |*b, j| b.* = self.items[i + 1 + j];
self.items[newlen] = undefined;
self.items.len = newlen;
return old_item;
}
/// Removes the element at the specified index and returns it.
/// The empty slot is filled from the end of the list.
/// This operation is O(1).
pub fn swapRemove(self: *Self, i: usize) T {
if (self.items.len - 1 == i) return self.pop();
const old_item = self.items[i];
self.items[i] = self.pop();
return old_item;
}
/// Append the slice of items to the list. Allocates more
/// memory as necessary.
pub fn appendSlice(self: *Self, items: SliceConst) !void {
try self.ensureCapacity(self.items.len + items.len);
self.appendSliceAssumeCapacity(items);
}
/// Append the slice of items to the list, asserting the capacity is already
/// enough to store the new items.
pub fn appendSliceAssumeCapacity(self: *Self, items: SliceConst) void {
const oldlen = self.items.len;
const newlen = self.items.len + items.len;
self.items.len = newlen;
mem.copy(T, self.items[oldlen..], items);
}
pub usingnamespace if (T != u8) struct {} else struct {
pub const Writer = std.io.Writer(*Self, error{OutOfMemory}, appendWrite);
/// Initializes a Writer which will append to the list.
pub fn writer(self: *Self) Writer {
return .{ .context = self };
}
/// Deprecated: use `writer`
pub const outStream = writer;
/// Same as `append` except it returns the number of bytes written, which is always the same
/// as `m.len`. The purpose of this function existing is to match `std.io.Writer` API.
fn appendWrite(self: *Self, m: []const u8) !usize {
try self.appendSlice(m);
return m.len;
}
};
/// Append a value to the list `n` times.
/// Allocates more memory as necessary.
pub fn appendNTimes(self: *Self, value: T, n: usize) !void {
const old_len = self.items.len;
try self.resize(self.items.len + n);
mem.set(T, self.items[old_len..self.items.len], value);
}
/// Append a value to the list `n` times.
/// Asserts the capacity is enough.
pub fn appendNTimesAssumeCapacity(self: *Self, value: T, n: usize) void {
const new_len = self.items.len + n;
assert(new_len <= self.capacity);
mem.set(T, self.items.ptr[self.items.len..new_len], value);
self.items.len = new_len;
}
/// Adjust the list's length to `new_len`.
/// Does not initialize added items if any.
pub fn resize(self: *Self, new_len: usize) !void {
try self.ensureCapacity(new_len);
self.items.len = new_len;
}
/// Reduce allocated capacity to `new_len`.
/// Invalidates element pointers.
pub fn shrink(self: *Self, new_len: usize) void {
assert(new_len <= self.items.len);
self.items = self.allocator.realloc(self.allocatedSlice(), new_len) catch |e| switch (e) {
error.OutOfMemory => { // no problem, capacity is still correct then.
self.items.len = new_len;
return;
},
};
self.capacity = new_len;
}
/// Reduce length to `new_len`.
/// Invalidates element pointers.
/// Keeps capacity the same.
pub fn shrinkRetainingCapacity(self: *Self, new_len: usize) void {
assert(new_len <= self.items.len);
self.items.len = new_len;
}
pub fn ensureCapacity(self: *Self, new_capacity: usize) !void {
var better_capacity = self.capacity;
if (better_capacity >= new_capacity) return;
while (true) {
better_capacity += better_capacity / 2 + 8;
if (better_capacity >= new_capacity) break;
}
// TODO This can be optimized to avoid needlessly copying undefined memory.
const new_memory = try self.allocator.reallocAtLeast(self.allocatedSlice(), better_capacity);
self.items.ptr = new_memory.ptr;
self.capacity = new_memory.len;
}
/// Increases the array's length to match the full capacity that is already allocated.
/// The new elements have `undefined` values. This operation does not invalidate any
/// element pointers.
pub fn expandToCapacity(self: *Self) void {
self.items.len = self.capacity;
}
/// Increase length by 1, returning pointer to the new item.
/// The returned pointer becomes invalid when the list is resized.
pub fn addOne(self: *Self) !*T {
const newlen = self.items.len + 1;
try self.ensureCapacity(newlen);
return self.addOneAssumeCapacity();
}
/// Increase length by 1, returning pointer to the new item.
/// Asserts that there is already space for the new item without allocating more.
/// The returned pointer becomes invalid when the list is resized.
pub fn addOneAssumeCapacity(self: *Self) *T {
assert(self.items.len < self.capacity);
self.items.len += 1;
return &self.items[self.items.len - 1];
}
/// Resize the array, adding `n` new elements, which have `undefined` values.
/// The return value is an array pointing to the newly allocated elements.
pub fn addManyAsArray(self: *Self, comptime n: usize) !*[n]T {
const prev_len = self.items.len;
try self.resize(self.items.len + n);
return self.items[prev_len..][0..n];
}
/// Resize the array, adding `n` new elements, which have `undefined` values.
/// The return value is an array pointing to the newly allocated elements.
/// Asserts that there is already space for the new item without allocating more.
pub fn addManyAsArrayAssumeCapacity(self: *Self, comptime n: usize) *[n]T {
assert(self.items.len + n <= self.capacity);
const prev_len = self.items.len;
self.items.len += n;
return self.items[prev_len..][0..n];
}
/// Remove and return the last element from the list.
/// Asserts the list has at least one item.
pub fn pop(self: *Self) T {
const val = self.items[self.items.len - 1];
self.items.len -= 1;
return val;
}
/// Remove and return the last element from the list.
/// If the list is empty, returns `null`.
pub fn popOrNull(self: *Self) ?T {
if (self.items.len == 0) return null;
return self.pop();
}
// For a nicer API, `items.len` is the length, not the capacity.
// This requires "unsafe" slicing.
fn allocatedSlice(self: Self) Slice {
return self.items.ptr[0..self.capacity];
}
};
}
/// Bring-your-own allocator with every function call.
/// Initialize directly and deinitialize with `deinit` or use `toOwnedSlice`.
pub fn ArrayListUnmanaged(comptime T: type) type {
return ArrayListAlignedUnmanaged(T, null);
}
pub fn ArrayListAlignedUnmanaged(comptime T: type, comptime alignment: ?u29) type {
if (alignment) |a| {
if (a == @alignOf(T)) {
return ArrayListAlignedUnmanaged(T, null);
}
}
return struct {
const Self = @This();
/// Content of the ArrayList.
items: Slice = &[_]T{},
capacity: usize = 0,
pub const Slice = if (alignment) |a| ([]align(a) T) else []T;
pub const SliceConst = if (alignment) |a| ([]align(a) const T) else []const T;
/// Initialize with capacity to hold at least num elements.
/// Deinitialize with `deinit` or use `toOwnedSlice`.
pub fn initCapacity(allocator: *Allocator, num: usize) !Self {
var self = Self{};
const new_memory = try allocator.allocAdvanced(T, alignment, num, .at_least);
self.items.ptr = new_memory.ptr;
self.capacity = new_memory.len;
return self;
}
/// Release all allocated memory.
pub fn deinit(self: *Self, allocator: *Allocator) void {
allocator.free(self.allocatedSlice());
self.* = undefined;
}
pub fn toManaged(self: *Self, allocator: *Allocator) ArrayListAligned(T, alignment) {
return .{ .items = self.items, .capacity = self.capacity, .allocator = allocator };
}
/// The caller owns the returned memory. ArrayList becomes empty.
pub fn toOwnedSlice(self: *Self, allocator: *Allocator) Slice {
const result = allocator.shrink(self.allocatedSlice(), self.items.len);
self.* = Self{};
return result;
}
/// Insert `item` at index `n`. Moves `list[n .. list.len]`
/// to make room.
pub fn insert(self: *Self, allocator: *Allocator, n: usize, item: T) !void {
try self.ensureCapacity(allocator, self.items.len + 1);
self.items.len += 1;
mem.copyBackwards(T, self.items[n + 1 .. self.items.len], self.items[n .. self.items.len - 1]);
self.items[n] = item;
}
/// Insert slice `items` at index `i`. Moves
/// `list[i .. list.len]` to make room.
/// This operation is O(N).
pub fn insertSlice(self: *Self, allocator: *Allocator, i: usize, items: SliceConst) !void {
try self.ensureCapacity(allocator, self.items.len + items.len);
self.items.len += items.len;
mem.copyBackwards(T, self.items[i + items.len .. self.items.len], self.items[i .. self.items.len - items.len]);
mem.copy(T, self.items[i .. i + items.len], items);
}
/// Replace range of elements `list[start..start+len]` with `new_items`
/// grows list if `len < new_items.len`. may allocate
/// shrinks list if `len > new_items.len`
pub fn replaceRange(self: *Self, allocator: *Allocator, start: usize, len: usize, new_items: SliceConst) !void {
var managed = self.toManaged(allocator);
try managed.replaceRange(start, len, new_items);
self.* = managed.toUnmanaged();
}
/// Extend the list by 1 element. Allocates more memory as necessary.
pub fn append(self: *Self, allocator: *Allocator, item: T) !void {
const new_item_ptr = try self.addOne(allocator);
new_item_ptr.* = item;
}
/// Extend the list by 1 element, but asserting `self.capacity`
/// is sufficient to hold an additional item.
pub fn appendAssumeCapacity(self: *Self, item: T) void {
const new_item_ptr = self.addOneAssumeCapacity();
new_item_ptr.* = item;
}
/// Remove the element at index `i` from the list and return its value.
/// Asserts the array has at least one item.
/// This operation is O(N).
pub fn orderedRemove(self: *Self, i: usize) T {
const newlen = self.items.len - 1;
if (newlen == i) return self.pop();
const old_item = self.items[i];
for (self.items[i..newlen]) |*b, j| b.* = self.items[i + 1 + j];
self.items[newlen] = undefined;
self.items.len = newlen;
return old_item;
}
/// Removes the element at the specified index and returns it.
/// The empty slot is filled from the end of the list.
/// This operation is O(1).
pub fn swapRemove(self: *Self, i: usize) T {
if (self.items.len - 1 == i) return self.pop();
const old_item = self.items[i];
self.items[i] = self.pop();
return old_item;
}
/// Append the slice of items to the list. Allocates more
/// memory as necessary.
pub fn appendSlice(self: *Self, allocator: *Allocator, items: SliceConst) !void {
try self.ensureCapacity(allocator, self.items.len + items.len);
self.appendSliceAssumeCapacity(items);
}
/// Append the slice of items to the list, asserting the capacity is enough
/// to store the new items.
pub fn appendSliceAssumeCapacity(self: *Self, items: SliceConst) void {
const oldlen = self.items.len;
const newlen = self.items.len + items.len;
self.items.len = newlen;
mem.copy(T, self.items[oldlen..], items);
}
/// Same as `append` except it returns the number of bytes written, which is always the same
/// as `m.len`. The purpose of this function existing is to match `std.io.OutStream` API.
/// This function may be called only when `T` is `u8`.
fn appendWrite(self: *Self, allocator: *Allocator, m: []const u8) !usize {
try self.appendSlice(allocator, m);
return m.len;
}
/// Append a value to the list `n` times.
/// Allocates more memory as necessary.
pub fn appendNTimes(self: *Self, allocator: *Allocator, value: T, n: usize) !void {
const old_len = self.items.len;
try self.resize(allocator, self.items.len + n);
mem.set(T, self.items[old_len..self.items.len], value);
}
/// Append a value to the list `n` times.
/// Asserts the capacity is enough.
pub fn appendNTimesAssumeCapacity(self: *Self, value: T, n: usize) void {
const new_len = self.items.len + n;
assert(new_len <= self.capacity);
mem.set(T, self.items.ptr[self.items.len..new_len], value);
self.items.len = new_len;
}
/// Adjust the list's length to `new_len`.
/// Does not initialize added items if any.
pub fn resize(self: *Self, allocator: *Allocator, new_len: usize) !void {
try self.ensureCapacity(allocator, new_len);
self.items.len = new_len;
}
/// Reduce allocated capacity to `new_len`.
/// Invalidates element pointers.
pub fn shrink(self: *Self, allocator: *Allocator, new_len: usize) void {
assert(new_len <= self.items.len);
self.items = allocator.realloc(self.allocatedSlice(), new_len) catch |e| switch (e) {
error.OutOfMemory => { // no problem, capacity is still correct then.
self.items.len = new_len;
return;
},
};
self.capacity = new_len;
}
/// Reduce length to `new_len`.
/// Invalidates element pointers.
/// Keeps capacity the same.
pub fn shrinkRetainingCapacity(self: *Self, new_len: usize) void {
assert(new_len <= self.items.len);
self.items.len = new_len;
}
pub fn ensureCapacity(self: *Self, allocator: *Allocator, new_capacity: usize) !void {
var better_capacity = self.capacity;
if (better_capacity >= new_capacity) return;
while (true) {
better_capacity += better_capacity / 2 + 8;
if (better_capacity >= new_capacity) break;
}
const new_memory = try allocator.reallocAtLeast(self.allocatedSlice(), better_capacity);
self.items.ptr = new_memory.ptr;
self.capacity = new_memory.len;
}
/// Increases the array's length to match the full capacity that is already allocated.
/// The new elements have `undefined` values.
/// This operation does not invalidate any element pointers.
pub fn expandToCapacity(self: *Self) void {
self.items.len = self.capacity;
}
/// Increase length by 1, returning pointer to the new item.
/// The returned pointer becomes invalid when the list is resized.
pub fn addOne(self: *Self, allocator: *Allocator) !*T {
const newlen = self.items.len + 1;
try self.ensureCapacity(allocator, newlen);
return self.addOneAssumeCapacity();
}
/// Increase length by 1, returning pointer to the new item.
/// Asserts that there is already space for the new item without allocating more.
/// The returned pointer becomes invalid when the list is resized.
/// This operation does not invalidate any element pointers.
pub fn addOneAssumeCapacity(self: *Self) *T {
assert(self.items.len < self.capacity);
self.items.len += 1;
return &self.items[self.items.len - 1];
}
/// Resize the array, adding `n` new elements, which have `undefined` values.
/// The return value is an array pointing to the newly allocated elements.
pub fn addManyAsArray(self: *Self, allocator: *Allocator, comptime n: usize) !*[n]T {
const prev_len = self.items.len;
try self.resize(allocator, self.items.len + n);
return self.items[prev_len..][0..n];
}
/// Resize the array, adding `n` new elements, which have `undefined` values.
/// The return value is an array pointing to the newly allocated elements.
/// Asserts that there is already space for the new item without allocating more.
pub fn addManyAsArrayAssumeCapacity(self: *Self, comptime n: usize) *[n]T {
assert(self.items.len + n <= self.capacity);
const prev_len = self.items.len;
self.items.len += n;
return self.items[prev_len..][0..n];
}
/// Remove and return the last element from the list.
/// Asserts the list has at least one item.
/// This operation does not invalidate any element pointers.
pub fn pop(self: *Self) T {
const val = self.items[self.items.len - 1];
self.items.len -= 1;
return val;
}
/// Remove and return the last element from the list.
/// If the list is empty, returns `null`.
/// This operation does not invalidate any element pointers.
pub fn popOrNull(self: *Self) ?T {
if (self.items.len == 0) return null;
return self.pop();
}
/// For a nicer API, `items.len` is the length, not the capacity.
/// This requires "unsafe" slicing.
fn allocatedSlice(self: Self) Slice {
return self.items.ptr[0..self.capacity];
}
};
}
test "std.ArrayList/ArrayListUnmanaged.init" {
{
var list = ArrayList(i32).init(testing.allocator);
defer list.deinit();
testing.expect(list.items.len == 0);
testing.expect(list.capacity == 0);
}
{
var list = ArrayListUnmanaged(i32){};
testing.expect(list.items.len == 0);
testing.expect(list.capacity == 0);
}
}
test "std.ArrayList/ArrayListUnmanaged.initCapacity" {
const a = testing.allocator;
{
var list = try ArrayList(i8).initCapacity(a, 200);
defer list.deinit();
testing.expect(list.items.len == 0);
testing.expect(list.capacity >= 200);
}
{
var list = try ArrayListUnmanaged(i8).initCapacity(a, 200);
defer list.deinit(a);
testing.expect(list.items.len == 0);
testing.expect(list.capacity >= 200);
}
}
test "std.ArrayList/ArrayListUnmanaged.basic" {
const a = testing.allocator;
{
var list = ArrayList(i32).init(a);
defer list.deinit();
{
var i: usize = 0;
while (i < 10) : (i += 1) {
list.append(@intCast(i32, i + 1)) catch unreachable;
}
}
{
var i: usize = 0;
while (i < 10) : (i += 1) {
testing.expect(list.items[i] == @intCast(i32, i + 1));
}
}
for (list.items) |v, i| {
testing.expect(v == @intCast(i32, i + 1));
}
testing.expect(list.pop() == 10);
testing.expect(list.items.len == 9);
list.appendSlice(&[_]i32{ 1, 2, 3 }) catch unreachable;
testing.expect(list.items.len == 12);
testing.expect(list.pop() == 3);
testing.expect(list.pop() == 2);
testing.expect(list.pop() == 1);
testing.expect(list.items.len == 9);
list.appendSlice(&[_]i32{}) catch unreachable;
testing.expect(list.items.len == 9);
// can only set on indices < self.items.len
list.items[7] = 33;
list.items[8] = 42;
testing.expect(list.pop() == 42);
testing.expect(list.pop() == 33);
}
{
var list = ArrayListUnmanaged(i32){};
defer list.deinit(a);
{
var i: usize = 0;
while (i < 10) : (i += 1) {
list.append(a, @intCast(i32, i + 1)) catch unreachable;
}
}
{
var i: usize = 0;
while (i < 10) : (i += 1) {
testing.expect(list.items[i] == @intCast(i32, i + 1));
}
}
for (list.items) |v, i| {
testing.expect(v == @intCast(i32, i + 1));
}
testing.expect(list.pop() == 10);
testing.expect(list.items.len == 9);
list.appendSlice(a, &[_]i32{ 1, 2, 3 }) catch unreachable;
testing.expect(list.items.len == 12);
testing.expect(list.pop() == 3);
testing.expect(list.pop() == 2);
testing.expect(list.pop() == 1);
testing.expect(list.items.len == 9);
list.appendSlice(a, &[_]i32{}) catch unreachable;
testing.expect(list.items.len == 9);
// can only set on indices < self.items.len
list.items[7] = 33;
list.items[8] = 42;
testing.expect(list.pop() == 42);
testing.expect(list.pop() == 33);
}
}
test "std.ArrayList/ArrayListUnmanaged.appendNTimes" {
const a = testing.allocator;
{
var list = ArrayList(i32).init(a);
defer list.deinit();
try list.appendNTimes(2, 10);
testing.expectEqual(@as(usize, 10), list.items.len);
for (list.items) |element| {
testing.expectEqual(@as(i32, 2), element);
}
}
{
var list = ArrayListUnmanaged(i32){};
defer list.deinit(a);
try list.appendNTimes(a, 2, 10);
testing.expectEqual(@as(usize, 10), list.items.len);
for (list.items) |element| {
testing.expectEqual(@as(i32, 2), element);
}
}
}
test "std.ArrayList/ArrayListUnmanaged.appendNTimes with failing allocator" {
const a = testing.failing_allocator;
{
var list = ArrayList(i32).init(a);
defer list.deinit();
testing.expectError(error.OutOfMemory, list.appendNTimes(2, 10));
}
{
var list = ArrayListUnmanaged(i32){};
defer list.deinit(a);
testing.expectError(error.OutOfMemory, list.appendNTimes(a, 2, 10));
}
}
test "std.ArrayList/ArrayListUnmanaged.orderedRemove" {
const a = testing.allocator;
{
var list = ArrayList(i32).init(a);
defer list.deinit();
try list.append(1);
try list.append(2);
try list.append(3);
try list.append(4);
try list.append(5);
try list.append(6);
try list.append(7);
//remove from middle
testing.expectEqual(@as(i32, 4), list.orderedRemove(3));
testing.expectEqual(@as(i32, 5), list.items[3]);
testing.expectEqual(@as(usize, 6), list.items.len);
//remove from end
testing.expectEqual(@as(i32, 7), list.orderedRemove(5));
testing.expectEqual(@as(usize, 5), list.items.len);
//remove from front
testing.expectEqual(@as(i32, 1), list.orderedRemove(0));
testing.expectEqual(@as(i32, 2), list.items[0]);
testing.expectEqual(@as(usize, 4), list.items.len);
}
{
var list = ArrayListUnmanaged(i32){};
defer list.deinit(a);
try list.append(a, 1);
try list.append(a, 2);
try list.append(a, 3);
try list.append(a, 4);
try list.append(a, 5);
try list.append(a, 6);
try list.append(a, 7);
//remove from middle
testing.expectEqual(@as(i32, 4), list.orderedRemove(3));
testing.expectEqual(@as(i32, 5), list.items[3]);
testing.expectEqual(@as(usize, 6), list.items.len);
//remove from end
testing.expectEqual(@as(i32, 7), list.orderedRemove(5));
testing.expectEqual(@as(usize, 5), list.items.len);
//remove from front
testing.expectEqual(@as(i32, 1), list.orderedRemove(0));
testing.expectEqual(@as(i32, 2), list.items[0]);
testing.expectEqual(@as(usize, 4), list.items.len);
}
}
test "std.ArrayList/ArrayListUnmanaged.swapRemove" {
const a = testing.allocator;
{
var list = ArrayList(i32).init(a);
defer list.deinit();
try list.append(1);
try list.append(2);
try list.append(3);
try list.append(4);
try list.append(5);
try list.append(6);
try list.append(7);
//remove from middle
testing.expect(list.swapRemove(3) == 4);
testing.expect(list.items[3] == 7);
testing.expect(list.items.len == 6);
//remove from end
testing.expect(list.swapRemove(5) == 6);
testing.expect(list.items.len == 5);
//remove from front
testing.expect(list.swapRemove(0) == 1);
testing.expect(list.items[0] == 5);
testing.expect(list.items.len == 4);
}
{
var list = ArrayListUnmanaged(i32){};
defer list.deinit(a);
try list.append(a, 1);
try list.append(a, 2);
try list.append(a, 3);
try list.append(a, 4);
try list.append(a, 5);
try list.append(a, 6);
try list.append(a, 7);
//remove from middle
testing.expect(list.swapRemove(3) == 4);
testing.expect(list.items[3] == 7);
testing.expect(list.items.len == 6);
//remove from end
testing.expect(list.swapRemove(5) == 6);
testing.expect(list.items.len == 5);
//remove from front
testing.expect(list.swapRemove(0) == 1);
testing.expect(list.items[0] == 5);
testing.expect(list.items.len == 4);
}
}
test "std.ArrayList/ArrayListUnmanaged.insert" {
const a = testing.allocator;
{
var list = ArrayList(i32).init(a);
defer list.deinit();
try list.append(1);
try list.append(2);
try list.append(3);
try list.insert(0, 5);
testing.expect(list.items[0] == 5);
testing.expect(list.items[1] == 1);
testing.expect(list.items[2] == 2);
testing.expect(list.items[3] == 3);
}
{
var list = ArrayListUnmanaged(i32){};
defer list.deinit(a);
try list.append(a, 1);
try list.append(a, 2);
try list.append(a, 3);
try list.insert(a, 0, 5);
testing.expect(list.items[0] == 5);
testing.expect(list.items[1] == 1);
testing.expect(list.items[2] == 2);
testing.expect(list.items[3] == 3);
}
}
test "std.ArrayList/ArrayListUnmanaged.insertSlice" {
const a = testing.allocator;
{
var list = ArrayList(i32).init(a);
defer list.deinit();
try list.append(1);
try list.append(2);
try list.append(3);
try list.append(4);
try list.insertSlice(1, &[_]i32{ 9, 8 });
testing.expect(list.items[0] == 1);
testing.expect(list.items[1] == 9);
testing.expect(list.items[2] == 8);
testing.expect(list.items[3] == 2);
testing.expect(list.items[4] == 3);
testing.expect(list.items[5] == 4);
const items = [_]i32{1};
try list.insertSlice(0, items[0..0]);
testing.expect(list.items.len == 6);
testing.expect(list.items[0] == 1);
}
{
var list = ArrayListUnmanaged(i32){};
defer list.deinit(a);
try list.append(a, 1);
try list.append(a, 2);
try list.append(a, 3);
try list.append(a, 4);
try list.insertSlice(a, 1, &[_]i32{ 9, 8 });
testing.expect(list.items[0] == 1);
testing.expect(list.items[1] == 9);
testing.expect(list.items[2] == 8);
testing.expect(list.items[3] == 2);
testing.expect(list.items[4] == 3);
testing.expect(list.items[5] == 4);
const items = [_]i32{1};
try list.insertSlice(a, 0, items[0..0]);
testing.expect(list.items.len == 6);
testing.expect(list.items[0] == 1);
}
}
test "std.ArrayList/ArrayListUnmanaged.replaceRange" {
var arena = std.heap.ArenaAllocator.init(testing.allocator);
defer arena.deinit();
const a = &arena.allocator;
const init = [_]i32{ 1, 2, 3, 4, 5 };
const new = [_]i32{ 0, 0, 0 };
const result_zero = [_]i32{ 1, 0, 0, 0, 2, 3, 4, 5 };
const result_eq = [_]i32{ 1, 0, 0, 0, 5 };
const result_le = [_]i32{ 1, 0, 0, 0, 4, 5 };
const result_gt = [_]i32{ 1, 0, 0, 0 };
{
var list_zero = ArrayList(i32).init(a);
var list_eq = ArrayList(i32).init(a);
var list_lt = ArrayList(i32).init(a);
var list_gt = ArrayList(i32).init(a);
try list_zero.appendSlice(&init);
try list_eq.appendSlice(&init);
try list_lt.appendSlice(&init);
try list_gt.appendSlice(&init);
try list_zero.replaceRange(1, 0, &new);
try list_eq.replaceRange(1, 3, &new);
try list_lt.replaceRange(1, 2, &new);
// after_range > new_items.len in function body
testing.expect(1 + 4 > new.len);
try list_gt.replaceRange(1, 4, &new);
testing.expectEqualSlices(i32, list_zero.items, &result_zero);
testing.expectEqualSlices(i32, list_eq.items, &result_eq);
testing.expectEqualSlices(i32, list_lt.items, &result_le);
testing.expectEqualSlices(i32, list_gt.items, &result_gt);
}
{
var list_zero = ArrayListUnmanaged(i32){};
var list_eq = ArrayListUnmanaged(i32){};
var list_lt = ArrayListUnmanaged(i32){};
var list_gt = ArrayListUnmanaged(i32){};
try list_zero.appendSlice(a, &init);
try list_eq.appendSlice(a, &init);
try list_lt.appendSlice(a, &init);
try list_gt.appendSlice(a, &init);
try list_zero.replaceRange(a, 1, 0, &new);
try list_eq.replaceRange(a, 1, 3, &new);
try list_lt.replaceRange(a, 1, 2, &new);
// after_range > new_items.len in function body
testing.expect(1 + 4 > new.len);
try list_gt.replaceRange(a, 1, 4, &new);
testing.expectEqualSlices(i32, list_zero.items, &result_zero);
testing.expectEqualSlices(i32, list_eq.items, &result_eq);
testing.expectEqualSlices(i32, list_lt.items, &result_le);
testing.expectEqualSlices(i32, list_gt.items, &result_gt);
}
}
const Item = struct {
integer: i32,
sub_items: ArrayList(Item),
};
const ItemUnmanaged = struct {
integer: i32,
sub_items: ArrayListUnmanaged(ItemUnmanaged),
};
test "std.ArrayList/ArrayListUnmanaged: ArrayList(T) of struct T" {
const a = std.testing.allocator;
{
var root = Item{ .integer = 1, .sub_items = ArrayList(Item).init(a) };
defer root.sub_items.deinit();
try root.sub_items.append(Item{ .integer = 42, .sub_items = ArrayList(Item).init(a) });
testing.expect(root.sub_items.items[0].integer == 42);
}
{
var root = ItemUnmanaged{ .integer = 1, .sub_items = ArrayListUnmanaged(ItemUnmanaged){} };
defer root.sub_items.deinit(a);
try root.sub_items.append(a, ItemUnmanaged{ .integer = 42, .sub_items = ArrayListUnmanaged(ItemUnmanaged){} });
testing.expect(root.sub_items.items[0].integer == 42);
}
}
test "std.ArrayList(u8) implements outStream" {
var buffer = ArrayList(u8).init(std.testing.allocator);
defer buffer.deinit();
const x: i32 = 42;
const y: i32 = 1234;
try buffer.outStream().print("x: {}\ny: {}\n", .{ x, y });
testing.expectEqualSlices(u8, "x: 42\ny: 1234\n", buffer.items);
}
test "std.ArrayList/ArrayListUnmanaged.shrink still sets length on error.OutOfMemory" {
// use an arena allocator to make sure realloc returns error.OutOfMemory
var arena = std.heap.ArenaAllocator.init(testing.allocator);
defer arena.deinit();
const a = &arena.allocator;
{
var list = ArrayList(i32).init(a);
try list.append(1);
try list.append(2);
try list.append(3);
list.shrink(1);
testing.expect(list.items.len == 1);
}
{
var list = ArrayListUnmanaged(i32){};
try list.append(a, 1);
try list.append(a, 2);
try list.append(a, 3);
list.shrink(a, 1);
testing.expect(list.items.len == 1);
}
}
test "std.ArrayList.writer" {
var list = ArrayList(u8).init(std.testing.allocator);
defer list.deinit();
const writer = list.writer();
try writer.writeAll("a");
try writer.writeAll("bc");
try writer.writeAll("d");
try writer.writeAll("efg");
testing.expectEqualSlices(u8, list.items, "abcdefg");
}
test "std.ArrayList/ArrayListUnmanaged.addManyAsArray" {
const a = std.testing.allocator;
{
var list = ArrayList(u8).init(a);
defer list.deinit();
(try list.addManyAsArray(4)).* = "aoeu".*;
try list.ensureCapacity(8);
list.addManyAsArrayAssumeCapacity(4).* = "asdf".*;
testing.expectEqualSlices(u8, list.items, "aoeuasdf");
}
{
var list = ArrayListUnmanaged(u8){};
defer list.deinit(a);
(try list.addManyAsArray(a, 4)).* = "aoeu".*;
try list.ensureCapacity(a, 8);
list.addManyAsArrayAssumeCapacity(4).* = "asdf".*;
testing.expectEqualSlices(u8, list.items, "aoeuasdf");
}
}
|
lib/std/array_list.zig
|
const root = @import("root");
const std = @import("std.zig");
const builtin = @import("builtin");
const assert = std.debug.assert;
const math = std.math;
const mem = std.mem;
const elf = std.elf;
const dl = @import("dynamic_library.zig");
const MAX_PATH_BYTES = std.fs.MAX_PATH_BYTES;
pub const darwin = @import("os/darwin.zig");
pub const dragonfly = @import("os/dragonfly.zig");
pub const freebsd = @import("os/freebsd.zig");
pub const netbsd = @import("os/netbsd.zig");
pub const linux = @import("os/linux.zig");
pub const uefi = @import("os/uefi.zig");
pub const wasi = @import("os/wasi.zig");
pub const windows = @import("os/windows.zig");
comptime {
assert(@import("std") == std); // std lib tests require --override-lib-dir
}
test "" {
_ = darwin;
_ = freebsd;
_ = linux;
_ = netbsd;
_ = uefi;
_ = wasi;
_ = windows;
_ = @import("os/test.zig");
}
/// Applications can override the `system` API layer in their root source file.
/// Otherwise, when linking libc, this is the C API.
/// When not linking libc, it is the OS-specific system interface.
pub const system = if (@hasDecl(root, "os") and root.os != @This())
root.os.system
else if (builtin.link_libc)
std.c
else switch (builtin.os.tag) {
.macosx, .ios, .watchos, .tvos => darwin,
.freebsd => freebsd,
.linux => linux,
.netbsd => netbsd,
.dragonfly => dragonfly,
.wasi => wasi,
.windows => windows,
else => struct {},
};
pub usingnamespace @import("os/bits.zig");
/// See also `getenv`. Populated by startup code before main().
/// TODO this is a footgun because the value will be undefined when using `zig build-lib`.
/// https://github.com/ziglang/zig/issues/4524
pub var environ: [][*:0]u8 = undefined;
/// Populated by startup code before main().
/// Not available on Windows. See `std.process.args`
/// for obtaining the process arguments.
pub var argv: [][*:0]u8 = undefined;
/// To obtain errno, call this function with the return value of the
/// system function call. For some systems this will obtain the value directly
/// from the return code; for others it will use a thread-local errno variable.
/// Therefore, this function only returns a well-defined value when it is called
/// directly after the system function call which one wants to learn the errno
/// value of.
pub const errno = system.getErrno;
/// Closes the file descriptor.
/// This function is not capable of returning any indication of failure. An
/// application which wants to ensure writes have succeeded before closing
/// must call `fsync` before `close`.
/// Note: The Zig standard library does not support POSIX thread cancellation.
pub fn close(fd: fd_t) void {
if (builtin.os.tag == .windows) {
return windows.CloseHandle(fd);
}
if (builtin.os.tag == .wasi) {
_ = wasi.fd_close(fd);
}
if (comptime std.Target.current.isDarwin()) {
// This avoids the EINTR problem.
switch (darwin.getErrno(darwin.@"close$NOCANCEL"(fd))) {
EBADF => unreachable, // Always a race condition.
else => return,
}
}
switch (errno(system.close(fd))) {
EBADF => unreachable, // Always a race condition.
EINTR => return, // This is still a success. See https://github.com/ziglang/zig/issues/2425
else => return,
}
}
pub const GetRandomError = OpenError;
/// Obtain a series of random bytes. These bytes can be used to seed user-space
/// random number generators or for cryptographic purposes.
/// When linking against libc, this calls the
/// appropriate OS-specific library call. Otherwise it uses the zig standard
/// library implementation.
pub fn getrandom(buffer: []u8) GetRandomError!void {
if (builtin.os.tag == .windows) {
return windows.RtlGenRandom(buffer);
}
if (builtin.os.tag == .linux or builtin.os.tag == .freebsd) {
var buf = buffer;
const use_c = builtin.os.tag != .linux or
std.c.versionCheck(builtin.Version{ .major = 2, .minor = 25, .patch = 0 }).ok;
while (buf.len != 0) {
var err: u16 = undefined;
const num_read = if (use_c) blk: {
const rc = std.c.getrandom(buf.ptr, buf.len, 0);
err = std.c.getErrno(rc);
break :blk @bitCast(usize, rc);
} else blk: {
const rc = linux.getrandom(buf.ptr, buf.len, 0);
err = linux.getErrno(rc);
break :blk rc;
};
switch (err) {
0 => buf = buf[num_read..],
EINVAL => unreachable,
EFAULT => unreachable,
EINTR => continue,
ENOSYS => return getRandomBytesDevURandom(buf),
else => return unexpectedErrno(err),
}
}
return;
}
if (builtin.os.tag == .wasi) {
switch (wasi.random_get(buffer.ptr, buffer.len)) {
0 => return,
else => |err| return unexpectedErrno(err),
}
}
return getRandomBytesDevURandom(buffer);
}
fn getRandomBytesDevURandom(buf: []u8) !void {
const fd = try openZ("/dev/urandom", O_RDONLY | O_CLOEXEC, 0);
defer close(fd);
const st = try fstat(fd);
if (!S_ISCHR(st.mode)) {
return error.NoDevice;
}
const file = std.fs.File{
.handle = fd,
.io_mode = .blocking,
.async_block_allowed = std.fs.File.async_block_allowed_yes,
};
const stream = file.inStream();
stream.readNoEof(buf) catch return error.Unexpected;
}
/// Causes abnormal process termination.
/// If linking against libc, this calls the abort() libc function. Otherwise
/// it raises SIGABRT followed by SIGKILL and finally lo
pub fn abort() noreturn {
@setCold(true);
// MSVCRT abort() sometimes opens a popup window which is undesirable, so
// even when linking libc on Windows we use our own abort implementation.
// See https://github.com/ziglang/zig/issues/2071 for more details.
if (builtin.os.tag == .windows) {
if (builtin.mode == .Debug) {
@breakpoint();
}
windows.kernel32.ExitProcess(3);
}
if (!builtin.link_libc and builtin.os.tag == .linux) {
raise(SIGABRT) catch {};
// TODO the rest of the implementation of abort() from musl libc here
raise(SIGKILL) catch {};
exit(127);
}
if (builtin.os.tag == .uefi) {
exit(0); // TODO choose appropriate exit code
}
if (builtin.os.tag == .wasi) {
@breakpoint();
exit(1);
}
system.abort();
}
pub const RaiseError = UnexpectedError;
pub fn raise(sig: u8) RaiseError!void {
if (builtin.link_libc) {
switch (errno(system.raise(sig))) {
0 => return,
else => |err| return unexpectedErrno(err),
}
}
if (builtin.os.tag == .linux) {
var set: linux.sigset_t = undefined;
// block application signals
_ = linux.sigprocmask(SIG_BLOCK, &linux.app_mask, &set);
const tid = linux.gettid();
const rc = linux.tkill(tid, sig);
// restore signal mask
_ = linux.sigprocmask(SIG_SETMASK, &set, null);
switch (errno(rc)) {
0 => return,
else => |err| return unexpectedErrno(err),
}
}
@compileError("std.os.raise unimplemented for this target");
}
pub const KillError = error{PermissionDenied} || UnexpectedError;
pub fn kill(pid: pid_t, sig: u8) KillError!void {
switch (errno(system.kill(pid, sig))) {
0 => return,
EINVAL => unreachable, // invalid signal
EPERM => return error.PermissionDenied,
ESRCH => unreachable, // always a race condition
else => |err| return unexpectedErrno(err),
}
}
/// Exits the program cleanly with the specified status code.
pub fn exit(status: u8) noreturn {
if (builtin.link_libc) {
system.exit(status);
}
if (builtin.os.tag == .windows) {
windows.kernel32.ExitProcess(status);
}
if (builtin.os.tag == .wasi) {
wasi.proc_exit(status);
}
if (builtin.os.tag == .linux and !builtin.single_threaded) {
linux.exit_group(status);
}
if (builtin.os.tag == .uefi) {
// exit() is only avaliable if exitBootServices() has not been called yet.
// This call to exit should not fail, so we don't care about its return value.
if (uefi.system_table.boot_services) |bs| {
_ = bs.exit(uefi.handle, @intToEnum(uefi.Status, status), 0, null);
}
// If we can't exit, reboot the system instead.
uefi.system_table.runtime_services.resetSystem(uefi.tables.ResetType.ResetCold, @intToEnum(uefi.Status, status), 0, null);
}
system.exit(status);
}
pub const ReadError = error{
InputOutput,
SystemResources,
IsDir,
OperationAborted,
BrokenPipe,
ConnectionResetByPeer,
/// This error occurs when no global event loop is configured,
/// and reading from the file descriptor would block.
WouldBlock,
} || UnexpectedError;
/// Returns the number of bytes that were read, which can be less than
/// buf.len. If 0 bytes were read, that means EOF.
/// If the application has a global event loop enabled, EAGAIN is handled
/// via the event loop. Otherwise EAGAIN results in error.WouldBlock.
///
/// Linux has a limit on how many bytes may be transferred in one `read` call, which is `0x7ffff000`
/// on both 64-bit and 32-bit systems. This is due to using a signed C int as the return value, as
/// well as stuffing the errno codes into the last `4096` values. This is noted on the `read` man page.
/// For POSIX the limit is `math.maxInt(isize)`.
pub fn read(fd: fd_t, buf: []u8) ReadError!usize {
if (builtin.os.tag == .windows) {
return windows.ReadFile(fd, buf, null);
}
if (builtin.os.tag == .wasi and !builtin.link_libc) {
const iovs = [1]iovec{iovec{
.iov_base = buf.ptr,
.iov_len = buf.len,
}};
var nread: usize = undefined;
switch (wasi.fd_read(fd, &iovs, iovs.len, &nread)) {
0 => return nread,
else => |err| return unexpectedErrno(err),
}
}
// Prevents EINVAL.
const max_count = switch (std.Target.current.os.tag) {
.linux => 0x7ffff000,
else => math.maxInt(isize),
};
const adjusted_len = math.min(max_count, buf.len);
while (true) {
const rc = system.read(fd, buf.ptr, adjusted_len);
switch (errno(rc)) {
0 => return @intCast(usize, rc),
EINTR => continue,
EINVAL => unreachable,
EFAULT => unreachable,
EAGAIN => if (std.event.Loop.instance) |loop| {
loop.waitUntilFdReadable(fd);
continue;
} else {
return error.WouldBlock;
},
EBADF => unreachable, // Always a race condition.
EIO => return error.InputOutput,
EISDIR => return error.IsDir,
ENOBUFS => return error.SystemResources,
ENOMEM => return error.SystemResources,
ECONNRESET => return error.ConnectionResetByPeer,
else => |err| return unexpectedErrno(err),
}
}
return index;
}
/// Number of bytes read is returned. Upon reading end-of-file, zero is returned.
///
/// For POSIX systems, if the application has a global event loop enabled, EAGAIN is handled
/// via the event loop. Otherwise EAGAIN results in `error.WouldBlock`.
/// On Windows, if the application has a global event loop enabled, I/O Completion Ports are
/// used to perform the I/O. `error.WouldBlock` is not possible on Windows.
///
/// This operation is non-atomic on the following systems:
/// * Windows
/// On these systems, the read races with concurrent writes to the same file descriptor.
pub fn readv(fd: fd_t, iov: []const iovec) ReadError!usize {
if (std.Target.current.os.tag == .windows) {
// TODO does Windows have a way to read an io vector?
if (iov.len == 0) return @as(usize, 0);
const first = iov[0];
return read(fd, first.iov_base[0..first.iov_len]);
}
while (true) {
// TODO handle the case when iov_len is too large and get rid of this @intCast
const rc = system.readv(fd, iov.ptr, iov_count);
switch (errno(rc)) {
0 => return @intCast(usize, rc),
EINTR => continue,
EINVAL => unreachable,
EFAULT => unreachable,
EAGAIN => if (std.event.Loop.instance) |loop| {
loop.waitUntilFdReadable(fd);
continue;
} else {
return error.WouldBlock;
},
EBADF => unreachable, // always a race condition
EIO => return error.InputOutput,
EISDIR => return error.IsDir,
ENOBUFS => return error.SystemResources,
ENOMEM => return error.SystemResources,
else => |err| return unexpectedErrno(err),
}
}
}
pub const PReadError = ReadError || error{Unseekable};
/// Number of bytes read is returned. Upon reading end-of-file, zero is returned.
///
/// Retries when interrupted by a signal.
///
/// For POSIX systems, if the application has a global event loop enabled, EAGAIN is handled
/// via the event loop. Otherwise EAGAIN results in `error.WouldBlock`.
/// On Windows, if the application has a global event loop enabled, I/O Completion Ports are
/// used to perform the I/O. `error.WouldBlock` is not possible on Windows.
pub fn pread(fd: fd_t, buf: []u8, offset: u64) PReadError!usize {
if (builtin.os.tag == .windows) {
return windows.ReadFile(fd, buf, offset);
}
while (true) {
const rc = system.pread(fd, buf.ptr, buf.len, offset);
switch (errno(rc)) {
0 => return @intCast(usize, rc),
EINTR => continue,
EINVAL => unreachable,
EFAULT => unreachable,
EAGAIN => if (std.event.Loop.instance) |loop| {
loop.waitUntilFdReadable(fd);
continue;
} else {
return error.WouldBlock;
},
EBADF => unreachable, // Always a race condition.
EIO => return error.InputOutput,
EISDIR => return error.IsDir,
ENOBUFS => return error.SystemResources,
ENOMEM => return error.SystemResources,
ECONNRESET => return error.ConnectionResetByPeer,
ENXIO => return error.Unseekable,
ESPIPE => return error.Unseekable,
EOVERFLOW => return error.Unseekable,
else => |err| return unexpectedErrno(err),
}
}
return index;
}
pub const TruncateError = error{
FileTooBig,
InputOutput,
CannotTruncate,
FileBusy,
} || UnexpectedError;
pub fn ftruncate(fd: fd_t, length: u64) TruncateError!void {
if (std.Target.current.os.tag == .windows) {
var io_status_block: windows.IO_STATUS_BLOCK = undefined;
var eof_info = windows.FILE_END_OF_FILE_INFORMATION{
.EndOfFile = @bitCast(windows.LARGE_INTEGER, length),
};
const rc = windows.ntdll.NtSetInformationFile(
fd,
&io_status_block,
&eof_info,
@sizeOf(windows.FILE_END_OF_FILE_INFORMATION),
.FileEndOfFileInformation,
);
switch (rc) {
.SUCCESS => return,
.INVALID_HANDLE => unreachable, // Handle not open for writing
.ACCESS_DENIED => return error.CannotTruncate,
else => return windows.unexpectedStatus(rc),
}
}
while (true) {
const rc = if (builtin.link_libc)
if (std.Target.current.os.tag == .linux)
system.ftruncate64(fd, @bitCast(off_t, length))
else
system.ftruncate(fd, @bitCast(off_t, length))
else
system.ftruncate(fd, length);
switch (errno(rc)) {
0 => return,
EINTR => continue,
EFBIG => return error.FileTooBig,
EIO => return error.InputOutput,
EPERM => return error.CannotTruncate,
ETXTBSY => return error.FileBusy,
EBADF => unreachable, // Handle not open for writing
EINVAL => unreachable, // Handle not open for writing
else => |err| return unexpectedErrno(err),
}
}
}
/// Number of bytes read is returned. Upon reading end-of-file, zero is returned.
///
/// Retries when interrupted by a signal.
///
/// For POSIX systems, if the application has a global event loop enabled, EAGAIN is handled
/// via the event loop. Otherwise EAGAIN results in `error.WouldBlock`.
/// On Windows, if the application has a global event loop enabled, I/O Completion Ports are
/// used to perform the I/O. `error.WouldBlock` is not possible on Windows.
///
/// This operation is non-atomic on the following systems:
/// * Darwin
/// * Windows
/// On these systems, the read races with concurrent writes to the same file descriptor.
pub fn preadv(fd: fd_t, iov: []const iovec, offset: u64) PReadError!usize {
const have_pread_but_not_preadv = switch (std.Target.current.os.tag) {
.windows, .macosx, .ios, .watchos, .tvos => true,
else => false,
};
if (have_pread_but_not_preadv) {
// We could loop here; but proper usage of `preadv` must handle partial reads anyway.
// So we simply read into the first vector only.
if (iov.len == 0) return @as(usize, 0);
const first = iov[0];
return pread(fd, first.iov_base[0..first.iov_len], offset);
}
const iov_count = math.cast(u31, iov.len) catch math.maxInt(u31);
while (true) {
const rc = system.preadv(fd, iov.ptr, iov_count, offset);
switch (errno(rc)) {
0 => return @bitCast(usize, rc),
EINTR => continue,
EINVAL => unreachable,
EFAULT => unreachable,
EAGAIN => if (std.event.Loop.instance) |loop| {
loop.waitUntilFdReadable(fd);
continue;
} else {
return error.WouldBlock;
},
EBADF => unreachable, // always a race condition
EIO => return error.InputOutput,
EISDIR => return error.IsDir,
ENOBUFS => return error.SystemResources,
ENOMEM => return error.SystemResources,
ENXIO => return error.Unseekable,
ESPIPE => return error.Unseekable,
EOVERFLOW => return error.Unseekable,
else => |err| return unexpectedErrno(err),
}
}
}
pub const WriteError = error{
DiskQuota,
FileTooBig,
InputOutput,
NoSpaceLeft,
AccessDenied,
BrokenPipe,
SystemResources,
OperationAborted,
/// This error occurs when no global event loop is configured,
/// and reading from the file descriptor would block.
WouldBlock,
} || UnexpectedError;
/// Write to a file descriptor.
/// Retries when interrupted by a signal.
/// Returns the number of bytes written. If nonzero bytes were supplied, this will be nonzero.
///
/// Note that a successful write() may transfer fewer than count bytes. Such partial writes can
/// occur for various reasons; for example, because there was insufficient space on the disk
/// device to write all of the requested bytes, or because a blocked write() to a socket, pipe, or
/// similar was interrupted by a signal handler after it had transferred some, but before it had
/// transferred all of the requested bytes. In the event of a partial write, the caller can make
/// another write() call to transfer the remaining bytes. The subsequent call will either
/// transfer further bytes or may result in an error (e.g., if the disk is now full).
///
/// For POSIX systems, if the application has a global event loop enabled, EAGAIN is handled
/// via the event loop. Otherwise EAGAIN results in `error.WouldBlock`.
/// On Windows, if the application has a global event loop enabled, I/O Completion Ports are
/// used to perform the I/O. `error.WouldBlock` is not possible on Windows.
///
/// Linux has a limit on how many bytes may be transferred in one `write` call, which is `0x7ffff000`
/// on both 64-bit and 32-bit systems. This is due to using a signed C int as the return value, as
/// well as stuffing the errno codes into the last `4096` values. This is noted on the `write` man page.
/// The corresponding POSIX limit is `math.maxInt(isize)`.
pub fn write(fd: fd_t, bytes: []const u8) WriteError!usize {
if (builtin.os.tag == .windows) {
return windows.WriteFile(fd, bytes, null);
}
if (builtin.os.tag == .wasi and !builtin.link_libc) {
const ciovs = [1]iovec_const{iovec_const{
.iov_base = bytes.ptr,
.iov_len = bytes.len,
}};
var nwritten: usize = undefined;
switch (wasi.fd_write(fd, &ciovs, ciovs.len, &nwritten)) {
0 => return nwritten,
else => |err| return unexpectedErrno(err),
}
}
const max_count = switch (std.Target.current.os.tag) {
.linux => 0x7ffff000,
else => math.maxInt(isize),
};
const adjusted_len = math.min(max_count, bytes.len);
while (true) {
const rc = system.write(fd, bytes.ptr, adjusted_len);
switch (errno(rc)) {
0 => return @intCast(usize, rc),
EINTR => continue,
EINVAL => unreachable,
EFAULT => unreachable,
EAGAIN => if (std.event.Loop.instance) |loop| {
loop.waitUntilFdWritable(fd);
continue;
} else {
return error.WouldBlock;
},
EBADF => unreachable, // Always a race condition.
EDESTADDRREQ => unreachable, // `connect` was never called.
EDQUOT => return error.DiskQuota,
EFBIG => return error.FileTooBig,
EIO => return error.InputOutput,
ENOSPC => return error.NoSpaceLeft,
EPERM => return error.AccessDenied,
EPIPE => return error.BrokenPipe,
else => |err| return unexpectedErrno(err),
}
}
}
/// Write multiple buffers to a file descriptor.
/// Retries when interrupted by a signal.
/// Returns the number of bytes written. If nonzero bytes were supplied, this will be nonzero.
///
/// Note that a successful write() may transfer fewer bytes than supplied. Such partial writes can
/// occur for various reasons; for example, because there was insufficient space on the disk
/// device to write all of the requested bytes, or because a blocked write() to a socket, pipe, or
/// similar was interrupted by a signal handler after it had transferred some, but before it had
/// transferred all of the requested bytes. In the event of a partial write, the caller can make
/// another write() call to transfer the remaining bytes. The subsequent call will either
/// transfer further bytes or may result in an error (e.g., if the disk is now full).
///
/// For POSIX systems, if the application has a global event loop enabled, EAGAIN is handled
/// via the event loop. Otherwise EAGAIN results in `error.WouldBlock`.
/// On Windows, if the application has a global event loop enabled, I/O Completion Ports are
/// used to perform the I/O. `error.WouldBlock` is not possible on Windows.
///
/// If `iov.len` is larger than will fit in a `u31`, a partial write will occur.
pub fn writev(fd: fd_t, iov: []const iovec_const) WriteError!usize {
if (std.Target.current.os.tag == .windows) {
// TODO does Windows have a way to write an io vector?
if (iov.len == 0) return @as(usize, 0);
const first = iov[0];
return write(fd, first.iov_base[0..first.iov_len]);
}
const iov_count = math.cast(u31, iov.len) catch math.maxInt(u31);
while (true) {
const rc = system.writev(fd, iov.ptr, iov_count);
switch (errno(rc)) {
0 => return @intCast(usize, rc),
EINTR => continue,
EINVAL => unreachable,
EFAULT => unreachable,
EAGAIN => if (std.event.Loop.instance) |loop| {
loop.waitUntilFdWritable(fd);
continue;
} else {
return error.WouldBlock;
},
EBADF => unreachable, // Always a race condition.
EDESTADDRREQ => unreachable, // `connect` was never called.
EDQUOT => return error.DiskQuota,
EFBIG => return error.FileTooBig,
EIO => return error.InputOutput,
ENOSPC => return error.NoSpaceLeft,
EPERM => return error.AccessDenied,
EPIPE => return error.BrokenPipe,
else => |err| return unexpectedErrno(err),
}
}
}
pub const PWriteError = WriteError || error{Unseekable};
/// Write to a file descriptor, with a position offset.
/// Retries when interrupted by a signal.
/// Returns the number of bytes written. If nonzero bytes were supplied, this will be nonzero.
///
/// Note that a successful write() may transfer fewer bytes than supplied. Such partial writes can
/// occur for various reasons; for example, because there was insufficient space on the disk
/// device to write all of the requested bytes, or because a blocked write() to a socket, pipe, or
/// similar was interrupted by a signal handler after it had transferred some, but before it had
/// transferred all of the requested bytes. In the event of a partial write, the caller can make
/// another write() call to transfer the remaining bytes. The subsequent call will either
/// transfer further bytes or may result in an error (e.g., if the disk is now full).
///
/// For POSIX systems, if the application has a global event loop enabled, EAGAIN is handled
/// via the event loop. Otherwise EAGAIN results in `error.WouldBlock`.
/// On Windows, if the application has a global event loop enabled, I/O Completion Ports are
/// used to perform the I/O. `error.WouldBlock` is not possible on Windows.
///
/// Linux has a limit on how many bytes may be transferred in one `pwrite` call, which is `0x7ffff000`
/// on both 64-bit and 32-bit systems. This is due to using a signed C int as the return value, as
/// well as stuffing the errno codes into the last `4096` values. This is noted on the `write` man page.
/// The corresponding POSIX limit is `math.maxInt(isize)`.
pub fn pwrite(fd: fd_t, bytes: []const u8, offset: u64) PWriteError!usize {
if (std.Target.current.os.tag == .windows) {
return windows.WriteFile(fd, bytes, offset);
}
// Prevent EINVAL.
const max_count = switch (std.Target.current.os.tag) {
.linux => 0x7ffff000,
else => math.maxInt(isize),
};
const adjusted_len = math.min(max_count, bytes.len);
while (true) {
const rc = system.pwrite(fd, bytes.ptr, adjusted_len, offset);
switch (errno(rc)) {
0 => return @intCast(usize, rc),
EINTR => continue,
EINVAL => unreachable,
EFAULT => unreachable,
EAGAIN => if (std.event.Loop.instance) |loop| {
loop.waitUntilFdWritable(fd);
continue;
} else {
return error.WouldBlock;
},
EBADF => unreachable, // Always a race condition.
EDESTADDRREQ => unreachable, // `connect` was never called.
EDQUOT => return error.DiskQuota,
EFBIG => return error.FileTooBig,
EIO => return error.InputOutput,
ENOSPC => return error.NoSpaceLeft,
EPERM => return error.AccessDenied,
EPIPE => return error.BrokenPipe,
ENXIO => return error.Unseekable,
ESPIPE => return error.Unseekable,
EOVERFLOW => return error.Unseekable,
else => |err| return unexpectedErrno(err),
}
}
}
/// Write multiple buffers to a file descriptor, with a position offset.
/// Retries when interrupted by a signal.
/// Returns the number of bytes written. If nonzero bytes were supplied, this will be nonzero.
///
/// Note that a successful write() may transfer fewer than count bytes. Such partial writes can
/// occur for various reasons; for example, because there was insufficient space on the disk
/// device to write all of the requested bytes, or because a blocked write() to a socket, pipe, or
/// similar was interrupted by a signal handler after it had transferred some, but before it had
/// transferred all of the requested bytes. In the event of a partial write, the caller can make
/// another write() call to transfer the remaining bytes. The subsequent call will either
/// transfer further bytes or may result in an error (e.g., if the disk is now full).
///
/// If the application has a global event loop enabled, EAGAIN is handled
/// via the event loop. Otherwise EAGAIN results in `error.WouldBlock`.
///
/// The following systems do not have this syscall, and will return partial writes if more than one
/// vector is provided:
/// * Darwin
/// * Windows
///
/// If `iov.len` is larger than will fit in a `u31`, a partial write will occur.
pub fn pwritev(fd: fd_t, iov: []const iovec_const, offset: u64) PWriteError!usize {
const have_pwrite_but_not_pwritev = switch (std.Target.current.os.tag) {
.windows, .macosx, .ios, .watchos, .tvos => true,
else => false,
};
if (have_pwrite_but_not_pwritev) {
// We could loop here; but proper usage of `pwritev` must handle partial writes anyway.
// So we simply write the first vector only.
if (iov.len == 0) return @as(usize, 0);
const first = iov[0];
return pwrite(fd, first.iov_base[0..first.iov_len], offset);
}
const iov_count = math.cast(u31, iov.len) catch math.maxInt(u31);
while (true) {
const rc = system.pwritev(fd, iov.ptr, iov_count, offset);
switch (errno(rc)) {
0 => return @intCast(usize, rc),
EINTR => continue,
EINVAL => unreachable,
EFAULT => unreachable,
EAGAIN => if (std.event.Loop.instance) |loop| {
loop.waitUntilFdWritable(fd);
continue;
} else {
return error.WouldBlock;
},
EBADF => unreachable, // Always a race condition.
EDESTADDRREQ => unreachable, // `connect` was never called.
EDQUOT => return error.DiskQuota,
EFBIG => return error.FileTooBig,
EIO => return error.InputOutput,
ENOSPC => return error.NoSpaceLeft,
EPERM => return error.AccessDenied,
EPIPE => return error.BrokenPipe,
ENXIO => return error.Unseekable,
ESPIPE => return error.Unseekable,
EOVERFLOW => return error.Unseekable,
else => |err| return unexpectedErrno(err),
}
}
}
pub const OpenError = error{
AccessDenied,
SymLinkLoop,
ProcessFdQuotaExceeded,
SystemFdQuotaExceeded,
NoDevice,
FileNotFound,
/// The path exceeded `MAX_PATH_BYTES` bytes.
NameTooLong,
/// Insufficient kernel memory was available, or
/// the named file is a FIFO and per-user hard limit on
/// memory allocation for pipes has been reached.
SystemResources,
/// The file is too large to be opened. This error is unreachable
/// for 64-bit targets, as well as when opening directories.
FileTooBig,
/// The path refers to directory but the `O_DIRECTORY` flag was not provided.
IsDir,
/// A new path cannot be created because the device has no room for the new file.
/// This error is only reachable when the `O_CREAT` flag is provided.
NoSpaceLeft,
/// A component used as a directory in the path was not, in fact, a directory, or
/// `O_DIRECTORY` was specified and the path was not a directory.
NotDir,
/// The path already exists and the `O_CREAT` and `O_EXCL` flags were provided.
PathAlreadyExists,
DeviceBusy,
/// The underlying filesystem does not support file locks
FileLocksNotSupported,
} || UnexpectedError;
/// Open and possibly create a file. Keeps trying if it gets interrupted.
/// See also `openC`.
/// TODO support windows
pub fn open(file_path: []const u8, flags: u32, perm: usize) OpenError!fd_t {
const file_path_c = try toPosixPath(file_path);
return openZ(&file_path_c, flags, perm);
}
pub const openC = @compileError("deprecated: renamed to openZ");
/// Open and possibly create a file. Keeps trying if it gets interrupted.
/// See also `open`.
/// TODO support windows
pub fn openZ(file_path: [*:0]const u8, flags: u32, perm: usize) OpenError!fd_t {
while (true) {
const rc = system.open(file_path, flags, perm);
switch (errno(rc)) {
0 => return @intCast(fd_t, rc),
EINTR => continue,
EFAULT => unreachable,
EINVAL => unreachable,
EACCES => return error.AccessDenied,
EFBIG => return error.FileTooBig,
EOVERFLOW => return error.FileTooBig,
EISDIR => return error.IsDir,
ELOOP => return error.SymLinkLoop,
EMFILE => return error.ProcessFdQuotaExceeded,
ENAMETOOLONG => return error.NameTooLong,
ENFILE => return error.SystemFdQuotaExceeded,
ENODEV => return error.NoDevice,
ENOENT => return error.FileNotFound,
ENOMEM => return error.SystemResources,
ENOSPC => return error.NoSpaceLeft,
ENOTDIR => return error.NotDir,
EPERM => return error.AccessDenied,
EEXIST => return error.PathAlreadyExists,
EBUSY => return error.DeviceBusy,
else => |err| return unexpectedErrno(err),
}
}
}
/// Open and possibly create a file. Keeps trying if it gets interrupted.
/// `file_path` is relative to the open directory handle `dir_fd`.
/// See also `openatC`.
/// TODO support windows
pub fn openat(dir_fd: fd_t, file_path: []const u8, flags: u32, mode: mode_t) OpenError!fd_t {
const file_path_c = try toPosixPath(file_path);
return openatZ(dir_fd, &file_path_c, flags, mode);
}
pub const openatC = @compileError("deprecated: renamed to openatZ");
/// Open and possibly create a file. Keeps trying if it gets interrupted.
/// `file_path` is relative to the open directory handle `dir_fd`.
/// See also `openat`.
/// TODO support windows
pub fn openatZ(dir_fd: fd_t, file_path: [*:0]const u8, flags: u32, mode: mode_t) OpenError!fd_t {
while (true) {
const rc = system.openat(dir_fd, file_path, flags, mode);
switch (errno(rc)) {
0 => return @intCast(fd_t, rc),
EINTR => continue,
EFAULT => unreachable,
EINVAL => unreachable,
EACCES => return error.AccessDenied,
EFBIG => return error.FileTooBig,
EOVERFLOW => return error.FileTooBig,
EISDIR => return error.IsDir,
ELOOP => return error.SymLinkLoop,
EMFILE => return error.ProcessFdQuotaExceeded,
ENAMETOOLONG => return error.NameTooLong,
ENFILE => return error.SystemFdQuotaExceeded,
ENODEV => return error.NoDevice,
ENOENT => return error.FileNotFound,
ENOMEM => return error.SystemResources,
ENOSPC => return error.NoSpaceLeft,
ENOTDIR => return error.NotDir,
EPERM => return error.AccessDenied,
EEXIST => return error.PathAlreadyExists,
EBUSY => return error.DeviceBusy,
EOPNOTSUPP => return error.FileLocksNotSupported,
else => |err| return unexpectedErrno(err),
}
}
}
pub fn dup2(old_fd: fd_t, new_fd: fd_t) !void {
while (true) {
switch (errno(system.dup2(old_fd, new_fd))) {
0 => return,
EBUSY, EINTR => continue,
EMFILE => return error.ProcessFdQuotaExceeded,
EINVAL => unreachable, // invalid parameters passed to dup2
EBADF => unreachable, // always a race condition
else => |err| return unexpectedErrno(err),
}
}
}
pub const ExecveError = error{
SystemResources,
AccessDenied,
InvalidExe,
FileSystem,
IsDir,
FileNotFound,
NotDir,
FileBusy,
ProcessFdQuotaExceeded,
SystemFdQuotaExceeded,
NameTooLong,
} || UnexpectedError;
pub const execveC = @compileError("deprecated: use execveZ");
/// Like `execve` except the parameters are null-terminated,
/// matching the syscall API on all targets. This removes the need for an allocator.
/// This function ignores PATH environment variable. See `execvpeZ` for that.
pub fn execveZ(
path: [*:0]const u8,
child_argv: [*:null]const ?[*:0]const u8,
envp: [*:null]const ?[*:0]const u8,
) ExecveError {
switch (errno(system.execve(path, child_argv, envp))) {
0 => unreachable,
EFAULT => unreachable,
E2BIG => return error.SystemResources,
EMFILE => return error.ProcessFdQuotaExceeded,
ENAMETOOLONG => return error.NameTooLong,
ENFILE => return error.SystemFdQuotaExceeded,
ENOMEM => return error.SystemResources,
EACCES => return error.AccessDenied,
EPERM => return error.AccessDenied,
EINVAL => return error.InvalidExe,
ENOEXEC => return error.InvalidExe,
EIO => return error.FileSystem,
ELOOP => return error.FileSystem,
EISDIR => return error.IsDir,
ENOENT => return error.FileNotFound,
ENOTDIR => return error.NotDir,
ETXTBSY => return error.FileBusy,
else => |err| return unexpectedErrno(err),
}
}
pub const execvpeC = @compileError("deprecated in favor of execvpeZ");
pub const Arg0Expand = enum {
expand,
no_expand,
};
/// Like `execvpeZ` except if `arg0_expand` is `.expand`, then `argv` is mutable,
/// and `argv[0]` is expanded to be the same absolute path that is passed to the execve syscall.
/// If this function returns with an error, `argv[0]` will be restored to the value it was when it was passed in.
pub fn execvpeZ_expandArg0(
comptime arg0_expand: Arg0Expand,
file: [*:0]const u8,
child_argv: switch (arg0_expand) {
.expand => [*:null]?[*:0]const u8,
.no_expand => [*:null]const ?[*:0]const u8,
},
envp: [*:null]const ?[*:0]const u8,
) ExecveError {
const file_slice = mem.spanZ(file);
if (mem.indexOfScalar(u8, file_slice, '/') != null) return execveZ(file, child_argv, envp);
const PATH = getenvZ("PATH") orelse "/usr/local/bin:/bin/:/usr/bin";
var path_buf: [MAX_PATH_BYTES]u8 = undefined;
var it = mem.tokenize(PATH, ":");
var seen_eacces = false;
var err: ExecveError = undefined;
// In case of expanding arg0 we must put it back if we return with an error.
const prev_arg0 = child_argv[0];
defer switch (arg0_expand) {
.expand => child_argv[0] = prev_arg0,
.no_expand => {},
};
while (it.next()) |search_path| {
if (path_buf.len < search_path.len + file_slice.len + 1) return error.NameTooLong;
mem.copy(u8, &path_buf, search_path);
path_buf[search_path.len] = '/';
mem.copy(u8, path_buf[search_path.len + 1 ..], file_slice);
const path_len = search_path.len + file_slice.len + 1;
path_buf[path_len] = 0;
const full_path = path_buf[0..path_len :0].ptr;
switch (arg0_expand) {
.expand => child_argv[0] = full_path,
.no_expand => {},
}
err = execveZ(full_path, child_argv, envp);
switch (err) {
error.AccessDenied => seen_eacces = true,
error.FileNotFound, error.NotDir => {},
else => |e| return e,
}
}
if (seen_eacces) return error.AccessDenied;
return err;
}
/// Like `execvpe` except the parameters are null-terminated,
/// matching the syscall API on all targets. This removes the need for an allocator.
/// This function also uses the PATH environment variable to get the full path to the executable.
/// If `file` is an absolute path, this is the same as `execveZ`.
pub fn execvpeZ(
file: [*:0]const u8,
argv: [*:null]const ?[*:0]const u8,
envp: [*:null]const ?[*:0]const u8,
) ExecveError {
return execvpeZ_expandArg0(.no_expand, file, argv, envp);
}
/// This is the same as `execvpe` except if the `arg0_expand` parameter is set to `.expand`,
/// then argv[0] will be replaced with the expanded version of it, after resolving in accordance
/// with the PATH environment variable.
pub fn execvpe_expandArg0(
allocator: *mem.Allocator,
arg0_expand: Arg0Expand,
argv_slice: []const []const u8,
env_map: *const std.BufMap,
) (ExecveError || error{OutOfMemory}) {
const argv_buf = try allocator.alloc(?[*:0]u8, argv_slice.len + 1);
mem.set(?[*:0]u8, argv_buf, null);
defer {
for (argv_buf) |arg| {
const arg_buf = mem.spanZ(arg) orelse break;
allocator.free(arg_buf);
}
allocator.free(argv_buf);
}
for (argv_slice) |arg, i| {
const arg_buf = try allocator.alloc(u8, arg.len + 1);
@memcpy(arg_buf.ptr, arg.ptr, arg.len);
arg_buf[arg.len] = 0;
argv_buf[i] = arg_buf[0..arg.len :0].ptr;
}
argv_buf[argv_slice.len] = null;
const argv_ptr = argv_buf[0..argv_slice.len :null].ptr;
const envp_buf = try createNullDelimitedEnvMap(allocator, env_map);
defer freeNullDelimitedEnvMap(allocator, envp_buf);
switch (arg0_expand) {
.expand => return execvpeZ_expandArg0(.expand, argv_buf.ptr[0].?, argv_ptr, envp_buf.ptr),
.no_expand => return execvpeZ_expandArg0(.no_expand, argv_buf.ptr[0].?, argv_ptr, envp_buf.ptr),
}
}
/// This function must allocate memory to add a null terminating bytes on path and each arg.
/// It must also convert to KEY=VALUE\0 format for environment variables, and include null
/// pointers after the args and after the environment variables.
/// `argv_slice[0]` is the executable path.
/// This function also uses the PATH environment variable to get the full path to the executable.
pub fn execvpe(
allocator: *mem.Allocator,
argv_slice: []const []const u8,
env_map: *const std.BufMap,
) (ExecveError || error{OutOfMemory}) {
return execvpe_expandArg0(allocator, .no_expand, argv_slice, env_map);
}
pub fn createNullDelimitedEnvMap(allocator: *mem.Allocator, env_map: *const std.BufMap) ![:null]?[*:0]u8 {
const envp_count = env_map.count();
const envp_buf = try allocator.alloc(?[*:0]u8, envp_count + 1);
mem.set(?[*:0]u8, envp_buf, null);
errdefer freeNullDelimitedEnvMap(allocator, envp_buf);
{
var it = env_map.iterator();
var i: usize = 0;
while (it.next()) |pair| : (i += 1) {
const env_buf = try allocator.alloc(u8, pair.key.len + pair.value.len + 2);
@memcpy(env_buf.ptr, pair.key.ptr, pair.key.len);
env_buf[pair.key.len] = '=';
@memcpy(env_buf.ptr + pair.key.len + 1, pair.value.ptr, pair.value.len);
const len = env_buf.len - 1;
env_buf[len] = 0;
envp_buf[i] = env_buf[0..len :0].ptr;
}
assert(i == envp_count);
}
return envp_buf[0..envp_count :null];
}
pub fn freeNullDelimitedEnvMap(allocator: *mem.Allocator, envp_buf: []?[*:0]u8) void {
for (envp_buf) |env| {
const env_buf = if (env) |ptr| ptr[0 .. mem.len(ptr) + 1] else break;
allocator.free(env_buf);
}
allocator.free(envp_buf);
}
/// Get an environment variable.
/// See also `getenvZ`.
pub fn getenv(key: []const u8) ?[]const u8 {
if (builtin.link_libc) {
var small_key_buf: [64]u8 = undefined;
if (key.len < small_key_buf.len) {
mem.copy(u8, &small_key_buf, key);
small_key_buf[key.len] = 0;
const key0 = small_key_buf[0..key.len :0];
return getenvZ(key0);
}
// Search the entire `environ` because we don't have a null terminated pointer.
var ptr = std.c.environ;
while (ptr.*) |line| : (ptr += 1) {
var line_i: usize = 0;
while (line[line_i] != 0 and line[line_i] != '=') : (line_i += 1) {}
const this_key = line[0..line_i];
if (!mem.eql(u8, this_key, key)) continue;
var end_i: usize = line_i;
while (line[end_i] != 0) : (end_i += 1) {}
const value = line[line_i + 1 .. end_i];
return value;
}
return null;
}
if (builtin.os.tag == .windows) {
@compileError("std.os.getenv is unavailable for Windows because environment string is in WTF-16 format. See std.process.getEnvVarOwned for cross-platform API or std.os.getenvW for Windows-specific API.");
}
// TODO see https://github.com/ziglang/zig/issues/4524
for (environ) |ptr| {
var line_i: usize = 0;
while (ptr[line_i] != 0 and ptr[line_i] != '=') : (line_i += 1) {}
const this_key = ptr[0..line_i];
if (!mem.eql(u8, key, this_key)) continue;
var end_i: usize = line_i;
while (ptr[end_i] != 0) : (end_i += 1) {}
const this_value = ptr[line_i + 1 .. end_i];
return this_value;
}
return null;
}
pub const getenvC = @compileError("Deprecated in favor of `getenvZ`");
/// Get an environment variable with a null-terminated name.
/// See also `getenv`.
pub fn getenvZ(key: [*:0]const u8) ?[]const u8 {
if (builtin.link_libc) {
const value = system.getenv(key) orelse return null;
return mem.spanZ(value);
}
if (builtin.os.tag == .windows) {
@compileError("std.os.getenvZ is unavailable for Windows because environment string is in WTF-16 format. See std.process.getEnvVarOwned for cross-platform API or std.os.getenvW for Windows-specific API.");
}
return getenv(mem.spanZ(key));
}
/// Windows-only. Get an environment variable with a null-terminated, WTF-16 encoded name.
/// See also `getenv`.
/// This function first attempts a case-sensitive lookup. If no match is found, and `key`
/// is ASCII, then it attempts a second case-insensitive lookup.
pub fn getenvW(key: [*:0]const u16) ?[:0]const u16 {
if (builtin.os.tag != .windows) {
@compileError("std.os.getenvW is a Windows-only API");
}
const key_slice = mem.spanZ(key);
const ptr = windows.peb().ProcessParameters.Environment;
var ascii_match: ?[:0]const u16 = null;
var i: usize = 0;
while (ptr[i] != 0) {
const key_start = i;
while (ptr[i] != 0 and ptr[i] != '=') : (i += 1) {}
const this_key = ptr[key_start..i];
if (ptr[i] == '=') i += 1;
const value_start = i;
while (ptr[i] != 0) : (i += 1) {}
const this_value = ptr[value_start..i :0];
if (mem.eql(u16, key_slice, this_key)) return this_value;
ascii_check: {
if (ascii_match != null) break :ascii_check;
if (key_slice.len != this_key.len) break :ascii_check;
for (key_slice) |a_c, key_index| {
const a = math.cast(u8, a_c) catch break :ascii_check;
const b = math.cast(u8, this_key[key_index]) catch break :ascii_check;
if (std.ascii.toLower(a) != std.ascii.toLower(b)) break :ascii_check;
}
ascii_match = this_value;
}
i += 1; // skip over null byte
}
return ascii_match;
}
pub const GetCwdError = error{
NameTooLong,
CurrentWorkingDirectoryUnlinked,
} || UnexpectedError;
/// The result is a slice of out_buffer, indexed from 0.
pub fn getcwd(out_buffer: []u8) GetCwdError![]u8 {
if (builtin.os.tag == .windows) {
return windows.GetCurrentDirectory(out_buffer);
}
const err = if (builtin.link_libc) blk: {
break :blk if (std.c.getcwd(out_buffer.ptr, out_buffer.len)) |_| 0 else std.c._errno().*;
} else blk: {
break :blk errno(system.getcwd(out_buffer.ptr, out_buffer.len));
};
switch (err) {
0 => return mem.spanZ(@ptrCast([*:0]u8, out_buffer.ptr)),
EFAULT => unreachable,
EINVAL => unreachable,
ENOENT => return error.CurrentWorkingDirectoryUnlinked,
ERANGE => return error.NameTooLong,
else => return unexpectedErrno(@intCast(usize, err)),
}
}
pub const SymLinkError = error{
AccessDenied,
DiskQuota,
PathAlreadyExists,
FileSystem,
SymLinkLoop,
FileNotFound,
SystemResources,
NoSpaceLeft,
ReadOnlyFileSystem,
NotDir,
NameTooLong,
InvalidUtf8,
BadPathName,
} || UnexpectedError;
/// Creates a symbolic link named `sym_link_path` which contains the string `target_path`.
/// A symbolic link (also known as a soft link) may point to an existing file or to a nonexistent
/// one; the latter case is known as a dangling link.
/// If `sym_link_path` exists, it will not be overwritten.
/// See also `symlinkC` and `symlinkW`.
pub fn symlink(target_path: []const u8, sym_link_path: []const u8) SymLinkError!void {
if (builtin.os.tag == .windows) {
const target_path_w = try windows.sliceToPrefixedFileW(target_path);
const sym_link_path_w = try windows.sliceToPrefixedFileW(sym_link_path);
return windows.CreateSymbolicLinkW(&sym_link_path_w, &target_path_w, 0);
} else {
const target_path_c = try toPosixPath(target_path);
const sym_link_path_c = try toPosixPath(sym_link_path);
return symlinkZ(&target_path_c, &sym_link_path_c);
}
}
pub const symlinkC = @compileError("deprecated: renamed to symlinkZ");
/// This is the same as `symlink` except the parameters are null-terminated pointers.
/// See also `symlink`.
pub fn symlinkZ(target_path: [*:0]const u8, sym_link_path: [*:0]const u8) SymLinkError!void {
if (builtin.os.tag == .windows) {
const target_path_w = try windows.cStrToPrefixedFileW(target_path);
const sym_link_path_w = try windows.cStrToPrefixedFileW(sym_link_path);
return windows.CreateSymbolicLinkW(&sym_link_path_w, &target_path_w, 0);
}
switch (errno(system.symlink(target_path, sym_link_path))) {
0 => return,
EFAULT => unreachable,
EINVAL => unreachable,
EACCES => return error.AccessDenied,
EPERM => return error.AccessDenied,
EDQUOT => return error.DiskQuota,
EEXIST => return error.PathAlreadyExists,
EIO => return error.FileSystem,
ELOOP => return error.SymLinkLoop,
ENAMETOOLONG => return error.NameTooLong,
ENOENT => return error.FileNotFound,
ENOTDIR => return error.NotDir,
ENOMEM => return error.SystemResources,
ENOSPC => return error.NoSpaceLeft,
EROFS => return error.ReadOnlyFileSystem,
else => |err| return unexpectedErrno(err),
}
}
pub fn symlinkat(target_path: []const u8, newdirfd: fd_t, sym_link_path: []const u8) SymLinkError!void {
const target_path_c = try toPosixPath(target_path);
const sym_link_path_c = try toPosixPath(sym_link_path);
return symlinkatZ(target_path_c, newdirfd, sym_link_path_c);
}
pub const symlinkatC = @compileError("deprecated: renamed to symlinkatZ");
pub fn symlinkatZ(target_path: [*:0]const u8, newdirfd: fd_t, sym_link_path: [*:0]const u8) SymLinkError!void {
switch (errno(system.symlinkat(target_path, newdirfd, sym_link_path))) {
0 => return,
EFAULT => unreachable,
EINVAL => unreachable,
EACCES => return error.AccessDenied,
EPERM => return error.AccessDenied,
EDQUOT => return error.DiskQuota,
EEXIST => return error.PathAlreadyExists,
EIO => return error.FileSystem,
ELOOP => return error.SymLinkLoop,
ENAMETOOLONG => return error.NameTooLong,
ENOENT => return error.FileNotFound,
ENOTDIR => return error.NotDir,
ENOMEM => return error.SystemResources,
ENOSPC => return error.NoSpaceLeft,
EROFS => return error.ReadOnlyFileSystem,
else => |err| return unexpectedErrno(err),
}
}
pub const UnlinkError = error{
FileNotFound,
AccessDenied,
FileBusy,
FileSystem,
IsDir,
SymLinkLoop,
NameTooLong,
NotDir,
SystemResources,
ReadOnlyFileSystem,
/// On Windows, file paths must be valid Unicode.
InvalidUtf8,
/// On Windows, file paths cannot contain these characters:
/// '/', '*', '?', '"', '<', '>', '|'
BadPathName,
} || UnexpectedError;
/// Delete a name and possibly the file it refers to.
/// See also `unlinkC`.
pub fn unlink(file_path: []const u8) UnlinkError!void {
if (builtin.os.tag == .windows) {
const file_path_w = try windows.sliceToPrefixedFileW(file_path);
return windows.DeleteFileW(&file_path_w);
} else {
const file_path_c = try toPosixPath(file_path);
return unlinkZ(&file_path_c);
}
}
pub const unlinkC = @compileError("deprecated: renamed to unlinkZ");
/// Same as `unlink` except the parameter is a null terminated UTF8-encoded string.
pub fn unlinkZ(file_path: [*:0]const u8) UnlinkError!void {
if (builtin.os.tag == .windows) {
const file_path_w = try windows.cStrToPrefixedFileW(file_path);
return windows.DeleteFileW(&file_path_w);
}
switch (errno(system.unlink(file_path))) {
0 => return,
EACCES => return error.AccessDenied,
EPERM => return error.AccessDenied,
EBUSY => return error.FileBusy,
EFAULT => unreachable,
EINVAL => unreachable,
EIO => return error.FileSystem,
EISDIR => return error.IsDir,
ELOOP => return error.SymLinkLoop,
ENAMETOOLONG => return error.NameTooLong,
ENOENT => return error.FileNotFound,
ENOTDIR => return error.NotDir,
ENOMEM => return error.SystemResources,
EROFS => return error.ReadOnlyFileSystem,
else => |err| return unexpectedErrno(err),
}
}
pub const UnlinkatError = UnlinkError || error{
/// When passing `AT_REMOVEDIR`, this error occurs when the named directory is not empty.
DirNotEmpty,
};
/// Delete a file name and possibly the file it refers to, based on an open directory handle.
/// Asserts that the path parameter has no null bytes.
pub fn unlinkat(dirfd: fd_t, file_path: []const u8, flags: u32) UnlinkatError!void {
if (builtin.os.tag == .windows) {
const file_path_w = try windows.sliceToPrefixedFileW(file_path);
return unlinkatW(dirfd, &file_path_w, flags);
}
const file_path_c = try toPosixPath(file_path);
return unlinkatZ(dirfd, &file_path_c, flags);
}
pub const unlinkatC = @compileError("deprecated: renamed to unlinkatZ");
/// Same as `unlinkat` but `file_path` is a null-terminated string.
pub fn unlinkatZ(dirfd: fd_t, file_path_c: [*:0]const u8, flags: u32) UnlinkatError!void {
if (builtin.os.tag == .windows) {
const file_path_w = try windows.cStrToPrefixedFileW(file_path_c);
return unlinkatW(dirfd, &file_path_w, flags);
}
switch (errno(system.unlinkat(dirfd, file_path_c, flags))) {
0 => return,
EACCES => return error.AccessDenied,
EPERM => return error.AccessDenied,
EBUSY => return error.FileBusy,
EFAULT => unreachable,
EIO => return error.FileSystem,
EISDIR => return error.IsDir,
ELOOP => return error.SymLinkLoop,
ENAMETOOLONG => return error.NameTooLong,
ENOENT => return error.FileNotFound,
ENOTDIR => return error.NotDir,
ENOMEM => return error.SystemResources,
EROFS => return error.ReadOnlyFileSystem,
ENOTEMPTY => return error.DirNotEmpty,
EINVAL => unreachable, // invalid flags, or pathname has . as last component
EBADF => unreachable, // always a race condition
else => |err| return unexpectedErrno(err),
}
}
/// Same as `unlinkat` but `sub_path_w` is UTF16LE, NT prefixed. Windows only.
pub fn unlinkatW(dirfd: fd_t, sub_path_w: [*:0]const u16, flags: u32) UnlinkatError!void {
const w = windows;
const want_rmdir_behavior = (flags & AT_REMOVEDIR) != 0;
const create_options_flags = if (want_rmdir_behavior)
@as(w.ULONG, w.FILE_DELETE_ON_CLOSE)
else
@as(w.ULONG, w.FILE_DELETE_ON_CLOSE | w.FILE_NON_DIRECTORY_FILE);
const path_len_bytes = @intCast(u16, mem.lenZ(sub_path_w) * 2);
var nt_name = w.UNICODE_STRING{
.Length = path_len_bytes,
.MaximumLength = path_len_bytes,
// The Windows API makes this mutable, but it will not mutate here.
.Buffer = @intToPtr([*]u16, @ptrToInt(sub_path_w)),
};
if (sub_path_w[0] == '.' and sub_path_w[1] == 0) {
// Windows does not recognize this, but it does work with empty string.
nt_name.Length = 0;
}
if (sub_path_w[0] == '.' and sub_path_w[1] == '.' and sub_path_w[2] == 0) {
// Can't remove the parent directory with an open handle.
return error.FileBusy;
}
var attr = w.OBJECT_ATTRIBUTES{
.Length = @sizeOf(w.OBJECT_ATTRIBUTES),
.RootDirectory = if (std.fs.path.isAbsoluteWindowsW(sub_path_w)) null else dirfd,
.Attributes = 0, // Note we do not use OBJ_CASE_INSENSITIVE here.
.ObjectName = &nt_name,
.SecurityDescriptor = null,
.SecurityQualityOfService = null,
};
var io: w.IO_STATUS_BLOCK = undefined;
var tmp_handle: w.HANDLE = undefined;
var rc = w.ntdll.NtCreateFile(
&tmp_handle,
w.SYNCHRONIZE | w.DELETE,
&attr,
&io,
null,
0,
w.FILE_SHARE_READ | w.FILE_SHARE_WRITE | w.FILE_SHARE_DELETE,
w.FILE_OPEN,
create_options_flags,
null,
0,
);
if (rc == .SUCCESS) {
rc = w.ntdll.NtClose(tmp_handle);
}
switch (rc) {
.SUCCESS => return,
.OBJECT_NAME_INVALID => unreachable,
.OBJECT_NAME_NOT_FOUND => return error.FileNotFound,
.INVALID_PARAMETER => unreachable,
.FILE_IS_A_DIRECTORY => return error.IsDir,
else => return w.unexpectedStatus(rc),
}
}
const RenameError = error{
AccessDenied,
FileBusy,
DiskQuota,
IsDir,
SymLinkLoop,
LinkQuotaExceeded,
NameTooLong,
FileNotFound,
NotDir,
SystemResources,
NoSpaceLeft,
PathAlreadyExists,
ReadOnlyFileSystem,
RenameAcrossMountPoints,
InvalidUtf8,
BadPathName,
NoDevice,
SharingViolation,
PipeBusy,
} || UnexpectedError;
/// Change the name or location of a file.
pub fn rename(old_path: []const u8, new_path: []const u8) RenameError!void {
if (builtin.os.tag == .windows) {
const old_path_w = try windows.sliceToPrefixedFileW(old_path);
const new_path_w = try windows.sliceToPrefixedFileW(new_path);
return renameW(&old_path_w, &new_path_w);
} else {
const old_path_c = try toPosixPath(old_path);
const new_path_c = try toPosixPath(new_path);
return renameZ(&old_path_c, &new_path_c);
}
}
pub const renameC = @compileError("deprecated: renamed to renameZ");
/// Same as `rename` except the parameters are null-terminated byte arrays.
pub fn renameZ(old_path: [*:0]const u8, new_path: [*:0]const u8) RenameError!void {
if (builtin.os.tag == .windows) {
const old_path_w = try windows.cStrToPrefixedFileW(old_path);
const new_path_w = try windows.cStrToPrefixedFileW(new_path);
return renameW(&old_path_w, &new_path_w);
}
switch (errno(system.rename(old_path, new_path))) {
0 => return,
EACCES => return error.AccessDenied,
EPERM => return error.AccessDenied,
EBUSY => return error.FileBusy,
EDQUOT => return error.DiskQuota,
EFAULT => unreachable,
EINVAL => unreachable,
EISDIR => return error.IsDir,
ELOOP => return error.SymLinkLoop,
EMLINK => return error.LinkQuotaExceeded,
ENAMETOOLONG => return error.NameTooLong,
ENOENT => return error.FileNotFound,
ENOTDIR => return error.NotDir,
ENOMEM => return error.SystemResources,
ENOSPC => return error.NoSpaceLeft,
EEXIST => return error.PathAlreadyExists,
ENOTEMPTY => return error.PathAlreadyExists,
EROFS => return error.ReadOnlyFileSystem,
EXDEV => return error.RenameAcrossMountPoints,
else => |err| return unexpectedErrno(err),
}
}
/// Same as `rename` except the parameters are null-terminated UTF16LE encoded byte arrays.
/// Assumes target is Windows.
pub fn renameW(old_path: [*:0]const u16, new_path: [*:0]const u16) RenameError!void {
const flags = windows.MOVEFILE_REPLACE_EXISTING | windows.MOVEFILE_WRITE_THROUGH;
return windows.MoveFileExW(old_path, new_path, flags);
}
/// Change the name or location of a file based on an open directory handle.
pub fn renameat(
old_dir_fd: fd_t,
old_path: []const u8,
new_dir_fd: fd_t,
new_path: []const u8,
) RenameError!void {
if (builtin.os.tag == .windows) {
const old_path_w = try windows.sliceToPrefixedFileW(old_path);
const new_path_w = try windows.sliceToPrefixedFileW(new_path);
return renameatW(old_dir_fd, &old_path_w, new_dir_fd, &new_path_w, windows.TRUE);
} else {
const old_path_c = try toPosixPath(old_path);
const new_path_c = try toPosixPath(new_path);
return renameatZ(old_dir_fd, &old_path_c, new_dir_fd, &new_path_c);
}
}
/// Same as `renameat` except the parameters are null-terminated byte arrays.
pub fn renameatZ(
old_dir_fd: fd_t,
old_path: [*:0]const u8,
new_dir_fd: fd_t,
new_path: [*:0]const u8,
) RenameError!void {
if (builtin.os.tag == .windows) {
const old_path_w = try windows.cStrToPrefixedFileW(old_path);
const new_path_w = try windows.cStrToPrefixedFileW(new_path);
return renameatW(old_dir_fd, &old_path_w, new_dir_fd, &new_path_w, windows.TRUE);
}
switch (errno(system.renameat(old_dir_fd, old_path, new_dir_fd, new_path))) {
0 => return,
EACCES => return error.AccessDenied,
EPERM => return error.AccessDenied,
EBUSY => return error.FileBusy,
EDQUOT => return error.DiskQuota,
EFAULT => unreachable,
EINVAL => unreachable,
EISDIR => return error.IsDir,
ELOOP => return error.SymLinkLoop,
EMLINK => return error.LinkQuotaExceeded,
ENAMETOOLONG => return error.NameTooLong,
ENOENT => return error.FileNotFound,
ENOTDIR => return error.NotDir,
ENOMEM => return error.SystemResources,
ENOSPC => return error.NoSpaceLeft,
EEXIST => return error.PathAlreadyExists,
ENOTEMPTY => return error.PathAlreadyExists,
EROFS => return error.ReadOnlyFileSystem,
EXDEV => return error.RenameAcrossMountPoints,
else => |err| return unexpectedErrno(err),
}
}
/// Same as `renameat` except the parameters are null-terminated UTF16LE encoded byte arrays.
/// Assumes target is Windows.
/// TODO these args can actually be slices when using ntdll. audit the rest of the W functions too.
pub fn renameatW(
old_dir_fd: fd_t,
old_path: [*:0]const u16,
new_dir_fd: fd_t,
new_path_w: [*:0]const u16,
ReplaceIfExists: windows.BOOLEAN,
) RenameError!void {
const access_mask = windows.SYNCHRONIZE | windows.GENERIC_WRITE | windows.DELETE;
const src_fd = windows.OpenFileW(old_dir_fd, old_path, null, access_mask, null, false, windows.FILE_OPEN) catch |err| switch (err) {
error.WouldBlock => unreachable,
else => |e| return e,
};
defer windows.CloseHandle(src_fd);
const struct_buf_len = @sizeOf(windows.FILE_RENAME_INFORMATION) + (MAX_PATH_BYTES - 1);
var rename_info_buf: [struct_buf_len]u8 align(@alignOf(windows.FILE_RENAME_INFORMATION)) = undefined;
const new_path = mem.span(new_path_w);
const struct_len = @sizeOf(windows.FILE_RENAME_INFORMATION) - 1 + new_path.len * 2;
if (struct_len > struct_buf_len) return error.NameTooLong;
const rename_info = @ptrCast(*windows.FILE_RENAME_INFORMATION, &rename_info_buf);
rename_info.* = .{
.ReplaceIfExists = ReplaceIfExists,
.RootDirectory = if (std.fs.path.isAbsoluteWindowsW(new_path_w)) null else new_dir_fd,
.FileNameLength = @intCast(u32, new_path.len * 2), // already checked error.NameTooLong
.FileName = undefined,
};
std.mem.copy(u16, @as([*]u16, &rename_info.FileName)[0..new_path.len], new_path);
var io_status_block: windows.IO_STATUS_BLOCK = undefined;
const rc = windows.ntdll.NtSetInformationFile(
src_fd,
&io_status_block,
rename_info,
@intCast(u32, struct_len), // already checked for error.NameTooLong
.FileRenameInformation,
);
switch (rc) {
.SUCCESS => return,
.INVALID_HANDLE => unreachable,
.INVALID_PARAMETER => unreachable,
.OBJECT_PATH_SYNTAX_BAD => unreachable,
.ACCESS_DENIED => return error.AccessDenied,
.OBJECT_NAME_NOT_FOUND => return error.FileNotFound,
.OBJECT_PATH_NOT_FOUND => return error.FileNotFound,
else => return windows.unexpectedStatus(rc),
}
}
pub const MakeDirError = error{
AccessDenied,
DiskQuota,
PathAlreadyExists,
SymLinkLoop,
LinkQuotaExceeded,
NameTooLong,
FileNotFound,
SystemResources,
NoSpaceLeft,
NotDir,
ReadOnlyFileSystem,
InvalidUtf8,
BadPathName,
NoDevice,
} || UnexpectedError;
pub fn mkdirat(dir_fd: fd_t, sub_dir_path: []const u8, mode: u32) MakeDirError!void {
if (builtin.os.tag == .windows) {
const sub_dir_path_w = try windows.sliceToPrefixedFileW(sub_dir_path);
return mkdiratW(dir_fd, &sub_dir_path_w, mode);
} else {
const sub_dir_path_c = try toPosixPath(sub_dir_path);
return mkdiratZ(dir_fd, &sub_dir_path_c, mode);
}
}
pub const mkdiratC = @compileError("deprecated: renamed to mkdiratZ");
pub fn mkdiratZ(dir_fd: fd_t, sub_dir_path: [*:0]const u8, mode: u32) MakeDirError!void {
if (builtin.os.tag == .windows) {
const sub_dir_path_w = try windows.cStrToPrefixedFileW(sub_dir_path);
return mkdiratW(dir_fd, &sub_dir_path_w, mode);
}
switch (errno(system.mkdirat(dir_fd, sub_dir_path, mode))) {
0 => return,
EACCES => return error.AccessDenied,
EBADF => unreachable,
EPERM => return error.AccessDenied,
EDQUOT => return error.DiskQuota,
EEXIST => return error.PathAlreadyExists,
EFAULT => unreachable,
ELOOP => return error.SymLinkLoop,
EMLINK => return error.LinkQuotaExceeded,
ENAMETOOLONG => return error.NameTooLong,
ENOENT => return error.FileNotFound,
ENOMEM => return error.SystemResources,
ENOSPC => return error.NoSpaceLeft,
ENOTDIR => return error.NotDir,
EROFS => return error.ReadOnlyFileSystem,
else => |err| return unexpectedErrno(err),
}
}
pub fn mkdiratW(dir_fd: fd_t, sub_path_w: [*:0]const u16, mode: u32) MakeDirError!void {
const sub_dir_handle = try windows.CreateDirectoryW(dir_fd, sub_path_w, null);
windows.CloseHandle(sub_dir_handle);
}
/// Create a directory.
/// `mode` is ignored on Windows.
pub fn mkdir(dir_path: []const u8, mode: u32) MakeDirError!void {
if (builtin.os.tag == .windows) {
const sub_dir_handle = try windows.CreateDirectory(null, dir_path, null);
windows.CloseHandle(sub_dir_handle);
return;
} else {
const dir_path_c = try toPosixPath(dir_path);
return mkdirZ(&dir_path_c, mode);
}
}
/// Same as `mkdir` but the parameter is a null-terminated UTF8-encoded string.
pub fn mkdirZ(dir_path: [*:0]const u8, mode: u32) MakeDirError!void {
if (builtin.os.tag == .windows) {
const dir_path_w = try windows.cStrToPrefixedFileW(dir_path);
const sub_dir_handle = try windows.CreateDirectoryW(null, &dir_path_w, null);
windows.CloseHandle(sub_dir_handle);
return;
}
switch (errno(system.mkdir(dir_path, mode))) {
0 => return,
EACCES => return error.AccessDenied,
EPERM => return error.AccessDenied,
EDQUOT => return error.DiskQuota,
EEXIST => return error.PathAlreadyExists,
EFAULT => unreachable,
ELOOP => return error.SymLinkLoop,
EMLINK => return error.LinkQuotaExceeded,
ENAMETOOLONG => return error.NameTooLong,
ENOENT => return error.FileNotFound,
ENOMEM => return error.SystemResources,
ENOSPC => return error.NoSpaceLeft,
ENOTDIR => return error.NotDir,
EROFS => return error.ReadOnlyFileSystem,
else => |err| return unexpectedErrno(err),
}
}
pub const DeleteDirError = error{
AccessDenied,
FileBusy,
SymLinkLoop,
NameTooLong,
FileNotFound,
SystemResources,
NotDir,
DirNotEmpty,
ReadOnlyFileSystem,
InvalidUtf8,
BadPathName,
} || UnexpectedError;
/// Deletes an empty directory.
pub fn rmdir(dir_path: []const u8) DeleteDirError!void {
if (builtin.os.tag == .windows) {
const dir_path_w = try windows.sliceToPrefixedFileW(dir_path);
return windows.RemoveDirectoryW(&dir_path_w);
} else {
const dir_path_c = try toPosixPath(dir_path);
return rmdirZ(&dir_path_c);
}
}
pub const rmdirC = @compileError("deprecated: renamed to rmdirZ");
/// Same as `rmdir` except the parameter is null-terminated.
pub fn rmdirZ(dir_path: [*:0]const u8) DeleteDirError!void {
if (builtin.os.tag == .windows) {
const dir_path_w = try windows.cStrToPrefixedFileW(dir_path);
return windows.RemoveDirectoryW(&dir_path_w);
}
switch (errno(system.rmdir(dir_path))) {
0 => return,
EACCES => return error.AccessDenied,
EPERM => return error.AccessDenied,
EBUSY => return error.FileBusy,
EFAULT => unreachable,
EINVAL => unreachable,
ELOOP => return error.SymLinkLoop,
ENAMETOOLONG => return error.NameTooLong,
ENOENT => return error.FileNotFound,
ENOMEM => return error.SystemResources,
ENOTDIR => return error.NotDir,
EEXIST => return error.DirNotEmpty,
ENOTEMPTY => return error.DirNotEmpty,
EROFS => return error.ReadOnlyFileSystem,
else => |err| return unexpectedErrno(err),
}
}
pub const ChangeCurDirError = error{
AccessDenied,
FileSystem,
SymLinkLoop,
NameTooLong,
FileNotFound,
SystemResources,
NotDir,
} || UnexpectedError;
/// Changes the current working directory of the calling process.
/// `dir_path` is recommended to be a UTF-8 encoded string.
pub fn chdir(dir_path: []const u8) ChangeCurDirError!void {
if (builtin.os.tag == .windows) {
const dir_path_w = try windows.sliceToPrefixedFileW(dir_path);
@compileError("TODO implement chdir for Windows");
} else {
const dir_path_c = try toPosixPath(dir_path);
return chdirZ(&dir_path_c);
}
}
pub const chdirC = @compileError("deprecated: renamed to chdirZ");
/// Same as `chdir` except the parameter is null-terminated.
pub fn chdirZ(dir_path: [*:0]const u8) ChangeCurDirError!void {
if (builtin.os.tag == .windows) {
const dir_path_w = try windows.cStrToPrefixedFileW(dir_path);
@compileError("TODO implement chdir for Windows");
}
switch (errno(system.chdir(dir_path))) {
0 => return,
EACCES => return error.AccessDenied,
EFAULT => unreachable,
EIO => return error.FileSystem,
ELOOP => return error.SymLinkLoop,
ENAMETOOLONG => return error.NameTooLong,
ENOENT => return error.FileNotFound,
ENOMEM => return error.SystemResources,
ENOTDIR => return error.NotDir,
else => |err| return unexpectedErrno(err),
}
}
pub const FchdirError = error{
AccessDenied,
NotDir,
FileSystem,
} || UnexpectedError;
pub fn fchdir(dirfd: fd_t) FchdirError!void {
while (true) {
switch (errno(system.fchdir(dirfd))) {
0 => return,
EACCES => return error.AccessDenied,
EBADF => unreachable,
ENOTDIR => return error.NotDir,
EINTR => continue,
EIO => return error.FileSystem,
else => |err| return unexpectedErrno(err),
}
}
}
pub const ReadLinkError = error{
AccessDenied,
FileSystem,
SymLinkLoop,
NameTooLong,
FileNotFound,
SystemResources,
NotDir,
} || UnexpectedError;
/// Read value of a symbolic link.
/// The return value is a slice of `out_buffer` from index 0.
pub fn readlink(file_path: []const u8, out_buffer: []u8) ReadLinkError![]u8 {
if (builtin.os.tag == .windows) {
const file_path_w = try windows.sliceToPrefixedFileW(file_path);
@compileError("TODO implement readlink for Windows");
} else {
const file_path_c = try toPosixPath(file_path);
return readlinkZ(&file_path_c, out_buffer);
}
}
pub const readlinkC = @compileError("deprecated: renamed to readlinkZ");
/// Same as `readlink` except `file_path` is null-terminated.
pub fn readlinkZ(file_path: [*:0]const u8, out_buffer: []u8) ReadLinkError![]u8 {
if (builtin.os.tag == .windows) {
const file_path_w = try windows.cStrToPrefixedFileW(file_path);
@compileError("TODO implement readlink for Windows");
}
const rc = system.readlink(file_path, out_buffer.ptr, out_buffer.len);
switch (errno(rc)) {
0 => return out_buffer[0..@bitCast(usize, rc)],
EACCES => return error.AccessDenied,
EFAULT => unreachable,
EINVAL => unreachable,
EIO => return error.FileSystem,
ELOOP => return error.SymLinkLoop,
ENAMETOOLONG => return error.NameTooLong,
ENOENT => return error.FileNotFound,
ENOMEM => return error.SystemResources,
ENOTDIR => return error.NotDir,
else => |err| return unexpectedErrno(err),
}
}
pub const readlinkatC = @compileError("deprecated: renamed to readlinkatZ");
pub fn readlinkatZ(dirfd: fd_t, file_path: [*:0]const u8, out_buffer: []u8) ReadLinkError![]u8 {
if (builtin.os.tag == .windows) {
const file_path_w = try windows.cStrToPrefixedFileW(file_path);
@compileError("TODO implement readlink for Windows");
}
const rc = system.readlinkat(dirfd, file_path, out_buffer.ptr, out_buffer.len);
switch (errno(rc)) {
0 => return out_buffer[0..@bitCast(usize, rc)],
EACCES => return error.AccessDenied,
EFAULT => unreachable,
EINVAL => unreachable,
EIO => return error.FileSystem,
ELOOP => return error.SymLinkLoop,
ENAMETOOLONG => return error.NameTooLong,
ENOENT => return error.FileNotFound,
ENOMEM => return error.SystemResources,
ENOTDIR => return error.NotDir,
else => |err| return unexpectedErrno(err),
}
}
pub const SetIdError = error{
ResourceLimitReached,
InvalidUserId,
PermissionDenied,
} || UnexpectedError;
pub fn setuid(uid: u32) SetIdError!void {
switch (errno(system.setuid(uid))) {
0 => return,
EAGAIN => return error.ResourceLimitReached,
EINVAL => return error.InvalidUserId,
EPERM => return error.PermissionDenied,
else => |err| return unexpectedErrno(err),
}
}
pub fn setreuid(ruid: u32, euid: u32) SetIdError!void {
switch (errno(system.setreuid(ruid, euid))) {
0 => return,
EAGAIN => return error.ResourceLimitReached,
EINVAL => return error.InvalidUserId,
EPERM => return error.PermissionDenied,
else => |err| return unexpectedErrno(err),
}
}
pub fn setgid(gid: u32) SetIdError!void {
switch (errno(system.setgid(gid))) {
0 => return,
EAGAIN => return error.ResourceLimitReached,
EINVAL => return error.InvalidUserId,
EPERM => return error.PermissionDenied,
else => |err| return unexpectedErrno(err),
}
}
pub fn setregid(rgid: u32, egid: u32) SetIdError!void {
switch (errno(system.setregid(rgid, egid))) {
0 => return,
EAGAIN => return error.ResourceLimitReached,
EINVAL => return error.InvalidUserId,
EPERM => return error.PermissionDenied,
else => |err| return unexpectedErrno(err),
}
}
/// Test whether a file descriptor refers to a terminal.
pub fn isatty(handle: fd_t) bool {
if (builtin.os.tag == .windows) {
if (isCygwinPty(handle))
return true;
var out: windows.DWORD = undefined;
return windows.kernel32.GetConsoleMode(handle, &out) != 0;
}
if (builtin.link_libc) {
return system.isatty(handle) != 0;
}
if (builtin.os.tag == .wasi) {
var statbuf: fdstat_t = undefined;
const err = system.fd_fdstat_get(handle, &statbuf);
if (err != 0) {
// errno = err;
return false;
}
// A tty is a character device that we can't seek or tell on.
if (statbuf.fs_filetype != FILETYPE_CHARACTER_DEVICE or
(statbuf.fs_rights_base & (RIGHT_FD_SEEK | RIGHT_FD_TELL)) != 0)
{
// errno = ENOTTY;
return false;
}
return true;
}
if (builtin.os.tag == .linux) {
var wsz: linux.winsize = undefined;
return linux.syscall3(.ioctl, @bitCast(usize, @as(isize, handle)), linux.TIOCGWINSZ, @ptrToInt(&wsz)) == 0;
}
unreachable;
}
pub fn isCygwinPty(handle: fd_t) bool {
if (builtin.os.tag != .windows) return false;
const size = @sizeOf(windows.FILE_NAME_INFO);
var name_info_bytes align(@alignOf(windows.FILE_NAME_INFO)) = [_]u8{0} ** (size + windows.MAX_PATH);
if (windows.kernel32.GetFileInformationByHandleEx(
handle,
windows.FileNameInfo,
@ptrCast(*c_void, &name_info_bytes),
name_info_bytes.len,
) == 0) {
return false;
}
const name_info = @ptrCast(*const windows.FILE_NAME_INFO, &name_info_bytes[0]);
const name_bytes = name_info_bytes[size .. size + @as(usize, name_info.FileNameLength)];
const name_wide = mem.bytesAsSlice(u16, name_bytes);
return mem.indexOf(u16, name_wide, &[_]u16{ 'm', 's', 'y', 's', '-' }) != null or
mem.indexOf(u16, name_wide, &[_]u16{ '-', 'p', 't', 'y' }) != null;
}
pub const SocketError = error{
/// Permission to create a socket of the specified type and/or
/// pro‐tocol is denied.
PermissionDenied,
/// The implementation does not support the specified address family.
AddressFamilyNotSupported,
/// Unknown protocol, or protocol family not available.
ProtocolFamilyNotAvailable,
/// The per-process limit on the number of open file descriptors has been reached.
ProcessFdQuotaExceeded,
/// The system-wide limit on the total number of open files has been reached.
SystemFdQuotaExceeded,
/// Insufficient memory is available. The socket cannot be created until sufficient
/// resources are freed.
SystemResources,
/// The protocol type or the specified protocol is not supported within this domain.
ProtocolNotSupported,
} || UnexpectedError;
pub fn socket(domain: u32, socket_type: u32, protocol: u32) SocketError!fd_t {
const rc = system.socket(domain, socket_type, protocol);
switch (errno(rc)) {
0 => return @intCast(fd_t, rc),
EACCES => return error.PermissionDenied,
EAFNOSUPPORT => return error.AddressFamilyNotSupported,
EINVAL => return error.ProtocolFamilyNotAvailable,
EMFILE => return error.ProcessFdQuotaExceeded,
ENFILE => return error.SystemFdQuotaExceeded,
ENOBUFS => return error.SystemResources,
ENOMEM => return error.SystemResources,
EPROTONOSUPPORT => return error.ProtocolNotSupported,
else => |err| return unexpectedErrno(err),
}
}
pub const BindError = error{
/// The address is protected, and the user is not the superuser.
/// For UNIX domain sockets: Search permission is denied on a component
/// of the path prefix.
AccessDenied,
/// The given address is already in use, or in the case of Internet domain sockets,
/// The port number was specified as zero in the socket
/// address structure, but, upon attempting to bind to an ephemeral port, it was
/// determined that all port numbers in the ephemeral port range are currently in
/// use. See the discussion of /proc/sys/net/ipv4/ip_local_port_range ip(7).
AddressInUse,
/// A nonexistent interface was requested or the requested address was not local.
AddressNotAvailable,
/// Too many symbolic links were encountered in resolving addr.
SymLinkLoop,
/// addr is too long.
NameTooLong,
/// A component in the directory prefix of the socket pathname does not exist.
FileNotFound,
/// Insufficient kernel memory was available.
SystemResources,
/// A component of the path prefix is not a directory.
NotDir,
/// The socket inode would reside on a read-only filesystem.
ReadOnlyFileSystem,
} || UnexpectedError;
/// addr is `*const T` where T is one of the sockaddr
pub fn bind(sockfd: fd_t, addr: *const sockaddr, len: socklen_t) BindError!void {
const rc = system.bind(sockfd, addr, len);
switch (errno(rc)) {
0 => return,
EACCES => return error.AccessDenied,
EADDRINUSE => return error.AddressInUse,
EBADF => unreachable, // always a race condition if this error is returned
EINVAL => unreachable, // invalid parameters
ENOTSOCK => unreachable, // invalid `sockfd`
EADDRNOTAVAIL => return error.AddressNotAvailable,
EFAULT => unreachable, // invalid `addr` pointer
ELOOP => return error.SymLinkLoop,
ENAMETOOLONG => return error.NameTooLong,
ENOENT => return error.FileNotFound,
ENOMEM => return error.SystemResources,
ENOTDIR => return error.NotDir,
EROFS => return error.ReadOnlyFileSystem,
else => |err| return unexpectedErrno(err),
}
}
const ListenError = error{
/// Another socket is already listening on the same port.
/// For Internet domain sockets, the socket referred to by sockfd had not previously
/// been bound to an address and, upon attempting to bind it to an ephemeral port, it
/// was determined that all port numbers in the ephemeral port range are currently in
/// use. See the discussion of /proc/sys/net/ipv4/ip_local_port_range in ip(7).
AddressInUse,
/// The file descriptor sockfd does not refer to a socket.
FileDescriptorNotASocket,
/// The socket is not of a type that supports the listen() operation.
OperationNotSupported,
} || UnexpectedError;
pub fn listen(sockfd: fd_t, backlog: u32) ListenError!void {
const rc = system.listen(sockfd, backlog);
switch (errno(rc)) {
0 => return,
EADDRINUSE => return error.AddressInUse,
EBADF => unreachable,
ENOTSOCK => return error.FileDescriptorNotASocket,
EOPNOTSUPP => return error.OperationNotSupported,
else => |err| return unexpectedErrno(err),
}
}
pub const AcceptError = error{
ConnectionAborted,
/// The per-process limit on the number of open file descriptors has been reached.
ProcessFdQuotaExceeded,
/// The system-wide limit on the total number of open files has been reached.
SystemFdQuotaExceeded,
/// Not enough free memory. This often means that the memory allocation is limited
/// by the socket buffer limits, not by the system memory.
SystemResources,
ProtocolFailure,
/// Firewall rules forbid connection.
BlockedByFirewall,
/// This error occurs when no global event loop is configured,
/// and accepting from the socket would block.
WouldBlock,
} || UnexpectedError;
/// Accept a connection on a socket.
/// If the application has a global event loop enabled, EAGAIN is handled
/// via the event loop. Otherwise EAGAIN results in error.WouldBlock.
pub fn accept4(
/// This argument is a socket that has been created with `socket`, bound to a local address
/// with `bind`, and is listening for connections after a `listen`.
sockfd: fd_t,
/// This argument is a pointer to a sockaddr structure. This structure is filled in with the
/// address of the peer socket, as known to the communications layer. The exact format of the
/// address returned addr is determined by the socket's address family (see `socket` and the
/// respective protocol man pages).
addr: *sockaddr,
/// This argument is a value-result argument: the caller must initialize it to contain the
/// size (in bytes) of the structure pointed to by addr; on return it will contain the actual size
/// of the peer address.
///
/// The returned address is truncated if the buffer provided is too small; in this case, `addr_size`
/// will return a value greater than was supplied to the call.
addr_size: *socklen_t,
/// If flags is 0, then `accept4` is the same as `accept`. The following values can be bitwise
/// ORed in flags to obtain different behavior:
/// * `SOCK_NONBLOCK` - Set the `O_NONBLOCK` file status flag on the open file description (see `open`)
/// referred to by the new file descriptor. Using this flag saves extra calls to `fcntl` to achieve
/// the same result.
/// * `SOCK_CLOEXEC` - Set the close-on-exec (`FD_CLOEXEC`) flag on the new file descriptor. See the
/// description of the `O_CLOEXEC` flag in `open` for reasons why this may be useful.
flags: u32,
) AcceptError!fd_t {
while (true) {
const rc = system.accept4(sockfd, addr, addr_size, flags);
switch (errno(rc)) {
0 => return @intCast(fd_t, rc),
EINTR => continue,
EAGAIN => if (std.event.Loop.instance) |loop| {
loop.waitUntilFdReadable(sockfd);
continue;
} else {
return error.WouldBlock;
},
EBADF => unreachable, // always a race condition
ECONNABORTED => return error.ConnectionAborted,
EFAULT => unreachable,
EINVAL => unreachable,
ENOTSOCK => unreachable,
EMFILE => return error.ProcessFdQuotaExceeded,
ENFILE => return error.SystemFdQuotaExceeded,
ENOBUFS => return error.SystemResources,
ENOMEM => return error.SystemResources,
EOPNOTSUPP => unreachable,
EPROTO => return error.ProtocolFailure,
EPERM => return error.BlockedByFirewall,
else => |err| return unexpectedErrno(err),
}
}
}
pub const EpollCreateError = error{
/// The per-user limit on the number of epoll instances imposed by
/// /proc/sys/fs/epoll/max_user_instances was encountered. See epoll(7) for further
/// details.
/// Or, The per-process limit on the number of open file descriptors has been reached.
ProcessFdQuotaExceeded,
/// The system-wide limit on the total number of open files has been reached.
SystemFdQuotaExceeded,
/// There was insufficient memory to create the kernel object.
SystemResources,
} || UnexpectedError;
pub fn epoll_create1(flags: u32) EpollCreateError!i32 {
const rc = system.epoll_create1(flags);
switch (errno(rc)) {
0 => return @intCast(i32, rc),
else => |err| return unexpectedErrno(err),
EINVAL => unreachable,
EMFILE => return error.ProcessFdQuotaExceeded,
ENFILE => return error.SystemFdQuotaExceeded,
ENOMEM => return error.SystemResources,
}
}
pub const EpollCtlError = error{
/// op was EPOLL_CTL_ADD, and the supplied file descriptor fd is already registered
/// with this epoll instance.
FileDescriptorAlreadyPresentInSet,
/// fd refers to an epoll instance and this EPOLL_CTL_ADD operation would result in a
/// circular loop of epoll instances monitoring one another.
OperationCausesCircularLoop,
/// op was EPOLL_CTL_MOD or EPOLL_CTL_DEL, and fd is not registered with this epoll
/// instance.
FileDescriptorNotRegistered,
/// There was insufficient memory to handle the requested op control operation.
SystemResources,
/// The limit imposed by /proc/sys/fs/epoll/max_user_watches was encountered while
/// trying to register (EPOLL_CTL_ADD) a new file descriptor on an epoll instance.
/// See epoll(7) for further details.
UserResourceLimitReached,
/// The target file fd does not support epoll. This error can occur if fd refers to,
/// for example, a regular file or a directory.
FileDescriptorIncompatibleWithEpoll,
} || UnexpectedError;
pub fn epoll_ctl(epfd: i32, op: u32, fd: i32, event: ?*epoll_event) EpollCtlError!void {
const rc = system.epoll_ctl(epfd, op, fd, event);
switch (errno(rc)) {
0 => return,
else => |err| return unexpectedErrno(err),
EBADF => unreachable, // always a race condition if this happens
EEXIST => return error.FileDescriptorAlreadyPresentInSet,
EINVAL => unreachable,
ELOOP => return error.OperationCausesCircularLoop,
ENOENT => return error.FileDescriptorNotRegistered,
ENOMEM => return error.SystemResources,
ENOSPC => return error.UserResourceLimitReached,
EPERM => return error.FileDescriptorIncompatibleWithEpoll,
}
}
/// Waits for an I/O event on an epoll file descriptor.
/// Returns the number of file descriptors ready for the requested I/O,
/// or zero if no file descriptor became ready during the requested timeout milliseconds.
pub fn epoll_wait(epfd: i32, events: []epoll_event, timeout: i32) usize {
while (true) {
// TODO get rid of the @intCast
const rc = system.epoll_wait(epfd, events.ptr, @intCast(u32, events.len), timeout);
switch (errno(rc)) {
0 => return @intCast(usize, rc),
EINTR => continue,
EBADF => unreachable,
EFAULT => unreachable,
EINVAL => unreachable,
else => unreachable,
}
}
}
pub const EventFdError = error{
SystemResources,
ProcessFdQuotaExceeded,
SystemFdQuotaExceeded,
} || UnexpectedError;
pub fn eventfd(initval: u32, flags: u32) EventFdError!i32 {
const rc = system.eventfd(initval, flags);
switch (errno(rc)) {
0 => return @intCast(i32, rc),
else => |err| return unexpectedErrno(err),
EINVAL => unreachable, // invalid parameters
EMFILE => return error.ProcessFdQuotaExceeded,
ENFILE => return error.SystemFdQuotaExceeded,
ENODEV => return error.SystemResources,
ENOMEM => return error.SystemResources,
}
}
pub const GetSockNameError = error{
/// Insufficient resources were available in the system to perform the operation.
SystemResources,
} || UnexpectedError;
pub fn getsockname(sockfd: fd_t, addr: *sockaddr, addrlen: *socklen_t) GetSockNameError!void {
switch (errno(system.getsockname(sockfd, addr, addrlen))) {
0 => return,
else => |err| return unexpectedErrno(err),
EBADF => unreachable, // always a race condition
EFAULT => unreachable,
EINVAL => unreachable, // invalid parameters
ENOTSOCK => unreachable,
ENOBUFS => return error.SystemResources,
}
}
pub const ConnectError = error{
/// For UNIX domain sockets, which are identified by pathname: Write permission is denied on the socket
/// file, or search permission is denied for one of the directories in the path prefix.
/// or
/// The user tried to connect to a broadcast address without having the socket broadcast flag enabled or
/// the connection request failed because of a local firewall rule.
PermissionDenied,
/// Local address is already in use.
AddressInUse,
/// (Internet domain sockets) The socket referred to by sockfd had not previously been bound to an
/// address and, upon attempting to bind it to an ephemeral port, it was determined that all port numbers
/// in the ephemeral port range are currently in use. See the discussion of
/// /proc/sys/net/ipv4/ip_local_port_range in ip(7).
AddressNotAvailable,
/// The passed address didn't have the correct address family in its sa_family field.
AddressFamilyNotSupported,
/// Insufficient entries in the routing cache.
SystemResources,
/// A connect() on a stream socket found no one listening on the remote address.
ConnectionRefused,
/// Network is unreachable.
NetworkUnreachable,
/// Timeout while attempting connection. The server may be too busy to accept new connections. Note
/// that for IP sockets the timeout may be very long when syncookies are enabled on the server.
ConnectionTimedOut,
/// This error occurs when no global event loop is configured,
/// and connecting to the socket would block.
WouldBlock,
/// The given path for the unix socket does not exist.
FileNotFound,
} || UnexpectedError;
/// Initiate a connection on a socket.
pub fn connect(sockfd: fd_t, sock_addr: *const sockaddr, len: socklen_t) ConnectError!void {
while (true) {
switch (errno(system.connect(sockfd, sock_addr, len))) {
0 => return,
EACCES => return error.PermissionDenied,
EPERM => return error.PermissionDenied,
EADDRINUSE => return error.AddressInUse,
EADDRNOTAVAIL => return error.AddressNotAvailable,
EAFNOSUPPORT => return error.AddressFamilyNotSupported,
EAGAIN, EINPROGRESS => {
const loop = std.event.Loop.instance orelse return error.WouldBlock;
loop.waitUntilFdWritableOrReadable(sockfd);
return getsockoptError(sockfd);
},
EALREADY => unreachable, // The socket is nonblocking and a previous connection attempt has not yet been completed.
EBADF => unreachable, // sockfd is not a valid open file descriptor.
ECONNREFUSED => return error.ConnectionRefused,
EFAULT => unreachable, // The socket structure address is outside the user's address space.
EINTR => continue,
EISCONN => unreachable, // The socket is already connected.
ENETUNREACH => return error.NetworkUnreachable,
ENOTSOCK => unreachable, // The file descriptor sockfd does not refer to a socket.
EPROTOTYPE => unreachable, // The socket type does not support the requested communications protocol.
ETIMEDOUT => return error.ConnectionTimedOut,
ENOENT => return error.FileNotFound, // Returned when socket is AF_UNIX and the given path does not exist.
else => |err| return unexpectedErrno(err),
}
}
}
pub fn getsockoptError(sockfd: fd_t) ConnectError!void {
var err_code: u32 = undefined;
var size: u32 = @sizeOf(u32);
const rc = system.getsockopt(sockfd, SOL_SOCKET, SO_ERROR, @ptrCast([*]u8, &err_code), &size);
assert(size == 4);
switch (errno(rc)) {
0 => switch (err_code) {
0 => return,
EACCES => return error.PermissionDenied,
EPERM => return error.PermissionDenied,
EADDRINUSE => return error.AddressInUse,
EADDRNOTAVAIL => return error.AddressNotAvailable,
EAFNOSUPPORT => return error.AddressFamilyNotSupported,
EAGAIN => return error.SystemResources,
EALREADY => unreachable, // The socket is nonblocking and a previous connection attempt has not yet been completed.
EBADF => unreachable, // sockfd is not a valid open file descriptor.
ECONNREFUSED => return error.ConnectionRefused,
EFAULT => unreachable, // The socket structure address is outside the user's address space.
EISCONN => unreachable, // The socket is already connected.
ENETUNREACH => return error.NetworkUnreachable,
ENOTSOCK => unreachable, // The file descriptor sockfd does not refer to a socket.
EPROTOTYPE => unreachable, // The socket type does not support the requested communications protocol.
ETIMEDOUT => return error.ConnectionTimedOut,
else => |err| return unexpectedErrno(err),
},
EBADF => unreachable, // The argument sockfd is not a valid file descriptor.
EFAULT => unreachable, // The address pointed to by optval or optlen is not in a valid part of the process address space.
EINVAL => unreachable,
ENOPROTOOPT => unreachable, // The option is unknown at the level indicated.
ENOTSOCK => unreachable, // The file descriptor sockfd does not refer to a socket.
else => |err| return unexpectedErrno(err),
}
}
pub fn waitpid(pid: i32, flags: u32) u32 {
// TODO allow implicit pointer cast from *u32 to *c_uint ?
const Status = if (builtin.link_libc) c_uint else u32;
var status: Status = undefined;
while (true) {
switch (errno(system.waitpid(pid, &status, flags))) {
0 => return @bitCast(u32, status),
EINTR => continue,
ECHILD => unreachable, // The process specified does not exist. It would be a race condition to handle this error.
EINVAL => unreachable, // The options argument was invalid
else => unreachable,
}
}
}
pub const FStatError = error{
SystemResources,
AccessDenied,
} || UnexpectedError;
pub fn fstat(fd: fd_t) FStatError!Stat {
var stat: Stat = undefined;
switch (errno(system.fstat(fd, &stat))) {
0 => return stat,
EINVAL => unreachable,
EBADF => unreachable, // Always a race condition.
ENOMEM => return error.SystemResources,
EACCES => return error.AccessDenied,
else => |err| return unexpectedErrno(err),
}
}
pub const FStatAtError = FStatError || error{NameTooLong, FileNotFound};
pub fn fstatat(dirfd: fd_t, pathname: []const u8, flags: u32) FStatAtError!Stat {
const pathname_c = try toPosixPath(pathname);
return fstatatZ(dirfd, &pathname_c, flags);
}
pub const fstatatC = @compileError("deprecated: renamed to fstatatZ");
pub fn fstatatZ(dirfd: fd_t, pathname: [*:0]const u8, flags: u32) FStatAtError!Stat {
var stat: Stat = undefined;
switch (errno(system.fstatat(dirfd, pathname, &stat, flags))) {
0 => return stat,
EINVAL => unreachable,
EBADF => unreachable, // Always a race condition.
ENOMEM => return error.SystemResources,
EACCES => return error.AccessDenied,
EFAULT => unreachable,
ENAMETOOLONG => return error.NameTooLong,
ENOENT => return error.FileNotFound,
ENOTDIR => return error.FileNotFound,
else => |err| return unexpectedErrno(err),
}
}
pub const KQueueError = error{
/// The per-process limit on the number of open file descriptors has been reached.
ProcessFdQuotaExceeded,
/// The system-wide limit on the total number of open files has been reached.
SystemFdQuotaExceeded,
} || UnexpectedError;
pub fn kqueue() KQueueError!i32 {
const rc = system.kqueue();
switch (errno(rc)) {
0 => return @intCast(i32, rc),
EMFILE => return error.ProcessFdQuotaExceeded,
ENFILE => return error.SystemFdQuotaExceeded,
else => |err| return unexpectedErrno(err),
}
}
pub const KEventError = error{
/// The process does not have permission to register a filter.
AccessDenied,
/// The event could not be found to be modified or deleted.
EventNotFound,
/// No memory was available to register the event.
SystemResources,
/// The specified process to attach to does not exist.
ProcessNotFound,
/// changelist or eventlist had too many items on it.
/// TODO remove this possibility
Overflow,
};
pub fn kevent(
kq: i32,
changelist: []const Kevent,
eventlist: []Kevent,
timeout: ?*const timespec,
) KEventError!usize {
while (true) {
const rc = system.kevent(
kq,
changelist.ptr,
try math.cast(c_int, changelist.len),
eventlist.ptr,
try math.cast(c_int, eventlist.len),
timeout,
);
switch (errno(rc)) {
0 => return @intCast(usize, rc),
EACCES => return error.AccessDenied,
EFAULT => unreachable,
EBADF => unreachable, // Always a race condition.
EINTR => continue,
EINVAL => unreachable,
ENOENT => return error.EventNotFound,
ENOMEM => return error.SystemResources,
ESRCH => return error.ProcessNotFound,
else => unreachable,
}
}
}
pub const INotifyInitError = error{
ProcessFdQuotaExceeded,
SystemFdQuotaExceeded,
SystemResources,
} || UnexpectedError;
/// initialize an inotify instance
pub fn inotify_init1(flags: u32) INotifyInitError!i32 {
const rc = system.inotify_init1(flags);
switch (errno(rc)) {
0 => return @intCast(i32, rc),
EINVAL => unreachable,
EMFILE => return error.ProcessFdQuotaExceeded,
ENFILE => return error.SystemFdQuotaExceeded,
ENOMEM => return error.SystemResources,
else => |err| return unexpectedErrno(err),
}
}
pub const INotifyAddWatchError = error{
AccessDenied,
NameTooLong,
FileNotFound,
SystemResources,
UserResourceLimitReached,
} || UnexpectedError;
/// add a watch to an initialized inotify instance
pub fn inotify_add_watch(inotify_fd: i32, pathname: []const u8, mask: u32) INotifyAddWatchError!i32 {
const pathname_c = try toPosixPath(pathname);
return inotify_add_watchZ(inotify_fd, &pathname_c, mask);
}
pub const inotify_add_watchC = @compileError("deprecated: renamed to inotify_add_watchZ");
/// Same as `inotify_add_watch` except pathname is null-terminated.
pub fn inotify_add_watchZ(inotify_fd: i32, pathname: [*:0]const u8, mask: u32) INotifyAddWatchError!i32 {
const rc = system.inotify_add_watch(inotify_fd, pathname, mask);
switch (errno(rc)) {
0 => return @intCast(i32, rc),
EACCES => return error.AccessDenied,
EBADF => unreachable,
EFAULT => unreachable,
EINVAL => unreachable,
ENAMETOOLONG => return error.NameTooLong,
ENOENT => return error.FileNotFound,
ENOMEM => return error.SystemResources,
ENOSPC => return error.UserResourceLimitReached,
else => |err| return unexpectedErrno(err),
}
}
/// remove an existing watch from an inotify instance
pub fn inotify_rm_watch(inotify_fd: i32, wd: i32) void {
switch (errno(system.inotify_rm_watch(inotify_fd, wd))) {
0 => return,
EBADF => unreachable,
EINVAL => unreachable,
else => unreachable,
}
}
pub const MProtectError = error{
/// The memory cannot be given the specified access. This can happen, for example, if you
/// mmap(2) a file to which you have read-only access, then ask mprotect() to mark it
/// PROT_WRITE.
AccessDenied,
/// Changing the protection of a memory region would result in the total number of map‐
/// pings with distinct attributes (e.g., read versus read/write protection) exceeding the
/// allowed maximum. (For example, making the protection of a range PROT_READ in the mid‐
/// dle of a region currently protected as PROT_READ|PROT_WRITE would result in three map‐
/// pings: two read/write mappings at each end and a read-only mapping in the middle.)
OutOfMemory,
} || UnexpectedError;
/// `memory.len` must be page-aligned.
pub fn mprotect(memory: []align(mem.page_size) u8, protection: u32) MProtectError!void {
assert(mem.isAligned(memory.len, mem.page_size));
switch (errno(system.mprotect(memory.ptr, memory.len, protection))) {
0 => return,
EINVAL => unreachable,
EACCES => return error.AccessDenied,
ENOMEM => return error.OutOfMemory,
else => |err| return unexpectedErrno(err),
}
}
pub const ForkError = error{SystemResources} || UnexpectedError;
pub fn fork() ForkError!pid_t {
const rc = system.fork();
switch (errno(rc)) {
0 => return @intCast(pid_t, rc),
EAGAIN => return error.SystemResources,
ENOMEM => return error.SystemResources,
else => |err| return unexpectedErrno(err),
}
}
pub const MMapError = error{
/// The underlying filesystem of the specified file does not support memory mapping.
MemoryMappingNotSupported,
/// A file descriptor refers to a non-regular file. Or a file mapping was requested,
/// but the file descriptor is not open for reading. Or `MAP_SHARED` was requested
/// and `PROT_WRITE` is set, but the file descriptor is not open in `O_RDWR` mode.
/// Or `PROT_WRITE` is set, but the file is append-only.
AccessDenied,
/// The `prot` argument asks for `PROT_EXEC` but the mapped area belongs to a file on
/// a filesystem that was mounted no-exec.
PermissionDenied,
LockedMemoryLimitExceeded,
OutOfMemory,
} || UnexpectedError;
/// Map files or devices into memory.
/// `length` does not need to be aligned.
/// Use of a mapped region can result in these signals:
/// * SIGSEGV - Attempted write into a region mapped as read-only.
/// * SIGBUS - Attempted access to a portion of the buffer that does not correspond to the file
pub fn mmap(
ptr: ?[*]align(mem.page_size) u8,
length: usize,
prot: u32,
flags: u32,
fd: fd_t,
offset: u64,
) MMapError![]align(mem.page_size) u8 {
const err = if (builtin.link_libc) blk: {
const rc = std.c.mmap(ptr, length, prot, flags, fd, offset);
if (rc != std.c.MAP_FAILED) return @ptrCast([*]align(mem.page_size) u8, @alignCast(mem.page_size, rc))[0..length];
break :blk @intCast(usize, system._errno().*);
} else blk: {
const rc = system.mmap(ptr, length, prot, flags, fd, offset);
const err = errno(rc);
if (err == 0) return @intToPtr([*]align(mem.page_size) u8, rc)[0..length];
break :blk err;
};
switch (err) {
ETXTBSY => return error.AccessDenied,
EACCES => return error.AccessDenied,
EPERM => return error.PermissionDenied,
EAGAIN => return error.LockedMemoryLimitExceeded,
EBADF => unreachable, // Always a race condition.
EOVERFLOW => unreachable, // The number of pages used for length + offset would overflow.
ENODEV => return error.MemoryMappingNotSupported,
EINVAL => unreachable, // Invalid parameters to mmap()
ENOMEM => return error.OutOfMemory,
else => return unexpectedErrno(err),
}
}
/// Deletes the mappings for the specified address range, causing
/// further references to addresses within the range to generate invalid memory references.
/// Note that while POSIX allows unmapping a region in the middle of an existing mapping,
/// Zig's munmap function does not, for two reasons:
/// * It violates the Zig principle that resource deallocation must succeed.
/// * The Windows function, VirtualFree, has this restriction.
pub fn munmap(memory: []align(mem.page_size) u8) void {
switch (errno(system.munmap(memory.ptr, memory.len))) {
0 => return,
EINVAL => unreachable, // Invalid parameters.
ENOMEM => unreachable, // Attempted to unmap a region in the middle of an existing mapping.
else => unreachable,
}
}
pub const AccessError = error{
PermissionDenied,
FileNotFound,
NameTooLong,
InputOutput,
SystemResources,
BadPathName,
FileBusy,
SymLinkLoop,
ReadOnlyFileSystem,
/// On Windows, file paths must be valid Unicode.
InvalidUtf8,
} || UnexpectedError;
/// check user's permissions for a file
/// TODO currently this assumes `mode` is `F_OK` on Windows.
pub fn access(path: []const u8, mode: u32) AccessError!void {
if (builtin.os.tag == .windows) {
const path_w = try windows.sliceToPrefixedFileW(path);
_ = try windows.GetFileAttributesW(&path_w);
return;
}
const path_c = try toPosixPath(path);
return accessZ(&path_c, mode);
}
pub const accessC = @compileError("Deprecated in favor of `accessZ`");
/// Same as `access` except `path` is null-terminated.
pub fn accessZ(path: [*:0]const u8, mode: u32) AccessError!void {
if (builtin.os.tag == .windows) {
const path_w = try windows.cStrToPrefixedFileW(path);
_ = try windows.GetFileAttributesW(&path_w);
return;
}
switch (errno(system.access(path, mode))) {
0 => return,
EACCES => return error.PermissionDenied,
EROFS => return error.ReadOnlyFileSystem,
ELOOP => return error.SymLinkLoop,
ETXTBSY => return error.FileBusy,
ENOTDIR => return error.FileNotFound,
ENOENT => return error.FileNotFound,
ENAMETOOLONG => return error.NameTooLong,
EINVAL => unreachable,
EFAULT => unreachable,
EIO => return error.InputOutput,
ENOMEM => return error.SystemResources,
else => |err| return unexpectedErrno(err),
}
}
/// Call from Windows-specific code if you already have a UTF-16LE encoded, null terminated string.
/// Otherwise use `access` or `accessC`.
/// TODO currently this ignores `mode`.
pub fn accessW(path: [*:0]const u16, mode: u32) windows.GetFileAttributesError!void {
const ret = try windows.GetFileAttributesW(path);
if (ret != windows.INVALID_FILE_ATTRIBUTES) {
return;
}
switch (windows.kernel32.GetLastError()) {
.FILE_NOT_FOUND => return error.FileNotFound,
.PATH_NOT_FOUND => return error.FileNotFound,
.ACCESS_DENIED => return error.PermissionDenied,
else => |err| return windows.unexpectedError(err),
}
}
/// Check user's permissions for a file, based on an open directory handle.
/// TODO currently this ignores `mode` and `flags` on Windows.
pub fn faccessat(dirfd: fd_t, path: []const u8, mode: u32, flags: u32) AccessError!void {
if (builtin.os.tag == .windows) {
const path_w = try windows.sliceToPrefixedFileW(path);
return faccessatW(dirfd, &path_w, mode, flags);
}
const path_c = try toPosixPath(path);
return faccessatZ(dirfd, &path_c, mode, flags);
}
/// Same as `faccessat` except the path parameter is null-terminated.
pub fn faccessatZ(dirfd: fd_t, path: [*:0]const u8, mode: u32, flags: u32) AccessError!void {
if (builtin.os.tag == .windows) {
const path_w = try windows.cStrToPrefixedFileW(path);
return faccessatW(dirfd, &path_w, mode, flags);
}
switch (errno(system.faccessat(dirfd, path, mode, flags))) {
0 => return,
EACCES => return error.PermissionDenied,
EROFS => return error.ReadOnlyFileSystem,
ELOOP => return error.SymLinkLoop,
ETXTBSY => return error.FileBusy,
ENOTDIR => return error.FileNotFound,
ENOENT => return error.FileNotFound,
ENAMETOOLONG => return error.NameTooLong,
EINVAL => unreachable,
EFAULT => unreachable,
EIO => return error.InputOutput,
ENOMEM => return error.SystemResources,
else => |err| return unexpectedErrno(err),
}
}
/// Same as `faccessat` except asserts the target is Windows and the path parameter
/// is NtDll-prefixed, null-terminated, WTF-16 encoded.
/// TODO currently this ignores `mode` and `flags`
pub fn faccessatW(dirfd: fd_t, sub_path_w: [*:0]const u16, mode: u32, flags: u32) AccessError!void {
if (sub_path_w[0] == '.' and sub_path_w[1] == 0) {
return;
}
if (sub_path_w[0] == '.' and sub_path_w[1] == '.' and sub_path_w[2] == 0) {
return;
}
const path_len_bytes = math.cast(u16, mem.lenZ(sub_path_w) * 2) catch |err| switch (err) {
error.Overflow => return error.NameTooLong,
};
var nt_name = windows.UNICODE_STRING{
.Length = path_len_bytes,
.MaximumLength = path_len_bytes,
.Buffer = @intToPtr([*]u16, @ptrToInt(sub_path_w)),
};
var attr = windows.OBJECT_ATTRIBUTES{
.Length = @sizeOf(windows.OBJECT_ATTRIBUTES),
.RootDirectory = if (std.fs.path.isAbsoluteWindowsW(sub_path_w)) null else dirfd,
.Attributes = 0, // Note we do not use OBJ_CASE_INSENSITIVE here.
.ObjectName = &nt_name,
.SecurityDescriptor = null,
.SecurityQualityOfService = null,
};
var basic_info: windows.FILE_BASIC_INFORMATION = undefined;
switch (windows.ntdll.NtQueryAttributesFile(&attr, &basic_info)) {
.SUCCESS => return,
.OBJECT_NAME_NOT_FOUND => return error.FileNotFound,
.OBJECT_PATH_NOT_FOUND => return error.FileNotFound,
.INVALID_PARAMETER => unreachable,
.ACCESS_DENIED => return error.PermissionDenied,
.OBJECT_PATH_SYNTAX_BAD => unreachable,
else => |rc| return windows.unexpectedStatus(rc),
}
}
pub const PipeError = error{
SystemFdQuotaExceeded,
ProcessFdQuotaExceeded,
} || UnexpectedError;
/// Creates a unidirectional data channel that can be used for interprocess communication.
pub fn pipe() PipeError![2]fd_t {
var fds: [2]fd_t = undefined;
switch (errno(system.pipe(&fds))) {
0 => return fds,
EINVAL => unreachable, // Invalid parameters to pipe()
EFAULT => unreachable, // Invalid fds pointer
ENFILE => return error.SystemFdQuotaExceeded,
EMFILE => return error.ProcessFdQuotaExceeded,
else => |err| return unexpectedErrno(err),
}
}
pub fn pipe2(flags: u32) PipeError![2]fd_t {
if (comptime std.Target.current.isDarwin()) {
var fds: [2]fd_t = try pipe();
if (flags == 0) return fds;
errdefer {
close(fds[0]);
close(fds[1]);
}
for (fds) |fd| switch (errno(system.fcntl(fd, F_SETFL, flags))) {
0 => {},
EINVAL => unreachable, // Invalid flags
EBADF => unreachable, // Always a race condition
else => |err| return unexpectedErrno(err),
};
return fds;
}
var fds: [2]fd_t = undefined;
switch (errno(system.pipe2(&fds, flags))) {
0 => return fds,
EINVAL => unreachable, // Invalid flags
EFAULT => unreachable, // Invalid fds pointer
ENFILE => return error.SystemFdQuotaExceeded,
EMFILE => return error.ProcessFdQuotaExceeded,
else => |err| return unexpectedErrno(err),
}
}
pub const SysCtlError = error{
PermissionDenied,
SystemResources,
NameTooLong,
UnknownName,
} || UnexpectedError;
pub fn sysctl(
name: []const c_int,
oldp: ?*c_void,
oldlenp: ?*usize,
newp: ?*c_void,
newlen: usize,
) SysCtlError!void {
const name_len = math.cast(c_uint, name.len) catch return error.NameTooLong;
switch (errno(system.sysctl(name.ptr, name_len, oldp, oldlenp, newp, newlen))) {
0 => return,
EFAULT => unreachable,
EPERM => return error.PermissionDenied,
ENOMEM => return error.SystemResources,
ENOENT => return error.UnknownName,
else => |err| return unexpectedErrno(err),
}
}
pub const sysctlbynameC = @compileError("deprecated: renamed to sysctlbynameZ");
pub fn sysctlbynameZ(
name: [*:0]const u8,
oldp: ?*c_void,
oldlenp: ?*usize,
newp: ?*c_void,
newlen: usize,
) SysCtlError!void {
switch (errno(system.sysctlbyname(name, oldp, oldlenp, newp, newlen))) {
0 => return,
EFAULT => unreachable,
EPERM => return error.PermissionDenied,
ENOMEM => return error.SystemResources,
ENOENT => return error.UnknownName,
else => |err| return unexpectedErrno(err),
}
}
pub fn gettimeofday(tv: ?*timeval, tz: ?*timezone) void {
switch (errno(system.gettimeofday(tv, tz))) {
0 => return,
EINVAL => unreachable,
else => unreachable,
}
}
pub const SeekError = error{Unseekable} || UnexpectedError;
/// Repositions read/write file offset relative to the beginning.
pub fn lseek_SET(fd: fd_t, offset: u64) SeekError!void {
if (builtin.os.tag == .linux and !builtin.link_libc and @sizeOf(usize) == 4) {
var result: u64 = undefined;
switch (errno(system.llseek(fd, offset, &result, SEEK_SET))) {
0 => return,
EBADF => unreachable, // always a race condition
EINVAL => return error.Unseekable,
EOVERFLOW => return error.Unseekable,
ESPIPE => return error.Unseekable,
ENXIO => return error.Unseekable,
else => |err| return unexpectedErrno(err),
}
}
if (builtin.os.tag == .windows) {
return windows.SetFilePointerEx_BEGIN(fd, offset);
}
const ipos = @bitCast(i64, offset); // the OS treats this as unsigned
switch (errno(system.lseek(fd, ipos, SEEK_SET))) {
0 => return,
EBADF => unreachable, // always a race condition
EINVAL => return error.Unseekable,
EOVERFLOW => return error.Unseekable,
ESPIPE => return error.Unseekable,
ENXIO => return error.Unseekable,
else => |err| return unexpectedErrno(err),
}
}
/// Repositions read/write file offset relative to the current offset.
pub fn lseek_CUR(fd: fd_t, offset: i64) SeekError!void {
if (builtin.os.tag == .linux and !builtin.link_libc and @sizeOf(usize) == 4) {
var result: u64 = undefined;
switch (errno(system.llseek(fd, @bitCast(u64, offset), &result, SEEK_CUR))) {
0 => return,
EBADF => unreachable, // always a race condition
EINVAL => return error.Unseekable,
EOVERFLOW => return error.Unseekable,
ESPIPE => return error.Unseekable,
ENXIO => return error.Unseekable,
else => |err| return unexpectedErrno(err),
}
}
if (builtin.os.tag == .windows) {
return windows.SetFilePointerEx_CURRENT(fd, offset);
}
switch (errno(system.lseek(fd, offset, SEEK_CUR))) {
0 => return,
EBADF => unreachable, // always a race condition
EINVAL => return error.Unseekable,
EOVERFLOW => return error.Unseekable,
ESPIPE => return error.Unseekable,
ENXIO => return error.Unseekable,
else => |err| return unexpectedErrno(err),
}
}
/// Repositions read/write file offset relative to the end.
pub fn lseek_END(fd: fd_t, offset: i64) SeekError!void {
if (builtin.os.tag == .linux and !builtin.link_libc and @sizeOf(usize) == 4) {
var result: u64 = undefined;
switch (errno(system.llseek(fd, @bitCast(u64, offset), &result, SEEK_END))) {
0 => return,
EBADF => unreachable, // always a race condition
EINVAL => return error.Unseekable,
EOVERFLOW => return error.Unseekable,
ESPIPE => return error.Unseekable,
ENXIO => return error.Unseekable,
else => |err| return unexpectedErrno(err),
}
}
if (builtin.os.tag == .windows) {
return windows.SetFilePointerEx_END(fd, offset);
}
switch (errno(system.lseek(fd, offset, SEEK_END))) {
0 => return,
EBADF => unreachable, // always a race condition
EINVAL => return error.Unseekable,
EOVERFLOW => return error.Unseekable,
ESPIPE => return error.Unseekable,
ENXIO => return error.Unseekable,
else => |err| return unexpectedErrno(err),
}
}
/// Returns the read/write file offset relative to the beginning.
pub fn lseek_CUR_get(fd: fd_t) SeekError!u64 {
if (builtin.os.tag == .linux and !builtin.link_libc and @sizeOf(usize) == 4) {
var result: u64 = undefined;
switch (errno(system.llseek(fd, 0, &result, SEEK_CUR))) {
0 => return result,
EBADF => unreachable, // always a race condition
EINVAL => return error.Unseekable,
EOVERFLOW => return error.Unseekable,
ESPIPE => return error.Unseekable,
ENXIO => return error.Unseekable,
else => |err| return unexpectedErrno(err),
}
}
if (builtin.os.tag == .windows) {
return windows.SetFilePointerEx_CURRENT_get(fd);
}
const rc = system.lseek(fd, 0, SEEK_CUR);
switch (errno(rc)) {
0 => return @bitCast(u64, rc),
EBADF => unreachable, // always a race condition
EINVAL => return error.Unseekable,
EOVERFLOW => return error.Unseekable,
ESPIPE => return error.Unseekable,
ENXIO => return error.Unseekable,
else => |err| return unexpectedErrno(err),
}
}
pub const FcntlError = error{
PermissionDenied,
FileBusy,
ProcessFdQuotaExceeded,
Locked,
} || UnexpectedError;
pub fn fcntl(fd: fd_t, cmd: i32, arg: usize) FcntlError!usize {
while (true) {
const rc = system.fcntl(fd, cmd, arg);
switch (errno(rc)) {
0 => return @intCast(usize, rc),
EINTR => continue,
EACCES => return error.Locked,
EBADF => unreachable,
EBUSY => return error.FileBusy,
EINVAL => unreachable, // invalid parameters
EPERM => return error.PermissionDenied,
EMFILE => return error.ProcessFdQuotaExceeded,
ENOTDIR => unreachable, // invalid parameter
else => |err| return unexpectedErrno(err),
}
}
}
pub const FlockError = error{
WouldBlock,
/// The kernel ran out of memory for allocating file locks
SystemResources,
} || UnexpectedError;
pub fn flock(fd: fd_t, operation: i32) FlockError!void {
while (true) {
const rc = system.flock(fd, operation);
switch (errno(rc)) {
0 => return,
EBADF => unreachable,
EINTR => continue,
EINVAL => unreachable, // invalid parameters
ENOLCK => return error.SystemResources,
EWOULDBLOCK => return error.WouldBlock, // TODO: integrate with async instead of just returning an error
else => |err| return unexpectedErrno(err),
}
}
}
pub const RealPathError = error{
FileNotFound,
AccessDenied,
NameTooLong,
NotSupported,
NotDir,
SymLinkLoop,
InputOutput,
FileTooBig,
IsDir,
ProcessFdQuotaExceeded,
SystemFdQuotaExceeded,
NoDevice,
SystemResources,
NoSpaceLeft,
FileSystem,
BadPathName,
DeviceBusy,
SharingViolation,
PipeBusy,
/// On Windows, file paths must be valid Unicode.
InvalidUtf8,
PathAlreadyExists,
} || UnexpectedError;
/// Return the canonicalized absolute pathname.
/// Expands all symbolic links and resolves references to `.`, `..`, and
/// extra `/` characters in `pathname`.
/// The return value is a slice of `out_buffer`, but not necessarily from the beginning.
/// See also `realpathC` and `realpathW`.
pub fn realpath(pathname: []const u8, out_buffer: *[MAX_PATH_BYTES]u8) RealPathError![]u8 {
if (builtin.os.tag == .windows) {
const pathname_w = try windows.sliceToPrefixedFileW(pathname);
return realpathW(&pathname_w, out_buffer);
}
const pathname_c = try toPosixPath(pathname);
return realpathZ(&pathname_c, out_buffer);
}
pub const realpathC = @compileError("deprecated: renamed realpathZ");
/// Same as `realpath` except `pathname` is null-terminated.
pub fn realpathZ(pathname: [*:0]const u8, out_buffer: *[MAX_PATH_BYTES]u8) RealPathError![]u8 {
if (builtin.os.tag == .windows) {
const pathname_w = try windows.cStrToPrefixedFileW(pathname);
return realpathW(&pathname_w, out_buffer);
}
if (builtin.os.tag == .linux and !builtin.link_libc) {
const fd = openZ(pathname, linux.O_PATH | linux.O_NONBLOCK | linux.O_CLOEXEC, 0) catch |err| switch (err) {
error.FileLocksNotSupported => unreachable,
else => |e| return e,
};
defer close(fd);
var procfs_buf: ["/proc/self/fd/-2147483648".len:0]u8 = undefined;
const proc_path = std.fmt.bufPrint(procfs_buf[0..], "/proc/self/fd/{}\x00", .{fd}) catch unreachable;
return readlinkZ(@ptrCast([*:0]const u8, proc_path.ptr), out_buffer);
}
const result_path = std.c.realpath(pathname, out_buffer) orelse switch (std.c._errno().*) {
EINVAL => unreachable,
EBADF => unreachable,
EFAULT => unreachable,
EACCES => return error.AccessDenied,
ENOENT => return error.FileNotFound,
ENOTSUP => return error.NotSupported,
ENOTDIR => return error.NotDir,
ENAMETOOLONG => return error.NameTooLong,
ELOOP => return error.SymLinkLoop,
EIO => return error.InputOutput,
else => |err| return unexpectedErrno(@intCast(usize, err)),
};
return mem.spanZ(result_path);
}
/// Same as `realpath` except `pathname` is null-terminated and UTF16LE-encoded.
/// TODO use ntdll for better semantics
pub fn realpathW(pathname: [*:0]const u16, out_buffer: *[MAX_PATH_BYTES]u8) RealPathError![]u8 {
const h_file = try windows.CreateFileW(
pathname,
windows.GENERIC_READ,
windows.FILE_SHARE_READ,
null,
windows.OPEN_EXISTING,
windows.FILE_FLAG_BACKUP_SEMANTICS,
null,
);
defer windows.CloseHandle(h_file);
var wide_buf: [windows.PATH_MAX_WIDE]u16 = undefined;
const wide_slice = try windows.GetFinalPathNameByHandleW(h_file, &wide_buf, wide_buf.len, windows.VOLUME_NAME_DOS);
// Windows returns \\?\ prepended to the path.
// We strip it to make this function consistent across platforms.
const prefix = [_]u16{ '\\', '\\', '?', '\\' };
const start_index = if (mem.startsWith(u16, wide_slice, &prefix)) prefix.len else 0;
// Trust that Windows gives us valid UTF-16LE.
const end_index = std.unicode.utf16leToUtf8(out_buffer, wide_slice[start_index..]) catch unreachable;
return out_buffer[0..end_index];
}
/// Spurious wakeups are possible and no precision of timing is guaranteed.
pub fn nanosleep(seconds: u64, nanoseconds: u64) void {
var req = timespec{
.tv_sec = math.cast(isize, seconds) catch math.maxInt(isize),
.tv_nsec = math.cast(isize, nanoseconds) catch math.maxInt(isize),
};
var rem: timespec = undefined;
while (true) {
switch (errno(system.nanosleep(&req, &rem))) {
EFAULT => unreachable,
EINVAL => {
// Sometimes Darwin returns EINVAL for no reason.
// We treat it as a spurious wakeup.
return;
},
EINTR => {
req = rem;
continue;
},
// This prong handles success as well as unexpected errors.
else => return,
}
}
}
pub fn dl_iterate_phdr(
context: var,
comptime Error: type,
comptime callback: fn (info: *dl_phdr_info, size: usize, context: @TypeOf(context)) Error!void,
) Error!void {
const Context = @TypeOf(context);
if (builtin.object_format != .elf)
@compileError("dl_iterate_phdr is not available for this target");
if (builtin.link_libc) {
switch (system.dl_iterate_phdr(struct {
fn callbackC(info: *dl_phdr_info, size: usize, data: ?*c_void) callconv(.C) c_int {
const context_ptr = @ptrCast(*const Context, @alignCast(@alignOf(*const Context), data));
callback(info, size, context_ptr.*) catch |err| return @errorToInt(err);
return 0;
}
}.callbackC, @intToPtr(?*c_void, @ptrToInt(&context)))) {
0 => return,
else => |err| return @errSetCast(Error, @intToError(@intCast(u16, err))), // TODO don't hardcode u16
}
}
const elf_base = std.process.getBaseAddress();
const ehdr = @intToPtr(*elf.Ehdr, elf_base);
// Make sure the base address points to an ELF image
assert(mem.eql(u8, ehdr.e_ident[0..4], "\x7fELF"));
const n_phdr = ehdr.e_phnum;
const phdrs = (@intToPtr([*]elf.Phdr, elf_base + ehdr.e_phoff))[0..n_phdr];
var it = dl.linkmap_iterator(phdrs) catch unreachable;
// The executable has no dynamic link segment, create a single entry for
// the whole ELF image
if (it.end()) {
var info = dl_phdr_info{
.dlpi_addr = 0,
.dlpi_name = "/proc/self/exe",
.dlpi_phdr = phdrs.ptr,
.dlpi_phnum = ehdr.e_phnum,
};
return callback(&info, @sizeOf(dl_phdr_info), context);
}
// Last return value from the callback function
while (it.next()) |entry| {
var dlpi_phdr: [*]elf.Phdr = undefined;
var dlpi_phnum: u16 = undefined;
if (entry.l_addr != 0) {
const elf_header = @intToPtr(*elf.Ehdr, entry.l_addr);
dlpi_phdr = @intToPtr([*]elf.Phdr, entry.l_addr + elf_header.e_phoff);
dlpi_phnum = elf_header.e_phnum;
} else {
// This is the running ELF image
dlpi_phdr = @intToPtr([*]elf.Phdr, elf_base + ehdr.e_phoff);
dlpi_phnum = ehdr.e_phnum;
}
var info = dl_phdr_info{
.dlpi_addr = entry.l_addr,
.dlpi_name = entry.l_name,
.dlpi_phdr = dlpi_phdr,
.dlpi_phnum = dlpi_phnum,
};
try callback(&info, @sizeOf(dl_phdr_info), context);
}
}
pub const ClockGetTimeError = error{UnsupportedClock} || UnexpectedError;
pub fn clock_gettime(clk_id: i32, tp: *timespec) ClockGetTimeError!void {
if (std.Target.current.os.tag == .wasi) {
var ts: timestamp_t = undefined;
switch (system.clock_time_get(@bitCast(u32, clk_id), 1, &ts)) {
0 => {
tp.* = .{
.tv_sec = @intCast(i64, ts / std.time.ns_per_s),
.tv_nsec = @intCast(isize, ts % std.time.ns_per_s),
};
},
EINVAL => return error.UnsupportedClock,
else => |err| return unexpectedErrno(err),
}
return;
}
switch (errno(system.clock_gettime(clk_id, tp))) {
0 => return,
EFAULT => unreachable,
EINVAL => return error.UnsupportedClock,
else => |err| return unexpectedErrno(err),
}
}
pub fn clock_getres(clk_id: i32, res: *timespec) ClockGetTimeError!void {
if (std.Target.current.os.tag == .wasi) {
var ts: timestamp_t = undefined;
switch (system.clock_res_get(@bitCast(u32, clk_id), &ts)) {
0 => res.* = .{
.tv_sec = @intCast(i64, ts / std.time.ns_per_s),
.tv_nsec = @intCast(isize, ts % std.time.ns_per_s),
},
EINVAL => return error.UnsupportedClock,
else => |err| return unexpectedErrno(err),
}
return;
}
switch (errno(system.clock_getres(clk_id, res))) {
0 => return,
EFAULT => unreachable,
EINVAL => return error.UnsupportedClock,
else => |err| return unexpectedErrno(err),
}
}
pub const SchedGetAffinityError = error{PermissionDenied} || UnexpectedError;
pub fn sched_getaffinity(pid: pid_t) SchedGetAffinityError!cpu_set_t {
var set: cpu_set_t = undefined;
switch (errno(system.sched_getaffinity(pid, @sizeOf(cpu_set_t), &set))) {
0 => return set,
EFAULT => unreachable,
EINVAL => unreachable,
ESRCH => unreachable,
EPERM => return error.PermissionDenied,
else => |err| return unexpectedErrno(err),
}
}
/// Used to convert a slice to a null terminated slice on the stack.
/// TODO https://github.com/ziglang/zig/issues/287
pub fn toPosixPath(file_path: []const u8) ![PATH_MAX - 1:0]u8 {
if (std.debug.runtime_safety) assert(std.mem.indexOfScalar(u8, file_path, 0) == null);
var path_with_null: [PATH_MAX - 1:0]u8 = undefined;
// >= rather than > to make room for the null byte
if (file_path.len >= PATH_MAX) return error.NameTooLong;
mem.copy(u8, &path_with_null, file_path);
path_with_null[file_path.len] = 0;
return path_with_null;
}
/// Whether or not error.Unexpected will print its value and a stack trace.
/// if this happens the fix is to add the error code to the corresponding
/// switch expression, possibly introduce a new error in the error set, and
/// send a patch to Zig.
pub const unexpected_error_tracing = builtin.mode == .Debug;
pub const UnexpectedError = error{
/// The Operating System returned an undocumented error code.
/// This error is in theory not possible, but it would be better
/// to handle this error than to invoke undefined behavior.
Unexpected,
};
/// Call this when you made a syscall or something that sets errno
/// and you get an unexpected error.
pub fn unexpectedErrno(err: usize) UnexpectedError {
if (unexpected_error_tracing) {
std.debug.warn("unexpected errno: {}\n", .{err});
std.debug.dumpCurrentStackTrace(null);
}
return error.Unexpected;
}
pub const SigaltstackError = error{
/// The supplied stack size was less than MINSIGSTKSZ.
SizeTooSmall,
/// Attempted to change the signal stack while it was active.
PermissionDenied,
} || UnexpectedError;
pub fn sigaltstack(ss: ?*stack_t, old_ss: ?*stack_t) SigaltstackError!void {
switch (errno(system.sigaltstack(ss, old_ss))) {
0 => return,
EFAULT => unreachable,
EINVAL => unreachable,
ENOMEM => return error.SizeTooSmall,
EPERM => return error.PermissionDenied,
else => |err| return unexpectedErrno(err),
}
}
/// Examine and change a signal action.
pub fn sigaction(sig: u6, act: *const Sigaction, oact: ?*Sigaction) void {
switch (errno(system.sigaction(sig, act, oact))) {
0 => return,
EFAULT => unreachable,
EINVAL => unreachable,
else => unreachable,
}
}
pub const FutimensError = error{
/// times is NULL, or both tv_nsec values are UTIME_NOW, and either:
/// * the effective user ID of the caller does not match the owner
/// of the file, the caller does not have write access to the
/// file, and the caller is not privileged (Linux: does not have
/// either the CAP_FOWNER or the CAP_DAC_OVERRIDE capability);
/// or,
/// * the file is marked immutable (see chattr(1)).
AccessDenied,
/// The caller attempted to change one or both timestamps to a value
/// other than the current time, or to change one of the timestamps
/// to the current time while leaving the other timestamp unchanged,
/// (i.e., times is not NULL, neither tv_nsec field is UTIME_NOW,
/// and neither tv_nsec field is UTIME_OMIT) and either:
/// * the caller's effective user ID does not match the owner of
/// file, and the caller is not privileged (Linux: does not have
/// the CAP_FOWNER capability); or,
/// * the file is marked append-only or immutable (see chattr(1)).
PermissionDenied,
ReadOnlyFileSystem,
} || UnexpectedError;
pub fn futimens(fd: fd_t, times: *const [2]timespec) FutimensError!void {
switch (errno(system.futimens(fd, times))) {
0 => return,
EACCES => return error.AccessDenied,
EPERM => return error.PermissionDenied,
EBADF => unreachable, // always a race condition
EFAULT => unreachable,
EINVAL => unreachable,
EROFS => return error.ReadOnlyFileSystem,
else => |err| return unexpectedErrno(err),
}
}
pub const GetHostNameError = error{PermissionDenied} || UnexpectedError;
pub fn gethostname(name_buffer: *[HOST_NAME_MAX]u8) GetHostNameError![]u8 {
if (builtin.link_libc) {
switch (errno(system.gethostname(name_buffer, name_buffer.len))) {
0 => return mem.spanZ(@ptrCast([*:0]u8, name_buffer)),
EFAULT => unreachable,
ENAMETOOLONG => unreachable, // HOST_NAME_MAX prevents this
EPERM => return error.PermissionDenied,
else => |err| return unexpectedErrno(err),
}
}
if (builtin.os.tag == .linux) {
const uts = uname();
const hostname = mem.spanZ(@ptrCast([*:0]const u8, &uts.nodename));
mem.copy(u8, name_buffer, hostname);
return name_buffer[0..hostname.len];
}
@compileError("TODO implement gethostname for this OS");
}
pub fn uname() utsname {
var uts: utsname = undefined;
switch (errno(system.uname(&uts))) {
0 => return uts,
EFAULT => unreachable,
else => unreachable,
}
}
pub fn res_mkquery(
op: u4,
dname: []const u8,
class: u8,
ty: u8,
data: []const u8,
newrr: ?[*]const u8,
buf: []u8,
) usize {
// This implementation is ported from musl libc.
// A more idiomatic "ziggy" implementation would be welcome.
var name = dname;
if (mem.endsWith(u8, name, ".")) name.len -= 1;
assert(name.len <= 253);
const n = 17 + name.len + @boolToInt(name.len != 0);
// Construct query template - ID will be filled later
var q: [280]u8 = undefined;
@memset(&q, 0, n);
q[2] = @as(u8, op) * 8 + 1;
q[5] = 1;
mem.copy(u8, q[13..], name);
var i: usize = 13;
var j: usize = undefined;
while (q[i] != 0) : (i = j + 1) {
j = i;
while (q[j] != 0 and q[j] != '.') : (j += 1) {}
// TODO determine the circumstances for this and whether or
// not this should be an error.
if (j - i - 1 > 62) unreachable;
q[i - 1] = @intCast(u8, j - i);
}
q[i + 1] = ty;
q[i + 3] = class;
// Make a reasonably unpredictable id
var ts: timespec = undefined;
clock_gettime(CLOCK_REALTIME, &ts) catch {};
const UInt = std.meta.IntType(false, @TypeOf(ts.tv_nsec).bit_count);
const unsec = @bitCast(UInt, ts.tv_nsec);
const id = @truncate(u32, unsec + unsec / 65536);
q[0] = @truncate(u8, id / 256);
q[1] = @truncate(u8, id);
mem.copy(u8, buf, q[0..n]);
return n;
}
pub const SendError = error{
/// (For UNIX domain sockets, which are identified by pathname) Write permission is denied
/// on the destination socket file, or search permission is denied for one of the
/// directories the path prefix. (See path_resolution(7).)
/// (For UDP sockets) An attempt was made to send to a network/broadcast address as though
/// it was a unicast address.
AccessDenied,
/// The socket is marked nonblocking and the requested operation would block, and
/// there is no global event loop configured.
/// It's also possible to get this error under the following condition:
/// (Internet domain datagram sockets) The socket referred to by sockfd had not previously
/// been bound to an address and, upon attempting to bind it to an ephemeral port, it was
/// determined that all port numbers in the ephemeral port range are currently in use. See
/// the discussion of /proc/sys/net/ipv4/ip_local_port_range in ip(7).
WouldBlock,
/// Another Fast Open is already in progress.
FastOpenAlreadyInProgress,
/// Connection reset by peer.
ConnectionResetByPeer,
/// The socket type requires that message be sent atomically, and the size of the message
/// to be sent made this impossible. The message is not transmitted.
MessageTooBig,
/// The output queue for a network interface was full. This generally indicates that the
/// interface has stopped sending, but may be caused by transient congestion. (Normally,
/// this does not occur in Linux. Packets are just silently dropped when a device queue
/// overflows.)
/// This is also caused when there is not enough kernel memory available.
SystemResources,
/// The local end has been shut down on a connection oriented socket. In this case, the
/// process will also receive a SIGPIPE unless MSG_NOSIGNAL is set.
BrokenPipe,
} || UnexpectedError;
/// Transmit a message to another socket.
///
/// The `sendto` call may be used only when the socket is in a connected state (so that the intended
/// recipient is known). The following call
///
/// send(sockfd, buf, len, flags);
///
/// is equivalent to
///
/// sendto(sockfd, buf, len, flags, NULL, 0);
///
/// If sendto() is used on a connection-mode (`SOCK_STREAM`, `SOCK_SEQPACKET`) socket, the arguments
/// `dest_addr` and `addrlen` are asserted to be `null` and `0` respectively, and asserted
/// that the socket was actually connected.
/// Otherwise, the address of the target is given by `dest_addr` with `addrlen` specifying its size.
///
/// If the message is too long to pass atomically through the underlying protocol,
/// `SendError.MessageTooBig` is returned, and the message is not transmitted.
///
/// There is no indication of failure to deliver.
///
/// When the message does not fit into the send buffer of the socket, `sendto` normally blocks,
/// unless the socket has been placed in nonblocking I/O mode. In nonblocking mode it would fail
/// with `SendError.WouldBlock`. The `select` call may be used to determine when it is
/// possible to send more data.
pub fn sendto(
/// The file descriptor of the sending socket.
sockfd: fd_t,
/// Message to send.
buf: []const u8,
flags: u32,
dest_addr: ?*const sockaddr,
addrlen: socklen_t,
) SendError!usize {
while (true) {
const rc = system.sendto(sockfd, buf.ptr, buf.len, flags, dest_addr, addrlen);
switch (errno(rc)) {
0 => return @intCast(usize, rc),
EACCES => return error.AccessDenied,
EAGAIN => if (std.event.Loop.instance) |loop| {
loop.waitUntilFdWritable(sockfd);
continue;
} else {
return error.WouldBlock;
},
EALREADY => return error.FastOpenAlreadyInProgress,
EBADF => unreachable, // always a race condition
ECONNRESET => return error.ConnectionResetByPeer,
EDESTADDRREQ => unreachable, // The socket is not connection-mode, and no peer address is set.
EFAULT => unreachable, // An invalid user space address was specified for an argument.
EINTR => continue,
EINVAL => unreachable, // Invalid argument passed.
EISCONN => unreachable, // connection-mode socket was connected already but a recipient was specified
EMSGSIZE => return error.MessageTooBig,
ENOBUFS => return error.SystemResources,
ENOMEM => return error.SystemResources,
ENOTCONN => unreachable, // The socket is not connected, and no target has been given.
ENOTSOCK => unreachable, // The file descriptor sockfd does not refer to a socket.
EOPNOTSUPP => unreachable, // Some bit in the flags argument is inappropriate for the socket type.
EPIPE => return error.BrokenPipe,
else => |err| return unexpectedErrno(err),
}
}
}
/// Transmit a message to another socket.
///
/// The `send` call may be used only when the socket is in a connected state (so that the intended
/// recipient is known). The only difference between `send` and `write` is the presence of
/// flags. With a zero flags argument, `send` is equivalent to `write`. Also, the following
/// call
///
/// send(sockfd, buf, len, flags);
///
/// is equivalent to
///
/// sendto(sockfd, buf, len, flags, NULL, 0);
///
/// There is no indication of failure to deliver.
///
/// When the message does not fit into the send buffer of the socket, `send` normally blocks,
/// unless the socket has been placed in nonblocking I/O mode. In nonblocking mode it would fail
/// with `SendError.WouldBlock`. The `select` call may be used to determine when it is
/// possible to send more data.
pub fn send(
/// The file descriptor of the sending socket.
sockfd: fd_t,
buf: []const u8,
flags: u32,
) SendError!usize {
return sendto(sockfd, buf, flags, null, 0);
}
pub const SendFileError = PReadError || WriteError || SendError;
fn count_iovec_bytes(iovs: []const iovec_const) usize {
var count: usize = 0;
for (iovs) |iov| {
count += iov.iov_len;
}
return count;
}
/// Transfer data between file descriptors, with optional headers and trailers.
/// Returns the number of bytes written, which can be zero.
///
/// The `sendfile` call copies `in_len` bytes from one file descriptor to another. When possible,
/// this is done within the operating system kernel, which can provide better performance
/// characteristics than transferring data from kernel to user space and back, such as with
/// `read` and `write` calls. When `in_len` is `0`, it means to copy until the end of the input file has been
/// reached. Note, however, that partial writes are still possible in this case.
///
/// `in_fd` must be a file descriptor opened for reading, and `out_fd` must be a file descriptor
/// opened for writing. They may be any kind of file descriptor; however, if `in_fd` is not a regular
/// file system file, it may cause this function to fall back to calling `read` and `write`, in which case
/// atomicity guarantees no longer apply.
///
/// Copying begins reading at `in_offset`. The input file descriptor seek position is ignored and not updated.
/// If the output file descriptor has a seek position, it is updated as bytes are written. When
/// `in_offset` is past the end of the input file, it successfully reads 0 bytes.
///
/// `flags` has different meanings per operating system; refer to the respective man pages.
///
/// These systems support atomically sending everything, including headers and trailers:
/// * macOS
/// * FreeBSD
///
/// These systems support in-kernel data copying, but headers and trailers are not sent atomically:
/// * Linux
///
/// Other systems fall back to calling `read` / `write`.
///
/// Linux has a limit on how many bytes may be transferred in one `sendfile` call, which is `0x7ffff000`
/// on both 64-bit and 32-bit systems. This is due to using a signed C int as the return value, as
/// well as stuffing the errno codes into the last `4096` values. This is cited on the `sendfile` man page.
/// The corresponding POSIX limit on this is `math.maxInt(isize)`.
pub fn sendfile(
out_fd: fd_t,
in_fd: fd_t,
in_offset: u64,
in_len: u64,
headers: []const iovec_const,
trailers: []const iovec_const,
flags: u32,
) SendFileError!usize {
var header_done = false;
var total_written: usize = 0;
// Prevents EOVERFLOW.
const size_t = @Type(std.builtin.TypeInfo{
.Int = .{
.is_signed = false,
.bits = @typeInfo(usize).Int.bits - 1,
},
});
const max_count = switch (std.Target.current.os.tag) {
.linux => 0x7ffff000,
else => math.maxInt(size_t),
};
switch (std.Target.current.os.tag) {
.linux => sf: {
// sendfile() first appeared in Linux 2.2, glibc 2.1.
const call_sf = comptime if (builtin.link_libc)
std.c.versionCheck(.{ .major = 2, .minor = 1 }).ok
else
std.Target.current.os.version_range.linux.range.max.order(.{ .major = 2, .minor = 2 }) != .lt;
if (!call_sf) break :sf;
if (headers.len != 0) {
const amt = try writev(out_fd, headers);
total_written += amt;
if (amt < count_iovec_bytes(headers)) return total_written;
header_done = true;
}
// Here we match BSD behavior, making a zero count value send as many bytes as possible.
const adjusted_count = if (in_len == 0) max_count else math.min(in_len, @as(size_t, max_count));
while (true) {
var offset: off_t = @bitCast(off_t, in_offset);
const rc = system.sendfile(out_fd, in_fd, &offset, adjusted_count);
switch (errno(rc)) {
0 => {
const amt = @bitCast(usize, rc);
total_written += amt;
if (in_len == 0 and amt == 0) {
// We have detected EOF from `in_fd`.
break;
} else if (amt < in_len) {
return total_written;
} else {
break;
}
},
EBADF => unreachable, // Always a race condition.
EFAULT => unreachable, // Segmentation fault.
EOVERFLOW => unreachable, // We avoid passing too large of a `count`.
ENOTCONN => unreachable, // `out_fd` is an unconnected socket.
EINVAL, ENOSYS => {
// EINVAL could be any of the following situations:
// * Descriptor is not valid or locked
// * an mmap(2)-like operation is not available for in_fd
// * count is negative
// * out_fd has the O_APPEND flag set
// Because of the "mmap(2)-like operation" possibility, we fall back to doing read/write
// manually, the same as ENOSYS.
break :sf;
},
EAGAIN => if (std.event.Loop.instance) |loop| {
loop.waitUntilFdWritable(out_fd);
continue;
} else {
return error.WouldBlock;
},
EIO => return error.InputOutput,
EPIPE => return error.BrokenPipe,
ENOMEM => return error.SystemResources,
ENXIO => return error.Unseekable,
ESPIPE => return error.Unseekable,
else => |err| {
const discard = unexpectedErrno(err);
break :sf;
},
}
}
if (trailers.len != 0) {
total_written += try writev(out_fd, trailers);
}
return total_written;
},
.freebsd => sf: {
var hdtr_data: std.c.sf_hdtr = undefined;
var hdtr: ?*std.c.sf_hdtr = null;
if (headers.len != 0 or trailers.len != 0) {
// Here we carefully avoid `@intCast` by returning partial writes when
// too many io vectors are provided.
const hdr_cnt = math.cast(u31, headers.len) catch math.maxInt(u31);
if (headers.len > hdr_cnt) return writev(out_fd, headers);
const trl_cnt = math.cast(u31, trailers.len) catch math.maxInt(u31);
hdtr_data = std.c.sf_hdtr{
.headers = headers.ptr,
.hdr_cnt = hdr_cnt,
.trailers = trailers.ptr,
.trl_cnt = trl_cnt,
};
hdtr = &hdtr_data;
}
const adjusted_count = math.min(in_len, max_count);
while (true) {
var sbytes: off_t = undefined;
const offset = @bitCast(off_t, in_offset);
const err = errno(system.sendfile(in_fd, out_fd, offset, adjusted_count, hdtr, &sbytes, flags));
const amt = @bitCast(usize, sbytes);
switch (err) {
0 => return amt,
EBADF => unreachable, // Always a race condition.
EFAULT => unreachable, // Segmentation fault.
ENOTCONN => unreachable, // `out_fd` is an unconnected socket.
EINVAL, EOPNOTSUPP, ENOTSOCK, ENOSYS => {
// EINVAL could be any of the following situations:
// * The fd argument is not a regular file.
// * The s argument is not a SOCK_STREAM type socket.
// * The offset argument is negative.
// Because of some of these possibilities, we fall back to doing read/write
// manually, the same as ENOSYS.
break :sf;
},
EINTR => if (amt != 0) return amt else continue,
EAGAIN => if (amt != 0) {
return amt;
} else if (std.event.Loop.instance) |loop| {
loop.waitUntilFdWritable(out_fd);
continue;
} else {
return error.WouldBlock;
},
EBUSY => if (amt != 0) {
return amt;
} else if (std.event.Loop.instance) |loop| {
loop.waitUntilFdReadable(in_fd);
continue;
} else {
return error.WouldBlock;
},
EIO => return error.InputOutput,
ENOBUFS => return error.SystemResources,
EPIPE => return error.BrokenPipe,
else => {
const discard = unexpectedErrno(err);
if (amt != 0) {
return amt;
} else {
break :sf;
}
},
}
}
},
.macosx, .ios, .tvos, .watchos => sf: {
var hdtr_data: std.c.sf_hdtr = undefined;
var hdtr: ?*std.c.sf_hdtr = null;
if (headers.len != 0 or trailers.len != 0) {
// Here we carefully avoid `@intCast` by returning partial writes when
// too many io vectors are provided.
const hdr_cnt = math.cast(u31, headers.len) catch math.maxInt(u31);
if (headers.len > hdr_cnt) return writev(out_fd, headers);
const trl_cnt = math.cast(u31, trailers.len) catch math.maxInt(u31);
hdtr_data = std.c.sf_hdtr{
.headers = headers.ptr,
.hdr_cnt = hdr_cnt,
.trailers = trailers.ptr,
.trl_cnt = trl_cnt,
};
hdtr = &hdtr_data;
}
const adjusted_count = math.min(in_len, @as(u63, max_count));
while (true) {
var sbytes: off_t = adjusted_count;
const signed_offset = @bitCast(i64, in_offset);
const err = errno(system.sendfile(in_fd, out_fd, signed_offset, &sbytes, hdtr, flags));
const amt = @bitCast(usize, sbytes);
switch (err) {
0 => return amt,
EBADF => unreachable, // Always a race condition.
EFAULT => unreachable, // Segmentation fault.
EINVAL => unreachable,
ENOTCONN => unreachable, // `out_fd` is an unconnected socket.
ENOTSUP, ENOTSOCK, ENOSYS => break :sf,
EINTR => if (amt != 0) return amt else continue,
EAGAIN => if (amt != 0) {
return amt;
} else if (std.event.Loop.instance) |loop| {
loop.waitUntilFdWritable(out_fd);
continue;
} else {
return error.WouldBlock;
},
EIO => return error.InputOutput,
EPIPE => return error.BrokenPipe,
else => {
const discard = unexpectedErrno(err);
if (amt != 0) {
return amt;
} else {
break :sf;
}
},
}
}
},
else => {}, // fall back to read/write
}
if (headers.len != 0 and !header_done) {
const amt = try writev(out_fd, headers);
total_written += amt;
if (amt < count_iovec_bytes(headers)) return total_written;
}
rw: {
var buf: [8 * 4096]u8 = undefined;
// Here we match BSD behavior, making a zero count value send as many bytes as possible.
const adjusted_count = if (in_len == 0) buf.len else math.min(buf.len, in_len);
const amt_read = try pread(in_fd, buf[0..adjusted_count], in_offset);
if (amt_read == 0) {
if (in_len == 0) {
// We have detected EOF from `in_fd`.
break :rw;
} else {
return total_written;
}
}
const amt_written = try write(out_fd, buf[0..amt_read]);
total_written += amt_written;
if (amt_written < in_len or in_len == 0) return total_written;
}
if (trailers.len != 0) {
total_written += try writev(out_fd, trailers);
}
return total_written;
}
pub const PollError = error{
/// The kernel had no space to allocate file descriptor tables.
SystemResources,
} || UnexpectedError;
pub fn poll(fds: []pollfd, timeout: i32) PollError!usize {
while (true) {
const rc = system.poll(fds.ptr, fds.len, timeout);
switch (errno(rc)) {
0 => return @intCast(usize, rc),
EFAULT => unreachable,
EINTR => continue,
EINVAL => unreachable,
ENOMEM => return error.SystemResources,
else => |err| return unexpectedErrno(err),
}
}
}
pub const RecvFromError = error{
/// The socket is marked nonblocking and the requested operation would block, and
/// there is no global event loop configured.
WouldBlock,
/// A remote host refused to allow the network connection, typically because it is not
/// running the requested service.
ConnectionRefused,
/// Could not allocate kernel memory.
SystemResources,
} || UnexpectedError;
pub fn recvfrom(
sockfd: fd_t,
buf: []u8,
flags: u32,
src_addr: ?*sockaddr,
addrlen: ?*socklen_t,
) RecvFromError!usize {
while (true) {
const rc = system.recvfrom(sockfd, buf.ptr, buf.len, flags, src_addr, addrlen);
switch (errno(rc)) {
0 => return @intCast(usize, rc),
EBADF => unreachable, // always a race condition
EFAULT => unreachable,
EINVAL => unreachable,
ENOTCONN => unreachable,
ENOTSOCK => unreachable,
EINTR => continue,
EAGAIN => if (std.event.Loop.instance) |loop| {
loop.waitUntilFdReadable(sockfd);
continue;
} else {
return error.WouldBlock;
},
ENOMEM => return error.SystemResources,
ECONNREFUSED => return error.ConnectionRefused,
else => |err| return unexpectedErrno(err),
}
}
}
pub const DnExpandError = error{InvalidDnsPacket};
pub fn dn_expand(
msg: []const u8,
comp_dn: []const u8,
exp_dn: []u8,
) DnExpandError!usize {
// This implementation is ported from musl libc.
// A more idiomatic "ziggy" implementation would be welcome.
var p = comp_dn.ptr;
var len: usize = std.math.maxInt(usize);
const end = msg.ptr + msg.len;
if (p == end or exp_dn.len == 0) return error.InvalidDnsPacket;
var dest = exp_dn.ptr;
const dend = dest + std.math.min(exp_dn.len, 254);
// detect reference loop using an iteration counter
var i: usize = 0;
while (i < msg.len) : (i += 2) {
// loop invariants: p<end, dest<dend
if ((p[0] & 0xc0) != 0) {
if (p + 1 == end) return error.InvalidDnsPacket;
var j = ((p[0] & @as(usize, 0x3f)) << 8) | p[1];
if (len == std.math.maxInt(usize)) len = @ptrToInt(p) + 2 - @ptrToInt(comp_dn.ptr);
if (j >= msg.len) return error.InvalidDnsPacket;
p = msg.ptr + j;
} else if (p[0] != 0) {
if (dest != exp_dn.ptr) {
dest.* = '.';
dest += 1;
}
var j = p[0];
p += 1;
if (j >= @ptrToInt(end) - @ptrToInt(p) or j >= @ptrToInt(dend) - @ptrToInt(dest)) {
return error.InvalidDnsPacket;
}
while (j != 0) {
j -= 1;
dest.* = p[0];
dest += 1;
p += 1;
}
} else {
dest.* = 0;
if (len == std.math.maxInt(usize)) len = @ptrToInt(p) + 1 - @ptrToInt(comp_dn.ptr);
return len;
}
}
return error.InvalidDnsPacket;
}
pub const SchedYieldError = error{
/// The system is not configured to allow yielding
SystemCannotYield,
};
pub fn sched_yield() SchedYieldError!void {
if (builtin.os.tag == .windows) {
// The return value has to do with how many other threads there are; it is not
// an error condition on Windows.
_ = windows.kernel32.SwitchToThread();
return;
}
switch (errno(system.sched_yield())) {
0 => return,
ENOSYS => return error.SystemCannotYield,
else => return error.SystemCannotYield,
}
}
pub const SetSockOptError = error{
/// The socket is already connected, and a specified option cannot be set while the socket is connected.
AlreadyConnected,
/// The option is not supported by the protocol.
InvalidProtocolOption,
/// The send and receive timeout values are too big to fit into the timeout fields in the socket structure.
TimeoutTooBig,
/// Insufficient resources are available in the system to complete the call.
SystemResources,
} || UnexpectedError;
/// Set a socket's options.
pub fn setsockopt(fd: fd_t, level: u32, optname: u32, opt: []const u8) SetSockOptError!void {
switch (errno(system.setsockopt(fd, level, optname, opt.ptr, @intCast(socklen_t, opt.len)))) {
0 => {},
EBADF => unreachable, // always a race condition
ENOTSOCK => unreachable, // always a race condition
EINVAL => unreachable,
EFAULT => unreachable,
EDOM => return error.TimeoutTooBig,
EISCONN => return error.AlreadyConnected,
ENOPROTOOPT => return error.InvalidProtocolOption,
ENOMEM => return error.SystemResources,
ENOBUFS => return error.SystemResources,
else => |err| return unexpectedErrno(err),
}
}
pub const MemFdCreateError = error{
SystemFdQuotaExceeded,
ProcessFdQuotaExceeded,
OutOfMemory,
/// memfd_create is available in Linux 3.17 and later. This error is returned
/// for older kernel versions.
SystemOutdated,
} || UnexpectedError;
pub const memfd_createC = @compileError("deprecated: renamed to memfd_createZ");
pub fn memfd_createZ(name: [*:0]const u8, flags: u32) MemFdCreateError!fd_t {
// memfd_create is available only in glibc versions starting with 2.27.
const use_c = std.c.versionCheck(.{ .major = 2, .minor = 27, .patch = 0 }).ok;
const sys = if (use_c) std.c else linux;
const getErrno = if (use_c) std.c.getErrno else linux.getErrno;
const rc = sys.memfd_create(name, flags);
switch (getErrno(rc)) {
0 => return @intCast(fd_t, rc),
EFAULT => unreachable, // name has invalid memory
EINVAL => unreachable, // name/flags are faulty
ENFILE => return error.SystemFdQuotaExceeded,
EMFILE => return error.ProcessFdQuotaExceeded,
ENOMEM => return error.OutOfMemory,
ENOSYS => return error.SystemOutdated,
else => |err| return unexpectedErrno(err),
}
}
pub const MFD_NAME_PREFIX = "memfd:";
pub const MFD_MAX_NAME_LEN = NAME_MAX - MFD_NAME_PREFIX.len;
fn toMemFdPath(name: []const u8) ![MFD_MAX_NAME_LEN:0]u8 {
var path_with_null: [MFD_MAX_NAME_LEN:0]u8 = undefined;
// >= rather than > to make room for the null byte
if (name.len >= MFD_MAX_NAME_LEN) return error.NameTooLong;
mem.copy(u8, &path_with_null, name);
path_with_null[name.len] = 0;
return path_with_null;
}
pub fn memfd_create(name: []const u8, flags: u32) !fd_t {
const name_t = try toMemFdPath(name);
return memfd_createZ(&name_t, flags);
}
pub fn getrusage(who: i32) rusage {
var result: rusage = undefined;
const rc = system.getrusage(who, &result);
switch (errno(rc)) {
0 => return result,
EINVAL => unreachable,
EFAULT => unreachable,
else => unreachable,
}
}
pub const TermiosGetError = error{NotATerminal} || UnexpectedError;
pub fn tcgetattr(handle: fd_t) TermiosGetError!termios {
var term: termios = undefined;
switch (errno(system.tcgetattr(handle, &term))) {
0 => return term,
EBADF => unreachable,
ENOTTY => return error.NotATerminal,
else => |err| return unexpectedErrno(err),
}
}
pub const TermiosSetError = TermiosGetError || error{ProcessOrphaned};
pub fn tcsetattr(handle: fd_t, optional_action: TCSA, termios_p: termios) TermiosSetError!void {
while (true) {
switch (errno(system.tcsetattr(handle, optional_action, &termios_p))) {
0 => return,
EBADF => unreachable,
EINTR => continue,
EINVAL => unreachable,
ENOTTY => return error.NotATerminal,
EIO => return error.ProcessOrphaned,
else => |err| return unexpectedErrno(err),
}
}
}
|
lib/std/os.zig
|
const std = @import("std");
const stb = @import("stb_image");
const gl = @import("gl");
const Self = @This();
id: c_uint = undefined,
width: f32 = undefined,
height: f32 = undefined,
dead: bool = true,
/// Loads an already existing opengl texture from a c_uint
/// inDepth optionally inspects the opengl texture to fill in texture width/height information.
pub fn from(id: c_uint, inDepth: bool) Self {
var self: Self = .{ .id = id, .dead = false };
if (inDepth) {
self.updateInformation();
}
return self;
}
/// Takes a file path and loads it into opengl using stb_image.
pub fn init(filePath: []const u8) !Self {
var ownedFp: [:0]const u8 = try std.heap.c_allocator.dupeZ(u8, filePath);
defer std.heap.c_allocator.free(ownedFp);
var w: c_int = 0;
var h: c_int = 0;
var numChannels: c_int = 0;
var data = stb.stbi_load(ownedFp.ptr, &w, &h, &numChannels, 0);
var self = Self{};
self.width = @intToFloat(f32, w);
self.height = @intToFloat(f32, h);
gl.glGenTextures(1, &self.id);
gl.glBindTexture(gl.GL_TEXTURE_2D, self.id);
gl.glTexParameteri(gl.GL_TEXTURE_2D, gl.GL_TEXTURE_WRAP_S, gl.GL_REPEAT);
gl.glTexParameteri(gl.GL_TEXTURE_2D, gl.GL_TEXTURE_WRAP_T, gl.GL_REPEAT);
gl.glTexParameteri(gl.GL_TEXTURE_2D, gl.GL_TEXTURE_MIN_FILTER, gl.GL_LINEAR);
gl.glTexParameteri(gl.GL_TEXTURE_2D, gl.GL_TEXTURE_MAG_FILTER, gl.GL_LINEAR);
switch (numChannels) {
3 => {
gl.glTexImage2D(gl.GL_TEXTURE_2D, 0, gl.GL_RGB, w, h, 0, gl.GL_RGB, gl.GL_UNSIGNED_BYTE, data);
},
4 => {
gl.glTexImage2D(gl.GL_TEXTURE_2D, 0, gl.GL_RGBA, w, h, 0, gl.GL_RGBA, gl.GL_UNSIGNED_BYTE, data);
},
else => {
std.debug.print("ERROR! Failed to compile texture {s} with {any} channels.\n", .{ filePath, numChannels });
gl.glBindTexture(gl.GL_TEXTURE_2D, 0);
return error.FailedToInit;
},
}
gl.glGenerateMipmap(gl.GL_TEXTURE_2D);
stb.stbi_image_free(data);
self.dead = false;
gl.glBindTexture(gl.GL_TEXTURE_2D, 0); // Init isnt an explicit bind, so reset.
return self;
}
pub fn initBlank(width: c_int, height: c_int) Self {
var self = Self{};
self.width = @intToFloat(f32, width);
self.height = @intToFloat(f32, height);
gl.glGenTextures(1, &self.id);
gl.glBindTexture(gl.GL_TEXTURE_2D, self.id);
gl.glTexImage2D(gl.GL_TEXTURE_2D, 0, gl.GL_RGBA, width, height, 0, gl.GL_RGBA, gl.GL_UNSIGNED_BYTE, null);
gl.glTexParameteri(gl.GL_TEXTURE_2D, gl.GL_TEXTURE_MIN_FILTER, gl.GL_LINEAR);
gl.glTexParameteri(gl.GL_TEXTURE_2D, gl.GL_TEXTURE_MAG_FILTER, gl.GL_LINEAR);
gl.glBindTexture(gl.GL_TEXTURE_2D, 0);
return self;
}
pub fn deinit(self: *Self) void {
gl.glDeleteTextures(1, &self.id);
self.dead = true;
}
/// using Texture.from(c_uint) is a naive cast that wont query size to generate information.
fn updateInformation(self: *Self) void {
self.bind();
var w: c_int = 0;
var h: c_int = 0;
gl.glGetTexLevelParameteriv(gl.GL_TEXTURE_2D, 0, gl.GL_TEXTURE_WIDTH, &w);
gl.glGetTexLevelParameteriv(gl.GL_TEXTURE_2D, 0, gl.GL_TEXTURE_HEIGHT, &h);
self.width = @intToFloat(f32, w);
self.height = @intToFloat(f32, h);
}
pub fn bind(self: *Self) void {
gl.glActiveTexture(gl.GL_TEXTURE0);
gl.glBindTexture(gl.GL_TEXTURE_2D, self.id);
}
pub fn unbind(self: *Self) void {
_ = self;
gl.glBindTexture(gl.GL_TEXTURE_2D, 0);
}
pub fn setNearestFilter(self: *Self) void {
gl.glBindTexture(gl.GL_TEXTURE_2D, self.id);
gl.glTexParameteri(gl.GL_TEXTURE_2D, gl.GL_TEXTURE_MIN_FILTER, gl.GL_NEAREST);
gl.glTexParameteri(gl.GL_TEXTURE_2D, gl.GL_TEXTURE_MAG_FILTER, gl.GL_NEAREST);
gl.glBindTexture(gl.GL_TEXTURE_2D, 0); // Clear
}
pub fn setLinearFilter(self: *Self) void {
gl.glBindTexture(gl.GL_TEXTURE_2D, self.id);
gl.glTexParameteri(gl.GL_TEXTURE_2D, gl.GL_TEXTURE_MIN_FILTER, gl.GL_LINEAR);
gl.glTexParameteri(gl.GL_TEXTURE_2D, gl.GL_TEXTURE_MAG_FILTER, gl.GL_LINEAR);
gl.glBindTexture(gl.GL_TEXTURE_2D, 0); // Clear
}
/// Use this to get the correct Texture ID for use in imgui.
pub fn imguiId(self: *Self) *anyopaque {
return @intToPtr(*anyopaque, self.id);
}
|
src/zt/texture.zig
|
const Builder = @import("std").build.Builder;
const packages = @import("zig-cache/packages.zig").list;
pub fn build(b: *Builder) void {
var target = b.standardTargetOptions(.{});
if (target.abi == null) {
target.abi = .musl;
}
const exe = b.addExecutable("toybox", "src/main.zig");
// TODO: for some reason we get SIGILL when not building C code with
// ReleaseFast
exe.setBuildMode(.ReleaseFast);
exe.setTarget(target);
exe.single_threaded = true;
exe.addIncludeDir(".");
exe.addIncludeDir("lib");
for (packages) |pkg| {
exe.addPackage(pkg);
}
exe.addCSourceFile("main.c", &[_][]const u8{});
inline for (lib_srcs) |src| {
exe.addCSourceFile("lib/" ++ src, &[_][]const u8{});
}
inline for (c_srcs) |src| {
exe.addCSourceFile("toys/" ++ src, &[_][]const u8{});
}
exe.setOutputDir(".");
exe.linkLibC();
exe.install();
const run_cmd = exe.run();
run_cmd.step.dependOn(b.getInstallStep());
const run_step = b.step("run", "Run the app");
run_step.dependOn(&run_cmd.step);
}
const lib_srcs = [_][]const u8{
"args.c",
"commas.c",
"deflate.c",
"dirtree.c",
"env.c",
"help.c",
"lib.c",
"linestack.c",
"llist.c",
"net.c",
"password.c",
"portability.c",
"tty.c",
"xwrap.c",
};
const c_srcs = [_][]const u8{
"posix/nl.c",
"posix/mkdir.c",
"posix/test.c",
"posix/sleep.c",
"posix/expand.c",
"posix/unlink.c",
"posix/du.c",
"posix/true.c",
"posix/chgrp.c",
"posix/cp.c",
"posix/who.c",
"posix/tar.c",
"posix/chmod.c",
"posix/ps.c",
"posix/iconv.c",
"posix/pwd.c",
"posix/uudecode.c",
"posix/file.c",
"posix/getconf.c",
"posix/split.c",
"posix/kill.c",
"posix/strings.c",
"posix/ln.c",
"posix/nice.c",
"posix/basename.c",
"posix/rm.c",
"posix/xargs.c",
"posix/df.c",
"posix/wc.c",
"posix/ulimit.c",
"posix/renice.c",
"posix/ls.c",
"posix/grep.c",
"posix/uname.c",
"posix/cpio.c",
"posix/tail.c",
"posix/tee.c",
"posix/sed.c",
"posix/env.c",
"posix/sort.c",
"posix/find.c",
"posix/false.c",
"posix/patch.c",
"posix/cut.c",
"posix/head.c",
"posix/logger.c",
"posix/printf.c",
"posix/cksum.c",
"posix/mkfifo.c",
"posix/echo.c",
"posix/cmp.c",
"posix/link.c",
"posix/id.c",
"posix/uniq.c",
"posix/nohup.c",
"posix/cal.c",
"posix/date.c",
"posix/rmdir.c",
"posix/cat.c",
"posix/od.c",
"posix/touch.c",
"posix/time.c",
"posix/paste.c",
"posix/uuencode.c",
"posix/dirname.c",
"posix/tty.c",
"posix/comm.c",
"net/microcom.c",
"net/netcat.c",
"net/tunctl.c",
"net/rfkill.c",
"net/ftpget.c",
"net/ping.c",
"net/netstat.c",
"net/ifconfig.c",
"net/sntp.c",
"other/ascii.c",
"other/uuidgen.c",
"other/rmmod.c",
"other/nsenter.c",
"other/w.c",
"other/count.c",
"other/modinfo.c",
"other/hwclock.c",
"other/mcookie.c",
"other/which.c",
"other/help.c",
"other/partprobe.c",
"other/reboot.c",
"other/acpi.c",
"other/inotifyd.c",
"other/nbd_client.c",
"other/usleep.c",
"other/fsfreeze.c",
"other/fmt.c",
"other/pmap.c",
"other/truncate.c",
"other/eject.c",
"other/ionice.c",
"other/xxd.c",
"other/pwdx.c",
"other/mix.c",
"other/setsid.c",
"other/losetup.c",
"other/switch_root.c",
"other/flock.c",
"other/vconfig.c",
"other/fsync.c",
"other/shred.c",
"other/devmem.c",
"other/watch.c",
"other/lspci.c",
"other/clear.c",
"other/lsattr.c",
"other/mountpoint.c",
"other/login.c",
"other/free.c",
"other/blkdiscard.c",
"other/setfattr.c",
"other/reset.c",
"other/uptime.c",
"other/sysctl.c",
"other/yes.c",
"other/readlink.c",
"other/readahead.c",
"other/chvt.c",
"other/mkpasswd.c",
"other/swapoff.c",
"other/pivot_root.c",
"other/timeout.c",
"other/insmod.c",
"other/blkid.c",
"other/blockdev.c",
"other/i2ctools.c",
"other/makedevs.c",
"other/mkswap.c",
"other/vmstat.c",
"other/printenv.c",
"other/factor.c",
"other/rtcwake.c",
"other/chrt.c",
"other/rev.c",
"other/tac.c",
"other/dos2unix.c",
"other/stat.c",
"other/lsusb.c",
"other/freeramdisk.c",
"other/oneit.c",
"other/chroot.c",
"other/fallocate.c",
"other/base64.c",
"other/taskset.c",
"other/swapon.c",
"other/bzcat.c",
"other/hexedit.c",
"other/lsmod.c",
"lsb/umount.c",
"lsb/md5sum.c",
"lsb/mknod.c",
"lsb/sync.c",
"lsb/su.c",
"lsb/mount.c",
"lsb/passwd.c",
"lsb/dmesg.c",
"lsb/mktemp.c",
"lsb/gzip.c",
"lsb/killall.c",
"lsb/pidof.c",
"lsb/seq.c",
"lsb/hostname.c",
};
|
build.zig
|
const math3d = @import("math3d.zig");
const Vec4 = math3d.Vec4;
const Mat4x4 = math3d.Mat4x4;
const mat4x4_identity = math3d.mat4x4_identity;
const tetris = @import("tetris.zig");
const Tetris = tetris.Tetris;
const std = @import("std");
const panic = std.debug.panic;
const assert = std.debug.assert;
const bufPrint = std.fmt.bufPrint;
const c = @import("c.zig");
const glfw = @import("vendor/zglfw/src/glfw3.zig");
const debug_gl = @import("debug_gl.zig");
const AllShaders = @import("all_shaders.zig").AllShaders;
const StaticGeometry = @import("static_geometry.zig").StaticGeometry;
const pieces = @import("pieces.zig");
const Piece = pieces.Piece;
const Spritesheet = @import("spritesheet.zig").Spritesheet;
var all_shaders: AllShaders = undefined;
var static_geometry: StaticGeometry = undefined;
var font: Spritesheet = undefined;
fn errorCallback(err: c_int, description: [*c]const u8) callconv(.C) void {
panic("Error: {}\n", .{@as([*:0]const u8, description)});
}
fn keyCallback(win: *glfw.Window, key: c_int, scancode: c_int, action: c_int, mods: c_int) callconv(.C) void {
if (action != @enumToInt(glfw.KeyState.Press)) return;
const t = @ptrCast(*Tetris, @alignCast(@alignOf(Tetris), glfw.getWindowUserPointer(win).?));
const key_enum = @intToEnum(glfw.Key, key);
switch (key_enum) {
glfw.Key.Escape => glfw.setWindowShouldClose(win, true),
glfw.Key.Space => tetris.userDropCurPiece(t),
glfw.Key.Down => tetris.userCurPieceFall(t),
glfw.Key.Left => tetris.userMoveCurPiece(t, -1),
glfw.Key.Right => tetris.userMoveCurPiece(t, 1),
glfw.Key.Up => tetris.userRotateCurPiece(t, 1),
glfw.Key.LeftShift, glfw.Key.RightShift => tetris.userRotateCurPiece(t, -1),
glfw.Key.R => tetris.restartGame(t),
glfw.Key.P => tetris.userTogglePause(t),
glfw.Key.LeftControl, glfw.Key.RightControl => tetris.userSetHoldPiece(t),
else => {},
}
}
var tetris_state: Tetris = undefined;
const font_png = @embedFile("../assets/font.png");
pub fn main() !void {
_ = glfw.setErrorCallback(errorCallback);
try glfw.init();
defer glfw.terminate();
glfw.windowHint(glfw.WindowHint.ContextVersionMajor, 3);
glfw.windowHint(glfw.WindowHint.ContextVersionMinor, 2);
glfw.windowHint(glfw.WindowHint.OpenGLForwardCompat, @as(c_int, c.GL_TRUE));
glfw.windowHint(glfw.WindowHint.OpenGLDebugContext, debug_gl.is_on);
glfw.windowHint(glfw.WindowHint.OpenGLProfile, @enumToInt(glfw.GLProfileAttribute.OpenglCoreProfile));
glfw.windowHint(glfw.WindowHint.DepthBits, 0);
glfw.windowHint(glfw.WindowHint.StencilBits, 8);
glfw.windowHint(glfw.WindowHint.Resizable, @as(c_int, c.GL_FALSE));
var window = try glfw.createWindow(tetris.window_width, tetris.window_height, "Tetris", null, null);
defer glfw.destroyWindow(window);
_ = glfw.setKeyCallback(window, keyCallback);
glfw.makeContextCurrent(window);
glfw.swapInterval(1);
// create and bind exactly one vertex array per context and use
// glVertexAttribPointer etc every frame.
var vertex_array_object: c.GLuint = undefined;
c.glGenVertexArrays(1, &vertex_array_object);
c.glBindVertexArray(vertex_array_object);
defer c.glDeleteVertexArrays(1, &vertex_array_object);
const t = &tetris_state;
glfw.getFramebufferSize(window, &t.framebuffer_width, &t.framebuffer_height);
assert(t.framebuffer_width >= tetris.window_width);
assert(t.framebuffer_height >= tetris.window_height);
all_shaders = try AllShaders.create();
defer all_shaders.destroy();
static_geometry = StaticGeometry.create();
defer static_geometry.destroy();
font.init(font_png, tetris.font_char_width, tetris.font_char_height) catch {
panic("unable to read assets\n", .{});
};
defer font.deinit();
var seed_bytes: [@sizeOf(u64)]u8 = undefined;
std.crypto.randomBytes(seed_bytes[0..]) catch |err| {
panic("unable to seed random number generator: {}", .{err});
};
t.prng = std.rand.DefaultPrng.init(std.mem.readIntNative(u64, &seed_bytes));
t.rand = &t.prng.random;
tetris.resetProjection(t);
tetris.restartGame(t);
c.glClearColor(0.0, 0.0, 0.0, 1.0);
c.glEnable(c.GL_BLEND);
c.glBlendFunc(c.GL_SRC_ALPHA, c.GL_ONE_MINUS_SRC_ALPHA);
c.glPixelStorei(c.GL_UNPACK_ALIGNMENT, 1);
c.glViewport(0, 0, t.framebuffer_width, t.framebuffer_height);
glfw.setWindowUserPointer(window, @ptrCast(*c_void, t));
debug_gl.assertNoError();
const start_time = glfw.getTime();
var prev_time = start_time;
while (!glfw.windowShouldClose(window)) {
c.glClear(c.GL_COLOR_BUFFER_BIT | c.GL_DEPTH_BUFFER_BIT | c.GL_STENCIL_BUFFER_BIT);
const now_time = glfw.getTime();
const elapsed = now_time - prev_time;
prev_time = now_time;
tetris.nextFrame(t, elapsed);
tetris.draw(t, @This());
glfw.swapBuffers(window);
glfw.pollEvents();
}
debug_gl.assertNoError();
}
pub fn fillRectMvp(t: *Tetris, color: Vec4, mvp: Mat4x4) void {
all_shaders.primitive.bind();
all_shaders.primitive.setUniformVec4(all_shaders.primitive_uniform_color, color);
all_shaders.primitive.setUniformMat4x4(all_shaders.primitive_uniform_mvp, mvp);
c.glBindBuffer(c.GL_ARRAY_BUFFER, static_geometry.rect_2d_vertex_buffer);
c.glEnableVertexAttribArray(@intCast(c.GLuint, all_shaders.primitive_attrib_position));
c.glVertexAttribPointer(@intCast(c.GLuint, all_shaders.primitive_attrib_position), 3, c.GL_FLOAT, c.GL_FALSE, 0, null);
c.glDrawArrays(c.GL_TRIANGLE_STRIP, 0, 4);
}
pub fn drawParticle(t: *Tetris, p: tetris.Particle) void {
const model = mat4x4_identity.translateByVec(p.pos).rotate(p.angle, p.axis).scale(p.scale_w, p.scale_h, 0.0);
const mvp = t.projection.mult(model);
all_shaders.primitive.bind();
all_shaders.primitive.setUniformVec4(all_shaders.primitive_uniform_color, p.color);
all_shaders.primitive.setUniformMat4x4(all_shaders.primitive_uniform_mvp, mvp);
c.glBindBuffer(c.GL_ARRAY_BUFFER, static_geometry.triangle_2d_vertex_buffer);
c.glEnableVertexAttribArray(@intCast(c.GLuint, all_shaders.primitive_attrib_position));
c.glVertexAttribPointer(@intCast(c.GLuint, all_shaders.primitive_attrib_position), 3, c.GL_FLOAT, c.GL_FALSE, 0, null);
c.glDrawArrays(c.GL_TRIANGLE_STRIP, 0, 3);
}
pub fn drawText(t: *Tetris, text: []const u8, left: i32, top: i32, size: f32) void {
for (text) |col, i| {
if (col <= '~') {
const char_left = @intToFloat(f32, left) + @intToFloat(f32, i * tetris.font_char_width) * size;
const model = mat4x4_identity.translate(char_left, @intToFloat(f32, top), 0.0).scale(size, size, 0.0);
const mvp = t.projection.mult(model);
font.draw(all_shaders, col, mvp);
} else {
unreachable;
}
}
}
|
src/main.zig
|
const std = @import("std");
const Compilation = @import("../Compilation.zig");
const Object = @import("../Object.zig");
const Elf = @This();
const Section = struct {
data: std.ArrayList(u8),
relocations: std.ArrayListUnmanaged(Relocation) = .{},
flags: u64,
type: u32,
index: u16 = undefined,
};
const Symbol = struct {
section: ?*Section,
size: u64,
offset: u64,
index: u16 = undefined,
info: u8,
};
const Relocation = packed struct {
symbol: *Symbol,
addend: i64,
offset: u48,
type: u8,
};
const additional_sections = 3; // null section, strtab, symtab
const strtab_index = 1;
const symtab_index = 2;
const strtab_default = "\x00.strtab\x00.symtab\x00";
const strtab_name = 1;
const symtab_name = "\x00.strtab\x00".len;
obj: Object,
/// The keys are owned by the Codegen.tree
sections: std.StringHashMapUnmanaged(*Section) = .{},
local_symbols: std.StringHashMapUnmanaged(*Symbol) = .{},
global_symbols: std.StringHashMapUnmanaged(*Symbol) = .{},
unnamed_symbol_mangle: u32 = 0,
strtab_len: u64 = strtab_default.len,
arena: std.heap.ArenaAllocator,
pub fn create(comp: *Compilation) !*Object {
const elf = try comp.gpa.create(Elf);
elf.* = .{
.obj = .{ .format = .elf, .comp = comp },
.arena = std.heap.ArenaAllocator.init(comp.gpa),
};
return &elf.obj;
}
pub fn deinit(elf: *Elf) void {
const gpa = elf.arena.child_allocator;
{
var it = elf.sections.valueIterator();
while (it.next()) |sect| {
sect.*.data.deinit();
sect.*.relocations.deinit(gpa);
}
}
elf.sections.deinit(gpa);
elf.local_symbols.deinit(gpa);
elf.global_symbols.deinit(gpa);
elf.arena.deinit();
gpa.destroy(elf);
}
fn sectionString(sec: Object.Section) []const u8 {
return switch (sec) {
.@"undefined" => unreachable,
.data => "data",
.read_only_data => "rodata",
.func => "text",
.strings => "rodata.str",
.custom => |name| name,
};
}
pub fn getSection(elf: *Elf, section_kind: Object.Section) !*std.ArrayList(u8) {
const section_name = sectionString(section_kind);
const section = elf.sections.get(section_name) orelse blk: {
const section = try elf.arena.allocator.create(Section);
section.* = .{
.data = std.ArrayList(u8).init(elf.arena.child_allocator),
.type = std.elf.SHT_PROGBITS,
.flags = switch (section_kind) {
.func, .custom => std.elf.SHF_ALLOC + std.elf.SHF_EXECINSTR,
.strings => std.elf.SHF_ALLOC + std.elf.SHF_MERGE + std.elf.SHF_STRINGS,
.read_only_data => std.elf.SHF_ALLOC,
.data => std.elf.SHF_ALLOC + std.elf.SHF_WRITE,
.@"undefined" => unreachable,
},
};
try elf.sections.putNoClobber(elf.arena.child_allocator, section_name, section);
elf.strtab_len += section_name.len + ".\x00".len;
break :blk section;
};
return §ion.data;
}
pub fn declareSymbol(
elf: *Elf,
section_kind: Object.Section,
maybe_name: ?[]const u8,
linkage: std.builtin.GlobalLinkage,
@"type": Object.SymbolType,
offset: u64,
size: u64,
) ![]const u8 {
const section = blk: {
if (section_kind == .@"undefined") break :blk null;
const section_name = sectionString(section_kind);
break :blk elf.sections.get(section_name);
};
const binding: u8 = switch (linkage) {
.Internal => std.elf.STB_LOCAL,
.Strong => std.elf.STB_GLOBAL,
.Weak => std.elf.STB_WEAK,
.LinkOnce => unreachable,
};
const sym_type: u8 = switch (@"type") {
.func => std.elf.STT_FUNC,
.variable => std.elf.STT_OBJECT,
.external => std.elf.STT_NOTYPE,
};
const name = if (maybe_name) |some| some else blk: {
defer elf.unnamed_symbol_mangle += 1;
break :blk try std.fmt.allocPrint(&elf.arena.allocator, ".L.{d}", .{elf.unnamed_symbol_mangle});
};
const gop = if (linkage == .Internal)
try elf.local_symbols.getOrPut(elf.arena.child_allocator, name)
else
try elf.global_symbols.getOrPut(elf.arena.child_allocator, name);
if (!gop.found_existing) {
gop.value_ptr.* = try elf.arena.allocator.create(Symbol);
elf.strtab_len += name.len + 1; // +1 for null byte
}
gop.value_ptr.*.* = .{
.section = section,
.size = size,
.offset = offset,
.info = (binding << 4) + sym_type,
};
return name;
}
pub fn addRelocation(elf: *Elf, name: []const u8, section_kind: Object.Section, address: u64, addend: i64) !void {
const section_name = sectionString(section_kind);
const symbol = elf.local_symbols.get(name) orelse elf.global_symbols.get(name).?; // reference to undeclared symbol
const section = elf.sections.get(section_name).?;
if (section.relocations.items.len == 0) elf.strtab_len += ".rela".len;
try section.relocations.append(elf.arena.child_allocator, .{
.symbol = symbol,
.offset = @intCast(u48, address),
.addend = addend,
.type = if (symbol.section == null) 4 else 2, // TODO
});
}
/// elf header
/// sections contents
/// symbols
/// relocations
/// strtab
/// section headers
pub fn finish(elf: *Elf, file: std.fs.File) !void {
var buf_writer = std.io.bufferedWriter(file.writer());
const w = buf_writer.writer();
var num_sections: std.elf.Elf64_Half = additional_sections;
var relocations_len: std.elf.Elf64_Off = 0;
var sections_len: std.elf.Elf64_Off = 0;
{
var it = elf.sections.valueIterator();
while (it.next()) |sect| {
sections_len += sect.*.data.items.len;
relocations_len += sect.*.relocations.items.len * @sizeOf(std.elf.Elf64_Rela);
sect.*.index = num_sections;
num_sections += 1;
num_sections += @boolToInt(sect.*.relocations.items.len != 0);
}
}
const symtab_len = (elf.local_symbols.count() + elf.global_symbols.count() + 1) * @sizeOf(std.elf.Elf64_Sym);
const symtab_offset = @sizeOf(std.elf.Elf64_Ehdr) + sections_len;
const symtab_offset_aligned = std.mem.alignForward(symtab_offset, 8);
const rela_offset = symtab_offset_aligned + symtab_len;
const strtab_offset = rela_offset + relocations_len;
const sh_offset = strtab_offset + elf.strtab_len;
const sh_offset_aligned = std.mem.alignForward(sh_offset, 16);
var elf_header = std.elf.Elf64_Ehdr{
.e_ident = .{ 0x7F, 'E', 'L', 'F', 2, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0 },
.e_type = std.elf.ET.REL, // we only produce relocatables
.e_machine = elf.obj.comp.target.cpu.arch.toElfMachine(),
.e_version = 1,
.e_entry = 0, // linker will handle this
.e_phoff = 0, // no program header
.e_shoff = sh_offset_aligned, // section headers offset
.e_flags = 0, // no flags
.e_ehsize = @sizeOf(std.elf.Elf64_Ehdr),
.e_phentsize = 0, // no program header
.e_phnum = 0, // no program header
.e_shentsize = @sizeOf(std.elf.Elf64_Shdr),
.e_shnum = num_sections,
.e_shstrndx = strtab_index,
};
try w.writeStruct(elf_header);
// write contents of sections
{
var it = elf.sections.valueIterator();
while (it.next()) |sect| try w.writeAll(sect.*.data.items);
}
// pad to 8 bytes
try w.writeByteNTimes(0, symtab_offset_aligned - symtab_offset);
var name_offset: u32 = strtab_default.len;
// write symbols
{
// first symbol must be null
try w.writeStruct(std.mem.zeroes(std.elf.Elf64_Sym));
var sym_index: u16 = 1;
var it = elf.local_symbols.iterator();
while (it.next()) |entry| {
const sym = entry.value_ptr.*;
try w.writeStruct(std.elf.Elf64_Sym{
.st_name = name_offset,
.st_info = sym.info,
.st_other = 0,
.st_shndx = if (sym.section) |some| some.index else 0,
.st_value = sym.offset,
.st_size = sym.size,
});
sym.index = sym_index;
sym_index += 1;
name_offset += @intCast(u32, entry.key_ptr.len + 1); // +1 for null byte
}
it = elf.global_symbols.iterator();
while (it.next()) |entry| {
const sym = entry.value_ptr.*;
try w.writeStruct(std.elf.Elf64_Sym{
.st_name = name_offset,
.st_info = sym.info,
.st_other = 0,
.st_shndx = if (sym.section) |some| some.index else 0,
.st_value = sym.offset,
.st_size = sym.size,
});
sym.index = sym_index;
sym_index += 1;
name_offset += @intCast(u32, entry.key_ptr.len + 1); // +1 for null byte
}
}
// write relocations
{
var it = elf.sections.valueIterator();
while (it.next()) |sect| {
for (sect.*.relocations.items) |rela| {
try w.writeStruct(std.elf.Elf64_Rela{
.r_offset = rela.offset,
.r_addend = rela.addend,
.r_info = (@as(u64, rela.symbol.index) << 32) | rela.type,
});
}
}
}
// write strtab
try w.writeAll(strtab_default);
{
var it = elf.local_symbols.keyIterator();
while (it.next()) |key| try w.print("{s}\x00", .{key.*});
it = elf.global_symbols.keyIterator();
while (it.next()) |key| try w.print("{s}\x00", .{key.*});
}
{
var it = elf.sections.iterator();
while (it.next()) |entry| {
if (entry.value_ptr.*.relocations.items.len != 0) try w.writeAll(".rela");
try w.print(".{s}\x00", .{entry.key_ptr.*});
}
}
// pad to 16 bytes
try w.writeByteNTimes(0, sh_offset_aligned - sh_offset);
// mandatory null header
try w.writeStruct(std.mem.zeroes(std.elf.Elf64_Shdr));
// write strtab section header
{
var sect_header = std.elf.Elf64_Shdr{
.sh_name = strtab_name,
.sh_type = std.elf.SHT_STRTAB,
.sh_flags = 0,
.sh_addr = 0,
.sh_offset = strtab_offset,
.sh_size = elf.strtab_len,
.sh_link = 0,
.sh_info = 0,
.sh_addralign = 1,
.sh_entsize = 0,
};
try w.writeStruct(sect_header);
}
// write symtab section header
{
var sect_header = std.elf.Elf64_Shdr{
.sh_name = symtab_name,
.sh_type = std.elf.SHT_SYMTAB,
.sh_flags = 0,
.sh_addr = 0,
.sh_offset = symtab_offset_aligned,
.sh_size = symtab_len,
.sh_link = strtab_index,
.sh_info = elf.local_symbols.size + 1,
.sh_addralign = 8,
.sh_entsize = @sizeOf(std.elf.Elf64_Sym),
};
try w.writeStruct(sect_header);
}
// remaining section headers
{
var sect_offset: u64 = @sizeOf(std.elf.Elf64_Ehdr);
var rela_sect_offset: u64 = rela_offset;
var it = elf.sections.iterator();
while (it.next()) |entry| {
const sect = entry.value_ptr.*;
const rela_count = sect.relocations.items.len;
const rela_name_offset = if (rela_count != 0) @truncate(u32, ".rela".len) else 0;
try w.writeStruct(std.elf.Elf64_Shdr{
.sh_name = rela_name_offset + name_offset,
.sh_type = sect.type,
.sh_flags = sect.flags,
.sh_addr = 0,
.sh_offset = sect_offset,
.sh_size = sect.data.items.len,
.sh_link = 0,
.sh_info = 0,
.sh_addralign = if (sect.flags & std.elf.SHF_EXECINSTR != 0) 16 else 1,
.sh_entsize = 0,
});
if (rela_count != 0) {
const size = rela_count * @sizeOf(std.elf.Elf64_Rela);
try w.writeStruct(std.elf.Elf64_Shdr{
.sh_name = name_offset,
.sh_type = std.elf.SHT_RELA,
.sh_flags = 0,
.sh_addr = 0,
.sh_offset = rela_sect_offset,
.sh_size = rela_count * @sizeOf(std.elf.Elf64_Rela),
.sh_link = symtab_index,
.sh_info = sect.index,
.sh_addralign = 8,
.sh_entsize = @sizeOf(std.elf.Elf64_Rela),
});
rela_sect_offset += size;
}
sect_offset += sect.data.items.len;
name_offset += @intCast(u32, entry.key_ptr.len + ".\x00".len) + rela_name_offset;
}
}
try buf_writer.flush();
}
|
src/object/Elf.zig
|
const std = @import("std");
const testing = std.testing;
const allocator = std.testing.allocator;
pub const Probe = struct {
const V2 = struct {
x: isize,
y: isize,
pub fn init(x: isize, y: isize) V2 {
var self = V2{ .x = x, .y = y };
return self;
}
};
tmin: V2,
tmax: V2,
pub fn init() Probe {
var self = Probe{
.tmin = V2.init(0, 0),
.tmax = V2.init(0, 0),
};
return self;
}
pub fn deinit(_: *Probe) void {}
pub fn process_line(self: *Probe, data: []const u8) !void {
var pos_colon: usize = 0;
var it_colon = std.mem.split(u8, data, ":");
while (it_colon.next()) |data_colon| : (pos_colon += 1) {
if (pos_colon != 1) continue;
var pos_comma: usize = 0;
var it_comma = std.mem.split(u8, data_colon, ",");
while (it_comma.next()) |data_comma| : (pos_comma += 1) {
var pos_eq: usize = 0;
var it_eq = std.mem.split(u8, data_comma, "=");
while (it_eq.next()) |data_eq| : (pos_eq += 1) {
if (pos_eq != 1) continue;
var pos_dots: usize = 0;
var it_dots = std.mem.split(u8, data_eq, "..");
while (it_dots.next()) |num| : (pos_dots += 1) {
const n = std.fmt.parseInt(isize, num, 10) catch unreachable;
if (pos_comma == 0 and pos_dots == 0) {
self.tmin.x = n;
continue;
}
if (pos_comma == 0 and pos_dots == 1) {
self.tmax.x = n;
continue;
}
if (pos_comma == 1 and pos_dots == 0) {
self.tmin.y = n;
continue;
}
if (pos_comma == 1 and pos_dots == 1) {
self.tmax.y = n;
continue;
}
unreachable;
}
}
}
// std.debug.warn("LINE => {} {}\n", .{ self.tmin, self.tmax });
}
}
pub fn shoot(self: Probe, vel_ini: V2) isize {
var pos: V2 = V2.init(0, 0);
var vel: V2 = vel_ini;
var top: isize = 0;
while (true) {
if (pos.x >= self.tmin.x and pos.x <= self.tmax.x and pos.y >= self.tmin.y and pos.y <= self.tmax.y) {
return top;
}
if (vel.x == 0 and pos.x < self.tmin.x and pos.x > self.tmax.x) break;
if (vel.y < 0 and pos.y < self.tmin.y) break;
pos.y += vel.y;
pos.x += vel.x;
vel.y -= 1;
if (vel.x > 0) {
vel.x -= 1;
} else if (vel.x < 0) {
vel.x += 1;
}
if (top < pos.y) top = pos.y;
}
return std.math.minInt(isize);
}
fn get_vx(x: isize) isize {
const ux = @intCast(usize, std.math.absInt(x) catch unreachable);
const delta = 1 + 8 * ux;
const vx = @divTrunc(@intCast(isize, std.math.sqrt(delta)), 2);
return vx;
}
pub fn find_highest_position(self: Probe) isize {
const mx = @divTrunc(self.tmax.x + self.tmin.x, 2);
const vx = get_vx(mx);
// we can find vx deterministically, but vy is brute-forced... :-(
var vel = V2.init(vx, 0);
var highest_pos: isize = std.math.minInt(isize);
var vy: isize = -200;
while (vy <= 200) : (vy += 1) {
vel.y = vy;
const h = self.shoot(vel);
if (highest_pos < h) highest_pos = h;
}
return highest_pos;
}
pub fn count_velocities(self: Probe) usize {
var count: usize = 0;
// v is brute-forced... :-(
var vx: isize = 0;
while (vx <= 200) : (vx += 1) {
var vy: isize = -200;
while (vy <= 200) : (vy += 1) {
var vel = V2.init(vx, vy);
const h = self.shoot(vel);
if (h == std.math.minInt(isize)) continue;
count += 1;
}
}
return count;
}
};
test "sample part a 1" {
const data: []const u8 =
\\target area: x=20..30, y=-10..-5
;
var probe = Probe.init();
defer probe.deinit();
var it = std.mem.split(u8, data, "\n");
while (it.next()) |line| {
try probe.process_line(line);
}
try testing.expect(probe.shoot(Probe.V2.init(7, 2)) != std.math.minInt(isize));
try testing.expect(probe.shoot(Probe.V2.init(6, 3)) != std.math.minInt(isize));
try testing.expect(probe.shoot(Probe.V2.init(9, 0)) != std.math.minInt(isize));
try testing.expect(probe.shoot(Probe.V2.init(17, -4)) == std.math.minInt(isize));
const highest = probe.find_highest_position();
try testing.expect(highest == 45);
}
test "sample part a b" {
const data: []const u8 =
\\target area: x=20..30, y=-10..-5
;
var probe = Probe.init();
defer probe.deinit();
var it = std.mem.split(u8, data, "\n");
while (it.next()) |line| {
try probe.process_line(line);
}
const count = probe.count_velocities();
try testing.expect(count == 112);
}
|
2021/p17/probe.zig
|
const std = @import("std");
const math = std.math;
const assert = std.debug.assert;
const L = std.unicode.utf8ToUtf16LeStringLiteral;
const zwin32 = @import("zwin32");
const w = zwin32.base;
const d3d12 = zwin32.d3d12;
const wasapi = zwin32.wasapi;
const mf = zwin32.mf;
const hrPanic = zwin32.hrPanic;
const hrPanicOnFail = zwin32.hrPanicOnFail;
const zd3d12 = @import("zd3d12");
const common = @import("common");
const c = common.c;
const vm = common.vectormath;
const GuiRenderer = common.GuiRenderer;
const Vec2 = vm.Vec2;
const num_vis_samples = 400;
pub export const D3D12SDKVersion: u32 = 4;
pub export const D3D12SDKPath: [*:0]const u8 = ".\\d3d12\\";
const content_dir = @import("build_options").content_dir;
const window_name = "zig-gamedev: audio playback test";
const window_width = 1920;
const window_height = 1080;
const AudioContex = struct {
client: *wasapi.IAudioClient3,
render_client: *wasapi.IAudioRenderClient,
buffer_ready_event: w.HANDLE,
buffer_size_in_frames: u32,
thread_handle: ?w.HANDLE,
samples: std.ArrayList(i16),
current_frame_index: u32,
is_locked: bool,
};
const DemoState = struct {
grfx: zd3d12.GraphicsContext,
gui: GuiRenderer,
frame_stats: common.FrameStats,
audio: AudioContex,
lines_pso: zd3d12.PipelineHandle,
image_pso: zd3d12.PipelineHandle,
lines_buffer: zd3d12.ResourceHandle,
image: zd3d12.ResourceHandle,
image_srv: d3d12.CPU_DESCRIPTOR_HANDLE,
};
fn fillAudioBuffer(audio: *AudioContex) void {
while (@cmpxchgWeak(bool, &audio.is_locked, false, true, .Acquire, .Monotonic) != null) {}
defer @atomicStore(bool, &audio.is_locked, false, .Release);
var buffer_padding_in_frames: w.UINT = 0;
hrPanicOnFail(audio.client.GetCurrentPadding(&buffer_padding_in_frames));
const num_frames = audio.buffer_size_in_frames - buffer_padding_in_frames;
var ptr: [*]f32 = undefined;
hrPanicOnFail(audio.render_client.GetBuffer(num_frames, @ptrCast(*?[*]w.BYTE, &ptr)));
var i: u32 = 0;
while (i < num_frames) : (i += 1) {
const frame = audio.current_frame_index;
ptr[i * 2 + 0] = @intToFloat(f32, audio.samples.items[frame * 2 + 0]) / @intToFloat(f32, 0x7fff);
ptr[i * 2 + 1] = @intToFloat(f32, audio.samples.items[frame * 2 + 1]) / @intToFloat(f32, 0x7fff);
audio.current_frame_index += 1;
if (audio.current_frame_index * 2 >= audio.samples.items.len) {
audio.current_frame_index = 0;
}
}
hrPanicOnFail(audio.render_client.ReleaseBuffer(num_frames, 0));
}
fn audioThread(ctx: ?*anyopaque) callconv(.C) w.DWORD {
const audio = @ptrCast(*AudioContex, @alignCast(8, ctx));
fillAudioBuffer(audio);
while (true) {
w.WaitForSingleObject(audio.buffer_ready_event, w.INFINITE) catch return 0;
fillAudioBuffer(audio);
}
return 0;
}
fn init(gpa_allocator: std.mem.Allocator) DemoState {
const window = common.initWindow(gpa_allocator, window_name, window_width, window_height) catch unreachable;
var grfx = zd3d12.GraphicsContext.init(gpa_allocator, window);
grfx.present_flags = 0;
grfx.present_interval = 1;
var arena_allocator_state = std.heap.ArenaAllocator.init(gpa_allocator);
defer arena_allocator_state.deinit();
const arena_allocator = arena_allocator_state.allocator();
const audio_device_enumerator = blk: {
var audio_device_enumerator: *wasapi.IMMDeviceEnumerator = undefined;
hrPanicOnFail(w.CoCreateInstance(
&wasapi.CLSID_MMDeviceEnumerator,
null,
w.CLSCTX_INPROC_SERVER,
&wasapi.IID_IMMDeviceEnumerator,
@ptrCast(*?*anyopaque, &audio_device_enumerator),
));
break :blk audio_device_enumerator;
};
defer _ = audio_device_enumerator.Release();
const audio_device = blk: {
var audio_device: *wasapi.IMMDevice = undefined;
hrPanicOnFail(audio_device_enumerator.GetDefaultAudioEndpoint(
.eRender,
.eConsole,
@ptrCast(*?*wasapi.IMMDevice, &audio_device),
));
break :blk audio_device;
};
defer _ = audio_device.Release();
const audio_client = blk: {
var audio_client: *wasapi.IAudioClient3 = undefined;
hrPanicOnFail(audio_device.Activate(
&wasapi.IID_IAudioClient3,
w.CLSCTX_INPROC_SERVER,
null,
@ptrCast(*?*anyopaque, &audio_client),
));
break :blk audio_client;
};
// Initialize audio client interafce.
{
var closest_format: ?*wasapi.WAVEFORMATEX = null;
const wanted_format = wasapi.WAVEFORMATEX{
.wFormatTag = wasapi.WAVE_FORMAT_IEEE_FLOAT,
.nChannels = 2,
.nSamplesPerSec = 48_000,
.nAvgBytesPerSec = 48_000 * 8,
.nBlockAlign = 8,
.wBitsPerSample = 32,
.cbSize = 0,
};
hrPanicOnFail(audio_client.IsFormatSupported(.SHARED, &wanted_format, &closest_format));
assert(closest_format == null);
hrPanicOnFail(audio_client.Initialize(
.SHARED,
wasapi.AUDCLNT_STREAMFLAGS_EVENTCALLBACK,
0,
0,
&wanted_format,
null,
));
}
const audio_render_client = blk: {
var audio_render_client: *wasapi.IAudioRenderClient = undefined;
hrPanicOnFail(audio_client.GetService(
&wasapi.IID_IAudioRenderClient,
@ptrCast(*?*anyopaque, &audio_render_client),
));
break :blk audio_render_client;
};
const audio_buffer_ready_event = w.CreateEventEx(
null,
"audio_buffer_ready_event",
0,
w.EVENT_ALL_ACCESS,
) catch unreachable;
hrPanicOnFail(audio_client.SetEventHandle(audio_buffer_ready_event));
var audio_buffer_size_in_frames: w.UINT = 0;
hrPanicOnFail(audio_client.GetBufferSize(&audio_buffer_size_in_frames));
const audio_samples = blk: {
hrPanicOnFail(mf.MFStartup(mf.VERSION, 0));
defer _ = mf.MFShutdown();
var config_attribs: *mf.IAttributes = undefined;
hrPanicOnFail(mf.MFCreateAttributes(&config_attribs, 1));
defer _ = config_attribs.Release();
hrPanicOnFail(config_attribs.SetUINT32(&mf.LOW_LATENCY, w.TRUE));
var source_reader: *mf.ISourceReader = undefined;
hrPanicOnFail(mf.MFCreateSourceReaderFromURL(
L(content_dir ++ "acid_walk.mp3"),
config_attribs,
&source_reader,
));
defer _ = source_reader.Release();
var media_type: *mf.IMediaType = undefined;
hrPanicOnFail(source_reader.GetNativeMediaType(mf.SOURCE_READER_FIRST_AUDIO_STREAM, 0, &media_type));
defer _ = media_type.Release();
hrPanicOnFail(media_type.SetGUID(&mf.MT_MAJOR_TYPE, &mf.MediaType_Audio));
hrPanicOnFail(media_type.SetGUID(&mf.MT_SUBTYPE, &mf.AudioFormat_PCM));
hrPanicOnFail(media_type.SetUINT32(&mf.MT_AUDIO_NUM_CHANNELS, 2));
hrPanicOnFail(media_type.SetUINT32(&mf.MT_AUDIO_BITS_PER_SAMPLE, 16));
hrPanicOnFail(media_type.SetUINT32(&mf.MT_AUDIO_SAMPLES_PER_SECOND, 48_000));
hrPanicOnFail(source_reader.SetCurrentMediaType(mf.SOURCE_READER_FIRST_AUDIO_STREAM, null, media_type));
var audio_samples = std.ArrayList(i16).init(gpa_allocator);
while (true) {
var flags: w.DWORD = 0;
var sample: ?*mf.ISample = null;
defer {
if (sample != null) {
_ = sample.?.Release();
}
}
hrPanicOnFail(source_reader.ReadSample(
mf.SOURCE_READER_FIRST_AUDIO_STREAM,
0,
null,
&flags,
null,
&sample,
));
if ((flags & mf.SOURCE_READERF_ENDOFSTREAM) != 0) {
break;
}
var buffer: *mf.IMediaBuffer = undefined;
hrPanicOnFail(sample.?.ConvertToContiguousBuffer(&buffer));
defer _ = buffer.Release();
var data_ptr: [*]i16 = undefined;
var data_len: u32 = 0;
hrPanicOnFail(buffer.Lock(@ptrCast(*[*]u8, &data_ptr), null, &data_len));
const data = data_ptr[0..@divExact(data_len, 2)];
for (data) |s| {
audio_samples.append(s) catch unreachable;
}
hrPanicOnFail(buffer.Unlock());
}
break :blk audio_samples;
};
const lines_pso = blk: {
const input_layout_desc = [_]d3d12.INPUT_ELEMENT_DESC{
d3d12.INPUT_ELEMENT_DESC.init("POSITION", 0, .R32G32_FLOAT, 0, 0, .PER_VERTEX_DATA, 0),
};
var pso_desc = d3d12.GRAPHICS_PIPELINE_STATE_DESC.initDefault();
pso_desc.InputLayout = .{
.pInputElementDescs = &input_layout_desc,
.NumElements = input_layout_desc.len,
};
pso_desc.RTVFormats[0] = .R8G8B8A8_UNORM;
pso_desc.NumRenderTargets = 1;
pso_desc.BlendState.RenderTarget[0].RenderTargetWriteMask = 0xf;
pso_desc.PrimitiveTopologyType = .LINE;
pso_desc.DepthStencilState.DepthEnable = w.FALSE;
pso_desc.RasterizerState.AntialiasedLineEnable = w.TRUE;
break :blk grfx.createGraphicsShaderPipeline(
arena_allocator,
&pso_desc,
content_dir ++ "shaders/lines.vs.cso",
content_dir ++ "shaders/lines.ps.cso",
);
};
const image_pso = blk: {
var pso_desc = d3d12.GRAPHICS_PIPELINE_STATE_DESC.initDefault();
pso_desc.RTVFormats[0] = .R8G8B8A8_UNORM;
pso_desc.NumRenderTargets = 1;
pso_desc.BlendState.RenderTarget[0].RenderTargetWriteMask = 0xf;
pso_desc.PrimitiveTopologyType = .TRIANGLE;
pso_desc.DepthStencilState.DepthEnable = w.FALSE;
break :blk grfx.createGraphicsShaderPipeline(
arena_allocator,
&pso_desc,
content_dir ++ "shaders/image.vs.cso",
content_dir ++ "shaders/image.ps.cso",
);
};
const lines_buffer = grfx.createCommittedResource(
.DEFAULT,
d3d12.HEAP_FLAG_NONE,
&d3d12.RESOURCE_DESC.initBuffer(num_vis_samples * @sizeOf(Vec2)),
d3d12.RESOURCE_STATE_COPY_DEST,
null,
) catch |err| hrPanic(err);
grfx.beginFrame();
var gui = GuiRenderer.init(arena_allocator, &grfx, 1, content_dir);
const image = grfx.createAndUploadTex2dFromFile(
content_dir ++ "genart_008b.png",
.{ .num_mip_levels = 1 },
) catch |err| hrPanic(err);
const image_srv = grfx.allocateCpuDescriptors(.CBV_SRV_UAV, 1);
grfx.device.CreateShaderResourceView(grfx.lookupResource(image).?, null, image_srv);
grfx.addTransitionBarrier(image, d3d12.RESOURCE_STATE_PIXEL_SHADER_RESOURCE);
grfx.endFrame();
grfx.finishGpuCommands();
return .{
.grfx = grfx,
.gui = gui,
.frame_stats = common.FrameStats.init(),
.audio = .{
.client = audio_client,
.render_client = audio_render_client,
.buffer_ready_event = audio_buffer_ready_event,
.buffer_size_in_frames = audio_buffer_size_in_frames,
.thread_handle = null,
.samples = audio_samples,
.current_frame_index = 0,
.is_locked = true,
},
.lines_pso = lines_pso,
.image_pso = image_pso,
.lines_buffer = lines_buffer,
.image = image,
.image_srv = image_srv,
};
}
fn deinit(demo: *DemoState, gpa_allocator: std.mem.Allocator) void {
demo.grfx.finishGpuCommands();
while (@cmpxchgWeak(bool, &demo.audio.is_locked, false, true, .Acquire, .Monotonic) != null) {}
_ = w.TerminateThread(demo.audio.thread_handle.?, 0);
w.CloseHandle(demo.audio.buffer_ready_event);
w.CloseHandle(demo.audio.thread_handle.?);
hrPanicOnFail(demo.audio.client.Stop());
_ = demo.audio.render_client.Release();
_ = demo.audio.client.Release();
demo.audio.samples.deinit();
demo.gui.deinit(&demo.grfx);
demo.grfx.deinit(gpa_allocator);
common.deinitWindow(gpa_allocator);
demo.* = undefined;
}
fn update(demo: *DemoState) void {
demo.frame_stats.update(demo.grfx.window, window_name);
common.newImGuiFrame(demo.frame_stats.delta_time);
}
fn draw(demo: *DemoState) void {
var grfx = &demo.grfx;
grfx.beginFrame();
const back_buffer = grfx.getBackBuffer();
grfx.addTransitionBarrier(back_buffer.resource_handle, d3d12.RESOURCE_STATE_RENDER_TARGET);
grfx.addTransitionBarrier(demo.lines_buffer, d3d12.RESOURCE_STATE_COPY_DEST);
grfx.flushResourceBarriers();
{
while (@cmpxchgWeak(bool, &demo.audio.is_locked, false, true, .Acquire, .Monotonic) != null) {}
defer @atomicStore(bool, &demo.audio.is_locked, false, .Release);
const frame = demo.audio.current_frame_index;
const upload = grfx.allocateUploadBufferRegion(Vec2, num_vis_samples);
for (upload.cpu_slice) |_, i| {
const y = blk: {
if ((frame + i) * 2 >= demo.audio.samples.items.len) {
break :blk 0.0;
} else {
const l = @intToFloat(f32, demo.audio.samples.items[(frame + i) * 2 + 0]) /
@intToFloat(f32, 0x7fff);
const r = @intToFloat(f32, demo.audio.samples.items[(frame + i) * 2 + 1]) /
@intToFloat(f32, 0x7fff);
break :blk (l + r) * 0.5;
}
};
const x = -1.0 + 2.0 * @intToFloat(f32, i) / @intToFloat(f32, num_vis_samples - 1);
upload.cpu_slice[i] = Vec2.init(0.95 * x, y);
}
grfx.cmdlist.CopyBufferRegion(
grfx.lookupResource(demo.lines_buffer).?,
0,
upload.buffer,
upload.buffer_offset,
upload.cpu_slice.len * @sizeOf(@TypeOf(upload.cpu_slice[0])),
);
}
grfx.addTransitionBarrier(demo.lines_buffer, d3d12.RESOURCE_STATE_VERTEX_AND_CONSTANT_BUFFER);
grfx.flushResourceBarriers();
grfx.cmdlist.OMSetRenderTargets(
1,
&[_]d3d12.CPU_DESCRIPTOR_HANDLE{back_buffer.descriptor_handle},
w.TRUE,
null,
);
grfx.cmdlist.ClearRenderTargetView(
back_buffer.descriptor_handle,
&[4]f32{ 0.0, 0.0, 0.0, 1.0 },
0,
null,
);
// Draw background image.
grfx.setCurrentPipeline(demo.image_pso);
grfx.cmdlist.IASetPrimitiveTopology(.TRIANGLELIST);
grfx.cmdlist.SetGraphicsRootDescriptorTable(0, grfx.copyDescriptorsToGpuHeap(1, demo.image_srv));
grfx.cmdlist.DrawInstanced(3, 1, 0, 0);
// Draw audio stream samples.
grfx.setCurrentPipeline(demo.lines_pso);
grfx.cmdlist.IASetPrimitiveTopology(.LINESTRIP);
grfx.cmdlist.IASetVertexBuffers(0, 1, &[_]d3d12.VERTEX_BUFFER_VIEW{.{
.BufferLocation = grfx.lookupResource(demo.lines_buffer).?.GetGPUVirtualAddress(),
.SizeInBytes = num_vis_samples * @sizeOf(Vec2),
.StrideInBytes = @sizeOf(Vec2),
}});
grfx.cmdlist.DrawInstanced(num_vis_samples, 1, 0, 0);
demo.gui.draw(grfx);
grfx.addTransitionBarrier(back_buffer.resource_handle, d3d12.RESOURCE_STATE_PRESENT);
grfx.flushResourceBarriers();
grfx.endFrame();
}
pub fn main() !void {
common.init();
defer common.deinit();
var gpa_allocator_state = std.heap.GeneralPurposeAllocator(.{}){};
defer {
const leaked = gpa_allocator_state.deinit();
assert(leaked == false);
}
const gpa_allocator = gpa_allocator_state.allocator();
var demo = init(gpa_allocator);
defer deinit(&demo, gpa_allocator);
demo.audio.thread_handle = w.kernel32.CreateThread(
null,
0,
audioThread,
@ptrCast(*anyopaque, &demo.audio),
0,
null,
).?;
hrPanicOnFail(demo.audio.client.Start());
@atomicStore(bool, &demo.audio.is_locked, false, .Release);
while (true) {
var message = std.mem.zeroes(w.user32.MSG);
const has_message = w.user32.peekMessageA(&message, null, 0, 0, w.user32.PM_REMOVE) catch false;
if (has_message) {
_ = w.user32.translateMessage(&message);
_ = w.user32.dispatchMessageA(&message);
if (message.message == w.user32.WM_QUIT) {
break;
}
} else {
update(&demo);
draw(&demo);
}
}
}
|
samples/audio_playback_test/src/audio_playback_test.zig
|
const std = @import("../std.zig");
const math = std.math;
const DefaultPrng = std.rand.DefaultPrng;
const Random = std.rand.Random;
const SplitMix64 = std.rand.SplitMix64;
const DefaultCsprng = std.rand.DefaultCsprng;
const expect = std.testing.expect;
const expectEqual = std.testing.expectEqual;
const SequentialPrng = struct {
const Self = @This();
next_value: u8,
pub fn init() Self {
return Self{
.next_value = 0,
};
}
pub fn random(self: *Self) Random {
return Random.init(self, fill);
}
pub fn fill(self: *Self, buf: []u8) void {
for (buf) |*b| {
b.* = self.next_value;
}
self.next_value +%= 1;
}
};
/// Do not use this PRNG! It is meant to be predictable, for the purposes of test reproducibility and coverage.
/// Its output is just a repeat of a user-specified byte pattern.
/// Name is a reference to this comic: https://dilbert.com/strip/2001-10-25
const Dilbert = struct {
pattern: []const u8 = undefined,
curr_idx: usize = 0,
pub fn init(pattern: []const u8) !Dilbert {
if (pattern.len == 0)
return error.EmptyPattern;
var self = Dilbert{};
self.pattern = pattern;
self.curr_idx = 0;
return self;
}
pub fn random(self: *Dilbert) Random {
return Random.init(self, fill);
}
pub fn fill(self: *Dilbert, buf: []u8) void {
for (buf) |*byte| {
byte.* = self.pattern[self.curr_idx];
self.curr_idx = (self.curr_idx + 1) % self.pattern.len;
}
}
test "Dilbert fill" {
var r = try Dilbert.init("9nine");
const seq = [_]u64{
0x396E696E65396E69,
0x6E65396E696E6539,
0x6E696E65396E696E,
0x65396E696E65396E,
0x696E65396E696E65,
};
for (seq) |s| {
var buf0: [8]u8 = undefined;
var buf1: [8]u8 = undefined;
std.mem.writeIntBig(u64, &buf0, s);
r.fill(&buf1);
try std.testing.expect(std.mem.eql(u8, buf0[0..], buf1[0..]));
}
}
};
test "Random int" {
try testRandomInt();
comptime try testRandomInt();
}
fn testRandomInt() !void {
var rng = SequentialPrng.init();
const random = rng.random();
try expect(random.int(u0) == 0);
rng.next_value = 0;
try expect(random.int(u1) == 0);
try expect(random.int(u1) == 1);
try expect(random.int(u2) == 2);
try expect(random.int(u2) == 3);
try expect(random.int(u2) == 0);
rng.next_value = 0xff;
try expect(random.int(u8) == 0xff);
rng.next_value = 0x11;
try expect(random.int(u8) == 0x11);
rng.next_value = 0xff;
try expect(random.int(u32) == 0xffffffff);
rng.next_value = 0x11;
try expect(random.int(u32) == 0x11111111);
rng.next_value = 0xff;
try expect(random.int(i32) == -1);
rng.next_value = 0x11;
try expect(random.int(i32) == 0x11111111);
rng.next_value = 0xff;
try expect(random.int(i8) == -1);
rng.next_value = 0x11;
try expect(random.int(i8) == 0x11);
rng.next_value = 0xff;
try expect(random.int(u33) == 0x1ffffffff);
rng.next_value = 0xff;
try expect(random.int(i1) == -1);
rng.next_value = 0xff;
try expect(random.int(i2) == -1);
rng.next_value = 0xff;
try expect(random.int(i33) == -1);
}
test "Random boolean" {
try testRandomBoolean();
comptime try testRandomBoolean();
}
fn testRandomBoolean() !void {
var rng = SequentialPrng.init();
const random = rng.random();
try expect(random.boolean() == false);
try expect(random.boolean() == true);
try expect(random.boolean() == false);
try expect(random.boolean() == true);
}
test "Random enum" {
try testRandomEnumValue();
comptime try testRandomEnumValue();
}
fn testRandomEnumValue() !void {
const TestEnum = enum {
First,
Second,
Third,
};
var rng = SequentialPrng.init();
const random = rng.random();
rng.next_value = 0;
try expect(random.enumValue(TestEnum) == TestEnum.First);
try expect(random.enumValue(TestEnum) == TestEnum.First);
try expect(random.enumValue(TestEnum) == TestEnum.First);
}
test "Random intLessThan" {
@setEvalBranchQuota(10000);
try testRandomIntLessThan();
comptime try testRandomIntLessThan();
}
fn testRandomIntLessThan() !void {
var rng = SequentialPrng.init();
const random = rng.random();
rng.next_value = 0xff;
try expect(random.uintLessThan(u8, 4) == 3);
try expect(rng.next_value == 0);
try expect(random.uintLessThan(u8, 4) == 0);
try expect(rng.next_value == 1);
rng.next_value = 0;
try expect(random.uintLessThan(u64, 32) == 0);
// trigger the bias rejection code path
rng.next_value = 0;
try expect(random.uintLessThan(u8, 3) == 0);
// verify we incremented twice
try expect(rng.next_value == 2);
rng.next_value = 0xff;
try expect(random.intRangeLessThan(u8, 0, 0x80) == 0x7f);
rng.next_value = 0xff;
try expect(random.intRangeLessThan(u8, 0x7f, 0xff) == 0xfe);
rng.next_value = 0xff;
try expect(random.intRangeLessThan(i8, 0, 0x40) == 0x3f);
rng.next_value = 0xff;
try expect(random.intRangeLessThan(i8, -0x40, 0x40) == 0x3f);
rng.next_value = 0xff;
try expect(random.intRangeLessThan(i8, -0x80, 0) == -1);
rng.next_value = 0xff;
try expect(random.intRangeLessThan(i3, -4, 0) == -1);
rng.next_value = 0xff;
try expect(random.intRangeLessThan(i3, -2, 2) == 1);
}
test "Random intAtMost" {
@setEvalBranchQuota(10000);
try testRandomIntAtMost();
comptime try testRandomIntAtMost();
}
fn testRandomIntAtMost() !void {
var rng = SequentialPrng.init();
const random = rng.random();
rng.next_value = 0xff;
try expect(random.uintAtMost(u8, 3) == 3);
try expect(rng.next_value == 0);
try expect(random.uintAtMost(u8, 3) == 0);
// trigger the bias rejection code path
rng.next_value = 0;
try expect(random.uintAtMost(u8, 2) == 0);
// verify we incremented twice
try expect(rng.next_value == 2);
rng.next_value = 0xff;
try expect(random.intRangeAtMost(u8, 0, 0x7f) == 0x7f);
rng.next_value = 0xff;
try expect(random.intRangeAtMost(u8, 0x7f, 0xfe) == 0xfe);
rng.next_value = 0xff;
try expect(random.intRangeAtMost(i8, 0, 0x3f) == 0x3f);
rng.next_value = 0xff;
try expect(random.intRangeAtMost(i8, -0x40, 0x3f) == 0x3f);
rng.next_value = 0xff;
try expect(random.intRangeAtMost(i8, -0x80, -1) == -1);
rng.next_value = 0xff;
try expect(random.intRangeAtMost(i3, -4, -1) == -1);
rng.next_value = 0xff;
try expect(random.intRangeAtMost(i3, -2, 1) == 1);
try expect(random.uintAtMost(u0, 0) == 0);
}
test "Random Biased" {
var prng = DefaultPrng.init(0);
const random = prng.random();
// Not thoroughly checking the logic here.
// Just want to execute all the paths with different types.
try expect(random.uintLessThanBiased(u1, 1) == 0);
try expect(random.uintLessThanBiased(u32, 10) < 10);
try expect(random.uintLessThanBiased(u64, 20) < 20);
try expect(random.uintAtMostBiased(u0, 0) == 0);
try expect(random.uintAtMostBiased(u1, 0) <= 0);
try expect(random.uintAtMostBiased(u32, 10) <= 10);
try expect(random.uintAtMostBiased(u64, 20) <= 20);
try expect(random.intRangeLessThanBiased(u1, 0, 1) == 0);
try expect(random.intRangeLessThanBiased(i1, -1, 0) == -1);
try expect(random.intRangeLessThanBiased(u32, 10, 20) >= 10);
try expect(random.intRangeLessThanBiased(i32, 10, 20) >= 10);
try expect(random.intRangeLessThanBiased(u64, 20, 40) >= 20);
try expect(random.intRangeLessThanBiased(i64, 20, 40) >= 20);
// uncomment for broken module error:
//expect(random.intRangeAtMostBiased(u0, 0, 0) == 0);
try expect(random.intRangeAtMostBiased(u1, 0, 1) >= 0);
try expect(random.intRangeAtMostBiased(i1, -1, 0) >= -1);
try expect(random.intRangeAtMostBiased(u32, 10, 20) >= 10);
try expect(random.intRangeAtMostBiased(i32, 10, 20) >= 10);
try expect(random.intRangeAtMostBiased(u64, 20, 40) >= 20);
try expect(random.intRangeAtMostBiased(i64, 20, 40) >= 20);
}
test "splitmix64 sequence" {
var r = SplitMix64.init(0xaeecf86f7878dd75);
const seq = [_]u64{
0x5dbd39db0178eb44,
0xa9900fb66b397da3,
0x5c1a28b1aeebcf5c,
0x64a963238f776912,
0xc6d4177b21d1c0ab,
0xb2cbdbdb5ea35394,
};
for (seq) |s| {
try expect(s == r.next());
}
}
// Actual Random helper function tests, pcg engine is assumed correct.
test "Random float correctness" {
var prng = DefaultPrng.init(0);
const random = prng.random();
var i: usize = 0;
while (i < 1000) : (i += 1) {
const val1 = random.float(f32);
try expect(val1 >= 0.0);
try expect(val1 < 1.0);
const val2 = random.float(f64);
try expect(val2 >= 0.0);
try expect(val2 < 1.0);
}
}
// Check the "astronomically unlikely" code paths.
test "Random float coverage" {
var prng = try Dilbert.init(&[_]u8{0});
const random = prng.random();
const rand_f64 = random.float(f64);
const rand_f32 = random.float(f32);
try expect(rand_f32 == 0.0);
try expect(rand_f64 == 0.0);
}
test "Random float chi-square goodness of fit" {
const num_numbers = 100000;
const num_buckets = 1000;
var f32_hist = std.AutoHashMap(u32, u32).init(std.testing.allocator);
defer f32_hist.deinit();
var f64_hist = std.AutoHashMap(u64, u32).init(std.testing.allocator);
defer f64_hist.deinit();
var prng = DefaultPrng.init(0);
const random = prng.random();
var i: usize = 0;
while (i < num_numbers) : (i += 1) {
const rand_f32 = random.float(f32);
const rand_f64 = random.float(f64);
var f32_put = try f32_hist.getOrPut(@floatToInt(u32, rand_f32 * @intToFloat(f32, num_buckets)));
if (f32_put.found_existing) {
f32_put.value_ptr.* += 1;
} else {
f32_put.value_ptr.* = 1;
}
var f64_put = try f64_hist.getOrPut(@floatToInt(u32, rand_f64 * @intToFloat(f64, num_buckets)));
if (f64_put.found_existing) {
f64_put.value_ptr.* += 1;
} else {
f64_put.value_ptr.* = 1;
}
}
var f32_total_variance: f64 = 0;
var f64_total_variance: f64 = 0;
{
var j: u32 = 0;
while (j < num_buckets) : (j += 1) {
const count = @intToFloat(f64, (if (f32_hist.get(j)) |v| v else 0));
const expected = @intToFloat(f64, num_numbers) / @intToFloat(f64, num_buckets);
const delta = count - expected;
const variance = (delta * delta) / expected;
f32_total_variance += variance;
}
}
{
var j: u64 = 0;
while (j < num_buckets) : (j += 1) {
const count = @intToFloat(f64, (if (f64_hist.get(j)) |v| v else 0));
const expected = @intToFloat(f64, num_numbers) / @intToFloat(f64, num_buckets);
const delta = count - expected;
const variance = (delta * delta) / expected;
f64_total_variance += variance;
}
}
// Accept p-values >= 0.05.
// Critical value is calculated by opening a Python interpreter and running:
// scipy.stats.chi2.isf(0.05, num_buckets - 1)
const critical_value = 1073.6426506574246;
try expect(f32_total_variance < critical_value);
try expect(f64_total_variance < critical_value);
}
test "Random shuffle" {
var prng = DefaultPrng.init(0);
const random = prng.random();
var seq = [_]u8{ 0, 1, 2, 3, 4 };
var seen = [_]bool{false} ** 5;
var i: usize = 0;
while (i < 1000) : (i += 1) {
random.shuffle(u8, seq[0..]);
seen[seq[0]] = true;
try expect(sumArray(seq[0..]) == 10);
}
// we should see every entry at the head at least once
for (seen) |e| {
try expect(e == true);
}
}
fn sumArray(s: []const u8) u32 {
var r: u32 = 0;
for (s) |e|
r += e;
return r;
}
test "Random range" {
var prng = DefaultPrng.init(0);
const random = prng.random();
try testRange(random, -4, 3);
try testRange(random, -4, -1);
try testRange(random, 10, 14);
try testRange(random, -0x80, 0x7f);
}
fn testRange(r: Random, start: i8, end: i8) !void {
try testRangeBias(r, start, end, true);
try testRangeBias(r, start, end, false);
}
fn testRangeBias(r: Random, start: i8, end: i8, biased: bool) !void {
const count = @intCast(usize, @as(i32, end) - @as(i32, start));
var values_buffer = [_]bool{false} ** 0x100;
const values = values_buffer[0..count];
var i: usize = 0;
while (i < count) {
const value: i32 = if (biased) r.intRangeLessThanBiased(i8, start, end) else r.intRangeLessThan(i8, start, end);
const index = @intCast(usize, value - start);
if (!values[index]) {
i += 1;
values[index] = true;
}
}
}
test "CSPRNG" {
var secret_seed: [DefaultCsprng.secret_seed_length]u8 = undefined;
std.crypto.random.bytes(&secret_seed);
var csprng = DefaultCsprng.init(secret_seed);
const random = csprng.random();
const a = random.int(u64);
const b = random.int(u64);
const c = random.int(u64);
try expect(a ^ b ^ c != 0);
}
|
lib/std/rand/test.zig
|
const std = @import("std");
const max = std.math.max;
const min = std.math.min;
const warn = std.debug.warn;
/// Fixed-length element sliding window.
/// Write to the very end.
/// Read from an offset from the end or theoretical start.
/// Older elements are removed.
/// Useful for audio processing and LZ77-style compression.
pub fn SlidingWindow(comptime Element: type, window_length: usize) type {
return struct {
const Self = @This();
elements: [window_length]Element = undefined, //[_]Element{0} ** window_length,
write_index: usize = 0,
current_window_length: usize = 0,
/// Appends an element to the end of the window.
pub fn appendElement(self: *Self, element: Element) !void {
// Add it!
self.elements[self.write_index] = element;
self.write_index = (self.write_index + 1) % window_length;
if (self.current_window_length < window_length) {
self.current_window_length += 1;
}
}
/// Given an offset from the element immediately past the end
/// of the sliding window, read the element at that point.
pub fn readElementFromEnd(self: *Self, offset: usize) !Element {
// Guard against trying to read back through the window
if (offset > self.current_window_length) {
return error.IndexOutOfRange;
}
// Also, 0 is not a valid distance
if (offset < 1) {
return error.IndexOutOfRange;
}
// We survived, so return the element
const idx = ((self.write_index + window_length) - offset) % window_length;
return self.elements[idx];
}
/// Given an offset from the element immediately past the end
/// of the sliding window, and an array to fill in, read the
/// elements from that point at that point.
///
/// Returns the number of elements actually read.
pub fn readElementsFromEnd(self: *Self, buffer: []Element, offset: usize) !usize {
// Guard against trying to read back through the window
if (offset > self.current_window_length) {
return error.IndexOutOfRange;
}
const elements_to_read = min(offset, buffer.len);
var i: usize = 0;
const beg_idx = ((self.write_index + window_length) - offset) % window_length;
const end_idx = beg_idx + elements_to_read;
// Do we need to split this into 2 copies?
if (end_idx > window_length) {
// Yes - do 2 copies.
const block_1_length = window_length - beg_idx;
const block_2_length = elements_to_read - block_1_length;
std.mem.copy(Element, buffer[0..block_1_length], self.elements[beg_idx..]);
std.mem.copy(Element, buffer[block_1_length..], self.elements[0..block_2_length]);
} else {
// No - do 1 copy.
std.mem.copy(Element, buffer, self.elements[beg_idx..end_idx]);
}
return elements_to_read;
}
/// Copies multiple elements from the end of the sliding window
/// element-by-element.
///
/// A theoretical `copy_dist` of 0 would point to reading just
/// past the last element in the sliding window, so the minimum
/// distance to be provided is 1.
///
/// If `copy_dist` is less than `copy_len` then the elements
/// are cyclically repeated. For example, if `copy_dist` is 1,
/// then this will repeat the last byte in the window `copy_len`
/// times.
pub fn copyElementsFromEnd(self: *Self, copy_dist: usize, copy_len: usize) !void {
// Guard against trying to read back through the window
if (copy_dist > self.current_window_length) {
return error.IndexOutOfRange;
}
// Also, 0 is not a valid distance
if (copy_dist < 1) {
return error.IndexOutOfRange;
}
// Copy elements
{
var i: usize = 0;
var idx = ((self.write_index + window_length) - copy_dist) % window_length;
while (i < copy_len) : (i += 1) {
self.elements[self.write_index] = self.elements[idx];
idx = (idx + 1) % window_length;
self.write_index = (self.write_index + 1) % window_length;
}
self.current_window_length = max(self.current_window_length + copy_len, window_length);
}
}
};
}
|
src/sliding_window.zig
|
usingnamespace @import("bits.zig");
pub const MMRESULT = UINT;
pub const MMSYSERR_BASE = 0;
pub const TIMERR_BASE = 96;
pub const MMSYSERR_ERROR = MMSYSERR_BASE + 1;
pub const MMSYSERR_BADDEVICEID = MMSYSERR_BASE + 2;
pub const MMSYSERR_NOTENABLED = MMSYSERR_BASE + 3;
pub const MMSYSERR_ALLOCATED = MMSYSERR_BASE + 4;
pub const MMSYSERR_INVALHANDLE = MMSYSERR_BASE + 5;
pub const MMSYSERR_NODRIVER = MMSYSERR_BASE + 6;
pub const MMSYSERR_NOMEM = MMSYSERR_BASE + 7;
pub const MMSYSERR_NOTSUPPORTED = MMSYSERR_BASE + 8;
pub const MMSYSERR_BADERRNUM = MMSYSERR_BASE + 9;
pub const MMSYSERR_INVALFLAG = MMSYSERR_BASE + 10;
pub const MMSYSERR_INVALPARAM = MMSYSERR_BASE + 11;
pub const MMSYSERR_HANDLEBUSY = MMSYSERR_BASE + 12;
pub const MMSYSERR_INVALIDALIAS = MMSYSERR_BASE + 13;
pub const MMSYSERR_BADDB = MMSYSERR_BASE + 14;
pub const MMSYSERR_KEYNOTFOUND = MMSYSERR_BASE + 15;
pub const MMSYSERR_READERROR = MMSYSERR_BASE + 16;
pub const MMSYSERR_WRITEERROR = MMSYSERR_BASE + 17;
pub const MMSYSERR_DELETEERROR = MMSYSERR_BASE + 18;
pub const MMSYSERR_VALNOTFOUND = MMSYSERR_BASE + 19;
pub const MMSYSERR_NODRIVERCB = MMSYSERR_BASE + 20;
pub const MMSYSERR_MOREDATA = MMSYSERR_BASE + 21;
pub const MMSYSERR_LASTERROR = MMSYSERR_BASE + 21;
pub const MMTIME = extern struct {
wType: UINT,
u: extern union {
ms: DWORD,
sample: DWORD,
cb: DWORD,
ticks: DWORD,
smpte: extern struct {
hour: BYTE,
min: BYTE,
sec: BYTE,
frame: BYTE,
fps: BYTE,
dummy: BYTE,
pad: [2]BYTE,
},
midi: extern struct {
songptrpos: DWORD,
},
},
};
pub const LPMMTIME = *MMTIME;
pub const TIME_MS = 0x0001;
pub const TIME_SAMPLES = 0x0002;
pub const TIME_BYTES = 0x0004;
pub const TIME_SMPTE = 0x0008;
pub const TIME_MIDI = 0x0010;
pub const TIME_TICKS = 0x0020;
// timeapi.h
pub const TIMECAPS = extern struct { wPeriodMin: UINT, wPeriodMax: UINT };
pub const LPTIMECAPS = *TIMECAPS;
pub const TIMERR_NOERROR = 0;
pub const TIMERR_NOCANDO = TIMERR_BASE + 1;
pub const TIMERR_STRUCT = TIMERR_BASE + 33;
pub extern "winmm" fn timeBeginPeriod(uPeriod: UINT) callconv(WINAPI) MMRESULT;
pub extern "winmm" fn timeEndPeriod(uPeriod: UINT) callconv(WINAPI) MMRESULT;
pub extern "winmm" fn timeGetDevCaps(ptc: LPTIMECAPS, cbtc: UINT) callconv(WINAPI) MMRESULT;
pub extern "winmm" fn timeGetSystemTime(pmmt: LPMMTIME, cbmmt: UINT) callconv(WINAPI) MMRESULT;
pub extern "winmm" fn timeGetTime() callconv(WINAPI) DWORD;
|
lib/std/os/windows/winmm.zig
|
const std = @import("std");
usingnamespace (@import("../machine.zig"));
usingnamespace (@import("../util.zig"));
// QuickRef: https://www.felixcloutier.com/x86/push
const imm = Operand.immediate;
const reg = Operand.register;
const regRm = Operand.registerRm;
const memRm = Operand.memoryRmDef;
test "push" {
const m16 = Machine.init(.x86_16);
const m32 = Machine.init(.x86_32);
const m64 = Machine.init(.x64);
debugPrint(false);
{
testOp1(m16, .PUSH, reg(.CS), "0E");
testOp1(m32, .PUSH, reg(.CS), "0E");
testOp1(m64, .PUSH, reg(.CS), AsmError.InvalidOperand);
//
testOp1(m16, .PUSH, reg(.SS), "16");
testOp1(m32, .PUSH, reg(.SS), "16");
testOp1(m64, .PUSH, reg(.SS), AsmError.InvalidOperand);
//
testOp1(m16, .PUSH, reg(.DS), "1E");
testOp1(m32, .PUSH, reg(.DS), "1E");
testOp1(m64, .PUSH, reg(.DS), AsmError.InvalidOperand);
//
testOp1(m16, .PUSH, reg(.ES), "06");
testOp1(m32, .PUSH, reg(.ES), "06");
testOp1(m64, .PUSH, reg(.ES), AsmError.InvalidOperand);
}
{
testOp1(m16, .PUSH, reg(.FS), "0F A0");
testOp1(m32, .PUSH, reg(.FS), "0F A0");
testOp1(m64, .PUSH, reg(.FS), "0F A0");
//
testOp1(m16, .PUSHW, reg(.FS), "0F A0");
testOp1(m32, .PUSHW, reg(.FS), "66 0F A0");
testOp1(m64, .PUSHW, reg(.FS), "66 0F A0");
//
testOp1(m16, .PUSHD, reg(.FS), "66 0F A0");
testOp1(m32, .PUSHD, reg(.FS), "0F A0");
testOp1(m64, .PUSHD, reg(.FS), AsmError.InvalidOperand);
//
testOp1(m16, .PUSHQ, reg(.FS), AsmError.InvalidOperand);
testOp1(m32, .PUSHQ, reg(.FS), AsmError.InvalidOperand);
testOp1(m64, .PUSHQ, reg(.FS), "0F A0");
}
{
testOp1(m16, .PUSH, reg(.GS), "0F A8");
testOp1(m32, .PUSH, reg(.GS), "0F A8");
testOp1(m64, .PUSH, reg(.GS), "0F A8");
//
testOp1(m16, .PUSHW, reg(.GS), "0F A8");
testOp1(m32, .PUSHW, reg(.GS), "66 0F A8");
testOp1(m64, .PUSHW, reg(.GS), "66 0F A8");
//
testOp1(m16, .PUSHD, reg(.GS), "66 0F A8");
testOp1(m32, .PUSHD, reg(.GS), "0F A8");
testOp1(m64, .PUSHD, reg(.GS), AsmError.InvalidOperand);
//
testOp1(m16, .PUSHQ, reg(.GS), AsmError.InvalidOperand);
testOp1(m32, .PUSHQ, reg(.GS), AsmError.InvalidOperand);
testOp1(m64, .PUSHQ, reg(.GS), "0F A8");
}
{
testOp1(m16, .PUSH, reg(.AX), "50");
testOp1(m32, .PUSH, reg(.AX), "66 50");
testOp1(m64, .PUSH, reg(.AX), "66 50");
//
testOp1(m16, .PUSH, reg(.EAX), "66 50");
testOp1(m32, .PUSH, reg(.EAX), "50");
testOp1(m64, .PUSH, reg(.EAX), AsmError.InvalidOperand);
//
testOp1(m16, .PUSH, reg(.RAX), AsmError.InvalidOperand);
testOp1(m32, .PUSH, reg(.RAX), AsmError.InvalidOperand);
testOp1(m64, .PUSH, reg(.RAX), "50");
//
testOp1(m16, .PUSH, reg(.R15), AsmError.InvalidOperand);
testOp1(m32, .PUSH, reg(.R15), AsmError.InvalidOperand);
testOp1(m64, .PUSH, reg(.R15), "41 57");
}
{
testOp1(m16, .PUSH, memRm(.WORD, .EAX, 0x11), "67 FF 70 11");
testOp1(m32, .PUSH, memRm(.WORD, .EAX, 0x11), "66 FF 70 11");
testOp1(m64, .PUSH, memRm(.WORD, .EAX, 0x11), "66 67 FF 70 11");
//
testOp1(m16, .PUSH, memRm(.DWORD, .EAX, 0x11), "66 67 FF 70 11");
testOp1(m32, .PUSH, memRm(.DWORD, .EAX, 0x11), "FF 70 11");
testOp1(m64, .PUSH, memRm(.DWORD, .EAX, 0x11), AsmError.InvalidOperand);
//
testOp1(m16, .PUSH, memRm(.QWORD, .EAX, 0x11), AsmError.InvalidOperand);
testOp1(m32, .PUSH, memRm(.QWORD, .EAX, 0x11), AsmError.InvalidOperand);
testOp1(m64, .PUSH, memRm(.QWORD, .EAX, 0x11), "67 FF 70 11");
//
testOp1(m16, .PUSH, memRm(.WORD, .RAX, 0x11), AsmError.InvalidOperand);
testOp1(m32, .PUSH, memRm(.WORD, .RAX, 0x11), AsmError.InvalidOperand);
testOp1(m64, .PUSH, memRm(.WORD, .RAX, 0x11), "66 FF 70 11");
//
testOp1(m16, .PUSH, memRm(.DWORD, .RAX, 0x11), AsmError.InvalidOperand);
testOp1(m32, .PUSH, memRm(.DWORD, .RAX, 0x11), AsmError.InvalidOperand);
testOp1(m64, .PUSH, memRm(.DWORD, .RAX, 0x11), AsmError.InvalidOperand);
//
testOp1(m16, .PUSH, memRm(.QWORD, .R15, 0x11), AsmError.InvalidOperand);
testOp1(m32, .PUSH, memRm(.QWORD, .R15, 0x11), AsmError.InvalidOperand);
testOp1(m64, .PUSH, memRm(.QWORD, .R15, 0x11), "41 FF 77 11");
}
{
testOp1(m16, .PUSH, imm(0), "6A 00");
testOp1(m32, .PUSH, imm(0), "6A 00");
testOp1(m64, .PUSH, imm(0), "6A 00");
//
testOp1(m16, .PUSH, imm(0x1100), "68 00 11");
testOp1(m32, .PUSH, imm(0x1100), "66 68 00 11");
testOp1(m64, .PUSH, imm(0x1100), "66 68 00 11");
//
testOp1(m16, .PUSH, imm(0x33221100), "66 68 00 11 22 33");
testOp1(m32, .PUSH, imm(0x33221100), "68 00 11 22 33");
testOp1(m64, .PUSH, imm(0x33221100), "68 00 11 22 33");
}
}
|
src/x86/tests/push.zig
|
const math = @import("std").math;
const c = @import("c.zig");
const vec2_zero = c.ImVec2{ .x = 0, .y = 0 };
const vec2_one = c.ImVec2{ .x = 1, .y = 1 };
const vec4_zero = c.ImVec4{ .x = 0, .y = 0, .z = 0, .w = 0 };
const vec4_one = c.ImVec4{ .x = 1, .y = 1, .z = 1, .w = 1 };
pub const Font = c.ImFont;
pub const getIO = c.igGetIO;
pub const getStyle = c.igGetStyle;
pub const getDrawData = c.igGetDrawData;
pub const showDemoWindow = c.igShowDemoWindow;
pub const showMetricsWindow = c.igShowMetricsWindow;
pub const showStackToolWindow = c.igShowStackToolWindow;
pub const showAboutWindow = c.igShowAboutWindow;
pub const showStyleEditor = c.igShowStyleEditor;
pub fn showStyleSelector(label: [:0]const u8) bool {
return c.igShowStyleSelector(label);
}
pub fn showFontSelector(label: [:0]const u8) void {
return c.igShowFontSelector(label);
}
pub const showUserGuide = c.igShowUserGuide;
pub const getVersion = c.igGetVersion;
pub const styleColorsDark = c.igStyleColorsDark;
pub const styleColorsLight = c.igStyleColorsLight;
pub const styleColorsClassic = c.igStyleColorsClassic;
// Windows
// - Begin() = push window to the stack and start appending to it. End() = pop window from the stack.
// - Passing 'bool* p_open != NULL' shows a window-closing widget in the upper-right corner of the window,
// which clicking will set the boolean to false when clicked.
// - You may append multiple times to the same window during the same frame by calling Begin()/End() pairs multiple times.
// Some information such as 'flags' or 'p_open' will only be considered by the first call to Begin().
// - Begin() return false to indicate the window is collapsed or fully clipped, so you may early out and omit submitting
// anything to the window. Always call a matching End() for each Begin() call, regardless of its return value!
// [Important: due to legacy reason, this is inconsistent with most other functions such as BeginMenu/EndMenu,
// BeginPopup/EndPopup, etc. where the EndXXX call should only be called if the corresponding BeginXXX function
// returned true. Begin and BeginChild are the only odd ones out. Will be fixed in a future update.]
// - Note that the bottom of window stack always contains a window called "Debug".
pub fn begin(name: [:0]const u8, p_open: ?*bool, flags: ?c.ImGuiWindowFlags) bool {
return c.igBegin(name, p_open, flags orelse 0);
}
pub const end = c.igEnd;
// Child Windows
// - Use child windows to begin into a self-contained independent scrolling/clipping regions within a host window. Child windows can embed their own child.
// - For each independent axis of 'size': ==0.0f: use remaining host window size / >0.0f: fixed size / <0.0f: use remaining window size minus abs(size) / Each axis can use a different mode, e.g. ImVec2(0,400).
// - BeginChild() returns false to indicate the window is collapsed or fully clipped, so you may early out and omit submitting anything to the window.
// Always call a matching EndChild() for each BeginChild() call, regardless of its return value.
// [Important: due to legacy reason, this is inconsistent with most other functions such as BeginMenu/EndMenu,
// BeginPopup/EndPopup, etc. where the EndXXX call should only be called if the corresponding BeginXXX function
// returned true. Begin and BeginChild are the only odd ones out. Will be fixed in a future update.]
pub const BeginChildOption = struct {
size: c.ImVec2 = vec2_zero,
border: bool = false,
flags: c.ImGuiWindowFlags = 0,
};
pub fn beginChild_Str(str_id: [:0]const u8, option: BeginChildOption) bool {
return c.igBeginChild_Str(str_id, option.size, option.border, option.flags);
}
pub fn beginChild_ID(id: c.ImGuiID, option: BeginChildOption) bool {
return c.igBeginChild_ID(id, option.size, option.border, option.flags);
}
pub const endChild = c.igEndChild;
// Windows Utilities
// - 'current window' = the window we are appending into while inside a Begin()/End() block. 'next window' = next window we will Begin() into.
pub const isWindowAppearing = c.igIsWindowAppearing;
pub const isWindowCollapsed = c.igIsWindowCollapsed;
pub fn isWindowFocused(flags: ?c.ImGuiFocusedFlags) bool {
return c.igIsWindowFocused(flags orelse 0);
}
pub fn isWindowHovered(flags: ?c.ImGuiHoveredFlags) bool {
return c.igIsWindowHovered(flags orelse 0);
}
pub const getWindowDrawList = c.igGetWindowDrawList;
pub fn getWindowPos(pOut: *c.ImVec2) void {
return c.igGetWindowPos(pOut);
}
pub fn getWindowSize(pOut: *c.ImVec2) void {
return c.igGetWindowSize(pOut);
}
pub const getWindowWidth = c.igGetWindowWidth;
pub const getWindowHeight = c.igGetWindowHeight;
// Window manipulation
// - Prefer using SetNextXXX functions (before Begin) rather that SetXXX functions (after Begin).
pub const SetNextWindowPosOption = struct {
cond: c.ImGuiCond = 0,
pivot: c.ImVec2 = vec2_zero,
};
pub fn setNextWindowPos(pos: c.ImVec2, option: SetNextWindowPosOption) void {
return c.igSetNextWindowPos(pos, option.cond, option.pivot);
}
pub fn setNextWindowSize(size: c.ImVec2, cond: c.ImGuiCond) void {
return c.igSetNextWindowSize(size, cond);
}
pub const SetNextWindowSizeConstraintsOption = struct {
custom_callback: c.ImGuiSizeCallback = null,
custom_callback_data: ?*anyopaque = null,
};
pub fn setNextWindowSizeConstraints(size_min: c.ImVec2, size_max: c.ImVec2, option: SetNextWindowSizeConstraintsOption) void {
return c.igSetNextWindowSizeConstraints(size_min, size_max, option.custom_callback, option.custom_callback_data);
}
pub fn setNextWindowContentSize(size: c.ImVec2) void {
return c.igSetNextWindowContentSize(size);
}
pub fn setNextWindowCollapsed(collapsed: bool, cond: c.ImGuiCond) void {
return c.igSetNextWindowCollapsed(collapsed, cond);
}
pub const setNextWindowFocus = c.igSetNextWindowFocus;
pub fn setNextWindowBgAlpha(alpha: f32) void {
return c.igSetNextWindowBgAlpha(alpha);
}
pub fn setWindowPos_Vec2(pos: c.ImVec2, cond: c.ImGuiCond) void {
return c.igSetWindowPos_Vec2(pos, cond);
}
pub fn setWindowSize_Vec2(size: c.ImVec2, cond: c.ImGuiCond) void {
return c.igSetWindowSize_Vec2(size, cond);
}
pub fn setWindowCollapsed_Bool(collapsed: bool, cond: c.ImGuiCond) void {
return c.igSetWindowCollapsed_Bool(collapsed, cond);
}
pub const setWindowFocus_Nil = c.igSetWindowFocus_Nil;
pub fn setWindowFontScale(scale: f32) void {
return c.igSetWindowFontScale(scale);
}
pub fn setWindowPos_Str(name: [:0]const u8, pos: c.ImVec2, cond: c.ImGuiCond) void {
return c.igSetWindowPos_Str(name, pos, cond);
}
pub fn setWindowSize_Str(name: [:0]const u8, size: c.ImVec2, cond: c.ImGuiCond) void {
return c.igSetWindowSize_Str(name, size, cond);
}
pub fn setWindowCollapsed_Str(name: [:0]const u8, collapsed: bool, cond: c.ImGuiCond) void {
return c.igSetWindowCollapsed_Str(name, collapsed, cond);
}
pub fn setWindowFocus_Str(name: [:0]const u8) void {
return c.igSetWindowFocus_Str(name);
}
// Content region
// - Retrieve available space from a given point. GetContentRegionAvail() is frequently useful.
// - Those functions are bound to be redesigned (they are confusing, incomplete and the Min/Max return values are in local window coordinates which increases confusion)
pub fn getContentRegionAvail(pOut: *c.ImVec2) void {
return c.igGetContentRegionAvail(pOut);
}
pub fn getContentRegionMax(pOut: *c.ImVec2) void {
return c.igGetContentRegionMax(pOut);
}
pub fn getWindowContentRegionMin(pOut: *c.ImVec2) void {
return c.igGetWindowContentRegionMin(pOut);
}
pub fn getWindowContentRegionMax(pOut: *c.ImVec2) void {
return c.igGetWindowContentRegionMax(pOut);
}
// Windows Scrolling
pub const getScrollX = c.igGetScrollX;
pub const getScrollY = c.igGetScrollY;
pub fn setScrollX_Float(scroll_x: f32) void {
return c.igSetScrollX_Float(scroll_x);
}
pub fn setScrollY_Float(scroll_y: f32) void {
return c.igSetScrollY_Float(scroll_y);
}
pub const getScrollMaxX = c.igGetScrollMaxX;
pub const getScrollMaxY = c.igGetScrollMaxY;
pub fn setScrollHereX(center_x_ratio: ?f32) void {
return c.igSetScrollHereX(center_x_ratio orelse 0.5);
}
pub fn setScrollHereY(center_y_ratio: ?f32) void {
return c.igSetScrollHereY(center_y_ratio orelse 0.5);
}
pub fn setScrollFromPosX_Float(local_x: f32, center_x_ratio: ?f32) void {
return c.igSetScrollFromPosX_Float(local_x, center_x_ratio orelse 0.5);
}
pub fn setScrollFromPosY_Float(local_y: f32, center_y_ratio: ?f32) void {
return c.igSetScrollFromPosY_Float(local_y, center_y_ratio orelse 0.5);
}
// Parameters stacks (shared)
pub fn pushFont(font: *c.ImFont) void {
return c.igPushFont(font);
}
pub const popFont = c.igPopFont;
pub fn pushStyleColor_U32(idx: c.ImGuiCol, col: c.ImU32) void {
return c.igPushStyleColor_U32(idx, col);
}
pub fn pushStyleColor_Vec4(idx: c.ImGuiCol, col: c.ImVec4) void {
return c.igPushStyleColor_Vec4(idx, col);
}
pub fn popStyleColor(count: c_int) void {
return c.igPopStyleColor(count);
}
pub fn pushStyleVar_Float(idx: c.ImGuiStyleVar, val: f32) void {
return c.igPushStyleVar_Float(idx, val);
}
pub fn pushStyleVar_Vec2(idx: c.ImGuiStyleVar, val: c.ImVec2) void {
return c.igPushStyleVar_Vec2(idx, val);
}
pub fn popStyleVar(count: c_int) void {
return c.igPopStyleVar(count);
}
pub fn pushAllowKeyboardFocus(allow_keyboard_focus: bool) void {
return c.igPushAllowKeyboardFocus(allow_keyboard_focus);
}
pub const popAllowKeyboardFocus = c.igPopAllowKeyboardFocus;
pub fn pushButtonRepeat(repeat: bool) void {
return c.igPushButtonRepeat(repeat);
}
pub const popButtonRepeat = c.igPopButtonRepeat;
// Parameters stacks (current window)
pub fn pushItemWidth(item_width: f32) void {
return c.igPushItemWidth(item_width);
}
pub const popItemWidth = c.igPopItemWidth;
pub fn setNextItemWidth(item_width: f32) void {
return c.igSetNextItemWidth(item_width);
}
pub const calcItemWidth = c.igCalcItemWidth;
pub fn pushTextWrapPos(wrap_local_pos_x: f32) void {
return c.igPushTextWrapPos(wrap_local_pos_x);
}
pub const popTextWrapPos = c.igPopTextWrapPos;
// Style read access
// - Use the style editor (ShowStyleEditor() function) to interactively see what the colors are)
pub const getFont = c.igGetFont;
pub const getFontSize = c.igGetFontSize;
pub fn getFontTexUvWhitePixel(pOut: *c.ImVec2) void {
return c.igGetFontTexUvWhitePixel(pOut);
}
pub fn getColorU32_Col(idx: c.ImGuiCol, alpha_mul: ?f32) c.ImU32 {
return c.igGetColorU32_Col(idx, alpha_mul orelse 1.0);
}
pub fn getColorU32_Vec4(col: c.ImVec4) c.ImU32 {
return c.igGetColorU32_Vec4(col);
}
pub fn getColorU32_U32(col: c.ImU32) c.ImU32 {
return c.igGetColorU32_U32(col);
}
pub fn getStyleColorVec4(idx: c.ImGuiCol) [*c]const c.ImVec4 {
return c.igGetStyleColorVec4(idx);
}
// Cursor / Layout
// - By "cursor" we mean the current output position.
// - The typical widget behavior is to output themselves at the current cursor position, then move the cursor one line down.
// - You can call SameLine() between widgets to undo the last carriage return and output at the right of the preceding widget.
// - Attention! We currently have inconsistencies between window-local and absolute positions we will aim to fix with future API:
// Window-local coordinates: SameLine(), GetCursorPos(), SetCursorPos(), GetCursorStartPos(), GetContentRegionMax(), GetWindowContentRegion*(), PushTextWrapPos()
// Absolute coordinate: GetCursorScreenPos(), SetCursorScreenPos(), all ImDrawList:: functions.
pub const separator = c.igSeparator;
pub const SameLineOption = struct {
offset_from_start_x: f32 = 0,
spacing: f32 = -1,
};
pub fn sameLine(option: SameLineOption) void {
return c.igSameLine(option.offset_from_start_x, option.spacing);
}
pub const newLine = c.igNewLine;
pub const spacing = c.igSpacing;
pub fn dummy(size: c.ImVec2) void {
return c.igDummy(size);
}
pub fn indent(indent_w: f32) void {
return c.igIndent(indent_w);
}
pub fn unindent(indent_w: f32) void {
return c.igUnindent(indent_w);
}
pub const beginGroup = c.igBeginGroup;
pub const endGroup = c.igEndGroup;
pub fn getCursorPos(pOut: *c.ImVec2) void {
return c.igGetCursorPos(pOut);
}
pub const getCursorPosX = c.igGetCursorPosX;
pub const getCursorPosY = c.igGetCursorPosY;
pub fn setCursorPos(local_pos: c.ImVec2) void {
return c.igSetCursorPos(local_pos);
}
pub fn setCursorPosX(local_x: f32) void {
return c.igSetCursorPosX(local_x);
}
pub fn setCursorPosY(local_y: f32) void {
return c.igSetCursorPosY(local_y);
}
pub fn getCursorStartPos(pOut: *c.ImVec2) void {
return c.igGetCursorStartPos(pOut);
}
pub fn getCursorScreenPos(pOut: *c.ImVec2) void {
return c.igGetCursorScreenPos(pOut);
}
pub fn setCursorScreenPos(pos: c.ImVec2) void {
return c.igSetCursorScreenPos(pos);
}
pub const alignTextToFramePadding = c.igAlignTextToFramePadding;
pub const getTextLineHeight = c.igGetTextLineHeight;
pub const getTextLineHeightWithSpacing = c.igGetTextLineHeightWithSpacing;
pub const getFrameHeight = c.igGetFrameHeight;
pub const getFrameHeightWithSpacing = c.igGetFrameHeightWithSpacing;
// ID stack/scopes
// Read the FAQ (docs/FAQ.md or http://dearimgui.org/faq) for more details about how ID are handled in dear imgui.
// - Those questions are answered and impacted by understanding of the ID stack system:
// - "Q: Why is my widget not reacting when I click on it?"
// - "Q: How can I have widgets with an empty label?"
// - "Q: How can I have multiple widgets with the same label?"
// - Short version: ID are hashes of the entire ID stack. If you are creating widgets in a loop you most likely
// want to push a unique identifier (e.g. object pointer, loop index) to uniquely differentiate them.
// - You can also use the "Label##foobar" syntax within widget label to distinguish them from each others.
// - In this header file we use the "label"/"name" terminology to denote a string that will be displayed + used as an ID,
// whereas "str_id" denote a string that is only used as an ID and not normally displayed.
pub fn pushID_Str(str_id: [:0]const u8) void {
return c.igPushID_Str(str_id);
}
pub fn pushID_Ptr(ptr_id: *const anyopaque) void {
return c.igPushID_Ptr(ptr_id);
}
pub fn pushID_Int(int_id: c_int) void {
return c.igPushID_Int(int_id);
}
pub const popID = c.igPopID;
pub fn getID_Str(str_id: [:0]const u8) c.ImGuiID {
return c.igGetID_Str(str_id);
}
pub fn getID_Ptr(ptr_id: *const anyopaque) c.ImGuiID {
return c.igGetID_Ptr(ptr_id);
}
// Widgets: Text
pub fn textUnformatted(_text: []const u8) void {
return c.igTextUnformatted(_text.ptr, _text.ptr + _text.len);
}
pub const text = c.igText;
pub const textColored = c.igTextColored;
pub const textDisabled = c.igTextDisabled;
pub const textWrapped = c.igTextWrapped;
pub const labelText = c.igLabelText;
pub const bulletText = c.igBulletText;
// Widgets: Main
// - Most widgets return true when the value has been changed or when pressed/selected
// - You may also use one of the many IsItemXXX functions (e.g. IsItemActive, IsItemHovered, etc.) to query widget state.
pub fn button(label: [:0]const u8, size: ?c.ImVec2) bool {
return c.igButton(label, size orelse vec2_zero);
}
pub fn smallButton(label: [:0]const u8) bool {
return c.igSmallButton(label);
}
pub fn invisibleButton(str_id: [:0]const u8, size: c.ImVec2, flags: ?c.ImGuiButtonFlags) bool {
return c.igInvisibleButton(str_id, size, flags orelse 0);
}
pub fn arrowButton(str_id: [:0]const u8, dir: c.ImGuiDir) bool {
return c.igArrowButton(str_id, dir);
}
pub const ImageOption = struct {
uv0: c.ImVec2 = vec2_zero,
uv1: c.ImVec2 = vec2_one,
tint_col: c.ImVec4 = vec4_one,
border_col: c.ImVec4 = vec4_zero,
};
pub fn image(user_texture_id: c.ImTextureID, size: c.ImVec2, option: ImageOption) void {
return c.igImage(user_texture_id, size, option.uv0, option.uv1, option.tint_col, option.border_col);
}
pub const ImageButtonOption = struct {
uv0: c.ImVec2 = vec2_zero,
uv1: c.ImVec2 = vec2_one,
frame_padding: c_int = -1,
bg_col: c.ImVec4 = vec4_zero,
tint_col: c.ImVec4 = vec4_one,
};
pub fn imageButton(user_texture_id: c.ImTextureID, size: c.ImVec2, option: ImageButtonOption) bool {
return c.igImageButton(user_texture_id, size, option.uv0, option.uv1, option.frame_padding, option.bg_col, option.tint_col);
}
pub fn checkbox(label: [:0]const u8, v: *bool) bool {
return c.igCheckbox(label, v);
}
pub fn checkboxFlags_IntPtr(label: [:0]const u8, flags: *c_int, flags_value: c_int) bool {
return c.igCheckboxFlags_IntPtr(label, flags, flags_value);
}
pub fn checkboxFlags_UintPtr(label: [:0]const u8, flags: [*c]c_uint, flags_value: c_uint) bool {
return c.igCheckboxFlags_UintPtr(label, flags, flags_value);
}
pub fn radioButton_Bool(label: [:0]const u8, active: bool) bool {
return c.igRadioButton_Bool(label, active);
}
pub fn radioButton_IntPtr(label: [:0]const u8, v: *c_int, v_button: c_int) bool {
return c.igRadioButton_IntPtr(label, v, v_button);
}
pub const ProgressBarOption = struct {
size_arg: c.ImVec2 = .{ .x = math.f32_min, .y = 0 },
overlay: [*c]const u8 = null,
};
pub fn progressBar(fraction: f32, option: ProgressBarOption) void {
return c.igProgressBar(fraction, option.size_arg, option.overlay);
}
pub const bullet = c.igBullet;
// Widgets: Combo Box
// - The BeginCombo()/EndCombo() api allows you to manage your contents and selection state however you want it, by creating e.g. Selectable() items.
// - The old Combo() api are helpers over BeginCombo()/EndCombo() which are kept available for convenience purpose. This is analogous to how ListBox are created.
pub fn beginCombo(label: [:0]const u8, preview_value: [:0]const u8, flags: ?c.ImGuiComboFlags) bool {
return c.igBeginCombo(label, preview_value, flags orelse 0);
}
pub const endCombo = c.igEndCombo;
pub fn combo_Str_arr(label: [:0]const u8, current_item: *c_int, items: []const [*c]const u8, popup_max_height_in_items: ?c_int) bool {
return c.igCombo_Str_arr(label, current_item, items.ptr, items.len, popup_max_height_in_items orelse -1);
}
pub fn combo_Str(label: [:0]const u8, current_item: *c_int, items_separated_by_zeros: [:0]const u8, popup_max_height_in_items: ?c_int) bool {
return c.igCombo_Str(label, current_item, items_separated_by_zeros, popup_max_height_in_items orelse -1);
}
pub fn combo_FnBoolPtr(label: [:0]const u8, current_item: *c_int, items_getter: fn (?*anyopaque, c_int, [*c][*c]const u8) callconv(.C) bool, data: ?*anyopaque, items_count: c_int, popup_max_height_in_items: ?c_int) bool {
return c.igCombo_FnBoolPtr(label, current_item, items_getter, data, items_count, popup_max_height_in_items orelse -1);
}
// Widgets: Drag Sliders
// - CTRL+Click on any drag box to turn them into an input box. Manually input values aren't clamped by default and can go off-bounds. Use ImGuiSliderFlags_AlwaysClamp to always clamp.
// - For all the Float2/Float3/Float4/Int2/Int3/Int4 versions of every functions, note that a 'float v[X]' function argument is the same as 'float* v', the array syntax is just a way to document the number of elements that are expected to be accessible. You can pass address of your first element out of a contiguous set, e.g. &myvector.x
// - Adjust format string to decorate the value with a prefix, a suffix, or adapt the editing and display precision e.g. "%.3f" -> 1.234; "%5.2f secs" -> 01.23 secs; "Biscuit: %.0f" -> Biscuit: 1; etc.
// - Format string may also be set to NULL or use the default format ("%f" or "%d").
// - Speed are per-pixel of mouse movement (v_speed=0.2f: mouse needs to move by 5 pixels to increase value by 1). For gamepad/keyboard navigation, minimum speed is Max(v_speed, minimum_step_at_given_precision).
// - Use v_min < v_max to clamp edits to given limits. Note that CTRL+Click manual input can override those limits if ImGuiSliderFlags_AlwaysClamp is not used.
// - Use v_max = FLT_MAX / INT_MAX etc to avoid clamping to a maximum, same with v_min = -FLT_MAX / INT_MIN to avoid clamping to a minimum.
// - We use the same sets of flags for DragXXX() and SliderXXX() functions as the features are the same and it makes it easier to swap them.
// - Legacy: Pre-1.78 there are DragXXX() function signatures that takes a final `float power=1.0f' argument instead of the `ImGuiSliderFlags flags=0' argument.
// If you get a warning converting a float to ImGuiSliderFlags, read https://github.com/ocornut/imgui/issues/3361
pub const DragFloatOption = struct {
v_speed: f32 = 1,
v_min: f32 = 0,
v_max: f32 = 0,
format: [:0]const u8 = "%.3f",
flags: c.ImGuiSliderFlags = 0,
};
pub fn dragFloat(label: [:0]const u8, v: *f32, option: DragFloatOption) bool {
return c.igDragFloat(label, v, option.v_speed, option.v_min, option.v_max, option.format, option.flags);
}
pub fn dragFloat2(label: [:0]const u8, v: *[2]f32, option: DragFloatOption) bool {
return c.igDragFloat2(label, v, option.v_speed, option.v_min, option.v_max, option.format, option.flags);
}
pub fn dragFloat3(label: [:0]const u8, v: *[3]f32, option: DragFloatOption) bool {
return c.igDragFloat3(label, v, option.v_speed, option.v_min, option.v_max, option.format, option.flags);
}
pub fn dragFloat4(label: [:0]const u8, v: *[4]f32, option: DragFloatOption) bool {
return c.igDragFloat4(label, v, option.v_speed, option.v_min, option.v_max, option.format, option.flags);
}
pub const DragFloatRangeOption = struct {
v_speed: f32 = 1,
v_min: f32 = 0,
v_max: f32 = 0,
format: [:0]const u8 = "%.3f",
format_max: [*c]const u8 = null,
flags: c.ImGuiSliderFlags = 0,
};
pub fn dragFloatRange2(label: [:0]const u8, v_current_min: *f32, v_current_max: *f32, option: DragFloatRangeOption) bool {
return c.igDragFloatRange2(label, v_current_min, v_current_max, option.v_speed, option.v_min, option.v_max, option.format, option.format_max, option.flags);
}
pub const DragIntOption = struct {
v_speed: f32 = 1,
v_min: c_int = 0,
v_max: c_int = 0,
format: [:0]const u8 = "%d",
flags: c.ImGuiSliderFlags = 0,
};
pub fn dragInt(label: [:0]const u8, v: *c_int, option: DragIntOption) bool {
return c.igDragInt(label, v, option.v_speed, option.v_min, option.v_max, option.format, option.flags);
}
pub fn dragInt2(label: [:0]const u8, v: *c_int, option: DragIntOption) bool {
return c.igDragInt2(label, v, option.v_speed, option.v_min, option.v_max, option.format, option.flags);
}
pub fn dragInt3(label: [:0]const u8, v: *c_int, option: DragIntOption) bool {
return c.igDragInt3(label, v, option.v_speed, option.v_min, option.v_max, option.format, option.flags);
}
pub fn dragInt4(label: [:0]const u8, v: *c_int, option: DragIntOption) bool {
return c.igDragInt4(label, v, option.v_speed, option.v_min, option.v_max, option.format, option.flags);
}
pub const DragIntRangeOption = struct {
v_speed: f32 = 1,
v_min: c_int = 0,
v_max: c_int = 0,
format: [:0]const u8 = "%d",
format_max: [*c]const u8 = null,
flags: c.ImGuiSliderFlags = 0,
};
pub fn dragIntRange2(label: [:0]const u8, v_current_min: *c_int, v_current_max: *c_int, option: DragIntRangeOption) bool {
return c.igDragIntRange2(label, v_current_min, v_current_max, option.v_speed, option.v_min, option.v_max, option.format, option.format_max, option.flags);
}
pub const DragScalarOption = struct {
v_speed: f32 = 1,
p_min: ?*const anyopaque = null,
p_max: ?*const anyopaque = null,
format: ?[:0]const u8 = null,
flags: c.ImGuiSliderFlags = 0,
};
pub fn dragScalar(label: [:0]const u8, data_type: c.ImGuiDataType, p_data: *anyopaque, option: DragScalarOption) bool {
return c.igDragScalar(label, data_type, p_data, option.v_speed, option.p_min, option.p_max, option.format, option.flags);
}
pub fn dragScalarN(label: [:0]const u8, data_type: c.ImGuiDataType, p_data: *anyopaque, components: c_int, option: DragScalarOption) bool {
return c.igDragScalarN(label, data_type, p_data, components, option.v_speed, option.p_min, option.p_max, option.format, option.flags);
}
// Widgets: Regular Sliders
// - CTRL+Click on any slider to turn them into an input box. Manually input values aren't clamped by default and can go off-bounds. Use ImGuiSliderFlags_AlwaysClamp to always clamp.
// - Adjust format string to decorate the value with a prefix, a suffix, or adapt the editing and display precision e.g. "%.3f" -> 1.234; "%5.2f secs" -> 01.23 secs; "Biscuit: %.0f" -> Biscuit: 1; etc.
// - Format string may also be set to NULL or use the default format ("%f" or "%d").
// - Legacy: Pre-1.78 there are SliderXXX() function signatures that takes a final `float power=1.0f' argument instead of the `ImGuiSliderFlags flags=0' argument.
// If you get a warning converting a float to ImGuiSliderFlags, read https://github.com/ocornut/imgui/issues/3361
pub const SliderFloatOption = struct {
format: [:0]const u8 = "%.3f",
flags: c.ImGuiSliderFlags = 0,
};
pub fn sliderFloat(label: [:0]const u8, v: *f32, v_min: f32, v_max: f32, option: SliderFloatOption) bool {
return c.igSliderFloat(label, v, v_min, v_max, option.format, option.flags);
}
pub fn sliderFloat2(label: [:0]const u8, v: *[2]f32, v_min: f32, v_max: f32, option: SliderFloatOption) bool {
return c.igSliderFloat2(label, v, v_min, v_max, option.format, option.flags);
}
pub fn sliderFloat3(label: [:0]const u8, v: *[2]f32, v_min: f32, v_max: f32, option: SliderFloatOption) bool {
return c.igSliderFloat3(label, v, v_min, v_max, option.format, option.flags);
}
pub fn sliderFloat4(label: [:0]const u8, v: *[3]f32, v_min: f32, v_max: f32, option: SliderFloatOption) bool {
return c.igSliderFloat4(label, v, v_min, v_max, option.format, option.flags);
}
pub const SliderAngleOption = struct {
v_degrees_min: f32 = -360.0,
v_degrees_max: f32 = 360.0,
format: [:0]const u8 = "%.0 deg",
flags: c.ImGuiSliderFlags = 0,
};
pub fn sliderAngle(label: [:0]const u8, v_rad: *f32, option: SliderAngleOption) bool {
return c.igSliderAngle(label, v_rad, option.v_degrees_min, option.v_degrees_max, option.format, option.flags);
}
pub const SliderIntOption = struct {
format: [:0]const u8 = "%d",
flags: c.ImGuiSliderFlags = 0,
};
pub fn sliderInt(label: [:0]const u8, v: *c_int, v_min: c_int, v_max: c_int, option: SliderIntOption) bool {
return c.igSliderInt(label, v, v_min, v_max, option.format, option.flags);
}
pub fn sliderInt2(label: [:0]const u8, v: *c_int, v_min: c_int, v_max: c_int, option: SliderIntOption) bool {
return c.igSliderInt2(label, v, v_min, v_max, option.format, option.flags);
}
pub fn sliderInt3(label: [:0]const u8, v: *c_int, v_min: c_int, v_max: c_int, option: SliderIntOption) bool {
return c.igSliderInt3(label, v, v_min, v_max, option.format, option.flags);
}
pub fn sliderInt4(label: [:0]const u8, v: *c_int, v_min: c_int, v_max: c_int, option: SliderIntOption) bool {
return c.igSliderInt4(label, v, v_min, v_max, option.format, option.flags);
}
pub const SliderScalarOption = struct {
format: ?[:0]const u8 = null,
flags: c.ImGuiSliderFlags = 0,
};
pub fn sliderScalar(label: [:0]const u8, data_type: c.ImGuiDataType, p_data: *anyopaque, p_min: *const anyopaque, p_max: *const anyopaque, option: SliderScalarOption) bool {
return c.igSliderScalar(label, data_type, p_data, p_min, p_max, option.format, option.flags);
}
pub fn sliderScalarN(label: [:0]const u8, data_type: c.ImGuiDataType, p_data: *anyopaque, components: c_int, p_min: *const anyopaque, p_max: *const anyopaque, option: SliderScalarOption) bool {
return c.igSliderScalarN(label, data_type, p_data, components, p_min, p_max, option.format, option.flags);
}
pub const VSliderFloatOption = struct {
format: [:0]const u8 = "%.3f",
flags: c.ImGuiSliderFlags = 0,
};
pub fn vSliderFloat(label: [:0]const u8, size: c.ImVec2, v: *f32, v_min: f32, v_max: f32, option: VSliderFloatOption) bool {
return c.igVSliderFloat(label, size, v, v_min, v_max, option.format, option.flags);
}
pub const VSliderIntOption = struct {
format: [:0]const u8 = "%d",
flags: c.ImGuiSliderFlags = 0,
};
pub fn vSliderInt(label: [:0]const u8, size: c.ImVec2, v: *c_int, v_min: c_int, v_max: c_int, option: VSliderIntOption) bool {
return c.igVSliderInt(label, size, v, v_min, v_max, option.format, option.flags);
}
pub const VSliderScalarOption = struct {
format: ?[:0]const u8 = null,
flags: c.ImGuiSliderFlags = 0,
};
pub fn vSliderScalar(label: [:0]const u8, size: c.ImVec2, data_type: c.ImGuiDataType, p_data: *anyopaque, p_min: *const anyopaque, p_max: *const anyopaque, option: VSliderScalarOption) bool {
return c.igVSliderScalar(label, size, data_type, p_data, p_min, p_max, option.format, option.flags);
}
// Widgets: Input with Keyboard
// - If you want to use InputText() with std::string or any custom dynamic string type, see misc/cpp/imgui_stdlib.h and comments in imgui_demo.cpp.
// - Most of the ImGuiInputTextFlags flags are only useful for InputText() and not for InputFloatX, InputIntX, InputDouble etc.
pub const InputTextOption = struct {
flags: c.ImGuiInputTextFlags = 0,
callback: c.ImGuiInputTextCallback = null,
user_data: ?*anyopaque = null,
};
pub fn inputText(label: [:0]const u8, buf: []u8, option: InputTextOption) bool {
return c.igInputText(label, buf.ptr, buf.len, option.flags, option.callback, option.user_data);
}
pub const InputTextMultilineOption = struct {
size: c.ImVec2 = vec2_zero,
flags: c.ImGuiInputTextFlags = 0,
callback: c.ImGuiInputTextCallback = null,
user_data: ?*anyopaque = null,
};
pub fn inputTextMultiline(label: [:0]const u8, buf: []u8, option: InputTextMultilineOption) bool {
return c.igInputTextMultiline(label, buf.ptr, buf.len, option.size, option.flags, option.callback, option.user_data);
}
pub fn inputTextWithHint(label: [:0]const u8, hint: [:0]const u8, buf: []u8, option: InputTextOption) bool {
return c.igInputTextWithHint(label, hint, buf.ptr, buf.len, option.flags, option.callback, option.user_data);
}
pub const InputFloatOption = struct {
step: f32 = 0,
step_fast: f32 = 0,
format: [:0]const u8 = "%.3f",
flags: c.ImGuiInputTextFlags = 0,
};
pub fn inputFloat(label: [:0]const u8, v: *f32, option: InputFloatOption) bool {
return c.igInputFloat(label, v, option.step, option.step_fast, option.format, option.flags);
}
pub const InputFloatsOption = struct {
format: [:0]const u8 = "%.3f",
flags: c.ImGuiInputTextFlags = 0,
};
pub fn inputFloat2(label: [:0]const u8, v: *[2]f32, option: InputFloatsOption) bool {
return c.igInputFloat2(label, v, option.format, option.flags);
}
pub fn inputFloat3(label: [:0]const u8, v: *[3]f32, option: InputFloatsOption) bool {
return c.igInputFloat3(label, v, option.format, option.flags);
}
pub fn inputFloat4(label: [:0]const u8, v: *[4]f32, option: InputFloatsOption) bool {
return c.igInputFloat4(label, v, option.format, option.flags);
}
pub const InputIntOption = struct {
step: c_int = 1,
step_fast: c_int = 100,
flags: c.ImGuiInputTextFlags = 0,
};
pub fn inputInt(label: [:0]const u8, v: *c_int, option: InputIntOption) bool {
return c.igInputInt(label, v, option.step, option.step_fast, option.flags);
}
pub fn inputInt2(label: [:0]const u8, v: *[2]c_int, flags: ?c.ImGuiInputTextFlags) bool {
return c.igInputInt2(label, v, flags orelse 0);
}
pub fn inputInt3(label: [:0]const u8, v: *[3]c_int, flags: ?c.ImGuiInputTextFlags) bool {
return c.igInputInt3(label, v, flags orelse 0);
}
pub fn inputInt4(label: [:0]const u8, v: *[4]c_int, flags: ?c.ImGuiInputTextFlags) bool {
return c.igInputInt4(label, v, flags orelse 0);
}
pub const InputDoubleOption = struct {
step: f64 = 0,
step_fast: f64 = 0,
format: [:0]const u8 = "%.6f",
flags: c.ImGuiInputTextFlags = 0,
};
pub fn inputDouble(label: [:0]const u8, v: *f64, option: InputDoubleOption) bool {
return c.igInputDouble(label, v, option.step, option.step_fast, option.format, option.flags);
}
pub const InputScalarOption = struct {
p_step: ?*const anyopaque = null,
p_step_fast: ?*const anyopaque = null,
format: ?[:0]const u8 = null,
flags: c.ImGuiInputTextFlags = 0,
};
pub fn inputScalar(label: [:0]const u8, data_type: c.ImGuiDataType, p_data: *anyopaque, option: InputScalarOption) bool {
return c.igInputScalar(label, data_type, p_data, option.p_step, option.p_step_fast, option.format, option.flags);
}
pub fn inputScalarN(label: [:0]const u8, data_type: c.ImGuiDataType, p_data: *anyopaque, components: c_int, option: InputScalarOption) bool {
return c.igInputScalarN(label, data_type, p_data, components, option.p_step, option.p_step_fast, option.format, option.flags);
}
// Widgets: Color Editor/Picker (tip: the ColorEdit* functions have a little color square that can be left-clicked to open a picker, and right-clicked to open an option menu.)
// - Note that in C++ a 'float v[X]' function argument is the _same_ as 'float* v', the array syntax is just a way to document the number of elements that are expected to be accessible.
// - You can pass the address of a first float element out of a contiguous structure, e.g. &myvector.x
pub fn colorEdit3(label: [:0]const u8, col: *[3]f32, flags: ?c.ImGuiColorEditFlags) bool {
return c.igColorEdit3(label, col, flags orelse 0);
}
pub fn colorEdit4(label: [:0]const u8, col: *[4]f32, flags: ?c.ImGuiColorEditFlags) bool {
return c.igColorEdit4(label, col, flags orelse 0);
}
pub fn colorPicker3(label: [:0]const u8, col: *[3]f32, flags: ?c.ImGuiColorEditFlags) bool {
return c.igColorPicker3(label, col, flags orelse 0);
}
pub fn colorPicker4(label: [:0]const u8, col: *[4]f32, flags: ?c.ImGuiColorEditFlags, ref_col: ?*[4]f32) bool {
return c.igColorPicker4(label, col, flags orelse 0, ref_col);
}
pub const ColorButtonOption = struct {
flags: c.ImGuiColorEditFlags = 0,
size: c.ImVec2 = vec2_zero,
};
pub fn colorButton(desc_id: [:0]const u8, col: c.ImVec4, option: ColorButtonOption) bool {
return c.igColorButton(desc_id, col, option.flags, option.size);
}
pub fn setColorEditOptions(flags: c.ImGuiColorEditFlags) void {
return c.igSetColorEditOptions(flags);
}
// Widgets: Trees
// - TreeNode functions return true when the node is open, in which case you need to also call TreePop() when you are finished displaying the tree node contents.
pub fn treeNode_Str(label: [:0]const u8) bool {
return c.igTreeNode_Str(label);
}
pub const treeNode_StrStr = c.igTreeNode_StrStr;
pub const treeNode_Ptr = c.igTreeNode_Ptr;
pub const treeNodeEx_Str = c.igTreeNodeEx_Str;
pub const treeNodeEx_StrStr = c.igTreeNodeEx_StrStr;
pub const treeNodeEx_Ptr = c.igTreeNodeEx_Ptr;
pub fn treePush_Str(str_id: [:0]const u8) void {
return c.igTreePush_Str(str_id);
}
pub fn treePush_Ptr(ptr_id: *const anyopaque) void {
return c.igTreePush_Ptr(ptr_id);
}
pub const treePop = c.igTreePop;
pub const getTreeNodeToLabelSpacing = c.igGetTreeNodeToLabelSpacing;
pub fn collapsingHeader_TreeNodeFlags(label: [:0]const u8, flags: ?c.ImGuiTreeNodeFlags) bool {
return c.igCollapsingHeader_TreeNodeFlags(label, flags orelse 0);
}
pub fn collapsingHeader_BoolPtr(label: [:0]const u8, p_visible: *bool, flags: ?c.ImGuiTreeNodeFlags) bool {
return c.igCollapsingHeader_BoolPtr(label, p_visible, flags orelse 0);
}
pub fn setNextItemOpen(is_open: bool, cond: ?c.ImGuiCond) void {
return c.igSetNextItemOpen(is_open, cond orelse 0);
}
// Widgets: Selectables
// - A selectable highlights when hovered, and can display another color when selected.
// - Neighbors selectable extend their highlight bounds in order to leave no gap between them. This is so a series of selected Selectable appear contiguous.
pub const SelectableOption = struct {
selected: bool = false,
flags: c.ImGuiSelectableFlags = 0,
size: c.ImVec2 = vec2_zero,
};
pub fn selectable_Bool(label: [:0]const u8, option: SelectableOption) bool {
return c.igSelectable_Bool(label, option.selected, option.flags, option.size);
}
pub const SelectablePtrOption = struct {
flags: c.ImGuiSelectableFlags,
size: c.ImVec2,
};
pub fn selectable_BoolPtr(label: [:0]const u8, p_selected: *bool, option: SelectablePtrOption) bool {
return c.igSelectable_BoolPtr(label, p_selected, option.flags, option.size);
}
// Widgets: List Boxes
// - This is essentially a thin wrapper to using BeginChild/EndChild with some stylistic changes.
// - The BeginListBox()/EndListBox() api allows you to manage your contents and selection state however you want it, by creating e.g. Selectable() or any items.
// - The simplified/old ListBox() api are helpers over BeginListBox()/EndListBox() which are kept available for convenience purpose. This is analoguous to how Combos are created.
// - Choose frame width: size.x > 0.0f: custom / size.x < 0.0f or -FLT_MIN: right-align / size.x = 0.0f (default): use current ItemWidth
// - Choose frame height: size.y > 0.0f: custom / size.y < 0.0f or -FLT_MIN: bottom-align / size.y = 0.0f (default): arbitrary default height which can fit ~7 items
pub fn beginListBox(label: [:0]const u8, size: ?c.ImVec2) bool {
return c.igBeginListBox(label, size orelse vec2_zero);
}
pub const endListBox = c.igEndListBox;
pub fn listBox_Str_arr(label: [:0]const u8, current_item: *c_int, items: []const [*c]const u8, height_in_items: ?c_int) bool {
return c.igListBox_Str_arr(label, current_item, items.ptr, @intCast(c_int, items.len), height_in_items orelse -1);
}
pub fn listBox_FnBoolPtr(label: [:0]const u8, current_item: *c_int, items_getter: fn (?*anyopaque, c_int, [*c][*c]const u8) callconv(.C) bool, data: ?*anyopaque, items_count: c_int, height_in_items: ?c_int) bool {
return c.igListBox_FnBoolPtr(label, current_item, items_getter, data, items_count, height_in_items orelse -1);
}
// Widgets: Data Plotting
// - Consider using ImPlot (https://github.com/epezent/implot) which is much better!
var PlotOption = struct {
values_offset: c_int = 0,
overlay_text: ?[:0]const u8 = null,
scale_min: f32 = math.f32_min,
scale_max: f32 = math.f32_max,
graph_size: c.ImVec2 = vec2_zero,
stride: c_int = @sizeOf(f32),
};
pub fn plotLines_FloatPtr(label: [:0]const u8, values: []const f32, option: PlotOption) void {
return c.igPlotLines_FloatPtr(label, values.ptr, @intCast(c_int, values.len), option.values_offset, option.overlay_text, option.scale_min, option.scale_max, option.graph_size, option.stride);
}
pub fn plotLines_FnFloatPtr(label: [:0]const u8, values_getter: fn (?*anyopaque, c_int) callconv(.C) f32, data: ?*anyopaque, values_count: c_int, option: PlotOption) void {
return c.igPlotLines_FnFloatPtr(label, values_getter, data, values_count, option.values_offset, option.overlay_text, option.scale_min, option.scale_max, option.graph_size);
}
pub fn plotHistogram_FloatPtr(label: [:0]const u8, values: []const f32, option: PlotOption) void {
return c.igPlotHistogram_FloatPtr(label, values.ptr, @intCast(c_int, values.len), option.values_offset, option.overlay_text, option.scale_min, option.scale_max, option.graph_size, option.stride);
}
pub fn plotHistogram_FnFloatPtr(label: [:0]const u8, values_getter: fn (?*anyopaque, c_int) callconv(.C) f32, data: ?*anyopaque, values_count: c_int, option: PlotOption) void {
return c.igPlotHistogram_FnFloatPtr(label, values_getter, data, values_count, option.values_offset, option.overlay_text, option.scale_min, option.scale_max, option.graph_size);
}
// Widgets: Value() Helpers.
// - Those are merely shortcut to calling Text() with a format string. Output single value in "name: value" format (tip: freely declare more in your code to handle your types. you can add functions to the ImGui namespace)
pub fn value_Bool(prefix: [*c]const u8, b: bool) void {
return c.igValue_Bool(prefix, b);
}
pub fn value_Int(prefix: [*c]const u8, v: c_int) void {
return c.igValue_Int(prefix, v);
}
pub fn value_Uint(prefix: [*c]const u8, v: c_uint) void {
return c.igValue_Uint(prefix, v);
}
pub fn value_Float(prefix: [*c]const u8, v: f32, float_format: ?[:0]const u8) void {
return c.igValue_Float(prefix, v, float_format);
}
// Widgets: Menus
// - Use BeginMenuBar() on a window ImGuiWindowFlags_MenuBar to append to its menu bar.
// - Use BeginMainMenuBar() to create a menu bar at the top of the screen and append to it.
// - Use BeginMenu() to create a menu. You can call BeginMenu() multiple time with the same identifier to append more items to it.
// - Not that MenuItem() keyboardshortcuts are displayed as a convenience but _not processed_ by Dear ImGui at the moment.
pub const beginMenuBar = c.igBeginMenuBar;
pub const endMenuBar = c.igEndMenuBar;
pub const beginMainMenuBar = c.igBeginMainMenuBar;
pub const endMainMenuBar = c.igEndMainMenuBar;
pub fn beginMenu(label: [:0]const u8, enabled: ?bool) bool {
return c.igBeginMenu(label, enabled orelse true);
}
pub const endMenu = c.igEndMenu;
pub const MenuItemOption = struct {
shortcut: ?[:0]const u8 = null,
selected: bool = false,
enabled: bool = true,
};
pub fn menuItem_Bool(label: [:0]const u8, option: MenuItemOption) bool {
return c.igMenuItem_Bool(label, option.shortcut, option.selected, option.enabled);
}
pub fn menuItem_BoolPtr(label: [:0]const u8, shortcut: [*c]const u8, p_selected: *bool, enabled: ?bool) bool {
return c.igMenuItem_BoolPtr(label, shortcut, p_selected, enabled orelse true);
}
// Tooltips
// - Tooltip are windows following the mouse. They do not take focus away.
pub const beginTooltip = c.igBeginTooltip;
pub const endTooltip = c.igEndTooltip;
pub const setTooltip = c.igSetTooltip;
// Popups, Modals
// - They block normal mouse hovering detection (and therefore most mouse interactions) behind them.
// - If not modal: they can be closed by clicking anywhere outside them, or by pressing ESCAPE.
// - Their visibility state (~bool) is held internally instead of being held by the programmer as we are used to with regular Begin*() calls.
// - The 3 properties above are related: we need to retain popup visibility state in the library because popups may be closed as any time.
// - You can bypass the hovering restriction by using ImGuiHoveredFlags_AllowWhenBlockedByPopup when calling IsItemHovered() or IsWindowHovered().
// - IMPORTANT: Popup identifiers are relative to the current ID stack, so OpenPopup and BeginPopup generally needs to be at the same level of the stack.
// This is sometimes leading to confusing mistakes. May rework this in the future.
// Popups: begin/end functions
// - BeginPopup(): query popup state, if open start appending into the window. Call EndPopup() afterwards. ImGuiWindowFlags are forwarded to the window.
// - BeginPopupModal(): block every interactions behind the window, cannot be closed by user, add a dimming background, has a title bar.
pub fn beginPopup(str_id: [:0]const u8, flags: ?c.ImGuiWindowFlags) bool {
return c.igBeginPopup(str_id, flags orelse 0);
}
pub fn beginPopupModal(name: [:0]const u8, p_open: ?*bool, flags: ?c.ImGuiWindowFlags) bool {
return c.igBeginPopupModal(name, p_open, flags orelse 0);
}
pub const endPopup = c.igEndPopup;
// Popups: open/close functions
// - OpenPopup(): set popup state to open. ImGuiPopupFlags are available for opening options.
// - If not modal: they can be closed by clicking anywhere outside them, or by pressing ESCAPE.
// - CloseCurrentPopup(): use inside the BeginPopup()/EndPopup() scope to close manually.
// - CloseCurrentPopup() is called by default by Selectable()/MenuItem() when activated (FIXME: need some options).
// - Use ImGuiPopupFlags_NoOpenOverExistingPopup to avoid opening a popup if there's already one at the same level. This is equivalent to e.g. testing for !IsAnyPopupOpen() prior to OpenPopup().
// - Use IsWindowAppearing() after BeginPopup() to tell if a window just opened.
pub fn openPopup_Str(str_id: [:0]const u8, popup_flags: ?c.ImGuiPopupFlags) void {
return c.igOpenPopup_Str(str_id, popup_flags orelse 0);
}
pub fn openPopup_ID(id: c.ImGuiID, popup_flags: ?c.ImGuiPopupFlags) void {
return c.igOpenPopup_ID(id, popup_flags orelse 0);
}
pub fn openPopupOnItemClick(str_id: ?[:0]const u8, popup_flags: ?c.ImGuiPopupFlags) void {
return c.igOpenPopupOnItemClick(str_id, popup_flags orelse 1);
}
pub const closeCurrentPopup = c.igCloseCurrentPopup;
// Popups: open+begin combined functions helpers
// - Helpers to do OpenPopup+BeginPopup where the Open action is triggered by e.g. hovering an item and right-clicking.
// - They are convenient to easily create context menus, hence the name.
// - IMPORTANT: Notice that BeginPopupContextXXX takes ImGuiPopupFlags just like OpenPopup() and unlike BeginPopup(). For full consistency, we may add ImGuiWindowFlags to the BeginPopupContextXXX functions in the future.
// - IMPORTANT: we exceptionally default their flags to 1 (== ImGuiPopupFlags_MouseButtonRight) for backward compatibility with older API taking 'int mouse_button = 1' parameter, so if you add other flags remember to re-add the ImGuiPopupFlags_MouseButtonRight.
pub fn beginPopupContextItem(str_id: ?[:0]const u8, popup_flags: ?c.ImGuiPopupFlags) bool {
return c.igBeginPopupContextItem(str_id, popup_flags orelse 0);
}
pub fn beginPopupContextWindow(str_id: ?[:0]const u8, popup_flags: ?c.ImGuiPopupFlags) bool {
return c.igBeginPopupContextWindow(str_id, popup_flags orelse 0);
}
pub fn beginPopupContextVoid(str_id: ?[:0]const u8, popup_flags: ?c.ImGuiPopupFlags) bool {
return c.igBeginPopupContextVoid(str_id, popup_flags orelse 0);
}
// Popups: query functions
// - IsPopupOpen(): return true if the popup is open at the current BeginPopup() level of the popup stack.
// - IsPopupOpen() with ImGuiPopupFlags_AnyPopupId: return true if any popup is open at the current BeginPopup() level of the popup stack.
// - IsPopupOpen() with ImGuiPopupFlags_AnyPopupId + ImGuiPopupFlags_AnyPopupLevel: return true if any popup is open.
pub fn isPopupOpen_Str(str_id: [:0]const u8, flags: ?c.ImGuiPopupFlags) bool {
return c.igIsPopupOpen_Str(str_id, flags orelse 0);
}
// Tables
// [BETA API] API may evolve slightly! If you use this, please update to the next version when it comes out!
// - Full-featured replacement for old Columns API.
// - See Demo->Tables for demo code.
// - See top of imgui_tables.cpp for general commentary.
// - See ImGuiTableFlags_ and ImGuiTableColumnFlags_ enums for a description of available flags.
// The typical call flow is:
// - 1. Call BeginTable().
// - 2. Optionally call TableSetupColumn() to submit column name/flags/defaults.
// - 3. Optionally call TableSetupScrollFreeze() to request scroll freezing of columns/rows.
// - 4. Optionally call TableHeadersRow() to submit a header row. Names are pulled from TableSetupColumn() data.
// - 5. Populate contents:
// - In most situations you can use TableNextRow() + TableSetColumnIndex(N) to start appending into a column.
// - If you are using tables as a sort of grid, where every columns is holding the same type of contents,
// you may prefer using TableNextColumn() instead of TableNextRow() + TableSetColumnIndex().
// TableNextColumn() will automatically wrap-around into the next row if needed.
// - IMPORTANT: Comparatively to the old Columns() API, we need to call TableNextColumn() for the first column!
// - Summary of possible call flow:
// --------------------------------------------------------------------------------------------------------
// TableNextRow() -> TableSetColumnIndex(0) -> Text("Hello 0") -> TableSetColumnIndex(1) -> Text("Hello 1") // OK
// TableNextRow() -> TableNextColumn() -> Text("Hello 0") -> TableNextColumn() -> Text("Hello 1") // OK
// TableNextColumn() -> Text("Hello 0") -> TableNextColumn() -> Text("Hello 1") // OK: TableNextColumn() automatically gets to next row!
// TableNextRow() -> Text("Hello 0") // Not OK! Missing TableSetColumnIndex() or TableNextColumn()! Text will not appear!
// --------------------------------------------------------------------------------------------------------
// - 5. Call EndTable()
pub const BeginTableOption = struct {
flags: c.ImGuiTableFlags = 0,
outer_size: c.ImVec2 = vec2_zero,
inner_width: f32 = 0,
};
pub fn beginTable(str_id: [:0]const u8, column: c_int, option: BeginTableOption) bool {
return c.igBeginTable(str_id, column, option.flags, option.outer_size, option.inner_width);
}
pub const endTable = c.igEndTable;
pub fn tableNextRow(row_flags: ?c.ImGuiTableRowFlags, min_row_height: ?f32) void {
return c.igTableNextRow(row_flags orelse 0, min_row_height orelse 0);
}
pub const tableNextColumn = c.igTableNextColumn;
pub fn tableSetColumnIndex(column_n: c_int) bool {
return c.igTableSetColumnIndex(column_n);
}
// Tables: Headers & Columns declaration
// - Use TableSetupColumn() to specify label, resizing policy, default width/weight, id, various other flags etc.
// - Use TableHeadersRow() to create a header row and automatically submit a TableHeader() for each column.
// Headers are required to perform: reordering, sorting, and opening the context menu.
// The context menu can also be made available in columns body using ImGuiTableFlags_ContextMenuInBody.
// - You may manually submit headers using TableNextRow() + TableHeader() calls, but this is only useful in
// some advanced use cases (e.g. adding custom widgets in header row).
// - Use TableSetupScrollFreeze() to lock columns/rows so they stay visible when scrolled.
pub const TableSetupColumnOption = struct {
flags: c.ImGuiTableColumnFlags = 0,
init_width_or_weight: f32 = 0,
user_id: c.ImGuiID = 0,
};
pub fn tableSetupColumn(label: [:0]const u8, option: TableSetupColumnOption) void {
return c.igTableSetupColumn(label, option.flags, option.init_width_or_weight, option.user_id);
}
pub fn tableSetupScrollFreeze(cols: c_int, rows: c_int) void {
return c.igTableSetupScrollFreeze(cols, rows);
}
pub const tableHeadersRow = c.igTableHeadersRow;
pub fn tableHeader(label: [:0]const u8) void {
return c.igTableHeader(label);
}
// Tables: Sorting
// - Call TableGetSortSpecs() to retrieve latest sort specs for the table. NULL when not sorting.
// - When 'SpecsDirty == true' you should sort your data. It will be true when sorting specs have changed
// since last call, or the first time. Make sure to set 'SpecsDirty = false' after sorting, else you may
// wastefully sort your data every frame!
// - Lifetime: don't hold on this pointer over multiple frames or past any subsequent call to BeginTable().
pub const tableGetSortSpecs = c.igTableGetSortSpecs;
// Tables: Miscellaneous functions
// - Functions args 'int column_n' treat the default value of -1 as the same as passing the current column index.
pub const tableGetColumnCount = c.igTableGetColumnCount;
pub const tableGetColumnIndex = c.igTableGetColumnIndex;
pub const tableGetRowIndex = c.igTableGetRowIndex;
pub fn tableGetColumnName_Int(column_n: ?c_int) [*c]const u8 {
return c.igTableGetColumnName_Int(column_n orelse -1);
}
pub fn tableGetColumnFlags(column_n: ?c_int) c.ImGuiTableColumnFlags {
return c.igTableGetColumnFlags(column_n orelse -1);
}
pub fn tableSetColumnEnabled(column_n: c_int, v: bool) void {
return c.igTableSetColumnEnabled(column_n, v);
}
pub fn tableSetBgColor(target: c.ImGuiTableBgTarget, color: c.ImU32, column_n: ?c_int) void {
return c.igTableSetBgColor(target, color, column_n orelse -1);
}
// Legacy Columns API (prefer using Tables!)
// - You can also use SameLine(pos_x) to mimic simplified columns.
pub fn columns(count: c_int, id: ?[:0]const u8, border: ?bool) void {
return c.igColumns(count, id, border orelse true);
}
pub const nextColumn = c.igNextColumn;
pub const getColumnIndex = c.igGetColumnIndex;
pub fn getColumnWidth(column_index: ?c_int) f32 {
return c.igGetColumnWidth(column_index orelse -1);
}
pub fn setColumnWidth(column_index: c_int, width: f32) void {
return c.igSetColumnWidth(column_index, width);
}
pub fn getColumnOffset(column_index: ?c_int) f32 {
return c.igGetColumnOffset(column_index orelse -1);
}
pub fn setColumnOffset(column_index: c_int, offset_x: f32) void {
return c.igSetColumnOffset(column_index, offset_x);
}
pub const getColumnsCount = c.igGetColumnsCount;
// Tab Bars, Tabs
pub fn beginTabBar(str_id: [:0]const u8, flags: ?c.ImGuiTabBarFlags) bool {
return c.igBeginTabBar(str_id, flags orelse 0);
}
pub const endTabBar = c.igEndTabBar;
pub fn beginTabItem(label: [:0]const u8, p_open: ?*bool, flags: ?c.ImGuiTabItemFlags) bool {
return c.igBeginTabItem(label, p_open, flags orelse 0);
}
pub const endTabItem = c.igEndTabItem;
pub fn tabItemButton(label: [:0]const u8, flags: ?c.ImGuiTabItemFlags) bool {
return c.igTabItemButton(label, flags orelse 0);
}
pub fn setTabItemClosed(tab_or_docked_window_label: [:0]const u8) void {
return c.igSetTabItemClosed(tab_or_docked_window_label);
}
// Logging/Capture
// - All text output from the interface can be captured into tty/file/clipboard. By default, tree nodes are automatically opened during logging.
pub fn logToTTY(auto_open_depth: ?c_int) void {
return c.igLogToTTY(auto_open_depth orelse -1);
}
pub fn logToFile(auto_open_depth: ?c_int, filename: ?[:0]const u8) void {
return c.igLogToFile(auto_open_depth orelse -1, filename);
}
pub fn logToClipboard(auto_open_depth: ?c_int) void {
return c.igLogToClipboard(auto_open_depth orelse -1);
}
pub const logFinish = c.igLogFinish;
pub const logButtons = c.igLogButtons;
pub const logText = c.igLogText;
// Drag and Drop
// - On source items, call BeginDragDropSource(), if it returns true also call SetDragDropPayload() + EndDragDropSource().
// - On target candidates, call BeginDragDropTarget(), if it returns true also call AcceptDragDropPayload() + EndDragDropTarget().
// - If you stop calling BeginDragDropSource() the payload is preserved however it won't have a preview tooltip (we currently display a fallback "..." tooltip, see #1725)
// - An item can be both drag source and drop target.
pub fn beginDragDropSource(flags: ?c.ImGuiDragDropFlags) bool {
return c.igBeginDragDropSource(flags orelse 0);
}
pub fn setDragDropPayload(@"type": [:0]const u8, data: *const anyopaque, sz: usize, cond: ?c.ImGuiCond) bool {
return c.igSetDragDropPayload(@"type", data, sz, cond orelse 0);
}
pub const endDragDropSource = c.igEndDragDropSource;
pub const beginDragDropTarget = c.igBeginDragDropTarget;
pub fn acceptDragDropPayload(@"type": [:0]const u8, flags: ?c.ImGuiDragDropFlags) [*c]const c.ImGuiPayload {
return c.igAcceptDragDropPayload(@"type", flags orelse 0);
}
pub const endDragDropTarget = c.igEndDragDropTarget;
pub const getDragDropPayload = c.igGetDragDropPayload;
// Disabling [BETA API]
// - Disable all user interactions and dim items visuals (applying style.DisabledAlpha over current colors)
// - Those can be nested but it cannot be used to enable an already disabled section (a single BeginDisabled(true) in the stack is enough to keep everything disabled)
// - BeginDisabled(false) essentially does nothing useful but is provided to facilitate use of boolean expressions. If you can avoid calling BeginDisabled(False)/EndDisabled() best to avoid it.
pub fn beginDisabled(disabled: ?bool) void {
return c.igBeginDisabled(disabled orelse true);
}
pub const endDisabled = c.igEndDisabled;
// Clipping
// - Mouse hovering is affected by ImGui::PushClipRect() calls, unlike direct calls to ImDrawList::PushClipRect() which are render only.
pub fn pushClipRect(clip_rect_min: c.ImVec2, clip_rect_max: c.ImVec2, intersect_with_current_clip_rect: bool) void {
return c.igPushClipRect(clip_rect_min, clip_rect_max, intersect_with_current_clip_rect);
}
pub const popClipRect = c.igPopClipRect;
// Focus, Activation
// - Prefer using "SetItemDefaultFocus()" over "if (IsWindowAppearing()) SetScrollHereY()" when applicable to signify "this is the default item"
pub const setItemDefaultFocus = c.igSetItemDefaultFocus;
pub fn setKeyboardFocusHere(offset: ?c_int) void {
return c.igSetKeyboardFocusHere(offset orelse 0);
}
// Item/Widgets Utilities and Query Functions
// - Most of the functions are referring to the previous Item that has been submitted.
// - See Demo Window under "Widgets->Querying Status" for an interactive visualization of most of those functions.
pub fn isItemHovered(flags: ?c.ImGuiHoveredFlags) bool {
return c.igIsItemHovered(flags orelse 0);
}
pub const isItemActive = c.igIsItemActive;
pub const isItemFocused = c.igIsItemFocused;
pub fn isItemClicked(mouse_button: ?c.ImGuiMouseButton) bool {
return c.igIsItemClicked(mouse_button orelse 0);
}
pub const isItemVisible = c.igIsItemVisible;
pub const isItemEdited = c.igIsItemEdited;
pub const isItemActivated = c.igIsItemActivated;
pub const isItemDeactivated = c.igIsItemDeactivated;
pub const isItemDeactivatedAfterEdit = c.igIsItemDeactivatedAfterEdit;
pub const isItemToggledOpen = c.igIsItemToggledOpen;
pub const isAnyItemHovered = c.igIsAnyItemHovered;
pub const isAnyItemActive = c.igIsAnyItemActive;
pub const isAnyItemFocused = c.igIsAnyItemFocused;
pub fn getItemRectMin(pOut: *c.ImVec2) void {
return c.igGetItemRectMin(pOut);
}
pub fn getItemRectMax(pOut: *c.ImVec2) void {
return c.igGetItemRectMax(pOut);
}
pub fn getItemRectSize(pOut: *c.ImVec2) void {
return c.igGetItemRectSize(pOut);
}
pub const setItemAllowOverlap = c.igSetItemAllowOverlap;
// Viewports
// - Currently represents the Platform Window created by the application which is hosting our Dear ImGui windows.
// - In 'docking' branch with multi-viewport enabled, we extend this concept to have multiple active viewports.
// - In the future we will extend this concept further to also represent Platform Monitor and support a "no main platform window" operation mode.
pub const getMainViewport = c.igGetMainViewport;
// Miscellaneous Utilities
pub fn isRectVisible_Nil(size: c.ImVec2) bool {
return c.igIsRectVisible_Nil(size);
}
pub fn isRectVisible_Vec2(rect_min: c.ImVec2, rect_max: c.ImVec2) bool {
return c.igIsRectVisible_Vec2(rect_min, rect_max);
}
pub const getTime = c.igGetTime;
pub const getFrameCount = c.igGetFrameCount;
pub const getBackgroundDrawList_Nil = c.igGetBackgroundDrawList_Nil;
pub const getForegroundDrawList_Nil = c.igGetForegroundDrawList_Nil;
pub const getDrawListSharedData = c.igGetDrawListSharedData;
pub fn getStyleColorName(idx: c.ImGuiCol) [*c]const u8 {
return c.igGetStyleColorName(idx);
}
pub fn setStateStorage(storage: [*c]c.ImGuiStorage) void {
return c.igSetStateStorage(storage);
}
pub const getStateStorage = c.igGetStateStorage;
pub fn calcListClipping(items_count: c_int, items_height: f32, out_items_display_start: *c_int, out_items_display_end: [*c]c_int) void {
return c.igCalcListClipping(items_count, items_height, out_items_display_start, out_items_display_end);
}
pub fn beginChildFrame(id: c.ImGuiID, size: c.ImVec2, flags: ?c.ImGuiWindowFlags) bool {
return c.igBeginChildFrame(id, size, flags orelse 0);
}
pub const endChildFrame = c.igEndChildFrame;
// Text Utilities
pub const CalcTextSizeOption = struct {
text_end: [*c]const u8 = null,
hide_text_after_double_hash: bool = false,
wrap_width: f32 = -1.0,
};
pub fn calcTextSize(pOut: *c.ImVec2, _text: [*c]const u8, option: CalcTextSizeOption) void {
return c.igCalcTextSize(pOut, _text, option.text_end, option.hide_text_after_double_hash, option.wrap_width);
}
// Color Utilities
pub fn colorConvertU32ToFloat4(pOut: *c.ImVec4, in: c.ImU32) void {
return c.igColorConvertU32ToFloat4(pOut, in);
}
pub fn colorConvertFloat4ToU32(in: c.ImVec4) c.ImU32 {
return c.igColorConvertFloat4ToU32(in);
}
pub fn colorConvertRGBtoHSV(r: f32, g: f32, b: f32, out_h: *f32, out_s: *f32, out_v: [*c]f32) void {
return c.igColorConvertRGBtoHSV(r, g, b, out_h, out_s, out_v);
}
pub fn colorConvertHSVtoRGB(h: f32, s: f32, v: f32, out_r: *f32, out_g: *f32, out_b: [*c]f32) void {
return c.igColorConvertHSVtoRGB(h, s, v, out_r, out_g, out_b);
}
// Inputs Utilities: Keyboard
// - For 'int user_key_index' you can use your own indices/enums according to how your backend/engine stored them in io.KeysDown[].
// - We don't know the meaning of those value. You can use GetKeyIndex() to map a ImGuiKey_ value into the user index.
pub fn getKeyIndex(imgui_key: c.ImGuiKey) c_int {
return c.igGetKeyIndex(imgui_key);
}
pub fn isKeyDown(user_key_index: c_int) bool {
return c.igIsKeyDown(user_key_index);
}
pub fn isKeyPressed(user_key_index: c_int, repeat: ?bool) bool {
return c.igIsKeyPressed(user_key_index, repeat orelse true);
}
pub fn isKeyReleased(user_key_index: c_int) bool {
return c.igIsKeyReleased(user_key_index);
}
pub fn getKeyPressedAmount(key_index: c_int, repeat_delay: f32, rate: f32) c_int {
return c.igGetKeyPressedAmount(key_index, repeat_delay, rate);
}
pub fn captureKeyboardFromApp(want_capture_keyboard_value: ?bool) void {
return c.igCaptureKeyboardFromApp(want_capture_keyboard_value orelse true);
}
// Inputs Utilities: Mouse
// - To refer to a mouse button, you may use named enums in your code e.g. ImGuiMouseButton_Left, ImGuiMouseButton_Right.
// - You can also use regular integer: it is forever guaranteed that 0=Left, 1=Right, 2=Middle.
// - Dragging operations are only reported after mouse has moved a certain distance away from the initial clicking position (see 'lock_threshold' and 'io.MouseDraggingThreshold')
pub fn isMouseDown(_button: c.ImGuiMouseButton) bool {
return c.igIsMouseDown(_button);
}
pub fn isMouseClicked(_button: c.ImGuiMouseButton, repeat: ?bool) bool {
return c.igIsMouseClicked(_button, repeat orelse false);
}
pub fn isMouseReleased(_button: c.ImGuiMouseButton) bool {
return c.igIsMouseReleased(_button);
}
pub fn isMouseDoubleClicked(_button: c.ImGuiMouseButton) bool {
return c.igIsMouseDoubleClicked(_button);
}
pub fn isMouseHoveringRect(r_min: c.ImVec2, r_max: c.ImVec2, clip: ?bool) bool {
return c.igIsMouseHoveringRect(r_min, r_max, clip orelse true);
}
pub fn isMousePosValid(mouse_pos: ?*const c.ImVec2) bool {
return c.igIsMousePosValid(mouse_pos);
}
pub const isAnyMouseDown = c.igIsAnyMouseDown;
pub fn getMousePos(pOut: *c.ImVec2) void {
return c.igGetMousePos(pOut);
}
pub fn getMousePosOnOpeningCurrentPopup(pOut: *c.ImVec2) void {
return c.igGetMousePosOnOpeningCurrentPopup(pOut);
}
pub fn isMouseDragging(_button: c.ImGuiMouseButton, lock_threshold: ?f32) bool {
return c.igIsMouseDragging(_button, lock_threshold orelse -1);
}
pub fn getMouseDragDelta(pOut: *c.ImVec2, _button: ?c.ImGuiMouseButton, lock_threshold: ?f32) void {
return c.igGetMouseDragDelta(pOut, _button orelse 0, lock_threshold orelse -1);
}
pub fn resetMouseDragDelta(_button: ?c.ImGuiMouseButton) void {
return c.igResetMouseDragDelta(_button orelse 0);
}
pub const getMouseCursor = c.igGetMouseCursor;
pub fn setMouseCursor(cursor_type: c.ImGuiMouseCursor) void {
return c.igSetMouseCursor(cursor_type);
}
pub fn captureMouseFromApp(want_capture_mouse_value: ?bool) void {
return c.igCaptureMouseFromApp(want_capture_mouse_value orelse true);
}
// Clipboard Utilities
// - Also see the LogToClipboard() function to capture GUI into clipboard, or easily output text data to the clipboard.
pub const getClipboardText = c.igGetClipboardText;
pub fn setClipboardText(_text: [:0]const u8) void {
return c.igSetClipboardText(_text);
}
// Settings/.Ini Utilities
// - The disk functions are automatically called if io.IniFilename != NULL (default is "imgui.ini").
// - Set io.IniFilename to NULL to load/save manually. Read io.WantSaveIniSettings description about handling .ini saving manually.
// - Important: default value "imgui.ini" is relative to current working dir! Most apps will want to lock this to an absolute path (e.g. same path as executables).
pub fn loadIniSettingsFromDisk(ini_filename: [:0]const u8) void {
return c.igLoadIniSettingsFromDisk(ini_filename);
}
pub fn loadIniSettingsFromMemory(ini_data: []const u8) void {
return c.igLoadIniSettingsFromMemory(ini_data.ptr, ini_data.len);
}
pub fn saveIniSettingsToDisk(ini_filename: [:0]const u8) void {
return c.igSaveIniSettingsToDisk(ini_filename);
}
pub fn saveIniSettingsToMemory(out_ini_size: ?*usize) [*c]const u8 {
return c.igSaveIniSettingsToMemory(out_ini_size);
}
// Debug Utilities
// - This is used by the IMGUI_CHECKVERSION() macro.
pub fn debugCheckVersionAndDataLayout(version_str: [:0]const u8, sz_io: usize, sz_style: usize, sz_vec2: usize, sz_vec4: usize, sz_drawvert: usize, sz_drawidx: usize) bool {
return c.igDebugCheckVersionAndDataLayout(version_str, sz_io, sz_style, sz_vec2, sz_vec4, sz_drawvert, sz_drawidx);
}
// Memory Allocators
// - Those functions are not reliant on the current context.
// - DLL users: heaps and globals are not shared across DLL boundaries! You will need to call SetCurrentContext() + SetAllocatorFunctions()
// for each static/DLL boundary you are calling from. Read "Context and Memory Allocators" section of imgui.cpp for more details.
pub fn setAllocatorFunctions(alloc_func: c.ImGuiMemAllocFunc, free_func: c.ImGuiMemFreeFunc, user_data: ?*anyopaque) void {
return c.igSetAllocatorFunctions(alloc_func, free_func, user_data);
}
pub fn getAllocatorFunctions(p_alloc_func: [*c]c.ImGuiMemAllocFunc, p_free_func: [*c]c.ImGuiMemFreeFunc, p_user_data: **anyopaque) void {
return c.igGetAllocatorFunctions(p_alloc_func, p_free_func, p_user_data);
}
pub fn memAlloc(size: usize) ?*anyopaque {
return c.igMemAlloc(size);
}
pub fn memFree(ptr: ?*anyopaque) void {
return c.igMemFree(ptr);
}
/// draw list
pub const DrawList = struct {
pub fn init(shared_data: *const c.ImDrawListSharedData) *c.ImDrawList {
return @ptrCast(*c.ImDrawList, c.ImDrawList_ImDrawList(shared_data));
}
pub fn deinit(self: *c.ImDrawList) void {
return c.ImDrawList_destroy(self);
}
pub fn pushClipRect(
self: *c.ImDrawList,
clip_rect_min: c.ImVec2,
clip_rect_max: c.ImVec2,
intersect_with_current_clip_rect: bool,
) void {
return c.ImDrawList_PushClipRect(self, clip_rect_min, clip_rect_max, intersect_with_current_clip_rect);
}
pub fn pushClipRectFullScreen(self: *c.ImDrawList) void {
return c.ImDrawList_PushClipRectFullScreen(self);
}
pub fn popClipRect(self: *c.ImDrawList) void {
return c.ImDrawList_PopClipRect(self);
}
pub fn pushTextureID(self: *c.ImDrawList, texture_id: c.ImTextureID) void {
return c.ImDrawList_PushTextureID(self, texture_id);
}
pub fn popTextureID(self: *c.ImDrawList) void {
return c.ImDrawList_PopTextureID(self);
}
pub fn getClipRectMin(pOut: [*c]c.ImVec2, self: *c.ImDrawList) void {
return c.ImDrawList_GetClipRectMin(pOut, self);
}
pub fn getClipRectMax(pOut: [*c]c.ImVec2, self: *c.ImDrawList) void {
return c.ImDrawList_GetClipRectMax(pOut, self);
}
pub fn addLine(self: *c.ImDrawList, p1: c.ImVec2, p2: c.ImVec2, col: c.ImU32, thickness: f32) void {
return c.ImDrawList_AddLine(self, p1, p2, col, thickness);
}
pub fn addRect(
self: *c.ImDrawList,
p_min: c.ImVec2,
p_max: c.ImVec2,
col: c.ImU32,
rounding: f32,
flags: c.ImDrawFlags,
thickness: f32,
) void {
return c.ImDrawList_AddRect(self, p_min, p_max, col, rounding, flags, thickness);
}
pub fn addRectFilled(
self: *c.ImDrawList,
p_min: c.ImVec2,
p_max: c.ImVec2,
col: c.ImU32,
rounding: f32,
flags: c.ImDrawFlags,
) void {
return c.ImDrawList_AddRectFilled(self, p_min, p_max, col, rounding, flags);
}
pub fn addRectFilledMultiColor(
self: *c.ImDrawList,
p_min: c.ImVec2,
p_max: c.ImVec2,
col_upr_left: c.ImU32,
col_upr_right: c.ImU32,
col_bot_right: c.ImU32,
col_bot_left: c.ImU32,
) void {
return c.ImDrawList_AddRectFilledMultiColor(self, p_min, p_max, col_upr_left, col_upr_right, col_bot_right, col_bot_left);
}
pub fn addQuad(
self: *c.ImDrawList,
p1: c.ImVec2,
p2: c.ImVec2,
p3: c.ImVec2,
p4: c.ImVec2,
col: c.ImU32,
thickness: f32,
) void {
return c.ImDrawList_AddQuad(self, p1, p2, p3, p4, col, thickness);
}
pub fn addQuadFilled(
self: *c.ImDrawList,
p1: c.ImVec2,
p2: c.ImVec2,
p3: c.ImVec2,
p4: c.ImVec2,
col: c.ImU32,
) void {
return c.ImDrawList_AddQuadFilled(self, p1, p2, p3, p4, col);
}
pub fn addTriangle(
self: *c.ImDrawList,
p1: c.ImVec2,
p2: c.ImVec2,
p3: c.ImVec2,
col: c.ImU32,
thickness: f32,
) void {
return c.ImDrawList_AddTriangle(self, p1, p2, p3, col, thickness);
}
pub fn addTriangleFilled(
self: *c.ImDrawList,
p1: c.ImVec2,
p2: c.ImVec2,
p3: c.ImVec2,
col: c.ImU32,
) void {
return c.ImDrawList_AddTriangleFilled(self, p1, p2, p3, col);
}
pub fn addCircle(
self: *c.ImDrawList,
center: c.ImVec2,
radius: f32,
col: c.ImU32,
num_segments: c_int,
thickness: f32,
) void {
return c.ImDrawList_AddCircle(self, center, radius, col, num_segments, thickness);
}
pub fn addCircleFilled(
self: *c.ImDrawList,
center: c.ImVec2,
radius: f32,
col: c.ImU32,
num_segments: c_int,
) void {
return c.ImDrawList_AddCircleFilled(self, center, radius, col, num_segments);
}
pub fn addNgon(
self: *c.ImDrawList,
center: c.ImVec2,
radius: f32,
col: c.ImU32,
num_segments: c_int,
thickness: f32,
) void {
return c.ImDrawList_AddNgon(self, center, radius, col, num_segments, thickness);
}
pub fn addNgonFilled(
self: *c.ImDrawList,
center: c.ImVec2,
radius: f32,
col: c.ImU32,
num_segments: c_int,
) void {
return c.ImDrawList_AddNgonFilled(self, center, radius, col, num_segments);
}
pub fn addText_Vec2(
self: *c.ImDrawList,
pos: c.ImVec2,
col: c.ImU32,
text_begin: [*c]const u8,
text_end: [*c]const u8,
) void {
return c.ImDrawList_AddText_Vec2(self, pos, col, text_begin, text_end);
}
pub fn addText_FontPtr(
self: *c.ImDrawList,
font: [*c]const c.ImFont,
font_size: f32,
pos: c.ImVec2,
col: c.ImU32,
text_begin: [*c]const u8,
text_end: [*c]const u8,
wrap_width: f32,
cpu_fine_clip_rect: [*c]const c.ImVec4,
) void {
return c.ImDrawList_AddText_FontPtr(
self,
font,
font_size,
pos,
col,
text_begin,
text_end,
wrap_width,
cpu_fine_clip_rect,
);
}
pub fn addPolyline(
self: *c.ImDrawList,
points: [*c]const c.ImVec2,
num_points: c_int,
col: c.ImU32,
flags: c.ImDrawFlags,
thickness: f32,
) void {
return c.ImDrawList_AddPolyline(self, points, num_points, col, flags, thickness);
}
pub fn addConvexPolyFilled(
self: *c.ImDrawList,
points: [*c]const c.ImVec2,
num_points: c_int,
col: c.ImU32,
) void {
return c.ImDrawList_AddConvexPolyFilled(self, points, num_points, col);
}
pub fn addBezierCubic(
self: *c.ImDrawList,
p1: c.ImVec2,
p2: c.ImVec2,
p3: c.ImVec2,
p4: c.ImVec2,
col: c.ImU32,
thickness: f32,
num_segments: c_int,
) void {
return c.ImDrawList_AddBezierCubic(self, p1, p2, p3, p4, col, thickness, num_segments);
}
pub fn addBezierQuadratic(
self: *c.ImDrawList,
p1: c.ImVec2,
p2: c.ImVec2,
p3: c.ImVec2,
col: c.ImU32,
thickness: f32,
num_segments: c_int,
) void {
return c.ImDrawList_AddBezierQuadratic(self, p1, p2, p3, col, thickness, num_segments);
}
pub fn addImage(
self: *c.ImDrawList,
user_texture_id: c.ImTextureID,
p_min: c.ImVec2,
p_max: c.ImVec2,
uv_min: c.ImVec2,
uv_max: c.ImVec2,
col: c.ImU32,
) void {
return c.ImDrawList_AddImage(self, user_texture_id, p_min, p_max, uv_min, uv_max, col);
}
pub fn addImageQuad(
self: *c.ImDrawList,
user_texture_id: c.ImTextureID,
p1: c.ImVec2,
p2: c.ImVec2,
p3: c.ImVec2,
p4: c.ImVec2,
uv1: c.ImVec2,
uv2: c.ImVec2,
uv3: c.ImVec2,
uv4: c.ImVec2,
col: c.ImU32,
) void {
return c.ImDrawList_AddImageQuad(
self,
user_texture_id,
p1,
p2,
p3,
p4,
uv1,
uv2,
uv3,
uv4,
col,
);
}
pub fn addImageRounded(
self: *c.ImDrawList,
user_texture_id: c.ImTextureID,
p_min: c.ImVec2,
p_max: c.ImVec2,
uv_min: c.ImVec2,
uv_max: c.ImVec2,
col: c.ImU32,
rounding: f32,
flags: c.ImDrawFlags,
) void {
return c.ImDrawList_AddImageRounded(
self,
user_texture_id,
p_min,
p_max,
uv_min,
uv_max,
col,
rounding,
flags,
);
}
pub fn pathClear(self: *c.ImDrawList) void {
return c.ImDrawList_PathClear(self);
}
pub fn pathLineTo(self: *c.ImDrawList, pos: c.ImVec2) void {
return c.ImDrawList_PathLineTo(self, pos);
}
pub fn pathLineToMergeDuplicate(self: *c.ImDrawList, pos: c.ImVec2) void {
return c.ImDrawList_PathLineToMergeDuplicate(self, pos);
}
pub fn pathFillConvex(self: *c.ImDrawList, col: c.ImU32) void {
return c.ImDrawList_PathFillConvex(self, col);
}
pub fn pathStroke(self: *c.ImDrawList, col: c.ImU32, flags: c.ImDrawFlags, thickness: f32) void {
return c.ImDrawList_PathStroke(self, col, flags, thickness);
}
pub fn pathArcTo(
self: *c.ImDrawList,
center: c.ImVec2,
radius: f32,
a_min: f32,
a_max: f32,
num_segments: c_int,
) void {
return c.ImDrawList_PathArcTo(self, center, radius, a_min, a_max, num_segments);
}
pub fn pathArcToFast(
self: *c.ImDrawList,
center: c.ImVec2,
radius: f32,
a_min_of_12: c_int,
a_max_of_12: c_int,
) void {
return c.ImDrawList_PathArcToFast(self, center, radius, a_min_of_12, a_max_of_12);
}
pub fn pathBezierCubicCurveTo(
self: *c.ImDrawList,
p2: c.ImVec2,
p3: c.ImVec2,
p4: c.ImVec2,
num_segments: c_int,
) void {
return c.ImDrawList_PathBezierCubicCurveTo(self, p2, p3, p4, num_segments);
}
pub fn pathBezierQuadraticCurveTo(
self: *c.ImDrawList,
p2: c.ImVec2,
p3: c.ImVec2,
num_segments: c_int,
) void {
return c.ImDrawList_PathBezierQuadraticCurveTo(self, p2, p3, num_segments);
}
pub fn pathRect(
self: *c.ImDrawList,
rect_min: c.ImVec2,
rect_max: c.ImVec2,
rounding: f32,
flags: c.ImDrawFlags,
) void {
return c.ImDrawList_PathRect(self, rect_min, rect_max, rounding, flags);
}
pub fn addCallback(
self: *c.ImDrawList,
callback: c.ImDrawCallback,
callback_data: ?*anyopaque,
) void {
return c.ImDrawList_AddCallback(self, callback, callback_data);
}
pub fn addDrawCmd(self: *c.ImDrawList) void {
return c.ImDrawList_AddDrawCmd(self);
}
pub fn cloneOutput(self: *c.ImDrawList) *c.ImDrawList {
return c.ImDrawList_CloneOutput(self);
}
pub fn channelsSplit(self: *c.ImDrawList, count: c_int) void {
return c.ImDrawList_ChannelsSplit(self, count);
}
pub fn channelsMerge(self: *c.ImDrawList) void {
return c.ImDrawList_ChannelsMerge(self);
}
pub fn channelsSetCurrent(self: *c.ImDrawList, n: c_int) void {
return c.ImDrawList_ChannelsSetCurrent(self, n);
}
pub fn primReserve(self: *c.ImDrawList, idx_count: c_int, vtx_count: c_int) void {
return c.ImDrawList_PrimReserve(self, idx_count, vtx_count);
}
pub fn primUnreserve(self: *c.ImDrawList, idx_count: c_int, vtx_count: c_int) void {
return c.ImDrawList_PrimUnreserve(self, idx_count, vtx_count);
}
pub fn primRect(self: *c.ImDrawList, a: c.ImVec2, b: c.ImVec2, col: c.ImU32) void {
return c.ImDrawList_PrimRect(self, a, b, col);
}
pub fn primRectUV(self: *c.ImDrawList, a: c.ImVec2, b: c.ImVec2, uv_a: c.ImVec2, uv_b: c.ImVec2, col: c.ImU32) void {
return c.ImDrawList_PrimRectUV(self, a, b, uv_a, uv_b, col);
}
pub fn primQuadUV(
self: *c.ImDrawList,
a: c.ImVec2,
b: c.ImVec2,
_c: c.ImVec2,
d: c.ImVec2,
uv_a: c.ImVec2,
uv_b: c.ImVec2,
uv_c: c.ImVec2,
uv_d: c.ImVec2,
col: c.ImU32,
) void {
return c.ImDrawList_PrimQuadUV(self, a, b, _c, d, uv_a, uv_b, uv_c, uv_d, col);
}
pub fn primWriteVtx(self: *c.ImDrawList, pos: c.ImVec2, uv: c.ImVec2, col: c.ImU32) void {
return c.ImDrawList_PrimWriteVtx(self, pos, uv, col);
}
pub fn primWriteIdx(self: *c.ImDrawList, idx: c.ImDrawIdx) void {
return c.ImDrawList_PrimWriteIdx(self, idx);
}
pub fn primVtx(self: *c.ImDrawList, pos: c.ImVec2, uv: c.ImVec2, col: c.ImU32) void {
return c.ImDrawList_PrimVtx(self, pos, uv, col);
}
pub fn resetForNewFrame(self: *c.ImDrawList) void {
return c.ImDrawList__ResetForNewFrame(self);
}
pub fn clearFreeMemory(self: *c.ImDrawList) void {
return c.ImDrawList__ClearFreeMemory(self);
}
pub fn popUnusedDrawCmd(self: *c.ImDrawList) void {
return c.ImDrawList__PopUnusedDrawCmd(self);
}
pub fn tryMergeDrawCmds(self: *c.ImDrawList) void {
return c.ImDrawList__TryMergeDrawCmds(self);
}
pub fn onChangedClipRect(self: *c.ImDrawList) void {
return c.ImDrawList__OnChangedClipRect(self);
}
pub fn onChangedTextureID(self: *c.ImDrawList) void {
return c.ImDrawList__OnChangedTextureID(self);
}
pub fn onChangedVtxOffset(self: *c.ImDrawList) void {
return c.ImDrawList__OnChangedVtxOffset(self);
}
pub fn calcCircleAutoSegmentCount(self: *c.ImDrawList, radius: f32) c_int {
return c.ImDrawList__CalcCircleAutoSegmentCount(self, radius);
}
pub fn pathArcToFastEx(
self: *c.ImDrawList,
center: c.ImVec2,
radius: f32,
a_min_sample: c_int,
a_max_sample: c_int,
a_step: c_int,
) void {
return c.ImDrawList__PathArcToFastEx(
self,
center,
radius,
a_min_sample,
a_max_sample,
a_step,
);
}
pub fn pathArcToN(
self: *c.ImDrawList,
center: c.ImVec2,
radius: f32,
a_min: f32,
a_max: f32,
num_segments: c_int,
) void {
return c.ImDrawList__PathArcToN(
self,
center,
radius,
a_min,
a_max,
num_segments,
);
}
};
/// ImGui Helpers
pub const helpers = struct {
// Helpers: Hashing
pub fn hashData(data: [*]const anyopaque, data_size: usize, seed: c.ImU32) c.ImGuiID {
return c.igImHashData(data, data_size, seed);
}
pub fn hashStr(data: []const u8, seed: c.ImU32) c.ImGuiID {
return c.igImHashStr(data.ptr, data.len, seed);
}
// Helpers: Color Blending
pub fn alphaBlendColors(col_a: c.ImU32, col_b: c.ImU32) c.ImU32 {
return c.igImAlphaBlendColors(col_a, col_b);
}
// Helpers: Bit manipulation
pub fn isPowerOfTwo_Int(v: c_int) bool {
return c.igImIsPowerOfTwo_Int(v);
}
pub fn isPowerOfTwo_U64(v: c.ImU64) bool {
return c.igImIsPowerOfTwo_U64(v);
}
pub fn upperPowerOfTwo(v: c_int) c_int {
return c.igImUpperPowerOfTwo(v);
}
// Helpers: String, Formatting
pub fn stricmp(str1: [*c]const u8, str2: [*c]const u8) c_int {
return c.igImStricmp(str1, str2);
}
pub fn strnicmp(str1: [*c]const u8, str2: [*c]const u8, count: usize) c_int {
return c.igImStrnicmp(str1, str2, count);
}
pub fn strncpy(dst: [*c]u8, src: [*c]const u8, count: usize) void {
return c.igImStrncpy(dst, src, count);
}
pub fn strdup(str: [*c]const u8) [*c]u8 {
return c.igImStrdup(str);
}
pub fn strdupcpy(dst: [*c]u8, p_dst_size: [*c]usize, str: [*c]const u8) [*c]u8 {
return c.igImStrdupcpy(dst, p_dst_size, str);
}
pub fn strchrRange(str_begin: [*c]const u8, str_end: [*c]const u8, _c: u8) [*c]const u8 {
return c.igImStrchrRange(str_begin, str_end, _c);
}
pub fn strlenW(str: [*c]const c.ImWchar) c_int {
return c.igImStrlenW(str);
}
pub fn streolRange(str: [*c]const u8, str_end: [*c]const u8) [*c]const u8 {
return c.igImStreolRange(str, str_end);
}
pub fn strbolW(buf_mid_line: *const c.ImWchar, buf_begin: [*c]const c.ImWchar) [*c]const c.ImWchar {
return c.igImStrbolW(buf_mid_line, buf_begin);
}
pub fn stristr(haystack: [*c]const u8, haystack_end: [*c]const u8, needle: [*c]const u8, needle_end: [*c]const u8) [*c]const u8 {
return c.igImStristr(haystack, haystack_end, needle, needle_end);
}
pub fn strTrimBlanks(str: [*c]u8) void {
return c.igImStrTrimBlanks(str);
}
pub fn strSkipBlank(str: [*c]const u8) [*c]const u8 {
return c.igImStrSkipBlank(str);
}
pub const formatString = c.igImFormatString;
pub fn parseFormatFindStart(format: [:0]const u8) [*c]const u8 {
return c.igImParseFormatFindStart(format);
}
pub fn parseFormatFindEnd(format: [:0]const u8) [*c]const u8 {
return c.igImParseFormatFindEnd(format);
}
pub fn parseFormatTrimDecorations(format: [:0]const u8, buf: [*c]u8, buf_size: usize) [*c]const u8 {
return c.igImParseFormatTrimDecorations(format, buf, buf_size);
}
pub fn parseFormatPrecision(format: [:0]const u8, default_value: c_int) c_int {
return c.igImParseFormatPrecision(format, default_value);
}
pub fn charIsBlankA(_c: u8) bool {
return c.igImCharIsBlankA(_c);
}
pub fn charIsBlankW(_c: c_uint) bool {
return c.igImCharIsBlankW(_c);
}
// Helpers: UTF-8 <> wchar conversions
pub fn textCharToUtf8(out_buf: [*c]u8, _c: c_uint) [*c]const u8 {
return c.igImTextCharToUtf8(out_buf, _c);
}
pub fn textStrToUtf8(out_buf: [*c]u8, out_buf_size: c_int, in_text: *const c.ImWchar, in_text_end: [*c]const c.ImWchar) c_int {
return c.igImTextStrToUtf8(out_buf, out_buf_size, in_text, in_text_end);
}
pub fn textCharFromUtf8(out_char: [*c]c_uint, in_text: [*c]const u8, in_text_end: [*c]const u8) c_int {
return c.igImTextCharFromUtf8(out_char, in_text, in_text_end);
}
pub fn textStrFromUtf8(out_buf: *c.ImWchar, out_buf_size: c_int, in_text: [*c]const u8, in_text_end: [*c]const u8, in_remaining: [*c][*c]const u8) c_int {
return c.igImTextStrFromUtf8(out_buf, out_buf_size, in_text, in_text_end, in_remaining);
}
pub fn textCountCharsFromUtf8(in_text: [*c]const u8, in_text_end: [*c]const u8) c_int {
return c.igImTextCountCharsFromUtf8(in_text, in_text_end);
}
pub fn textCountUtf8BytesFromChar(in_text: [*c]const u8, in_text_end: [*c]const u8) c_int {
return c.igImTextCountUtf8BytesFromChar(in_text, in_text_end);
}
pub fn textCountUtf8BytesFromStr(in_text: *const c.ImWchar, in_text_end: [*c]const c.ImWchar) c_int {
return c.igImTextCountUtf8BytesFromStr(in_text, in_text_end);
}
// Helpers: File System
pub fn fileOpen(filename: [*c]const u8, mode: [*c]const u8) c.ImFileHandle {
return c.igImFileOpen(filename, mode);
}
pub fn fileClose(file: c.ImFileHandle) bool {
return c.igImFileClose(file);
}
pub fn fileGetSize(file: c.ImFileHandle) c.ImU64 {
return c.igImFileGetSize(file);
}
pub fn fileRead(data: ?*anyopaque, size: c.ImU64, count: c.ImU64, file: c.ImFileHandle) c.ImU64 {
return c.igImFileRead(data, size, count, file);
}
pub fn fileWrite(data: ?*const anyopaque, size: c.ImU64, count: c.ImU64, file: c.ImFileHandle) c.ImU64 {
return c.igImFileWrite(data, size, count, file);
}
pub fn fileLoadToMemory(filename: [*c]const u8, mode: [*c]const u8, out_file_size: [*c]usize, padding_bytes: c_int) ?*anyopaque {
return c.igImFileLoadToMemory(filename, mode, out_file_size, padding_bytes);
}
// Helpers: Maths
pub fn pow_Float(x: f32, y: f32) f32 {
return c.igImPow_Float(x, y);
}
pub fn pow_double(x: f64, y: f64) f64 {
return c.igImPow_double(x, y);
}
pub fn log_Float(x: f32) f32 {
return c.igImLog_Float(x);
}
pub fn log_double(x: f64) f64 {
return c.igImLog_double(x);
}
pub fn abs_Int(x: c_int) c_int {
return c.igImAbs_Int(x);
}
pub fn abs_Float(x: f32) f32 {
return c.igImAbs_Float(x);
}
pub fn abs_double(x: f64) f64 {
return c.igImAbs_double(x);
}
pub fn sign_Float(x: f32) f32 {
return c.igImSign_Float(x);
}
pub fn sign_double(x: f64) f64 {
return c.igImSign_double(x);
}
pub fn rsqrt_Float(x: f32) f32 {
return c.igImRsqrt_Float(x);
}
pub fn rsqrt_double(x: f64) f64 {
return c.igImRsqrt_double(x);
}
// - ImMin/ImMax/ImClamp/ImLerp/ImSwap are used by widgets which support variety of types: signed/unsigned int/long long float/double
// (Exceptionally using templates here but we could also redefine them for those types)
pub fn min(pOut: *c.ImVec2, lhs: c.ImVec2, rhs: c.ImVec2) void {
return c.igImMin(pOut, lhs, rhs);
}
pub fn max(pOut: *c.ImVec2, lhs: c.ImVec2, rhs: c.ImVec2) void {
return c.igImMax(pOut, lhs, rhs);
}
pub fn clamp(pOut: *c.ImVec2, v: c.ImVec2, mn: c.ImVec2, mx: c.ImVec2) void {
return c.igImClamp(pOut, v, mn, mx);
}
pub fn lerp_Vec2Float(pOut: *c.ImVec2, a: c.ImVec2, b: c.ImVec2, t: f32) void {
return c.igImLerp_Vec2Float(pOut, a, b, t);
}
pub fn lerp_Vec2Vec2(pOut: *c.ImVec2, a: c.ImVec2, b: c.ImVec2, t: c.ImVec2) void {
return c.igImLerp_Vec2Vec2(pOut, a, b, t);
}
pub fn lerp_Vec4(pOut: *c.ImVec4, a: c.ImVec4, b: c.ImVec4, t: f32) void {
return c.igImLerp_Vec4(pOut, a, b, t);
}
pub fn saturate(f: f32) f32 {
return c.igImSaturate(f);
}
pub fn lengthSqr_Vec2(lhs: c.ImVec2) f32 {
return c.igImLengthSqr_Vec2(lhs);
}
pub fn lengthSqr_Vec4(lhs: c.ImVec4) f32 {
return c.igImLengthSqr_Vec4(lhs);
}
pub fn invLength(lhs: c.ImVec2, fail_value: f32) f32 {
return c.igImInvLength(lhs, fail_value);
}
pub fn floor_Float(f: f32) f32 {
return c.igImFloor_Float(f);
}
pub fn floorSigned(f: f32) f32 {
return c.igImFloorSigned(f);
}
pub fn floor_Vec2(pOut: *c.ImVec2, v: c.ImVec2) void {
return c.igImFloor_Vec2(pOut, v);
}
pub fn modPositive(a: c_int, b: c_int) c_int {
return c.igImModPositive(a, b);
}
pub fn dot(a: c.ImVec2, b: c.ImVec2) f32 {
return c.igImDot(a, b);
}
pub fn rotate(pOut: *c.ImVec2, v: c.ImVec2, cos_a: f32, sin_a: f32) void {
return c.igImRotate(pOut, v, cos_a, sin_a);
}
pub fn linearSweep(current: f32, target: f32, speed: f32) f32 {
return c.igImLinearSweep(current, target, speed);
}
pub fn mul(pOut: *c.ImVec2, lhs: c.ImVec2, rhs: c.ImVec2) void {
return c.igImMul(pOut, lhs, rhs);
}
// Helpers: Geometry
pub fn bezierCubicCalc(pOut: *c.ImVec2, p1: c.ImVec2, p2: c.ImVec2, p3: c.ImVec2, p4: c.ImVec2, t: f32) void {
return c.igImBezierCubicCalc(pOut, p1, p2, p3, p4, t);
}
pub fn bezierCubicClosestPoint(pOut: *c.ImVec2, p1: c.ImVec2, p2: c.ImVec2, p3: c.ImVec2, p4: c.ImVec2, p: c.ImVec2, num_segments: c_int) void {
return c.igImBezierCubicClosestPoint(pOut, p1, p2, p3, p4, p, num_segments);
}
pub fn bezierCubicClosestPointCasteljau(pOut: *c.ImVec2, p1: c.ImVec2, p2: c.ImVec2, p3: c.ImVec2, p4: c.ImVec2, p: c.ImVec2, tess_tol: f32) void {
return c.igImBezierCubicClosestPointCasteljau(pOut, p1, p2, p3, p4, p, tess_tol);
}
pub fn bezierQuadraticCalc(pOut: *c.ImVec2, p1: c.ImVec2, p2: c.ImVec2, p3: c.ImVec2, t: f32) void {
return c.igImBezierQuadraticCalc(pOut, p1, p2, p3, t);
}
pub fn lineClosestPoint(pOut: *c.ImVec2, a: c.ImVec2, b: c.ImVec2, p: c.ImVec2) void {
return c.igImLineClosestPoint(pOut, a, b, p);
}
pub fn triangleContainsPoint(a: c.ImVec2, b: c.ImVec2, _c: c.ImVec2, p: c.ImVec2) bool {
return c.igImTriangleContainsPoint(a, b, _c, p);
}
pub fn triangleClosestPoint(pOut: *c.ImVec2, a: c.ImVec2, b: c.ImVec2, _c: c.ImVec2, p: c.ImVec2) void {
return c.igImTriangleClosestPoint(pOut, a, b, _c, p);
}
pub fn triangleBarycentricCoords(a: c.ImVec2, b: c.ImVec2, _c: c.ImVec2, p: c.ImVec2, out_u: *f32, out_v: *f32, out_w: *f32) void {
return c.igImTriangleBarycentricCoords(a, b, _c, p, out_u, out_v, out_w);
}
pub fn triangleArea(a: c.ImVec2, b: c.ImVec2, _c: c.ImVec2) f32 {
return c.igImTriangleArea(a, b, _c);
}
pub fn getDirQuadrantFromDelta(dx: f32, dy: f32) c.ImGuiDir {
return c.igImGetDirQuadrantFromDelta(dx, dy);
}
// Helper: ImBitArray
pub fn bitArrayTestBit(arr: *const c.ImU32, n: c_int) bool {
return c.igImBitArrayTestBit(arr, n);
}
pub fn bitArrayClearBit(arr: *c.ImU32, n: c_int) void {
return c.igImBitArrayClearBit(arr, n);
}
pub fn bitArraySetBit(arr: *c.ImU32, n: c_int) void {
return c.igImBitArraySetBit(arr, n);
}
pub fn bitArraySetBitRange(arr: *c.ImU32, n: c_int, n2: c_int) void {
return c.igImBitArraySetBitRange(arr, n, n2);
}
};
/// ImGui internal API
/// No guarantee of forward compatibility here!
pub const internal = struct {
// Windows
// We should always have a CurrentWindow in the stack (there is an implicit "Debug" window)
// If this ever crash because g.CurrentWindow is NULL it means that either
// - ImGui::NewFrame() has never been called, which is illegal.
// - You are calling ImGui functions after ImGui::EndFrame()/ImGui::Render() and before the next ImGui::NewFrame(), which is also illegal.
pub const getCurrentWindowRead = c.igGetCurrentWindowRead;
pub const getCurrentWindow = c.igGetCurrentWindow;
pub fn findWindowByID(id: c.ImGuiID) ?*c.ImGuiWindow {
return c.igFindWindowByID(id);
}
pub fn findWindowByName(name: [:0]const u8) ?*c.ImGuiWindow {
return c.igFindWindowByName(name);
}
pub fn updateWindowParentAndRootLinks(window: ?*c.ImGuiWindow, flags: c.ImGuiWindowFlags, parent_window: ?*c.ImGuiWindow) void {
return c.igUpdateWindowParentAndRootLinks(window, flags, parent_window);
}
pub fn calcWindowNextAutoFitSize(pOut: *c.ImVec2, window: ?*c.ImGuiWindow) void {
return c.igCalcWindowNextAutoFitSize(pOut, window);
}
pub fn isWindowChildOf(window: ?*c.ImGuiWindow, potential_parent: ?*c.ImGuiWindow, popup_hierarchy: bool) bool {
return c.igIsWindowChildOf(window, potential_parent, popup_hierarchy);
}
pub fn isWindowAbove(potential_above: ?*c.ImGuiWindow, potential_below: ?*c.ImGuiWindow) bool {
return c.igIsWindowAbove(potential_above, potential_below);
}
pub fn isWindowNavFocusable(window: ?*c.ImGuiWindow) bool {
return c.igIsWindowNavFocusable(window);
}
pub fn setWindowPos_WindowPtr(window: ?*c.ImGuiWindow, pos: c.ImVec2, cond: c.ImGuiCond) void {
return c.igSetWindowPos_WindowPtr(window, pos, cond);
}
pub fn setWindowSize_WindowPtr(window: ?*c.ImGuiWindow, size: c.ImVec2, cond: c.ImGuiCond) void {
return c.igSetWindowSize_WindowPtr(window, size, cond);
}
pub fn setWindowCollapsed_WindowPtr(window: ?*c.ImGuiWindow, collapsed: bool, cond: c.ImGuiCond) void {
return c.igSetWindowCollapsed_WindowPtr(window, collapsed, cond);
}
pub fn setWindowHitTestHole(window: ?*c.ImGuiWindow, pos: c.ImVec2, size: c.ImVec2) void {
return c.igSetWindowHitTestHole(window, pos, size);
}
// Windows: Display Order and Focus Order
pub fn focusWindow(window: ?*c.ImGuiWindow) void {
return c.igFocusWindow(window);
}
pub fn focusTopMostWindowUnderOne(under_this_window: ?*c.ImGuiWindow, ignore_window: ?*c.ImGuiWindow) void {
return c.igFocusTopMostWindowUnderOne(under_this_window, ignore_window);
}
pub fn bringWindowToFocusFront(window: ?*c.ImGuiWindow) void {
return c.igBringWindowToFocusFront(window);
}
pub fn bringWindowToDisplayFront(window: ?*c.ImGuiWindow) void {
return c.igBringWindowToDisplayFront(window);
}
pub fn bringWindowToDisplayBack(window: ?*c.ImGuiWindow) void {
return c.igBringWindowToDisplayBack(window);
}
// Fonts, drawing
pub fn setCurrentFont(font: [*c]c.ImFont) void {
return c.igSetCurrentFont(font);
}
pub const getDefaultFont = c.igGetDefaultFont;
pub fn getForegroundDrawList_WindowPtr(window: ?*c.ImGuiWindow) [*c]c.ImDrawList {
return c.igGetForegroundDrawList_WindowPtr(window);
}
pub fn getBackgroundDrawList_ViewportPtr(viewport: [*c]c.ImGuiViewport) [*c]c.ImDrawList {
return c.igGetBackgroundDrawList_ViewportPtr(viewport);
}
pub fn getForegroundDrawList_ViewportPtr(viewport: [*c]c.ImGuiViewport) [*c]c.ImDrawList {
return c.igGetForegroundDrawList_ViewportPtr(viewport);
}
// Init
pub fn initialize(context: [*c]c.ImGuiContext) void {
return c.igInitialize(context);
}
pub fn shutdown(context: [*c]c.ImGuiContext) void {
return c.igShutdown(context);
}
// NewFrame
pub const updateHoveredWindowAndCaptureFlags = c.igUpdateHoveredWindowAndCaptureFlags;
pub fn startMouseMovingWindow(window: ?*c.ImGuiWindow) void {
return c.igStartMouseMovingWindow(window);
}
pub const updateMouseMovingWindowNewFrame = c.igUpdateMouseMovingWindowNewFrame;
pub const updateMouseMovingWindowEndFrame = c.igUpdateMouseMovingWindowEndFrame;
// Generic context hooks
pub fn addContextHook(context: [*c]c.ImGuiContext, hook: [*c]const c.ImGuiContextHook) c.ImGuiID {
return c.igAddContextHook(context, hook);
}
pub fn removeContextHook(context: [*c]c.ImGuiContext, hook_to_remove: c.ImGuiID) void {
return c.igRemoveContextHook(context, hook_to_remove);
}
pub fn callContextHooks(context: [*c]c.ImGuiContext, @"type": c.ImGuiContextHookType) void {
return c.igCallContextHooks(context, @"type");
}
// Settings
pub const markIniSettingsDirty_Nil = c.igMarkIniSettingsDirty_Nil;
pub fn markIniSettingsDirty_WindowPtr(window: ?*c.ImGuiWindow) void {
return c.igMarkIniSettingsDirty_WindowPtr(window);
}
pub const clearIniSettings = c.igClearIniSettings;
pub fn createNewWindowSettings(name: [:0]const u8) [*c]c.ImGuiWindowSettings {
return c.igCreateNewWindowSettings(name);
}
pub fn findWindowSettings(id: c.ImGuiID) [*c]c.ImGuiWindowSettings {
return c.igFindWindowSettings(id);
}
pub fn findOrCreateWindowSettings(name: [:0]const u8) [*c]c.ImGuiWindowSettings {
return c.igFindOrCreateWindowSettings(name);
}
pub fn findSettingsHandler(type_name: [*c]const u8) [*c]c.ImGuiSettingsHandler {
return c.igFindSettingsHandler(type_name);
}
// Scrolling
pub fn setNextWindowScroll(scroll: c.ImVec2) void {
return c.igSetNextWindowScroll(scroll);
}
pub fn setScrollX_WindowPtr(window: ?*c.ImGuiWindow, scroll_x: f32) void {
return c.igSetScrollX_WindowPtr(window, scroll_x);
}
pub fn setScrollY_WindowPtr(window: ?*c.ImGuiWindow, scroll_y: f32) void {
return c.igSetScrollY_WindowPtr(window, scroll_y);
}
pub fn setScrollFromPosX_WindowPtr(window: ?*c.ImGuiWindow, local_x: f32, center_x_ratio: f32) void {
return c.igSetScrollFromPosX_WindowPtr(window, local_x, center_x_ratio);
}
pub fn setScrollFromPosY_WindowPtr(window: ?*c.ImGuiWindow, local_y: f32, center_y_ratio: f32) void {
return c.igSetScrollFromPosY_WindowPtr(window, local_y, center_y_ratio);
}
// Early work-in-progress API (ScrollToItem() will become public)
pub fn scrollToItem(flags: c.ImGuiScrollFlags) void {
return c.igScrollToItem(flags);
}
pub fn scrollToRect(window: ?*c.ImGuiWindow, rect: c.ImRect, flags: c.ImGuiScrollFlags) void {
return c.igScrollToRect(window, rect, flags);
}
pub fn scrollToRectEx(pOut: *c.ImVec2, window: ?*c.ImGuiWindow, rect: c.ImRect, flags: c.ImGuiScrollFlags) void {
return c.igScrollToRectEx(pOut, window, rect, flags);
}
pub fn scrollToBringRectIntoView(window: ?*c.ImGuiWindow, rect: c.ImRect) void {
return c.igScrollToBringRectIntoView(window, rect);
}
// Basic Accessors
pub const getItemID = c.igGetItemID;
pub const getItemStatusFlags = c.igGetItemStatusFlags;
pub const getItemFlags = c.igGetItemFlags;
pub const getActiveID = c.igGetActiveID;
pub const getFocusID = c.igGetFocusID;
pub fn setActiveID(id: c.ImGuiID, window: ?*c.ImGuiWindow) void {
return c.igSetActiveID(id, window);
}
pub fn setFocusID(id: c.ImGuiID, window: ?*c.ImGuiWindow) void {
return c.igSetFocusID(id, window);
}
pub const clearActiveID = c.igClearActiveID;
pub const getHoveredID = c.igGetHoveredID;
pub fn setHoveredID(id: c.ImGuiID) void {
return c.igSetHoveredID(id);
}
pub fn keepAliveID(id: c.ImGuiID) void {
return c.igKeepAliveID(id);
}
pub fn markItemEdited(id: c.ImGuiID) void {
return c.igMarkItemEdited(id);
}
pub fn pushOverrideID(id: c.ImGuiID) void {
return c.igPushOverrideID(id);
}
pub fn getIDWithSeed(str_id: [:0]const u8, seed: c.ImGuiID) c.ImGuiID {
return c.igGetIDWithSeed(str_id.ptr, str_id.ptr + str_id.len, seed);
}
// Basic Helpers for widget code
pub fn itemSize_Vec2(size: c.ImVec2, text_baseline_y: f32) void {
return c.igItemSize_Vec2(size, text_baseline_y);
}
pub fn itemSize_Rect(bb: c.ImRect, text_baseline_y: f32) void {
return c.igItemSize_Rect(bb, text_baseline_y);
}
pub fn itemAdd(bb: c.ImRect, id: c.ImGuiID, nav_bb: *const c.ImRect, extra_flags: c.ImGuiItemFlags) bool {
return c.igItemAdd(bb, id, nav_bb, extra_flags);
}
pub fn itemHoverable(bb: c.ImRect, id: c.ImGuiID) bool {
return c.igItemHoverable(bb, id);
}
pub fn isClippedEx(bb: c.ImRect, id: c.ImGuiID) bool {
return c.igIsClippedEx(bb, id);
}
pub fn calcItemSize(pOut: *c.ImVec2, size: c.ImVec2, default_w: f32, default_h: f32) void {
return c.igCalcItemSize(pOut, size, default_w, default_h);
}
pub fn calcWrapWidthForPos(pos: c.ImVec2, wrap_pos_x: f32) f32 {
return c.igCalcWrapWidthForPos(pos, wrap_pos_x);
}
pub fn pushMultiItemsWidths(components: c_int, width_full: f32) void {
return c.igPushMultiItemsWidths(components, width_full);
}
pub const isItemToggledSelection = c.igIsItemToggledSelection;
pub fn getContentRegionMaxAbs(pOut: *c.ImVec2) void {
return c.igGetContentRegionMaxAbs(pOut);
}
pub fn shrinkWidths(items: [*c]c.ImGuiShrinkWidthItem, count: c_int, width_excess: f32) void {
return c.igShrinkWidths(items, count, width_excess);
}
// Parameter stacks
pub fn pushItemFlag(option: c.ImGuiItemFlags, enabled: bool) void {
return c.igPushItemFlag(option, enabled);
}
pub const popItemFlag = c.igPopItemFlag;
// Logging/Capture
pub fn logBegin(@"type": c.ImGuiLogType, auto_open_depth: c_int) void {
return c.igLogBegin(@"type", auto_open_depth);
}
pub fn logToBuffer(auto_open_depth: c_int) void {
return c.igLogToBuffer(auto_open_depth);
}
pub fn logRenderedText(ref_pos: *const c.ImVec2, _text: [*c]const u8, text_end: [*c]const u8) void {
return c.igLogRenderedText(ref_pos, _text, text_end);
}
pub fn logSetNextTextDecoration(prefix: [*c]const u8, suffix: [*c]const u8) void {
return c.igLogSetNextTextDecoration(prefix, suffix);
}
// Popups, Modals, Tooltips
pub fn beginChildEx(name: [:0]const u8, id: c.ImGuiID, size_arg: c.ImVec2, border: bool, flags: c.ImGuiWindowFlags) bool {
return c.igBeginChildEx(name, id, size_arg, border, flags);
}
pub fn openPopupEx(id: c.ImGuiID, popup_flags: c.ImGuiPopupFlags) void {
return c.igOpenPopupEx(id, popup_flags);
}
pub fn closePopupToLevel(remaining: c_int, restore_focus_to_window_under_popup: bool) void {
return c.igClosePopupToLevel(remaining, restore_focus_to_window_under_popup);
}
pub fn closePopupsOverWindow(ref_window: ?*c.ImGuiWindow, restore_focus_to_window_under_popup: bool) void {
return c.igClosePopupsOverWindow(ref_window, restore_focus_to_window_under_popup);
}
pub const closePopupsExceptModals = c.igClosePopupsExceptModals;
pub fn isPopupOpen_ID(id: c.ImGuiID, popup_flags: c.ImGuiPopupFlags) bool {
return c.igIsPopupOpen_ID(id, popup_flags);
}
pub fn beginPopupEx(id: c.ImGuiID, extra_flags: c.ImGuiWindowFlags) bool {
return c.igBeginPopupEx(id, extra_flags);
}
pub fn beginTooltipEx(extra_flags: c.ImGuiWindowFlags, tooltip_flags: c.ImGuiTooltipFlags) void {
return c.igBeginTooltipEx(extra_flags, tooltip_flags);
}
pub fn getPopupAllowedExtentRect(pOut: *c.ImRect, window: ?*c.ImGuiWindow) void {
return c.igGetPopupAllowedExtentRect(pOut, window);
}
pub const getTopMostPopupModal = c.igGetTopMostPopupModal;
pub fn findBestWindowPosForPopup(pOut: *c.ImVec2, window: ?*c.ImGuiWindow) void {
return c.igFindBestWindowPosForPopup(pOut, window);
}
pub fn findBestWindowPosForPopupEx(pOut: *c.ImVec2, ref_pos: c.ImVec2, size: c.ImVec2, last_dir: [*c]c.ImGuiDir, r_outer: c.ImRect, r_avoid: c.ImRect, policy: c.ImGuiPopupPositionPolicy) void {
return c.igFindBestWindowPosForPopupEx(pOut, ref_pos, size, last_dir, r_outer, r_avoid, policy);
}
// Menus
pub fn beginViewportSideBar(name: [:0]const u8, viewport: [*c]c.ImGuiViewport, dir: c.ImGuiDir, size: f32, window_flags: c.ImGuiWindowFlags) bool {
return c.igBeginViewportSideBar(name, viewport, dir, size, window_flags);
}
pub fn beginMenuEx(label: [:0]const u8, icon: [*c]const u8, enabled: bool) bool {
return c.igBeginMenuEx(label, icon, enabled);
}
pub fn menuItemEx(label: [:0]const u8, icon: [*c]const u8, shortcut: [*c]const u8, selected: bool, enabled: bool) bool {
return c.igMenuItemEx(label, icon, shortcut, selected, enabled);
}
// Combos
pub fn beginComboPopup(popup_id: c.ImGuiID, bb: c.ImRect, flags: c.ImGuiComboFlags) bool {
return c.igBeginComboPopup(popup_id, bb, flags);
}
pub const beginComboPreview = c.igBeginComboPreview;
pub const endComboPreview = c.igEndComboPreview;
// Gamepad/Keyboard Navigation
pub fn navInitWindow(window: ?*c.ImGuiWindow, force_reinit: bool) void {
return c.igNavInitWindow(window, force_reinit);
}
pub const navInitRequestApplyResult = c.igNavInitRequestApplyResult;
pub const navMoveRequestButNoResultYet = c.igNavMoveRequestButNoResultYet;
pub fn navMoveRequestSubmit(move_dir: c.ImGuiDir, clip_dir: c.ImGuiDir, move_flags: c.ImGuiNavMoveFlags, scroll_flags: c.ImGuiScrollFlags) void {
return c.igNavMoveRequestSubmit(move_dir, clip_dir, move_flags, scroll_flags);
}
pub fn navMoveRequestForward(move_dir: c.ImGuiDir, clip_dir: c.ImGuiDir, move_flags: c.ImGuiNavMoveFlags, scroll_flags: c.ImGuiScrollFlags) void {
return c.igNavMoveRequestForward(move_dir, clip_dir, move_flags, scroll_flags);
}
pub const navMoveRequestResolveWithLastItem = c.igNavMoveRequestResolveWithLastItem;
pub const navMoveRequestCancel = c.igNavMoveRequestCancel;
pub const navMoveRequestApplyResult = c.igNavMoveRequestApplyResult;
pub fn navMoveRequestTryWrapping(window: ?*c.ImGuiWindow, move_flags: c.ImGuiNavMoveFlags) void {
return c.igNavMoveRequestTryWrapping(window, move_flags);
}
pub fn getNavInputAmount(n: c.ImGuiNavInput, mode: c.ImGuiInputReadMode) f32 {
return c.igGetNavInputAmount(n, mode);
}
pub fn getNavInputAmount2d(pOut: *c.ImVec2, dir_sources: c.ImGuiNavDirSourceFlags, mode: c.ImGuiInputReadMode, slow_factor: f32, fast_factor: f32) void {
return c.igGetNavInputAmount2d(pOut, dir_sources, mode, slow_factor, fast_factor);
}
pub fn calcTypematicRepeatAmount(t0: f32, t1: f32, repeat_delay: f32, repeat_rate: f32) c_int {
return c.igCalcTypematicRepeatAmount(t0, t1, repeat_delay, repeat_rate);
}
pub fn activateItem(id: c.ImGuiID) void {
return c.igActivateItem(id);
}
pub fn setNavID(id: c.ImGuiID, nav_layer: c.ImGuiNavLayer, focus_scope_id: c.ImGuiID, rect_rel: c.ImRect) void {
return c.igSetNavID(id, nav_layer, focus_scope_id, rect_rel);
}
// Focus Scope (WIP)
// This is generally used to identify a selection set (multiple of which may be in the same window), as selection
// patterns generally need to react (e.g. clear selection) when landing on an item of the set.
pub fn pushFocusScope(id: c.ImGuiID) void {
return c.igPushFocusScope(id);
}
pub const popFocusScope = c.igPopFocusScope;
pub const getFocusedFocusScope = c.igGetFocusedFocusScope;
pub const getFocusScope = c.igGetFocusScope;
// Inputs
// FIXME: Eventually we should aim to move e.g. IsActiveIdUsingKey() into IsKeyXXX functions.
pub const setItemUsingMouseWheel = c.igSetItemUsingMouseWheel;
pub const setActiveIdUsingNavAndKeys = c.igSetActiveIdUsingNavAndKeys;
pub fn isActiveIdUsingNavDir(dir: c.ImGuiDir) bool {
return c.igIsActiveIdUsingNavDir(dir);
}
pub fn isActiveIdUsingNavInput(input: c.ImGuiNavInput) bool {
return c.igIsActiveIdUsingNavInput(input);
}
pub fn isActiveIdUsingKey(key: c.ImGuiKey) bool {
return c.igIsActiveIdUsingKey(key);
}
pub fn isMouseDragPastThreshold(_button: c.ImGuiMouseButton, lock_threshold: f32) bool {
return c.igIsMouseDragPastThreshold(_button, lock_threshold);
}
pub fn isKeyPressedMap(key: c.ImGuiKey, repeat: bool) bool {
return c.igIsKeyPressedMap(key, repeat);
}
pub fn isNavInputDown(n: c.ImGuiNavInput) bool {
return c.igIsNavInputDown(n);
}
pub fn isNavInputTest(n: c.ImGuiNavInput, rm: c.ImGuiInputReadMode) bool {
return c.igIsNavInputTest(n, rm);
}
pub const getMergedKeyModFlags = c.igGetMergedKeyModFlags;
// Drag and Drop
pub fn beginDragDropTargetCustom(bb: c.ImRect, id: c.ImGuiID) bool {
return c.igBeginDragDropTargetCustom(bb, id);
}
pub const clearDragDrop = c.igClearDragDrop;
pub const isDragDropPayloadBeingAccepted = c.igIsDragDropPayloadBeingAccepted;
// Internal Columns API (this is not exposed because we will encourage transitioning to the Tables API)
pub fn setWindowClipRectBeforeSetChannel(window: ?*c.ImGuiWindow, clip_rect: c.ImRect) void {
return c.igSetWindowClipRectBeforeSetChannel(window, clip_rect);
}
pub fn beginColumns(str_id: [:0]const u8, count: c_int, flags: c.ImGuiOldColumnFlags) void {
return c.igBeginColumns(str_id, count, flags);
}
pub const endColumns = c.igEndColumns;
pub fn pushColumnClipRect(column_index: c_int) void {
return c.igPushColumnClipRect(column_index);
}
pub const pushColumnsBackground = c.igPushColumnsBackground;
pub const popColumnsBackground = c.igPopColumnsBackground;
pub fn getColumnsID(str_id: [:0]const u8, count: c_int) c.ImGuiID {
return c.igGetColumnsID(str_id, count);
}
pub fn findOrCreateColumns(window: ?*c.ImGuiWindow, id: c.ImGuiID) [*c]c.ImGuiOldColumns {
return c.igFindOrCreateColumns(window, id);
}
pub fn getColumnOffsetFromNorm(_columns: [*c]const c.ImGuiOldColumns, offset_norm: f32) f32 {
return c.igGetColumnOffsetFromNorm(_columns, offset_norm);
}
pub fn getColumnNormFromOffset(_columns: [*c]const c.ImGuiOldColumns, offset: f32) f32 {
return c.igGetColumnNormFromOffset(_columns, offset);
}
// Tables: Candidates for public API
pub fn tableOpenContextMenu(column_n: c_int) void {
return c.igTableOpenContextMenu(column_n);
}
pub fn tableSetColumnWidth(column_n: c_int, width: f32) void {
return c.igTableSetColumnWidth(column_n, width);
}
pub fn tableSetColumnSortDirection(column_n: c_int, sort_direction: c.ImGuiSortDirection, append_to_sort_specs: bool) void {
return c.igTableSetColumnSortDirection(column_n, sort_direction, append_to_sort_specs);
}
pub const tableGetHoveredColumn = c.igTableGetHoveredColumn;
pub const tableGetHeaderRowHeight = c.igTableGetHeaderRowHeight;
pub const tablePushBackgroundChannel = c.igTablePushBackgroundChannel;
pub const tablePopBackgroundChannel = c.igTablePopBackgroundChannel;
// Tables: Internals
pub const getCurrentTable = c.igGetCurrentTable;
pub fn tableFindByID(id: c.ImGuiID) ?*c.ImGuiTable {
return c.igTableFindByID(id);
}
pub fn beginTableEx(name: [:0]const u8, id: c.ImGuiID, columns_count: c_int, flags: c.ImGuiTableFlags, outer_size: c.ImVec2, inner_width: f32) bool {
return c.igBeginTableEx(name, id, columns_count, flags, outer_size, inner_width);
}
pub fn tableBeginInitMemory(table: ?*c.ImGuiTable, columns_count: c_int) void {
return c.igTableBeginInitMemory(table, columns_count);
}
pub fn tableBeginApplyRequests(table: ?*c.ImGuiTable) void {
return c.igTableBeginApplyRequests(table);
}
pub fn tableSetupDrawChannels(table: ?*c.ImGuiTable) void {
return c.igTableSetupDrawChannels(table);
}
pub fn tableUpdateLayout(table: ?*c.ImGuiTable) void {
return c.igTableUpdateLayout(table);
}
pub fn tableUpdateBorders(table: ?*c.ImGuiTable) void {
return c.igTableUpdateBorders(table);
}
pub fn tableUpdateColumnsWeightFromWidth(table: ?*c.ImGuiTable) void {
return c.igTableUpdateColumnsWeightFromWidth(table);
}
pub fn tableDrawBorders(table: ?*c.ImGuiTable) void {
return c.igTableDrawBorders(table);
}
pub fn tableDrawContextMenu(table: ?*c.ImGuiTable) void {
return c.igTableDrawContextMenu(table);
}
pub fn tableMergeDrawChannels(table: ?*c.ImGuiTable) void {
return c.igTableMergeDrawChannels(table);
}
pub fn tableSortSpecsSanitize(table: ?*c.ImGuiTable) void {
return c.igTableSortSpecsSanitize(table);
}
pub fn tableSortSpecsBuild(table: ?*c.ImGuiTable) void {
return c.igTableSortSpecsBuild(table);
}
pub fn tableGetColumnNextSortDirection(column: ?*c.ImGuiTableColumn) c.ImGuiSortDirection {
return c.igTableGetColumnNextSortDirection(column);
}
pub fn tableFixColumnSortDirection(table: ?*c.ImGuiTable, column: ?*c.ImGuiTableColumn) void {
return c.igTableFixColumnSortDirection(table, column);
}
pub fn tableGetColumnWidthAuto(table: ?*c.ImGuiTable, column: ?*c.ImGuiTableColumn) f32 {
return c.igTableGetColumnWidthAuto(table, column);
}
pub fn tableBeginRow(table: ?*c.ImGuiTable) void {
return c.igTableBeginRow(table);
}
pub fn tableEndRow(table: ?*c.ImGuiTable) void {
return c.igTableEndRow(table);
}
pub fn tableBeginCell(table: ?*c.ImGuiTable, column_n: c_int) void {
return c.igTableBeginCell(table, column_n);
}
pub fn tableEndCell(table: ?*c.ImGuiTable) void {
return c.igTableEndCell(table);
}
pub fn tableGetCellBgRect(pOut: *c.ImRect, table: ?*const c.ImGuiTable, column_n: c_int) void {
return c.igTableGetCellBgRect(pOut, table, column_n);
}
pub fn tableGetColumnName_TablePtr(table: ?*const c.ImGuiTable, column_n: c_int) [*c]const u8 {
return c.igTableGetColumnName_TablePtr(table, column_n);
}
pub fn tableGetColumnResizeID(table: ?*const c.ImGuiTable, column_n: c_int, instance_no: c_int) c.ImGuiID {
return c.igTableGetColumnResizeID(table, column_n, instance_no);
}
pub fn tableGetMaxColumnWidth(table: ?*const c.ImGuiTable, column_n: c_int) f32 {
return c.igTableGetMaxColumnWidth(table, column_n);
}
pub fn tableSetColumnWidthAutoSingle(table: ?*c.ImGuiTable, column_n: c_int) void {
return c.igTableSetColumnWidthAutoSingle(table, column_n);
}
pub fn tableSetColumnWidthAutoAll(table: ?*c.ImGuiTable) void {
return c.igTableSetColumnWidthAutoAll(table);
}
pub fn tableRemove(table: ?*c.ImGuiTable) void {
return c.igTableRemove(table);
}
pub fn tableGcCompactTransientBuffers_TablePtr(table: ?*c.ImGuiTable) void {
return c.igTableGcCompactTransientBuffers_TablePtr(table);
}
pub fn tableGcCompactTransientBuffers_TableTempDataPtr(table: [*c]c.ImGuiTableTempData) void {
return c.igTableGcCompactTransientBuffers_TableTempDataPtr(table);
}
pub const tableGcCompactSettings = c.igTableGcCompactSettings;
// Tables: Settings
pub fn tableLoadSettings(table: ?*c.ImGuiTable) void {
return c.igTableLoadSettings(table);
}
pub fn tableSaveSettings(table: ?*c.ImGuiTable) void {
return c.igTableSaveSettings(table);
}
pub fn tableResetSettings(table: ?*c.ImGuiTable) void {
return c.igTableResetSettings(table);
}
pub fn tableGetBoundSettings(table: ?*c.ImGuiTable) [*c]c.ImGuiTableSettings {
return c.igTableGetBoundSettings(table);
}
pub fn tableSettingsInstallHandler(context: [*c]c.ImGuiContext) void {
return c.igTableSettingsInstallHandler(context);
}
pub fn tableSettingsCreate(id: c.ImGuiID, columns_count: c_int) [*c]c.ImGuiTableSettings {
return c.igTableSettingsCreate(id, columns_count);
}
pub fn tableSettingsFindByID(id: c.ImGuiID) [*c]c.ImGuiTableSettings {
return c.igTableSettingsFindByID(id);
}
// Tab Bars
pub fn beginTabBarEx(tab_bar: [*c]c.ImGuiTabBar, bb: c.ImRect, flags: c.ImGuiTabBarFlags) bool {
return c.igBeginTabBarEx(tab_bar, bb, flags);
}
pub fn tabBarFindTabByID(tab_bar: [*c]c.ImGuiTabBar, tab_id: c.ImGuiID) [*c]c.ImGuiTabItem {
return c.igTabBarFindTabByID(tab_bar, tab_id);
}
pub fn tabBarRemoveTab(tab_bar: [*c]c.ImGuiTabBar, tab_id: c.ImGuiID) void {
return c.igTabBarRemoveTab(tab_bar, tab_id);
}
pub fn tabBarCloseTab(tab_bar: [*c]c.ImGuiTabBar, tab: [*c]c.ImGuiTabItem) void {
return c.igTabBarCloseTab(tab_bar, tab);
}
pub fn tabBarQueueReorder(tab_bar: [*c]c.ImGuiTabBar, tab: [*c]const c.ImGuiTabItem, offset: c_int) void {
return c.igTabBarQueueReorder(tab_bar, tab, offset);
}
pub fn tabBarQueueReorderFromMousePos(tab_bar: [*c]c.ImGuiTabBar, tab: [*c]const c.ImGuiTabItem, mouse_pos: c.ImVec2) void {
return c.igTabBarQueueReorderFromMousePos(tab_bar, tab, mouse_pos);
}
pub fn tabBarProcessReorder(tab_bar: [*c]c.ImGuiTabBar) bool {
return c.igTabBarProcessReorder(tab_bar);
}
pub fn tabItemEx(tab_bar: [*c]c.ImGuiTabBar, label: [:0]const u8, p_open: ?*bool, flags: c.ImGuiTabItemFlags) bool {
return c.igTabItemEx(tab_bar, label, p_open, flags);
}
pub fn tabItemCalcSize(pOut: *c.ImVec2, label: [:0]const u8, has_close_button: bool) void {
return c.igTabItemCalcSize(pOut, label, has_close_button);
}
pub fn tabItemBackground(draw_list: *c.ImDrawList, bb: c.ImRect, flags: c.ImGuiTabItemFlags, col: c.ImU32) void {
return c.igTabItemBackground(draw_list, bb, flags, col);
}
pub fn tabItemLabelAndCloseButton(draw_list: *c.ImDrawList, bb: c.ImRect, flags: c.ImGuiTabItemFlags, frame_padding: c.ImVec2, label: [:0]const u8, tab_id: c.ImGuiID, close_button_id: c.ImGuiID, is_contents_visible: bool, out_just_closed: *bool, out_text_clipped: [*c]bool) void {
return c.igTabItemLabelAndCloseButton(draw_list, bb, flags, frame_padding, label, tab_id, close_button_id, is_contents_visible, out_just_closed, out_text_clipped);
}
// Render helpers
// AVOID USING OUTSIDE OF IMGUI.CPP! NOT FOR PUBLIC CONSUMPTION. THOSE FUNCTIONS ARE A MESS. THEIR SIGNATURE AND BEHAVIOR WILL CHANGE, THEY NEED TO BE REFACTORED INTO SOMETHING DECENT.
// NB: All position are in absolute pixels coordinates (we are never using window coordinates internally)
pub fn renderText(pos: c.ImVec2, _text: [*c]const u8, text_end: [*c]const u8, hide_text_after_hash: bool) void {
return c.igRenderText(pos, _text, text_end, hide_text_after_hash);
}
pub fn renderTextWrapped(pos: c.ImVec2, _text: [*c]const u8, text_end: [*c]const u8, wrap_width: f32) void {
return c.igRenderTextWrapped(pos, _text, text_end, wrap_width);
}
pub fn renderTextClipped(pos_min: c.ImVec2, pos_max: c.ImVec2, _text: [*c]const u8, text_end: [*c]const u8, text_size_if_known: *const c.ImVec2, @"align": c.ImVec2, clip_rect: [*c]const c.ImRect) void {
return c.igRenderTextClipped(pos_min, pos_max, _text, text_end, text_size_if_known, @"align", clip_rect);
}
pub fn renderTextClippedEx(draw_list: *c.ImDrawList, pos_min: c.ImVec2, pos_max: c.ImVec2, _text: [*c]const u8, text_end: [*c]const u8, text_size_if_known: *const c.ImVec2, @"align": c.ImVec2, clip_rect: [*c]const c.ImRect) void {
return c.igRenderTextClippedEx(draw_list, pos_min, pos_max, _text, text_end, text_size_if_known, @"align", clip_rect);
}
pub fn renderTextEllipsis(draw_list: *c.ImDrawList, pos_min: c.ImVec2, pos_max: c.ImVec2, clip_max_x: f32, ellipsis_max_x: f32, _text: [*c]const u8, text_end: [*c]const u8, text_size_if_known: [*c]const c.ImVec2) void {
return c.igRenderTextEllipsis(draw_list, pos_min, pos_max, clip_max_x, ellipsis_max_x, _text, text_end, text_size_if_known);
}
pub fn renderFrame(p_min: c.ImVec2, p_max: c.ImVec2, fill_col: c.ImU32, border: bool, rounding: f32) void {
return c.igRenderFrame(p_min, p_max, fill_col, border, rounding);
}
pub fn renderFrameBorder(p_min: c.ImVec2, p_max: c.ImVec2, rounding: f32) void {
return c.igRenderFrameBorder(p_min, p_max, rounding);
}
pub fn renderColorRectWithAlphaCheckerboard(draw_list: *c.ImDrawList, p_min: c.ImVec2, p_max: c.ImVec2, fill_col: c.ImU32, grid_step: f32, grid_off: c.ImVec2, rounding: f32, flags: c.ImDrawFlags) void {
return c.igRenderColorRectWithAlphaCheckerboard(draw_list, p_min, p_max, fill_col, grid_step, grid_off, rounding, flags);
}
pub fn renderNavHighlight(bb: c.ImRect, id: c.ImGuiID, flags: c.ImGuiNavHighlightFlags) void {
return c.igRenderNavHighlight(bb, id, flags);
}
pub fn findRenderedTextEnd(_text: [*c]const u8, text_end: [*c]const u8) [*c]const u8 {
return c.igFindRenderedTextEnd(_text, text_end);
}
// Render helpers (those functions don't access any ImGui state!)
pub fn renderArrow(draw_list: *c.ImDrawList, pos: c.ImVec2, col: c.ImU32, dir: c.ImGuiDir, scale: f32) void {
return c.igRenderArrow(draw_list, pos, col, dir, scale);
}
pub fn renderBullet(draw_list: *c.ImDrawList, pos: c.ImVec2, col: c.ImU32) void {
return c.igRenderBullet(draw_list, pos, col);
}
pub fn renderCheckMark(draw_list: *c.ImDrawList, pos: c.ImVec2, col: c.ImU32, sz: f32) void {
return c.igRenderCheckMark(draw_list, pos, col, sz);
}
pub fn renderMouseCursor(draw_list: *c.ImDrawList, pos: c.ImVec2, scale: f32, mouse_cursor: c.ImGuiMouseCursor, col_fill: c.ImU32, col_border: c.ImU32, col_shadow: c.ImU32) void {
return c.igRenderMouseCursor(draw_list, pos, scale, mouse_cursor, col_fill, col_border, col_shadow);
}
pub fn renderArrowPointingAt(draw_list: *c.ImDrawList, pos: c.ImVec2, half_sz: c.ImVec2, direction: c.ImGuiDir, col: c.ImU32) void {
return c.igRenderArrowPointingAt(draw_list, pos, half_sz, direction, col);
}
pub fn renderRectFilledRangeH(draw_list: *c.ImDrawList, rect: c.ImRect, col: c.ImU32, x_start_norm: f32, x_end_norm: f32, rounding: f32) void {
return c.igRenderRectFilledRangeH(draw_list, rect, col, x_start_norm, x_end_norm, rounding);
}
pub fn renderRectFilledWithHole(draw_list: *c.ImDrawList, outer: c.ImRect, inner: c.ImRect, col: c.ImU32, rounding: f32) void {
return c.igRenderRectFilledWithHole(draw_list, outer, inner, col, rounding);
}
// Widgets
pub fn textEx(_text: [*c]const u8, text_end: [*c]const u8, flags: c.ImGuiTextFlags) void {
return c.igTextEx(_text, text_end, flags);
}
pub fn buttonEx(label: [:0]const u8, size_arg: c.ImVec2, flags: c.ImGuiButtonFlags) bool {
return c.igButtonEx(label, size_arg, flags);
}
pub fn closeButton(id: c.ImGuiID, pos: c.ImVec2) bool {
return c.igCloseButton(id, pos);
}
pub fn collapseButton(id: c.ImGuiID, pos: c.ImVec2) bool {
return c.igCollapseButton(id, pos);
}
pub fn arrowButtonEx(str_id: [:0]const u8, dir: c.ImGuiDir, size_arg: c.ImVec2, flags: c.ImGuiButtonFlags) bool {
return c.igArrowButtonEx(str_id, dir, size_arg, flags);
}
pub fn scrollbar(axis: c.ImGuiAxis) void {
return c.igScrollbar(axis);
}
pub fn scrollbarEx(bb: c.ImRect, id: c.ImGuiID, axis: c.ImGuiAxis, p_scroll_v: *i64, avail_v: i64, contents_v: i64, flags: c.ImDrawFlags) bool {
return c.igScrollbarEx(bb, id, axis, p_scroll_v, avail_v, contents_v, flags);
}
pub fn imageButtonEx(id: c.ImGuiID, texture_id: c.ImTextureID, size: c.ImVec2, uv0: c.ImVec2, uv1: c.ImVec2, padding: c.ImVec2, bg_col: c.ImVec4, tint_col: c.ImVec4) bool {
return c.igImageButtonEx(id, texture_id, size, uv0, uv1, padding, bg_col, tint_col);
}
pub fn getWindowScrollbarRect(pOut: *c.ImRect, window: ?*c.ImGuiWindow, axis: c.ImGuiAxis) void {
return c.igGetWindowScrollbarRect(pOut, window, axis);
}
pub fn getWindowScrollbarID(window: ?*c.ImGuiWindow, axis: c.ImGuiAxis) c.ImGuiID {
return c.igGetWindowScrollbarID(window, axis);
}
pub fn getWindowResizeCornerID(window: ?*c.ImGuiWindow, n: c_int) c.ImGuiID {
return c.igGetWindowResizeCornerID(window, n);
}
pub fn getWindowResizeBorderID(window: ?*c.ImGuiWindow, dir: c.ImGuiDir) c.ImGuiID {
return c.igGetWindowResizeBorderID(window, dir);
}
pub fn separatorEx(flags: c.ImGuiSeparatorFlags) void {
return c.igSeparatorEx(flags);
}
pub fn checkboxFlags_S64Ptr(label: [:0]const u8, flags: *c.ImS64, flags_value: c.ImS64) bool {
return c.igCheckboxFlags_S64Ptr(label, flags, flags_value);
}
pub fn checkboxFlags_U64Ptr(label: [:0]const u8, flags: *c.ImU64, flags_value: c.ImU64) bool {
return c.igCheckboxFlags_U64Ptr(label, flags, flags_value);
}
// Widgets low-level behaviors
pub fn buttonBehavior(bb: c.ImRect, id: c.ImGuiID, out_hovered: *bool, out_held: *bool, flags: c.ImGuiButtonFlags) bool {
return c.igButtonBehavior(bb, id, out_hovered, out_held, flags);
}
pub fn dragBehavior(id: c.ImGuiID, data_type: c.ImGuiDataType, p_v: ?*anyopaque, v_speed: f32, p_min: ?*const anyopaque, p_max: ?*const anyopaque, format: [:0]const u8, flags: c.ImGuiSliderFlags) bool {
return c.igDragBehavior(id, data_type, p_v, v_speed, p_min, p_max, format, flags);
}
pub fn sliderBehavior(bb: c.ImRect, id: c.ImGuiID, data_type: c.ImGuiDataType, p_v: ?*anyopaque, p_min: ?*const anyopaque, p_max: ?*const anyopaque, format: [:0]const u8, flags: c.ImGuiSliderFlags, out_grab_bb: [*c]c.ImRect) bool {
return c.igSliderBehavior(bb, id, data_type, p_v, p_min, p_max, format, flags, out_grab_bb);
}
pub fn splitterBehavior(bb: c.ImRect, id: c.ImGuiID, axis: c.ImGuiAxis, size1: *f32, size2: *f32, min_size1: f32, min_size2: f32, hover_extend: f32, hover_visibility_delay: f32) bool {
return c.igSplitterBehavior(bb, id, axis, size1, size2, min_size1, min_size2, hover_extend, hover_visibility_delay);
}
pub fn treeNodeBehavior(id: c.ImGuiID, flags: c.ImGuiTreeNodeFlags, label: [:0]const u8, label_end: [*c]const u8) bool {
return c.igTreeNodeBehavior(id, flags, label, label_end);
}
pub fn treeNodeBehaviorIsOpen(id: c.ImGuiID, flags: c.ImGuiTreeNodeFlags) bool {
return c.igTreeNodeBehaviorIsOpen(id, flags);
}
pub fn treePushOverrideID(id: c.ImGuiID) void {
return c.igTreePushOverrideID(id);
}
// Data type helpers
pub fn dataTypeGetInfo(data_type: c.ImGuiDataType) [*c]const c.ImGuiDataTypeInfo {
return c.igDataTypeGetInfo(data_type);
}
pub fn dataTypeFormatString(buf: [*c]u8, buf_size: c_int, data_type: c.ImGuiDataType, p_data: ?*const anyopaque, format: [:0]const u8) c_int {
return c.igDataTypeFormatString(buf, buf_size, data_type, p_data, format);
}
pub fn dataTypeApplyOp(data_type: c.ImGuiDataType, op: c_int, output: ?*anyopaque, arg_1: ?*const anyopaque, arg_2: ?*const anyopaque) void {
return c.igDataTypeApplyOp(data_type, op, output, arg_1, arg_2);
}
pub fn dataTypeApplyOpFromText(buf: [*c]const u8, initial_value_buf: [*c]const u8, data_type: c.ImGuiDataType, p_data: ?*anyopaque, format: [:0]const u8) bool {
return c.igDataTypeApplyOpFromText(buf, initial_value_buf, data_type, p_data, format);
}
pub fn dataTypeCompare(data_type: c.ImGuiDataType, arg_1: ?*const anyopaque, arg_2: ?*const anyopaque) c_int {
return c.igDataTypeCompare(data_type, arg_1, arg_2);
}
pub fn dataTypeClamp(data_type: c.ImGuiDataType, p_data: ?*anyopaque, p_min: ?*const anyopaque, p_max: ?*const anyopaque) bool {
return c.igDataTypeClamp(data_type, p_data, p_min, p_max);
}
// InputText
pub fn inputTextEx(label: [:0]const u8, hint: [*c]const u8, buf: [*c]u8, buf_size: c_int, size_arg: c.ImVec2, flags: c.ImGuiInputTextFlags, callback: c.ImGuiInputTextCallback, user_data: ?*anyopaque) bool {
return c.igInputTextEx(label, hint, buf, buf_size, size_arg, flags, callback, user_data);
}
pub fn tempInputText(bb: c.ImRect, id: c.ImGuiID, label: [:0]const u8, buf: [*c]u8, buf_size: c_int, flags: c.ImGuiInputTextFlags) bool {
return c.igTempInputText(bb, id, label, buf, buf_size, flags);
}
pub fn tempInputScalar(bb: c.ImRect, id: c.ImGuiID, label: [:0]const u8, data_type: c.ImGuiDataType, p_data: ?*anyopaque, format: [:0]const u8, p_clamp_min: ?*const anyopaque, p_clamp_max: ?*const anyopaque) bool {
return c.igTempInputScalar(bb, id, label, data_type, p_data, format, p_clamp_min, p_clamp_max);
}
pub fn tempInputIsActive(id: c.ImGuiID) bool {
return c.igTempInputIsActive(id);
}
pub fn getInputTextState(id: c.ImGuiID) [*c]c.ImGuiInputTextState {
return c.igGetInputTextState(id);
}
// Color
pub fn colorTooltip(_text: [*c]const u8, col: *const f32, flags: c.ImGuiColorEditFlags) void {
return c.igColorTooltip(_text, col, flags);
}
pub fn colorEditOptionsPopup(col: *const f32, flags: c.ImGuiColorEditFlags) void {
return c.igColorEditOptionsPopup(col, flags);
}
pub fn colorPickerOptionsPopup(ref_col: *const f32, flags: c.ImGuiColorEditFlags) void {
return c.igColorPickerOptionsPopup(ref_col, flags);
}
// Plot
pub fn plotEx(plot_type: c.ImGuiPlotType, label: [:0]const u8, values_getter: fn (?*anyopaque, c_int) callconv(.C) f32, data: ?*anyopaque, values_count: c_int, values_offset: c_int, overlay_text: [*c]const u8, scale_min: f32, scale_max: f32, frame_size: c.ImVec2) c_int {
return c.igPlotEx(plot_type, label, values_getter, data, values_count, values_offset, overlay_text, scale_min, scale_max, frame_size);
}
// Shade functions (write over already created vertices)
pub fn shadeVertsLinearColorGradientKeepAlpha(draw_list: *c.ImDrawList, vert_start_idx: c_int, vert_end_idx: c_int, gradient_p0: c.ImVec2, gradient_p1: c.ImVec2, col0: c.ImU32, col1: c.ImU32) void {
return c.igShadeVertsLinearColorGradientKeepAlpha(draw_list, vert_start_idx, vert_end_idx, gradient_p0, gradient_p1, col0, col1);
}
pub fn shadeVertsLinearUV(draw_list: *c.ImDrawList, vert_start_idx: c_int, vert_end_idx: c_int, a: c.ImVec2, b: c.ImVec2, uv_a: c.ImVec2, uv_b: c.ImVec2, _clamp: bool) void {
return c.igShadeVertsLinearUV(draw_list, vert_start_idx, vert_end_idx, a, b, uv_a, uv_b, _clamp);
}
// Garbage collection
pub const gcCompactTransientMiscBuffers = c.igGcCompactTransientMiscBuffers;
pub fn gcCompactTransientWindowBuffers(window: ?*c.ImGuiWindow) void {
return c.igGcCompactTransientWindowBuffers(window);
}
pub fn gcAwakeTransientWindowBuffers(window: ?*c.ImGuiWindow) void {
return c.igGcAwakeTransientWindowBuffers(window);
}
// Debug Tools
pub fn errorCheckEndFrameRecover(log_callback: c.ImGuiErrorLogCallback, user_data: ?*anyopaque) void {
return c.igErrorCheckEndFrameRecover(log_callback, user_data);
}
pub fn errorCheckEndWindowRecover(log_callback: c.ImGuiErrorLogCallback, user_data: ?*anyopaque) void {
return c.igErrorCheckEndWindowRecover(log_callback, user_data);
}
pub fn debugDrawItemRect(col: c.ImU32) void {
return c.igDebugDrawItemRect(col);
}
pub const debugStartItemPicker = c.igDebugStartItemPicker;
pub fn showFontAtlas(atlas: [*c]c.ImFontAtlas) void {
return c.igShowFontAtlas(atlas);
}
pub fn debugHookIdInfo(id: c.ImGuiID, data_type: c.ImGuiDataType, data_id: []u8) void {
return c.igDebugHookIdInfo(id, data_type, data_id.ptr, data_id.ptr + data_id.len);
}
pub fn debugNodeColumns(_columns: *c.ImGuiOldColumns) void {
return c.igDebugNodeColumns(_columns);
}
pub fn debugNodeDrawList(window: ?*c.ImGuiWindow, draw_list: *const c.ImDrawList, label: [:0]const u8) void {
return c.igDebugNodeDrawList(window, draw_list, label);
}
pub fn debugNodeDrawCmdShowMeshAndBoundingBox(
out_draw_list: *c.ImDrawList,
draw_list: *const c.ImDrawList,
draw_cmd: *const c.ImDrawCmd,
show_mesh: bool,
show_aabb: bool,
) void {
return c.igDebugNodeDrawCmdShowMeshAndBoundingBox(out_draw_list, draw_list, draw_cmd, show_mesh, show_aabb);
}
pub fn debugNodeFont(font: *c.ImFont) void {
return c.igDebugNodeFont(font);
}
pub fn debugNodeStorage(storage: *c.ImGuiStorage, label: [:0]const u8) void {
return c.igDebugNodeStorage(storage, label);
}
pub fn debugNodeTabBar(tab_bar: *c.ImGuiTabBar, label: [:0]const u8) void {
return c.igDebugNodeTabBar(tab_bar, label);
}
pub fn debugNodeTable(table: *c.ImGuiTable) void {
return c.igDebugNodeTable(table);
}
pub fn debugNodeTableSettings(settings: *c.ImGuiTableSettings) void {
return c.igDebugNodeTableSettings(settings);
}
pub fn debugNodeWindow(window: *c.ImGuiWindow, label: [:0]const u8) void {
return c.igDebugNodeWindow(window, label);
}
pub fn debugNodeWindowSettings(settings: *c.ImGuiWindowSettings) void {
return c.igDebugNodeWindowSettings(settings);
}
pub fn debugNodeWindowsList(windows: *c.ImVector_ImGuiWindowPtr, label: [:0]const u8) void {
return c.igDebugNodeWindowsList(windows, label);
}
pub fn debugNodeViewport(viewport: *c.ImGuiViewportP) void {
return c.igDebugNodeViewport(viewport);
}
pub fn debugRenderViewportThumbnail(draw_list: *c.ImDrawList, viewport: *c.ImGuiViewportP, bb: c.ImRect) void {
return c.igDebugRenderViewportThumbnail(draw_list, viewport, bb);
}
};
/// ImFontAtlas internal API
pub const fontatlas = struct {
// Helper for font builder
pub const getBuilderForStbTruetype = c.igImFontAtlasGetBuilderForStbTruetype;
pub fn buildInit(atlas: *c.ImFontAtlas) void {
return c.igImFontAtlasBuildInit(atlas);
}
pub fn buildSetupFont(atlas: *c.ImFontAtlas, font: *c.ImFont, font_config: *c.ImFontConfig, ascent: f32, descent: f32) void {
return c.igImFontAtlasBuildSetupFont(atlas, font, font_config, ascent, descent);
}
pub fn buildPackCustomRects(atlas: *c.ImFontAtlas, stbrp_context_opaque: ?*anyopaque) void {
return c.igImFontAtlasBuildPackCustomRects(atlas, stbrp_context_opaque);
}
pub fn buildFinish(atlas: *c.ImFontAtlas) void {
return c.igImFontAtlasBuildFinish(atlas);
}
pub fn buildRender8bppRectFromString(atlas: *c.ImFontAtlas, x: c_int, y: c_int, w: c_int, h: c_int, in_str: [*c]const u8, in_marker_char: u8, in_marker_pixel_value: u8) void {
return c.igImFontAtlasBuildRender8bppRectFromString(atlas, x, y, w, h, in_str, in_marker_char, in_marker_pixel_value);
}
pub fn buildRender32bppRectFromString(atlas: *c.ImFontAtlas, x: c_int, y: c_int, w: c_int, h: c_int, in_str: [*c]const u8, in_marker_char: u8, in_marker_pixel_value: c_uint) void {
return c.igImFontAtlasBuildRender32bppRectFromString(atlas, x, y, w, h, in_str, in_marker_char, in_marker_pixel_value);
}
pub fn buildMultiplyCalcLookupTable(out_table: [*c]u8, in_multiply_factor: f32) void {
return c.igImFontAtlasBuildMultiplyCalcLookupTable(out_table, in_multiply_factor);
}
pub fn buildMultiplyRectAlpha8(table: [*c]const u8, pixels: [*c]u8, x: c_int, y: c_int, w: c_int, h: c_int, stride: c_int) void {
return c.igImFontAtlasBuildMultiplyRectAlpha8(table, pixels, x, y, w, h, stride);
}
};
|
src/deps/imgui/api.zig
|