code
stringlengths
235
11.6M
repo_path
stringlengths
3
263
const getty = @import("getty"); const std = @import("std"); const eql = std.mem.eql; const testing = std.testing; const expect = testing.expect; const expectEqual = testing.expectEqual; const expectEqualSlices = testing.expectEqualSlices; const expectError = testing.expectError; pub const de = struct { pub fn free(allocator: std.mem.Allocator, value: anytype) void { return getty.de.free(allocator, value); } }; pub const Deserializer = @import("de/deserializer.zig").Deserializer; pub fn fromDeserializer(comptime T: type, d: *Deserializer) !T { const value = try getty.deserialize(d.allocator, T, d.deserializer()); errdefer if (d.allocator) |alloc| de.free(alloc, value); try d.end(); return value; } pub fn fromDeserializerWith(comptime T: type, d: *Deserializer, _de: anytype) !T { const value = try getty.deserializeWith(d.allocator, T, d.deserializer(), _de); errdefer if (d.allocator) |alloc| de.free(alloc, value); try d.end(); return value; } pub fn fromSlice(allocator: ?std.mem.Allocator, comptime T: type, slice: []const u8) !T { var d = if (allocator) |alloc| Deserializer.withAllocator(alloc, slice) else Deserializer.init(slice); return fromDeserializer(T, &d); } pub fn fromSliceWith(allocator: ?std.mem.Allocator, comptime T: type, slice: []const u8, _de: anytype) !T { var d = if (allocator) |alloc| Deserializer.withAllocator(alloc, slice) else Deserializer.init(slice); return fromDeserializerWith(T, &d, _de); } test "array" { try expectEqual([0]bool{}, try fromSlice(null, [0]bool, "[]")); try expectEqual([1]bool{true}, try fromSlice(null, [1]bool, "[true]")); try expectEqual([2]bool{ true, false }, try fromSlice(null, [2]bool, "[true,false]")); try expectEqual([5]i32{ 1, 2, 3, 4, 5 }, try fromSlice(null, [5]i32, "[1,2,3,4,5]")); try expectEqual([2][1]i32{ .{1}, .{2} }, try fromSlice(null, [2][1]i32, "[[1],[2]]")); try expectEqual([2][1][3]i32{ .{.{ 1, 2, 3 }}, .{.{ 4, 5, 6 }} }, try fromSlice(null, [2][1][3]i32, "[[[1,2,3]],[[4,5,6]]]")); } test "array list" { // scalar child { const got = try fromSlice(testing.allocator, std.ArrayList(u8), "[1,2,3,4,5]"); defer got.deinit(); try expectEqual(std.ArrayList(u8), @TypeOf(got)); try expect(eql(u8, &[_]u8{ 1, 2, 3, 4, 5 }, got.items)); } // array list child { const got = try fromSlice(testing.allocator, std.ArrayList(std.ArrayList(u8)), "[[1, 2],[3,4]]"); defer de.free(testing.allocator, got); try expectEqual(std.ArrayList(std.ArrayList(u8)), @TypeOf(got)); try expectEqual(std.ArrayList(u8), @TypeOf(got.items[0])); try expectEqual(std.ArrayList(u8), @TypeOf(got.items[1])); try expect(eql(u8, &[_]u8{ 1, 2 }, got.items[0].items)); try expect(eql(u8, &[_]u8{ 3, 4 }, got.items[1].items)); } } test "bool" { try expectEqual(true, try fromSlice(null, bool, "true")); try expectEqual(false, try fromSlice(null, bool, "false")); } test "enum" { const Enum = enum { foo, bar }; try expectEqual(Enum.foo, try fromSlice(null, Enum, "0")); try expectEqual(Enum.bar, try fromSlice(null, Enum, "1")); try expectEqual(Enum.foo, try fromSlice(testing.allocator, Enum, "\"foo\"")); try expectEqual(Enum.bar, try fromSlice(testing.allocator, Enum, "\"bar\"")); } test "float" { try expectEqual(@as(f32, std.math.f32_min), try fromSlice(null, f32, "1.17549435082228750797e-38")); try expectEqual(@as(f32, std.math.f32_max), try fromSlice(null, f32, "3.40282346638528859812e+38")); try expectEqual(@as(f64, std.math.f64_min), try fromSlice(null, f64, "2.2250738585072014e-308")); try expectEqual(@as(f64, std.math.f64_max), try fromSlice(null, f64, "1.79769313486231570815e+308")); try expectEqual(@as(f32, 1.0), try fromSlice(null, f32, "1")); try expectEqual(@as(f64, 2.0), try fromSlice(null, f64, "2")); } test "int" { try expectEqual(@as(u8, std.math.maxInt(u8)), try fromSlice(null, u8, "255")); try expectEqual(@as(u32, std.math.maxInt(u32)), try fromSlice(null, u32, "4294967295")); try expectEqual(@as(u64, std.math.maxInt(u64)), try fromSlice(null, u64, "18446744073709551615")); try expectEqual(@as(i8, std.math.maxInt(i8)), try fromSlice(null, i8, "127")); try expectEqual(@as(i32, std.math.maxInt(i32)), try fromSlice(null, i32, "2147483647")); try expectEqual(@as(i64, std.math.maxInt(i64)), try fromSlice(null, i64, "9223372036854775807")); try expectEqual(@as(i8, std.math.minInt(i8)), try fromSlice(null, i8, "-128")); try expectEqual(@as(i32, std.math.minInt(i32)), try fromSlice(null, i32, "-2147483648")); try expectEqual(@as(i64, std.math.minInt(i64)), try fromSlice(null, i64, "-9223372036854775808")); // TODO: higher-bit conversions from float don't seem to work. } test "optional" { try expectEqual(@as(?bool, null), try fromSlice(null, ?bool, "null")); try expectEqual(@as(?bool, true), try fromSlice(null, ?bool, "true")); } test "pointer" { // one level of indirection { const value = try fromSlice(testing.allocator, *bool, "true"); defer de.free(testing.allocator, value); try expectEqual(true, value.*); } // two levels of indirection { const value = try fromSlice(testing.allocator, **[]const u8, "\"Hello, World!\""); defer de.free(testing.allocator, value); try expectEqualSlices(u8, "Hello, World!", value.*.*); } // enum { const T = enum { foo, bar }; // Tag value { const value = try fromSlice(testing.allocator, *T, "0"); defer de.free(testing.allocator, value); try expectEqual(T.foo, value.*); } // Tag name { const value = try fromSlice(testing.allocator, *T, "\"bar\""); defer de.free(testing.allocator, value); try expectEqual(T.bar, value.*); } } // optional { // some { const value = try fromSlice(testing.allocator, *?bool, "true"); defer de.free(testing.allocator, value); try expectEqual(true, value.*.?); } // none { const value = try fromSlice(testing.allocator, *?bool, "null"); defer de.free(testing.allocator, value); try expectEqual(false, value.* orelse false); } } // sequence { const value = try fromSlice(testing.allocator, *[3]i8, "[1,2,3]"); defer de.free(testing.allocator, value); try expectEqual([_]i8{ 1, 2, 3 }, value.*); } // struct { const T = struct { x: i32, y: []const u8, z: *[]const u8 }; const value = try fromSlice(testing.allocator, *T, \\{"x":1,"y":"hello","z":"world"} ); defer de.free(testing.allocator, value); try expectEqual(@as(i32, 1), value.*.x); try expectEqualSlices(u8, "hello", value.*.y); try expectEqualSlices(u8, "world", value.*.z.*); } // void { const value = try fromSlice(testing.allocator, *void, "null"); defer de.free(testing.allocator, value); try expectEqual({}, value.*); } } test "slice (string)" { // Zig string const got = try fromSlice(testing.allocator, []const u8, "\"Hello, World!\""); defer de.free(testing.allocator, got); try expect(eql(u8, "Hello, World!", got)); // Non-zig string try expectError(error.InvalidType, fromSlice(testing.allocator, []i8, "\"Hello, World!\"")); } test "slice (non-string)" { // scalar child { const got = try fromSlice(testing.allocator, []i32, "[1,2,3,4,5]"); defer de.free(testing.allocator, got); try expectEqual([]i32, @TypeOf(got)); try expect(eql(i32, &[_]i32{ 1, 2, 3, 4, 5 }, got)); } // array child { const wants = .{ [3]u32{ 1, 2, 3 }, [3]u32{ 4, 5, 6 }, [3]u32{ 7, 8, 9 }, }; const got = try fromSlice(testing.allocator, [][3]u32, \\[[1,2,3],[4,5,6],[7,8,9]] ); defer de.free(testing.allocator, got); try expectEqual([][3]u32, @TypeOf(got)); inline for (wants) |want, i| try expect(eql(u32, &want, &got[i])); } // slice child { const wants = .{ [_]i8{ 1, 2, 3 }, [_]i8{ 4, 5 }, [_]i8{6}, [_]i8{ 7, 8, 9, 10 }, }; const got = try fromSlice(testing.allocator, [][]i8, \\[[1,2,3],[4,5],[6],[7,8,9,10]] ); defer de.free(testing.allocator, got); try expectEqual([][]i8, @TypeOf(got)); inline for (wants) |want, i| try expect(eql(i8, &want, got[i])); } // string child { const wants = .{ "Foo", "Bar", "Foobar", }; const got = try fromSlice(testing.allocator, [][]const u8, \\["Foo","Bar","Foobar"] ); defer de.free(testing.allocator, got); try expectEqual([][]const u8, @TypeOf(got)); inline for (wants) |want, i| { try expect(eql(u8, want, got[i])); } } } test "struct" { const got = try fromSlice(testing.allocator, struct { x: i32, y: []const u8 }, \\{"x":1,"y":"Hello"} ); defer de.free(testing.allocator, got); try expectEqual(@as(i32, 1), got.x); try expect(eql(u8, "Hello", got.y)); } test "void" { try expectEqual({}, try fromSlice(null, void, "null")); try testing.expectError(error.InvalidType, fromSlice(null, void, "true")); try testing.expectError(error.InvalidType, fromSlice(null, void, "1")); } test { testing.refAllDecls(@This()); }
src/de.zig
const __floattitf = @import("floattitf.zig").__floattitf; const testing = @import("std").testing; fn test__floattitf(a: i128, expected: f128) void { const x = __floattitf(a); testing.expect(x == expected); } test "floattitf" { if (@import("std").Target.current.os.tag == .windows) { // TODO https://github.com/ziglang/zig/issues/508 return error.SkipZigTest; } test__floattitf(0, 0.0); test__floattitf(1, 1.0); test__floattitf(2, 2.0); test__floattitf(20, 20.0); test__floattitf(-1, -1.0); test__floattitf(-2, -2.0); test__floattitf(-20, -20.0); test__floattitf(0x7FFFFF8000000000, 0x1.FFFFFEp+62); test__floattitf(0x7FFFFFFFFFFFF800, 0x1.FFFFFFFFFFFFEp+62); test__floattitf(0x7FFFFF0000000000, 0x1.FFFFFCp+62); test__floattitf(0x7FFFFFFFFFFFF000, 0x1.FFFFFFFFFFFFCp+62); test__floattitf(make_ti(0x8000008000000000, 0), -0x1.FFFFFEp+126); test__floattitf(make_ti(0x8000000000000800, 0), -0x1.FFFFFFFFFFFFEp+126); test__floattitf(make_ti(0x8000010000000000, 0), -0x1.FFFFFCp+126); test__floattitf(make_ti(0x8000000000001000, 0), -0x1.FFFFFFFFFFFFCp+126); test__floattitf(make_ti(0x8000000000000000, 0), -0x1.000000p+127); test__floattitf(make_ti(0x8000000000000001, 0), -0x1.FFFFFFFFFFFFFFFCp+126); test__floattitf(0x0007FB72E8000000, 0x1.FEDCBAp+50); test__floattitf(0x0007FB72EA000000, 0x1.FEDCBA8p+50); test__floattitf(0x0007FB72EB000000, 0x1.FEDCBACp+50); test__floattitf(0x0007FB72EBFFFFFF, 0x1.FEDCBAFFFFFFCp+50); test__floattitf(0x0007FB72EC000000, 0x1.FEDCBBp+50); test__floattitf(0x0007FB72E8000001, 0x1.FEDCBA0000004p+50); test__floattitf(0x0007FB72E6000000, 0x1.FEDCB98p+50); test__floattitf(0x0007FB72E7000000, 0x1.FEDCB9Cp+50); test__floattitf(0x0007FB72E7FFFFFF, 0x1.FEDCB9FFFFFFCp+50); test__floattitf(0x0007FB72E4000001, 0x1.FEDCB90000004p+50); test__floattitf(0x0007FB72E4000000, 0x1.FEDCB9p+50); test__floattitf(0x023479FD0E092DC0, 0x1.1A3CFE870496Ep+57); test__floattitf(0x023479FD0E092DA1, 0x1.1A3CFE870496D08p+57); test__floattitf(0x023479FD0E092DB0, 0x1.1A3CFE870496D8p+57); test__floattitf(0x023479FD0E092DB8, 0x1.1A3CFE870496DCp+57); test__floattitf(0x023479FD0E092DB6, 0x1.1A3CFE870496DBp+57); test__floattitf(0x023479FD0E092DBF, 0x1.1A3CFE870496DF8p+57); test__floattitf(0x023479FD0E092DC1, 0x1.1A3CFE870496E08p+57); test__floattitf(0x023479FD0E092DC7, 0x1.1A3CFE870496E38p+57); test__floattitf(0x023479FD0E092DC8, 0x1.1A3CFE870496E4p+57); test__floattitf(0x023479FD0E092DCF, 0x1.1A3CFE870496E78p+57); test__floattitf(0x023479FD0E092DD0, 0x1.1A3CFE870496E8p+57); test__floattitf(0x023479FD0E092DD1, 0x1.1A3CFE870496E88p+57); test__floattitf(0x023479FD0E092DD8, 0x1.1A3CFE870496ECp+57); test__floattitf(0x023479FD0E092DDF, 0x1.1A3CFE870496EF8p+57); test__floattitf(0x023479FD0E092DE0, 0x1.1A3CFE870496Fp+57); test__floattitf(make_ti(0x023479FD0E092DC0, 0), 0x1.1A3CFE870496Ep+121); test__floattitf(make_ti(0x023479FD0E092DA1, 1), 0x1.1A3CFE870496D08p+121); test__floattitf(make_ti(0x023479FD0E092DB0, 2), 0x1.1A3CFE870496D8p+121); test__floattitf(make_ti(0x023479FD0E092DB8, 3), 0x1.1A3CFE870496DCp+121); test__floattitf(make_ti(0x023479FD0E092DB6, 4), 0x1.1A3CFE870496DBp+121); test__floattitf(make_ti(0x023479FD0E092DBF, 5), 0x1.1A3CFE870496DF8p+121); test__floattitf(make_ti(0x023479FD0E092DC1, 6), 0x1.1A3CFE870496E08p+121); test__floattitf(make_ti(0x023479FD0E092DC7, 7), 0x1.1A3CFE870496E38p+121); test__floattitf(make_ti(0x023479FD0E092DC8, 8), 0x1.1A3CFE870496E4p+121); test__floattitf(make_ti(0x023479FD0E092DCF, 9), 0x1.1A3CFE870496E78p+121); test__floattitf(make_ti(0x023479FD0E092DD0, 0), 0x1.1A3CFE870496E8p+121); test__floattitf(make_ti(0x023479FD0E092DD1, 11), 0x1.1A3CFE870496E88p+121); test__floattitf(make_ti(0x023479FD0E092DD8, 12), 0x1.1A3CFE870496ECp+121); test__floattitf(make_ti(0x023479FD0E092DDF, 13), 0x1.1A3CFE870496EF8p+121); test__floattitf(make_ti(0x023479FD0E092DE0, 14), 0x1.1A3CFE870496Fp+121); test__floattitf(make_ti(0, 0xFFFFFFFFFFFFFFFF), 0x1.FFFFFFFFFFFFFFFEp+63); test__floattitf(make_ti(0x123456789ABCDEF0, 0x123456789ABC2801), 0x1.23456789ABCDEF0123456789ABC3p+124); test__floattitf(make_ti(0x123456789ABCDEF0, 0x123456789ABC3000), 0x1.23456789ABCDEF0123456789ABC3p+124); test__floattitf(make_ti(0x123456789ABCDEF0, 0x123456789ABC37FF), 0x1.23456789ABCDEF0123456789ABC3p+124); test__floattitf(make_ti(0x123456789ABCDEF0, 0x123456789ABC3800), 0x1.23456789ABCDEF0123456789ABC4p+124); test__floattitf(make_ti(0x123456789ABCDEF0, 0x123456789ABC4000), 0x1.23456789ABCDEF0123456789ABC4p+124); test__floattitf(make_ti(0x123456789ABCDEF0, 0x123456789ABC47FF), 0x1.23456789ABCDEF0123456789ABC4p+124); test__floattitf(make_ti(0x123456789ABCDEF0, 0x123456789ABC4800), 0x1.23456789ABCDEF0123456789ABC4p+124); test__floattitf(make_ti(0x123456789ABCDEF0, 0x123456789ABC4801), 0x1.23456789ABCDEF0123456789ABC5p+124); test__floattitf(make_ti(0x123456789ABCDEF0, 0x123456789ABC57FF), 0x1.23456789ABCDEF0123456789ABC5p+124); } fn make_ti(high: u64, low: u64) i128 { var result: u128 = high; result <<= 64; result |= low; return @bitCast(i128, result); }
lib/std/special/compiler_rt/floattitf_test.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 bufPrint = std.fmt.bufPrint; const matrix = @import("matrix.zig"); const Matrix = matrix.Matrix; const M44f32 = matrix.M44f32; const m44f32_unit = matrix.m44f32_unit; const ae = @import("modules/zig-approxeql/approxeql.zig"); const tc = @import("typeconversions.zig"); const misc = @import("modules/zig-misc/index.zig"); const testExpected = misc.testExpected; const degToRad = @import("degrad.zig").degToRad; const DBG = false; pub fn Vec(comptime T: type, comptime size: usize) type { if (@typeId(T) != TypeId.Float) @compileError("Vec only support TypeId.Floats at this time"); switch (size) { 2 => { return struct { const Self = @This(); pub data: [2]T, pub fn init(xp: T, yp: T) Self { return Self{ .data = []T{ xp, yp } }; } pub fn initVal(val: T) Self { return Vec(T, size).init(val, val); } pub fn x(pSelf: *const Self) T { return pSelf.data[0]; } pub fn y(pSelf: *const Self) T { return pSelf.data[1]; } pub fn set(pSelf: *Self, vx: T, vy: T) void { pSelf.setX(vx); pSelf.setY(vy); } pub fn setX(pSelf: *Self, v: T) void { pSelf.data[0] = v; } pub fn setY(pSelf: *Self, v: T) void { pSelf.data[1] = v; } pub fn eql(pSelf: *const Self, pOther: *const Self) bool { return pSelf.x() == pOther.x() and pSelf.y() == pOther.y(); } pub fn approxEql(pSelf: *const Self, pOther: *const Self, digits: usize) bool { return ae.approxEql(pSelf.x(), pOther.x(), digits) and ae.approxEql(pSelf.y(), pOther.y(), digits); } pub fn neg(pSelf: *const Self) Self { return Vec(T, size).init(-pSelf.x(), -pSelf.y()); } pub fn scale(pSelf: *const Self, factor: T) Self { return Vec(T, size).init(pSelf.x() * factor, pSelf.y() * factor); } pub fn add(pSelf: *const Self, pOther: *const Self) Self { return Vec(T, size).init((pSelf.x() + pOther.x()), (pSelf.y() + pOther.y())); } pub fn sub(pSelf: *const Self, pOther: *const Self) Self { return Vec(T, size).init( (pSelf.x() - pOther.x()), (pSelf.y() - pOther.y()), ); } pub fn mul(pSelf: *const Self, pOther: *const Self) Self { return Vec(T, size).init( (pSelf.x() * pOther.x()), (pSelf.y() * pOther.y()), ); } pub fn div(pSelf: *const Self, pOther: *const Self) Self { return Vec(T, size).init( (pSelf.x() / pOther.x()), (pSelf.y() / pOther.y()), ); } /// Returns the length as a f64, f32 or f16 pub fn length(pSelf: *const Self) T { return math.sqrt(pSelf.normal()); } pub fn dot(pSelf: *const Self, pOther: *const Self) T { return (pSelf.x() * pOther.x()) + (pSelf.y() * pOther.y()); } pub fn normal(pSelf: *const Self) T { return (pSelf.x() * pSelf.x()) + (pSelf.y() * pSelf.y()); } pub fn normalize(pSelf: *const Self) Self { var len = pSelf.length(); var v: Self = undefined; if (len > 0) { v.setX(pSelf.x() / len); v.setY(pSelf.y() / len); } else { v = pSelf.*; } return v; } // The cross product of 2D vectors returns the signed magnitude of the // z component if we assume the 2D vectors are in the xy plane of a 3D // coordinate space and thus each have a z component of 0. pub fn cross(pSelf: *const Self, pOther: *const Self) T { return (pSelf.x() * pOther.y()) - (pSelf.y() * pOther.x()); } /// Custom format routine pub fn format( self: *const Self, comptime fmt: []const u8, context: var, comptime FmtError: type, output: fn (@typeOf(context), []const u8) FmtError!void, ) FmtError!void { try formatVec(T, size, self, fmt, context, FmtError, output); } }; }, 3 => { return struct { const Self = @This(); pub data: [3]T, pub fn init(xp: T, yp: T, zp: T) Self { return Self{ .data = []T{ xp, yp, zp } }; } pub fn initVal(val: T) Self { return Vec(T, size).init(val, val, val); } pub fn unitX() Self { return Self.init(1, 0, 0); } pub fn unitY() Self { return Self.init(0, 1, 0); } pub fn unitZ() Self { return Self.init(0, 0, 1); } pub fn x(pSelf: *const Self) T { return pSelf.data[0]; } pub fn y(pSelf: *const Self) T { return pSelf.data[1]; } pub fn z(pSelf: *const Self) T { return pSelf.data[2]; } pub fn set(pSelf: *Self, vx: T, vy: T, vz: T) void { pSelf.setX(vx); pSelf.setY(vy); pSelf.setZ(vz); } pub fn setX(pSelf: *Self, v: T) void { pSelf.data[0] = v; } pub fn setY(pSelf: *Self, v: T) void { pSelf.data[1] = v; } pub fn setZ(pSelf: *Self, v: T) void { pSelf.data[2] = v; } pub fn eql(pSelf: *const Self, pOther: *const Self) bool { return pSelf.x() == pOther.x() and pSelf.y() == pOther.y() and pSelf.z() == pOther.z(); } pub fn approxEql(pSelf: *const Self, pOther: *const Self, digits: usize) bool { return ae.approxEql(pSelf.x(), pOther.x(), digits) and ae.approxEql(pSelf.y(), pOther.y(), digits) and ae.approxEql(pSelf.z(), pOther.z(), digits); } pub fn neg(pSelf: *const Self) Self { return Vec(T, size).init(-pSelf.x(), -pSelf.y(), -pSelf.z()); } pub fn scale(pSelf: *const Self, factor: T) Self { return Vec(T, size).init(pSelf.x() * factor, pSelf.y() * factor, pSelf.z() * factor); } pub fn add(pSelf: *const Self, pOther: *const Self) Self { return Vec(T, size).init( (pSelf.x() + pOther.x()), (pSelf.y() + pOther.y()), (pSelf.z() + pOther.z()), ); } pub fn sub(pSelf: *const Self, pOther: *const Self) Self { return Vec(T, size).init( (pSelf.x() - pOther.x()), (pSelf.y() - pOther.y()), (pSelf.z() - pOther.z()), ); } pub fn mul(pSelf: *const Self, pOther: *const Self) Self { return Vec(T, size).init( (pSelf.x() * pOther.x()), (pSelf.y() * pOther.y()), (pSelf.z() * pOther.z()), ); } pub fn div(pSelf: *const Self, pOther: *const Self) Self { return Vec(T, size).init( (pSelf.x() / pOther.x()), (pSelf.y() / pOther.y()), (pSelf.z() / pOther.z()), ); } /// Returns the length as a f64, f32 or f16 pub fn length(pSelf: *const Self) T { return math.sqrt(pSelf.normal()); } pub fn dot(pSelf: *const Self, pOther: *const Self) T { return (pSelf.x() * pOther.x()) + (pSelf.y() * pOther.y()) + (pSelf.z() * pOther.z()); } pub fn normal(pSelf: *const Self) T { return (pSelf.x() * pSelf.x()) + (pSelf.y() * pSelf.y()) + (pSelf.z() * pSelf.z()); } pub fn normalize(pSelf: *const Self) Self { var len = pSelf.length(); var v: Self = undefined; if (len > 0) { v.setX(pSelf.x() / len); v.setY(pSelf.y() / len); v.setZ(pSelf.z() / len); } else { v = pSelf.*; } return v; } pub fn cross(pSelf: *const Self, pOther: *const Self) Self { return Vec(T, size).init( (pSelf.y() * pOther.z()) - (pSelf.z() * pOther.y()), (pSelf.z() * pOther.x()) - (pSelf.x() * pOther.z()), (pSelf.x() * pOther.y()) - (pSelf.y() * pOther.x()), ); } pub fn transform(pSelf: *const Self, m: *const Matrix(T, 4, 4)) Self { var vx = pSelf.x(); var vy = pSelf.y(); var vz = pSelf.z(); const rx = (vx * m.data[0][0]) + (vy * m.data[1][0]) + (vz * m.data[2][0]) + m.data[3][0]; const ry = (vx * m.data[0][1]) + (vy * m.data[1][1]) + (vz * m.data[2][1]) + m.data[3][1]; const rz = (vx * m.data[0][2]) + (vy * m.data[1][2]) + (vz * m.data[2][2]) + m.data[3][2]; var rw = (vx * m.data[0][3]) + (vy * m.data[1][3]) + (vz * m.data[2][3]) + m.data[3][3]; if (rw != 1) { rw = 1.0 / rw; } return Self.init(rx * rw, ry * rw, rz * rw); } pub fn transformNormal(pSelf: *const Self, m: *const Matrix(T, 4, 4)) Self { var vx = pSelf.x(); var vy = pSelf.y(); var vz = pSelf.z(); const rx = (vx * m.data[0][0]) + (vy * m.data[1][0]) + (vz * m.data[2][0]); const ry = (vx * m.data[0][1]) + (vy * m.data[1][1]) + (vz * m.data[2][1]); const rz = (vx * m.data[0][2]) + (vy * m.data[1][2]) + (vz * m.data[2][2]); return Self.init(rx, ry, rz); } /// Custom format routine pub fn format( self: *const Self, comptime fmt: []const u8, context: var, comptime FmtError: type, output: fn (@typeOf(context), []const u8) FmtError!void, ) FmtError!void { try formatVec(T, size, self, fmt, context, FmtError, output); } }; }, else => @compileError("Only Vec size 2 and 3 supported"), } } pub const V2f32 = Vec(f32, 2); pub const V3f32 = Vec(f32, 3); /// Custom format routine fn formatVec( comptime T: type, comptime size: usize, pSelf: *const Vec(T, size), comptime fmt: []const u8, context: var, comptime FmtError: type, output: fn (@typeOf(context), []const u8) FmtError!void, ) FmtError!void { try std.fmt.format(context, FmtError, output, "[]{} {{ ", @typeName(T)); for (pSelf.data) |col, i| { try std.fmt.format(context, FmtError, output, "{}{.5}{}", if (math.signbit(col)) "-" else " ", if (math.signbit(col)) -col else col, if (i < (pSelf.data.len - 1)) ", " else " "); } try std.fmt.format(context, FmtError, output, "}}"); } test "vec3.init" { const vf64 = Vec(f64, 3).initVal(0); assert(vf64.x() == 0); assert(vf64.y() == 0); assert(vf64.z() == 0); const vf32 = Vec(f32, 3).initVal(1); assert(vf32.x() == 1); assert(vf32.y() == 1); assert(vf32.z() == 1); var v1 = V3f32.init(1, 2, 3); assert(v1.x() == 1); assert(v1.y() == 2); assert(v1.z() == 3); v1 = V3f32.unitX(); assert(v1.x() == 1); assert(v1.y() == 0); assert(v1.z() == 0); v1 = V3f32.unitY(); assert(v1.x() == 0); assert(v1.y() == 1); assert(v1.z() == 0); v1 = V3f32.unitZ(); assert(v1.x() == 0); assert(v1.y() == 0); assert(v1.z() == 1); } test "vec3.copy" { var v1 = Vec(f32, 3).init(1, 2, 3); assert(v1.x() == 1); assert(v1.y() == 2); assert(v1.z() == 3); // Copy a vector var v2 = v1; assert(v2.x() == 1); assert(v2.y() == 2); assert(v2.z() == 3); // Copy via a pointer var pV1 = &v1; var v3 = pV1.*; assert(v3.x() == 1); assert(v3.y() == 2); assert(v3.z() == 3); } test "vec3.eql" { const v1 = Vec(f32, 3).init(1.2345678, 2.3456789, 3.4567890); const v2 = Vec(f32, 3).init(1.2345678, 2.3456789, 3.4567890); assert(v1.eql(&v2)); } test "vec3.approxEql" { const v1 = Vec(f32, 3).init(1.2345678, 2.3456789, 3.4567890); const v2 = Vec(f32, 3).init(1.2345600, 2.3456700, 3.4567800); assert(v1.approxEql(&v2, 1)); assert(v1.approxEql(&v2, 2)); assert(v1.approxEql(&v2, 3)); assert(v1.approxEql(&v2, 4)); assert(v1.approxEql(&v2, 5)); assert(v1.approxEql(&v2, 6)); assert(!v1.approxEql(&v2, 7)); assert(!v1.approxEql(&v2, 8)); } test "vec2.neg" { const v1 = V2f32.init(1, 2); const v2 = V2f32.init(-1, -2); assert(v2.eql(&v1.neg())); } test "vec3.neg" { const v1 = V3f32.init(1, 2, 3); const v2 = V3f32.init(-1, -2, -3); assert(v2.eql(&v1.neg())); } test "vec2.scale" { const factor = f32(0.5); const v1 = V2f32.init(1, 2); const v2 = V2f32.init(1 * factor, 2 * factor); assert(v2.eql(&v1.scale(factor))); } test "vec3.scale" { const factor = f32(0.5); const v1 = V3f32.init(1, 2, 3); const v2 = V3f32.init(1 * factor, 2 * factor, 3 * factor); assert(v2.eql(&v1.scale(factor))); } test "vec3.add" { const v1 = Vec(f32, 3).init(3, 2, 1); const v2 = Vec(f32, 3).init(1, 2, 3); const v3 = v1.add(&v2); assert(v3.x() == 4); assert(v3.y() == 4); assert(v3.z() == 4); } test "vec3.sub" { const v1 = Vec(f32, 3).init(3, 2, 1); const v2 = Vec(f32, 3).init(1, 2, 3); const v3 = v1.sub(&v2); assert(v3.x() == 2); assert(v3.y() == 0); assert(v3.z() == -2); } test "vec3.mul" { const v1 = Vec(f32, 3).init(3, 2, 1); const v2 = Vec(f32, 3).init(1, 2, 3); const v3 = v1.mul(&v2); assert(v3.x() == 3); assert(v3.y() == 4); assert(v3.z() == 3); } test "vec3.div" { const v1 = Vec(f32, 3).init(3, 2, 1); const v2 = Vec(f32, 3).init(1, 2, 3); const v3 = v1.div(&v2); assert(v3.x() == 3); assert(v3.y() == 1); assert(v3.z() == f32(1.0 / 3.0)); } test "vec2.format" { var buf: [100]u8 = undefined; const v2 = Vec(f32, 2).init(2, 1); var result = try bufPrint(buf[0..], "v2={}", v2); if (DBG) warn("\nvec.format: {}\n", result); assert(testExpected("v2=[]f32 { 2.00000, 1.00000 }", result)); } test "vec3.format" { var buf: [100]u8 = undefined; const v3 = Vec(f32, 3).init(3, 2, 1); var result = try bufPrint(buf[0..], "v3={}", v3); if (DBG) warn("vec3.format: {}\n", result); assert(testExpected("v3=[]f32 { 3.00000, 2.00000, 1.00000 }", result)); } test "vec2.length" { const x = f32(3); const y = f32(4); const v1 = V2f32.init(x, y); var len = v1.length(); if (DBG) warn("vec2.length: {}\n", len); assert(len == math.sqrt((x * x) + (y * y))); } test "vec3.length" { const x = f32(3); const y = f32(4); const z = f32(5); const v1 = V3f32.init(x, y, z); var len = v1.length(); if (DBG) warn("vec3.length: {}\n", len); assert(len == math.sqrt((x * x) + (y * y) + (z * z))); } test "vec3.dot" { if (DBG) warn("\n"); const v1 = Vec(f32, 3).init(3, 2, 1); const v2 = Vec(f32, 3).init(1, 2, 3); var d = v1.dot(&v2); if (DBG) warn("d={.3}\n", d); assert(d == (3 * 1) + (2 * 2) + (3 * 1)); // Sqrt of the dot product of itself is the length assert(math.sqrt(v2.dot(&v2)) == v2.length()); } test "vec3.normal" { var v0 = Vec(f32, 3).initVal(0); assert(v0.normal() == 0); v0 = Vec(f32, 3).init(4, 5, 6); assert(v0.normal() == 4 * 4 + 5 * 5 + 6 * 6); } test "vec3.normalize" { var v0 = Vec(f32, 3).initVal(0); var v1 = v0.normalize(); assert(v1.x() == 0); assert(v1.y() == 0); assert(v1.z() == 0); v0 = Vec(f32, 3).init(1, 1, 1); v1 = v0.normalize(); var len: f32 = math.sqrt(1.0 + 1.0 + 1.0); assert(v1.x() == 1.0 / len); assert(v1.y() == 1.0 / len); assert(v1.z() == 1.0 / len); } test "vec2.cross" { if (DBG) warn("\n"); var v3_1 = V3f32.init(1, 0, 0); var v3_2 = V3f32.init(0, 1, 0); // Calculate cross of a V3 in both dirctions var v3_cross = v3_1.cross(&v3_2); assert(v3_cross.x() == 0); assert(v3_cross.y() == 0); assert(v3_cross.z() == 1); // Assert cross of two v2's is equal v3_cross.z() var v2_1 = V2f32.init(1, 0); var v2_2 = V2f32.init(0, 1); assert(v2_1.cross(&v2_2) == v3_cross.z()); assert(v2_1.cross(&v2_2) == 1); // Change order and the sign's will be negative v3_cross = v3_2.cross(&v3_1); assert(v3_cross.x() == 0); assert(v3_cross.y() == 0); assert(v3_cross.z() == -1); assert(v2_2.cross(&v2_1) == v3_cross.z()); assert(v2_2.cross(&v2_1) == -1); // Check changing both signs v3_1.set(-1.0, 0.0, 0.0); v3_2.set(0.0, -1.0, 0.0); v2_1.set(-1.0, 0.0); v2_2.set(0.0, -1.0); assert(v2_1.cross(&v2_2) == v3_1.cross(&v3_2).z()); assert(v2_1.cross(&v2_2) == 1); assert(v2_2.cross(&v2_1) == v3_2.cross(&v3_1).z()); assert(v2_2.cross(&v2_1) == -1); // Check changing one sign v3_1.set(-1.0, 0.0, 0.0); v3_2.set(0.0, 1.0, 0.0); v2_1.set(-1.0, 0.0); v2_2.set(0.0, 1.0); assert(v2_1.cross(&v2_2) == v3_1.cross(&v3_2).z()); assert(v2_1.cross(&v2_2) == -1); assert(v2_2.cross(&v2_1) == v3_2.cross(&v3_1).z()); assert(v2_2.cross(&v2_1) == 1); // Check you don't need unit vectors v3_1.set(1.5, 1.5, 0.0); v3_2.set(2.5, 1.5, 0.0); v2_1.set(1.5, 1.5); v2_2.set(2.5, 1.5); assert(v2_1.cross(&v2_2) == v3_1.cross(&v3_2).z()); } test "vec3.cross" { if (DBG) warn("\n"); var v1 = Vec(f32, 3).init(1, 0, 0); // Unit Vector X var v2 = Vec(f32, 3).init(0, 1, 0); // Unit Vector Y // Cross product of two unit vectors on X,Y yields unit vector Z var v3 = v1.cross(&v2); assert(v3.x() == 0); assert(v3.y() == 0); assert(v3.z() == 1); v1 = V3f32.init(1.5, 2.5, 3.5); v2 = V3f32.init(4.5, 3.5, 2.5); v3 = v1.cross(&v2); if (DBG) warn("v3={}\n", &v3); assert(v3.eql(&V3f32.init( (v1.y() * v2.z()) - (v1.z() * v2.y()), (v1.z() * v2.x()) - (v1.x() * v2.z()), (v1.x() * v2.y()) - (v1.y() * v2.x()) )) ); v1 = Vec(f32, 3).init(3, 2, 1); v2 = Vec(f32, 3).init(1, 2, 3); v3 = v1.cross(&v2); assert(v3.x() == 4); assert(v3.y() == -8); assert(v3.z() == 4); // Changing the order yields neg. var v4 = v2.cross(&v1); assert(v3.x() == -v4.x()); assert(v3.y() == -v4.y()); assert(v3.z() == -v4.z()); assert(v4.eql(&v3.neg())); } test "vec3.transform" { if (DBG) warn("\n"); var v1 = V3f32.init(2, 3, 4); var v2 = v1.transform(&m44f32_unit); assert(v1.eql(&v2)); var m1 = M44f32.initVal(0.2); v1 = V3f32.init(0.5, 0.5, 0.5); v2 = v1.transform(&m1); if (DBG) warn("v1:\n{}\nm1:\n{}\nv2:\n{}\n", &v1, &m1, &v2); assert(v2.eql(&V3f32.init(1, 1, 1))); m1.data[3][3] = 1; v2 = v1.transform(&m1); if (DBG) warn("v1:\n{}\nm1:\n{}\nv2:\n{}\n", &v1, &m1, &v2); assert(v2.approxEql(&V3f32.init(0.3846154, 0.3846154, 0.3846154), 6)); } test "vec3.world.to.screen" { if (DBG) warn("\n"); const T = f32; const M44 = Matrix(T, 4, 4); const fov: T = 90; const widthf: T = 512; const heightf: T = 512; const width: u32 = @floatToInt(u32, 512); const height: u32 = @floatToInt(u32, 512); const aspect: T = widthf / heightf; const znear: T = 0.01; const zfar: T = 1.0; var camera_to_perspective_matrix = matrix.perspectiveM44(T, fov, aspect, znear, zfar); var world_to_camera_matrix = M44f32.initUnit(); world_to_camera_matrix.data[3][2] = 2; var world_vertexs = []V3f32{ V3f32.init(0, 1.0, 0), V3f32.init(0, -1.0, 0), V3f32.init(0, 1.0, 0.2), V3f32.init(0, -1.0, -0.2), }; var expected_camera_vertexs = []V3f32{ V3f32.init(0, 1.0, 2), V3f32.init(0, -1.0, 2.0), V3f32.init(0, 1.0, 2.2), V3f32.init(0, -1.0, 1.8), }; var expected_projected_vertexs = []V3f32{ V3f32.init(0, 0.30869, 1.00505), V3f32.init(0, -0.30869, 1.00505), V3f32.init(0, 0.28062, 1.00551), V3f32.init(0, -0.34298, 1.00449), }; var expected_screen_vertexs = [][2]u32{ []u32{ 256, 176 }, []u32{ 256, 335 }, []u32{ 256, 184 }, []u32{ 256, 343 }, }; for (world_vertexs) |world_vert, i| { if (DBG) warn("world_vert[{}] = {}\n", i, &world_vert); var camera_vert = world_vert.transform(&world_to_camera_matrix); if (DBG) warn("camera_vert = {}\n", camera_vert); assert(camera_vert.approxEql(&expected_camera_vertexs[i], 6)); var projected_vert = camera_vert.transform(&camera_to_perspective_matrix); if (DBG) warn("projected_vert = {}", projected_vert); assert(projected_vert.approxEql(&expected_projected_vertexs[i], 6)); var xf = projected_vert.x(); var yf = projected_vert.y(); if (DBG) warn(" {.3}:{.3}", xf, yf); if ((xf < -1) or (xf > 1) or (yf < -1) or (yf > 1)) { if (DBG) warn(" clipped\n"); } var x = @floatToInt(u32, math.min(widthf - 1, (xf + 1) * 0.5 * widthf)); var y = @floatToInt(u32, math.min(heightf - 1, (1 - (yf + 1) * 0.5) * heightf)); if (DBG) warn(" visible {}:{}\n", x, y); assert(x == expected_screen_vertexs[i][0]); assert(y == expected_screen_vertexs[i][1]); } }
vec.zig
usingnamespace @import("root").preamble; const PixelFormat = lib.graphics.pixel_format.PixelFormat; const Color = lib.graphics.color.Color; pub const InvalidateRectFunc = fn (r: *ImageRegion, x: usize, y: usize, width: usize, height: usize) void; pub const ImageRegion = struct { width: usize, height: usize, pixel_format: PixelFormat, bytes: []u8, pitch: usize, /// Function to call when a subregion of the image has been modified invalidateRectFunc: ?InvalidateRectFunc, // The following variables are managed by this struct and shouldn't be changed /// If the image is a less wide subregion() of any other ImageRegion /// means that the bytes between bpp*width and pitch can't be overwritten full_width: bool = true, // Offsets are needed for the invalidation callbacks for subregions x_offset: usize = 0, y_offset: usize = 0, pub fn subregion( self: *const @This(), x: usize, y: usize, width: usize, height: usize, ) @This() { if (x + width > self.width) unreachable; if (y + height > self.height) unreachable; return .{ .width = width, .height = height, .pixel_format = self.pixel_format, .bytes = self.startingAt(x, y), .pitch = self.pitch, .invalidateRectFunc = self.invalidateRectFunc, .full_width = self.full_width and width == self.width, .x_offset = self.x_offset + x, .y_offset = self.y_offset + y, }; } pub fn invalidateRect( self: *const @This(), x: usize, y: usize, width: usize, height: usize, ) void { if (x + width > self.width) unreachable; if (y + height > self.height) unreachable; if (self.invalidateRectFunc) |func| func(@intToPtr(*@This(), @ptrToInt(self)), x + self.x_offset, y + self.y_offset, width, height); } /// Draw a pixel to the region pub fn drawPixel( self: *const @This(), c: Color, x: usize, y: usize, comptime invalidate: bool, ) void { switch (self.pixel_format) { .rgb => self.drawPixelWithFormat(.rgb, c, x, y, invalidate), .rgba => self.drawPixelWithFormat(.rgba, c, x, y, invalidate), .rgbx => self.drawPixelWithFormat(.rgbx, c, x, y, invalidate), } } /// Draw a pixel, assuming the target format pub fn drawPixelWithFormat( self: *const @This(), comptime fmt: PixelFormat, c: Color, x: usize, y: usize, comptime invalidate: bool, ) void { if (x > self.width) unreachable; if (y > self.height) unreachable; if (fmt != self.pixel_format) unreachable; c.writeAsFmt(fmt, self.startingAt(x, y)); if (comptime invalidate) self.invalidateRect(x, y, 1, 1); } pub fn getPixel( self: *const @This(), x: usize, y: usize, ) Color { return switch (self.pixel_format) { .rgb => self.getPixelWithFormat(.rgb, x, y), .rgba => self.getPixelWithFormat(.rgba, x, y), .rgbx => self.getPixelWithFormat(.rgbx, x, y), }; } pub fn getPixelWithFormat(self: *const @This(), comptime fmt: PixelFormat, x: usize, y: usize) Color { if (x > self.width) unreachable; if (y > self.height) unreachable; if (fmt != self.pixel_format) unreachable; return readAsFmt(fmt, startingAt(x, y)); } pub fn fill( self: *const @This(), c: Color, x: usize, y: usize, width: usize, height: usize, comptime invalidate: bool, ) void { switch (self.pixel_format) { .rgb => self.fillWithFormat(.rgb, c, x, y, width, height, invalidate), .rgba => self.fillWithFormat(.rgba, c, x, y, width, height, invalidate), .rgbx => self.fillWithFormat(.rgbx, c, x, y, width, height, invalidate), } } pub fn fillWithFormat( target: *const @This(), comptime fmt: PixelFormat, c: Color, x: usize, y: usize, width: usize, height: usize, comptime invalidate: bool, ) void { if (!target.pixel_format.canWrite(fmt)) unreachable; if (width + x > target.width) unreachable; if (height + y > target.height) unreachable; // Can we memset (all bytes equal) when filing? if (c.memsetAsFmt(fmt)) |byte_value| { if (x == 0 and width == target.width and target.full_width) { lib.util.libalign.alignedFill(u32, target.startingAt(0, y)[0 .. height * target.pitch], byte_value); } else { var curr_y: usize = 0; var target_lines = target.startingAt(x, y); while (true) { const line = target_lines[0 .. width * comptime fmt.bytesPerPixel()]; lib.util.libalign.alignedFill(u32, line, byte_value); curr_y += 1; if (curr_y == height) break; target_lines = target_lines[target.pitch..]; } } } else { var pixel_bytes: [fmt.meaningfulBytesPerPixel()]u8 = undefined; c.writeAsFmt(fmt, &pixel_bytes); var curr_y: usize = 0; var target_lines = target.startingAt(x, y); while (true) { var curr_x: usize = 0; var target_pixels = target_lines; while (true) { lib.util.libalign.alignedCopy(u8, target_pixels, pixel_bytes[0..]); curr_x += 1; if (curr_x == width) break; target_pixels = target_pixels[comptime fmt.bytesPerPixel()..]; } curr_y += 1; if (curr_y == height) break; target_lines = target_lines[target.pitch..]; } } if (comptime invalidate) target.invalidateRect(x, y, width, height); } /// Assume both source and target formats pub fn drawImageWithFmt( target: *const @This(), comptime source_fmt: PixelFormat, comptime target_fmt: PixelFormat, source: ImageRegion, x: usize, y: usize, comptime invalidate: bool, ) void { // Check if the formats we're using are valid if (!source.pixel_format.canReadManyAs(source_fmt)) unreachable; if (!target.pixel_format.canWriteMany(target_fmt)) unreachable; // Bounds checks if (source.width + x > target.width) unreachable; if (source.height + y > target.height) unreachable; // Check if the input and output formats are bit-compatible if (comptime target_fmt.canWriteMany(source_fmt)) { // Can we copy the entire thing in one memcpy? if (source.pitch == target.pitch and source.full_width and target.full_width) { const num_bytes = source.pitch * source.height; lib.util.libalign.alignedCopy(u32, target.startingAt(x, y), source.bytes); } else { const num_bytes = source.width * comptime source_fmt.bytesPerPixel(); var source_bytes = source.bytes; var target_bytes = target.startingAt(x, y); var source_y: usize = 0; while (true) { lib.util.libalign.alignedCopy(u32, target_bytes, source_bytes[0..num_bytes]); source_y += 1; if (source_y == source.height) break; target_bytes = target_bytes[target.pitch..]; source_bytes = source_bytes[source.pitch..]; } } } // Fine, do one pixel at a time else { var source_lines = source.bytes; var target_lines = target.startingAt(x, y); var source_y: usize = 0; while (true) { var source_x: usize = 0; var source_pixels = source_lines; var target_pixels = target_lines; while (true) { if (comptime target_fmt.canWrite(source_fmt)) { const source_bytes = source_fmt.meaningfulBytesPerPixel(); const target_bytes = target_fmt.meaningfulBytesPerPixel(); const bytes_to_copy = std.math.min(source_bytes, target_bytes); lib.util.libalign.alignedCopy(u32, target_pixels, source_pixels[0..comptime bytes_to_copy]); } else { lib.graphics.color.Color.readAsFmt( source_fmt, source_pixels, ).writeAsFmt( target_fmt, target_pixels, ); } source_x += 1; if (source_x == source.width) break; source_pixels = source_pixels[comptime source_fmt.bytesPerPixel()..]; target_pixels = target_pixels[comptime target_fmt.bytesPerPixel()..]; } source_y += 1; if (source_y == source.height) break; source_lines = source_lines[source.pitch..]; target_lines = target_lines[target.pitch..]; } } if (comptime invalidate) target.invalidateRect(x, y, source.width, source.height); } // I wish I could use https://github.com/ziglang/zig/issues/7224 right now... /// Assume the sourcce format pub fn drawImageWithSourceFmt( self: *const @This(), comptime source_fmt: PixelFormat, source: ImageRegion, x: usize, y: usize, comptime invalidate: bool, ) void { switch (self.pixel_format) { .rgb => self.drawImageWithFmt(source_fmt, .rgb, source, x, y, invalidate), .rgba => self.drawImageWithFmt(source_fmt, .rgba, source, x, y, invalidate), .rgbx => self.drawImageWithFmt(source_fmt, .rgbx, source, x, y, invalidate), } } /// Assume the target format pub fn drawImageWithTargetFmt( self: *const @This(), comptime target_fmt: PixelFormat, source: ImageRegion, x: usize, y: usize, comptime invalidate: bool, ) void { switch (source.pixel_format) { .rgb => self.drawImageWithFmt(.rgb, target_fmt, source, x, y, invalidate), .rgba => self.drawImageWithFmt(.rgba, target_fmt, source, x, y, invalidate), .rgbx => self.drawImageWithFmt(.rgbx, target_fmt, source, x, y, invalidate), } } /// Assume the source and target pixel formats are equal pub fn drawImageSameFmt( self: *const @This(), source: ImageRegion, x: usize, y: usize, comptime invalidate: bool, ) void { switch (self.pixel_format) { .rgb => self.drawImageWithFmt(.rgb, .rgb, source, x, y, invalidate), .rgba => self.drawImageWithFmt(.rgba, .rgba, source, x, y, invalidate), .rgbx => self.drawImageWithFmt(.rgbx, .rgbx, source, x, y, invalidate), } } /// Draw the source image region to the target one pub fn drawImage( self: *const @This(), source: ImageRegion, x: usize, y: usize, comptime invalidate: bool, ) void { switch (self.pixel_format) { .rgb => self.drawImageWithTargetFmt(.rgb, source, x, y, invalidate), .rgba => self.drawImageWithTargetFmt(.rgba, source, x, y, invalidate), .rgbx => self.drawImageWithTargetFmt(.rgbx, source, x, y, invalidate), } } fn startingAt(self: *const @This(), x: usize, y: usize) []u8 { if (x > self.width) unreachable; if (y > self.height) unreachable; const offset = self.pixel_format.bytesPerPixel() * x + self.pitch * y; return self.bytes[offset..]; } };
lib/graphics/image_region.zig
const std = @import("../std.zig"); const math = std.math; const mem = std.mem; const assert = std.debug.assert; const testing = std.testing; const maxInt = math.maxInt; const Vector = std.meta.Vector; const Poly1305 = std.crypto.onetimeauth.Poly1305; // Vectorized implementation of the core function const ChaCha20VecImpl = struct { const Lane = Vector(4, u32); const BlockVec = [4]Lane; fn initContext(key: [8]u32, d: [4]u32) BlockVec { const c = "expand 32-byte k"; const constant_le = comptime Lane{ mem.readIntLittle(u32, c[0..4]), mem.readIntLittle(u32, c[4..8]), mem.readIntLittle(u32, c[8..12]), mem.readIntLittle(u32, c[12..16]), }; return BlockVec{ constant_le, Lane{ key[0], key[1], key[2], key[3] }, Lane{ key[4], key[5], key[6], key[7] }, Lane{ d[0], d[1], d[2], d[3] }, }; } inline fn chacha20Core(x: *BlockVec, input: BlockVec) void { x.* = input; var r: usize = 0; while (r < 20) : (r += 2) { x[0] +%= x[1]; x[3] ^= x[0]; x[3] = math.rotl(Lane, x[3], 16); x[2] +%= x[3]; x[1] ^= x[2]; x[1] = math.rotl(Lane, x[1], 12); x[0] +%= x[1]; x[3] ^= x[0]; x[0] = @shuffle(u32, x[0], undefined, [_]i32{ 3, 0, 1, 2 }); x[3] = math.rotl(Lane, x[3], 8); x[2] +%= x[3]; x[3] = @shuffle(u32, x[3], undefined, [_]i32{ 2, 3, 0, 1 }); x[1] ^= x[2]; x[2] = @shuffle(u32, x[2], undefined, [_]i32{ 1, 2, 3, 0 }); x[1] = math.rotl(Lane, x[1], 7); x[0] +%= x[1]; x[3] ^= x[0]; x[3] = math.rotl(Lane, x[3], 16); x[2] +%= x[3]; x[1] ^= x[2]; x[1] = math.rotl(Lane, x[1], 12); x[0] +%= x[1]; x[3] ^= x[0]; x[0] = @shuffle(u32, x[0], undefined, [_]i32{ 1, 2, 3, 0 }); x[3] = math.rotl(Lane, x[3], 8); x[2] +%= x[3]; x[3] = @shuffle(u32, x[3], undefined, [_]i32{ 2, 3, 0, 1 }); x[1] ^= x[2]; x[2] = @shuffle(u32, x[2], undefined, [_]i32{ 3, 0, 1, 2 }); x[1] = math.rotl(Lane, x[1], 7); } } inline fn hashToBytes(out: *[64]u8, x: BlockVec) void { var i: usize = 0; while (i < 4) : (i += 1) { mem.writeIntLittle(u32, out[16 * i + 0 ..][0..4], x[i][0]); mem.writeIntLittle(u32, out[16 * i + 4 ..][0..4], x[i][1]); mem.writeIntLittle(u32, out[16 * i + 8 ..][0..4], x[i][2]); mem.writeIntLittle(u32, out[16 * i + 12 ..][0..4], x[i][3]); } } inline fn contextFeedback(x: *BlockVec, ctx: BlockVec) void { x[0] +%= ctx[0]; x[1] +%= ctx[1]; x[2] +%= ctx[2]; x[3] +%= ctx[3]; } fn chacha20Xor(out: []u8, in: []const u8, key: [8]u32, counter: [4]u32) void { var ctx = initContext(key, counter); var x: BlockVec = undefined; var buf: [64]u8 = undefined; var i: usize = 0; while (i + 64 <= in.len) : (i += 64) { chacha20Core(x[0..], ctx); contextFeedback(&x, ctx); hashToBytes(buf[0..], x); var xout = out[i..]; const xin = in[i..]; var j: usize = 0; while (j < 64) : (j += 1) { xout[j] = xin[j]; } j = 0; while (j < 64) : (j += 1) { xout[j] ^= buf[j]; } ctx[3][0] += 1; } if (i < in.len) { chacha20Core(x[0..], ctx); contextFeedback(&x, ctx); hashToBytes(buf[0..], x); var xout = out[i..]; const xin = in[i..]; var j: usize = 0; while (j < in.len % 64) : (j += 1) { xout[j] = xin[j] ^ buf[j]; } } } fn hchacha20(input: [16]u8, key: [32]u8) [32]u8 { var c: [4]u32 = undefined; for (c) |_, i| { c[i] = mem.readIntLittle(u32, input[4 * i ..][0..4]); } const ctx = initContext(keyToWords(key), c); var x: BlockVec = undefined; chacha20Core(x[0..], ctx); var out: [32]u8 = undefined; mem.writeIntLittle(u32, out[0..4], x[0][0]); mem.writeIntLittle(u32, out[4..8], x[0][1]); mem.writeIntLittle(u32, out[8..12], x[0][2]); mem.writeIntLittle(u32, out[12..16], x[0][3]); mem.writeIntLittle(u32, out[16..20], x[3][0]); mem.writeIntLittle(u32, out[20..24], x[3][1]); mem.writeIntLittle(u32, out[24..28], x[3][2]); mem.writeIntLittle(u32, out[28..32], x[3][3]); return out; } }; // Non-vectorized implementation of the core function const ChaCha20NonVecImpl = struct { const BlockVec = [16]u32; fn initContext(key: [8]u32, d: [4]u32) BlockVec { const c = "expand 32-byte k"; const constant_le = comptime [4]u32{ mem.readIntLittle(u32, c[0..4]), mem.readIntLittle(u32, c[4..8]), mem.readIntLittle(u32, c[8..12]), mem.readIntLittle(u32, c[12..16]), }; return BlockVec{ constant_le[0], constant_le[1], constant_le[2], constant_le[3], key[0], key[1], key[2], key[3], key[4], key[5], key[6], key[7], d[0], d[1], d[2], d[3], }; } const QuarterRound = struct { a: usize, b: usize, c: usize, d: usize, }; fn Rp(a: usize, b: usize, c: usize, d: usize) QuarterRound { return QuarterRound{ .a = a, .b = b, .c = c, .d = d, }; } inline fn chacha20Core(x: *BlockVec, input: BlockVec) void { x.* = input; const rounds = comptime [_]QuarterRound{ Rp(0, 4, 8, 12), Rp(1, 5, 9, 13), Rp(2, 6, 10, 14), Rp(3, 7, 11, 15), Rp(0, 5, 10, 15), Rp(1, 6, 11, 12), Rp(2, 7, 8, 13), Rp(3, 4, 9, 14), }; comptime var j: usize = 0; inline while (j < 20) : (j += 2) { inline for (rounds) |r| { x[r.a] +%= x[r.b]; x[r.d] = math.rotl(u32, x[r.d] ^ x[r.a], @as(u32, 16)); x[r.c] +%= x[r.d]; x[r.b] = math.rotl(u32, x[r.b] ^ x[r.c], @as(u32, 12)); x[r.a] +%= x[r.b]; x[r.d] = math.rotl(u32, x[r.d] ^ x[r.a], @as(u32, 8)); x[r.c] +%= x[r.d]; x[r.b] = math.rotl(u32, x[r.b] ^ x[r.c], @as(u32, 7)); } } } inline fn hashToBytes(out: *[64]u8, x: BlockVec) void { var i: usize = 0; while (i < 4) : (i += 1) { mem.writeIntLittle(u32, out[16 * i + 0 ..][0..4], x[i * 4 + 0]); mem.writeIntLittle(u32, out[16 * i + 4 ..][0..4], x[i * 4 + 1]); mem.writeIntLittle(u32, out[16 * i + 8 ..][0..4], x[i * 4 + 2]); mem.writeIntLittle(u32, out[16 * i + 12 ..][0..4], x[i * 4 + 3]); } } inline fn contextFeedback(x: *BlockVec, ctx: BlockVec) void { var i: usize = 0; while (i < 16) : (i += 1) { x[i] +%= ctx[i]; } } fn chacha20Xor(out: []u8, in: []const u8, key: [8]u32, counter: [4]u32) void { var ctx = initContext(key, counter); var x: BlockVec = undefined; var buf: [64]u8 = undefined; var i: usize = 0; while (i + 64 <= in.len) : (i += 64) { chacha20Core(x[0..], ctx); contextFeedback(&x, ctx); hashToBytes(buf[0..], x); var xout = out[i..]; const xin = in[i..]; var j: usize = 0; while (j < 64) : (j += 1) { xout[j] = xin[j]; } j = 0; while (j < 64) : (j += 1) { xout[j] ^= buf[j]; } ctx[12] += 1; } if (i < in.len) { chacha20Core(x[0..], ctx); contextFeedback(&x, ctx); hashToBytes(buf[0..], x); var xout = out[i..]; const xin = in[i..]; var j: usize = 0; while (j < in.len % 64) : (j += 1) { xout[j] = xin[j] ^ buf[j]; } } } fn hchacha20(input: [16]u8, key: [32]u8) [32]u8 { var c: [4]u32 = undefined; for (c) |_, i| { c[i] = mem.readIntLittle(u32, input[4 * i ..][0..4]); } const ctx = initContext(keyToWords(key), c); var x: BlockVec = undefined; chacha20Core(x[0..], ctx); var out: [32]u8 = undefined; mem.writeIntLittle(u32, out[0..4], x[0]); mem.writeIntLittle(u32, out[4..8], x[1]); mem.writeIntLittle(u32, out[8..12], x[2]); mem.writeIntLittle(u32, out[12..16], x[3]); mem.writeIntLittle(u32, out[16..20], x[12]); mem.writeIntLittle(u32, out[20..24], x[13]); mem.writeIntLittle(u32, out[24..28], x[14]); mem.writeIntLittle(u32, out[28..32], x[15]); return out; } }; const ChaCha20Impl = if (std.Target.current.cpu.arch == .x86_64) ChaCha20VecImpl else ChaCha20NonVecImpl; fn keyToWords(key: [32]u8) [8]u32 { var k: [8]u32 = undefined; var i: usize = 0; while (i < 8) : (i += 1) { k[i] = mem.readIntLittle(u32, key[i * 4 ..][0..4]); } return k; } /// ChaCha20 avoids the possibility of timing attacks, as there are no branches /// on secret key data. /// /// in and out should be the same length. /// counter should generally be 0 or 1 /// /// ChaCha20 is self-reversing. To decrypt just run the cipher with the same /// counter, nonce, and key. pub const ChaCha20IETF = struct { pub fn xor(out: []u8, in: []const u8, counter: u32, key: [32]u8, nonce: [12]u8) void { assert(in.len == out.len); assert((in.len >> 6) + counter <= maxInt(u32)); var c: [4]u32 = undefined; c[0] = counter; c[1] = mem.readIntLittle(u32, nonce[0..4]); c[2] = mem.readIntLittle(u32, nonce[4..8]); c[3] = mem.readIntLittle(u32, nonce[8..12]); ChaCha20Impl.chacha20Xor(out, in, keyToWords(key), c); } }; /// This is the original ChaCha20 before RFC 7539, which recommends using the /// orgininal version on applications such as disk or file encryption that might /// exceed the 256 GiB limit of the 96-bit nonce version. pub const ChaCha20With64BitNonce = struct { pub fn xor(out: []u8, in: []const u8, counter: u64, key: [32]u8, nonce: [8]u8) void { assert(in.len == out.len); assert(counter +% (in.len >> 6) >= counter); var cursor: usize = 0; const k = keyToWords(key); var c: [4]u32 = undefined; c[0] = @truncate(u32, counter); c[1] = @truncate(u32, counter >> 32); c[2] = mem.readIntLittle(u32, nonce[0..4]); c[3] = mem.readIntLittle(u32, nonce[4..8]); const block_length = (1 << 6); // The full block size is greater than the address space on a 32bit machine const big_block = if (@sizeOf(usize) > 4) (block_length << 32) else maxInt(usize); // first partial big block if (((@intCast(u64, maxInt(u32) - @truncate(u32, counter)) + 1) << 6) < in.len) { ChaCha20Impl.chacha20Xor(out[cursor..big_block], in[cursor..big_block], k, c); cursor = big_block - cursor; c[1] += 1; if (comptime @sizeOf(usize) > 4) { // A big block is giant: 256 GiB, but we can avoid this limitation var remaining_blocks: u32 = @intCast(u32, (in.len / big_block)); var i: u32 = 0; while (remaining_blocks > 0) : (remaining_blocks -= 1) { ChaCha20Impl.chacha20Xor(out[cursor .. cursor + big_block], in[cursor .. cursor + big_block], k, c); c[1] += 1; // upper 32-bit of counter, generic chacha20Xor() doesn't know about this. cursor += big_block; } } } ChaCha20Impl.chacha20Xor(out[cursor..], in[cursor..], k, c); } }; // https://tools.ietf.org/html/rfc7539#section-2.4.2 test "crypto.chacha20 test vector sunscreen" { const expected_result = [_]u8{ 0x6e, 0x2e, 0x35, 0x9a, 0x25, 0x68, 0xf9, 0x80, 0x41, 0xba, 0x07, 0x28, 0xdd, 0x0d, 0x69, 0x81, 0xe9, 0x7e, 0x7a, 0xec, 0x1d, 0x43, 0x60, 0xc2, 0x0a, 0x27, 0xaf, 0xcc, 0xfd, 0x9f, 0xae, 0x0b, 0xf9, 0x1b, 0x65, 0xc5, 0x52, 0x47, 0x33, 0xab, 0x8f, 0x59, 0x3d, 0xab, 0xcd, 0x62, 0xb3, 0x57, 0x16, 0x39, 0xd6, 0x24, 0xe6, 0x51, 0x52, 0xab, 0x8f, 0x53, 0x0c, 0x35, 0x9f, 0x08, 0x61, 0xd8, 0x07, 0xca, 0x0d, 0xbf, 0x50, 0x0d, 0x6a, 0x61, 0x56, 0xa3, 0x8e, 0x08, 0x8a, 0x22, 0xb6, 0x5e, 0x52, 0xbc, 0x51, 0x4d, 0x16, 0xcc, 0xf8, 0x06, 0x81, 0x8c, 0xe9, 0x1a, 0xb7, 0x79, 0x37, 0x36, 0x5a, 0xf9, 0x0b, 0xbf, 0x74, 0xa3, 0x5b, 0xe6, 0xb4, 0x0b, 0x8e, 0xed, 0xf2, 0x78, 0x5e, 0x42, 0x87, 0x4d, }; const input = "Ladies and Gentlemen of the class of '99: If I could offer you only one tip for the future, sunscreen would be it."; var result: [114]u8 = undefined; const key = [_]u8{ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, }; const nonce = [_]u8{ 0, 0, 0, 0, 0, 0, 0, 0x4a, 0, 0, 0, 0, }; ChaCha20IETF.xor(result[0..], input[0..], 1, key, nonce); testing.expectEqualSlices(u8, &expected_result, &result); // Chacha20 is self-reversing. var plaintext: [114]u8 = undefined; ChaCha20IETF.xor(plaintext[0..], result[0..], 1, key, nonce); testing.expect(mem.order(u8, input, &plaintext) == .eq); } // https://tools.ietf.org/html/draft-agl-tls-chacha20poly1305-04#section-7 test "crypto.chacha20 test vector 1" { const expected_result = [_]u8{ 0x76, 0xb8, 0xe0, 0xad, 0xa0, 0xf1, 0x3d, 0x90, 0x40, 0x5d, 0x6a, 0xe5, 0x53, 0x86, 0xbd, 0x28, 0xbd, 0xd2, 0x19, 0xb8, 0xa0, 0x8d, 0xed, 0x1a, 0xa8, 0x36, 0xef, 0xcc, 0x8b, 0x77, 0x0d, 0xc7, 0xda, 0x41, 0x59, 0x7c, 0x51, 0x57, 0x48, 0x8d, 0x77, 0x24, 0xe0, 0x3f, 0xb8, 0xd8, 0x4a, 0x37, 0x6a, 0x43, 0xb8, 0xf4, 0x15, 0x18, 0xa1, 0x1c, 0xc3, 0x87, 0xb6, 0x69, 0xb2, 0xee, 0x65, 0x86, }; const input = [_]u8{ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, }; var result: [64]u8 = undefined; const key = [_]u8{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, }; const nonce = [_]u8{ 0, 0, 0, 0, 0, 0, 0, 0 }; ChaCha20With64BitNonce.xor(result[0..], input[0..], 0, key, nonce); testing.expectEqualSlices(u8, &expected_result, &result); } test "crypto.chacha20 test vector 2" { const expected_result = [_]u8{ 0x45, 0x40, 0xf0, 0x5a, 0x9f, 0x1f, 0xb2, 0x96, 0xd7, 0x73, 0x6e, 0x7b, 0x20, 0x8e, 0x3c, 0x96, 0xeb, 0x4f, 0xe1, 0x83, 0x46, 0x88, 0xd2, 0x60, 0x4f, 0x45, 0x09, 0x52, 0xed, 0x43, 0x2d, 0x41, 0xbb, 0xe2, 0xa0, 0xb6, 0xea, 0x75, 0x66, 0xd2, 0xa5, 0xd1, 0xe7, 0xe2, 0x0d, 0x42, 0xaf, 0x2c, 0x53, 0xd7, 0x92, 0xb1, 0xc4, 0x3f, 0xea, 0x81, 0x7e, 0x9a, 0xd2, 0x75, 0xae, 0x54, 0x69, 0x63, }; const input = [_]u8{ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, }; var result: [64]u8 = undefined; const key = [_]u8{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, }; const nonce = [_]u8{ 0, 0, 0, 0, 0, 0, 0, 0 }; ChaCha20With64BitNonce.xor(result[0..], input[0..], 0, key, nonce); testing.expectEqualSlices(u8, &expected_result, &result); } test "crypto.chacha20 test vector 3" { const expected_result = [_]u8{ 0xde, 0x9c, 0xba, 0x7b, 0xf3, 0xd6, 0x9e, 0xf5, 0xe7, 0x86, 0xdc, 0x63, 0x97, 0x3f, 0x65, 0x3a, 0x0b, 0x49, 0xe0, 0x15, 0xad, 0xbf, 0xf7, 0x13, 0x4f, 0xcb, 0x7d, 0xf1, 0x37, 0x82, 0x10, 0x31, 0xe8, 0x5a, 0x05, 0x02, 0x78, 0xa7, 0x08, 0x45, 0x27, 0x21, 0x4f, 0x73, 0xef, 0xc7, 0xfa, 0x5b, 0x52, 0x77, 0x06, 0x2e, 0xb7, 0xa0, 0x43, 0x3e, 0x44, 0x5f, 0x41, 0xe3, }; const input = [_]u8{ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, }; var result: [60]u8 = undefined; const key = [_]u8{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, }; const nonce = [_]u8{ 0, 0, 0, 0, 0, 0, 0, 1 }; ChaCha20With64BitNonce.xor(result[0..], input[0..], 0, key, nonce); testing.expectEqualSlices(u8, &expected_result, &result); } test "crypto.chacha20 test vector 4" { const expected_result = [_]u8{ 0xef, 0x3f, 0xdf, 0xd6, 0xc6, 0x15, 0x78, 0xfb, 0xf5, 0xcf, 0x35, 0xbd, 0x3d, 0xd3, 0x3b, 0x80, 0x09, 0x63, 0x16, 0x34, 0xd2, 0x1e, 0x42, 0xac, 0x33, 0x96, 0x0b, 0xd1, 0x38, 0xe5, 0x0d, 0x32, 0x11, 0x1e, 0x4c, 0xaf, 0x23, 0x7e, 0xe5, 0x3c, 0xa8, 0xad, 0x64, 0x26, 0x19, 0x4a, 0x88, 0x54, 0x5d, 0xdc, 0x49, 0x7a, 0x0b, 0x46, 0x6e, 0x7d, 0x6b, 0xbd, 0xb0, 0x04, 0x1b, 0x2f, 0x58, 0x6b, }; const input = [_]u8{ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, }; var result: [64]u8 = undefined; const key = [_]u8{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, }; const nonce = [_]u8{ 1, 0, 0, 0, 0, 0, 0, 0 }; ChaCha20With64BitNonce.xor(result[0..], input[0..], 0, key, nonce); testing.expectEqualSlices(u8, &expected_result, &result); } test "crypto.chacha20 test vector 5" { const expected_result = [_]u8{ 0xf7, 0x98, 0xa1, 0x89, 0xf1, 0x95, 0xe6, 0x69, 0x82, 0x10, 0x5f, 0xfb, 0x64, 0x0b, 0xb7, 0x75, 0x7f, 0x57, 0x9d, 0xa3, 0x16, 0x02, 0xfc, 0x93, 0xec, 0x01, 0xac, 0x56, 0xf8, 0x5a, 0xc3, 0xc1, 0x34, 0xa4, 0x54, 0x7b, 0x73, 0x3b, 0x46, 0x41, 0x30, 0x42, 0xc9, 0x44, 0x00, 0x49, 0x17, 0x69, 0x05, 0xd3, 0xbe, 0x59, 0xea, 0x1c, 0x53, 0xf1, 0x59, 0x16, 0x15, 0x5c, 0x2b, 0xe8, 0x24, 0x1a, 0x38, 0x00, 0x8b, 0x9a, 0x26, 0xbc, 0x35, 0x94, 0x1e, 0x24, 0x44, 0x17, 0x7c, 0x8a, 0xde, 0x66, 0x89, 0xde, 0x95, 0x26, 0x49, 0x86, 0xd9, 0x58, 0x89, 0xfb, 0x60, 0xe8, 0x46, 0x29, 0xc9, 0xbd, 0x9a, 0x5a, 0xcb, 0x1c, 0xc1, 0x18, 0xbe, 0x56, 0x3e, 0xb9, 0xb3, 0xa4, 0xa4, 0x72, 0xf8, 0x2e, 0x09, 0xa7, 0xe7, 0x78, 0x49, 0x2b, 0x56, 0x2e, 0xf7, 0x13, 0x0e, 0x88, 0xdf, 0xe0, 0x31, 0xc7, 0x9d, 0xb9, 0xd4, 0xf7, 0xc7, 0xa8, 0x99, 0x15, 0x1b, 0x9a, 0x47, 0x50, 0x32, 0xb6, 0x3f, 0xc3, 0x85, 0x24, 0x5f, 0xe0, 0x54, 0xe3, 0xdd, 0x5a, 0x97, 0xa5, 0xf5, 0x76, 0xfe, 0x06, 0x40, 0x25, 0xd3, 0xce, 0x04, 0x2c, 0x56, 0x6a, 0xb2, 0xc5, 0x07, 0xb1, 0x38, 0xdb, 0x85, 0x3e, 0x3d, 0x69, 0x59, 0x66, 0x09, 0x96, 0x54, 0x6c, 0xc9, 0xc4, 0xa6, 0xea, 0xfd, 0xc7, 0x77, 0xc0, 0x40, 0xd7, 0x0e, 0xaf, 0x46, 0xf7, 0x6d, 0xad, 0x39, 0x79, 0xe5, 0xc5, 0x36, 0x0c, 0x33, 0x17, 0x16, 0x6a, 0x1c, 0x89, 0x4c, 0x94, 0xa3, 0x71, 0x87, 0x6a, 0x94, 0xdf, 0x76, 0x28, 0xfe, 0x4e, 0xaa, 0xf2, 0xcc, 0xb2, 0x7d, 0x5a, 0xaa, 0xe0, 0xad, 0x7a, 0xd0, 0xf9, 0xd4, 0xb6, 0xad, 0x3b, 0x54, 0x09, 0x87, 0x46, 0xd4, 0x52, 0x4d, 0x38, 0x40, 0x7a, 0x6d, 0xeb, 0x3a, 0xb7, 0x8f, 0xab, 0x78, 0xc9, }; const input = [_]u8{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, }; var result: [256]u8 = undefined; const key = [_]u8{ 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f, }; const nonce = [_]u8{ 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, }; ChaCha20With64BitNonce.xor(result[0..], input[0..], 0, key, nonce); testing.expectEqualSlices(u8, &expected_result, &result); } pub const chacha20poly1305_tag_length = 16; fn chacha20poly1305SealDetached(ciphertext: []u8, tag: *[chacha20poly1305_tag_length]u8, plaintext: []const u8, data: []const u8, key: [32]u8, nonce: [12]u8) void { assert(ciphertext.len == plaintext.len); // derive poly1305 key var polyKey = [_]u8{0} ** 32; ChaCha20IETF.xor(polyKey[0..], polyKey[0..], 0, key, nonce); // encrypt plaintext ChaCha20IETF.xor(ciphertext[0..plaintext.len], plaintext, 1, key, nonce); // construct mac var mac = Poly1305.init(polyKey[0..]); mac.update(data); if (data.len % 16 != 0) { const zeros = [_]u8{0} ** 16; const padding = 16 - (data.len % 16); mac.update(zeros[0..padding]); } mac.update(ciphertext[0..plaintext.len]); if (plaintext.len % 16 != 0) { const zeros = [_]u8{0} ** 16; const padding = 16 - (plaintext.len % 16); mac.update(zeros[0..padding]); } var lens: [16]u8 = undefined; mem.writeIntLittle(u64, lens[0..8], data.len); mem.writeIntLittle(u64, lens[8..16], plaintext.len); mac.update(lens[0..]); mac.final(tag); } fn chacha20poly1305Seal(ciphertextAndTag: []u8, plaintext: []const u8, data: []const u8, key: [32]u8, nonce: [12]u8) void { return chacha20poly1305SealDetached(ciphertextAndTag[0..plaintext.len], ciphertextAndTag[plaintext.len..][0..chacha20poly1305_tag_length], plaintext, data, key, nonce); } /// Verifies and decrypts an authenticated message produced by chacha20poly1305SealDetached. fn chacha20poly1305OpenDetached(dst: []u8, ciphertext: []const u8, tag: *const [chacha20poly1305_tag_length]u8, data: []const u8, key: [32]u8, nonce: [12]u8) !void { // split ciphertext and tag assert(dst.len == ciphertext.len); // derive poly1305 key var polyKey = [_]u8{0} ** 32; ChaCha20IETF.xor(polyKey[0..], polyKey[0..], 0, key, nonce); // construct mac var mac = Poly1305.init(polyKey[0..]); mac.update(data); if (data.len % 16 != 0) { const zeros = [_]u8{0} ** 16; const padding = 16 - (data.len % 16); mac.update(zeros[0..padding]); } mac.update(ciphertext); if (ciphertext.len % 16 != 0) { const zeros = [_]u8{0} ** 16; const padding = 16 - (ciphertext.len % 16); mac.update(zeros[0..padding]); } var lens: [16]u8 = undefined; mem.writeIntLittle(u64, lens[0..8], data.len); mem.writeIntLittle(u64, lens[8..16], ciphertext.len); mac.update(lens[0..]); var computedTag: [16]u8 = undefined; mac.final(computedTag[0..]); // verify mac in constant time // TODO: we can't currently guarantee that this will run in constant time. // See https://github.com/ziglang/zig/issues/1776 var acc: u8 = 0; for (computedTag) |_, i| { acc |= computedTag[i] ^ tag[i]; } if (acc != 0) { return error.AuthenticationFailed; } // decrypt ciphertext ChaCha20IETF.xor(dst[0..ciphertext.len], ciphertext, 1, key, nonce); } /// Verifies and decrypts an authenticated message produced by chacha20poly1305Seal. fn chacha20poly1305Open(dst: []u8, ciphertextAndTag: []const u8, data: []const u8, key: [32]u8, nonce: [12]u8) !void { if (ciphertextAndTag.len < chacha20poly1305_tag_length) { return error.InvalidMessage; } const ciphertextLen = ciphertextAndTag.len - chacha20poly1305_tag_length; return try chacha20poly1305OpenDetached(dst, ciphertextAndTag[0..ciphertextLen], ciphertextAndTag[ciphertextLen..][0..chacha20poly1305_tag_length], data, key, nonce); } fn extend(key: [32]u8, nonce: [24]u8) struct { key: [32]u8, nonce: [12]u8 } { var subnonce: [12]u8 = undefined; mem.set(u8, subnonce[0..4], 0); mem.copy(u8, subnonce[4..], nonce[16..24]); return .{ .key = ChaCha20Impl.hchacha20(nonce[0..16].*, key), .nonce = subnonce, }; } pub const XChaCha20IETF = struct { pub fn xor(out: []u8, in: []const u8, counter: u32, key: [32]u8, nonce: [24]u8) void { const extended = extend(key, nonce); ChaCha20IETF.xor(out, in, counter, extended.key, extended.nonce); } }; pub const xchacha20poly1305_tag_length = 16; fn xchacha20poly1305SealDetached(ciphertext: []u8, tag: *[chacha20poly1305_tag_length]u8, plaintext: []const u8, data: []const u8, key: [32]u8, nonce: [24]u8) void { const extended = extend(key, nonce); return chacha20poly1305SealDetached(ciphertext, tag, plaintext, data, extended.key, extended.nonce); } fn xchacha20poly1305Seal(ciphertextAndTag: []u8, plaintext: []const u8, data: []const u8, key: [32]u8, nonce: [24]u8) void { const extended = extend(key, nonce); return chacha20poly1305Seal(ciphertextAndTag, plaintext, data, extended.key, extended.nonce); } /// Verifies and decrypts an authenticated message produced by xchacha20poly1305SealDetached. fn xchacha20poly1305OpenDetached(plaintext: []u8, ciphertext: []const u8, tag: *const [chacha20poly1305_tag_length]u8, data: []const u8, key: [32]u8, nonce: [24]u8) !void { const extended = extend(key, nonce); return try chacha20poly1305OpenDetached(plaintext, ciphertext, tag, data, extended.key, extended.nonce); } /// Verifies and decrypts an authenticated message produced by xchacha20poly1305Seal. fn xchacha20poly1305Open(ciphertextAndTag: []u8, msgAndTag: []const u8, data: []const u8, key: [32]u8, nonce: [24]u8) !void { const extended = extend(key, nonce); return try chacha20poly1305Open(ciphertextAndTag, msgAndTag, data, extended.key, extended.nonce); } test "seal" { { const plaintext = ""; const data = ""; const key = [_]u8{ 0x80, 0x81, 0x82, 0x83, 0x84, 0x85, 0x86, 0x87, 0x88, 0x89, 0x8a, 0x8b, 0x8c, 0x8d, 0x8e, 0x8f, 0x90, 0x91, 0x92, 0x93, 0x94, 0x95, 0x96, 0x97, 0x98, 0x99, 0x9a, 0x9b, 0x9c, 0x9d, 0x9e, 0x9f, }; const nonce = [_]u8{ 0x7, 0x0, 0x0, 0x0, 0x40, 0x41, 0x42, 0x43, 0x44, 0x45, 0x46, 0x47 }; const exp_out = [_]u8{ 0xa0, 0x78, 0x4d, 0x7a, 0x47, 0x16, 0xf3, 0xfe, 0xb4, 0xf6, 0x4e, 0x7f, 0x4b, 0x39, 0xbf, 0x4 }; var out: [exp_out.len]u8 = undefined; chacha20poly1305Seal(out[0..], plaintext, data, key, nonce); testing.expectEqualSlices(u8, exp_out[0..], out[0..]); } { const plaintext = [_]u8{ 0x4c, 0x61, 0x64, 0x69, 0x65, 0x73, 0x20, 0x61, 0x6e, 0x64, 0x20, 0x47, 0x65, 0x6e, 0x74, 0x6c, 0x65, 0x6d, 0x65, 0x6e, 0x20, 0x6f, 0x66, 0x20, 0x74, 0x68, 0x65, 0x20, 0x63, 0x6c, 0x61, 0x73, 0x73, 0x20, 0x6f, 0x66, 0x20, 0x27, 0x39, 0x39, 0x3a, 0x20, 0x49, 0x66, 0x20, 0x49, 0x20, 0x63, 0x6f, 0x75, 0x6c, 0x64, 0x20, 0x6f, 0x66, 0x66, 0x65, 0x72, 0x20, 0x79, 0x6f, 0x75, 0x20, 0x6f, 0x6e, 0x6c, 0x79, 0x20, 0x6f, 0x6e, 0x65, 0x20, 0x74, 0x69, 0x70, 0x20, 0x66, 0x6f, 0x72, 0x20, 0x74, 0x68, 0x65, 0x20, 0x66, 0x75, 0x74, 0x75, 0x72, 0x65, 0x2c, 0x20, 0x73, 0x75, 0x6e, 0x73, 0x63, 0x72, 0x65, 0x65, 0x6e, 0x20, 0x77, 0x6f, 0x75, 0x6c, 0x64, 0x20, 0x62, 0x65, 0x20, 0x69, 0x74, 0x2e, }; const data = [_]u8{ 0x50, 0x51, 0x52, 0x53, 0xc0, 0xc1, 0xc2, 0xc3, 0xc4, 0xc5, 0xc6, 0xc7 }; const key = [_]u8{ 0x80, 0x81, 0x82, 0x83, 0x84, 0x85, 0x86, 0x87, 0x88, 0x89, 0x8a, 0x8b, 0x8c, 0x8d, 0x8e, 0x8f, 0x90, 0x91, 0x92, 0x93, 0x94, 0x95, 0x96, 0x97, 0x98, 0x99, 0x9a, 0x9b, 0x9c, 0x9d, 0x9e, 0x9f, }; const nonce = [_]u8{ 0x7, 0x0, 0x0, 0x0, 0x40, 0x41, 0x42, 0x43, 0x44, 0x45, 0x46, 0x47 }; const exp_out = [_]u8{ 0xd3, 0x1a, 0x8d, 0x34, 0x64, 0x8e, 0x60, 0xdb, 0x7b, 0x86, 0xaf, 0xbc, 0x53, 0xef, 0x7e, 0xc2, 0xa4, 0xad, 0xed, 0x51, 0x29, 0x6e, 0x8, 0xfe, 0xa9, 0xe2, 0xb5, 0xa7, 0x36, 0xee, 0x62, 0xd6, 0x3d, 0xbe, 0xa4, 0x5e, 0x8c, 0xa9, 0x67, 0x12, 0x82, 0xfa, 0xfb, 0x69, 0xda, 0x92, 0x72, 0x8b, 0x1a, 0x71, 0xde, 0xa, 0x9e, 0x6, 0xb, 0x29, 0x5, 0xd6, 0xa5, 0xb6, 0x7e, 0xcd, 0x3b, 0x36, 0x92, 0xdd, 0xbd, 0x7f, 0x2d, 0x77, 0x8b, 0x8c, 0x98, 0x3, 0xae, 0xe3, 0x28, 0x9, 0x1b, 0x58, 0xfa, 0xb3, 0x24, 0xe4, 0xfa, 0xd6, 0x75, 0x94, 0x55, 0x85, 0x80, 0x8b, 0x48, 0x31, 0xd7, 0xbc, 0x3f, 0xf4, 0xde, 0xf0, 0x8e, 0x4b, 0x7a, 0x9d, 0xe5, 0x76, 0xd2, 0x65, 0x86, 0xce, 0xc6, 0x4b, 0x61, 0x16, 0x1a, 0xe1, 0xb, 0x59, 0x4f, 0x9, 0xe2, 0x6a, 0x7e, 0x90, 0x2e, 0xcb, 0xd0, 0x60, 0x6, 0x91, }; var out: [exp_out.len]u8 = undefined; chacha20poly1305Seal(out[0..], plaintext[0..], data[0..], key, nonce); testing.expectEqualSlices(u8, exp_out[0..], out[0..]); } } test "open" { { const ciphertext = [_]u8{ 0xa0, 0x78, 0x4d, 0x7a, 0x47, 0x16, 0xf3, 0xfe, 0xb4, 0xf6, 0x4e, 0x7f, 0x4b, 0x39, 0xbf, 0x4 }; const data = ""; const key = [_]u8{ 0x80, 0x81, 0x82, 0x83, 0x84, 0x85, 0x86, 0x87, 0x88, 0x89, 0x8a, 0x8b, 0x8c, 0x8d, 0x8e, 0x8f, 0x90, 0x91, 0x92, 0x93, 0x94, 0x95, 0x96, 0x97, 0x98, 0x99, 0x9a, 0x9b, 0x9c, 0x9d, 0x9e, 0x9f, }; const nonce = [_]u8{ 0x7, 0x0, 0x0, 0x0, 0x40, 0x41, 0x42, 0x43, 0x44, 0x45, 0x46, 0x47 }; const exp_out = ""; var out: [exp_out.len]u8 = undefined; try chacha20poly1305Open(out[0..], ciphertext[0..], data, key, nonce); testing.expectEqualSlices(u8, exp_out[0..], out[0..]); } { const ciphertext = [_]u8{ 0xd3, 0x1a, 0x8d, 0x34, 0x64, 0x8e, 0x60, 0xdb, 0x7b, 0x86, 0xaf, 0xbc, 0x53, 0xef, 0x7e, 0xc2, 0xa4, 0xad, 0xed, 0x51, 0x29, 0x6e, 0x8, 0xfe, 0xa9, 0xe2, 0xb5, 0xa7, 0x36, 0xee, 0x62, 0xd6, 0x3d, 0xbe, 0xa4, 0x5e, 0x8c, 0xa9, 0x67, 0x12, 0x82, 0xfa, 0xfb, 0x69, 0xda, 0x92, 0x72, 0x8b, 0x1a, 0x71, 0xde, 0xa, 0x9e, 0x6, 0xb, 0x29, 0x5, 0xd6, 0xa5, 0xb6, 0x7e, 0xcd, 0x3b, 0x36, 0x92, 0xdd, 0xbd, 0x7f, 0x2d, 0x77, 0x8b, 0x8c, 0x98, 0x3, 0xae, 0xe3, 0x28, 0x9, 0x1b, 0x58, 0xfa, 0xb3, 0x24, 0xe4, 0xfa, 0xd6, 0x75, 0x94, 0x55, 0x85, 0x80, 0x8b, 0x48, 0x31, 0xd7, 0xbc, 0x3f, 0xf4, 0xde, 0xf0, 0x8e, 0x4b, 0x7a, 0x9d, 0xe5, 0x76, 0xd2, 0x65, 0x86, 0xce, 0xc6, 0x4b, 0x61, 0x16, 0x1a, 0xe1, 0xb, 0x59, 0x4f, 0x9, 0xe2, 0x6a, 0x7e, 0x90, 0x2e, 0xcb, 0xd0, 0x60, 0x6, 0x91, }; const data = [_]u8{ 0x50, 0x51, 0x52, 0x53, 0xc0, 0xc1, 0xc2, 0xc3, 0xc4, 0xc5, 0xc6, 0xc7 }; const key = [_]u8{ 0x80, 0x81, 0x82, 0x83, 0x84, 0x85, 0x86, 0x87, 0x88, 0x89, 0x8a, 0x8b, 0x8c, 0x8d, 0x8e, 0x8f, 0x90, 0x91, 0x92, 0x93, 0x94, 0x95, 0x96, 0x97, 0x98, 0x99, 0x9a, 0x9b, 0x9c, 0x9d, 0x9e, 0x9f, }; const nonce = [_]u8{ 0x7, 0x0, 0x0, 0x0, 0x40, 0x41, 0x42, 0x43, 0x44, 0x45, 0x46, 0x47 }; const exp_out = [_]u8{ 0x4c, 0x61, 0x64, 0x69, 0x65, 0x73, 0x20, 0x61, 0x6e, 0x64, 0x20, 0x47, 0x65, 0x6e, 0x74, 0x6c, 0x65, 0x6d, 0x65, 0x6e, 0x20, 0x6f, 0x66, 0x20, 0x74, 0x68, 0x65, 0x20, 0x63, 0x6c, 0x61, 0x73, 0x73, 0x20, 0x6f, 0x66, 0x20, 0x27, 0x39, 0x39, 0x3a, 0x20, 0x49, 0x66, 0x20, 0x49, 0x20, 0x63, 0x6f, 0x75, 0x6c, 0x64, 0x20, 0x6f, 0x66, 0x66, 0x65, 0x72, 0x20, 0x79, 0x6f, 0x75, 0x20, 0x6f, 0x6e, 0x6c, 0x79, 0x20, 0x6f, 0x6e, 0x65, 0x20, 0x74, 0x69, 0x70, 0x20, 0x66, 0x6f, 0x72, 0x20, 0x74, 0x68, 0x65, 0x20, 0x66, 0x75, 0x74, 0x75, 0x72, 0x65, 0x2c, 0x20, 0x73, 0x75, 0x6e, 0x73, 0x63, 0x72, 0x65, 0x65, 0x6e, 0x20, 0x77, 0x6f, 0x75, 0x6c, 0x64, 0x20, 0x62, 0x65, 0x20, 0x69, 0x74, 0x2e, }; var out: [exp_out.len]u8 = undefined; try chacha20poly1305Open(out[0..], ciphertext[0..], data[0..], key, nonce); testing.expectEqualSlices(u8, exp_out[0..], out[0..]); // corrupting the ciphertext, data, key, or nonce should cause a failure var bad_ciphertext = ciphertext; bad_ciphertext[0] ^= 1; testing.expectError(error.AuthenticationFailed, chacha20poly1305Open(out[0..], bad_ciphertext[0..], data[0..], key, nonce)); var bad_data = data; bad_data[0] ^= 1; testing.expectError(error.AuthenticationFailed, chacha20poly1305Open(out[0..], ciphertext[0..], bad_data[0..], key, nonce)); var bad_key = key; bad_key[0] ^= 1; testing.expectError(error.AuthenticationFailed, chacha20poly1305Open(out[0..], ciphertext[0..], data[0..], bad_key, nonce)); var bad_nonce = nonce; bad_nonce[0] ^= 1; testing.expectError(error.AuthenticationFailed, chacha20poly1305Open(out[0..], ciphertext[0..], data[0..], key, bad_nonce)); // a short ciphertext should result in a different error testing.expectError(error.InvalidMessage, chacha20poly1305Open(out[0..], "", data[0..], key, bad_nonce)); } } test "crypto.xchacha20" { const key = [_]u8{69} ** 32; const nonce = [_]u8{42} ** 24; const input = "Ladies and Gentlemen of the class of '99: If I could offer you only one tip for the future, sunscreen would be it."; { var ciphertext: [input.len]u8 = undefined; XChaCha20IETF.xor(ciphertext[0..], input[0..], 0, key, nonce); var buf: [2 * ciphertext.len]u8 = undefined; testing.expectEqualStrings(try std.fmt.bufPrint(&buf, "{X}", .{ciphertext}), "E0A1BCF939654AFDBDC1746EC49832647C19D891F0D1A81FC0C1703B4514BDEA584B512F6908C2C5E9DD18D5CBC1805DE5803FE3B9CA5F193FB8359E91FAB0C3BB40309A292EB1CF49685C65C4A3ADF4F11DB0CD2B6B67FBC174BC2E860E8F769FD3565BBFAD1C845E05A0FED9BE<KEY>"); } { const data = "Additional data"; var ciphertext: [input.len + xchacha20poly1305_tag_length]u8 = undefined; xchacha20poly1305Seal(ciphertext[0..], input, data, key, nonce); var out: [input.len]u8 = undefined; try xchacha20poly1305Open(out[0..], ciphertext[0..], data, key, nonce); var buf: [2 * ciphertext.len]u8 = undefined; testing.expectEqualStrings(try std.fmt.bufPrint(&buf, "{X}", .{ciphertext}), "994D2DD32333F48E53650C02C7A2ABB8E018B0836D7175AEC779F52E961780768F815C58F1AA52D211498DB89B9216763F569C9433A6BBFCEFB4D4A49387A4C5207FBB3B5A92B5941294DF30588C6740D39DC16FA1F0E634F7246CF7CDCB978E44347D89381B7A74EB7084F754B90BDE9AAF5A94B8F2A85EFD0B50692AE2D425E234"); testing.expectEqualSlices(u8, out[0..], input); ciphertext[0] += 1; testing.expectError(error.AuthenticationFailed, xchacha20poly1305Open(out[0..], ciphertext[0..], data, key, nonce)); } } pub const Chacha20Poly1305 = struct { pub const tag_length = 16; pub const nonce_length = 12; pub const key_length = 32; /// c: ciphertext: output buffer should be of size m.len /// tag: authentication tag: output MAC /// m: message /// ad: Associated Data /// npub: public nonce /// k: private key pub fn encrypt(c: []u8, tag: *[tag_length]u8, m: []const u8, ad: []const u8, npub: [nonce_length]u8, k: [key_length]u8) void { assert(c.len == m.len); return chacha20poly1305SealDetached(c, tag, m, ad, k, npub); } /// m: message: output buffer should be of size c.len /// c: ciphertext /// tag: authentication tag /// ad: Associated Data /// npub: public nonce /// k: private key /// NOTE: the check of the authentication tag is currently not done in constant time pub fn decrypt(m: []u8, c: []const u8, tag: [tag_length]u8, ad: []const u8, npub: [nonce_length]u8, k: [key_length]u8) !void { assert(c.len == m.len); return try chacha20poly1305OpenDetached(m, c, tag[0..], ad, k, npub); } }; pub const XChacha20Poly1305 = struct { pub const tag_length = 16; pub const nonce_length = 24; pub const key_length = 32; /// c: ciphertext: output buffer should be of size m.len /// tag: authentication tag: output MAC /// m: message /// ad: Associated Data /// npub: public nonce /// k: private key pub fn encrypt(c: []u8, tag: *[tag_length]u8, m: []const u8, ad: []const u8, npub: [nonce_length]u8, k: [key_length]u8) void { assert(c.len == m.len); return xchacha20poly1305SealDetached(c, tag, m, ad, k, npub); } /// m: message: output buffer should be of size c.len /// c: ciphertext /// tag: authentication tag /// ad: Associated Data /// npub: public nonce /// k: private key /// NOTE: the check of the authentication tag is currently not done in constant time pub fn decrypt(m: []u8, c: []const u8, tag: [tag_length]u8, ad: []const u8, npub: [nonce_length]u8, k: [key_length]u8) !void { assert(c.len == m.len); return try xchacha20poly1305OpenDetached(m, c, tag[0..], ad, k, npub); } }; test "chacha20 AEAD API" { const aeads = [_]type{ Chacha20Poly1305, XChacha20Poly1305 }; const input = "Ladies and Gentlemen of the class of '99: If I could offer you only one tip for the future, sunscreen would be it."; const data = "Additional data"; inline for (aeads) |aead| { const key = [_]u8{69} ** aead.key_length; const nonce = [_]u8{42} ** aead.nonce_length; var ciphertext: [input.len]u8 = undefined; var tag: [aead.tag_length]u8 = undefined; var out: [input.len]u8 = undefined; aead.encrypt(ciphertext[0..], tag[0..], input, data, nonce, key); try aead.decrypt(out[0..], ciphertext[0..], tag, data[0..], nonce, key); testing.expectEqualSlices(u8, out[0..], input); ciphertext[0] += 1; testing.expectError(error.AuthenticationFailed, aead.decrypt(out[0..], ciphertext[0..], tag, data[0..], nonce, key)); } }
lib/std/crypto/chacha20.zig
const std = @import("../index.zig"); const math = std.math; const expect = std.testing.expect; const maxInt = std.math.maxInt; pub fn isInf(x: var) bool { const T = @typeOf(x); switch (T) { f16 => { const bits = @bitCast(u16, x); return bits & 0x7FFF == 0x7C00; }, f32 => { const bits = @bitCast(u32, x); return bits & 0x7FFFFFFF == 0x7F800000; }, f64 => { const bits = @bitCast(u64, x); return bits & (maxInt(u64) >> 1) == (0x7FF << 52); }, f128 => { const bits = @bitCast(u128, x); return bits & (maxInt(u128) >> 1) == (0x7FFF << 112); }, else => { @compileError("isInf not implemented for " ++ @typeName(T)); }, } } pub fn isPositiveInf(x: var) bool { const T = @typeOf(x); switch (T) { f16 => { return @bitCast(u16, x) == 0x7C00; }, f32 => { return @bitCast(u32, x) == 0x7F800000; }, f64 => { return @bitCast(u64, x) == 0x7FF << 52; }, f128 => { return @bitCast(u128, x) == 0x7FFF << 112; }, else => { @compileError("isPositiveInf not implemented for " ++ @typeName(T)); }, } } pub fn isNegativeInf(x: var) bool { const T = @typeOf(x); switch (T) { f16 => { return @bitCast(u16, x) == 0xFC00; }, f32 => { return @bitCast(u32, x) == 0xFF800000; }, f64 => { return @bitCast(u64, x) == 0xFFF << 52; }, f128 => { return @bitCast(u128, x) == 0xFFFF << 112; }, else => { @compileError("isNegativeInf not implemented for " ++ @typeName(T)); }, } } test "math.isInf" { expect(!isInf(f16(0.0))); expect(!isInf(f16(-0.0))); expect(!isInf(f32(0.0))); expect(!isInf(f32(-0.0))); expect(!isInf(f64(0.0))); expect(!isInf(f64(-0.0))); expect(!isInf(f128(0.0))); expect(!isInf(f128(-0.0))); expect(isInf(math.inf(f16))); expect(isInf(-math.inf(f16))); expect(isInf(math.inf(f32))); expect(isInf(-math.inf(f32))); expect(isInf(math.inf(f64))); expect(isInf(-math.inf(f64))); expect(isInf(math.inf(f128))); expect(isInf(-math.inf(f128))); } test "math.isPositiveInf" { expect(!isPositiveInf(f16(0.0))); expect(!isPositiveInf(f16(-0.0))); expect(!isPositiveInf(f32(0.0))); expect(!isPositiveInf(f32(-0.0))); expect(!isPositiveInf(f64(0.0))); expect(!isPositiveInf(f64(-0.0))); expect(!isPositiveInf(f128(0.0))); expect(!isPositiveInf(f128(-0.0))); expect(isPositiveInf(math.inf(f16))); expect(!isPositiveInf(-math.inf(f16))); expect(isPositiveInf(math.inf(f32))); expect(!isPositiveInf(-math.inf(f32))); expect(isPositiveInf(math.inf(f64))); expect(!isPositiveInf(-math.inf(f64))); expect(isPositiveInf(math.inf(f128))); expect(!isPositiveInf(-math.inf(f128))); } test "math.isNegativeInf" { expect(!isNegativeInf(f16(0.0))); expect(!isNegativeInf(f16(-0.0))); expect(!isNegativeInf(f32(0.0))); expect(!isNegativeInf(f32(-0.0))); expect(!isNegativeInf(f64(0.0))); expect(!isNegativeInf(f64(-0.0))); expect(!isNegativeInf(f128(0.0))); expect(!isNegativeInf(f128(-0.0))); expect(!isNegativeInf(math.inf(f16))); expect(isNegativeInf(-math.inf(f16))); expect(!isNegativeInf(math.inf(f32))); expect(isNegativeInf(-math.inf(f32))); expect(!isNegativeInf(math.inf(f64))); expect(isNegativeInf(-math.inf(f64))); expect(!isNegativeInf(math.inf(f128))); expect(isNegativeInf(-math.inf(f128))); }
std/math/isinf.zig
const std = @import("std"); const utils = @import("utils.zig"); const vector = @import("vector.zig"); const Vec4 = vector.Vec4; const Mat4 = @import("matrix.zig").Mat4; const Shape = @import("shape.zig").Shape; const initPoint = vector.initPoint; const initVector = vector.initVector; pub const Ray = struct { const Self = @This(); origin: Vec4, direction: Vec4, pub fn init(origin: Vec4, direction: Vec4) Self { return Self{ .origin = origin, .direction = direction, }; } pub fn position(self: Self, t: f64) Vec4 { return self.origin.add(self.direction.scale(t)); } pub fn transform(self: Self, mat: Mat4) Self { return Self{ .origin = mat.multVec(self.origin), .direction = mat.multVec(self.direction), }; } }; test "creating and querying a ray" { const origin = initPoint(1, 2, 3); const direction = initVector(4, 5, 6); const r = Ray.init(origin, direction); try std.testing.expect(r.origin.eql(origin)); try std.testing.expect(r.direction.eql(direction)); } test "computing a point from a distance" { const r = Ray.init(initPoint(2, 3, 4), initVector(1, 0, 0)); try std.testing.expect(r.position(0).eql(initPoint(2, 3, 4))); try std.testing.expect(r.position(1).eql(initPoint(3, 3, 4))); try std.testing.expect(r.position(-1).eql(initPoint(1, 3, 4))); try std.testing.expect(r.position(2.5).eql(initPoint(4.5, 3, 4))); } pub const Intersection = struct { t: f64, object: Shape, }; pub const Intersections = struct { const Self = @This(); allocator: std.mem.Allocator, list: std.ArrayList(Intersection), pub fn init(allocator: std.mem.Allocator) Self { return .{ .allocator = allocator, .list = std.ArrayList(Intersection).init(allocator), }; } pub fn hit(self: Self) ?Intersection { std.sort.sort(Intersection, self.list.items, {}, lessThanIntersection); const first_hit = for (self.list.items) |intersection| { if (intersection.t >= 0) break intersection; } else null; return first_hit; } pub fn deinit(self: *Self) void { self.list.deinit(); } pub fn lessThanIntersection(context: void, a: Intersection, b: Intersection) bool { _ = context; return a.t < b.t; } }; const alloc = std.testing.allocator; test "The hit, when all intersections have positive t" { const s = Shape{ .geo = .{ .sphere = .{} } }; var xs = Intersections.init(alloc); defer xs.deinit(); const is1 = Intersection{ .t = 1, .object = s }; try xs.list.append(is1); const is2 = Intersection{ .t = 2, .object = s }; try xs.list.append(is2); try std.testing.expectEqual(is1, xs.hit().?); } test "The hit, when some intersections have negative t" { const s = Shape{ .geo = .{ .sphere = .{} } }; var xs = Intersections.init(alloc); defer xs.deinit(); const is1 = Intersection{ .t = -1, .object = s }; try xs.list.append(is1); const is2 = Intersection{ .t = 1, .object = s }; try xs.list.append(is2); try std.testing.expectEqual(is2, xs.hit().?); } test "The hit, when all intersections have negative t" { const s = Shape{ .geo = .{ .sphere = .{} } }; var xs = Intersections.init(alloc); defer xs.deinit(); const is1 = Intersection{ .t = -2, .object = s }; try xs.list.append(is1); const is2 = Intersection{ .t = -1, .object = s }; try xs.list.append(is2); try std.testing.expect(xs.hit() == null); } test "The hit is always the lowest nonnegative intersection" { const s = Shape{ .geo = .{ .sphere = .{} } }; var xs = Intersections.init(alloc); defer xs.deinit(); const is1 = Intersection{ .t = 5, .object = s }; try xs.list.append(is1); const is2 = Intersection{ .t = 7, .object = s }; try xs.list.append(is2); const is3 = Intersection{ .t = -3, .object = s }; try xs.list.append(is3); const is4 = Intersection{ .t = 2, .object = s }; try xs.list.append(is4); try std.testing.expectEqual(is4, xs.hit().?); } test "Translating a ray" { const r = Ray.init(initPoint(1, 2, 3), initVector(0, 1, 0)); const m = Mat4.identity().translate(3, 4, 5); const r2 = r.transform(m); try std.testing.expect(r2.origin.eql(initPoint(4, 6, 8))); try std.testing.expect(r2.direction.eql(initVector(0, 1, 0))); } test "Scaling a ray" { const r = Ray.init(initPoint(1, 2, 3), initVector(0, 1, 0)); const m = Mat4.identity().scale(2, 3, 4); const r2 = r.transform(m); try std.testing.expect(r2.origin.eql(initPoint(2, 6, 12))); try std.testing.expect(r2.direction.eql(initVector(0, 3, 0))); }
ray.zig
const std = @import("std"); const expect = std.testing.expect; pub const Vec3 = Vector3(f32); pub const Point3 = Vector3(f32); pub const Color = Vector3(f32); fn Vector3(comptime T: type) type { return struct { const Self = @This(); x: T, y: T, z: T, pub const zero = Vec3.initAll(0); pub fn init(x: T, y: T, z: T) Self { return Self{ .x = x, .y = y, .z = z }; } pub fn initAll(x: T) Self { return Self.init(x, x, x); } pub fn random(r: *std.rand.Random) Self { return Self.init(r.float(T), r.float(T), r.float(T)); } // Vector arithmetic pub fn add(a: Self, b: Self) Self { return Self.init(a.x + b.x, a.y + b.y, a.z + b.z); } pub fn sub(a: Self, b: Self) Self { return Self.init(a.x - b.x, a.y - b.y, a.z - b.z); } pub fn dot(a: Self, b: Self) T { return a.x * b.x + a.y * b.y + a.z * b.z; } pub fn cross(a: Self, b: Self) Self { return Self.init( a.y * b.z - a.z * b.y, a.z * b.x - a.x * b.z, a.x * b.y - a.y * b.x, ); } /// Component-wise multiplication pub fn mul(a: Self, b: Self) Self { return Self.init(a.x * b.x, a.y * b.y, a.z * b.z); } // Scalar arithmetic pub fn scale(a: Self, b: T) Self { return Self.init(a.x * b, a.y * b, a.z * b); } pub fn div(a: Self, b: T) Self { return a.scale(@as(T, 1) / b); } pub fn len2(a: Self) T { return dot(a, a); } pub fn len(a: Self) T { return @sqrt(len2(a)); } pub fn normalize(a: Self) Self { return a.div(len(a)); } pub fn neg(a: Self) Self { return a.scale(@as(T, -1)); } pub fn sqrt(a: Self) Self { return Self.init(@sqrt(a.x), @sqrt(a.y), @sqrt(a.z)); } pub fn eql(a: Self, b: Self) bool { return std.meta.eql(a, b); } pub fn approxEqAbs(a: Self, b: Self, eps: T) bool { return std.math.approxEqAbs(T, a.x, b.x, eps) and std.math.approxEqAbs(T, a.y, b.y, eps) and std.math.approxEqAbs(T, a.z, b.z, eps); } /// Reflects vector `v` around the normal vector `n`. pub fn reflect(v: Self, n: Self) Self { return v.sub(n.scale(2 * v.dot(n))); } pub fn refract(v: Self, n: Self, eta: f32) Self { const cos_theta = @minimum(-v.dot(n), 1); // Perpendicular and parallel parts of the refracted vector. const perp = v.add(n.scale(cos_theta)).scale(eta); const par = n.scale(-@sqrt(@fabs(1 - perp.len2()))); return perp.add(par); } pub fn lerp(a: Self, b: Self, t: f32) Self { return a.scale(1.0 - t).add(b.scale(t)); } pub const red = Self.init(1, 0, 0); pub const green = Self.init(0, 1, 0); pub const blue = Self.init(0, 0, 1); pub const white = Self.init(1, 1, 1); pub const black = Self.init(0, 0, 0); }; } test "add" { const a = Vec3.init(1, 2, 3); const b = Vec3.init(4, 5, 6); try expect(a.add(b).eql(Vec3.init(5, 7, 9))); } test "sub" { const a = Vec3.init(1, 2, 3); const b = Vec3.init(4, 5, 6); try expect(a.sub(b).eql(Vec3.init(-3, -3, -3))); } test "dot" { const a = Vec3.init(1, 2, 3); const b = Vec3.init(4, 5, 6); try expect(a.dot(b) == 32); } test "cross" { const a = Vec3.init(1, 2, 3); const b = Vec3.init(4, 5, 6); try expect(a.cross(b).eql(Vec3.init(-3, 6, -3))); } test "scale" { const a = Vec3.init(1, 2, 3); const b = 10.0; try expect(a.scale(b).eql(Vec3.init(10, 20, 30))); } test "norm" { const a = Vec3.init(1, 2, 3); try expect(a.len() == @sqrt(14.0)); } test "normalize" { const a = Vec3.init(10, 0, 0); try expect(a.normalize().eql(Vec3.init(1, 0, 0))); }
src/vec.zig
const std = @import("std"); const aoc = @import("aoc-lib.zig"); test "examples" { try aoc.assertEq(@as(usize, 2), part1(aoc.test1file)); try aoc.assertEq(@as(usize, 1), part2(aoc.test1file)); try aoc.assertEq(@as(usize, 454), part1(aoc.inputfile)); try aoc.assertEq(@as(usize, 649), part2(aoc.inputfile)); } fn part1(inp: anytype) usize { var lit = std.mem.split(u8, inp, "\n"); var c: usize = 0; while (lit.next()) |line| { if (line.len == 0) { break; } var fit = std.mem.tokenize(u8, line, "- :"); const n1 = std.fmt.parseInt(i64, fit.next().?, 10) catch unreachable; const n2 = std.fmt.parseInt(i64, fit.next().?, 10) catch unreachable; const ch = (fit.next().?)[0]; const str = fit.next().?; var cc: i64 = 0; for (str) |tch| { if (tch == ch) { cc += 1; } } if (cc >= n1 and cc <= n2) { c += 1; } } return c; } fn part2(inp: anytype) usize { var lit = std.mem.split(u8, inp, "\n"); var c: usize = 0; while (lit.next()) |line| { if (line.len == 0) { break; } var fit = std.mem.tokenize(u8, line, "- :"); const n1 = std.fmt.parseUnsigned(usize, fit.next().?, 10) catch unreachable; const n2 = std.fmt.parseUnsigned(usize, fit.next().?, 10) catch unreachable; const ch = (fit.next().?)[0]; const str = fit.next().?; var cc: i64 = 0; for (str) |tch| { if (tch == ch) { cc += 1; } } const first = str[n1 - 1] == ch; const second = str[n2 - 1] == ch; if ((first or second) and !(first and second)) { c += 1; } } return c; } fn day02(inp: []const u8, bench: bool) anyerror!void { var p1 = part1(inp); var p2 = part2(inp); if (!bench) { try aoc.print("Part 1: {}\nPart 2: {}\n", .{ p1, p2 }); } } pub fn main() anyerror!void { try aoc.benchme(aoc.input(), day02); }
2020/02/aoc.zig
export var vector_table linksection(".vector_table") = packed struct { initial_sp: u32 = model.memory.ram.stack_bottom, reset: EntryPoint = reset, system_exceptions: [14]EntryPoint = [1]EntryPoint{exception} ** 14, interrupts: [model.number_of_peripherals]EntryPoint = [1]EntryPoint{exception} ** model.number_of_peripherals, const EntryPoint = fn () callconv(.C) noreturn; }{}; fn reset() callconv(.C) noreturn { model.memory.ram.prepare(); Uart.prepare(); Timers[0].prepare(); Terminal.reset(); Terminal.attribute(Terminal.background_green); Terminal.clearScreen(); Terminal.move(1, 1); log("https://github.com/markfirmware/zig-vector-table is running on a microbit!", .{}); var status_line_number: u32 = 2; if (Ficr.isQemu()) { Terminal.attribute(Terminal.foreground_magenta); log("actually qemu -M microbit (zig build qemu)", .{}); log("the emulated timer can be slower than a real one", .{}); log(" and also slightly erratic (due to running on a shared host)", .{}); Terminal.attribute(Terminal.foreground_black); status_line_number += 3; Terminal.move(status_line_number, 1); log("waiting for timer ...", .{}); } var t = TimeKeeper.ofMilliseconds(1000); var i: u32 = 0; while (true) { Uart.update(); if (t.isFinishedThenReset()) { i += 1; Terminal.move(status_line_number, 1); log("up and running for {} seconds!", .{i}); } } } fn exception() callconv(.C) noreturn { const ipsr_interrupt_program_status_register = asm ("mrs %[ipsr_interrupt_program_status_register], ipsr" : [ipsr_interrupt_program_status_register] "=r" (-> usize) ); const isr_number = ipsr_interrupt_program_status_register & 0xff; panicf("arm exception ipsr.isr_number {}", .{isr_number}); } pub fn panic(message: []const u8, trace: ?*std.builtin.StackTrace) noreturn { _ = trace; panicf("panic(): {s}", .{message}); } fn hangf(comptime fmt: []const u8, args: anytype) noreturn { log(fmt, args); Uart.drainTx(); while (true) {} } fn panicf(comptime fmt: []const u8, args: anytype) noreturn { @setCold(true); log("\npanicf(): " ++ fmt, args); hangf("panic completed", .{}); } const Ficr = struct { pub fn deviceId() u64 { return @as(u64, contents[0x64 / 4]) << 32 | contents[0x60 / 4]; } pub fn isQemu() bool { return deviceId() == 0x1234567800000003; } pub const contents = @intToPtr(*[64]u32, 0x10000000); }; const Gpio = struct { const p = Peripheral.at(0x50000000); pub const registers = struct { pub const out = p.typedRegisterGroup(0x504, 0x508, 0x50c, Pins); pub const in = p.typedRegister(0x510, Pins); pub const direction = p.typedRegisterGroup(0x514, 0x518, 0x51c, Pins); pub const config = p.typedRegisterArray(32, 0x700, Config); pub const Config = packed struct { output_connected: u1, input_disconnected: u1, pull: enum(u2) { disabled, down, up = 3 }, unused1: u4 = 0, drive: enum(u3) { s0s1, h0s1, s0h1, h0h1, d0s1, d0h1, s0d1, h0d1 }, unused2: u5 = 0, sense: enum(u2) { disabled, high = 2, low }, unused3: u14 = 0, }; }; }; const Peripheral = struct { fn at(base: u32) type { assert(base == 0xe000e000 or base == 0x50000000 or base & 0xfffe0fff == 0x40000000); return struct { const peripheral_id = base >> 12 & 0x1f; fn mmio(address: u32, comptime T: type) *align(4) volatile T { return @intToPtr(*align(4) volatile T, address); } fn event(offset: u32) Event { var e: Event = undefined; e.address = base + offset; return e; } fn typedRegister(offset: u32, comptime the_layout: type) type { return struct { pub const layout = the_layout; pub noinline fn read() layout { return mmio(base + offset, layout).*; } pub noinline fn write(x: layout) void { mmio(base + offset, layout).* = x; } }; } fn register(offset: u32) type { return typedRegister(offset, u32); } fn registerGroup(offsets: RegisterGroup) type { return typedRegisterGroup(offsets, u32); } fn typedRegisterGroup(offsets: RegisterGroup, comptime T: type) type { assert(offsets.read == offsets.write); assert(offsets.set == offsets.write + 4); assert(offsets.clear == offsets.set + 4); return struct { pub fn read() T { return typedRegister(offsets.read, T).read(); } pub fn write(x: T) void { typedRegister(offsets.write, T).write(x); } pub fn set(x: T) void { typedRegister(offsets.set, T).write(x); } pub fn clear(x: T) void { typedRegister(offsets.clear, T).write(x); } }; } fn Register(comptime T: type) type { return struct { address: u32, pub noinline fn read(self: @This()) T { return mmio(self.address, T).*; } pub noinline fn write(self: @This(), x: T) void { mmio(self.address, T).* = x; } }; } fn typedRegisterArray(comptime length: u32, offset: u32, comptime T: type) [length]Register(T) { return addressedArray(length, offset, 4, Register(T)); } fn registerArray(comptime length: u32, offset: u32) [length]Register(u32) { return addressedArray(length, offset, 4, Register(u32)); } fn registerArrayDelta(comptime length: u32, offset: u32, delta: u32) [length]Register(u32) { return addressedArray(length, offset, delta, Register(u32)); } fn shorts(comptime EventsType: type, comptime TasksType: type, event2: EventsType.enums, task2: TasksType.enums) type { _ = event2; _ = task2; return struct { fn enable(pairs: []struct { event: EventsType.enums, task: TasksType.enums }) void { _ = pairs; } }; } fn task(offset: u32) Task { var t: Task = undefined; t.address = base + offset; return t; } fn addressedArray(comptime length: u32, offset: u32, delta: u32, comptime T: type) [length]T { var t: [length]T = undefined; var i: u32 = 0; while (i < length) : (i += 1) { t[i].address = base + offset + i * delta; } return t; } fn eventArray(comptime length: u32, offset: u32) [length]Event { return addressedArray(length, offset, 4, Event); } fn taskArray(comptime length: u32, offset: u32) [length]Task { return addressedArray(length, offset, 4, Task); } fn taskArrayDelta(comptime length: u32, offset: u32, delta: u32) [length]Task { return addressedArray(length, offset, delta, Task); } const Event = struct { address: u32, pub fn clearEvent(self: Event) void { mmio(self.address, u32).* = 0; } pub fn eventOccurred(self: Event) bool { return mmio(self.address, u32).* == 1; } }; const RegisterGroup = struct { read: u32, write: u32, set: u32, clear: u32, }; const Task = struct { address: u32, pub fn doTask(self: Task) void { mmio(self.address, u32).* = 1; } }; }; } }; pub const Pins = packed struct { i2c_scl: u1 = 0, ring2: u1 = 0, ring1: u1 = 0, ring0: u1 = 0, led_cathodes: u9 = 0, led_anodes: u3 = 0, unused1: u1 = 0, button_a: u1 = 0, unused2: u6 = 0, target_txd: u1 = 0, target_rxd: u1 = 0, button_b: u1 = 0, unused3: u3 = 0, i2c_sda: u1 = 0, unused4: u1 = 0, pub const of = struct { pub const i2c_scl = Pins{ .i2c_scl = 1 }; pub const ring2 = Pins{ .ring2 = 1 }; pub const ring1 = Pins{ .ring1 = 1 }; pub const ring0 = Pins{ .ring0 = 1 }; pub const led_anodes = Pins{ .led_anodes = 0x7 }; pub const led_cathodes = Pins{ .led_cathodes = 0x1ff }; pub const leds = led_anodes.maskUnion(led_cathodes); pub const button_a = Pins{ .button_a = 1 }; pub const target_txd = Pins{ .target_txd = 1 }; pub const target_rxd = Pins{ .target_rxd = 1 }; pub const button_b = Pins{ .button_b = 1 }; pub const i2c_sda = Pins{ .i2c_sda = 1 }; }; pub fn clear(self: Pins) void { Gpio.registers.out.clear(self); } pub fn config(self: Pins, the_config: Gpio.registers.Config) void { var i: u32 = 0; while (i < self.width()) : (i += 1) { Gpio.registers.config[self.bitPosition(i)].write(the_config); } } pub fn connectI2c(self: Pins) void { self.config(.{ .output_connected = 0, .input_disconnected = 0, .pull = .disabled, .drive = .s0d1, .sense = .disabled }); } pub fn connectInput(self: Pins) void { self.config(.{ .output_connected = 0, .input_disconnected = 0, .pull = .disabled, .drive = .s0s1, .sense = .disabled }); } pub fn connectIo(self: Pins) void { self.config(.{ .output_connected = 1, .input_disconnected = 0, .pull = .disabled, .drive = .s0s1, .sense = .disabled }); } pub fn connectOutput(self: Pins) void { self.config(.{ .output_connected = 1, .input_disconnected = 1, .pull = .disabled, .drive = .s0s1, .sense = .disabled }); } pub fn directionClear(self: @This()) void { Gpio.registers.direction.clear(self); } pub fn directionSet(self: @This()) void { Gpio.registers.direction.set(self); } pub fn mask(self: Pins) u32 { assert(@sizeOf(Pins) == 4); return @bitCast(u32, self); } pub fn maskUnion(self: Pins, other: Pins) Pins { return @bitCast(Pins, self.mask() | other.mask()); } pub fn outRead(self: Pins) u32 { return (@bitCast(u32, Gpio.registers.out.read()) & self.mask()) >> self.bitPosition(0); } fn bitPosition(self: Pins, i: u32) u5 { return @truncate(u5, @ctz(u32, self.mask()) + i); } pub fn read(self: Pins) u32 { return (@bitCast(u32, Gpio.registers.in.read()) & self.mask()) >> self.bitPosition(0); } pub fn set(self: Pins) void { Gpio.registers.out.set(self); } fn width(self: Pins) u32 { return 32 - @clz(u32, self.mask()) - @ctz(u32, self.mask()); } pub fn write(self: Pins, x: u32) void { var new = Gpio.registers.out.read().mask() & ~self.mask(); new |= (x << self.bitPosition(0)) & self.mask(); Gpio.registers.out.write(@bitCast(Pins, new)); } pub fn writeWholeMask(self: Pins) void { Gpio.registers.out.write(self); } }; pub const Terminal = struct { pub fn attribute(n: u32) void { pair(n, 0, "m"); } pub fn clearScreen() void { pair(2, 0, "J"); } pub fn hideCursor() void { Uart.writeText(csi ++ "?25l"); } pub fn line(comptime fmt: []const u8, args: anytype) void { print(fmt, args); pair(0, 0, "K"); Uart.writeText("\n"); } pub fn move(row: u32, column: u32) void { pair(row, column, "H"); } pub fn pair(a: u32, b: u32, letter: []const u8) void { if (a <= 1 and b <= 1) { print("{s}{s}", .{ csi, letter }); } else if (b <= 1) { print("{s}{}{s}", .{ csi, a, letter }); } else if (a <= 1) { print("{s};{}{s}", .{ csi, b, letter }); } else { print("{s}{};{}{s}", .{ csi, a, b, letter }); } } pub fn requestCursorPosition() void { Uart.writeText(csi ++ "6n"); } pub fn requestDeviceCode() void { Uart.writeText(csi ++ "c"); } pub fn reset() void { Uart.writeText("\x1bc"); } pub fn restoreCursorAndAttributes() void { Uart.writeText("\x1b8"); } pub fn saveCursorAndAttributes() void { Uart.writeText("\x1b7"); } pub fn setLineWrap(enabled: bool) void { pair(0, 0, if (enabled) "7h" else "7l"); } pub fn setScrollingRegion(top: u32, bottom: u32) void { pair(top, bottom, "r"); } pub fn showCursor() void { Uart.writeText(csi ++ "?25h"); } const csi = "\x1b["; const background_green = 42; const background_yellow = 43; const foreground_black = 30; const foreground_magenta = 35; const print = Uart.print; var height: u32 = 24; var width: u32 = 80; }; pub const TimeKeeper = struct { duration: u32, max_elapsed: u32, start_time: u32, fn capture(self: *TimeKeeper) u32 { _ = self; Timers[0].tasks.capture[0].doTask(); return Timers[0].registers.capture_compare[0].read(); } fn elapsed(self: *TimeKeeper) u32 { return self.capture() -% self.start_time; } fn ofMilliseconds(ms: u32) TimeKeeper { var t: TimeKeeper = undefined; t.prepare(1000 * ms); return t; } fn prepare(self: *TimeKeeper, duration: u32) void { self.duration = duration; self.max_elapsed = 0; self.reset(); } fn isFinishedThenReset(self: *TimeKeeper) bool { const since = self.elapsed(); if (since >= self.duration) { if (since > self.max_elapsed) { self.max_elapsed = since; } self.reset(); return true; } else { return false; } } fn reset(self: *TimeKeeper) void { self.start_time = self.capture(); } fn wait(self: *TimeKeeper) void { while (!self.isFinishedThenReset()) {} } pub fn delay(duration: u32) void { var time_keeper: TimeKeeper = undefined; time_keeper.prepare(duration); time_keeper.wait(); } }; pub const Timers = [_]@TypeOf(Timer(0x40008000)){ Timer(0x40008000), Timer(0x40009000), Timer(0x4000a000) }; fn Timer(base: u32) type { return struct { const max_width = if (base == 0x40008000) @as(u32, 32) else 16; const p = Peripheral.at(base); pub const tasks = struct { pub const start = p.task(0x000); pub const stop = p.task(0x004); pub const count = p.task(0x008); pub const clear = p.task(0x00c); pub const capture = p.taskArray(4, 0x040); }; pub const events = struct { pub const compare = p.eventArray(4, 0x140); }; pub const registers = struct { pub const shorts = p.register(0x200); pub const interrupts = p.registerSetClear(0x304, 0x308); pub const mode = p.register(0x504); pub const bit_mode = p.register(0x508); pub const prescaler = p.register(0x510); pub const capture_compare = p.registerArray(4, 0x540); }; pub fn captureAndRead() u32 { tasks.capture[0].doTask(); return registers.capture_compare[0].read(); } pub fn prepare() void { registers.mode.write(0x0); registers.bit_mode.write(if (base == 0x40008000) @as(u32, 0x3) else 0x0); registers.prescaler.write(if (base == 0x40008000) @as(u32, 4) else 9); tasks.start.doTask(); const now = captureAndRead(); var i: u32 = 0; while (captureAndRead() == now) : (i += 1) { if (i == 1000) { panicf("timer 0x{x} is not responding", .{base}); } } } }; } const Uart = struct { const p = Peripheral.at(0x40002000); pub const tasks = struct { pub const start_rx = p.task(0x000); pub const stop_rx = p.task(0x004); pub const start_tx = p.task(0x008); pub const stop_tx = p.task(0x00c); }; pub const events = struct { pub const cts = p.event(0x100); pub const not_cts = p.event(0x104); pub const rx_ready = p.event(0x108); pub const tx_ready = p.event(0x11c); pub const error_detected = p.event(0x124); pub const rx_timeout = p.event(0x144); }; pub const registers = struct { pub const interrupts = p.registerGroup(.{ .read = 0x300, .write = 0x300, .set = 0x304, .clear = 0x308 }); pub const error_source = p.register(0x480); pub const enable = p.register(0x500); pub const pin_select_rts = p.register(0x508); pub const pin_select_txd = p.register(0x50c); pub const pin_select_cts = p.register(0x510); pub const pin_select_rxd = p.register(0x514); pub const rxd = p.register(0x518); pub const txd = p.register(0x51c); pub const baud_rate = p.register(0x524); }; const Instance = struct { pub fn write(context: *Instance, buffer: []const u8) Error!usize { _ = context; Uart.writeText(buffer); return buffer.len; } const Error = error{UartError}; const Writer = std.io.Writer(*Instance, Instance.Error, Instance.write); const writer = Writer{ .context = &instance }; var instance = Instance{}; }; var tx_busy: bool = undefined; var tx_queue: [3]u8 = undefined; var tx_queue_read: usize = undefined; var tx_queue_write: usize = undefined; var updater: ?fn () void = undefined; pub fn drainTx() void { while (tx_queue_read != tx_queue_write) { loadTxd(); } } pub fn prepare() void { Pins.of.target_txd.connectOutput(); registers.pin_select_rxd.write(Pins.of.target_rxd.bitPosition(0)); registers.pin_select_txd.write(Pins.of.target_txd.bitPosition(0)); registers.enable.write(0x04); tasks.start_rx.doTask(); tasks.start_tx.doTask(); } pub fn isReadByteReady() bool { return events.rx_ready.eventOccurred(); } pub fn print(comptime fmt: []const u8, args: anytype) void { std.fmt.format(Instance.writer, fmt, args) catch {}; } pub fn loadTxd() void { if (tx_queue_read != tx_queue_write and (!tx_busy or events.tx_ready.eventOccurred())) { events.tx_ready.clearEvent(); registers.txd.write(tx_queue[tx_queue_read]); tx_queue_read = (tx_queue_read + 1) % tx_queue.len; tx_busy = true; if (updater) |an_updater| { an_updater(); } } } pub fn log(comptime fmt: []const u8, args: anytype) void { print(fmt ++ "\n", args); } pub fn writeText(buffer: []const u8) void { for (buffer) |c| { switch (c) { '\n' => { writeByteBlocking('\r'); writeByteBlocking('\n'); }, else => writeByteBlocking(c), } } } pub fn setUpdater(new_updater: fn () void) void { updater = new_updater; } pub fn update() void { loadTxd(); } pub fn writeByteBlocking(byte: u8) void { const next = (tx_queue_write + 1) % tx_queue.len; while (next == tx_queue_read) { loadTxd(); } tx_queue[tx_queue_write] = byte; tx_queue_write = next; loadTxd(); } pub fn readByte() u8 { events.rx_ready.clearEvent(); return @truncate(u8, registers.rxd.read()); } }; const assert = std.debug.assert; const log = Uart.log; const model = @import("system_model.zig"); const std = @import("std");
main.zig
const std = @import("std"); const assert = std.debug.assert; pub const ActivationFunction = enum { ReLU, Identity, }; pub fn Layer(comptime InputType_: type, comptime inputs_size_: usize, comptime OutputType_: type, comptime outputs_size_: usize, comptime activation_function: ActivationFunction) type { return struct { const SelfType = @This(); const InputType: type = InputType_; const inputs_size: usize = inputs_size_; const OutputType: type = OutputType_; const outputs_size: usize = outputs_size_; weights: [outputs_size_][inputs_size_]SelfType.InputType = undefined, biases: [inputs_size_]SelfType.InputType = undefined, pub fn feedForward(self: *const SelfType, inputs: [*]SelfType.InputType, outputs: [*]SelfType.OutputType) void { comptime var neuron_index: usize = 0; inline while (neuron_index < outputs_size_) : (neuron_index += 1) { var input_index: usize = 0; var neuron_result: SelfType.OutputType = 0; while (input_index < inputs_size_) : (input_index += 1) { var input_result: SelfType.InputType = self.weights[neuron_index][input_index] * inputs[input_index] + self.biases[input_index]; input_result = switch (activation_function) { .ReLU => std.math.min(@as(SelfType.InputType, std.math.maxInt(SelfType.OutputType)), std.math.max(0, input_result)), .Identity => std.math.max(@as(SelfType.InputType, std.math.minInt(SelfType.OutputType)), std.math.min(@as(SelfType.InputType, std.math.maxInt(SelfType.OutputType)), input_result)), }; neuron_result += @intCast(SelfType.OutputType, input_result); } outputs[neuron_index] = neuron_result; } } }; } pub fn Network(comptime layer_list: anytype) type { return struct { const SelfType = @This(); const InputType = @TypeOf(layer_list[0]).InputType; const inputs_size = @TypeOf(layer_list[0]).inputs_size; const OutputType = @TypeOf(layer_list[layer_list.len - 1]).OutputType; const outputs_size = @TypeOf(layer_list[layer_list.len - 1]).outputs_size; layers: @TypeOf(layer_list) = layer_list, pub fn feedForward(self: *const SelfType, inputs: [*]SelfType.InputType, outputs: [*]SelfType.OutputType) void { comptime assert(self.layers.len > 0); var layer_inputs = inputs; comptime var layer_index: usize = 0; inline while (layer_index < self.layers.len - 1) : (layer_index += 1) { const layer = self.layers[layer_index]; var layer_outputs: [@TypeOf(layer).outputs_size]InputType = undefined; layer.feedForward(layer_inputs, &layer_outputs); layer_inputs = &layer_outputs; } self.layers[layer_index].feedForward(layer_inputs, outputs); } }; } pub fn ParallelNetworkGroup(comptime network_list: anytype) type { return struct { const SelfType = @This(); const InputType = @TypeOf(network_list[0]).InputType; const inputs_size = comptime calculateInputsSize(); const OutputType = @TypeOf(network_list[0]).OutputType; const outputs_size = comptime calculateOutputsSize(); networks: @TypeOf(network_list) = network_list, pub fn feedForward(self: *const SelfType, inputs: [*]SelfType.InputType, outputs: [*]SelfType.OutputType) void { comptime assert(self.networks.len > 0); comptime var inputs_index = 0; comptime var outputs_index = 0; comptime var network_index: usize = 0; inline while (network_index < network_list.len) : (network_index += 1) { const network = &self.networks[network_index]; comptime assert(@TypeOf(network.*).InputType == SelfType.InputType); comptime assert(@TypeOf(network.*).OutputType == SelfType.OutputType); network.feedForward(inputs + inputs_index, outputs + outputs_index); inputs_index += @TypeOf(network.layers[0]).inputs_size; outputs_index += @TypeOf(network.layers[network.layers.len - 1]).outputs_size; } } fn calculateInputsSize() usize { var inputs_size_counter: usize = 0; comptime var network_index = 0; inline while (network_index < network_list.len) : (network_index += 1) { inputs_size_counter += @TypeOf(network_list[network_index]).inputs_size; } return inputs_size_counter; } fn calculateOutputsSize() usize { var outputs_size_counter: usize = 0; comptime var network_index: usize = 0; inline while (network_index < network_list.len) : (network_index += 1) { outputs_size_counter += @TypeOf(network_list[network_index]).outputs_size; } return outputs_size_counter; } }; } pub fn SerialNetworkGroup(comptime network_list: anytype) type { return struct { const SelfType = @This(); const FirstNetworkType = @TypeOf(network_list[0]); const InputType = FirstNetworkType.InputType; const inputs_size = FirstNetworkType.inputs_size; const LastNetworkType = @TypeOf(network_list[network_list.len - 1]); const OutputType = LastNetworkType.OutputType; const outputs_size = LastNetworkType.outputs_size; networks: @TypeOf(network_list) = network_list, pub fn feedForward(self: *const SelfType, inputs: [*]SelfType.InputType, outputs: [*]SelfType.OutputType) void { comptime assert(self.networks.len > 0); var network_inputs = inputs; comptime var network_index: usize = 0; inline while (network_index < network_list.len - 1) : (network_index += 1) { const network = &self.networks[network_index]; const network_type = @TypeOf(network.*); var network_outputs: [network_type.outputs_size]network_type.OutputType = undefined; network.feedForward(network_inputs, &network_outputs); network_inputs = &network_outputs; } self.networks[network_index].feedForward(network_inputs, outputs); } }; } //const possible_king_squares = 64; //const possible_non_king_piece_color_squares = 5 * 2 * 64; // No +1 for the captured piece from the Shogi NNUE implementation //const halfkp_size = possible_king_squares * possible_non_king_piece_color_squares; // //const WhiteInputLayer = Layer(i16, halfkp_size, i8, halfkp_size); //const WhiteInputAffineLayer = Layer(i8, halfkp_size, i8, 256); //const white_input_network = Network(.{ readWhiteInputLayer(), readWhiteInputAffineLayer() }){}; // //const BlackInputLayer = Layer(i16, halfkp_size, i8, halfkp_size); //const BlackAffineLayer = Layer(i8, halfkp_size, i8, 256); //const black_input_network = Network(.{ readBlackInputLayer(), readBlackInputAffineLayer() }){}; // //const board_input_network = ParallelNetworkGroup(.{ white_input_network, black_input_network }){}; // //const HiddenLayer1 = Layer(i8, 2 * 256, i8, 32 * 32); //const HiddenLayer2 = Layer(i8, 32 * 32, i8, 32); //const OutputLayer = Layer(i8, 32, i32, 1); //const evaluation_hidden_network = Network(.{ readHiddenLayer1(), readHiddenLayer2(), readOutputLayer() }){}; // //pub const halfkp_2x256_32_32_network = SerialNetworkGroup(.{ board_input_network, evaluation_hidden_network }); test "Layer Identity Test" { const layer = Layer(i16, 2, i8, 2, .Identity){ .weights = [2][2]i16{ [2]i16{ -50, 4 }, [2]i16{ 3, 4 }, }, .biases = [2]i16{ 10, 50 }, }; var inputs = [2]i16{ 2, 3 }; var outputs: [2]i8 = undefined; layer.feedForward(&inputs, &outputs); assert(outputs[0] == -28); assert(outputs[1] == 78); } test "Layer ReLU Test" { const layer = Layer(i16, 2, i8, 2, .ReLU){ .weights = [2][2]i16{ [2]i16{ -50, 4 }, [2]i16{ 3, 4 }, }, .biases = [2]i16{ 10, 50 }, }; var inputs = [2]i16{ 2, 3 }; var outputs: [2]i8 = undefined; layer.feedForward(&inputs, &outputs); assert(outputs[0] == 62); assert(outputs[1] == 78); } test "Network Test" { const layer1 = Layer(i16, 2, i16, 2, .Identity){ .weights = [2][2]i16{ [2]i16{ 2, 4 }, [2]i16{ 3, 4 }, }, .biases = [2]i16{ 10, 50 }, }; const layer2 = Layer(i16, 2, i16, 1, .Identity){ .weights = [1][2]i16{ [2]i16{ 3, 5 }, }, .biases = [2]i16{ 1, 2 }, }; const network = Network(.{ layer1, layer2 }){}; var inputs = [2]i16{ 2, 3 }; var outputs: [1]i16 = undefined; network.feedForward(&inputs, &outputs); assert(outputs[0] == 621); } test "Parallel Network Test" { const layer1 = Layer(i16, 2, i16, 2, .Identity){ .weights = [2][2]i16{ [2]i16{ 2, 4 }, [2]i16{ 3, 4 }, }, .biases = [2]i16{ 10, 50 }, }; const layer2n1 = Layer(i16, 2, i16, 1, .Identity){ .weights = [1][2]i16{ [2]i16{ 3, 5 }, }, .biases = [2]i16{ 1, 2 }, }; const layer2n2 = Layer(i16, 2, i16, 1, .Identity){ .weights = [1][2]i16{ [2]i16{ 3, 6 }, }, .biases = [2]i16{ 1, 2 }, }; const network1 = Network(.{ layer1, layer2n1 }){}; const network2 = Network(.{ layer1, layer2n2 }){}; const parallel_networks = ParallelNetworkGroup(.{ network1, network2 }){}; var inputs = [4]i16{ 2, 3, 2, 3 }; var outputs: [2]i16 = undefined; parallel_networks.feedForward(&inputs, &outputs); assert(outputs[0] == 621); assert(outputs[1] == 699); } test "Serial Network Test" { const layer1 = Layer(i16, 2, i16, 2, .Identity){ .weights = [2][2]i16{ [2]i16{ 2, 4 }, [2]i16{ 3, 4 }, }, .biases = [2]i16{ 10, 50 }, }; const layer2 = Layer(i16, 2, i16, 1, .Identity){ .weights = [1][2]i16{ [2]i16{ 3, 5 }, }, .biases = [2]i16{ 1, 2 }, }; const network1 = Network(.{layer1}){}; const network2 = Network(.{layer2}){}; const serial_networks = SerialNetworkGroup(.{ network1, network2 }){}; var inputs = [2]i16{ 2, 3 }; var outputs: [1]i16 = undefined; serial_networks.feedForward(&inputs, &outputs); assert(outputs[0] == 621); } test "Composed Parallel and Serial Networks Test" { const layer1g1 = Layer(i16, 2, i16, 2, .Identity){ .weights = [2][2]i16{ [2]i16{ 2, 4 }, [2]i16{ 3, 4 }, }, .biases = [2]i16{ 10, 50 }, }; const layer2n1g1 = Layer(i16, 2, i16, 1, .Identity){ .weights = [1][2]i16{ [2]i16{ 3, 5 }, }, .biases = [2]i16{ 1, 2 }, }; const layer2n2g1 = Layer(i16, 2, i16, 1, .Identity){ .weights = [1][2]i16{ [2]i16{ 3, 6 }, }, .biases = [2]i16{ 1, 2 }, }; const network1g1 = Network(.{ layer1g1, layer2n1g1 }){}; const network2g1 = Network(.{ layer1g1, layer2n2g1 }){}; const parallel_networks = ParallelNetworkGroup(.{ network1g1, network2g1 }){}; const layer1g2 = Layer(i16, 2, i16, 1, .Identity){ .weights = [1][2]i16{ [2]i16{ -1, 1 }, }, .biases = [2]i16{ 1, 6 }, }; const networkg2 = Network(.{layer1g2}){}; const composed_network = SerialNetworkGroup(.{ parallel_networks, networkg2 }){}; var inputs = [4]i16{ 2, 3, 2, 3 }; var outputs: [1]i16 = undefined; composed_network.feedForward(&inputs, &outputs); assert(outputs[0] == 85); }
src/nnue/nn.zig
const std = @import("std"); const common = @import("common.zig"); const Line = common.Line; const Point = common.Point; const expect = std.testing.expect; const Allocator = std.mem.Allocator; const test_allocator = std.testing.allocator; const ArrayList = std.ArrayList; const AutoArrayHashMap = std.AutoArrayHashMap; // creates a hash representation (u64) of a point given by x and y coordinates. fn hash_point(x: i32, y: i32) u64 { var hasher = std.hash.Wyhash.init(0); std.hash.autoHashStrat(&hasher, Point{ .x = x, .y = y }, .Deep); return hasher.final(); } // produces a range based on the start/end. it works with increasing/decreasing ranges. fn range(allocator: *Allocator, start: i32, end: i32) anyerror!ArrayList(i32) { const d = end - start; const d_norm = if (d < 0) @as(i32, -1) else if (d > 0) @as(i32, 1) else @as(i32, 0); const len = std.math.absCast(d) + 1; var i: i32 = 0; var n = start; var arr = ArrayList(i32).init(allocator); while (i < len) : (i += 1) { try arr.append(n); n += d_norm; } return arr; } // generates the horizontal coordinates of a line. // 1. generates a range for both x and y axis; // 2. iterates over the ranges in a nested form, generating the coordinates; // 3. hash the coordinates using `hash_point` function; // 3. return the list of hashed coordinates. fn horizontal_coordinates(allocator: *Allocator, line: Line) anyerror!ArrayList(u64) { var result = ArrayList(u64).init(allocator); var i_range = try range(allocator, line.start.x, line.end.x); defer i_range.deinit(); var j_range = try range(allocator, line.start.y, line.end.y); defer j_range.deinit(); for (i_range.items) |i| { for (j_range.items) |j| { try result.append(hash_point(i, j)); } } return result; } // PART 1 // 1. iterates over all lines: // 1.1 generates coordinates for horizontal/vertical lines only using `horizontal_coordinates`. // 1.2 store coordinates at a `ArrayHashMap` using the coordinate hash as key and counter as value; // 1.2.1 everytime it sees a repeated increase the counter. // 2. iterate over the `ArrayHashMap` and count the number of coordinates that have more than 2 occurrencies; pub fn count_line_overlaps(allocator: *Allocator, lines: ArrayList(Line)) anyerror!usize { var occurrencies = AutoArrayHashMap(u64, i32).init(allocator); defer occurrencies.deinit(); for (lines.items) |line| { // not an horizontal line. if (line.start.x != line.end.x and line.start.y != line.end.y) { continue; } var coordinates = try horizontal_coordinates(allocator, line); defer coordinates.deinit(); for (coordinates.items) |coordinate| { var curr = occurrencies.get(coordinate) orelse 0; try occurrencies.put(coordinate, curr + 1); } } var iter = occurrencies.iterator(); var count: usize = 0; while (iter.next()) |entry| { if (entry.value_ptr.* > 1) { count += 1; } } return count; } // decides if it is a vertical/horizontal or a diagonal line, and then generate // the coordinates using the proper function. fn line_coordinates(allocator: *Allocator, line: Line) anyerror!ArrayList(u64) { if (line.start.x != line.end.x and line.start.y != line.end.y) { return vertical_coordinates(allocator, line); } return horizontal_coordinates(allocator, line); } // generates vertical coordinates. // 1. calculate the x and y "movements", this is how the coordinates are going to be generated; // 2. iterate until the x and y are equal to the line.end coordinates; // 3. add the last coordinate since it is inclusive; fn vertical_coordinates(allocator: *Allocator, line: Line) anyerror!ArrayList(u64) { var result = ArrayList(u64).init(allocator); const x_move = if (line.start.x > line.end.x) @as(i32, -1) else @as(i32, 1); const y_move = if (line.start.y > line.end.y) @as(i32, -1) else @as(i32, 1); var x: i32 = line.start.x; var y: i32 = line.start.y; while (x != line.end.x and y != line.end.y) { try result.append(hash_point(x, y)); x += x_move; y += y_move; } // add the end point. try result.append(hash_point(line.end.x, line.end.y)); return result; } // PART 2 // 1. iterates over all lines: // 1.1 generates coordinates for horizontal/vertical and diagonal lines. // 1.2 store coordinates at a `ArrayHashMap` using the coordinate hash as key and counter as value; // 1.2.1 everytime it sees a repeated increase the counter. // 2. iterate over the `ArrayHashMap` and count the number of coordinates that have more than 2 occurrencies; pub fn count_line_overlaps_with_diagonal(allocator: *Allocator, lines: ArrayList(Line)) anyerror!usize { var occurrencies = AutoArrayHashMap(u64, i32).init(allocator); defer occurrencies.deinit(); for (lines.items) |line| { // not an horizontal line. var coordinates: ArrayList(u64) = try line_coordinates(allocator, line); defer coordinates.deinit(); for (coordinates.items) |coordinate| { var curr = occurrencies.get(coordinate) orelse 0; try occurrencies.put(coordinate, curr + 1); } } var iter = occurrencies.iterator(); var count: usize = 0; while (iter.next()) |entry| { if (entry.value_ptr.* > 1) { count += 1; } } return count; } test "line overlap" { var lines = ArrayList(Line).init(test_allocator); defer lines.deinit(); try lines.append(Line { .start = Point { .x = 0, .y = 9 }, .end = Point { .x = 5, .y = 9 } }); try lines.append(Line { .start = Point { .x = 8, .y = 0 }, .end = Point { .x = 0, .y = 8 } }); try lines.append(Line { .start = Point { .x = 9, .y = 4 }, .end = Point { .x = 3, .y = 4 } }); try lines.append(Line { .start = Point { .x = 2, .y = 2 }, .end = Point { .x = 2, .y = 1 } }); try lines.append(Line { .start = Point { .x = 7, .y = 0 }, .end = Point { .x = 7, .y = 4 } }); try lines.append(Line { .start = Point { .x = 6, .y = 4 }, .end = Point { .x = 2, .y = 0 } }); try lines.append(Line { .start = Point { .x = 0, .y = 9 }, .end = Point { .x = 2, .y = 9 } }); try lines.append(Line { .start = Point { .x = 3, .y = 4 }, .end = Point { .x = 1, .y = 4 } }); try lines.append(Line { .start = Point { .x = 0, .y = 0 }, .end = Point { .x = 8, .y = 8 } }); try lines.append(Line { .start = Point { .x = 5, .y = 5 }, .end = Point { .x = 8, .y = 2 } }); var points_with_overlap = try count_line_overlaps(test_allocator, lines); try expect(points_with_overlap == 5); var points_with_overlap_diagonal = try count_line_overlaps_with_diagonal(test_allocator, lines); try expect(points_with_overlap_diagonal == 12); }
day5/src/solution.zig
const high_bit = 1 << @typeInfo(usize).Int.bits - 1; pub const Status = extern enum(usize) { /// The operation completed successfully. Success = 0, /// The image failed to load. LoadError = high_bit | 1, /// A parameter was incorrect. InvalidParameter = high_bit | 2, /// The operation is not supported. Unsupported = high_bit | 3, /// The buffer was not the proper size for the request. BadBufferSize = high_bit | 4, /// The buffer is not large enough to hold the requested data. The required buffer size is returned in the appropriate parameter when this error occurs. BufferTooSmall = high_bit | 5, /// There is no data pending upon return. NotReady = high_bit | 6, /// The physical device reported an error while attempting the operation. DeviceError = high_bit | 7, /// The device cannot be written to. WriteProtected = high_bit | 8, /// A resource has run out. OutOfResources = high_bit | 9, /// An inconstancy was detected on the file system causing the operating to fail. VolumeCorrupted = high_bit | 10, /// There is no more space on the file system. VolumeFull = high_bit | 11, /// The device does not contain any medium to perform the operation. NoMedia = high_bit | 12, /// The medium in the device has changed since the last access. MediaChanged = high_bit | 13, /// The item was not found. NotFound = high_bit | 14, /// Access was denied. AccessDenied = high_bit | 15, /// The server was not found or did not respond to the request. NoResponse = high_bit | 16, /// A mapping to a device does not exist. NoMapping = high_bit | 17, /// The timeout time expired. Timeout = high_bit | 18, /// The protocol has not been started. NotStarted = high_bit | 19, /// The protocol has already been started. AlreadyStarted = high_bit | 20, /// The operation was aborted. Aborted = high_bit | 21, /// An ICMP error occurred during the network operation. IcmpError = high_bit | 22, /// A TFTP error occurred during the network operation. TftpError = high_bit | 23, /// A protocol error occurred during the network operation. ProtocolError = high_bit | 24, /// The function encountered an internal version that was incompatible with a version requested by the caller. IncompatibleVersion = high_bit | 25, /// The function was not performed due to a security violation. SecurityViolation = high_bit | 26, /// A CRC error was detected. CrcError = high_bit | 27, /// Beginning or end of media was reached EndOfMedia = high_bit | 28, /// The end of the file was reached. EndOfFile = high_bit | 31, /// The language specified was invalid. InvalidLanguage = high_bit | 32, /// The security status of the data is unknown or compromised and the data must be updated or replaced to restore a valid security status. CompromisedData = high_bit | 33, /// There is an address conflict address allocation IpAddressConflict = high_bit | 34, /// A HTTP error occurred during the network operation. HttpError = high_bit | 35, NetworkUnreachable = high_bit | 100, HostUnreachable = high_bit | 101, ProtocolUnreachable = high_bit | 102, PortUnreachable = high_bit | 103, ConnectionFin = high_bit | 104, ConnectionReset = high_bit | 105, ConnectionRefused = high_bit | 106, /// The string contained one or more characters that the device could not render and were skipped. WarnUnknownGlyph = 1, /// The handle was closed, but the file was not deleted. WarnDeleteFailure = 2, /// The handle was closed, but the data to the file was not flushed properly. WarnWriteFailure = 3, /// The resulting buffer was too small, and the data was truncated to the buffer size. WarnBufferTooSmall = 4, /// The data has not been updated within the timeframe set by localpolicy for this type of data. WarnStaleData = 5, /// The resulting buffer contains UEFI-compliant file system. WarnFileSystem = 6, /// The operation will be processed across a system reset. WarnResetRequired = 7, _, };
lib/std/os/uefi/status.zig
const inputFile = @embedFile("./input/day07.txt"); const std = @import("std"); const Allocator = std.mem.Allocator; // const ArrayList = std.ArrayList; const assert = std.debug.assert; /// Part 1 /// Simplest solution, no math knowledge required /// Brute forces from 0 - max, /// The distance from the current point to each other point /// Complexity: O(n2) fn shortestDistanceBF(numCrabsAtDist: []u32) usize { var bestPoint: usize = undefined; var bestPointFuel: usize = std.math.maxInt(usize); for (numCrabsAtDist) |_, i| { var dist: usize = 0; // compute distance for (numCrabsAtDist) |n, j| { dist += n * absDiff(i, j); } if (dist < bestPointFuel) { bestPoint = i; bestPointFuel = dist; } } return bestPointFuel; } /// Part 2 /// Simplest solution, no math knowledge required /// Brute forces from 0 - max, /// The distance from the current point to each other point /// Complexity: O(n2) fn shortestTriangleDistanceBF(numCrabsAtDist: []u32) usize { var bestPoint: usize = undefined; var bestPointFuel: usize = std.math.maxInt(usize); for (numCrabsAtDist) |_, i| { var dist: usize = 0; // compute distance for (numCrabsAtDist) |n, j| { dist += n * triangleDiff(i, j); } if (dist < bestPointFuel) { bestPoint = i; bestPointFuel = dist; } } return bestPointFuel; } // Absolute difference of two unsigned numbers // performs branching fn absDiff(x: usize, y: usize) usize { if (x > y) return x - y; return y - x; } /// Given two numbers, compute the absolute triangle number diff between them /// e.g. if abs(x - y) = 3, the triangle number diff is T(3) = 1 + 2 + 3 = 6 fn triangleDiff(x: usize, y: usize) usize { if (x > y) return triangleDiff(y, x); if (x == y) return 0; const d = y - x; return d * (d + 1) / 2; } pub fn main() !void { const stdout = std.io.getStdOut().writer(); var gpa = std.heap.GeneralPurposeAllocator(.{}){}; var allocator = &gpa.allocator; defer std.debug.assert(!gpa.deinit()); // no leaks const numCrabsAtDist = try parseInput(inputFile, allocator); defer allocator.free(numCrabsAtDist); try stdout.print("Part 1: {d}\nPart2: {d}\n", .{ shortestDistanceBF(numCrabsAtDist), shortestTriangleDistanceBF(numCrabsAtDist) }); } /// Given a list of numbers /// Returns a list of counts of each number in the range 0 - max /// Where the max is whatever is in the input file /// Caller is responsible for freeing memory fn parseInput(input: []const u8, allocator: *Allocator) ![]u32 { // First pass: find max val var max: usize = 0; { var start: usize = 0; while (std.mem.indexOfAnyPos(u8, input, start, &.{ ',', '\n' })) |end| : (start = end + 1) { const val = try std.fmt.parseInt(u32, input[start..end], 10); if (val > max) max = val; } } // Allocate zeroes from 0 - max var result = try allocator.alloc(u32, max + 1); std.mem.set(u32, result, 0); // Second pass: fill result { var start: usize = 0; while (std.mem.indexOfAnyPos(u8, input, start, &.{ ',', '\n' })) |end| : (start = end + 1) { const val = try std.fmt.parseInt(u32, input[start..end], 10); result[val] += 1; } } return result; }
src/day07.zig
const std = @import("std.zig"); const assert = std.debug.assert; const meta = std.meta; const mem = std.mem; const Allocator = mem.Allocator; const testing = std.testing; /// A MultiArrayList stores a list of a struct type. /// Instead of storing a single list of items, MultiArrayList /// stores separate lists for each field of the struct. /// This allows for memory savings if the struct has padding, /// and also improves cache usage if only some fields are needed /// for a computation. The primary API for accessing fields is /// the `slice()` function, which computes the start pointers /// for the array of each field. From the slice you can call /// `.items(.<field_name>)` to obtain a slice of field values. pub fn MultiArrayList(comptime S: type) type { return struct { bytes: [*]align(@alignOf(S)) u8 = undefined, len: usize = 0, capacity: usize = 0, pub const Elem = S; pub const Field = meta.FieldEnum(S); /// A MultiArrayList.Slice contains cached start pointers for each field in the list. /// These pointers are not normally stored to reduce the size of the list in memory. /// If you are accessing multiple fields, call slice() first to compute the pointers, /// and then get the field arrays from the slice. pub const Slice = struct { /// This array is indexed by the field index which can be obtained /// by using @enumToInt() on the Field enum ptrs: [fields.len][*]u8, len: usize, capacity: usize, pub fn items(self: Slice, comptime field: Field) []FieldType(field) { const F = FieldType(field); if (self.capacity == 0) { return &[_]F{}; } const byte_ptr = self.ptrs[@enumToInt(field)]; const casted_ptr: [*]F = if (@sizeOf([*]F) == 0) undefined else @ptrCast([*]F, @alignCast(@alignOf(F), byte_ptr)); return casted_ptr[0..self.len]; } pub fn toMultiArrayList(self: Slice) Self { if (self.ptrs.len == 0) { return .{}; } const unaligned_ptr = self.ptrs[sizes.fields[0]]; const aligned_ptr = @alignCast(@alignOf(S), unaligned_ptr); const casted_ptr = @ptrCast([*]align(@alignOf(S)) u8, aligned_ptr); return .{ .bytes = casted_ptr, .len = self.len, .capacity = self.capacity, }; } pub fn deinit(self: *Slice, gpa: *Allocator) void { var other = self.toMultiArrayList(); other.deinit(gpa); self.* = undefined; } }; const Self = @This(); const fields = meta.fields(S); /// `sizes.bytes` is an array of @sizeOf each S field. Sorted by alignment, descending. /// `sizes.fields` is an array mapping from `sizes.bytes` array index to field index. const sizes = blk: { const Data = struct { size: usize, size_index: usize, alignment: usize, }; var data: [fields.len]Data = undefined; for (fields) |field_info, i| { data[i] = .{ .size = @sizeOf(field_info.field_type), .size_index = i, .alignment = if (@sizeOf(field_info.field_type) == 0) 1 else field_info.alignment, }; } const Sort = struct { fn lessThan(trash: *i32, lhs: Data, rhs: Data) bool { return lhs.alignment > rhs.alignment; } }; var trash: i32 = undefined; // workaround for stage1 compiler bug std.sort.sort(Data, &data, &trash, Sort.lessThan); var sizes_bytes: [fields.len]usize = undefined; var field_indexes: [fields.len]usize = undefined; for (data) |elem, i| { sizes_bytes[i] = elem.size; field_indexes[i] = elem.size_index; } break :blk .{ .bytes = sizes_bytes, .fields = field_indexes, }; }; /// Release all allocated memory. pub fn deinit(self: *Self, gpa: *Allocator) void { gpa.free(self.allocatedBytes()); self.* = undefined; } /// The caller owns the returned memory. Empties this MultiArrayList. pub fn toOwnedSlice(self: *Self) Slice { const result = self.slice(); self.* = .{}; return result; } /// Compute pointers to the start of each field of the array. /// If you need to access multiple fields, calling this may /// be more efficient than calling `items()` multiple times. pub fn slice(self: Self) Slice { var result: Slice = .{ .ptrs = undefined, .len = self.len, .capacity = self.capacity, }; var ptr: [*]u8 = self.bytes; for (sizes.bytes) |field_size, i| { result.ptrs[sizes.fields[i]] = ptr; ptr += field_size * self.capacity; } return result; } /// Get the slice of values for a specified field. /// If you need multiple fields, consider calling slice() /// instead. pub fn items(self: Self, comptime field: Field) []FieldType(field) { return self.slice().items(field); } /// Overwrite one array element with new data. pub fn set(self: *Self, index: usize, elem: S) void { const slices = self.slice(); inline for (fields) |field_info, i| { slices.items(@intToEnum(Field, i))[index] = @field(elem, field_info.name); } } /// Obtain all the data for one array element. pub fn get(self: *Self, index: usize) S { const slices = self.slice(); var result: S = undefined; inline for (fields) |field_info, i| { @field(result, field_info.name) = slices.items(@intToEnum(Field, i))[index]; } return result; } /// Extend the list by 1 element. Allocates more memory as necessary. pub fn append(self: *Self, gpa: *Allocator, elem: S) !void { try self.ensureUnusedCapacity(gpa, 1); self.appendAssumeCapacity(elem); } /// Extend the list by 1 element, but asserting `self.capacity` /// is sufficient to hold an additional item. pub fn appendAssumeCapacity(self: *Self, elem: S) void { assert(self.len < self.capacity); self.len += 1; self.set(self.len - 1, elem); } /// Extend the list by 1 element, asserting `self.capacity` /// is sufficient to hold an additional item. Returns the /// newly reserved index with uninitialized data. pub fn addOneAssumeCapacity(self: *Self) usize { assert(self.len < self.capacity); const index = self.len; self.len += 1; return index; } /// Inserts an item into an ordered list. Shifts all elements /// after and including the specified index back by one and /// sets the given index to the specified element. May reallocate /// and invalidate iterators. pub fn insert(self: *Self, gpa: *Allocator, index: usize, elem: S) void { try self.ensureCapacity(gpa, self.len + 1); self.insertAssumeCapacity(index, elem); } /// Inserts an item into an ordered list which has room for it. /// Shifts all elements after and including the specified index /// back by one and sets the given index to the specified element. /// Will not reallocate the array, does not invalidate iterators. pub fn insertAssumeCapacity(self: *Self, index: usize, elem: S) void { assert(self.len < self.capacity); assert(index <= self.len); self.len += 1; const slices = self.slice(); inline for (fields) |field_info, field_index| { const field_slice = slices.items(@intToEnum(Field, field_index)); var i: usize = self.len-1; while (i > index) : (i -= 1) { field_slice[i] = field_slice[i-1]; } field_slice[index] = @field(elem, field_info.name); } } /// Remove the specified item from the list, swapping the last /// item in the list into its position. Fast, but does not /// retain list ordering. pub fn swapRemove(self: *Self, index: usize) void { const slices = self.slice(); inline for (fields) |field_info, i| { const field_slice = slices.items(@intToEnum(Field, i)); field_slice[index] = field_slice[self.len-1]; field_slice[self.len-1] = undefined; } self.len -= 1; } /// Remove the specified item from the list, shifting items /// after it to preserve order. pub fn orderedRemove(self: *Self, index: usize) void { const slices = self.slice(); inline for (fields) |field_info, field_index| { const field_slice = slices.items(@intToEnum(Field, field_index)); var i = index; while (i < self.len-1) : (i += 1) { field_slice[i] = field_slice[i+1]; } field_slice[i] = undefined; } self.len -= 1; } /// Adjust the list's length to `new_len`. /// Does not initialize added items, if any. pub fn resize(self: *Self, gpa: *Allocator, new_len: usize) !void { try self.ensureTotalCapacity(gpa, new_len); self.len = new_len; } /// Attempt to reduce allocated capacity to `new_len`. /// If `new_len` is greater than zero, this may fail to reduce the capacity, /// but the data remains intact and the length is updated to new_len. pub fn shrinkAndFree(self: *Self, gpa: *Allocator, new_len: usize) void { if (new_len == 0) { gpa.free(self.allocatedBytes()); self.* = .{}; return; } assert(new_len <= self.capacity); assert(new_len <= self.len); const other_bytes = gpa.allocAdvanced( u8, @alignOf(S), capacityInBytes(new_len), .exact, ) catch { const self_slice = self.slice(); inline for (fields) |field_info, i| { if (@sizeOf(field_info.field_type) != 0) { const field = @intToEnum(Field, i); const dest_slice = self_slice.items(field)[new_len..]; const byte_count = dest_slice.len * @sizeOf(field_info.field_type); // We use memset here for more efficient codegen in safety-checked, // valgrind-enabled builds. Otherwise the valgrind client request // will be repeated for every element. @memset(@ptrCast([*]u8, dest_slice.ptr), undefined, byte_count); } } self.len = new_len; return; }; var other = Self{ .bytes = other_bytes.ptr, .capacity = new_len, .len = new_len, }; self.len = new_len; const self_slice = self.slice(); const other_slice = other.slice(); inline for (fields) |field_info, i| { if (@sizeOf(field_info.field_type) != 0) { const field = @intToEnum(Field, i); // TODO we should be able to use std.mem.copy here but it causes a // test failure on aarch64 with -OReleaseFast const src_slice = mem.sliceAsBytes(self_slice.items(field)); const dst_slice = mem.sliceAsBytes(other_slice.items(field)); @memcpy(dst_slice.ptr, src_slice.ptr, src_slice.len); } } gpa.free(self.allocatedBytes()); self.* = other; } /// Reduce length to `new_len`. /// Invalidates pointers to elements `items[new_len..]`. /// Keeps capacity the same. pub fn shrinkRetainingCapacity(self: *Self, new_len: usize) void { self.len = new_len; } /// Deprecated: call `ensureUnusedCapacity` or `ensureTotalCapacity`. pub const ensureCapacity = ensureTotalCapacity; /// Modify the array so that it can hold at least `new_capacity` items. /// Implements super-linear growth to achieve amortized O(1) append operations. /// Invalidates pointers if additional memory is needed. pub fn ensureTotalCapacity(self: *Self, gpa: *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; } return self.setCapacity(gpa, better_capacity); } /// Modify the array so that it can hold at least `additional_count` **more** items. /// Invalidates pointers if additional memory is needed. pub fn ensureUnusedCapacity(self: *Self, gpa: *Allocator, additional_count: usize) !void { return self.ensureTotalCapacity(gpa, self.len + additional_count); } /// Modify the array so that it can hold exactly `new_capacity` items. /// Invalidates pointers if additional memory is needed. /// `new_capacity` must be greater or equal to `len`. pub fn setCapacity(self: *Self, gpa: *Allocator, new_capacity: usize) !void { assert(new_capacity >= self.len); const new_bytes = try gpa.allocAdvanced( u8, @alignOf(S), capacityInBytes(new_capacity), .exact, ); if (self.len == 0) { gpa.free(self.allocatedBytes()); self.bytes = new_bytes.ptr; self.capacity = new_capacity; return; } var other = Self{ .bytes = new_bytes.ptr, .capacity = new_capacity, .len = self.len, }; const self_slice = self.slice(); const other_slice = other.slice(); inline for (fields) |field_info, i| { if (@sizeOf(field_info.field_type) != 0) { const field = @intToEnum(Field, i); // TODO we should be able to use std.mem.copy here but it causes a // test failure on aarch64 with -OReleaseFast const src_slice = mem.sliceAsBytes(self_slice.items(field)); const dst_slice = mem.sliceAsBytes(other_slice.items(field)); @memcpy(dst_slice.ptr, src_slice.ptr, src_slice.len); } } gpa.free(self.allocatedBytes()); self.* = other; } /// Create a copy of this list with a new backing store, /// using the specified allocator. pub fn clone(self: Self, gpa: *Allocator) !Self { var result = Self{}; errdefer result.deinit(gpa); try result.ensureCapacity(gpa, self.len); result.len = self.len; const self_slice = self.slice(); const result_slice = result.slice(); inline for (fields) |field_info, i| { if (@sizeOf(field_info.field_type) != 0) { const field = @intToEnum(Field, i); // TODO we should be able to use std.mem.copy here but it causes a // test failure on aarch64 with -OReleaseFast const src_slice = mem.sliceAsBytes(self_slice.items(field)); const dst_slice = mem.sliceAsBytes(result_slice.items(field)); @memcpy(dst_slice.ptr, src_slice.ptr, src_slice.len); } } return result; } fn capacityInBytes(capacity: usize) usize { const sizes_vector: std.meta.Vector(sizes.bytes.len, usize) = sizes.bytes; const capacity_vector = @splat(sizes.bytes.len, capacity); return @reduce(.Add, capacity_vector * sizes_vector); } fn allocatedBytes(self: Self) []align(@alignOf(S)) u8 { return self.bytes[0..capacityInBytes(self.capacity)]; } fn FieldType(field: Field) type { return meta.fieldInfo(S, field).field_type; } }; } test "basic usage" { const ally = testing.allocator; const Foo = struct { a: u32, b: []const u8, c: u8, }; var list = MultiArrayList(Foo){}; defer list.deinit(ally); try testing.expectEqual(@as(usize, 0), list.items(.a).len); try list.ensureTotalCapacity(ally, 2); list.appendAssumeCapacity(.{ .a = 1, .b = "foobar", .c = 'a', }); list.appendAssumeCapacity(.{ .a = 2, .b = "zigzag", .c = 'b', }); try testing.expectEqualSlices(u32, list.items(.a), &[_]u32{ 1, 2 }); try testing.expectEqualSlices(u8, list.items(.c), &[_]u8{ 'a', 'b' }); try testing.expectEqual(@as(usize, 2), list.items(.b).len); try testing.expectEqualStrings("foobar", list.items(.b)[0]); try testing.expectEqualStrings("zigzag", list.items(.b)[1]); try list.append(ally, .{ .a = 3, .b = "fizzbuzz", .c = 'c', }); try testing.expectEqualSlices(u32, list.items(.a), &[_]u32{ 1, 2, 3 }); try testing.expectEqualSlices(u8, list.items(.c), &[_]u8{ 'a', 'b', 'c' }); try testing.expectEqual(@as(usize, 3), list.items(.b).len); try testing.expectEqualStrings("foobar", list.items(.b)[0]); try testing.expectEqualStrings("zigzag", list.items(.b)[1]); try testing.expectEqualStrings("fizzbuzz", list.items(.b)[2]); // Add 6 more things to force a capacity increase. var i: usize = 0; while (i < 6) : (i += 1) { try list.append(ally, .{ .a = @intCast(u32, 4 + i), .b = "whatever", .c = @intCast(u8, 'd' + i), }); } try testing.expectEqualSlices( u32, &[_]u32{ 1, 2, 3, 4, 5, 6, 7, 8, 9 }, list.items(.a), ); try testing.expectEqualSlices( u8, &[_]u8{ 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i' }, list.items(.c), ); list.shrinkAndFree(ally, 3); try testing.expectEqualSlices(u32, list.items(.a), &[_]u32{ 1, 2, 3 }); try testing.expectEqualSlices(u8, list.items(.c), &[_]u8{ 'a', 'b', 'c' }); try testing.expectEqual(@as(usize, 3), list.items(.b).len); try testing.expectEqualStrings("foobar", list.items(.b)[0]); try testing.expectEqualStrings("zigzag", list.items(.b)[1]); try testing.expectEqualStrings("fizzbuzz", list.items(.b)[2]); } // This was observed to fail on aarch64 with LLVM 11, when the capacityInBytes // function used the @reduce code path. test "regression test for @reduce bug" { const ally = testing.allocator; var list = MultiArrayList(struct { tag: std.zig.Token.Tag, start: u32, }){}; defer list.deinit(ally); try list.ensureTotalCapacity(ally, 20); try list.append(ally, .{ .tag = .keyword_const, .start = 0 }); try list.append(ally, .{ .tag = .identifier, .start = 6 }); try list.append(ally, .{ .tag = .equal, .start = 10 }); try list.append(ally, .{ .tag = .builtin, .start = 12 }); try list.append(ally, .{ .tag = .l_paren, .start = 19 }); try list.append(ally, .{ .tag = .string_literal, .start = 20 }); try list.append(ally, .{ .tag = .r_paren, .start = 25 }); try list.append(ally, .{ .tag = .semicolon, .start = 26 }); try list.append(ally, .{ .tag = .keyword_pub, .start = 29 }); try list.append(ally, .{ .tag = .keyword_fn, .start = 33 }); try list.append(ally, .{ .tag = .identifier, .start = 36 }); try list.append(ally, .{ .tag = .l_paren, .start = 40 }); try list.append(ally, .{ .tag = .r_paren, .start = 41 }); try list.append(ally, .{ .tag = .identifier, .start = 43 }); try list.append(ally, .{ .tag = .bang, .start = 51 }); try list.append(ally, .{ .tag = .identifier, .start = 52 }); try list.append(ally, .{ .tag = .l_brace, .start = 57 }); try list.append(ally, .{ .tag = .identifier, .start = 63 }); try list.append(ally, .{ .tag = .period, .start = 66 }); try list.append(ally, .{ .tag = .identifier, .start = 67 }); try list.append(ally, .{ .tag = .period, .start = 70 }); try list.append(ally, .{ .tag = .identifier, .start = 71 }); try list.append(ally, .{ .tag = .l_paren, .start = 75 }); try list.append(ally, .{ .tag = .string_literal, .start = 76 }); try list.append(ally, .{ .tag = .comma, .start = 113 }); try list.append(ally, .{ .tag = .period, .start = 115 }); try list.append(ally, .{ .tag = .l_brace, .start = 116 }); try list.append(ally, .{ .tag = .r_brace, .start = 117 }); try list.append(ally, .{ .tag = .r_paren, .start = 118 }); try list.append(ally, .{ .tag = .semicolon, .start = 119 }); try list.append(ally, .{ .tag = .r_brace, .start = 121 }); try list.append(ally, .{ .tag = .eof, .start = 123 }); const tags = list.items(.tag); try testing.expectEqual(tags[1], .identifier); try testing.expectEqual(tags[2], .equal); try testing.expectEqual(tags[3], .builtin); try testing.expectEqual(tags[4], .l_paren); try testing.expectEqual(tags[5], .string_literal); try testing.expectEqual(tags[6], .r_paren); try testing.expectEqual(tags[7], .semicolon); try testing.expectEqual(tags[8], .keyword_pub); try testing.expectEqual(tags[9], .keyword_fn); try testing.expectEqual(tags[10], .identifier); try testing.expectEqual(tags[11], .l_paren); try testing.expectEqual(tags[12], .r_paren); try testing.expectEqual(tags[13], .identifier); try testing.expectEqual(tags[14], .bang); try testing.expectEqual(tags[15], .identifier); try testing.expectEqual(tags[16], .l_brace); try testing.expectEqual(tags[17], .identifier); try testing.expectEqual(tags[18], .period); try testing.expectEqual(tags[19], .identifier); try testing.expectEqual(tags[20], .period); try testing.expectEqual(tags[21], .identifier); try testing.expectEqual(tags[22], .l_paren); try testing.expectEqual(tags[23], .string_literal); try testing.expectEqual(tags[24], .comma); try testing.expectEqual(tags[25], .period); try testing.expectEqual(tags[26], .l_brace); try testing.expectEqual(tags[27], .r_brace); try testing.expectEqual(tags[28], .r_paren); try testing.expectEqual(tags[29], .semicolon); try testing.expectEqual(tags[30], .r_brace); try testing.expectEqual(tags[31], .eof); } test "ensure capacity on empty list" { const ally = testing.allocator; const Foo = struct { a: u32, b: u8, }; var list = MultiArrayList(Foo){}; defer list.deinit(ally); try list.ensureTotalCapacity(ally, 2); list.appendAssumeCapacity(.{ .a = 1, .b = 2 }); list.appendAssumeCapacity(.{ .a = 3, .b = 4 }); try testing.expectEqualSlices(u32, &[_]u32{ 1, 3 }, list.items(.a)); try testing.expectEqualSlices(u8, &[_]u8{ 2, 4 }, list.items(.b)); list.len = 0; list.appendAssumeCapacity(.{ .a = 5, .b = 6 }); list.appendAssumeCapacity(.{ .a = 7, .b = 8 }); try testing.expectEqualSlices(u32, &[_]u32{ 5, 7 }, list.items(.a)); try testing.expectEqualSlices(u8, &[_]u8{ 6, 8 }, list.items(.b)); list.len = 0; try list.ensureTotalCapacity(ally, 16); list.appendAssumeCapacity(.{ .a = 9, .b = 10 }); list.appendAssumeCapacity(.{ .a = 11, .b = 12 }); try testing.expectEqualSlices(u32, &[_]u32{ 9, 11 }, list.items(.a)); try testing.expectEqualSlices(u8, &[_]u8{ 10, 12 }, list.items(.b)); }
lib/std/multi_array_list.zig
const std = @import("std"); const root = @import("main.zig"); const math = std.math; const testing = std.testing; pub const Vec2 = Vector2(f32); pub const Vec2_f64 = Vector2(f64); pub const Vec2_i32 = Vector2(i32); /// A 2 dimensional vector. pub fn Vector2(comptime T: type) type { if (@typeInfo(T) != .Float and @typeInfo(T) != .Int) { @compileError("Vector2 not implemented for " ++ @typeName(T)); } return struct { x: T = 0, y: T = 0, const Self = @This(); /// Construct vector from given 2 components. pub fn new(x: T, y: T) Self { return .{ .x = x, .y = y }; } /// Set all components to the same given value. pub fn set(val: T) Self { return Self.new(val, val); } pub fn zero() Self { return Self.new(0, 0); } pub fn one() Self { return Self.new(1, 1); } pub fn up() Self { return Self.new(0, 1); } /// Cast a type to another type. Only for integers and floats. /// It's like builtins: @intCast, @floatCast, @intToFloat, @floatToInt. pub fn cast(self: Self, dest: anytype) Vector2(dest) { const source_info = @typeInfo(T); const dest_info = @typeInfo(dest); if (source_info == .Float and dest_info == .Int) { const x = @floatToInt(dest, self.x); const y = @floatToInt(dest, self.y); return Vector2(dest).new(x, y); } if (source_info == .Int and dest_info == .Float) { const x = @intToFloat(dest, self.x); const y = @intToFloat(dest, self.y); return Vector2(dest).new(x, y); } return switch (dest_info) { .Float => { const x = @floatCast(dest, self.x); const y = @floatCast(dest, self.y); return Vector2(dest).new(x, y); }, .Int => { const x = @intCast(dest, self.x); const y = @intCast(dest, self.y); return Vector2(dest).new(x, y); }, else => panic( "Error, given type should be integer or float.\n", .{}, ), }; } /// Construct new vector from slice. pub fn fromSlice(slice: []const T) Self { return Self.new(slice[0], slice[1]); } /// Transform vector to array. pub fn toArray(self: Self) [2]T { return .{ self.x, self.y }; } /// Return the angle in degrees between two vectors. pub fn getAngle(left: Self, right: Self) T { const dot_product = Self.dot(left.norm(), right.norm()); return root.toDegrees(math.acos(dot_product)); } /// Compute the length (magnitude) of given vector |a|. pub fn length(self: Self) T { return math.sqrt((self.x * self.x) + (self.y * self.y)); } /// Compute the distance between two points. pub fn distance(a: Self, b: Self) T { return math.sqrt( math.pow(T, b.x - a.x, 2) + math.pow(T, b.y - a.y, 2), ); } /// Construct new normalized vector from a given vector. pub fn norm(self: Self) Self { var l = length(self); return Self.new(self.x / l, self.y / l); } pub fn eql(left: Self, right: Self) bool { return left.x == right.x and left.y == right.y; } /// Substraction between two given vector. pub fn sub(left: Self, right: Self) Self { return Self.new(left.x - right.x, left.y - right.y); } /// Addition betwen two given vector. pub fn add(left: Self, right: Self) Self { return Self.new(left.x + right.x, left.y + right.y); } /// Multiply each components by the given scalar. pub fn scale(v: Self, scalar: T) Self { return Self.new(v.x * scalar, v.y * scalar); } /// Return the dot product between two given vector. pub fn dot(left: Self, right: Self) T { return (left.x * right.x) + (left.y * right.y); } /// Lerp between two vectors. pub fn lerp(left: Self, right: Self, t: T) Self { const x = root.lerp(T, left.x, right.x, t); const y = root.lerp(T, left.y, right.y, t); return Self.new(x, y); } /// Construct a new vector from the min components between two vectors. pub fn min(left: Self, right: Self) Self { return Self.new( math.min(left.x, right.x), math.min(left.y, right.y), ); } /// Construct a new vector from the max components between two vectors. pub fn max(left: Self, right: Self) Self { return Self.new( math.max(left.x, right.x), math.max(left.y, right.y), ); } }; } test "zalgebra.Vec2.init" { var a = Vec2.new(1.5, 2.6); try testing.expectEqual(a.x, 1.5); try testing.expectEqual(a.y, 2.6); } test "zalgebra.Vec2.set" { var a = Vec2.new(2.5, 2.5); var b = Vec2.set(2.5); try testing.expectEqual(Vec2.eql(a, b), true); } test "zalgebra.Vec2.getAngle" { var a = Vec2.new(1, 0); var b = Vec2.up(); var c = Vec2.new(-1, 0); var d = Vec2.new(1, 1); try testing.expectEqual(Vec2.getAngle(a, b), 90); try testing.expectEqual(Vec2.getAngle(a, c), 180); try testing.expectEqual(Vec2.getAngle(a, d), 45); } test "zalgebra.Vec2.toArray" { const a = Vec2.up().toArray(); const b = [_]f32{ 0, 1 }; try testing.expectEqual(std.mem.eql(f32, &a, &b), true); } test "zalgebra.Vec2.eql" { var a = Vec2.new(1, 2); var b = Vec2.new(1, 2); var c = Vec2.new(1.5, 2); try testing.expectEqual(Vec2.eql(a, b), true); try testing.expectEqual(Vec2.eql(a, c), false); } test "zalgebra.Vec2.length" { var a = Vec2.new(1.5, 2.6); try testing.expectEqual(a.length(), 3.00166606); } test "zalgebra.Vec2.distance" { var a = Vec2.new(0, 0); var b = Vec2.new(-1, 0); var c = Vec2.new(0, 5); try testing.expectEqual(Vec2.distance(a, b), 1); try testing.expectEqual(Vec2.distance(a, c), 5); } test "zalgebra.Vec2.normalize" { var a = Vec2.new(1.5, 2.6); try testing.expectEqual(Vec2.eql(a.norm(), Vec2.new(0.499722480, 0.866185605)), true); } test "zalgebra.Vec2.sub" { var a = Vec2.new(1, 2); var b = Vec2.new(2, 2); try testing.expectEqual(Vec2.eql(Vec2.sub(a, b), Vec2.new(-1, 0)), true); } test "zalgebra.Vec2.add" { var a = Vec2.new(1, 2); var b = Vec2.new(2, 2); try testing.expectEqual(Vec2.eql(Vec2.add(a, b), Vec2.new(3, 4)), true); } test "zalgebra.Vec2.scale" { var a = Vec2.new(1, 2); try testing.expectEqual(Vec2.eql(Vec2.scale(a, 5), Vec2.new(5, 10)), true); } test "zalgebra.Vec2.dot" { var a = Vec2.new(1.5, 2.6); var b = Vec2.new(2.5, 3.45); try testing.expectEqual(Vec2.dot(a, b), 12.7200002); } test "zalgebra.Vec2.lerp" { var a = Vec2.new(-10.0, 0.0); var b = Vec2.new(10.0, 10.0); try testing.expectEqual(Vec2.eql(Vec2.lerp(a, b, 0.5), Vec2.new(0.0, 5.0)), true); } test "zalgebra.Vec2.min" { var a = Vec2.new(10.0, -2.0); var b = Vec2.new(-10.0, 5.0); try testing.expectEqual(Vec2.eql(Vec2.min(a, b), Vec2.new(-10.0, -2.0)), true); } test "zalgebra.Vec2.max" { var a = Vec2.new(10.0, -2.0); var b = Vec2.new(-10.0, 5.0); try testing.expectEqual(Vec2.eql(Vec2.max(a, b), Vec2.new(10.0, 5.0)), true); } test "zalgebra.Vec2.fromSlice" { const array = [2]f32{ 2, 4 }; try testing.expectEqual(Vec2.eql(Vec2.fromSlice(&array), Vec2.new(2, 4)), true); } test "zalgebra.Vec2.cast" { const a = Vec2_i32.new(3, 6); const b = Vector2(usize).new(3, 6); try testing.expectEqual( Vector2(usize).eql(a.cast(usize), b), true, ); const c = Vec2.new(3.5, 6.5); const d = Vec2_f64.new(3.5, 6.5); try testing.expectEqual( Vec2_f64.eql(c.cast(f64), d), true, ); const e = Vec2_i32.new(3, 6); const f = Vec2.new(3.0, 6.0); try testing.expectEqual( Vec2.eql(e.cast(f32), f), true, ); const g = Vec2.new(3.0, 6.0); const h = Vec2_i32.new(3, 6); try testing.expectEqual( Vec2_i32.eql(g.cast(i32), h), true, ); }
src/vec2.zig
const std = @import("std"); const expect = std.testing.expect; const expectEqualSlices = std.testing.expectEqualSlices; const expectEqual = std.testing.expectEqual; const mem = std.mem; const x = @intToPtr([*]i32, 0x1000)[0..0x500]; const y = x[0x100..]; test "compile time slice of pointer to hard coded address" { expect(@ptrToInt(x.ptr) == 0x1000); expect(x.len == 0x500); expect(@ptrToInt(y.ptr) == 0x1100); expect(y.len == 0x400); } test "runtime safety lets us slice from len..len" { var an_array = [_]u8{ 1, 2, 3, }; expect(mem.eql(u8, sliceFromLenToLen(an_array[0..], 3, 3), "")); } fn sliceFromLenToLen(a_slice: []u8, start: usize, end: usize) []u8 { return a_slice[start..end]; } test "implicitly cast array of size 0 to slice" { var msg = [_]u8{}; assertLenIsZero(&msg); } fn assertLenIsZero(msg: []const u8) void { expect(msg.len == 0); } test "C pointer" { var buf: [*c]const u8 = "kjdhfkjdhfdkjhfkfjhdfkjdhfkdjhfdkjhf"; var len: u32 = 10; var slice = buf[0..len]; expectEqualSlices(u8, "kjdhfkjdhf", slice); } fn sliceSum(comptime q: []const u8) i32 { comptime var result = 0; inline for (q) |item| { result += item; } return result; } test "comptime slices are disambiguated" { expect(sliceSum(&[_]u8{ 1, 2 }) == 3); expect(sliceSum(&[_]u8{ 3, 4 }) == 7); } test "slice type with custom alignment" { const LazilyResolvedType = struct { anything: i32, }; var slice: []align(32) LazilyResolvedType = undefined; var array: [10]LazilyResolvedType align(32) = undefined; slice = &array; slice[1].anything = 42; expect(array[1].anything == 42); } test "access len index of sentinel-terminated slice" { const S = struct { fn doTheTest() void { var slice: [:0]const u8 = "hello"; expect(slice.len == 5); expect(slice[5] == 0); } }; S.doTheTest(); comptime S.doTheTest(); } test "obtaining a null terminated slice" { // here we have a normal array var buf: [50]u8 = undefined; buf[0] = 'a'; buf[1] = 'b'; buf[2] = 'c'; buf[3] = 0; // now we obtain a null terminated slice: const ptr = buf[0..3 :0]; var runtime_len: usize = 3; const ptr2 = buf[0..runtime_len :0]; // ptr2 is a null-terminated slice comptime expect(@TypeOf(ptr2) == [:0]u8); comptime expect(@TypeOf(ptr2[0..2]) == []u8); } test "empty array to slice" { const S = struct { fn doTheTest() void { const empty: []align(16) u8 = &[_]u8{}; const align_1: []align(1) u8 = empty; const align_4: []align(4) u8 = empty; const align_16: []align(16) u8 = empty; expectEqual(1, @typeInfo(@TypeOf(align_1)).Pointer.alignment); expectEqual(4, @typeInfo(@TypeOf(align_4)).Pointer.alignment); expectEqual(16, @typeInfo(@TypeOf(align_16)).Pointer.alignment); } }; S.doTheTest(); comptime S.doTheTest(); }
test/stage1/behavior/slice.zig
const std = @import("std"); const assert = std.debug.assert; pub const Cancellation = error{ GeneratorCancelled, }; pub const State = enum { Initialized, Started, Error, Returned, Cancelled }; /// Generator handle, to be used in Handle's Ctx type /// /// `T` is the type that the generator yields /// `Return` is generator's return type pub fn Handle(comptime T: type) type { return struct { const Self = @This(); const HandleState = enum { Working, Yielded, Cancel }; const Suspension = enum(u8) { Unsuspended, Suspended, Yielded }; frame: *@Frame(yield) = undefined, gen_frame: anyframe = undefined, gen_frame_suspended: std.atomic.Atomic(Suspension) = std.atomic.Atomic(Suspension).init(.Unsuspended), state: union(HandleState) { Working: void, Yielded: T, Cancel: void, } = .Working, /// Yields a value pub fn yield(self: *Self, t: T) error{GeneratorCancelled}!void { if (self.state == .Cancel) return error.GeneratorCancelled; suspend { self.state = .{ .Yielded = t }; self.frame = @frame(); if (self.gen_frame_suspended.swap(.Yielded, .SeqCst) == .Suspended) { resume self.gen_frame; } } if (self.state == .Cancel) return error.GeneratorCancelled; self.state = .Working; } }; } /// Generator type allows an async function to yield multiple /// values, and return an error or a result. /// /// Ctx type must be a struct and it must have the following function: /// /// * `generate(self: *@This(), handle: *generator.Handle(T)) !Return` /// /// where `T` is the type of value yielded by the generator and `Return` is /// the type of the return value. /// /// NOTE: In many cases it may be advisable to have `T` be a pointer to a type, /// particularly if the the yielded type is larger than a machine word. /// This will eliminate the unnecessary copying of the value and may have a positive /// impact on performance. /// This is also a critical consideration if the generator needs to be able to /// observe changes that occurred to the value during suspension. pub fn Generator(comptime Ctx: type, comptime T: type) type { const ty = @typeInfo(Ctx); comptime { assert(ty == .Struct); assert(@hasDecl(Ctx, "generate")); } const generate_fn = Ctx.generate; const generate_fn_info = @typeInfo(@TypeOf(generate_fn)); assert(generate_fn_info == .Fn); assert(generate_fn_info.Fn.args.len == 2); const arg1_tinfo = @typeInfo(generate_fn_info.Fn.args[0].arg_type.?); const arg2_tinfo = @typeInfo(generate_fn_info.Fn.args[1].arg_type.?); const ret_tinfo = @typeInfo(generate_fn_info.Fn.return_type.?); // context assert(arg1_tinfo == .Pointer); assert(arg1_tinfo.Pointer.child == Ctx); // Handle assert(arg2_tinfo == .Pointer); assert(arg2_tinfo.Pointer.child == Handle(T)); assert(ret_tinfo == .ErrorUnion); return struct { const Self = @This(); const Err = ret_tinfo.ErrorUnion.error_set; const CompleteErrorSet = Err || Cancellation; pub const Return = ret_tinfo.ErrorUnion.payload; pub const Context = Ctx; pub const GeneratorState = union(State) { Initialized: void, Started: void, Error: Err, Returned: Return, Cancelled: void, }; handle: Handle(T) = Handle(T){}, /// Generator's state /// /// * `.Initialized` -- it hasn't been started yet /// * `.Started` -- it has been started /// * `.Returned` -- it has returned a value /// * `.Error` -- it has returned an error /// * `.Cancelled` -- it has been cancelled state: GeneratorState = .Initialized, /// Generator's own structure context: Context, generator_frame: @Frame(generator) = undefined, /// Initializes a generator pub fn init(ctx: Ctx) Self { return Self{ .context = ctx, }; } fn generator(self: *Self) void { if (generate_fn(&self.context, &self.handle)) |val| { self.state = .{ .Returned = val }; } else |err| { switch (err) { error.GeneratorCancelled => { self.state = .Cancelled; }, else => |e| { self.state = .{ .Error = e }; }, } } if (self.handle.gen_frame_suspended.swap(.Unsuspended, .SeqCst) == .Suspended) { resume self.handle.gen_frame; } suspend {} unreachable; } /// Returns the next yielded value, or `null` if the generator returned or was cancelled. /// `next()` propagates errors returned by the generator function. /// /// .state.Returned union variant can be used to retrieve the return value of the generator /// .state.Cancelled indicates that the generator was cancelled /// .state.Error union variant can be used to retrieve the error /// pub fn next(self: *Self) Err!?T { switch (self.state) { .Initialized => { self.state = .Started; self.handle.gen_frame = @frame(); self.generator_frame = async self.generator(); }, .Started => { resume self.handle.frame; }, else => return null, } while (self.state == .Started and self.handle.state == .Working) { suspend { if (self.handle.gen_frame_suspended.swap(.Suspended, .SeqCst) == .Yielded) { resume @frame(); } } } self.handle.gen_frame_suspended.store(.Unsuspended, .SeqCst); switch (self.state) { .Started => { return self.handle.state.Yielded; }, .Error => |e| return e, else => return null, } } /// Drains the generator until it is done pub fn drain(self: *Self) !void { while (try self.next()) |_| {} } /// Cancels the generator /// /// It won't yield any more values and will run its deferred code. /// /// However, it may still continue working until it attempts to yield. /// This is possible if the generator is an async function using other async functions. /// /// NOTE that the generator must cooperate (or at least, not get in the way) with its cancellation. /// An uncooperative generator can catch `GeneratorCancelled` error and refuse to be terminated. /// In such case, the generator will be effectively drained upon an attempt to cancel it. pub fn cancel(self: *Self) void { self.handle.state = .Cancel; } }; } test "basic generator" { const expect = std.testing.expect; const ty = struct { pub fn generate(_: *@This(), handle: *Handle(u8)) !void { try handle.yield(0); try handle.yield(1); try handle.yield(2); } }; const G = Generator(ty, u8); var g = G.init(ty{}); try expect((try g.next()).? == 0); try expect((try g.next()).? == 1); try expect((try g.next()).? == 2); try expect((try g.next()) == null); try expect(g.state == .Returned); try expect((try g.next()) == null); } test "generator with async i/o" { const expect = std.testing.expect; const ty = struct { pub fn generate(_: *@This(), handle: *Handle(u8)) !void { const file = try std.fs.cwd() .openFile("README.md", std.fs.File.OpenFlags{ .read = true, .write = false }); const reader = file.reader(); while (true) { const byte = reader.readByte() catch return; try handle.yield(byte); } } }; const G = Generator(ty, u8); var g = G.init(ty{}); var bytes: usize = 0; while (try g.next()) |_| { bytes += 1; } try expect(bytes > 0); } test "generator with async await" { const expect = std.testing.expect; const ty = struct { fn doAsync() callconv(.Async) u8 { suspend { resume @frame(); } return 1; } pub fn generate(_: *@This(), handle: *Handle(u8)) !void { try handle.yield(await async doAsync()); } }; const G = Generator(ty, u8); var g = G.init(ty{}); try expect((try g.next()).? == 1); } test "context" { const expect = std.testing.expect; const ty = struct { a: u8 = 1, pub fn generate(_: *@This(), handle: *Handle(u8)) !void { try handle.yield(0); try handle.yield(1); try handle.yield(2); } }; const G = Generator(ty, u8); var g = G.init(ty{}); try expect(g.context.a == 1); } test "errors in generators" { const expect = std.testing.expect; const ty = struct { pub fn generate(_: *@This(), handle: *Handle(u8)) !void { try handle.yield(0); try handle.yield(1); return error.SomeError; } }; const G = Generator(ty, u8); var g = G.init(ty{}); try expect((try g.next()).? == 0); try expect((try g.next()).? == 1); _ = g.next() catch |err| { try expect(g.state == .Error); try expect((try g.next()) == null); switch (err) { error.SomeError => { return; }, else => { @panic("incorrect error has been captured"); }, } return; }; @panic("error should have been generated"); } test "return value in generator" { const expect = std.testing.expect; const ty = struct { complete: bool = false, pub fn generate(self: *@This(), handle: *Handle(u8)) !u8 { defer { self.complete = true; } try handle.yield(0); try handle.yield(1); try handle.yield(2); return 3; } }; const G = Generator(ty, u8); var g = G.init(ty{}); try expect((try g.next()).? == 0); try expect((try g.next()).? == 1); try expect((try g.next()).? == 2); try expect((try g.next()) == null); try expect(g.state == .Returned); try expect(g.state.Returned == 3); try expect(g.context.complete); } test "drain" { const expect = std.testing.expect; const ty = struct { pub fn generate(_: *@This(), handle: *Handle(u8)) !u8 { try handle.yield(0); try handle.yield(1); try handle.yield(2); return 3; } }; const G = Generator(ty, u8); var g = G.init(ty{}); try g.drain(); try expect(g.state.Returned == 3); } test "cancel" { const expect = std.testing.expect; const ty = struct { drained: bool = false, cancelled: bool = false, pub fn generate(self: *@This(), handle: *Handle(u8)) !u8 { errdefer |e| { if (e == error.GeneratorCancelled) { self.cancelled = true; } } try handle.yield(0); try handle.yield(1); try handle.yield(2); self.drained = true; return 3; } }; const G = Generator(ty, u8); // cancel before yielding var g = G.init(ty{}); g.cancel(); try expect((try g.next()) == null); try expect(g.state == .Cancelled); try expect(!g.context.drained); try expect(g.context.cancelled); // cancel after yielding g = G.init(ty{}); try expect((try g.next()).? == 0); g.cancel(); try expect((try g.next()) == null); try expect(g.state == .Cancelled); try expect(!g.context.drained); try expect(g.context.cancelled); } test "uncooperative cancellation" { const expect = std.testing.expect; const ty = struct { drained: bool = false, ignored_termination_0: bool = false, ignored_termination_1: bool = false, pub fn generate(self: *@This(), handle: *Handle(u8)) !void { handle.yield(0) catch { self.ignored_termination_0 = true; }; handle.yield(1) catch { self.ignored_termination_1 = true; }; self.drained = true; } }; const G = Generator(ty, u8); // Cancel before yielding var g = G.init(ty{}); g.cancel(); try expect((try g.next()) == null); try expect(g.state == .Returned); try expect(g.context.drained); try expect(g.context.ignored_termination_0); try expect(g.context.ignored_termination_1); // Cancel after yielding g = G.init(ty{}); try expect((try g.next()).? == 0); g.cancel(); try expect((try g.next()) == null); try expect(g.state == .Returned); try expect(g.context.drained); try expect(g.context.ignored_termination_0); try expect(g.context.ignored_termination_1); }
src/generator.zig
const std = @import("std"); const expect = std.testing.expect; const expectEqualSlices = std.testing.expectEqualSlices; // Most tests here can be comptime but use runtime so that a stacktrace // can show failure location. // // Note certain results of `@typeName()` expect `behavior.zig` to be the // root file. Running a test against this file as root will result in // failures. // CAUTION: this test is source-location sensitive. test "anon fn param - source-location sensitive" { // https://github.com/ziglang/zig/issues/9339 try expectEqualSlices(u8, @typeName(TypeFromFn(struct {})), "behavior.typename.TypeFromFn(behavior.typename.struct:15:52)"); try expectEqualSlices(u8, @typeName(TypeFromFn(union { unused: u8 })), "behavior.typename.TypeFromFn(behavior.typename.union:16:52)"); try expectEqualSlices(u8, @typeName(TypeFromFn(enum { unused })), "behavior.typename.TypeFromFn(behavior.typename.enum:17:52)"); try expectEqualSlices( u8, @typeName(TypeFromFn3(struct {}, union { unused: u8 }, enum { unused })), "behavior.typename.TypeFromFn3(behavior.typename.struct:21:31,behavior.typename.union:21:42,behavior.typename.enum:21:64)", ); } // CAUTION: this test is source-location sensitive. test "anon field init" { const Foo = .{ .T1 = struct {}, .T2 = union { unused: u8 }, .T3 = enum { unused }, }; try expectEqualSlices(u8, @typeName(Foo.T1), "behavior.typename.struct:29:15"); try expectEqualSlices(u8, @typeName(Foo.T2), "behavior.typename.union:30:15"); try expectEqualSlices(u8, @typeName(Foo.T3), "behavior.typename.enum:31:15"); } test "basic" { try expectEqualSlices(u8, @typeName(i64), "i64"); try expectEqualSlices(u8, @typeName(*usize), "*usize"); try expectEqualSlices(u8, @typeName([]u8), "[]u8"); } test "top level decl" { try expectEqualSlices(u8, @typeName(A_Struct), "A_Struct"); try expectEqualSlices(u8, @typeName(A_Union), "A_Union"); try expectEqualSlices(u8, @typeName(A_Enum), "A_Enum"); // regular fn, without error try expectEqualSlices(u8, @typeName(@TypeOf(regular)), "fn() void"); // regular fn inside struct, with error try expectEqualSlices(u8, @typeName(@TypeOf(B.doTest)), "fn() @typeInfo(@typeInfo(@TypeOf(behavior.typename.B.doTest)).Fn.return_type.?).ErrorUnion.error_set!void"); // generic fn try expectEqualSlices(u8, @typeName(@TypeOf(TypeFromFn)), "fn(type) anytype"); } const A_Struct = struct {}; const A_Union = union { unused: u8, }; const A_Enum = enum { unused, }; fn regular() void {} test "fn body decl" { try B.doTest(); } const B = struct { fn doTest() !void { const B_Struct = struct {}; const B_Union = union { unused: u8, }; const B_Enum = enum { unused, }; try expectEqualSlices(u8, @typeName(B_Struct), "B_Struct"); try expectEqualSlices(u8, @typeName(B_Union), "B_Union"); try expectEqualSlices(u8, @typeName(B_Enum), "B_Enum"); } }; test "fn param" { // https://github.com/ziglang/zig/issues/675 try expectEqualSlices(u8, @typeName(TypeFromFn(u8)), "behavior.typename.TypeFromFn(u8)"); try expectEqualSlices(u8, @typeName(TypeFromFn(A_Struct)), "behavior.typename.TypeFromFn(behavior.typename.A_Struct)"); try expectEqualSlices(u8, @typeName(TypeFromFn(A_Union)), "behavior.typename.TypeFromFn(behavior.typename.A_Union)"); try expectEqualSlices(u8, @typeName(TypeFromFn(A_Enum)), "behavior.typename.TypeFromFn(behavior.typename.A_Enum)"); try expectEqualSlices(u8, @typeName(TypeFromFn2(u8, bool)), "behavior.typename.TypeFromFn2(u8,bool)"); } fn TypeFromFn(comptime T: type) type { _ = T; return struct {}; } fn TypeFromFn2(comptime T1: type, comptime T2: type) type { _ = T1; _ = T2; return struct {}; } fn TypeFromFn3(comptime T1: type, comptime T2: type, comptime T3: type) type { _ = T1; _ = T2; _ = T3; return struct {}; }
test/behavior/typename.zig
const fmath = @import("index.zig"); const expo2 = @import("_expo2.zig").expo2; pub fn sinh(x: var) -> @typeOf(x) { const T = @typeOf(x); switch (T) { f32 => @inlineCall(sinhf, x), f64 => @inlineCall(sinhd, x), else => @compileError("sinh not implemented for " ++ @typeName(T)), } } // sinh(x) = (exp(x) - 1 / exp(x)) / 2 // = (exp(x) - 1 + (exp(x) - 1) / exp(x)) / 2 // = x + x^3 / 6 + o(x^5) fn sinhf(x: f32) -> f32 { const u = @bitCast(u32, x); const ux = u & 0x7FFFFFFF; const ax = @bitCast(f32, ux); var h: f32 = 0.5; if (u >> 31 != 0) { h = -h; } // |x| < log(FLT_MAX) if (ux < 0x42B17217) { const t = fmath.expm1(ax); if (ux < 0x3F800000) { if (ux < 0x3F800000 - (12 << 23)) { return x; } else { return h * (2 * t - t * t / (t + 1)); } } return h * (t + t / (t + 1)); } // |x| > log(FLT_MAX) or nan 2 * h * expo2(ax) } fn sinhd(x: f64) -> f64 { const u = @bitCast(u64, x); const w = u32(u >> 32); const ax = @bitCast(f64, u & (@maxValue(u64) >> 1)); var h: f32 = 0.5; if (u >> 63 != 0) { h = -h; } // |x| < log(FLT_MAX) if (w < 0x40862E42) { const t = fmath.expm1(ax); if (w < 0x3FF00000) { if (w < 0x3FF00000 - (26 << 20)) { return x; } else { return h * (2 * t - t * t / (t + 1)); } } // NOTE: |x| > log(0x1p26) + eps could be h * exp(x) return h * (t + t / (t + 1)); } // |x| > log(DBL_MAX) or nan 2 * h * expo2(ax) } test "sinh" { fmath.assert(sinh(f32(1.5)) == sinhf(1.5)); fmath.assert(sinh(f64(1.5)) == sinhd(1.5)); } test "sinhf" { const epsilon = 0.000001; fmath.assert(fmath.approxEq(f32, sinhf(0.0), 0.0, epsilon)); fmath.assert(fmath.approxEq(f32, sinhf(0.2), 0.201336, epsilon)); fmath.assert(fmath.approxEq(f32, sinhf(0.8923), 1.015512, epsilon)); fmath.assert(fmath.approxEq(f32, sinhf(1.5), 2.129279, epsilon)); } test "sinhd" { const epsilon = 0.000001; fmath.assert(fmath.approxEq(f64, sinhd(0.0), 0.0, epsilon)); fmath.assert(fmath.approxEq(f64, sinhd(0.2), 0.201336, epsilon)); fmath.assert(fmath.approxEq(f64, sinhd(0.8923), 1.015512, epsilon)); fmath.assert(fmath.approxEq(f64, sinhd(1.5), 2.129279, epsilon)); }
src/sinh.zig
const std = @import("std"); const assert = std.debug.assert; const allocator = std.heap.page_allocator; const Computer = @import("./computer.zig").Computer; pub const Map = struct { pub const Pos = struct { x: usize, y: usize, pub fn init(x: usize, y: usize) Pos { return Pos{ .x = x, .y = y, }; } pub fn equal(self: Pos, other: Pos) bool { return self.x == other.x and self.y == other.y; } }; cells: std.AutoHashMap(Pos, Tile), pmin: Pos, pmax: Pos, prg: []const u8, pub const Tile = enum(u8) { Stationary = 0, Pulled = 1, }; pub fn init(minx: usize, miny: usize, maxx: usize, maxy: usize, prg: []const u8) Map { var self = Map{ .cells = std.AutoHashMap(Pos, Tile).init(allocator), .pmin = Pos.init(minx, miny), .pmax = Pos.init(maxx, maxy), .prg = prg, }; return self; } pub fn deinit(self: *Map) void { self.cells.deinit(); } pub fn run_for_one_point(self: *Map, p: Pos) Tile { var comp = Computer.init(true); defer comp.deinit(); comp.parse(self.prg); comp.enqueueInput(@intCast(i64, p.x)); comp.enqueueInput(@intCast(i64, p.y)); comp.run(); const output = comp.getOutput(); if (output == null) { std.debug.warn("FUCK\n", .{}); return Tile.Stationary; } const v = @intCast(u8, output.?); // std.debug.warn("RUN {} {} => {}\n", .{ p.x, p.y, v}); const t = @intToEnum(Tile, v); return t; } pub fn find_first_pulled(self: *Map, y: usize) usize { var xl: usize = 0; var xh: usize = (y - 48) * 45 / 41 + 53; var s: usize = 1; var t: Tile = undefined; while (true) { const p = Pos.init(xh, y); t = self.run_for_one_point(p); // std.debug.warn("D {} {} {}\n", .{ xh, y, t}); if (t == Tile.Pulled) break; xh += s; s *= 2; } while (xl <= xh) { var xm: usize = (xl + xh) / 2; const p = Pos.init(xm, y); t = self.run_for_one_point(p); // std.debug.warn("M {} {} {}\n", .{ xm, y, t}); if (t == Tile.Pulled) { xh = xm - 1; } else { xl = xm + 1; } } // if (t != Tile.Pulled) xl += 1; // std.debug.warn("F {} {}\n", .{ xl, y}); return xl; } pub fn run_to_get_map(self: *Map) usize { var count: usize = 0; var y: usize = self.pmin.y; while (y < self.pmax.y) : (y += 1) { var x: usize = self.pmin.x; while (x < self.pmax.x) : (x += 1) { // if (self.computer.halted) break :main; const p = Pos.init(x, y); const t = self.run_for_one_point(p); self.set_pos(p, t); if (t == Tile.Pulled) count += 1; } } return count; } pub fn set_pos(self: *Map, pos: Pos, mark: Tile) void { _ = self.cells.put(pos, mark) catch unreachable; } pub fn show(self: Map) void { std.debug.warn("MAP: {} {} - {} {}\n", .{ self.pmin.x, self.pmin.y, self.pmax.x, self.pmax.y }); var y: usize = self.pmin.y; while (y < self.pmax.y) : (y += 1) { std.debug.warn("{:4} | ", .{y}); var x: usize = self.pmin.x; while (x < self.pmax.x) : (x += 1) { const p = Pos.init(x, y); const g = self.cells.get(p); var c: u8 = ' '; if (g) |v| { switch (v) { Tile.Stationary => c = '.', Tile.Pulled => c = '#', } } std.debug.warn("{c}", .{c}); } std.debug.warn("\n", .{}); } } };
2019/p19/map.zig
const std = @import("std"); const za = @import("zalgebra"); const Vec2 = za.vec2; const Vec3 = za.vec3; const Vec4 = za.vec4; // dross-zig const Vector2 = @import("vector2.zig").Vector2; // ----------------------------------------- // - Vector3 - // ----------------------------------------- pub const Vector3 = struct { data: Vec3, const Self = @This(); /// Builds and returns a new Vector3 with the compoents /// set to their respective passed values. pub fn new(x_value: f32, y_value: f32, z_value: f32) Self { return Self{ .data = Vec3.new(x_value, y_value, z_value), }; } /// Create a Vector3 from a given Vector2 and a z value pub fn fromVector2(xy: Vector2, desired_z: f32) Self { return Self{ .data = Vec3.new(xy.x(), xy.y(), desired_z), }; } /// Returns the value of the x component pub fn x(self: Self) f32 { return self.data.x; } /// Returns the value of the y component pub fn y(self: Self) f32 { return self.data.y; } /// Returns the value of the z component pub fn z(self: Self) f32 { return self.data.z; } /// Builds and returns a Vector3 with all components /// set to `value`. pub fn setAll(value: f32) Self { return Self{ .data = Vec3.set(value), }; } /// Copies the values of the given Vector pub fn copy(self: Self, other: Self) Self { return .{ .data = Vec3.new(other.data.x, other.data.y, other.data.z), }; } /// Shorthand for a zeroed out Vector 3 pub fn zero() Self { return Self{ .data = Vec3.zero(), }; } /// Shorthand for (0.0, 1.0, 0.0) pub fn up() Self { return Self{ .data = Vec3.up(), }; } /// Shorthand for (1.0, 0.0, 0.0) pub fn right() Self { return Self{ .data = Vec3.right(), }; } /// Shorthand for (0.0, 0.0, 1.0) pub fn forward() Self { return Self{ .data = Vec3.forward(), }; } /// Transform vector to an array pub fn toArray(self: Self) [3]f32 { return self.data.to_array(); } /// Returns the angle (in degrees) between two vectors. pub fn getAngle(lhs: Self, rhs: Self) f32 { return lhs.data.get_angle(rhs.data); } /// Returns the length (magnitude) of the calling vector |a|. pub fn length(self: Self) f32 { return self.data.length(); } /// Returns a normalized copy of the calling vector. pub fn normalize(self: Self) Self { return Self{ .data = self.data.norm(), }; } /// Returns whether two vectors are equal or not pub fn isEqual(lhs: Self, rhs: Self) bool { return lhs.data.is_eq(rhs.data); } /// Subtraction between two vectors. pub fn subtract(lhs: Self, rhs: Self) Self { return Self{ .data = Vec3.sub(lhs.data, rhs.data), }; } /// Addition between two vectors. pub fn add(lhs: Self, rhs: Self) Self { return Self{ .data = Vec3.add(lhs.data, rhs.data), }; } /// Returns a new Vector3 multiplied by a scalar value pub fn scale(self: Self, scalar: f32) Self { return Self{ .data = self.data.scale(scalar), }; } /// Returns the cross product of the given vectors. pub fn cross(lhs: Self, rhs: Self) Self { return Self{ .data = lhs.data.cross(rhs.data), }; } /// Returns the dot product between two given vectors. pub fn dot(lhs: Self, rhs: Self) f32 { return lhs.data.dot(rhs.data); } /// Returns a linear interpolated Vector3 of the given vectors. /// t: [0.0 - 1.0] - How much should lhs move towards rhs /// Formula for a single value: /// start * (1 - t) + end * t pub fn lerp(lhs: Self, rhs: Self, t: f32) Self { return Self{ .data = lhs.data.lerp(rhs.data, t), }; } /// Returns a random Vector3 with a minimum range of `min` and /// a maximum range of `max`, inclusively. If pub fn random(max: f32) !Self { var prng = std.rand.DefaultPrng.init(blk: { var seed: u64 = undefined; try std.os.getrandom(std.mem.asBytes(&seed)); break :blk seed; }); const rand = &prng.random; return Self{ .data = Vec3.new( rand.float(f32) * max, rand.float(f32) * max, rand.float(f32) * max, ), }; } };
src/core/vector3.zig
const std = @import("std"); const Allocator = std.mem.Allocator; const ArrayList = std.ArrayList; const abs = std.math.absInt; const assert = std.debug.assert; const Point = struct { x: i32, y: i32, const Self = @This(); pub fn distance(self: Self) !i32 { return (try abs(self.x)) + (try abs(self.y)); } pub fn distanceBetween(a: Self, b: Self) !i32 { return (try abs(a.x - b.x)) + (try abs(a.y - b.y)); } pub fn eql(a: Self, b: Self) bool { return a.x == b.x and a.y == b.y; } pub fn flip(self: Self) Self { return Self{ .x = self.y, .y = self.x }; } }; const Direction = enum { Up, Down, Left, Right, }; const Instruction = struct { dir: Direction, len: i32, const Self = @This(); pub fn fromStr(s: []const u8) !Self { return Self{ .dir = switch (s[0]) { 'U' => .Up, 'D' => .Down, 'L' => .Left, 'R' => .Right, else => { std.debug.warn("{}\n", .{s}); return error.InvalidDirection; }, }, .len = try std.fmt.parseInt(i32, s[1..], 10), }; } }; const TwoDir = enum { Vertical, Horizontal, }; const Line = struct { start: Point, end: Point, const Self = @This(); pub const IntersectError = Allocator.Error; pub fn intersect(alloc: *Allocator, a: Self, b: Self) IntersectError![]Point { var result = ArrayList(Point).init(alloc); const dir_a = if (a.start.x == a.end.x) TwoDir.Vertical else TwoDir.Horizontal; const dir_b = if (b.start.x == b.end.x) TwoDir.Vertical else TwoDir.Horizontal; // Parallel if (dir_a == TwoDir.Vertical and dir_b == TwoDir.Vertical) { // They need to have same x, otherwise it's impossible // to have an intersection if (a.start.x == b.start.x) { const a_bot_p = if (a.start.y < a.end.y) a.start else a.end; const a_top_p = if (a.start.y < a.end.y) a.end else a.start; const b_bot_p = if (b.start.y < b.end.y) b.start else b.end; const b_top_p = if (b.start.y < b.end.y) b.end else b.start; if (a_top_p.y > b_top_p.y) { const start_y = b_top_p.y; const end_y = a_bot_p.y; var i: i32 = start_y; while (i >= end_y) : (i -= 1) { try result.append(Point{ .x = a_bot_p.x, .y = i }); } } else { const start_y = a_top_p.y; const end_y = b_bot_p.y; var i: i32 = start_y; while (i >= end_y) : (i -= 1) { try result.append(Point{ .x = a_bot_p.x, .y = i }); } } } } else if (dir_a == TwoDir.Horizontal and dir_b == TwoDir.Horizontal) { // Flip x and y try result.appendSlice(try Self.intersect(alloc, Self{ .start = a.start.flip(), .end = a.end.flip() }, Self{ .start = b.start.flip(), .end = b.end.flip() })); } // Crossed else if (dir_a == TwoDir.Vertical and dir_b == TwoDir.Horizontal) { const a_x = a.start.x; const b_y = b.start.y; // a_x needs to be in range of b.start.x to b.end.x const b_left_p = if (b.start.x < b.end.x) b.start else b.end; const b_right_p = if (b.start.x < b.end.x) b.end else b.start; if (a_x >= b_left_p.x and a_x <= b_right_p.x) { // b_y needs to be in range of a.start.y to a.end.y const a_bot_p = if (a.start.y < a.end.y) a.start else a.end; const a_top_p = if (a.start.y < a.end.y) a.end else a.start; if (b_y >= a_bot_p.y and b_y <= a_top_p.y) { try result.append(Point{ .x = a_x, .y = b_y }); } } } else { // Flip a and b try result.appendSlice(try Self.intersect(alloc, b, a)); } // Remove (0,0) as valid intersections var i: usize = 0; while (i < result.items.len) { if (result.items[i].x == 0 and result.items[i].y == 0) { _ = result.orderedRemove(i); } else { i += 1; } } return result.items; } pub fn len(self: Line) !i32 { return try self.start.distanceBetween(self.end); } pub fn has(self: Line, p: Point) !bool { const dir = if (self.start.x == self.end.x) TwoDir.Vertical else TwoDir.Horizontal; const correct_dir = (dir == .Vertical and self.start.x == p.x) or (dir == .Horizontal and self.start.y == p.y); const between = (try self.start.distanceBetween(p)) <= (try self.len()); return correct_dir and between; } }; const Path = struct { lines: []Line, const Self = @This(); pub fn fromInstructions(alloc: *Allocator, instr: []Instruction) !Self { var result = ArrayList(Line).init(alloc); var current = Point{ .x = 0, .y = 0 }; for (instr) |i| { switch (i.dir) { .Right => { const dest_x = current.x + i.len; const dest = Point{ .x = dest_x, .y = current.y }; try result.append(Line{ .start = current, .end = dest }); current = dest; }, .Left => { const dest_x = current.x - i.len; const dest = Point{ .x = dest_x, .y = current.y }; try result.append(Line{ .start = current, .end = dest }); current = dest; }, .Down => { const dest_y = current.y - i.len; const dest = Point{ .x = current.x, .y = dest_y }; try result.append(Line{ .start = current, .end = dest }); current = dest; }, .Up => { const dest_y = current.y + i.len; const dest = Point{ .x = current.x, .y = dest_y }; try result.append(Line{ .start = current, .end = dest }); current = dest; }, } } return Path{ .lines = result.toOwnedSlice() }; } pub fn intersections(alloc: *Allocator, a: Path, b: Path) ![]Point { var result = ArrayList(Point).init(alloc); for (a.lines) |l| { for (b.lines) |p| { const ints = try Line.intersect(alloc, l, p); try result.appendSlice(ints); } } return result.toOwnedSlice(); } pub fn distanceFromStart(self: Path, p: Point) !i32 { var result: i32 = 0; // add up all the lines that lead up to this point var last_line = self.lines[0]; for (self.lines) |l| { last_line = l; if (try l.has(p)) { break; } else { result += try l.len(); } } // add the distance from the last line to the point result += try p.distanceBetween(last_line.start); return result; } }; test "test example path" { var arena = std.heap.ArenaAllocator.init(std.heap.page_allocator); const allocator = &arena.allocator; defer arena.deinit(); var instructions_1 = ArrayList(Instruction).init(allocator); try instructions_1.append(try Instruction.fromStr("R8")); try instructions_1.append(try Instruction.fromStr("U5")); try instructions_1.append(try Instruction.fromStr("L5")); try instructions_1.append(try Instruction.fromStr("D3")); const path_1 = try Path.fromInstructions(allocator, instructions_1.toOwnedSlice()); var instructions_2 = ArrayList(Instruction).init(allocator); try instructions_2.append(try Instruction.fromStr("U7")); try instructions_2.append(try Instruction.fromStr("R6")); try instructions_2.append(try Instruction.fromStr("D4")); try instructions_2.append(try Instruction.fromStr("L4")); const path_2 = try Path.fromInstructions(allocator, instructions_2.toOwnedSlice()); const ints = try Path.intersections(allocator, path_1, path_2); assert(path_1.lines.len == 4); assert(path_2.lines.len == 4); std.debug.warn("ints len {}\n", .{ints.len}); std.debug.warn("ints 0 {}\n", .{ints[0]}); std.debug.warn("ints 0 x {}\n", .{ints[0].x}); std.debug.warn("ints 0 y {}\n", .{ints[0].y}); assert(ints.len == 2); } pub fn main() !void { var arena = std.heap.ArenaAllocator.init(std.heap.page_allocator); const allocator = &arena.allocator; defer arena.deinit(); var paths = ArrayList(Path).init(allocator); const input_file = try std.fs.cwd().openFile("input03.txt", .{}); var input_stream = input_file.reader(); while (input_stream.readUntilDelimiterAlloc(allocator, '\n', 1024)) |line| { var instructions = ArrayList(Instruction).init(allocator); defer instructions.deinit(); var iter = std.mem.split(line, ","); while (iter.next()) |itm| { try instructions.append(try Instruction.fromStr(itm)); } try paths.append(try Path.fromInstructions(allocator, instructions.items)); } else |err| switch (err) { error.EndOfStream => {}, else => return err, } const path_1 = paths.items[0]; const path_2 = paths.items[1]; const ints = try Path.intersections(allocator, path_1, path_2); std.debug.warn("Number of intersections: {}\n", .{ints.len}); // Find closest intersection var min_dist: ?i32 = null; for (ints) |p| { const dist = (try path_1.distanceFromStart(p)) + (try path_2.distanceFromStart(p)); if (min_dist) |min| { if (dist < min) min_dist = dist; } else { min_dist = dist; } } std.debug.warn("Minimum distance: {}\n", .{min_dist}); }
zig/03_2.zig
const std = @import("std"); const expect = std.testing.expect; const assert = std.debug.assert; fn RingBuffer(comptime T: type) type { return struct { buffer: []T, head: usize, tail: usize, last_action: enum { Add, Remove }, pub fn init(buffer: []T) @This() { return .{ .buffer = buffer, .head = 0, .tail = 0, .last_action = .Remove, }; } pub fn next(self: *@This()) void { std.debug.assert(!self.is_empty()); self.tail = (self.tail + 1) % self.buffer.len; self.last_action = .Remove; } pub fn skip(self: *@This(), count: usize) void { std.debug.assert(count <= self.used_size()); self.tail = (self.tail + count) % self.buffer.len; if (count != 0) { self.last_action = .Remove; } } pub fn read_ahead(self: *const @This()) T { std.debug.assert(!self.is_empty()); return self.buffer[self.tail]; } pub fn read_ahead_at(self: *const @This(), index: usize) T { std.debug.assert(index < self.used_size()); return self.buffer[(self.tail + index) % self.buffer.len]; } pub fn read_ahead_slice(self: *const @This(), slice: []T) void { std.debug.assert(slice.len <= self.used_size()); for (slice) |*ref, i| { ref.* = self.read_ahead_at(i); } } pub fn push(self: *@This(), elem: T) void { std.debug.assert(!self.is_full()); self.buffer[self.head] = elem; self.head = (self.head + 1) % self.buffer.len; self.last_action = .Add; } pub fn pop(self: *@This()) T { std.debug.assert(!self.is_empty()); var result: T = self.buffer[self.tail]; self.next(); return result; } pub fn push_slice(self: *@This(), slice: []const T) void { std.debug.assert(slice.len <= self.free_size()); for (slice) |value| { self.push(value); } } pub fn pop_slice(self: *@This(), slice: []T) void { std.debug.assert(slice.len <= self.used_size()); self.read_ahead_slice(slice); self.skip(slice.len); } pub fn used_size(self: *const @This()) usize { if (self.head > self.tail) { return self.head - self.tail; } else if (self.head < self.tail) { return (self.head + self.buffer.len) - self.tail; } else if (self.last_action == .Remove) { return 0; } else { return self.buffer.len; } } pub fn free_size(self: *const @This()) usize { return self.buffer.len - self.used_size(); } pub fn is_empty(self: *const @This()) bool { return self.used_size() == 0; } pub fn is_full(self: *const @This()) bool { return self.free_size() == 0; } }; } test "push pop sequence" { var buffer_space: [4]u64 = undefined; var buffer = RingBuffer(u64).init(&buffer_space); buffer.push(1); buffer.push(2); buffer.push(3); buffer.push(4); expect(buffer.pop() == 1); buffer.push(5); expect(buffer.pop() == 2); expect(buffer.pop() == 3); expect(buffer.pop() == 4); expect(buffer.pop() == 5); } test "push pop slices sequence" { var buffer_space: [5]u64 = undefined; var buffer = RingBuffer(u64).init(&buffer_space); buffer.push_slice(&[_]u64{ 0, 1, 2, 3 }); buffer.next(); var return_buffer: [3]u64 = undefined; buffer.pop_slice(&return_buffer); expect(return_buffer[0] == 1); expect(return_buffer[1] == 2); expect(return_buffer[2] == 3); } test "read ahead" { var buffer_space: [3]u64 = undefined; var buffer = RingBuffer(u64).init(&buffer_space); buffer.push(1); buffer.push(2); buffer.push(3); buffer.next(); buffer.push(4); expect(buffer.read_ahead() == 2); expect(buffer.read_ahead_at(0) == 2); expect(buffer.read_ahead_at(1) == 3); expect(buffer.read_ahead_at(2) == 4); var read_ahead_buffer: [2]u64 = undefined; buffer.read_ahead_slice(&read_ahead_buffer); expect(read_ahead_buffer[0] == 2); expect(read_ahead_buffer[1] == 3); } test "sizes" { var buffer_space: [4]u64 = undefined; var buffer = RingBuffer(u64).init(&buffer_space); expect(buffer.free_size() == 4); expect(buffer.used_size() == 0); expect(buffer.is_empty()); expect(!buffer.is_full()); buffer.push(0); expect(buffer.free_size() == 3); expect(buffer.used_size() == 1); expect(!buffer.is_empty()); expect(!buffer.is_full()); buffer.push(1); buffer.push(2); buffer.push(3); expect(buffer.free_size() == 0); expect(buffer.used_size() == 4); expect(buffer.is_full()); expect(!buffer.is_empty()); buffer.next(); expect(buffer.free_size() == 1); expect(buffer.used_size() == 3); expect(!buffer.is_empty()); expect(!buffer.is_full()); } test "skip and next" { var buffer_space: [4]u64 = undefined; var buffer = RingBuffer(u64).init(&buffer_space); buffer.push(0); buffer.push(1); buffer.push(2); buffer.push(3); buffer.next(); buffer.skip(2); expect(buffer.pop() == 3); }
src/lib/ringbuffer.zig
const builtin = @import("builtin"); const testing = @import("std").testing; // TODO: I wish I could write something like `{ ...self, ._state = ty }` pub fn setField(lhs: var, comptime field_name: []const u8, value: var) @typeOf(lhs) { var new = lhs; @field(new, field_name) = value; return new; } test "setField updates a field and returns a brand new struct" { const x = setField(struct { a: u32, b: u32, }{ .a = 42, .b = 84, }, "a", 100); testing.expectEqual(u32(100), x.a); testing.expectEqual(u32(84), x.b); } pub fn append(lhs: var, x: var) @typeOf(lhs) { switch (@typeInfo(@typeOf(lhs))) { builtin.TypeId.Pointer => |info| switch (info.size) { builtin.TypeInfo.Pointer.Size.Slice => { const elem_type = info.child; return lhs ++ ([_]elem_type{x})[0..1]; }, else => @compileError("lhs must be a slice"), }, else => @compileError("lhs must be a slice"), } } test "append appends a new element" { comptime { const s0 = empty(u32); const s1 = append(s0, 100); testing.expectEqual([]const u32, @typeOf(s1)); testing.expectEqual(100, s1[0]); const s2 = append(s1, 200); testing.expectEqual([]const u32, @typeOf(s2)); testing.expectEqual(100, s2[0]); testing.expectEqual(200, s2[1]); } } pub fn empty(comptime ty: type) []const ty { return [_]ty{}; } test "empty produces an empty slice" { comptime { testing.expectEqual(empty(u32).len, 0); } } pub fn map(comptime To: type, comptime transducer: var, comptime slice: var) [slice.len]To { var ret: [slice.len]To = undefined; for (slice) |*e, i| { ret[i] = transducer(e); } return ret; } test "map does its job" { comptime { const array1 = map(u8, struct { fn ___(x: *const u32) u8 { return undefined; } }.___, empty(u8)); testing.expectEqual([0]u8, @typeOf(array1)); testing.expectEqualSlices(u8, &[_]u8{}, &array1); const array2 = map(u8, struct { fn ___(x: *const u32) u8 { return @truncate(u8, x.*) + 1; } }.___, [_]u32{ 1, 2, 3 }); testing.expectEqual([3]u8, @typeOf(array2)); testing.expectEqualSlices(u8, &[_]u8{ 2, 3, 4 }, &array2); } } pub fn intToStr(comptime i: var) []const u8 { comptime { if (i < 0) { @compileError("negative numbers are not supported (yet)"); } else if (i == 0) { return "0"; } else { var str: []const u8 = ""; var ii = i; while (ii > 0) { str = [1]u8{'0' + ii % 10} ++ str; ii /= 10; } return str; } } } test "intToStr does its job" { testing.expectEqualSlices(u8, &"0", intToStr(0)); testing.expectEqualSlices(u8, &"4", intToStr(4)); testing.expectEqualSlices(u8, &"42", intToStr(42)); }
druzhba/comptimeutils.zig
const std = @import("std"); const debug = std.debug; const fmt = std.fmt; const mem = std.mem; const math = std.math; pub fn main() !void { var allocator = &std.heap.DirectAllocator.init().allocator; var result1 = try biggest_finite_area(allocator, coordinates); debug.assert(result1 == 2342); debug.warn("06-1: {}\n", result1); var result2 = try safe_area(coordinates, 10000); debug.assert(result2 == 43302); debug.warn("06-2: {}\n", result2); } fn safe_area(coords: []const V2, distance_threshold: usize) !u32 { var max = point(0, 0); for (coords) |c| { //V2.print(c); if (c.x > max.x) { max.x = c.x; } if (c.y > max.y) { max.y = c.y; } } const field_stride = max.x + 1; const field_size: usize = field_stride * (max.y + 1); var area: u32 = 0; var cell_i: usize = 0; while (cell_i < field_size) : (cell_i += 1) { var distance_sum: usize = 0; for (coords) |coord, coord_i| { var dist = try manhattan_distance(point_from_index(cell_i, field_stride), coord); distance_sum += dist; if (distance_sum >= distance_threshold) { break; } } if (distance_sum < distance_threshold) { area += 1; } } return area; } test "safe area" { const test_threshold: usize = 32; debug.assert(16 == try safe_area(test_coords, test_threshold)); } fn biggest_finite_area(allocator: *mem.Allocator, coords: []const V2) !u32 { var max = point(0, 0); for (coords) |c| { //V2.print(c); if (c.x > max.x) { max.x = c.x; } if (c.y > max.y) { max.y = c.y; } } var field_stride = max.x + 1; var field = try allocator.alloc(isize, field_stride * (max.y + 1)); defer allocator.free(field); for (field) |*cell, cell_i| { cell.* = -1; var closest_distance = field.len * 1000; for (coords) |coord, coord_i| { var dist = try manhattan_distance(point_from_index(cell_i, field_stride), coord); if (dist < closest_distance) { closest_distance = dist; cell.* = @intCast(isize, coord_i); } else if (dist == closest_distance) { // when a cell of the field contains -1, this represents a tie cell.* = -1; } } } var coord_counts = try allocator.alloc(isize, coords.len); defer allocator.free(coord_counts); for (coord_counts) |*count| { count.* = 0; } for (field) |cell, cell_i| { if (cell < 0) { continue; } var current_cell = point_from_index(cell_i, field_stride); if (current_cell.x == 0 or current_cell.y == 0 or current_cell.x >= max.x or current_cell.y >= max.y) { // when a coord_count contains -1, this means that the area of that // coord is infinite coord_counts[@intCast(usize, cell)] = -1; } else { if (coord_counts[@intCast(usize, cell)] != -1) { coord_counts[@intCast(usize, cell)] += 1; } } } var max_area: isize = 0; var max_coord: usize = 0; for (coord_counts) |count, coord_i| { //debug.warn("[{}]: {}\n", coord_i, count); if (count > max_area) { max_area = count; max_coord = coord_i; } } debug.assert(max_area >= 0); return @intCast(u32, max_area); } test "biggest finite area" { var allocator = &std.heap.DirectAllocator.init().allocator; debug.assert(17 == try biggest_finite_area(allocator, test_coords)); } fn point_from_index(i: usize, stride: usize) V2 { var x: u32 = @intCast(u32, i % stride); var y: u32 = @intCast(u32, @divTrunc(i, stride)); return V2 { .x = x, .y = y }; } // 0 1 2 3 4 // 5 6 7 8 9 // 10 11 12 13 14 test "point from index" { debug.assert(0 == point_from_index(0, 5).x); debug.assert(0 == point_from_index(0, 5).y); debug.assert(1 == point_from_index(6, 5).x); debug.assert(1 == point_from_index(6, 5).y); debug.assert(2 == point_from_index(7, 5).x); debug.assert(1 == point_from_index(7, 5).y); debug.assert(4 == point_from_index(14, 5).x); debug.assert(2 == point_from_index(14, 5).y); } fn manhattan_distance(p1: V2, p2: V2) !u32 { var x_dist = (try math.absInt(@intCast(i32, p1.x) - @intCast(i32, p2.x))); var y_dist = (try math.absInt(@intCast(i32, p1.y) - @intCast(i32, p2.y))); return @intCast(u32, x_dist + y_dist); } test "manhattan" { debug.assert(5 == try manhattan_distance(point(1, 1), point(3, 4))); debug.assert(5 == try manhattan_distance(point(3, 4), point(1, 1))); debug.assert(0 == try manhattan_distance(point(13, 14), point(13, 14))); } const V2 = struct { x: u32, y: u32, fn print(self: V2) void { debug.warn("({}, {})\n", self.x, self.y); } }; inline fn point(x: u32, y: u32) V2 { return V2 { .x = x, .y = y, }; } const test_coords = []const V2 { point(1, 1), point(1, 6), point(8, 3), point(3, 4), point(5, 5), point(8, 9), }; const coordinates = comptime block: { break :block []V2{ point(67, 191), point(215, 237), point(130, 233), point(244, 61), point(93, 93), point(145, 351), point(254, 146), point(260, 278), point(177, 117), point(89, 291), point(313, 108), point(145, 161), point(143, 304), point(329, 139), point(153, 357), point(217, 156), point(139, 247), point(304, 63), point(202, 344), point(140, 302), point(233, 127), point(260, 251), point(235, 46), point(357, 336), point(302, 284), point(313, 260), point(135, 40), point(95, 57), point(227, 202), point(277, 126), point(163, 99), point(232, 271), point(130, 158), point(72, 289), point(89, 66), point(94, 111), point(210, 184), point(139, 58), point(99, 272), point(322, 148), point(209, 111), point(170, 244), point(230, 348), point(112, 200), point(287, 55), point(320, 270), point(53, 219), point(42, 52), point(313, 205), point(166, 259), }; };
2018/day_06.zig
const std = @import("std"); const builtin = @import("builtin"); const liu = @import("./lib.zig"); const EPSILON: f32 = 0.000001; const Allocator = std.mem.Allocator; const ArrayList = std.ArrayList; // Parser - https://github.com/RazrFalcon/ttf-parser // Raster - https://github.com/raphlinus/font-rs pub fn accumulate(alloc: Allocator, src: []const f32) ![]u8 { var acc: f32 = 0.0; const out = try alloc.alloc(u8, src.len); for (src) |c, idx| { acc += c; var y = @fabs(acc); y = if (y < 1.0) y else 1.0; out[idx] = @floatToInt(u8, 255.0 * y); } return out; } const Point = struct { x: f32, y: f32, pub fn intInit(x: i64, y: i64) Point { const xF = @intToFloat(f32, x); const yF = @intToFloat(f32, y); return .{ .x = xF, .y = yF }; } pub fn lerp(t0: f32, p0: Point, p1: Point) Point { const t = @splat(2, t0); const d0 = liu.Vec2{ p0.x, p0.y }; const d1 = liu.Vec2{ p1.x, p1.y }; const data = d0 + t * (d1 - d0); return Point{ .x = data[0], .y = data[1] }; } }; const Affine = struct { data: [6]f32, pub fn concat(t1: *const Affine, t2: *const Affine) Affine { _ = t1; _ = t2; const Vec6 = @Vector(6, f32); const v0 = Vec6{ t1[0], t1[1], t1[0], t1[1], t1[0], t1[1] }; const v1 = Vec6{ t2[0], t2[0], t2[2], t2[2], t2[4], t2[4] }; const v2 = Vec6{ t1[2], t1[3], t1[2], t1[3], t1[2], t1[3] }; const v3 = Vec6{ t2[1], t2[1], t2[3], t2[3], t2[5], t2[5] }; var out = v0 * v1 + v2 * v3; out[4] += t1[4]; out[5] += t1[5]; return Affine{ .data = out }; } pub fn pt(z: *const Affine, p: *const Point) Point { const v0 = liu.Vec2{ z.data[0], z.data[1] }; const v1 = liu.Vec2{ p.x, p.x }; const v2 = liu.Vec2{ z.data[2], z.data[3] }; const v3 = liu.Vec2{ p.y, p.y }; const v4 = liu.Vec2{ z.data[4], z.data[5] }; const data = v0 * v1 + v2 * v3 + v4; return Point{ .x = data[0], .y = data[1] }; } }; const Metrics = struct { l: i32, t: i32, r: i32, b: i32, pub fn width(self: *const Metrics) usize { return @intCast(usize, self.r - self.l); } pub fn height(self: *const Metrics) usize { return @intCast(usize, self.b - self.t); } }; pub const VMetrics = struct { ascent: f32, descent: f32, line_gap: f32, }; pub const HMetrics = struct { advance_width: f32, left_side_bearing: f32, }; const Raster = struct { w: usize, h: usize, a: []f32, pub fn init(alloc: Allocator, w: usize, h: usize) !Raster { const a = try alloc.alloc(f32, w * h + 4); std.mem.set(f32, a, 0.0); return Raster{ .w = w, .h = h, .a = a }; } pub fn drawLine(self: *Raster, _p0: Point, _p1: Point) void { if (@fabs(_p0.y - _p1.y) <= EPSILON) { return; } var p0 = _p0; var p1 = _p1; const dir: f32 = if (p0.y < p1.y) 1.0 else value: { p0 = _p1; p1 = _p0; break :value -1.0; }; const dxdy = (p1.x - p0.x) / (p1.y - p0.y); var x = p0.x; if (p0.y < 0.0) { x -= p0.y * dxdy; } const h_f32 = @intToFloat(f32, self.h); const max = @floatToInt(usize, std.math.min(h_f32, @ceil(p1.y))); // Raph says: "note: implicit max of 0 because usize (TODO: really true?)" // Raph means: Who tf knows. Wouldn't it be the MIN that's zero? Also, // doesn't your coordinate system start at zero anyways? var y: usize = @floatToInt(usize, p0.y); while (y < max) : (y += 1) { const linestart = y * self.w; const y_plus_1 = @intToFloat(f32, y + 1); const y_f32 = @intToFloat(f32, y); const dy = std.math.min(y_plus_1, p1.y) - std.math.max(y_f32, p0.y); const d = dy * dir; const xnext = x + dxdy * dy; var x0 = xnext; var x1 = x; if (x < xnext) { x0 = x; x1 = xnext; } const x0floor = @floor(x0); const x0i = @floatToInt(i32, x0floor); const x1ceil = @ceil(x1); const x1i = @floatToInt(i32, x1ceil); const linestart_x0i = @intCast(isize, linestart) + x0i; if (linestart_x0i < 0) { continue; // oob index } const linestart_x0 = @intCast(usize, linestart_x0i); if (x1i <= x0i + 1) { const xmf = 0.5 * (x + xnext) - x0floor; self.a[linestart_x0] += d - d * xmf; self.a[linestart_x0 + 1] += d * xmf; } else { const s = 1.0 / (x1 - x0); const x0f = x0 - x0floor; const a0 = 0.5 * s * (1.0 - x0f) * (1.0 - x0f); const x1f = x1 - x1ceil + 1.0; const am = 0.5 * s * x1f * x1f; self.a[linestart_x0] += d * a0; if (x1i == x0i + 2) { self.a[linestart_x0 + 1] += d * (1.0 - a0 - am); } else { const a1 = s * (1.5 - x0f); self.a[linestart_x0 + 1] += d * (a1 - a0); var xi: usize = @intCast(usize, x0i) + 2; while (xi < x1i - 1) : (xi += 1) { self.a[linestart + xi] += d * s; } const a2 = a1 + @intToFloat(f32, x1i - x0i - 3) * s; self.a[linestart + @intCast(usize, x1i - 1)] += d * (1.0 - a2 - am); } self.a[linestart + @intCast(usize, x1i)] += d * am; } x = xnext; } } pub fn drawQuad(self: *Raster, p0: Point, p1: Point, p2: Point) void { const devx = p0.x - 2.0 * p1.x + p2.x; const devy = p0.y - 2.0 * p1.y + p2.y; const devsq = devx * devx + devy * devy; if (devsq < 0.333) { self.drawLine(p0, p2); return; } // I'm pretty sure `tol` here stands for tolerance but the original code // says `tol` and i dont wanna change it without knowing what `tol` // actually stands for const tol = 3.0; const n = n: { // No idea what these interim values are, but having it be // written the other way seems dumb idk const idk0 = devx * devx + devy * devy; const idk1 = tol * idk0; const idk2 = @floor(@sqrt(@sqrt(idk1))); const idk3 = 1 + @floatToInt(usize, idk2); break :n idk3; }; var p = p0; const nrecip = 1 / @intToFloat(f32, n); var t: f32 = 0.0; var i: u32 = 0; while (i < n - 1) : (i += 1) { t += nrecip; const a = Point.lerp(t, p0, p1); const b = Point.lerp(t, p1, p2); const pn = Point.lerp(t, a, b); self.drawLine(p, pn); p = pn; } self.drawLine(p, p2); } }; const native_endian = builtin.target.cpu.arch.endian(); pub fn read(bytes: []const u8, comptime T: type) ?T { const Size = @sizeOf(T); if (bytes.len < Size) return null; switch (@typeInfo(T)) { .Int => { var value: T = @bitCast(T, bytes[0..Size].*); if (native_endian != .Big) value = @byteSwap(T, value); return value; }, else => @compileError("input type is not allowed (only allows integers right now)"), } } const FontParseError = error{ HeaderInvalid, OffsetInvalid, OffsetLengthInvalid, Unknown, }; const Font = struct { version: u32, head: []const u8, maxp: []const u8, loca: ?[]const u8, cmap: ?[]const u8, glyf: ?[]const u8, hhea: ?[]const u8, hmtx: ?[]const u8, const TagDescriptor = struct { tag: u32, value: usize }; const Tag = enum(u16) { head, maxp, loca, glyf, cmap, hhea, hmtx, _ }; const Count = std.meta.fields(Tag).len; const TagData: []const TagDescriptor = tags: { var data: []const TagDescriptor = &.{}; for (std.meta.fields(Tag)) |field| { data = data ++ [_]TagDescriptor{.{ .tag = @bitCast(u32, field.name[0..4].*), .value = field.value, }}; } break :tags data; }; pub fn init(data: []const u8) FontParseError!Font { const HeadErr = error.HeaderInvalid; const version = read(data[0..], u32) orelse return HeadErr; const num_tables = read(data[4..], u16) orelse return HeadErr; var tags: [Count]?[]const u8 = .{null} ** Count; var i: u16 = 0; table_loop: while (i < num_tables) : (i += 1) { const entry_begin = 12 + i * 16; const header = data[entry_begin..][0..16]; const offset = read(header[8..], u32) orelse return HeadErr; const length = read(header[12..], u32) orelse return HeadErr; if (offset > data.len) return error.OffsetInvalid; if (offset + length > data.len) return error.OffsetLengthInvalid; const table_data = data[offset..][0..length]; const tag = @bitCast(u32, header[0..4].*); // Ideally the code below should use: // // ``` // inline for (std.meta.fields(Tag)) |field| { // ``` // // But that seg-faults. Seems like a compiler bug. for (TagData) |field| { if (tag == field.tag) { tags[field.value] = table_data; continue :table_loop; } } } return Font{ .version = version, .head = tags[@enumToInt(Tag.head)] orelse return HeadErr, .maxp = tags[@enumToInt(Tag.maxp)] orelse return HeadErr, .loca = tags[@enumToInt(Tag.loca)], .cmap = tags[@enumToInt(Tag.cmap)], .glyf = tags[@enumToInt(Tag.glyf)], .hhea = tags[@enumToInt(Tag.hhea)], .hmtx = tags[@enumToInt(Tag.hmtx)], }; } // IDK what to do here yet pub fn getGlyphId(self: *const Font, code_point: u32) FontParseError!?u16 { if (code_point > std.math.maxInt(u16)) { return null; } // const num_tables = read(self.cmap[0..], u16) orelse return error.OffsetInvalid; // if (self.cmap.len < 4 + num_tables * 8) { // return error.OffsetLengthInvalid; // } // const encoding = encoding: { // var i: u16 = 0; // while (i < num_tables) : (i += 1) { // const offset = 8 * i + 4; // const table = self.cmap[offset..][0..8]; // const subtable_offset = read(table[4..], u32) orelse return error.OffsetInvalid; // const subtable_len = read(self.cmap[(subtable_offset + 2)..], u16) orelse // return error.OffsetInvalid; // const subtable = self.cmap[subtable_offset..][0..subtable_len]; // const format = read(subtable[0..], u16) orelse return error.OffsetInvalid; // std.debug.print("\nasdf: {}\n", .{format}); // if (format == 4) break :encoding subtable; // } // return error.Unknown; // }; // _ = encoding; _ = self; return 12; } }; // https://github.com/A1Liu/ted/blob/624527d690bd7019d463b51baa8fac8bea796c00/src/editor/fonts.rs#L71 // let face = expect(ttf::Face::from_slice(COURIER, 0)); // let (ascent, descent) = (face.ascender(), face.descender()); // let line_gap = face.line_gap(); // let glyph_id = unwrap(face.glyph_index('_')); // let rect = unwrap(face.glyph_bounding_box(glyph_id)); // face.outline_glyph(id, &mut builder); test "Fonts: basic" { const mark = liu.TempMark; defer liu.TempMark = mark; const bytes = @embedFile("../../static/fonts/cour.ttf"); const f = try Font.init(bytes); _ = try f.getGlyphId('A'); const affine = Affine{ .data = .{ 0, 1, 0, 1, 0.5, 0.25 } }; const p0 = Point{ .x = 1, .y = 0 }; const p1 = Point{ .x = 0, .y = 1 }; const p2 = Point{ .x = 0, .y = 0 }; var raster = try Raster.init(liu.Temp, 100, 100); raster.drawLine(p0, p1); raster.drawQuad(p0, p1, p2); _ = Point.lerp(0.5, p0, p1); _ = affine.pt(&p1); const out = try accumulate(liu.Temp, raster.a); _ = out; }
src/liu/fonts.zig
const std = @import("std"); const ArrayList = std.ArrayList; const AutoHashMap = std.AutoHashMap; const Allocator = std.mem.Allocator; const print = std.debug.print; const helpers = @import("helpers.zig"); const mode = @import("builtin").mode; const dbg = helpers.dbg; const testing = std.testing; /// A node in an undirected graph. It holds a value, and a hashmap representing /// edges where each entry stores the adjacent node pointer as its key and the /// weight as its value. /// `Value` is the type of data to be stored in `Node`s, with copy semantics. /// `Weight` is the type of weights or costs between `Node`s. Weights are /// allocated twice, once in each nodes' edge hashmap. An edge that is set /// twice between the same two nodes simply has its weight updated. pub fn Node(comptime Value: type, comptime Weight: type) type { return struct { pub const Self = @This(); pub const EdgeMap = AutoHashMap(*Self, Weight); pub const Edge = struct { that: *Self, weight: Weight, }; /// An edges between two node pointers. Isn't used by Nodes to store /// their edges (a hashmap is used instead) but rather when enumerating /// all edges in the graph. pub const FullEdge = struct { this: *Self, that: *Self, weight: Weight, }; allocator: Allocator, value: Value, /// Individual edges are stored twice, once in each node in a pair /// that form the edge. These are separate from `FullEdge` structs, which /// keep track of pairs of nodes. edges: EdgeMap, /// Creates a new node, allocating a copy of Value. pub fn init(allocator: Allocator, value: Value) !*Self { var node = try allocator.create(Self); node.* = Self{ .allocator = allocator, .value = value, .edges = EdgeMap.init(allocator), }; return node; } /// Same as `init`, but initializes this node's hashmap to the edges /// passed in. Duplicate edges will only have the last copy saved. pub fn initWithEdges( allocator: Allocator, value: Value, edges: []const Edge, ) !*Self { var node = try init(allocator, value); // Add edges into the hashmap. for (edges) |edge| try node.addEdge(edge.that, edge.weight); return node; } /// Puts an edge entry into each node's hashmap. /// If the edge already exists, the weight will be updated. pub fn addEdge(self: *Self, other: *Self, weight: Weight) !void { // Use of `put` assumes `edges` was passed in with no // duplicates, otherwise will overwrite the weight. try self.edges.put(other, weight); // Add this node to the adjacent's edges try other.edges.put(self, weight); } /// Removes an edge by deleting the outgoing and all incoming /// references. // Assumes edges are always a valid pair of incoming/outgoing pub fn removeEdge(self: *Self, other: *Self) bool { return self.edges.remove(other) and // Remove outgoing other.edges.remove(self); // Remove incoming } /// Removes a node and all its references (equivalent to calling /// detach and destroy, but faster). /// You probably want this function instead of calling both detach and /// destroy. pub fn deinit(self: *Self, allocator: Allocator) void { var edge_iter = self.edges.keyIterator(); while (edge_iter.next()) |adjacent| _ = adjacent.*.edges.remove(self); self.edges.deinit(); // Free this list of edges allocator.destroy(self); // Free this node } /// Detach adjacent nodes (erase their references of this node). pub fn detach(self: *Self) void { var edge_iter = self.edges.keyIterator(); // Free incoming references to this node in adjacents. while (edge_iter.next()) |adjacent| { const was_removed = adjacent.*.edges.remove(self); comptime { if (std.builtin.mod == .debugs) testing.expect(!was_removed); } } // Free outgoing references self.edges.clear(); // self.edges.clearRetainingCapacity(); } /// Free the memory backing this node. /// Incoming edges will no longer be valid, so this function should /// only be called on detached nodes (ones without edges). pub fn destroy(self: *Self) void { self.edges.deinit(); // Free this list of edges self.allocator.destroy(self); // Free this node } /// Returns a set of all nodes in this graph. /// Caller frees (calls `deinit`). // Node pointers must be used because HashMaps don't allow structs // containing slices. pub fn nodeSet( self: *const Self, allocator: Allocator, ) !AutoHashMap(*const Self, void) { var node_set = AutoHashMap(*const Self, void).init(allocator); // A stack to add nodes reached across edges var to_visit = ArrayList(*const Self).init(allocator); defer to_visit.deinit(); // Greedily add all neighbors to `to_visit`, then loop until // no new neighbors are found. try to_visit.append(self); while (to_visit.popOrNull()) |node_ptr| { // If the node is unvisited if (!node_set.contains(node_ptr)) { // Add to set (marks as visited) try node_set.put(node_ptr, {}); // Save adjacent nodes to check later var adjacents = self.edges.keyIterator(); while (adjacents.next()) |adjacent_ptr| { try to_visit.append(adjacent_ptr.*); } } } return node_set; } /// Returns a set of all node pointers in this graph. /// If you don't need to mutate any nodes, call `nodes` instead. /// Caller frees (calls `deinit`). pub fn nodePtrSet( self: *Self, allocator: Allocator, ) !AutoHashMap(*Self, void) { var node_set = AutoHashMap(*Self, void).init(allocator); // A stack to add nodes reached across edges var to_visit = ArrayList(*Self).init(allocator); defer to_visit.deinit(); // Greedily add all neighbors to `to_visit`, then loop until // no new neighbors are found. try to_visit.append(self); while (to_visit.popOrNull()) |node_ptr| { // If the node is unvisited if (!node_set.contains(node_ptr)) { // Add to set (marks as visited) try node_set.put(node_ptr, {}); // Save adjacent nodes to check later var adjacents = self.edges.keyIterator(); while (adjacents.next()) |adjacent_ptr| { try to_visit.append(adjacent_ptr.*); } } } return node_set; } /// Returns a set of all edges in this graph. /// Caller frees (calls `deinit`). pub fn edgeSet( self: *Self, allocator: Allocator, ) !AutoHashMap(FullEdge, void) { // Use a 0 size value (void) to use a hashmap as a set, in order // to avoid listing edges twice. var edge_set = AutoHashMap(FullEdge, void).init(allocator); // Get a view of all nodes var node_set = try self.nodePtrSet(allocator); defer node_set.deinit(); var nodes_iter = node_set.keyIterator(); while (nodes_iter.next()) |node_ptr| { // For each node var edge_iter = node_ptr.*.edges.iterator(); // Get its edges while (edge_iter.next()) |edge_entry| { // For each edge if (!edge_set.contains( // If it's reverse isn't in yet FullEdge{ .this = edge_entry.key_ptr.*, .that = node_ptr.*, .weight = edge_entry.value_ptr.*, }, )) // Overwrite if the edge exists already try edge_set.put( FullEdge{ .this = node_ptr.*, .that = edge_entry.key_ptr.*, .weight = edge_entry.value_ptr.*, }, {}, // The 0 size "value" ); } } return edge_set; } /// Pass into `exportDot` to configure dot output. pub const DotSettings = struct { // graph_setting: ?String = null, // node_setting: ?String = null, // edge_setting: ?String = null, }; /// Writes the graph out in dot (graphviz) to the given `writer`. /// Node value types currently must be `[]const u8`. pub fn exportDot( self: *Self, allocator: Allocator, writer: anytype, dot_settings: DotSettings, ) !void { _ = dot_settings; // TODO try writer.writeAll("Graph {\n"); var node_set = try self.nodePtrSet(allocator); defer node_set.deinit(); var nodes_iter = node_set.keyIterator(); while (nodes_iter.next()) |node_ptr| { try writer.print( "{s} [];\n", .{node_ptr.*.value}, ); } var edge_set = try self.edgeSet(self.allocator); defer edge_set.deinit(); var edge_iter = edge_set.keyIterator(); while (edge_iter.next()) |edge| { try writer.print( "{s} -- {s} [label={}];\n", .{ edge.this.value, edge.that.value, edge.weight, }, ); } try writer.writeAll("}\n"); } }; } // TODO: test memory under rare conditions: // - allocator failure // - inside add: allocator succeeds but list append fails test "graph memory management" { std.testing.log_level = .debug; const allocator = std.testing.allocator; var node1 = try Node([]const u8, u32).init(allocator, "n1"); defer node1.deinit(allocator); var node2 = try Node([]const u8, u32).init(allocator, "n2"); defer node2.deinit(allocator); try node1.addEdge(node2, 123); } test "iterate over single node" { const allocator = std.testing.allocator; var node1 = try Node([]const u8, u32).init(allocator, "n1"); defer node1.deinit(allocator); var edges = try node1.edgeSet(allocator); defer edges.deinit(); var edge_iter = edges.keyIterator(); // Print nodes' values while (edge_iter.next()) |edge_ptr| { print("({s})--[{}]--({s})\n", .{ edge_ptr.this.value, edge_ptr.weight, edge_ptr.that.value, }); } } test "iterate over edges" { const allocator = std.testing.allocator; var node1 = try Node([]const u8, u32).init(allocator, "n1"); defer node1.deinit(allocator); var node2 = try Node([]const u8, u32).initWithEdges(allocator, "n2", &.{}); defer node2.deinit(allocator); var node3 = try Node([]const u8, u32).initWithEdges(allocator, "n3", &.{}); defer node3.deinit(allocator); const node4 = try Node([]const u8, u32).initWithEdges( allocator, "n4", // Segfaults if an anon struct is used instead &[_]Node([]const u8, u32).Edge{ .{ .that = node1, .weight = 41 }, }, ); defer node4.deinit(allocator); try node1.addEdge(node2, 12); try node3.addEdge(node1, 31); try node2.addEdge(node1, 21); // should update 12 to 21 try node2.addEdge(node1, 21); // should be a no op try node2.addEdge(node3, 23); // Allocate the current edges var edges = try node1.edgeSet(allocator); defer edges.deinit(); // The hashmap is used as a set, so it only has keys var edge_iter = edges.keyIterator(); // Print their nodes' values and the weights between them while (edge_iter.next()) |edge| { print("({s})--[{}]--({s})\n", .{ edge.this.value, edge.weight, edge.that.value, }); } } test "dot export" { const allocator = std.testing.allocator; var node1 = try Node([]const u8, u32).init(allocator, "n1"); defer node1.deinit(allocator); var node2 = try Node([]const u8, u32).init(allocator, "n2"); defer node2.deinit(allocator); try node1.addEdge(node2, 123); _ = try node1.exportDot(allocator, std.io.getStdOut().writer(), .{}); } test "remove edge" { std.testing.log_level = .debug; const allocator = std.testing.allocator; var node1 = try Node([]const u8, u32).init(allocator, "n1"); defer node1.deinit(allocator); var node2 = try Node([]const u8, u32).init(allocator, "n2"); defer node2.deinit(allocator); try node1.addEdge(node2, 123); try testing.expect(node1.removeEdge(node2)); // should be removable try testing.expect(!node1.removeEdge(node2)); // shouldn't be there }
src/graph.zig
const std = @import("std"); const math = std.math; const qnan128 = @bitCast(f128, @as(u128, 0x7fff800000000000) << 64); const __addtf3 = @import("addXf3.zig").__addtf3; fn test__addtf3(a: f128, b: f128, expected_hi: u64, expected_lo: u64) !void { const x = __addtf3(a, b); const rep = @bitCast(u128, x); const hi = @intCast(u64, rep >> 64); const lo = @truncate(u64, rep); if (hi == expected_hi and lo == expected_lo) { return; } // test other possible NaN representation (signal NaN) else if (expected_hi == 0x7fff800000000000 and expected_lo == 0x0) { if ((hi & 0x7fff000000000000) == 0x7fff000000000000 and ((hi & 0xffffffffffff) > 0 or lo > 0)) { return; } } return error.TestFailed; } test "addtf3" { try test__addtf3(qnan128, 0x1.23456789abcdefp+5, 0x7fff800000000000, 0x0); // NaN + any = NaN try test__addtf3(@bitCast(f128, (@as(u128, 0x7fff000000000000) << 64) | @as(u128, 0x800030000000)), 0x1.23456789abcdefp+5, 0x7fff800000000000, 0x0); // inf + inf = inf try test__addtf3(math.inf(f128), math.inf(f128), 0x7fff000000000000, 0x0); // inf + any = inf try test__addtf3(math.inf(f128), 0x1.2335653452436234723489432abcdefp+5, 0x7fff000000000000, 0x0); // any + any try test__addtf3(0x1.23456734245345543849abcdefp+5, 0x1.edcba52449872455634654321fp-1, 0x40042afc95c8b579, 0x61e58dd6c51eb77c); try test__addtf3(0x1.edcba52449872455634654321fp-1, 0x1.23456734245345543849abcdefp+5, 0x40042afc95c8b579, 0x61e58dd6c51eb77c); } const __subtf3 = @import("addXf3.zig").__subtf3; fn test__subtf3(a: f128, b: f128, expected_hi: u64, expected_lo: u64) !void { const x = __subtf3(a, b); const rep = @bitCast(u128, x); const hi = @intCast(u64, rep >> 64); const lo = @truncate(u64, rep); if (hi == expected_hi and lo == expected_lo) { return; } // test other possible NaN representation (signal NaN) else if (expected_hi == 0x7fff800000000000 and expected_lo == 0x0) { if ((hi & 0x7fff000000000000) == 0x7fff000000000000 and ((hi & 0xffffffffffff) > 0 or lo > 0)) { return; } } return error.TestFailed; } test "subtf3" { // qNaN - any = qNaN try test__subtf3(qnan128, 0x1.23456789abcdefp+5, 0x7fff800000000000, 0x0); // NaN + any = NaN try test__subtf3(@bitCast(f128, (@as(u128, 0x7fff000000000000) << 64) | @as(u128, 0x800030000000)), 0x1.23456789abcdefp+5, 0x7fff800000000000, 0x0); // inf - any = inf try test__subtf3(math.inf(f128), 0x1.23456789abcdefp+5, 0x7fff000000000000, 0x0); // any + any try test__subtf3(0x1.234567829a3bcdef5678ade36734p+5, 0x1.ee9d7c52354a6936ab8d7654321fp-1, 0x40041b8af1915166, 0xa44a7bca780a166c); try test__subtf3(0x1.ee9d7c52354a6936ab8d7654321fp-1, 0x1.234567829a3bcdef5678ade36734p+5, 0xc0041b8af1915166, 0xa44a7bca780a166c); } const __addxf3 = @import("addXf3.zig").__addxf3; const qnan80 = @bitCast(f80, @bitCast(u80, math.nan(f80)) | (1 << (math.floatFractionalBits(f80) - 1))); fn test__addxf3(a: f80, b: f80, expected: u80) !void { const x = __addxf3(a, b); const rep = @bitCast(u80, x); if (rep == expected) return; if (math.isNan(@bitCast(f80, expected)) and math.isNan(x)) return; // We don't currently test NaN payload propagation return error.TestFailed; } test "addxf3" { // NaN + any = NaN try test__addxf3(qnan80, 0x1.23456789abcdefp+5, @bitCast(u80, qnan80)); try test__addxf3(@bitCast(f80, @as(u80, 0x7fff_8000_8000_3000_0000)), 0x1.23456789abcdefp+5, @bitCast(u80, qnan80)); // any + NaN = NaN try test__addxf3(0x1.23456789abcdefp+5, qnan80, @bitCast(u80, qnan80)); try test__addxf3(0x1.23456789abcdefp+5, @bitCast(f80, @as(u80, 0x7fff_8000_8000_3000_0000)), @bitCast(u80, qnan80)); // NaN + inf = NaN try test__addxf3(qnan80, math.inf(f80), @bitCast(u80, qnan80)); // inf + NaN = NaN try test__addxf3(math.inf(f80), qnan80, @bitCast(u80, qnan80)); // inf + inf = inf try test__addxf3(math.inf(f80), math.inf(f80), @bitCast(u80, math.inf(f80))); // inf + -inf = NaN try test__addxf3(math.inf(f80), -math.inf(f80), @bitCast(u80, qnan80)); // -inf + inf = NaN try test__addxf3(-math.inf(f80), math.inf(f80), @bitCast(u80, qnan80)); // inf + any = inf try test__addxf3(math.inf(f80), 0x1.2335653452436234723489432abcdefp+5, @bitCast(u80, math.inf(f80))); // any + inf = inf try test__addxf3(0x1.2335653452436234723489432abcdefp+5, math.inf(f80), @bitCast(u80, math.inf(f80))); // any + any try test__addxf3(0x1.23456789abcdp+5, 0x1.dcba987654321p+5, 0x4005_BFFFFFFFFFFFC400); try test__addxf3(0x1.23456734245345543849abcdefp+5, 0x1.edcba52449872455634654321fp-1, 0x4004_957E_4AE4_5ABC_B0F3); try test__addxf3(0x1.ffff_ffff_ffff_fffcp+0, 0x1.0p-63, 0x3FFF_FFFFFFFFFFFFFFFF); // exact try test__addxf3(0x1.ffff_ffff_ffff_fffep+0, 0x0.0p0, 0x3FFF_FFFFFFFFFFFFFFFF); // exact try test__addxf3(0x1.ffff_ffff_ffff_fffcp+0, 0x1.4p-63, 0x3FFF_FFFFFFFFFFFFFFFF); // round down try test__addxf3(0x1.ffff_ffff_ffff_fffcp+0, 0x1.8p-63, 0x4000_8000000000000000); // round up to even try test__addxf3(0x1.ffff_ffff_ffff_fffcp+0, 0x1.cp-63, 0x4000_8000000000000000); // round up try test__addxf3(0x1.ffff_ffff_ffff_fffcp+0, 0x2.0p-63, 0x4000_8000000000000000); // exact try test__addxf3(0x1.ffff_ffff_ffff_fffcp+0, 0x2.1p-63, 0x4000_8000000000000000); // round down try test__addxf3(0x1.ffff_ffff_ffff_fffcp+0, 0x3.0p-63, 0x4000_8000000000000000); // round down to even try test__addxf3(0x1.ffff_ffff_ffff_fffcp+0, 0x3.1p-63, 0x4000_8000000000000001); // round up try test__addxf3(0x1.ffff_ffff_ffff_fffcp+0, 0x4.0p-63, 0x4000_8000000000000001); // exact try test__addxf3(0x1.0fff_ffff_ffff_fffep+0, 0x1.0p-63, 0x3FFF_8800000000000000); // exact try test__addxf3(0x1.0fff_ffff_ffff_fffep+0, 0x1.7p-63, 0x3FFF_8800000000000000); // round down try test__addxf3(0x1.0fff_ffff_ffff_fffep+0, 0x1.8p-63, 0x3FFF_8800000000000000); // round down to even try test__addxf3(0x1.0fff_ffff_ffff_fffep+0, 0x1.9p-63, 0x3FFF_8800000000000001); // round up try test__addxf3(0x1.0fff_ffff_ffff_fffep+0, 0x2.0p-63, 0x3FFF_8800000000000001); // exact try test__addxf3(0x0.ffff_ffff_ffff_fffcp-16382, 0x0.0000_0000_0000_0002p-16382, 0x0000_7FFFFFFFFFFFFFFF); // exact try test__addxf3(0x0.1fff_ffff_ffff_fffcp-16382, 0x0.0000_0000_0000_0002p-16382, 0x0000_0FFFFFFFFFFFFFFF); // exact }
lib/compiler_rt/addXf3_test.zig
const std = @import("std"); const assert = std.debug.assert; /// A First In, First Out ring buffer holding at most `size` elements. pub fn RingBuffer(comptime T: type, comptime size: usize) type { return struct { const Self = @This(); buffer: [size]T = undefined, /// The index of the slot with the first item, if any. index: usize = 0, /// The number of items in the buffer. count: usize = 0, /// Add an element to the RingBuffer. Returns an error if the buffer /// is already full and the element could not be added. pub fn push(self: *Self, item: T) error{NoSpaceLeft}!void { if (self.full()) return error.NoSpaceLeft; self.buffer[(self.index + self.count) % self.buffer.len] = item; self.count += 1; } /// Return, but do not remove, the next item, if any. pub fn peek(self: *Self) ?T { return (self.peek_ptr() orelse return null).*; } /// Return a pointer to, but do not remove, the next item, if any. pub fn peek_ptr(self: *Self) ?*T { if (self.empty()) return null; return &self.buffer[self.index]; } /// Remove and return the next item, if any. pub fn pop(self: *Self) ?T { if (self.empty()) return null; defer { self.index = (self.index + 1) % self.buffer.len; self.count -= 1; } return self.buffer[self.index]; } /// Returns whether the ring buffer is completely full. pub fn full(self: *const Self) bool { return self.count == self.buffer.len; } /// Returns whether the ring buffer is completely empty. pub fn empty(self: *const Self) bool { return self.count == 0; } pub const Iterator = struct { ring: *Self, count: usize = 0, pub fn next(it: *Iterator) ?T { return (it.next_ptr() orelse return null).*; } pub fn next_ptr(it: *Iterator) ?*T { assert(it.count <= it.ring.count); if (it.count == it.ring.count) return null; defer it.count += 1; return &it.ring.buffer[(it.ring.index + it.count) % it.ring.buffer.len]; } }; /// Returns an iterator to iterate through all `count` items in the ring buffer. /// The iterator is invalidated and unsafe if the ring buffer is modified. pub fn iterator(self: *Self) Iterator { return .{ .ring = self }; } }; } const testing = std.testing; test "push/peek/pop/full/empty" { var fifo = RingBuffer(u32, 3){}; try testing.expect(!fifo.full()); try testing.expect(fifo.empty()); try fifo.push(1); try testing.expectEqual(@as(?u32, 1), fifo.peek()); try testing.expect(!fifo.full()); try testing.expect(!fifo.empty()); try fifo.push(2); try testing.expectEqual(@as(?u32, 1), fifo.peek()); try fifo.push(3); try testing.expectError(error.NoSpaceLeft, fifo.push(4)); try testing.expect(fifo.full()); try testing.expect(!fifo.empty()); try testing.expectEqual(@as(?u32, 1), fifo.peek()); try testing.expectEqual(@as(?u32, 1), fifo.pop()); try testing.expect(!fifo.full()); try testing.expect(!fifo.empty()); fifo.peek_ptr().?.* += 1000; try testing.expectEqual(@as(?u32, 1002), fifo.pop()); try testing.expectEqual(@as(?u32, 3), fifo.pop()); try testing.expectEqual(@as(?u32, null), fifo.pop()); try testing.expect(!fifo.full()); try testing.expect(fifo.empty()); } fn test_iterator(comptime T: type, ring: *T, values: []const u32) !void { const ring_index = ring.index; var loops: usize = 0; while (loops < 2) : (loops += 1) { var iterator = ring.iterator(); var index: usize = 0; while (iterator.next()) |item| { try testing.expectEqual(values[index], item); index += 1; } try testing.expectEqual(values.len, index); } try testing.expectEqual(ring_index, ring.index); } test "iterator" { const Ring = RingBuffer(u32, 2); var ring = Ring{}; try test_iterator(Ring, &ring, &[_]u32{}); try ring.push(0); try test_iterator(Ring, &ring, &[_]u32{0}); try ring.push(1); try test_iterator(Ring, &ring, &[_]u32{ 0, 1 }); try testing.expectEqual(@as(?u32, 0), ring.pop()); try test_iterator(Ring, &ring, &[_]u32{1}); try ring.push(2); try test_iterator(Ring, &ring, &[_]u32{ 1, 2 }); var iterator = ring.iterator(); while (iterator.next_ptr()) |item_ptr| { item_ptr.* += 1000; } try testing.expectEqual(@as(?u32, 1001), ring.pop()); try test_iterator(Ring, &ring, &[_]u32{1002}); try ring.push(3); try test_iterator(Ring, &ring, &[_]u32{ 1002, 3 }); try testing.expectEqual(@as(?u32, 1002), ring.pop()); try test_iterator(Ring, &ring, &[_]u32{3}); try testing.expectEqual(@as(?u32, 3), ring.pop()); try test_iterator(Ring, &ring, &[_]u32{}); }
src/ring_buffer.zig
const std = @import("std"); const Rational = std.math.big.Rational; const Allocator = std.mem.Allocator; const Real = @import("Real.zig").Real; const IntermediateRepresentation = @import("ir.zig"); // TODO: rhm will have approximate mode, which runs faster at the expense of using floats instead of Reals // TODO: resolve() standard function for resolving equations (only on functions with no control flow) // ex: function sinus(x) -> sin(x) // resolve(sinus, "=") -- return a function that given an expected result b, returns a number a such that f(a) = b // resolve(sinus, "=")(1) -- should be equal to π/2 const Value = union(enum) { None: void, // TODO: UInt32, Int32, etc. types to save on memory // TODO: use rationals Number: *Real, // Number: Real String: []const u8, pub fn clone(self: *Value, allocator: Allocator) !Value { switch (self.*) { .Number => |object| { return Value { .Number = try object.clone(allocator) }; }, .String => std.debug.todo("clone strings"), .None => unreachable, } } pub fn reference(self: *Value) void { switch (self.*) { .Number => |object| { object.rc.reference(); }, else => {} } } pub fn dereference(self: *Value) void { switch (self.*) { .Number => |object| { object.rc.dereference(); }, else => {} } } }; pub fn execute(allocator: Allocator, ir: []const IntermediateRepresentation.Instruction) !void { var registers: [256]Value = [_]Value{ .None } ** 256; // TODO: dynamically size locals array var locals: [16]Value = [_]Value{ .None } ** 16; for (ir) |instruction| { std.log.scoped(.vm).debug("{}", .{ instruction }); switch (instruction) { .LoadByte => |lb| { const real = try Real.initFloat(allocator, @intToFloat(f32, lb.value)); // Dereference old value const registerId = @enumToInt(lb.target); registers[registerId].dereference(); registers[@enumToInt(lb.target)] = .{ .Number = real }; }, .LoadString => |ls| { // Dereference old value const registerId = @enumToInt(ls.target); registers[registerId].dereference(); registers[@enumToInt(ls.target)] = .{ .String = ls.value }; }, .Add => |add| { var result = try registers[@enumToInt(add.lhs)].Number.clone(allocator); try result.add(allocator, registers[@enumToInt(add.rhs)].Number); // Dereference old value const registerId = @enumToInt(add.target); registers[registerId].dereference(); registers[@enumToInt(add.target)] = .{ .Number = result }; }, .SetLocal => |set| { std.log.scoped(.vm).debug("set local {d} to {d}", .{ set.local, registers[@enumToInt(set.source)] }); const localId = @enumToInt(set.local); // If there was already a local there, de-reference it locals[localId].dereference(); locals[localId] = try registers[@enumToInt(set.source)].clone(allocator); }, .LoadLocal => |load| { std.log.scoped(.vm).debug("load from local {d} to register {d} = {d}", .{ load.local, load.target, locals[@enumToInt(load.local)] }); // Dereference old value const registerId = @enumToInt(load.target); registers[registerId].dereference(); registers[registerId] = try locals[@enumToInt(load.local)].clone(allocator); }, .LoadGlobal => |load| { std.log.scoped(.vm).debug("load from global {s} to register {d}", .{ load.global, load.target }); if (std.mem.eql(u8, load.global, "pi")) { // Dereference old value const registerId = @enumToInt(load.target); registers[registerId].dereference(); registers[@enumToInt(load.target)] = .{ .Number = try Real.pi(allocator) }; } else { @panic("TODO"); } }, .CallFunction => |call| { std.log.scoped(.vm).debug("call {s} with {d} arguments ", .{ call.name, call.args_num }); if (std.mem.eql(u8, call.name, "print")) { var i: u8 = 0; while (i < call.args_num) : (i += 1) { const value = registers[@enumToInt(call.args_start) + i]; switch (value) { .None => @panic("'None' value cannot be used by a program"), .Number => std.log.info("{d}", .{ value.Number }), .String => std.log.info("{s}", .{ value.String }), } } } else { std.log.err("no such function {s}", .{ call.name }); break; } }, .Move => |move| { // Dereference old value const registerId = @enumToInt(move.target); registers[registerId].dereference(); registers[@enumToInt(move.target)] = try registers[@enumToInt(move.source)].clone(allocator); } } } for (locals) |*local, idx| { if (local.* != .None) std.log.debug("deinit local {d}", .{ idx }); local.dereference(); } for (registers) |*register, idx| { if (register.* != .None) std.log.debug("deinit register {d}", .{ idx }); register.dereference(); } }
src/vm.zig
const std = @import("std"); const zp = @import("zplay"); const VertexArray = zp.graphics.common.VertexArray; const Texture2D = zp.graphics.texture.Texture2D; const Camera = zp.graphics.@"3d".Camera; const Material = zp.graphics.@"3d".Material; const Renderer = zp.graphics.@"3d".Renderer; const SimpleRenderer = zp.graphics.@"3d".SimpleRenderer; const alg = zp.deps.alg; const Vec3 = alg.Vec3; const Mat4 = alg.Mat4; var simple_renderer: SimpleRenderer = undefined; var vertex_array: VertexArray = undefined; var material: Material = undefined; const vertices = [_]f32{ -0.5, -0.5, 0.0, 1.0, 0.0, 0.0, 1.0, 0.5, -0.5, 0.0, 0.0, 1.0, 0.0, 1.0, 0.0, 0.5, 0.0, 0.0, 0.0, 1.0, 1.0, }; fn init(ctx: *zp.Context) anyerror!void { _ = ctx; std.log.info("game init", .{}); // create renderer simple_renderer = SimpleRenderer.init(); simple_renderer.mix_factor = 1; // vertex array vertex_array = VertexArray.init(5); vertex_array.use(); defer vertex_array.disuse(); vertex_array.bufferData(0, f32, &vertices, .array_buffer, .static_draw); vertex_array.setAttribute(0, SimpleRenderer.ATTRIB_LOCATION_POS, 3, f32, false, 7 * @sizeOf(f32), 0); vertex_array.setAttribute(0, SimpleRenderer.ATTRIB_LOCATION_COLOR, 4, f32, false, 7 * @sizeOf(f32), 3 * @sizeOf(f32)); // create material material = Material.init(.{ .single_texture = try Texture2D.fromPixelData( std.testing.allocator, &.{ 0, 0, 0, 255, 0, 255, 0, 255, 0, 0, 255, 255, 255, 255, 255, 255, }, 2, 2, .{}, ) }); _ = material.allocTextureUnit(0); } fn loop(ctx: *zp.Context) void { while (ctx.pollEvent()) |e| { switch (e) { .window_event => |we| { switch (we.data) { .resized => |size| { ctx.graphics.setViewport(0, 0, size.width, size.height); }, else => {}, } }, .keyboard_event => |key| { if (key.trigger_type == .up) { switch (key.scan_code) { .escape => ctx.kill(), .f1 => ctx.toggleFullscreeen(null), else => {}, } } }, .quit_event => ctx.kill(), else => {}, } } ctx.graphics.clear(true, false, false, [_]f32{ 0.2, 0.3, 0.3, 1.0 }); // update color and draw triangle simple_renderer.renderer().begin(); simple_renderer.renderer().render( vertex_array, false, .triangles, 0, 3, Mat4.identity(), Mat4.identity(), null, material, null, ) catch unreachable; simple_renderer.renderer().end(); } fn quit(ctx: *zp.Context) void { _ = ctx; std.log.info("game quit", .{}); } pub fn main() anyerror!void { try zp.run(.{ .initFn = init, .loopFn = loop, .quitFn = quit, .enable_resizable = true, }); }
examples/single_triangle.zig
const std = @import("std"); const aoc = @import("aoc-lib.zig"); test "examples" { const test0 = try aoc.Ints(aoc.talloc, i64, aoc.test0file); defer aoc.talloc.free(test0); const test1 = try aoc.Ints(aoc.talloc, i64, aoc.test1file); defer aoc.talloc.free(test1); const test2 = try aoc.Ints(aoc.talloc, i64, aoc.test2file); defer aoc.talloc.free(test2); const inp = try aoc.Ints(aoc.talloc, i64, aoc.inputfile); defer aoc.talloc.free(inp); try aoc.assertEq(@as(i64, 8), part1(aoc.talloc, test0)); try aoc.assertEq(@as(i64, 4), part2(aoc.talloc, test0)); try aoc.assertEq(@as(i64, 35), part1(aoc.talloc, test1)); try aoc.assertEq(@as(i64, 8), part2(aoc.talloc, test1)); try aoc.assertEq(@as(i64, 220), part1(aoc.talloc, test2)); try aoc.assertEq(@as(i64, 19208), part2(aoc.talloc, test2)); try aoc.assertEq(@as(i64, 1920), part1(aoc.talloc, inp)); try aoc.assertEq(@as(i64, 1511207993344), part2(aoc.talloc, inp)); } fn part1(alloc: std.mem.Allocator, in: []const i64) i64 { var nums: []i64 = alloc.dupe(i64, in) catch unreachable; defer alloc.free(nums); std.sort.sort(i64, nums, {}, aoc.i64LessThan); var cj: i64 = 0; var c = std.AutoHashMap(i64, i64).init(alloc); defer c.deinit(); for (nums) |j| { const d = j - cj; c.put(d, (c.get(d) orelse 0) + 1) catch unreachable; cj = j; } if (cj - nums[nums.len - 1] == 1) { return (1 + c.get(1).?) * c.get(3).?; } else { return c.get(1).? * (c.get(3).? + 1); } } fn count(cj: i64, tj: i64, ni: usize, nums: []i64, state: *std.AutoHashMap(usize, i64)) i64 { const k: usize = std.math.absCast(cj) + ni * nums.len; if (state.contains(k)) { return state.get(k).?; } if (ni >= nums.len) { return 1; } var c: i64 = 0; var i: usize = 0; while (ni + i < nums.len and i < 3) : (i += 1) { var j = nums[ni + i]; if ((j - cj) <= 3) { c += count(j, tj, ni + i + 1, nums, state); } } state.put(k, c) catch unreachable; return c; } fn part2(alloc: std.mem.Allocator, in: []const i64) i64 { var nums: []i64 = alloc.dupe(i64, in) catch unreachable; defer alloc.free(nums); std.sort.sort(i64, nums, {}, aoc.i64LessThan); var state = std.AutoHashMap(usize, i64).init(alloc); defer state.deinit(); return count(0, in[in.len - 1], 0, nums, &state); } fn day10(inp: []const u8, bench: bool) anyerror!void { var nums = try aoc.Ints(aoc.halloc, i64, inp); defer aoc.halloc.free(nums); var p1 = part1(aoc.halloc, nums); var p2 = part2(aoc.halloc, nums); if (!bench) { try aoc.print("Part 1: {}\nPart 2: {}\n", .{ p1, p2 }); } } pub fn main() anyerror!void { try aoc.benchme(aoc.input(), day10); }
2020/10/aoc.zig
const std = @import("std"); const assert = std.debug.assert; const tools = @import("tools"); const Tile = struct { dist: u16, tag: u8, fn tile2char(t: @This()) u8 { if (t.tag == 0) { return '.'; } else if (t.tag == 1) { return '#'; } else if (t.dist == 0) { return 'A' + (t.tag - 2); } else { return 'a' + (t.tag - 2); } } }; const Vec2 = tools.Vec2; const Map = tools.Map(Tile, 2000, 2000, true); fn abs(x: i32) u32 { return if (x >= 0) @intCast(u32, x) else @intCast(u32, -x); } pub fn run(input: []const u8, allocator: std.mem.Allocator) ![2][]const u8 { const map = try allocator.create(Map); defer allocator.destroy(map); map.default_tile = Tile{ .tag = 0, .dist = 0 }; map.bbox = tools.BBox.empty; map.fill(Tile{ .tag = 0, .dist = 0 }, null); const coordList = try allocator.alloc(Vec2, 1000); defer allocator.free(coordList); var coordCount: usize = 0; { var tag: u8 = 2; var it = std.mem.tokenize(u8, input, "\n\r"); while (it.next()) |line| { const fields = tools.match_pattern("{}, {}", line) orelse unreachable; const pos = Vec2{ .x = @intCast(i32, fields[0].imm), .y = @intCast(i32, fields[1].imm) }; coordList[coordCount] = pos; coordCount += 1; map.set(pos, Tile{ .tag = tag, .dist = 0 }); tag += 1; } map.bbox.min = map.bbox.min.add(Vec2{ .x = -2, .y = -2 }); map.bbox.max = map.bbox.max.add(Vec2{ .x = 2, .y = 2 }); //var buf: [50000]u8 = undefined; //std.debug.print("amp=\n{}\n", .{map.printToBuf(null, null, Tile.tile2char, &buf)}); } // update distance map { var changed = true; while (changed) { changed = false; var it = map.iter(null); while (it.nextEx()) |tn| { var d: u16 = 65534; var tag: u8 = 0; for (tn.neib) |neib| { if (neib) |n| { if (n.tag != 0) { if (n.dist + 1 < d) { d = n.dist + 1; tag = n.tag; } else if (n.dist + 1 == d and tag != n.tag) { tag = 1; // equidistant } } } } if (tag != 0 and tn.t.dist > d or (tn.t.dist == d and tn.t.tag != tag) or tn.t.tag == 0) { tn.t.tag = tag; tn.t.dist = d; changed = true; } } } //var buf: [50000]u8 = undefined; //std.debug.print("amp=\n{}\n", .{map.printToBuf(null, null, Tile.tile2char, &buf)}); } // part1 //var arena = std.heap.ArenaAllocator.init(std.heap.page_allocator); //defer arena.deinit(); const ans1 = ans: { // bon je pense que tout ce qui est sur le bord exterieur va se propager à l'infini (en ligne droite ça sera toujours plus court) var infiniteTags = [_]bool{false} ** 100; { var x = map.bbox.min.x; while (x <= map.bbox.max.x) : (x += 1) { infiniteTags[map.at(Vec2{ .x = x, .y = map.bbox.min.y }).tag] = true; infiniteTags[map.at(Vec2{ .x = x, .y = map.bbox.max.y }).tag] = true; } var y = map.bbox.min.y; while (y <= map.bbox.max.y) : (y += 1) { infiniteTags[map.at(Vec2{ .x = map.bbox.min.x, .y = y }).tag] = true; infiniteTags[map.at(Vec2{ .x = map.bbox.max.x, .y = y }).tag] = true; } } var counts = [_]u32{0} ** 100; var bestCount: u32 = 0; var bestTag: u8 = 0; var it = map.iter(null); while (it.next()) |t| { if (t.tag > 1 and !infiniteTags[t.tag]) { counts[t.tag] += 1; if (counts[t.tag] > bestCount) { bestCount = counts[t.tag]; bestTag = t.tag; } } } break :ans bestCount; }; // part2 const ans2 = ans: { const coords = coordList[0..coordCount]; var count: u32 = 0; var y = map.bbox.min.y; while (y <= map.bbox.max.y) : (y += 1) { var x = map.bbox.min.x; while (x <= map.bbox.max.x) : (x += 1) { var d: u32 = 0; for (coords) |c| { d += abs(c.x - x) + abs(c.y - y); } if (d < 10000) count += 1; } } break :ans count; }; return [_][]const u8{ try std.fmt.allocPrint(allocator, "{}", .{ans1}), try std.fmt.allocPrint(allocator, "{}", .{ans2}), }; } pub const main = tools.defaultMain("2018/input_day06.txt", run);
2018/day06.zig
const std = @import("../../std.zig"); const mem = std.mem; const debug = std.debug; const Vector = std.meta.Vector; const BlockVec = Vector(2, u64); /// A single AES block. pub const Block = struct { pub const block_size: usize = 16; /// Internal representation of a block. repr: BlockVec, /// Convert a byte sequence into an internal representation. pub inline fn fromBytes(bytes: *const [16]u8) Block { const repr = mem.bytesToValue(BlockVec, bytes); return Block{ .repr = repr }; } /// Convert the internal representation of a block into a byte sequence. pub inline fn toBytes(block: Block) [16]u8 { return mem.toBytes(block.repr); } /// XOR the block with a byte sequence. pub inline fn xorBytes(block: Block, bytes: *const [16]u8) [16]u8 { const x = block.repr ^ fromBytes(bytes).repr; return mem.toBytes(x); } /// Encrypt a block with a round key. pub inline fn encrypt(block: Block, round_key: Block) Block { return Block{ .repr = asm ( \\ vaesenc %[rk], %[in], %[out] : [out] "=x" (-> BlockVec) : [in] "x" (block.repr), [rk] "x" (round_key.repr) ), }; } /// Encrypt a block with the last round key. pub inline fn encryptLast(block: Block, round_key: Block) Block { return Block{ .repr = asm ( \\ vaesenclast %[rk], %[in], %[out] : [out] "=x" (-> BlockVec) : [in] "x" (block.repr), [rk] "x" (round_key.repr) ), }; } /// Decrypt a block with a round key. pub inline fn decrypt(block: Block, inv_round_key: Block) Block { return Block{ .repr = asm ( \\ vaesdec %[rk], %[in], %[out] : [out] "=x" (-> BlockVec) : [in] "x" (block.repr), [rk] "x" (inv_round_key.repr) ), }; } /// Decrypt a block with the last round key. pub inline fn decryptLast(block: Block, inv_round_key: Block) Block { return Block{ .repr = asm ( \\ vaesdeclast %[rk], %[in], %[out] : [out] "=x" (-> BlockVec) : [in] "x" (block.repr), [rk] "x" (inv_round_key.repr) ), }; } /// XOR the content of two blocks. pub inline fn xor(block1: Block, block2: Block) Block { return Block{ .repr = block1.repr ^ block2.repr }; } /// Perform operations on multiple blocks in parallel. pub const parallel = struct { /// The recommended number of AES encryption/decryption to perform in parallel for the chosen implementation. pub const optimal_parallel_blocks = 8; /// Encrypt multiple blocks in parallel, each their own round key. pub inline fn encryptParallel(comptime count: usize, blocks: [count]Block, round_keys: [count]Block) [count]Block { comptime var i = 0; var out: [count]Block = undefined; inline while (i < count) : (i += 1) { out[i] = blocks[i].encrypt(round_keys[i]); } return out; } /// Decrypt multiple blocks in parallel, each their own round key. pub inline fn decryptParallel(comptime count: usize, blocks: [count]Block, round_keys: [count]Block) [count]Block { comptime var i = 0; var out: [count]Block = undefined; inline while (i < count) : (i += 1) { out[i] = blocks[i].decrypt(round_keys[i]); } return out; } /// Encrypt multple blocks in parallel with the same round key. pub inline fn encryptWide(comptime count: usize, blocks: [count]Block, round_key: Block) [count]Block { comptime var i = 0; var out: [count]Block = undefined; inline while (i < count) : (i += 1) { out[i] = blocks[i].encrypt(round_key); } return out; } /// Decrypt multple blocks in parallel with the same round key. pub inline fn decryptWide(comptime count: usize, blocks: [count]Block, round_key: Block) [count]Block { comptime var i = 0; var out: [count]Block = undefined; inline while (i < count) : (i += 1) { out[i] = blocks[i].decrypt(round_key); } return out; } /// Encrypt multple blocks in parallel with the same last round key. pub inline fn encryptLastWide(comptime count: usize, blocks: [count]Block, round_key: Block) [count]Block { comptime var i = 0; var out: [count]Block = undefined; inline while (i < count) : (i += 1) { out[i] = blocks[i].encryptLast(round_key); } return out; } /// Decrypt multple blocks in parallel with the same last round key. pub inline fn decryptLastWide(comptime count: usize, blocks: [count]Block, round_key: Block) [count]Block { comptime var i = 0; var out: [count]Block = undefined; inline while (i < count) : (i += 1) { out[i] = blocks[i].decryptLast(round_key); } return out; } }; }; fn KeySchedule(comptime AES: type) type { std.debug.assert(AES.rounds == 10 or AES.rounds == 14); const rounds = AES.rounds; return struct { const Self = @This(); round_keys: [rounds + 1]Block, fn drc(comptime second: bool, comptime rc: u8, t: BlockVec, tx: BlockVec) BlockVec { var s: BlockVec = undefined; var ts: BlockVec = undefined; return asm ( \\ vaeskeygenassist %[rc], %[t], %[s] \\ vpslldq $4, %[tx], %[ts] \\ vpxor %[ts], %[tx], %[r] \\ vpslldq $8, %[r], %[ts] \\ vpxor %[ts], %[r], %[r] \\ vpshufd %[mask], %[s], %[ts] \\ vpxor %[ts], %[r], %[r] : [r] "=&x" (-> BlockVec), [s] "=&x" (s), [ts] "=&x" (ts) : [rc] "n" (rc), [t] "x" (t), [tx] "x" (tx), [mask] "n" (@as(u8, if (second) 0xaa else 0xff)) ); } fn expand128(t1: *Block) Self { var round_keys: [11]Block = undefined; const rcs = [_]u8{ 1, 2, 4, 8, 16, 32, 64, 128, 27, 54 }; inline for (rcs) |rc, round| { round_keys[round] = t1.*; t1.repr = drc(false, rc, t1.repr, t1.repr); } round_keys[rcs.len] = t1.*; return Self{ .round_keys = round_keys }; } fn expand256(t1: *Block, t2: *Block) Self { var round_keys: [15]Block = undefined; const rcs = [_]u8{ 1, 2, 4, 8, 16, 32 }; round_keys[0] = t1.*; inline for (rcs) |rc, round| { round_keys[round * 2 + 1] = t2.*; t1.repr = drc(false, rc, t2.repr, t1.repr); round_keys[round * 2 + 2] = t1.*; t2.repr = drc(true, rc, t1.repr, t2.repr); } round_keys[rcs.len * 2 + 1] = t2.*; t1.repr = drc(false, 64, t2.repr, t1.repr); round_keys[rcs.len * 2 + 2] = t1.*; return Self{ .round_keys = round_keys }; } /// Invert the key schedule. pub fn invert(key_schedule: Self) Self { const round_keys = &key_schedule.round_keys; var inv_round_keys: [rounds + 1]Block = undefined; inv_round_keys[0] = round_keys[rounds]; comptime var i = 1; inline while (i < rounds) : (i += 1) { inv_round_keys[i] = Block{ .repr = asm ( \\ vaesimc %[rk], %[inv_rk] : [inv_rk] "=x" (-> BlockVec) : [rk] "x" (round_keys[rounds - i].repr) ), }; } inv_round_keys[rounds] = round_keys[0]; return Self{ .round_keys = inv_round_keys }; } }; } /// A context to perform encryption using the standard AES key schedule. pub fn AESEncryptCtx(comptime AES: type) type { std.debug.assert(AES.key_bits == 128 or AES.key_bits == 256); const rounds = AES.rounds; return struct { const Self = @This(); pub const block = AES.block; pub const block_size = block.block_size; key_schedule: KeySchedule(AES), /// Create a new encryption context with the given key. pub fn init(key: [AES.key_bits / 8]u8) Self { var t1 = Block.fromBytes(key[0..16]); const key_schedule = if (AES.key_bits == 128) ks: { break :ks KeySchedule(AES).expand128(&t1); } else ks: { var t2 = Block.fromBytes(key[16..32]); break :ks KeySchedule(AES).expand256(&t1, &t2); }; return Self{ .key_schedule = key_schedule, }; } /// Encrypt a single block. pub fn encrypt(ctx: Self, dst: *[16]u8, src: *const [16]u8) void { const round_keys = ctx.key_schedule.round_keys; var t = Block.fromBytes(src).xor(round_keys[0]); comptime var i = 1; inline while (i < rounds) : (i += 1) { t = t.encrypt(round_keys[i]); } t = t.encryptLast(round_keys[rounds]); dst.* = t.toBytes(); } /// Encrypt+XOR a single block. pub fn xor(ctx: Self, dst: *[16]u8, src: *const [16]u8, counter: [16]u8) void { const round_keys = ctx.key_schedule.round_keys; var t = Block.fromBytes(&counter).xor(round_keys[0]); comptime var i = 1; inline while (i < rounds) : (i += 1) { t = t.encrypt(round_keys[i]); } t = t.encryptLast(round_keys[rounds]); dst.* = t.xorBytes(src); } /// Encrypt multiple blocks, possibly leveraging parallelization. pub fn encryptWide(ctx: Self, comptime count: usize, dst: *[16 * count]u8, src: *const [16 * count]u8) void { const round_keys = ctx.key_schedule.round_keys; var ts: [count]Block = undefined; comptime var j = 0; inline while (j < count) : (j += 1) { ts[j] = Block.fromBytes(src[j * 16 .. j * 16 + 16][0..16]).xor(round_keys[0]); } comptime var i = 1; inline while (i < rounds) : (i += 1) { ts = Block.parallel.encryptWide(count, ts, round_keys[i]); } i = 1; inline while (i < count) : (i += 1) { ts = Block.parallel.encryptLastWide(count, ts, round_keys[i]); } j = 0; inline while (j < count) : (j += 1) { dst[16 * j .. 16 * j + 16].* = ts[j].toBytes(); } } /// Encrypt+XOR multiple blocks, possibly leveraging parallelization. pub fn xorWide(ctx: Self, comptime count: usize, dst: *[16 * count]u8, src: *const [16 * count]u8, counters: [16 * count]u8) void { const round_keys = ctx.key_schedule.round_keys; var ts: [count]Block = undefined; comptime var j = 0; inline while (j < count) : (j += 1) { ts[j] = Block.fromBytes(counters[j * 16 .. j * 16 + 16][0..16]).xor(round_keys[0]); } comptime var i = 1; inline while (i < rounds) : (i += 1) { ts = Block.parallel.encryptWide(count, ts, round_keys[i]); } ts = Block.parallel.encryptLastWide(count, ts, round_keys[i]); j = 0; inline while (j < count) : (j += 1) { dst[16 * j .. 16 * j + 16].* = ts[j].xorBytes(src[16 * j .. 16 * j + 16]); } } }; } /// A context to perform decryption using the standard AES key schedule. pub fn AESDecryptCtx(comptime AES: type) type { std.debug.assert(AES.key_bits == 128 or AES.key_bits == 256); const rounds = AES.rounds; return struct { const Self = @This(); pub const block = AES.block; pub const block_size = block.block_size; key_schedule: KeySchedule(AES), /// Create a decryption context from an existing encryption context. pub fn initFromEnc(ctx: AESEncryptCtx(AES)) Self { return Self{ .key_schedule = ctx.key_schedule.invert(), }; } /// Create a new decryption context with the given key. pub fn init(key: [AES.key_bits / 8]u8) Self { const enc_ctx = AESEncryptCtx(AES).init(key); return initFromEnc(enc_ctx); } /// Decrypt a single block. pub fn decrypt(ctx: Self, dst: *[16]u8, src: *const [16]u8) void { const inv_round_keys = ctx.key_schedule.round_keys; var t = Block.fromBytes(src).xor(inv_round_keys[0]); comptime var i = 1; inline while (i < rounds) : (i += 1) { t = t.decrypt(inv_round_keys[i]); } t = t.decryptLast(inv_round_keys[rounds]); dst.* = t.toBytes(); } /// Decrypt multiple blocks, possibly leveraging parallelization. pub fn decryptWide(ctx: Self, comptime count: usize, dst: *[16 * count]u8, src: *const [16 * count]u8) void { const inv_round_keys = ctx.key_schedule.round_keys; var ts: [count]Block = undefined; comptime var j = 0; inline while (j < count) : (j += 1) { ts[j] = Block.fromBytes(src[j * 16 .. j * 16 + 16][0..16]).xor(inv_round_keys[0]); } comptime var i = 1; inline while (i < rounds) : (i += 1) { ts = Block.parallel.decryptWide(count, ts, inv_round_keys[i]); } i = 1; inline while (i < count) : (i += 1) { ts = Block.parallel.decryptLastWide(count, ts, inv_round_keys[i]); } j = 0; inline while (j < count) : (j += 1) { dst[16 * j .. 16 * j + 16].* = ts[j].toBytes(); } } }; } /// AES-128 with the standard key schedule. pub const AES128 = struct { pub const key_bits: usize = 128; pub const rounds = ((key_bits - 64) / 32 + 8); pub const block = Block; /// Create a new context for encryption. pub fn initEnc(key: [key_bits / 8]u8) AESEncryptCtx(AES128) { return AESEncryptCtx(AES128).init(key); } /// Create a new context for decryption. pub fn initDec(key: [key_bits / 8]u8) AESDecryptCtx(AES128) { return AESDecryptCtx(AES128).init(key); } }; /// AES-256 with the standard key schedule. pub const AES256 = struct { pub const key_bits: usize = 256; pub const rounds = ((key_bits - 64) / 32 + 8); pub const block = Block; /// Create a new context for encryption. pub fn initEnc(key: [key_bits / 8]u8) AESEncryptCtx(AES256) { return AESEncryptCtx(AES256).init(key); } /// Create a new context for decryption. pub fn initDec(key: [key_bits / 8]u8) AESDecryptCtx(AES256) { return AESDecryptCtx(AES256).init(key); } };
lib/std/crypto/aes/aesni.zig
const std = @import("std"); const mem = std.mem; const field_size = [32]u8{ 0xed, 0xd3, 0xf5, 0x5c, 0x1a, 0x63, 0x12, 0x58, 0xd6, 0x9c, 0xf7, 0xa2, 0xde, 0xf9, 0xde, 0x14, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x10, // 2^252+27742317777372353535851937790883648493 }; const ScalarExpanded = struct { limbs: [64]i64 = [_]i64{0} ** 64, fn fromBytes(s: [32]u8) ScalarExpanded { var limbs: [64]i64 = undefined; for (s) |x, idx| { limbs[idx] = @as(i64, x); } mem.set(i64, limbs[32..], 0); return .{ .limbs = limbs }; } fn fromBytes64(s: [64]u8) ScalarExpanded { var limbs: [64]i64 = undefined; for (s) |x, idx| { limbs[idx] = @as(i64, x); } return .{ .limbs = limbs }; } fn reduce(e: *ScalarExpanded) void { const limbs = &e.limbs; var carry: i64 = undefined; var i: usize = 63; while (i >= 32) : (i -= 1) { carry = 0; const k = i - 12; const xi = limbs[i]; var j = i - 32; while (j < k) : (j += 1) { const xj = limbs[j] + carry - 16 * xi * @as(i64, field_size[j - (i - 32)]); carry = (xj + 128) >> 8; limbs[j] = xj - carry * 256; } limbs[k] += carry; limbs[i] = 0; } carry = 0; comptime var j: usize = 0; inline while (j < 32) : (j += 1) { const xi = limbs[j] + carry - (limbs[31] >> 4) * @as(i64, field_size[j]); carry = xi >> 8; limbs[j] = xi & 255; } j = 0; inline while (j < 32) : (j += 1) { limbs[j] -= carry * @as(i64, field_size[j]); } j = 0; inline while (j < 32) : (j += 1) { limbs[j + 1] += limbs[j] >> 8; } } fn toBytes(e: *ScalarExpanded) [32]u8 { e.reduce(); var r: [32]u8 = undefined; var i: usize = 0; while (i < 32) : (i += 1) { r[i] = @intCast(u8, e.limbs[i]); } return r; } fn add(a: ScalarExpanded, b: ScalarExpanded) ScalarExpanded { var r = ScalarExpanded{}; comptime var i = 0; inline while (i < 64) : (i += 1) { r.limbs[i] = a.limbs[i] + b.limbs[i]; } return r; } fn mul(a: ScalarExpanded, b: ScalarExpanded) ScalarExpanded { var r = ScalarExpanded{}; var i: usize = 0; while (i < 32) : (i += 1) { const ai = a.limbs[i]; comptime var j = 0; inline while (j < 32) : (j += 1) { r.limbs[i + j] += ai * b.limbs[j]; } } r.reduce(); return r; } fn sq(a: ScalarExpanded) ScalarExpanded { return a.mul(a); } fn mulAdd(a: ScalarExpanded, b: ScalarExpanded, c: ScalarExpanded) ScalarExpanded { var r: ScalarExpanded = .{ .limbs = c.limbs }; var i: usize = 0; while (i < 32) : (i += 1) { const ai = a.limbs[i]; comptime var j = 0; inline while (j < 32) : (j += 1) { r.limbs[i + j] += ai * b.limbs[j]; } } r.reduce(); return r; } }; /// Reject a scalar whose encoding is not canonical. pub fn rejectNonCanonical(s: [32]u8) !void { var c: u8 = 0; var n: u8 = 1; var i: usize = 31; while (true) : (i -= 1) { const xs = @as(u16, s[i]); const xfield_size = @as(u16, field_size[i]); c |= @intCast(u8, ((xs -% xfield_size) >> 8) & n); n &= @intCast(u8, ((xs ^ xfield_size) -% 1) >> 8); if (i == 0) break; } if (c == 0) { return error.NonCanonical; } } /// Reduce a scalar to the field size. pub fn reduce(s: [32]u8) [32]u8 { return ScalarExpanded.fromBytes(s).toBytes(); } /// Reduce a 64-bytes scalar to the field size. pub fn reduce64(s: [64]u8) [32]u8 { return ScalarExpanded.fromBytes64(s).toBytes(); } /// Perform the X25519 "clamping" operation. /// The scalar is then guaranteed to be a multiple of the cofactor. pub inline fn clamp(s: *[32]u8) void { s[0] &= 248; s[31] = (s[31] & 127) | 64; } /// Return a*b+c (mod L) pub fn mulAdd(a: [32]u8, b: [32]u8, c: [32]u8) [32]u8 { return ScalarExpanded.fromBytes(a).mulAdd(ScalarExpanded.fromBytes(b), ScalarExpanded.fromBytes(c)).toBytes(); } test "scalar25519" { const bytes: [32]u8 = .{ 1, 2, 3, 4, 5, 6, 7, 8, 1, 2, 3, 4, 5, 6, 7, 8, 1, 2, 3, 4, 5, 6, 7, 8, 1, 2, 3, 4, 5, 6, 7, 255 }; var x = ScalarExpanded.fromBytes(bytes); var y = x.toBytes(); try rejectNonCanonical(y); var buf: [128]u8 = undefined; std.testing.expectEqualStrings(try std.fmt.bufPrint(&buf, "{X}", .{y}), "1E979B917937F3DE71D18077F961F6CEFF01030405060708010203040506070F"); const reduced = reduce(field_size); std.testing.expectEqualStrings(try std.fmt.bufPrint(&buf, "{X}", .{reduced}), "0000000000000000000000000000000000000000000000000000000000000000"); } test "non-canonical scalar25519" { const too_targe: [32]u8 = .{ 0xed, 0xd3, 0xf5, 0x5c, 0x1a, 0x63, 0x12, 0x58, 0xd6, 0x9c, 0xf7, 0xa2, 0xde, 0xf9, 0xde, 0x14, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x10 }; std.testing.expectError(error.NonCanonical, rejectNonCanonical(too_targe)); } test "mulAdd overflow check" { const a: [32]u8 = [_]u8{0xff} ** 32; const b: [32]u8 = [_]u8{0xff} ** 32; const c: [32]u8 = [_]u8{0xff} ** 32; const x = mulAdd(a, b, c); var buf: [128]u8 = undefined; std.testing.expectEqualStrings(try std.fmt.bufPrint(&buf, "{X}", .{x}), "D14DF91389432C25AD60FF9791B9FD1D67BEF517D273ECCE3D9A307C1B419903"); }
lib/std/crypto/25519/scalar.zig
const peripherals = @import("peripherals.zig"); const AddressRange = peripherals.AddressRange; const std = @import("std"); /// A structure containin info about the BCM2835 chip /// see this website which does a brilliant job of explaining everything /// https://www.pieter-jan.com/node/15 /// The most important thing is to look at the BCM2835 peripheral manual (pi1 / p2) /// and then see in section 1.2.3 how the register addresses in the manual relate with /// the physical memory. Then see the Gpio section for an explanation of how to /// operate the Gpio pins using the registers. /// The primary source for all of this is the Broadcom BCM2835 ARM Peripherals Manual pub const BoardInfo = struct { /// the *physical* address space of all peripherals pub const peripheral_addresses: AddressRange = .{ .start = 0x20000000, .len = 0xFFFFFF }; // address space of the GPIO registers pub const gpio_registers = .{ .start = peripheral_addresses.start + 0x200000, .len = 0xB4 }; // /// physical address space of the gpio registers GPFSEL{n} (function select) pub const gpfsel_registers: AddressRange = .{ .start = peripheral_addresses.start + 0x200000, .len = 6 * 4 }; /// physical address space of the gpio registers GPSET{n} (output setting) pub const gpset_registers: AddressRange = .{ .start = gpfsel_registers.start + 0x1C, .len = 2 * 4 }; /// physical address space of the gpio registers GPCLR{n} (clearing pin output) pub const gpclr_registers: AddressRange = .{ .start = gpfsel_registers.start + 0x28, .len = 2 * 4 }; /// physical address space of the gpio registers GPLEV{n} (reading pin levels) pub const gplev_registers: AddressRange = .{ .start = gpfsel_registers.start + 0x34, .len = 2 * 4 }; /// phys address space of the gpio register GPPUD (pull up / pull down) pub const gppud_register: AddressRange = .{ .start = gpfsel_registers.start + 0x94, .len = 1 * 4 }; /// phys address space of the gpio register GPPUDCLK{n} (pull up / down clocks) pub const gppudclk_registers: AddressRange = .{ .start = gpfsel_registers.start + 0x98, .len = 2 * 4 }; /// the number of GPIO pins. Pin indices start at 0. pub const NUM_GPIO_PINS = 53; }; pub const Bcm2385GpioMemoryMapper = struct { const Self: type = @This(); /// the GpioMemMapper interface memory_mapper: peripherals.GpioMemMapper, /// the raw bytes representing the memory mapping devgpiomem: []align(std.mem.page_size) u8, pub fn init() !Self { const devgpiomem = try std.fs.openFileAbsolute("/dev/gpiomem", std.fs.File.OpenFlags{ .read = true, .write = true }); defer devgpiomem.close(); return Self{ .devgpiomem = try std.os.mmap(null, BoardInfo.gpio_registers.len, std.os.PROT.READ | std.os.PROT.WRITE, std.os.MAP.SHARED, devgpiomem.handle, 0), .memory_mapper = .{ .map_fn = Self.memoryMap } }; } /// unmap the mapped memory pub fn deinit(self: Self) void { std.os.munmap(self.devgpiomem); } pub fn memoryMap(interface: *peripherals.GpioMemMapper) !peripherals.GpioRegisterMemory { var self = @fieldParentPtr(Self, "memory_mapper", interface); return std.mem.bytesAsSlice(u32, self.devgpiomem); } };
src/bcm2835.zig
const std = @import("std"); const debug = std.debug; const mem = std.mem; const grid_serial_number: u32 = 5791; const grid_side_len = 300; pub fn main() void { const result1 = regionOfHighestTotalPower(grid_serial_number); debug.assert(V2.eq(V2.init(20, 68), result1)); debug.warn("11-1: {}\n", result1); const result2 = regionOfHighestTotalPowerOfAnySize(grid_serial_number); debug.assert(V2.eq(V2.init(231, 273), result2.region)); debug.assert(16 == result2.square_side_len); debug.warn("11-2: {},{}\n", result2.region, result2.square_side_len); } fn regionOfHighestTotalPowerOfAnySize(gsn: u32) RegionInfo { var grid = []i32{0} ** (grid_side_len * grid_side_len); for (grid) |*cell, i| { var coord = point_from_index(i, grid_side_len); // grid is 1 based, though array is 0 based cell.* = getFuelCellPower(coord.x + 1, coord.y + 1, gsn); } // https://en.wikipedia.org/wiki/Summed-area_table var sat = []i32{0} ** grid.len; for (grid) |cell, i| { const c = point_from_index(i, grid_side_len); sat[i] = grid[index_from_point(c.x, c.y, grid_side_len)]; if (c.x > 0) { sat[i] += sat[index_from_point(c.x - 1, c.y, grid_side_len)]; } if (c.y > 0) { sat[i] += sat[index_from_point(c.x, c.y - 1, grid_side_len)]; } if (c.x > 0 and c.y > 0) { sat[i] -= sat[index_from_point(c.x - 1, c.y - 1, grid_side_len)]; } } var highest_highest_power: i32 = grid[0]; var highest_highest_power_region = V2.init(0, 0); var highest_square_side_len: u32 = 1; var square_side_len: u32 = 1; while (square_side_len <= grid_side_len) : (square_side_len += 1) { var highest_power: i32 = @minValue(i32); var highest_power_region = V2.init(1, 1); for (grid) |cell, i| { const array_coord = point_from_index(i, grid_side_len); // cells start at (1, 1) const cell_coord = V2.init(array_coord.x + 1, array_coord.y + 1); const search_threshold = (grid_side_len - square_side_len) + 1; if (cell_coord.x > search_threshold or cell_coord.y > search_threshold) { continue; } const ssl = square_side_len - 1; // +----------------------+ // | | | | // | A| B| | // |------+-----------+ | // | | | | // | | | | // | | | | // | C| D| | // |------+-----------+ | // | | // +----------------------+ // sum = D - B - C + A // D var sum: i32 = sat[index_from_point(array_coord.x + ssl, array_coord.y + ssl, grid_side_len)]; if (array_coord.x > 0) { // - C sum -= sat[index_from_point(array_coord.x - 1, array_coord.y + ssl, grid_side_len)]; } if (array_coord.y > 0) { // - B sum -= sat[index_from_point(array_coord.x + ssl, array_coord.y - 1, grid_side_len)]; } if (array_coord.x > 0 and array_coord.y > 0) { // + A sum += sat[index_from_point(array_coord.x - 1, array_coord.y - 1, grid_side_len)]; } if (sum > highest_power) { highest_power = sum; highest_power_region = cell_coord; } } if (highest_power > highest_highest_power) { highest_highest_power = highest_power; highest_highest_power_region = highest_power_region; highest_square_side_len = square_side_len; } } return RegionInfo { .region = highest_highest_power_region, .square_side_len = highest_square_side_len, }; } const RegionInfo = struct { region: V2, square_side_len: u32, }; test "region of highest total power of any size" { const r18 = regionOfHighestTotalPowerOfAnySize(18); debug.assert(V2.eq(V2.init(90, 269), r18.region)); debug.assert(16 == r18.square_side_len); const r42 = regionOfHighestTotalPowerOfAnySize(42); debug.assert(V2.eq(V2.init(232, 251), r42.region)); debug.assert(12 == r42.square_side_len); } fn regionOfHighestTotalPower(gsn: u32) V2{ var grid = []i32{0} ** (grid_side_len * grid_side_len); for (grid) |*cell, i| { var coord = point_from_index(i, grid_side_len); // grid is 1 based, though array is 0 based coord.x += 1; coord.y += 1; cell.* = getFuelCellPower(coord.x, coord.y, gsn); } var square_side_len: u32 = 3; var highest_power: i32 = 0; var highest_power_region = V2.init(1, 1); for (grid) |cell, i| { const array_coord = point_from_index(i, grid_side_len); const cell_coord = V2.init(array_coord.x + 1, array_coord.y + 1); const search_threshold = grid_side_len - square_side_len; if (cell_coord.x >= search_threshold or cell_coord.y >= search_threshold) { continue; } var sum: i32 = 0; var square_x: u32 = 0; while (square_x < square_side_len) : (square_x += 1) { var square_y: u32 = 0; while (square_y < square_side_len) : (square_y += 1) { sum += grid[index_from_point(array_coord.x + square_x, array_coord.y + square_y, grid_side_len)]; } } if (sum > highest_power) { highest_power = sum; highest_power_region = cell_coord; } } return highest_power_region; } test "region of highest total power" { debug.assert(V2.eq(V2.init(33, 45), regionOfHighestTotalPower(18))); debug.assert(V2.eq(V2.init(21, 61), regionOfHighestTotalPower(42))); } fn getFuelCellPower(cell_x: u32, cell_y: u32, gsn: u32) i32 { const rack_id = cell_x + 10; var power_level: i32 = @intCast(i32, rack_id * cell_y); power_level += @intCast(i32, gsn); power_level *= @intCast(i32, rack_id); power_level = hundredsDigit(power_level); power_level -= 5; return power_level; } test "get fuel cell power" { debug.assert(4 == getFuelCellPower(3, 5, 8)); debug.assert(-5 == getFuelCellPower(122, 79, 57)); debug.assert(0 == getFuelCellPower(217, 196, 39)); debug.assert(4 == getFuelCellPower(101, 153, 71)); } inline fn hundredsDigit(n: i32) i32 { return @mod(@divTrunc(n, 100), 10); } test "hundreds digit" { debug.assert(0 == hundredsDigit(0)); debug.assert(0 == hundredsDigit(10)); debug.assert(1 == hundredsDigit(100)); debug.assert(0 == hundredsDigit(1000)); debug.assert(3 == hundredsDigit(12345)); } fn point_from_index(i: usize, stride: usize) V2 { var x: u32 = @intCast(u32, i % stride); var y: u32 = @intCast(u32, @divTrunc(i, stride)); return V2.init(x, y); } test "point from index" { debug.assert(V2.eq(V2.init(0, 0), point_from_index(0, 5))); debug.assert(V2.eq(V2.init(1, 1), point_from_index(6, 5))); debug.assert(V2.eq(V2.init(2, 1), point_from_index(7, 5))); debug.assert(V2.eq(V2.init(4, 2), point_from_index(14, 5))); debug.assert(V2.eq(V2.init(4, 4), point_from_index(24, 5))); } inline fn index_from_point(x: u32, y: u32, stride: usize) usize { return y * stride + x; } test "index from point" { debug.assert(0 == index_from_point(0, 0, 5)); debug.assert(6 == index_from_point(1, 1, 5)); debug.assert(7 == index_from_point(2, 1, 5)); debug.assert(14 == index_from_point(4, 2, 5)); debug.assert(24 == index_from_point(4, 4, 5)); } const V2 = struct { x: u32, y: u32, pub fn init(x: u32, y: u32) V2 { return V2 { .x = x, .y = y, }; } pub fn eq(vec1: V2, vec2: V2) bool { return vec1.x == vec2.x and vec1.y == vec2.y; } };
2018/day_11.zig
const builtin = @import("builtin"); const std = @import("../std.zig"); const math = std.math; const expo2 = @import("expo2.zig").expo2; const expect = std.testing.expect; const maxInt = std.math.maxInt; /// Returns the hyperbolic cosine of x. /// /// Special Cases: /// - cosh(+-0) = 1 /// - cosh(+-inf) = +inf /// - cosh(nan) = nan pub fn cosh(x: var) @typeOf(x) { const T = @typeOf(x); return switch (T) { f32 => cosh32(x), f64 => cosh64(x), else => @compileError("cosh not implemented for " ++ @typeName(T)), }; } // cosh(x) = (exp(x) + 1 / exp(x)) / 2 // = 1 + 0.5 * (exp(x) - 1) * (exp(x) - 1) / exp(x) // = 1 + (x * x) / 2 + o(x^4) fn cosh32(x: f32) f32 { const u = @bitCast(u32, x); const ux = u & 0x7FFFFFFF; const ax = @bitCast(f32, ux); // |x| < log(2) if (ux < 0x3F317217) { if (ux < 0x3F800000 - (12 << 23)) { math.raiseOverflow(); return 1.0; } const t = math.expm1(ax); return 1 + t * t / (2 * (1 + t)); } // |x| < log(FLT_MAX) if (ux < 0x42B17217) { const t = math.exp(ax); return 0.5 * (t + 1 / t); } // |x| > log(FLT_MAX) or nan return expo2(ax); } fn cosh64(x: f64) f64 { const u = @bitCast(u64, x); const w = @intCast(u32, u >> 32); const ax = @bitCast(f64, u & (maxInt(u64) >> 1)); // TODO: Shouldn't need this explicit check. if (x == 0.0) { return 1.0; } // |x| < log(2) if (w < 0x3FE62E42) { if (w < 0x3FF00000 - (26 << 20)) { if (x != 0) { math.raiseInexact(); } return 1.0; } const t = math.expm1(ax); return 1 + t * t / (2 * (1 + t)); } // |x| < log(DBL_MAX) if (w < 0x40862E42) { const t = math.exp(ax); // NOTE: If x > log(0x1p26) then 1/t is not required. return 0.5 * (t + 1 / t); } // |x| > log(CBL_MAX) or nan return expo2(ax); } test "math.cosh" { expect(cosh(@as(f32, 1.5)) == cosh32(1.5)); expect(cosh(@as(f64, 1.5)) == cosh64(1.5)); } test "math.cosh32" { const epsilon = 0.000001; expect(math.approxEq(f32, cosh32(0.0), 1.0, epsilon)); expect(math.approxEq(f32, cosh32(0.2), 1.020067, epsilon)); expect(math.approxEq(f32, cosh32(0.8923), 1.425225, epsilon)); expect(math.approxEq(f32, cosh32(1.5), 2.352410, epsilon)); } test "math.cosh64" { const epsilon = 0.000001; expect(math.approxEq(f64, cosh64(0.0), 1.0, epsilon)); expect(math.approxEq(f64, cosh64(0.2), 1.020067, epsilon)); expect(math.approxEq(f64, cosh64(0.8923), 1.425225, epsilon)); expect(math.approxEq(f64, cosh64(1.5), 2.352410, epsilon)); } test "math.cosh32.special" { expect(cosh32(0.0) == 1.0); expect(cosh32(-0.0) == 1.0); expect(math.isPositiveInf(cosh32(math.inf(f32)))); expect(math.isPositiveInf(cosh32(-math.inf(f32)))); expect(math.isNan(cosh32(math.nan(f32)))); } test "math.cosh64.special" { expect(cosh64(0.0) == 1.0); expect(cosh64(-0.0) == 1.0); expect(math.isPositiveInf(cosh64(math.inf(f64)))); expect(math.isPositiveInf(cosh64(-math.inf(f64)))); expect(math.isNan(cosh64(math.nan(f64)))); }
lib/std/math/cosh.zig
const std = @import("std"); usingnamespace @import("vector3.zig"); usingnamespace @import("quaternion.zig"); pub fn Matrix4Fn(comptime T: type) type { if (@typeInfo(T) != .Float) { @compileError("Matrix4 not implemented for " ++ @typeName(T) ++ " must use float type"); } return struct { const Self = @This(); const Vec3Type = Vector3Fn(T); const QuatType = QuaternionFn(T); data: [4]std.meta.Vector(4, T), pub const zero = Self{ .data = .{ .{ 0, 0, 0, 0 }, .{ 0, 0, 0, 0 }, .{ 0, 0, 0, 0 }, .{ 0, 0, 0, 0 }, }, }; pub const identity = Self{ .data = .{ .{ 1, 0, 0, 0 }, .{ 0, 1, 0, 0 }, .{ 0, 0, 1, 0 }, .{ 0, 0, 0, 1 }, }, }; pub fn translation(vec: Vec3Type) Self { return Self{ .data = .{ .{ 1, 0, 0, 0 }, .{ 0, 1, 0, 0 }, .{ 0, 0, 1, 0 }, .{ vec.data[0], vec.data[1], vec.data[2], 1 }, }, }; } pub fn rotation(quat: QuatType) Self { var data = quat.data; var qxx = data[1] * data[1]; var qyy = data[2] * data[2]; var qzz = data[3] * data[3]; var qxz = data[1] * data[3]; var qxy = data[1] * data[2]; var qyz = data[2] * data[3]; var qwx = data[0] * data[1]; var qwy = data[0] * data[2]; var qwz = data[0] * data[3]; var result = Self.identity; //TODO: transpose this? result.data[0][0] = 1 - 2 * (qyy + qzz); result.data[0][1] = 2 * (qxy + qwz); result.data[0][2] = 2 * (qxz - qwy); result.data[1][0] = 2 * (qxy - qwz); result.data[1][1] = 1 - 2 * (qxx + qzz); result.data[1][2] = 2 * (qyz + qwx); result.data[2][0] = 2 * (qxz + qwy); result.data[2][1] = 2 * (qyz - qwx); result.data[2][2] = 1 - 2 * (qxx + qyy); return result; } pub fn scale(vec: Vec3Type) Self { return Self{ .data = .{ .{ vec.data[0], 0, 0, 0 }, .{ 0, vec.data[1], 0, 0 }, .{ 0, 0, vec.data[2], 0 }, .{ 0, 0, 0, 1 }, }, }; } pub fn model(p: Vec3Type, r: QuatType, s: Vec3Type) Self { return Self.translation(p).mul(Self.rotation(r)).mul(Self.scale(s)); } pub fn orthographic_lh_zo(left: T, right: T, bottom: T, top: T, near: T, far: T) Self { return Self{ .data = .{ .{ 2 / (right - left), 0, 0, 0 }, .{ 0, 2 / (top - bottom), 0, 0 }, .{ 0, 0, 1 / (far - near), 0 }, .{ -(right + left) / (right - left), -(top + bottom) / (top - bottom), -near / (far - near), 1, }, }, }; } pub fn perspective_lh_zo(fovy: T, aspect_ratio: T, near: T, far: T) Self { var tan_half_fov = std.math.tan(fovy / 2); return Self{ .data = .{ .{ 1 / (aspect_ratio * tan_half_fov), 0, 0, 0 }, .{ 0, 1 / tan_half_fov, 0, 0 }, .{ 0, 0, far / (far - near), 1 }, .{ 0, 0, -(far * near) / (far - near), 1 }, }, }; } pub fn view_lh(pos: Vec3Type, rot: QuatType) Self { var r = rot.rotate(Vec3Type.xaxis).normalize(); var u = rot.rotate(Vec3Type.yaxis).normalize(); var f = rot.rotate(Vec3Type.zaxis).normalize(); return Self{ .data = .{ .{ r.data[0], u.data[0], f.data[0], 0 }, .{ r.data[1], u.data[1], f.data[1], 0 }, .{ r.data[2], u.data[2], f.data[2], 0 }, .{ -r.dot(pos), -u.dot(pos), -f.dot(pos), 1 }, }, }; } pub fn transpose(mat: Self) Self { var m = mat.data; return Self{ .data = .{ .{ m[0][0], m[1][0], m[2][0], m[3][0] }, .{ m[0][1], m[1][1], m[2][1], m[3][1] }, .{ m[0][2], m[1][2], m[2][2], m[3][2] }, .{ m[0][3], m[1][3], m[2][3], m[3][3] }, }, }; } pub fn mul(left: Self, right: Self) Self { var mat = Self.zero; var columns: usize = 0; while (columns < 4) : (columns += 1) { var rows: usize = 0; while (rows < 4) : (rows += 1) { var sum: T = 0.0; var current_mat: usize = 0; while (current_mat < 4) : (current_mat += 1) { sum += left.data[current_mat][rows] * right.data[columns][current_mat]; } mat.data[columns][rows] = sum; } } return mat; //TODO: fix this // var lhs = self.data; // var rhs = other.transpose().data; // var result = Self.zero; // var row: u8 = 0; // while (row < 4) : (row += 1) { // var column: u8 = 0; // while (column < 4) : (column += 1) { // //Force to product to slice // var products: [4]f32 = lhs[row] * rhs[column]; // //TODO: unroll or use SIMD? // for (products) |value| { // result.data[row][column] += value; // } // } // } // return result; } }; } //TODO: Make tests for these? // var identity = Matrix4.identity; // var scale = Matrix4.scale(Vector3.new(1, 2, 3)); // var translation = Matrix4.translation(Vector3.new(1, 2, 3)); // var rotation = Matrix4.rotation(Quaternion.axisAngle(Vector3.yaxis, 3.1415926 / 4.0)); // var multiply = translation.mul(scale).mul(rotation); // std.log.info("Identity : {d:0.2}", .{identity.data}); // std.log.info("scale : {d:0.2}", .{scale.data}); // std.log.info("translation: {d:0.2}", .{translation.data}); // std.log.info("rotation : {d:0.2}", .{rotation.data}); // std.log.info("multiply : {d:0.2}", .{multiply.data});
src/linear_math/matrix4.zig
const std = @import("std"); const testing = std.testing; const binary_search = @import("binary_search.zig"); const SearchError = binary_search.SearchError; test "finds a value in an array with one element" { comptime try testing.expectEqual(0, try binary_search.binarySearch(i4, 6, &[_]i4{6})); } test "finds a value in the middle of an array" { comptime try testing.expectEqual(3, try binary_search.binarySearch(u4, 6, &[_]u4{1, 3, 4, 6, 8, 9, 11})); } test "finds a value at the beginning of an array" { comptime try testing.expectEqual(0, try binary_search.binarySearch(i8, 1, &[_]i8{1, 3, 4, 6, 8, 9, 11})); } test "finds a value at the end of an array" { comptime try testing.expectEqual(6, try binary_search.binarySearch(u8, 11, &[_]u8{1, 3, 4, 6, 8, 9, 11})); } test "finds a value in an array of odd length" { comptime try testing.expectEqual(5, try binary_search.binarySearch(i16, 21, &[_]i16{1, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 634})); } test "finds a value in an array of even length" { comptime try testing.expectEqual(5, try binary_search.binarySearch(u16, 21, &[_]u16{1, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377})); } test "identifies that a value is not included in the array" { try testing.expectError(SearchError.ValueAbsent, binary_search.binarySearch(i32, 7, &[_]i32{1, 3, 4, 6, 8, 9, 11})); } test "a value smaller than the arrays smallest value is not found" { try testing.expectError(SearchError.ValueAbsent, binary_search.binarySearch(u32, 0, &[_]u32{1, 3, 4, 6, 8, 9, 11})); } test "a value larger than the arrays largest value is not found" { try testing.expectError(SearchError.ValueAbsent, binary_search.binarySearch(i64, 13, &[_]i64{1, 3, 4, 6, 8, 9, 11})); } test "nothing is found in an empty array" { try testing.expectError(SearchError.EmptyBuffer, binary_search.binarySearch(u64, 13, &[_]u64{})); } test "nothing is found when the left and right bounds cross" { try testing.expectError(SearchError.ValueAbsent, binary_search.binarySearch(isize, 13, &[_]isize{1, 2})); }
exercises/practice/binary-search/test_binary_search.zig
pub extern "LALR" const zig_grammar = struct { const Precedence = struct { right: enum { Precedence_enumlit, }, left: enum { // AssignOp Equal, AsteriskEqual, SlashEqual, PercentEqual, PlusEqual, MinusEqual, AngleBracketAngleBracketLeftEqual, AngleBracketAngleBracketRightEqual, AmpersandEqual, CaretEqual, PipeEqual, AsteriskPercentEqual, PlusPercentEqual, MinusPercentEqual, }, right: enum { Keyword_break, Keyword_return, Keyword_continue, Keyword_resume, Keyword_cancel, Keyword_comptime, Keyword_promise, }, left: enum { Keyword_or, }, left: enum { Keyword_and, AmpersandAmpersand, }, left: enum { // CompareOp EqualEqual, BangEqual, AngleBracketLeft, AngleBracketRight, AngleBracketLeftEqual, AngleBracketRightEqual, }, left: enum { Keyword_orelse, Keyword_catch, }, left: enum { // Bitwise OR Pipe, }, left: enum { // Bitwise XOR Caret, }, left: enum { // Bitwise AND Ampersand, }, left: enum { AngleBracketAngleBracketLeft, AngleBracketAngleBracketRight, }, left: enum { Plus, Minus, PlusPlus, PlusPercent, MinusPercent, }, left: enum { Asterisk, Slash, Percent, AsteriskAsterisk, AsteriskPercent, PipePipe, }, right: enum { Keyword_try, Keyword_await, Precedence_not, Precedence_neg, Tilde, Precedence_ref, QuestionMark, }, right: enum { // x{} initializer LCurly, LBrace, // x.* x.? PeriodAsterisk, PeriodQuestionMark, }, left: enum { // a!b Bang, }, left: enum { LParen, LBracket, Period, }, left: enum { Precedence_async, }, }; fn Root(MaybeRootDocComment: ?*Node.DocComment, MaybeContainerMembers: ?*NodeList) *Node { const node = try parser.createNode(Node.Root); node.doc_comments = arg1; node.decls = if (arg2) |p| p.* else NodeList.init(parser.allocator); result = &node.base; } // DocComments fn MaybeDocComment() ?*Node.DocComment; fn MaybeDocComment(DocCommentLines: *TokenList) ?*Node.DocComment { const node = try parser.createNode(Node.DocComment); node.lines = arg1.*; result = node; } fn DocCommentLines(DocCommentLines: *TokenList, DocComment: *Token) *TokenList { result = arg1; try arg1.append(arg2); } fn DocCommentLines(DocComment: *Token) *TokenList { result = try parser.createListWithToken(TokenList, arg1); } fn MaybeRootDocComment() ?*Node.DocComment; fn MaybeRootDocComment(RootDocCommentLines: *TokenList) ?*Node.DocComment { const node = try parser.createNode(Node.DocComment); node.lines = arg1.*; result = node; } fn RootDocCommentLines(RootDocCommentLines: *TokenList, RootDocComment: *Token) *TokenList { result = arg1; try arg1.append(arg2); } fn RootDocCommentLines(RootDocComment: *Token) *TokenList { result = try parser.createListWithToken(TokenList, arg1); } // Containers fn MaybeContainerMembers() ?*NodeList; fn MaybeContainerMembers(ContainerMembers: *NodeList) ?*NodeList; fn ContainerMembers(ContainerMembers: *NodeList, ContainerMember: *Node) *NodeList { result = arg1; try arg1.append(arg2); } fn ContainerMembers(ContainerMember: *Node) *NodeList { result = try parser.createListWithNode(NodeList, arg1); } fn ContainerMember(MaybeDocComment: ?*Node.DocComment, TestDecl: *Node.TestDecl) *Node { result = &arg2.base; arg2.doc_comments = arg1; } fn ContainerMember(MaybeDocComment: ?*Node.DocComment, TopLevelComptime: *Node.Comptime) *Node { result = &arg2.base; arg2.doc_comments = arg1; } fn ContainerMember(MaybeDocComment: ?*Node.DocComment, MaybePub: ?*Token, TopLevelDecl: *Node) *Node { result = arg3; if (arg3.cast(Node.VarDecl)) |node| { node.doc_comments = arg1; node.visib_token = arg2; } else if (arg3.cast(Node.FnProto)) |node| { node.doc_comments = arg1; node.visib_token = arg2; } else { const node = arg3.unsafe_cast(Node.Use); node.doc_comments = arg1; node.visib_token = arg2; } } fn ContainerMember(MaybeDocComment: ?*Node.DocComment, MaybePub: ?*Token, ContainerField: *Node, Comma: *Token) *Node { result = arg3; const node = arg3.unsafe_cast(Node.ContainerField); node.doc_comments = arg1; node.visib_token = arg2; } // Test fn TestDecl(Keyword_test: *Token, StringLiteral: *Token, Block: *Node.Block) *Node.TestDecl { const name = try parser.createNode(Node.StringLiteral); name.token = arg2; const node = try parser.createNode(Node.TestDecl); node.test_token = arg1; node.name = &name.base; node.body_node = &arg3.base; result = node; } // Comptime fn TopLevelComptime(Keyword_comptime: *Token, BlockExpr: *Node) *Node.Comptime { const node = try parser.createNode(Node.Comptime); node.comptime_token = arg1; node.expr = arg2; result = node; } // TopLevel declarations fn TopLevelDecl(FnProto: *Node.FnProto, Semicolon: *Token) *Node { result = &arg1.base; } fn TopLevelDecl(FnProto: *Node.FnProto, Block: *Node.Block) *Node { arg1.body_node = &arg2.base; result = &arg1.base; } fn TopLevelDecl(Keyword_extern: *Token, StringLiteral: *Token, FnProto: *Node.FnProto, Semicolon: *Token) *Node { result = &arg3.base; const lib_name = try parser.createNode(Node.StringLiteral); lib_name.token = arg2; arg3.extern_export_inline_token = arg1; arg3.lib_name = &lib_name.base; } fn TopLevelDecl(Keyword_extern: *Token, StringLiteral: *Token, FnProto: *Node.FnProto, Block: *Node.Block) *Node { result = &arg3.base; const lib_name = try parser.createNode(Node.StringLiteral); lib_name.token = arg2; arg3.extern_export_inline_token = arg1; arg3.lib_name = &lib_name.base; arg3.body_node = &arg4.base; } fn TopLevelDecl(Keyword_export: *Token, FnProto: *Node.FnProto, Semicolon: *Token) *Node { result = &arg2.base; arg2.extern_export_inline_token = arg1; } fn TopLevelDecl(Keyword_inline: *Token, FnProto: *Node.FnProto, Semicolon: *Token) *Node { result = &arg2.base; arg2.extern_export_inline_token = arg1; } fn TopLevelDecl(Keyword_export: *Token, FnProto: *Node.FnProto, Block: *Node.Block) *Node { result = &arg2.base; arg2.extern_export_inline_token = arg1; arg2.body_node = &arg3.base; } fn TopLevelDecl(Keyword_inline: *Token, FnProto: *Node.FnProto, Block: *Node.Block) *Node { result = &arg2.base; arg2.extern_export_inline_token = arg1; arg2.body_node = &arg3.base; } fn TopLevelDecl(MaybeThreadlocal: ?*Token, VarDecl: *Node) *Node { result = arg2; const node = arg2.unsafe_cast(Node.VarDecl); node.thread_local_token = arg1; } fn TopLevelDecl(Keyword_extern: *Token, StringLiteral: *Token, MaybeThreadlocal: ?*Token, VarDecl: *Node) *Node { result = arg4; const lib_name = try parser.createNode(Node.StringLiteral); lib_name.token = arg2; const node = arg4.unsafe_cast(Node.VarDecl); node.extern_export_token = arg1; node.lib_name = &lib_name.base; node.thread_local_token = arg3; } fn TopLevelDecl(Keyword_export: *Token, MaybeThreadlocal: ?*Token, VarDecl: *Node) *Node { result = arg3; const node = arg3.unsafe_cast(Node.VarDecl); node.extern_export_token = arg1; node.thread_local_token = arg2; } fn TopLevelDecl(Keyword_extern: *Token, MaybeThreadlocal: ?*Token, VarDecl: *Node) *Node { result = arg3; const node = arg3.unsafe_cast(Node.VarDecl); node.extern_export_token = arg1; node.thread_local_token = arg2; } fn TopLevelDecl(Keyword_usingnamespace: *Token, Expr: *Node, Semicolon: *Token) *Node { const node = try parser.createNode(Node.Use); node.use_token = arg1; node.expr = arg2; node.semicolon_token = arg3; result = &node.base; } fn TopLevelDecl(Keyword_use: *Token, Expr: *Node, Semicolon: *Token) *Node { const node = try parser.createNode(Node.Use); node.use_token = arg1; node.expr = arg2; node.semicolon_token = arg3; result = &node.base; } fn MaybeThreadlocal() ?*Token; fn MaybeThreadlocal(Keyword_threadlocal: *Token) ?*Token; // Functions fn FnProto(Keyword_fn: *Token, MaybeIdentifier: ?*Token, LParen: Precedence_none(*Token), MaybeParamDeclList: ?*NodeList, RParen: *Token, MaybeByteAlign: ?*Node, MaybeLinkSection: ?*Node, Expr: *Node) *Node.FnProto { const node = try parser.createNode(Node.FnProto); node.fn_token = arg1; node.name_token = arg2; node.params = if (arg4) |p| p.* else NodeList.init(parser.allocator); node.align_expr = arg6; node.section_expr = arg7; node.return_type = Node.FnProto.ReturnType{ .Explicit = arg8 }; result = node; } fn FnProto(FnCC: *Token, Keyword_fn: *Token, MaybeIdentifier: ?*Token, LParen: Precedence_none(*Token), MaybeParamDeclList: ?*NodeList, RParen: *Token, MaybeByteAlign: ?*Node, MaybeLinkSection: ?*Node, Expr: *Node) *Node.FnProto { const node = try parser.createNode(Node.FnProto); node.cc_token = arg1; node.fn_token = arg2; node.name_token = arg3; node.params = if (arg5) |p| p.* else NodeList.init(parser.allocator); node.align_expr = arg7; node.section_expr = arg8; node.return_type = Node.FnProto.ReturnType{ .Explicit = arg9 }; result = node; } fn FnProto(Keyword_fn: *Token, MaybeIdentifier: ?*Token, LParen: Precedence_none(*Token), MaybeParamDeclList: ?*NodeList, RParen: *Token, MaybeByteAlign: ?*Node, MaybeLinkSection: ?*Node, Bang: Precedence_none(*Token), Expr: *Node) *Node.FnProto { const node = try parser.createNode(Node.FnProto); node.fn_token = arg1; node.name_token = arg2; node.params = if (arg4) |p| p.* else NodeList.init(parser.allocator); node.align_expr = arg6; node.section_expr = arg7; node.return_type = Node.FnProto.ReturnType{ .InferErrorSet = arg9 }; result = node; } fn FnProto(FnCC: *Token, Keyword_fn: *Token, MaybeIdentifier: ?*Token, LParen: Precedence_none(*Token), MaybeParamDeclList: ?*NodeList, RParen: *Token, MaybeByteAlign: ?*Node, MaybeLinkSection: ?*Node, Bang: Precedence_none(*Token), Expr: *Node) *Node.FnProto { const node = try parser.createNode(Node.FnProto); node.cc_token = arg1; node.fn_token = arg2; node.name_token = arg3; node.params = if (arg5) |p| p.* else NodeList.init(parser.allocator); node.align_expr = arg7; node.section_expr = arg8; node.return_type = Node.FnProto.ReturnType{ .InferErrorSet = arg10 }; result = node; } fn FnProto(Keyword_fn: *Token, MaybeIdentifier: ?*Token, LParen: Precedence_none(*Token), MaybeParamDeclList: ?*NodeList, RParen: *Token, MaybeByteAlign: ?*Node, MaybeLinkSection: ?*Node, Keyword_var: *Token) *Node.FnProto { const vnode = try parser.createNode(Node.VarType); vnode.token = arg8; const node = try parser.createNode(Node.FnProto); node.fn_token = arg1; node.name_token = arg2; node.params = if (arg4) |p| p.* else NodeList.init(parser.allocator); node.align_expr = arg6; node.section_expr = arg7; node.return_type = Node.FnProto.ReturnType{ .Explicit = &vnode.base }; result = node; } fn FnProto(FnCC: *Token, Keyword_fn: *Token, MaybeIdentifier: ?*Token, LParen: Precedence_none(*Token), MaybeParamDeclList: ?*NodeList, RParen: *Token, MaybeByteAlign: ?*Node, MaybeLinkSection: ?*Node, Keyword_var: *Token) *Node.FnProto { const vnode = try parser.createNode(Node.VarType); vnode.token = arg9; const node = try parser.createNode(Node.FnProto); node.cc_token = arg1; node.fn_token = arg2; node.name_token = arg3; node.params = if (arg5) |p| p.* else NodeList.init(parser.allocator); node.align_expr = arg7; node.section_expr = arg8; node.return_type = Node.FnProto.ReturnType{ .Explicit = &vnode.base }; result = node; } fn FnProto(Keyword_fn: *Token, MaybeIdentifier: ?*Token, LParen: Precedence_none(*Token), MaybeParamDeclList: ?*NodeList, RParen: *Token, MaybeByteAlign: ?*Node, MaybeLinkSection: ?*Node, Bang: Precedence_none(*Token), Keyword_var: *Token) *Node.FnProto { const vnode = try parser.createNode(Node.VarType); vnode.token = arg9; const node = try parser.createNode(Node.FnProto); node.fn_token = arg1; node.name_token = arg2; node.params = if (arg4) |p| p.* else NodeList.init(parser.allocator); node.align_expr = arg6; node.section_expr = arg7; node.return_type = Node.FnProto.ReturnType{ .InferErrorSet = &vnode.base }; result = node; } fn FnProto(FnCC: *Token, Keyword_fn: *Token, MaybeIdentifier: ?*Token, LParen: Precedence_none(*Token), MaybeParamDeclList: ?*NodeList, RParen: *Token, MaybeByteAlign: ?*Node, MaybeLinkSection: ?*Node, Bang: Precedence_none(*Token), Keyword_var: *Token) *Node.FnProto { const vnode = try parser.createNode(Node.VarType); vnode.token = arg10; const node = try parser.createNode(Node.FnProto); node.cc_token = arg1; node.fn_token = arg2; node.name_token = arg3; node.params = if (arg5) |p| p.* else NodeList.init(parser.allocator); node.align_expr = arg7; node.section_expr = arg8; node.return_type = Node.FnProto.ReturnType{ .InferErrorSet = &vnode.base }; result = node; } // Variables fn VarDecl(Keyword_const: *Token, Identifier: *Token, MaybeColonTypeExpr: ?*Node, MaybeByteAlign: ?*Node, MaybeLinkSection: ?*Node, MaybeEqualExpr: ?*Node, Semicolon: *Token) *Node { const node = try parser.createNode(Node.VarDecl); node.mut_token = arg1; node.name_token = arg2; node.type_node = arg3; node.align_node = arg4; node.section_node = arg5; node.init_node = arg6; node.semicolon_token = arg7; result = &node.base; } fn VarDecl(Keyword_var: *Token, Identifier: *Token, MaybeColonTypeExpr: ?*Node, MaybeByteAlign: ?*Node, MaybeLinkSection: ?*Node, MaybeEqualExpr: ?*Node, Semicolon: *Token) *Node { const node = try parser.createNode(Node.VarDecl); node.mut_token = arg1; node.name_token = arg2; node.type_node = arg3; node.align_node = arg4; node.section_node = arg5; node.init_node = arg6; node.semicolon_token = arg7; result = &node.base; } // Container field fn ContainerField(Identifier: *Token, MaybeColonTypeExpr: ?*Node, MaybeEqualExpr: ?*Node) *Node { const node = try parser.createNode(Node.ContainerField); node.name_token = arg1; node.type_expr = arg2; node.value_expr = arg3; result = &node.base; } // Statements fn MaybeStatements() ?*NodeList; fn MaybeStatements(Statements: *NodeList) ?*NodeList; fn Statements(Statement: *Node) *NodeList { result = try parser.createListWithNode(NodeList, arg1); } fn Statements(Statements: *NodeList, Statement: *Node) *NodeList { result = arg1; try arg1.append(arg2); } fn Statement(Keyword_comptime: *Token, VarDecl: *Node) *Node { const node = try parser.createNode(Node.Comptime); node.comptime_token = arg1; node.expr = arg2; result = &node.base; } fn Statement(VarDecl: *Node) *Node; fn Statement(Keyword_comptime: *Token, BlockExpr: *Node) *Node { const node = try parser.createNode(Node.Comptime); node.comptime_token = arg1; node.expr = arg2; result = &node.base; } fn Statement(Keyword_suspend: *Token, Semicolon: *Token) *Node { const node = try parser.createNode(Node.Suspend); node.suspend_token = arg1; result = &node.base; } fn Statement(Keyword_suspend: *Token, BlockExprStatement: *Node) *Node { const node = try parser.createNode(Node.Suspend); node.suspend_token = arg1; node.body = arg2; result = &node.base; } fn Statement(Keyword_defer: *Token, BlockExprStatement: *Node) *Node { const node = try parser.createNode(Node.Defer); node.defer_token = arg1; node.expr = arg2; result = &node.base; } fn Statement(Keyword_errdefer: *Token, BlockExprStatement: *Node) *Node { const node = try parser.createNode(Node.Defer); node.defer_token = arg1; node.expr = arg2; result = &node.base; } fn Statement(IfStatement: *Node) *Node; fn Statement(MaybeInline: ?*Token, ForStatement: *Node.For) *Node { result = &arg2.base; arg2.inline_token = arg1; } fn Statement(MaybeInline: ?*Token, WhileStatement: *Node.While) *Node { result = &arg2.base; arg2.inline_token = arg1; } fn Statement(LabeledStatement: *Node) *Node; fn Statement(SwitchExpr: *Node) *Node; fn Statement(AssignExpr: *Node, Semicolon: *Token) *Node { result = arg1; } fn IfStatement(IfPrefix: *Node.If, BlockExpr: *Node) *Node { result = &arg1.base; arg1.body = arg2; } fn IfStatement(IfPrefix: *Node.If, BlockExpr: *Node, ElseStatement: *Node.Else) *Node { result = &arg1.base; arg1.body = arg2; arg1.@"else" = arg3; } fn IfStatement(IfPrefix: *Node.If, AssignExpr: *Node, Semicolon: *Token) *Node { result = &arg1.base; arg1.body = arg2; } fn IfStatement(IfPrefix: *Node.If, AssignExpr: *Node, ElseStatement: *Node.Else) *Node { result = &arg1.base; arg1.body = arg2; arg1.@"else" = arg3; } fn ElseStatement(Keyword_else: *Token, MaybePayload: ?*Node, Statement: *Node) *Node.Else { const node = try parser.createNode(Node.Else); node.else_token = arg1; node.payload = arg2; node.body = arg3; result = node; } fn LabeledStatement(BlockLabel: *Token, MaybeInline: ?*Token, ForStatement: *Node.For) *Node { result = &arg3.base; arg3.label = arg1; arg3.inline_token = arg2; } fn LabeledStatement(BlockLabel: *Token, MaybeInline: ?*Token, WhileStatement: *Node.While) *Node { result = &arg3.base; arg3.label = arg1; arg3.inline_token = arg2; } fn LabeledStatement(BlockExpr: *Node) *Node; fn ForStatement(ForPrefix: *Node.For, BlockExpr: *Node) *Node.For { result = arg1; arg1.body = arg2; } fn ForStatement(ForPrefix: *Node.For, BlockExpr: *Node, ElseNoPayloadStatement: *Node.Else) *Node.For { result = arg1; arg1.body = arg2; arg1.@"else" = arg3; } fn ForStatement(ForPrefix: *Node.For, AssignExpr: *Node, Semicolon: *Token) *Node.For { result = arg1; arg1.body = arg2; } fn ForStatement(ForPrefix: *Node.For, AssignExpr: *Node, ElseNoPayloadStatement: *Node.Else) *Node.For { result = arg1; arg1.body = arg2; arg1.@"else" = arg3; } fn ElseNoPayloadStatement(Keyword_else: *Token, Statement: *Node) *Node.Else { const node = try parser.createNode(Node.Else); node.else_token = arg1; node.body = arg2; result = node; } fn WhileStatement(WhilePrefix: *Node.While, BlockExpr: *Node) *Node.While { result = arg1; arg1.body = arg2; } fn WhileStatement(WhilePrefix: *Node.While, BlockExpr: *Node, ElseStatement: *Node.Else) *Node.While { result = arg1; arg1.body = arg2; arg1.@"else" = arg3; } fn WhileStatement(WhilePrefix: *Node.While, AssignExpr: *Node, Semicolon: *Token) *Node.While { result = arg1; arg1.body = arg2; } fn WhileStatement(WhilePrefix: *Node.While, AssignExpr: *Node, ElseStatement: *Node.Else) *Node.While { result = arg1; arg1.body = arg2; arg1.@"else" = arg3; } fn BlockExprStatement(BlockExpr: *Node) *Node; fn BlockExprStatement(AssignExpr: *Node, Semicolon: *Token) *Node { result = arg1; } // Expression level fn AssignExpr(Expr: *Node, AsteriskEqual: *Token, Expr: *Node) *Node { const node = try parser.createNode(Node.InfixOp); node.lhs = arg1; node.op_token = arg2; node.op = .AssignTimes; node.rhs = arg3; result = &node.base; } fn AssignExpr(Expr: *Node, SlashEqual: *Token, Expr: *Node) *Node { const node = try parser.createNode(Node.InfixOp); node.lhs = arg1; node.op_token = arg2; node.op = .AssignDiv; node.rhs = arg3; result = &node.base; } fn AssignExpr(Expr: *Node, PercentEqual: *Token, Expr: *Node) *Node { const node = try parser.createNode(Node.InfixOp); node.lhs = arg1; node.op_token = arg2; node.op = .AssignMod; node.rhs = arg3; result = &node.base; } fn AssignExpr(Expr: *Node, PlusEqual: *Token, Expr: *Node) *Node { const node = try parser.createNode(Node.InfixOp); node.lhs = arg1; node.op_token = arg2; node.op = .AssignPlus; node.rhs = arg3; result = &node.base; } fn AssignExpr(Expr: *Node, MinusEqual: *Token, Expr: *Node) *Node { const node = try parser.createNode(Node.InfixOp); node.lhs = arg1; node.op_token = arg2; node.op = .AssignMinus; node.rhs = arg3; result = &node.base; } fn AssignExpr(Expr: *Node, AngleBracketAngleBracketLeftEqual: *Token, Expr: *Node) *Node { const node = try parser.createNode(Node.InfixOp); node.lhs = arg1; node.op_token = arg2; node.op = .AssignBitShiftLeft; node.rhs = arg3; result = &node.base; } fn AssignExpr(Expr: *Node, AngleBracketAngleBracketRightEqual: *Token, Expr: *Node) *Node { const node = try parser.createNode(Node.InfixOp); node.lhs = arg1; node.op_token = arg2; node.op = .AssignBitShiftRight; node.rhs = arg3; result = &node.base; } fn AssignExpr(Expr: *Node, AmpersandEqual: *Token, Expr: *Node) *Node { const node = try parser.createNode(Node.InfixOp); node.lhs = arg1; node.op_token = arg2; node.op = .AssignBitAnd; node.rhs = arg3; result = &node.base; } fn AssignExpr(Expr: *Node, CaretEqual: *Token, Expr: *Node) *Node { const node = try parser.createNode(Node.InfixOp); node.lhs = arg1; node.op_token = arg2; node.op = .AssignBitXor; node.rhs = arg3; result = &node.base; } fn AssignExpr(Expr: *Node, PipeEqual: *Token, Expr: *Node) *Node { const node = try parser.createNode(Node.InfixOp); node.lhs = arg1; node.op_token = arg2; node.op = .AssignBitOr; node.rhs = arg3; result = &node.base; } fn AssignExpr(Expr: *Node, AsteriskPercentEqual: *Token, Expr: *Node) *Node { const node = try parser.createNode(Node.InfixOp); node.lhs = arg1; node.op_token = arg2; node.op = .AssignTimesWrap; node.rhs = arg3; result = &node.base; } fn AssignExpr(Expr: *Node, PlusPercentEqual: *Token, Expr: *Node) *Node { const node = try parser.createNode(Node.InfixOp); node.lhs = arg1; node.op_token = arg2; node.op = .AssignPlusWrap; node.rhs = arg3; result = &node.base; } fn AssignExpr(Expr: *Node, MinusPercentEqual: *Token, Expr: *Node) *Node { const node = try parser.createNode(Node.InfixOp); node.lhs = arg1; node.op_token = arg2; node.op = .AssignMinusWrap; node.rhs = arg3; result = &node.base; } fn AssignExpr(Expr: *Node, Equal: *Token, Expr: *Node) *Node { const node = try parser.createNode(Node.InfixOp); node.lhs = arg1; node.op_token = arg2; node.op = .Assign; node.rhs = arg3; result = &node.base; } fn AssignExpr(Expr: *Node) *Node; fn MaybeEqualExpr() ?*Node; fn MaybeEqualExpr(Equal: *Token, Expr: *Node) ?*Node { result = arg2; } // Recovery fn Expr(Recovery: *Token) *Node { const node = try parser.createNode(Node.Recovery); node.token = arg1; result = &node.base; } // Grouped fn Expr(LParen: *Token, Expr: *Node, RParen: *Token) *Node { if (arg2.id != .GroupedExpression) { const node = try parser.createNode(Node.GroupedExpression); node.lparen = arg1; node.expr = arg2; node.rparen = arg3; result = &node.base; } else result = arg2; } // Infix fn Expr(Expr: *Node, Keyword_orelse: *Token, Expr: *Node) *Node { const node = try parser.createNode(Node.InfixOp); node.lhs = arg1; node.op_token = arg2; node.op = .UnwrapOptional; node.rhs = arg3; result = &node.base; } fn Expr(Expr: *Node, Keyword_catch: *Token, MaybePayload: ?*Node, Expr: *Node) *Node { const node = try parser.createNode(Node.InfixOp); node.lhs = arg1; node.op_token = arg2; node.op = Node.InfixOp.Op{ .Catch = arg3 }; node.rhs = arg4; result = &node.base; } fn Expr(Expr: *Node, Keyword_or: *Token, Expr: *Node) *Node { const node = try parser.createNode(Node.InfixOp); node.lhs = arg1; node.op_token = arg2; node.op = .BoolOr; node.rhs = arg3; result = &node.base; } fn Expr(Expr: *Node, AmpersandAmpersand: *Token, Expr: *Node) *Node { try parser.reportError(ParseError.AmpersandAmpersand, arg2); const node = try parser.createNode(Node.InfixOp); node.lhs = arg1; node.op_token = arg2; node.op = .BoolAnd; node.rhs = arg3; result = &node.base; } fn Expr(Expr: *Node, Keyword_and: *Token, Expr: *Node) *Node { const node = try parser.createNode(Node.InfixOp); node.lhs = arg1; node.op_token = arg2; node.op = .BoolAnd; node.rhs = arg3; result = &node.base; } fn Expr(Expr: *Node, EqualEqual: *Token, Expr: *Node) *Node { const node = try parser.createNode(Node.InfixOp); node.lhs = arg1; node.op_token = arg2; node.op = .EqualEqual; node.rhs = arg3; result = &node.base; } fn Expr(Expr: *Node, BangEqual: *Token, Expr: *Node) *Node { const node = try parser.createNode(Node.InfixOp); node.lhs = arg1; node.op_token = arg2; node.op = .BangEqual; node.rhs = arg3; result = &node.base; } fn Expr(Expr: *Node, AngleBracketLeft: *Token, Expr: *Node) *Node { const node = try parser.createNode(Node.InfixOp); node.lhs = arg1; node.op_token = arg2; node.op = .LessThan; node.rhs = arg3; result = &node.base; } fn Expr(Expr: *Node, AngleBracketRight: *Token, Expr: *Node) *Node { const node = try parser.createNode(Node.InfixOp); node.lhs = arg1; node.op_token = arg2; node.op = .GreaterThan; node.rhs = arg3; result = &node.base; } fn Expr(Expr: *Node, AngleBracketLeftEqual: *Token, Expr: *Node) *Node { const node = try parser.createNode(Node.InfixOp); node.lhs = arg1; node.op_token = arg2; node.op = .LessOrEqual; node.rhs = arg3; result = &node.base; } fn Expr(Expr: *Node, AngleBracketRightEqual: *Token, Expr: *Node) *Node { const node = try parser.createNode(Node.InfixOp); node.lhs = arg1; node.op_token = arg2; node.op = .GreaterOrEqual; node.rhs = arg3; result = &node.base; } fn Expr(Expr: *Node, Pipe: *Token, Expr: *Node) *Node { const node = try parser.createNode(Node.InfixOp); node.lhs = arg1; node.op_token = arg2; node.op = .BitOr; node.rhs = arg3; result = &node.base; } fn Expr(Expr: *Node, Caret: *Token, Expr: *Node) *Node { const node = try parser.createNode(Node.InfixOp); node.lhs = arg1; node.op_token = arg2; node.op = .BitXor; node.rhs = arg3; result = &node.base; } fn Expr(Expr: *Node, Ampersand: *Token, Expr: *Node) *Node { const node = try parser.createNode(Node.InfixOp); node.lhs = arg1; node.op_token = arg2; node.op = .BitAnd; node.rhs = arg3; result = &node.base; } fn Expr(Expr: *Node, AngleBracketAngleBracketLeft: *Token, Expr: *Node) *Node { const node = try parser.createNode(Node.InfixOp); node.lhs = arg1; node.op_token = arg2; node.op = .BitShiftLeft; node.rhs = arg3; result = &node.base; } fn Expr(Expr: *Node, AngleBracketAngleBracketRight: *Token, Expr: *Node) *Node { const node = try parser.createNode(Node.InfixOp); node.lhs = arg1; node.op_token = arg2; node.op = .BitShiftRight; node.rhs = arg3; result = &node.base; } fn Expr(Expr: *Node, Plus: *Token, Expr: *Node) *Node { const node = try parser.createNode(Node.InfixOp); node.lhs = arg1; node.op_token = arg2; node.op = .Add; node.rhs = arg3; result = &node.base; } fn Expr(Expr: *Node, Minus: *Token, Expr: *Node) *Node { const node = try parser.createNode(Node.InfixOp); node.lhs = arg1; node.op_token = arg2; node.op = .Sub; node.rhs = arg3; result = &node.base; } fn Expr(Expr: *Node, PlusPlus: *Token, Expr: *Node) *Node { const node = try parser.createNode(Node.InfixOp); node.lhs = arg1; node.op_token = arg2; node.op = .ArrayCat; node.rhs = arg3; result = &node.base; } fn Expr(Expr: *Node, PlusPercent: *Token, Expr: *Node) *Node { const node = try parser.createNode(Node.InfixOp); node.lhs = arg1; node.op_token = arg2; node.op = .AddWrap; node.rhs = arg3; result = &node.base; } fn Expr(Expr: *Node, MinusPercent: *Token, Expr: *Node) *Node { const node = try parser.createNode(Node.InfixOp); node.lhs = arg1; node.op_token = arg2; node.op = .SubWrap; node.rhs = arg3; result = &node.base; } fn Expr(Expr: *Node, Asterisk: *Token, Expr: *Node) *Node { const node = try parser.createNode(Node.InfixOp); node.lhs = arg1; node.op_token = arg2; node.op = .Div; node.rhs = arg3; result = &node.base; } fn Expr(Expr: *Node, Slash: *Token, Expr: *Node) *Node { const node = try parser.createNode(Node.InfixOp); node.lhs = arg1; node.op_token = arg2; node.op = .Div; node.rhs = arg3; result = &node.base; } fn Expr(Expr: *Node, Percent: *Token, Expr: *Node) *Node { const node = try parser.createNode(Node.InfixOp); node.lhs = arg1; node.op_token = arg2; node.op = .Mod; node.rhs = arg3; result = &node.base; } fn Expr(Expr: *Node, AsteriskAsterisk: *Token, Expr: *Node) *Node { const node = try parser.createNode(Node.InfixOp); node.lhs = arg1; node.op_token = arg2; node.op = .ArrayMult; node.rhs = arg3; result = &node.base; } fn Expr(Expr: *Node, AsteriskPercent: *Token, Expr: *Node) *Node { const node = try parser.createNode(Node.InfixOp); node.lhs = arg1; node.op_token = arg2; node.op = .MultWrap; node.rhs = arg3; result = &node.base; } fn Expr(Expr: *Node, PipePipe: *Token, Expr: *Node) *Node { const node = try parser.createNode(Node.InfixOp); node.lhs = arg1; node.op_token = arg2; node.op = .ErrorUnion; node.rhs = arg3; result = &node.base; } // Prefix fn Expr(Bang: Precedence_not(*Token), Expr: *Node) *Node { const node = try parser.createNode(Node.PrefixOp); node.op_token = arg1; node.op = .BoolNot; node.rhs = arg2; result = &node.base; } fn Expr(Minus: Precedence_neg(*Token), Expr: *Node) *Node { const node = try parser.createNode(Node.PrefixOp); node.op_token = arg1; node.op = .Negation; node.rhs = arg2; result = &node.base; } fn Expr(MinusPercent: Precedence_neg(*Token), Expr: *Node) *Node { const node = try parser.createNode(Node.PrefixOp); node.op_token = arg1; node.op = .NegationWrap; node.rhs = arg2; result = &node.base; } fn Expr(Tilde: *Token, Expr: *Node) *Node { const node = try parser.createNode(Node.PrefixOp); node.op_token = arg1; node.op = .BitNot; node.rhs = arg2; result = &node.base; } fn Expr(Ampersand: Precedence_ref(*Token), Expr: *Node) *Node { const node = try parser.createNode(Node.PrefixOp); node.op_token = arg1; node.op = .AddressOf; node.rhs = arg2; result = &node.base; } fn Expr(Keyword_async: *Token, Expr: *Node) *Node { const node = try parser.createNode(Node.PrefixOp); node.op_token = arg1; node.op = .Async; node.rhs = arg2; result = &node.base; } fn Expr(Keyword_try: *Token, Expr: *Node) *Node { const node = try parser.createNode(Node.PrefixOp); node.op_token = arg1; node.op = .Try; node.rhs = arg2; result = &node.base; } fn Expr(Keyword_await: *Token, Expr: *Node) *Node { const node = try parser.createNode(Node.PrefixOp); node.op_token = arg1; node.op = .Await; node.rhs = arg2; result = &node.base; } fn Expr(Keyword_comptime: *Token, Expr: *Node) *Node { const node = try parser.createNode(Node.Comptime); node.comptime_token = arg1; node.expr = arg2; result = &node.base; } // Primary fn Expr(AsmExpr: *Node) *Node; fn Expr(Keyword_resume: *Token, Expr: *Node) *Node { const node = try parser.createNode(Node.PrefixOp); node.op_token = arg1; node.op = .Resume; node.rhs = arg2; result = &node.base; } fn Expr(Keyword_cancel: *Token, Expr: *Node) *Node { const node = try parser.createNode(Node.PrefixOp); node.op_token = arg1; node.op = .Cancel; node.rhs = arg2; result = &node.base; } fn Expr(Keyword_break: *Token) *Node { const node = try parser.createNode(Node.ControlFlowExpression); node.ltoken = arg1; node.kind = Node.ControlFlowExpression.Kind{ .Break = null }; result = &node.base; } fn Expr(Keyword_break: *Token, BreakLabel: *Node) *Node { const node = try parser.createNode(Node.ControlFlowExpression); node.ltoken = arg1; node.kind = Node.ControlFlowExpression.Kind{ .Break = arg2 }; result = &node.base; } fn Expr(Keyword_break: *Token, Expr: *Node) *Node { const node = try parser.createNode(Node.ControlFlowExpression); node.ltoken = arg1; node.kind = Node.ControlFlowExpression.Kind{ .Break = null }; node.rhs = arg2; result = &node.base; } fn Expr(Keyword_break: *Token, BreakLabel: *Node, Expr: *Node) *Node { const node = try parser.createNode(Node.ControlFlowExpression); node.ltoken = arg1; node.kind = Node.ControlFlowExpression.Kind{ .Break = arg2 }; node.rhs = arg3; result = &node.base; } fn Expr(Keyword_continue: *Token) *Node { const node = try parser.createNode(Node.ControlFlowExpression); node.ltoken = arg1; node.kind = Node.ControlFlowExpression.Kind{ .Continue = null }; result = &node.base; } fn Expr(Keyword_continue: *Token, BreakLabel: *Node) *Node { const node = try parser.createNode(Node.ControlFlowExpression); node.ltoken = arg1; node.kind = Node.ControlFlowExpression.Kind{ .Continue = arg2 }; result = &node.base; } fn Expr(Keyword_return: *Token) *Node { const node = try parser.createNode(Node.ControlFlowExpression); node.ltoken = arg1; node.kind = .Return; result = &node.base; } fn Expr(Keyword_return: *Token, Expr: *Node) *Node { const node = try parser.createNode(Node.ControlFlowExpression); node.ltoken = arg1; node.kind = .Return; node.rhs = arg2; result = &node.base; } // Initializer list fn Expr(Expr: *Node, LCurly: *Token, RBrace: *Token) *Node { const node = try parser.createNode(Node.SuffixOp); node.lhs = arg1; node.op = Node.SuffixOp.Op{ .ArrayInitializer = NodeList.init(parser.allocator) }; node.rtoken = arg3; result = &node.base; } fn Expr(Expr: *Node, LCurly: *Token, InitList: *NodeList, MaybeComma: ?*Token, RBrace: *Token) *Node { const node = try parser.createNode(Node.SuffixOp); node.lhs = arg1; node.op = init: { if (arg3.at(0).cast(Node.InfixOp)) |infix| { switch (infix.op) { // StructInitializer .Assign => break :init Node.SuffixOp.Op{ .StructInitializer = arg3.* }, else => {}, } } // ArrayInitializer break :init Node.SuffixOp.Op{ .ArrayInitializer = arg3.* }; }; node.rtoken = arg5; result = &node.base; } // Prefix fn Expr(QuestionMark: *Token, Expr: *Node) *Node { const node = try parser.createNode(Node.PrefixOp); node.op_token = arg1; node.op = .OptionalType; node.rhs = arg2; result = &node.base; } fn Expr(Keyword_promise: *Token) *Node { const node = try parser.createNode(Node.PromiseType); node.promise_token = arg1; result = &node.base; } fn Expr(Keyword_promise: *Token, MinusAngleBracketRight: *Token, Expr: *Node) *Node { const node = try parser.createNode(Node.PromiseType); node.promise_token = arg1; node.result = Node.PromiseType.Result{ .arrow_token = arg2, .return_type = arg3 }; result = &node.base; } // ArrayType fn Expr(LBracket: *Token, Expr: *Node, RBracket: *Token, Expr: *Node) *Node { const node = try parser.createNode(Node.PrefixOp); node.op_token = arg1; node.op = Node.PrefixOp.Op{ .ArrayType = arg2 }; node.rhs = arg4; result = &node.base; } // SliceType fn Expr(LBracket: *Token, RBracket: *Token, MaybeAllowzero: ?*Token, MaybeAlign: ?*Node.PrefixOp.PtrInfo.Align, MaybeConst: ?*Token, MaybeVolatile: ?*Token, Expr: *Node) *Node { const node = try parser.createNode(Node.PrefixOp); node.op_token = arg1; node.op = Node.PrefixOp.Op{ .SliceType = Node.PrefixOp.PtrInfo{ .allowzero_token = arg3, .align_info = if (arg4) |p| p.* else null, .const_token = arg5, .volatile_token = arg6 } }; node.rhs = arg7; result = &node.base; } // PtrType fn Expr(Asterisk: Precedence_none(*Token), MaybeAllowzero: ?*Token, MaybeAlign: ?*Node.PrefixOp.PtrInfo.Align, MaybeConst: ?*Token, MaybeVolatile: ?*Token, Expr: *Node) *Node { const node = try parser.createNode(Node.PrefixOp); node.op_token = arg1; node.op = Node.PrefixOp.Op{ .PtrType = Node.PrefixOp.PtrInfo{ .allowzero_token = arg2, .align_info = if (arg3) |p| p.* else null, .const_token = arg4, .volatile_token = arg5 } }; node.rhs = arg6; result = &node.base; } fn Expr(AsteriskAsterisk: Precedence_none(*Token), MaybeAllowzero: ?*Token, MaybeAlign: ?*Node.PrefixOp.PtrInfo.Align, MaybeConst: ?*Token, MaybeVolatile: ?*Token, Expr: *Node) *Node { arg1.id = .Asterisk; const node = try parser.createNode(Node.PrefixOp); node.op_token = arg1; node.op = Node.PrefixOp.Op{ .PtrType = Node.PrefixOp.PtrInfo{ .allowzero_token = arg2, .align_info = if (arg3) |p| p.* else null, .const_token = arg4, .volatile_token = arg5 } }; node.rhs = arg6; const outer = try parser.createNode(Node.PrefixOp); outer.op_token = arg1; outer.op = Node.PrefixOp.Op{ .PtrType = Node.PrefixOp.PtrInfo{ .allowzero_token = null, .align_info = null, .const_token = null, .volatile_token = null } }; outer.rhs = &node.base; result = &outer.base; } fn Expr(BracketStarBracket: *Token, MaybeAllowzero: ?*Token, MaybeAlign: ?*Node.PrefixOp.PtrInfo.Align, MaybeConst: ?*Token, MaybeVolatile: ?*Token, Expr: *Node) *Node { const node = try parser.createNode(Node.PrefixOp); node.op_token = arg1; node.op = Node.PrefixOp.Op{ .PtrType = Node.PrefixOp.PtrInfo{ .allowzero_token = arg2, .align_info = if (arg3) |p| p.* else null, .const_token = arg4, .volatile_token = arg5 } }; node.rhs = arg6; result = &node.base; } fn Expr(BracketStarCBracket: *Token, MaybeAllowzero: ?*Token, MaybeAlign: ?*Node.PrefixOp.PtrInfo.Align, MaybeConst: ?*Token, MaybeVolatile: ?*Token, Expr: *Node) *Node { const node = try parser.createNode(Node.PrefixOp); node.op_token = arg1; node.op = Node.PrefixOp.Op{ .PtrType = Node.PrefixOp.PtrInfo{ .allowzero_token = arg2, .align_info = if (arg3) |p| p.* else null, .const_token = arg4, .volatile_token = arg5 } }; node.rhs = arg6; result = &node.base; } // Block fn Expr(BlockExpr: Shadow(*Node)) *Node; fn BlockExpr(Block: *Node.Block) *Node { result = &arg1.base; } fn BlockExpr(BlockLabel: *Token, Block: *Node.Block) *Node { result = &arg2.base; arg2.label = arg1; } fn Block(LBrace: *Token, MaybeStatements: ?*NodeList, RBrace: *Token) *Node.Block { const node = try parser.createNode(Node.Block); node.lbrace = arg1; node.statements = if (arg2) |p| p.* else NodeList.init(parser.allocator); node.rbrace = arg3; result = node; } fn BlockLabel(Identifier: *Token, Colon: *Token) *Token { result = arg1; } // ErrorType fn Expr(Expr: *Node, Bang: *Token, Expr: *Node) *Node { const node = try parser.createNode(Node.InfixOp); node.lhs = arg1; node.op_token = arg2; node.op = .ErrorUnion; node.rhs = arg3; result = &node.base; } // Literals fn Expr(Identifier: *Token) *Node { const node = try parser.createNode(Node.Identifier); node.token = arg1; result = &node.base; } fn Expr(CharLiteral: *Token) *Node { const node = try parser.createNode(Node.CharLiteral); node.token = arg1; result = &node.base; } fn Expr(FloatLiteral: *Token) *Node { const node = try parser.createNode(Node.FloatLiteral); node.token = arg1; result = &node.base; } fn Expr(IntegerLiteral: *Token) *Node { const node = try parser.createNode(Node.IntegerLiteral); node.token = arg1; result = &node.base; } fn Expr(StringLiteral: *Token) *Node { const node = try parser.createNode(Node.StringLiteral); node.token = arg1; result = &node.base; } fn Expr(MultilineStringLiteral: *TokenList) *Node { const node = try parser.createNode(Node.MultilineStringLiteral); node.lines = arg1.*; result = &node.base; } fn Expr(MultilineCStringLiteral: *TokenList) *Node { const node = try parser.createNode(Node.MultilineStringLiteral); node.lines = arg1.*; result = &node.base; } fn Expr(Period: Precedence_enumlit(*Token), Identifier: *Token) *Node { const node = try parser.createNode(Node.EnumLiteral); node.dot = arg1; node.name = arg2; result = &node.base; } // Simple types fn Expr(Keyword_error: *Token, Period: *Token, Identifier: *Token) *Node { const err = try parser.createNode(Node.ErrorType); err.token = arg1; const name = try parser.createNode(Node.Identifier); name.token = arg3; const infix = try parser.createNode(Node.InfixOp); infix.lhs = &err.base; infix.op_token = arg2; infix.op = .Period; infix.rhs = &name.base; result = &infix.base; } fn Expr(Keyword_error: *Token, LCurly: Precedence_none(*Token), RBrace: *Token) *Node { const error_set = try parser.createNode(Node.ErrorSetDecl); error_set.error_token = arg1; error_set.decls = NodeList.init(parser.allocator); error_set.rbrace_token = arg3; result = &error_set.base; } fn Expr(Keyword_error: *Token, LCurly: Precedence_none(*Token), ErrorTagList: *NodeList, MaybeComma: ?*Token, RBrace: *Token) *Node { const error_set = try parser.createNode(Node.ErrorSetDecl); error_set.error_token = arg1; error_set.decls = arg3.*; error_set.rbrace_token = arg5; result = &error_set.base; } fn Expr(Keyword_false: *Token) *Node { const node = try parser.createNode(Node.BoolLiteral); node.token = arg1; result = &node.base; } fn Expr(Keyword_true: *Token) *Node { const node = try parser.createNode(Node.BoolLiteral); node.token = arg1; result = &node.base; } fn Expr(Keyword_null: *Token) *Node { const node = try parser.createNode(Node.NullLiteral); node.token = arg1; result = &node.base; } fn Expr(Keyword_undefined: *Token) *Node { const node = try parser.createNode(Node.UndefinedLiteral); node.token = arg1; result = &node.base; } fn Expr(Keyword_unreachable: *Token) *Node { const node = try parser.createNode(Node.Unreachable); node.token = arg1; result = &node.base; } // Flow types fn Expr(SwitchExpr: Shadow(*Node)) *Node; // IfExpr fn Expr(IfPrefix: *Node.If, Expr: *Node) *Node { result = &arg1.base; arg1.body = arg2; } fn Expr(IfPrefix: *Node.If, Expr: *Node, Keyword_else: *Token, MaybePayload: ?*Node, Expr: *Node) *Node { result = &arg1.base; const node = try parser.createNode(Node.Else); node.else_token = arg3; node.payload = arg4; node.body = arg5; arg1.body = arg2; arg1.@"else" = node; } // Builtin calls fn Expr(Builtin: *Token, LParen: *Token, MaybeExprList: ?*NodeList, RParen: *Token) *Node { const node = try parser.createNode(Node.BuiltinCall); node.builtin_token = arg1; node.params = if (arg3) |p| p.* else NodeList.init(parser.allocator); node.rparen_token = arg4; result = &node.base; } // FunctionType fn Expr(FnProto: *Node.FnProto) *Node { result = &arg1.base; } // a[] fn Expr(Expr: *Node, LBracket: *Token, Expr: *Node, RBracket: *Token) *Node { const node = try parser.createNode(Node.SuffixOp); node.lhs = arg1; node.op = Node.SuffixOp.Op{ .ArrayAccess = arg3 }; node.rtoken = arg4; result = &node.base; } fn Expr(Expr: *Node, LBracket: *Token, Expr: *Node, Ellipsis2: *Token, RBracket: *Token) *Node { const node = try parser.createNode(Node.SuffixOp); node.lhs = arg1; node.op = Node.SuffixOp.Op{ .Slice = Node.SuffixOp.Op.Slice{ .start = arg3, .end = null } }; node.rtoken = arg5; result = &node.base; } fn Expr(Expr: *Node, LBracket: *Token, Expr: *Node, Ellipsis2: *Token, Expr: *Node, RBracket: *Token) *Node { const node = try parser.createNode(Node.SuffixOp); node.lhs = arg1; node.op = Node.SuffixOp.Op{ .Slice = Node.SuffixOp.Op.Slice{ .start = arg3, .end = arg5 } }; node.rtoken = arg6; result = &node.base; } // a.b fn Expr(Expr: *Node, Period: *Token, Identifier: *Token) *Node { const name = try parser.createNode(Node.Identifier); name.token = arg3; const infix = try parser.createNode(Node.InfixOp); infix.lhs = arg1; infix.op_token = arg2; infix.op = .Period; infix.rhs = &name.base; result = &infix.base; } // a.* fn Expr(Expr: *Node, PeriodAsterisk: *Token) *Node { const node = try parser.createNode(Node.SuffixOp); node.lhs = arg1; node.op = .Deref; node.rtoken = arg2; result = &node.base; } // a.? fn Expr(Expr: *Node, PeriodQuestionMark: *Token) *Node { const node = try parser.createNode(Node.SuffixOp); node.lhs = arg1; node.op = .UnwrapOptional; node.rtoken = arg2; result = &node.base; } // a() fn Expr(Expr: *Node, LParen: *Token, MaybeExprList: ?*NodeList, RParen: *Token) *Node { const node = try parser.createNode(Node.SuffixOp); node.lhs = arg1; node.op = Node.SuffixOp.Op{ .Call = Node.SuffixOp.Op.Call{ .params = if (arg3) |p| p.* else NodeList.init(parser.allocator) } }; node.rtoken = arg4; result = &node.base; } // Containers (struct/enum/union) fn Expr(ContainerDecl: *Node) *Node; fn ContainerDecl(ContainerDeclOp: *Token, LBrace: *Token, MaybeContainerMembers: ?*NodeList, RBrace: *Token) *Node { const node = try parser.createNode(Node.ContainerDecl); node.kind_token = arg1; node.init_arg_expr = .None; node.lbrace_token = arg2; node.fields_and_decls = if (arg3) |p| p.* else NodeList.init(parser.allocator); node.rbrace_token = arg4; result = &node.base; } fn ContainerDecl(ExternPacked: *Token, ContainerDeclOp: *Token, LBrace: *Token, MaybeContainerMembers: ?*NodeList, RBrace: *Token) *Node { const node = try parser.createNode(Node.ContainerDecl); node.layout_token = arg1; node.kind_token = arg2; node.init_arg_expr = .None; node.lbrace_token = arg3; node.fields_and_decls = if (arg4) |p| p.* else NodeList.init(parser.allocator); node.rbrace_token = arg5; result = &node.base; } fn ContainerDecl(Keyword_enum: *Token, ContainerDeclTypeType: *Node, LBrace: *Token, MaybeContainerMembers: ?*NodeList, RBrace: *Token) *Node { const node = try parser.createNode(Node.ContainerDecl); node.kind_token = arg1; node.init_arg_expr = Node.ContainerDecl.InitArg{ .Type = arg2 }; node.lbrace_token = arg3; node.fields_and_decls = if (arg4) |p| p.* else NodeList.init(parser.allocator); node.rbrace_token = arg5; result = &node.base; } fn ContainerDecl(ExternPacked: *Token, Keyword_enum: *Token, ContainerDeclTypeType: *Node, LBrace: *Token, MaybeContainerMembers: ?*NodeList, RBrace: *Token) *Node { const node = try parser.createNode(Node.ContainerDecl); node.layout_token = arg1; node.kind_token = arg2; node.init_arg_expr = Node.ContainerDecl.InitArg{ .Type = arg3 }; node.lbrace_token = arg4; node.fields_and_decls = if (arg5) |p| p.* else NodeList.init(parser.allocator); node.rbrace_token = arg6; result = &node.base; } fn ContainerDecl(Keyword_union: *Token, ContainerDeclTypeType: *Node, LBrace: *Token, MaybeContainerMembers: ?*NodeList, RBrace: *Token) *Node { const node = try parser.createNode(Node.ContainerDecl); node.kind_token = arg1; node.init_arg_expr = Node.ContainerDecl.InitArg{ .Type = arg2 }; node.lbrace_token = arg3; node.fields_and_decls = if (arg4) |p| p.* else NodeList.init(parser.allocator); node.rbrace_token = arg5; result = &node.base; } fn ContainerDecl(ExternPacked: *Token, Keyword_union: *Token, ContainerDeclTypeType: *Node, LBrace: *Token, MaybeContainerMembers: ?*NodeList, RBrace: *Token) *Node { const node = try parser.createNode(Node.ContainerDecl); node.layout_token = arg1; node.kind_token = arg2; node.init_arg_expr = Node.ContainerDecl.InitArg{ .Type = arg3 }; node.lbrace_token = arg4; node.fields_and_decls = if (arg5) |p| p.* else NodeList.init(parser.allocator); node.rbrace_token = arg6; result = &node.base; } fn ContainerDecl(Keyword_union: *Token, ContainerDeclTypeEnum: ?*Node, LBrace: *Token, MaybeContainerMembers: ?*NodeList, RBrace: *Token) *Node { const node = try parser.createNode(Node.ContainerDecl); node.kind_token = arg1; node.init_arg_expr = Node.ContainerDecl.InitArg{ .Enum = arg2 }; node.lbrace_token = arg3; node.fields_and_decls = if (arg4) |p| p.* else NodeList.init(parser.allocator); node.rbrace_token = arg5; result = &node.base; } fn ContainerDecl(ExternPacked: *Token, Keyword_union: *Token, ContainerDeclTypeEnum: ?*Node, LBrace: *Token, MaybeContainerMembers: ?*NodeList, RBrace: *Token) *Node { const node = try parser.createNode(Node.ContainerDecl); node.layout_token = arg1; node.kind_token = arg2; node.init_arg_expr = Node.ContainerDecl.InitArg{ .Enum = arg3 }; node.lbrace_token = arg4; node.fields_and_decls = if (arg5) |p| p.* else NodeList.init(parser.allocator); node.rbrace_token = arg6; result = &node.base; } // ContainerDecl helper fn ExternPacked(Keyword_extern: *Token) *Token; fn ExternPacked(Keyword_packed: *Token) *Token; fn SwitchExpr(Keyword_switch: *Token, LParen: *Token, Expr: *Node, RParen: *Token, LBrace: *Token, SwitchProngList: *NodeList, MaybeComma: ?*Token, RBrace: *Token) *Node { const node = try parser.createNode(Node.Switch); node.switch_token = arg1; node.expr = arg3; node.cases = arg6.*; node.rbrace = arg8; result = &node.base; } // Assembly fn String(StringLiteral: *Token) *Node { const node = try parser.createNode(Node.StringLiteral); node.token = arg1; result = &node.base; } fn String(MultilineStringLiteral: *TokenList) *Node { const node = try parser.createNode(Node.MultilineStringLiteral); node.lines = arg1.*; result = &node.base; } fn String(MultilineCStringLiteral: *TokenList) *Node { const node = try parser.createNode(Node.MultilineStringLiteral); node.lines = arg1.*; result = &node.base; } fn AsmExpr(Keyword_asm: *Token, MaybeVolatile: ?*Token, LParen: *Token, String: *Node, RParen: *Token) *Node { const node = try parser.createNode(Node.Asm); node.asm_token = arg1; node.volatile_token = arg2; node.template = arg4; node.outputs = NodeList.init(parser.allocator); node.inputs = NodeList.init(parser.allocator); node.clobbers = NodeList.init(parser.allocator); node.rparen = arg5; result = &node.base; } fn AsmExpr(Keyword_asm: *Token, MaybeVolatile: ?*Token, LParen: *Token, String: *Node, AsmOutput: ?*NodeList, RParen: *Token) *Node { const node = try parser.createNode(Node.Asm); node.asm_token = arg1; node.volatile_token = arg2; node.template = arg4; node.outputs = if (arg5) |p| p.* else NodeList.init(parser.allocator); node.inputs = NodeList.init(parser.allocator); node.clobbers = NodeList.init(parser.allocator); node.rparen = arg6; result = &node.base; } fn AsmExpr(Keyword_asm: *Token, MaybeVolatile: ?*Token, LParen: *Token, String: *Node, AsmOutput: ?*NodeList, AsmInput: ?*NodeList, RParen: *Token) *Node { const node = try parser.createNode(Node.Asm); node.asm_token = arg1; node.volatile_token = arg2; node.template = arg4; node.outputs = if (arg5) |p| p.* else NodeList.init(parser.allocator); node.inputs = if (arg6) |p| p.* else NodeList.init(parser.allocator); node.clobbers = NodeList.init(parser.allocator); node.rparen = arg7; result = &node.base; } fn AsmExpr(Keyword_asm: *Token, MaybeVolatile: ?*Token, LParen: *Token, String: *Node, AsmOutput: ?*NodeList, AsmInput: ?*NodeList, AsmClobber: ?*NodeList, RParen: *Token) *Node { const node = try parser.createNode(Node.Asm); node.asm_token = arg1; node.volatile_token = arg2; node.template = arg4; node.outputs = if (arg5) |p| p.* else NodeList.init(parser.allocator); node.inputs = if (arg6) |p| p.* else NodeList.init(parser.allocator); node.clobbers = if (arg7) |p| p.* else NodeList.init(parser.allocator); node.rparen = arg8; result = &node.base; } fn AsmOutput(Colon: *Token) ?*NodeList { result = null; } fn AsmOutput(Colon: *Token, AsmOutputList: *NodeList) ?*NodeList { result = arg2; } fn AsmOutputItem(LBracket: *Token, Identifier: *Token, RBracket: *Token, String: *Node, LParen: *Token, Identifier: *Token, RParen: *Token) *Node { const name = try parser.createNode(Node.Identifier); name.token = arg2; const variable = try parser.createNode(Node.Identifier); variable.token = arg6; const node = try parser.createNode(Node.AsmOutput); node.lbracket = arg1; node.symbolic_name = &name.base; node.constraint = arg4; node.kind = Node.AsmOutput.Kind{ .Variable = variable }; node.rparen = arg7; result = &node.base; } fn AsmOutputItem(LBracket: *Token, Identifier: *Token, RBracket: *Token, String: *Node, LParen: *Token, MinusAngleBracketRight: *Token, Expr: *Node, RParen: *Token) *Node { const name = try parser.createNode(Node.Identifier); name.token = arg2; const node = try parser.createNode(Node.AsmOutput); node.lbracket = arg1; node.symbolic_name = &name.base; node.constraint = arg4; node.kind = Node.AsmOutput.Kind{ .Return = arg7 }; node.rparen = arg8; result = &node.base; } fn AsmInput(Colon: *Token) ?*NodeList { result = null; } fn AsmInput(Colon: *Token, AsmInputList: *NodeList) ?*NodeList { result = arg2; } fn AsmInputItem(LBracket: *Token, Identifier: *Token, RBracket: *Token, String: *Node, LParen: *Token, Expr: *Node, RParen: *Token) *Node { const name = try parser.createNode(Node.Identifier); name.token = arg2; const node = try parser.createNode(Node.AsmInput); node.lbracket = arg1; node.symbolic_name = &name.base; node.constraint = arg4; node.expr = arg6; node.rparen = arg7; result = &node.base; } fn AsmClobber(Colon: *Token) ?*NodeList { result = null; } fn AsmClobber(Colon: *Token, StringList: *NodeList) ?*NodeList { result = arg2; } // Helper grammar fn BreakLabel(Colon: *Token, Identifier: *Token) *Node { const node = try parser.createNode(Node.Identifier); node.token = arg2; result = &node.base; } fn MaybeLinkSection() ?*Node; fn MaybeLinkSection(Keyword_linksection: *Token, LParen: *Token, Expr: *Node, RParen: *Token) ?*Node { result = arg3; } // Function specific fn FnCC(Keyword_nakedcc: *Token) *Token; fn FnCC(Keyword_stdcallcc: *Token) *Token; fn FnCC(Keyword_extern: *Token) *Token; fn FnCC(Keyword_async: *Token) *Token; fn ParamDecl(MaybeNoalias: ?*Token, ParamType: *Node.ParamDecl) *Node.ParamDecl { result = arg2; arg2.noalias_token = arg1; } fn ParamDecl(MaybeNoalias: ?*Token, Identifier: *Token, Colon: *Token, ParamType: *Node.ParamDecl) *Node.ParamDecl { result = arg4; arg4.noalias_token = arg1; arg4.name_token = arg2; } fn ParamDecl(MaybeNoalias: ?*Token, Keyword_comptime: *Token, Identifier: *Token, Colon: *Token, ParamType: *Node.ParamDecl) *Node.ParamDecl { result = arg5; arg5.noalias_token = arg1; arg5.comptime_token = arg2; arg5.name_token = arg3; } fn ParamType(Keyword_var: *Token) *Node.ParamDecl { const vtype = try parser.createNode(Node.VarType); vtype.token = arg1; const node = try parser.createNode(Node.ParamDecl); node.type_node = &vtype.base; result = node; } fn ParamType(Ellipsis3: *Token) *Node.ParamDecl { const node = try parser.createNode(Node.ParamDecl); node.var_args_token = arg1; result = node; } fn ParamType(Expr: *Node) *Node.ParamDecl { const node = try parser.createNode(Node.ParamDecl); node.type_node = arg1; result = node; } // Control flow prefixes fn IfPrefix(Keyword_if: *Token, LParen: *Token, Expr: *Node, RParen: *Token, MaybePtrPayload: ?*Node) *Node.If { const node = try parser.createNode(Node.If); node.if_token = arg1; node.condition = arg3; node.payload = arg5; result = node; } fn ForPrefix(Keyword_for: *Token, LParen: *Token, Expr: *Node, RParen: *Token, PtrIndexPayload: *Node) *Node.For { const node = try parser.createNode(Node.For); node.for_token = arg1; node.array_expr = arg3; node.payload = arg5; result = node; } fn WhilePrefix(Keyword_while: *Token, LParen: *Token, Expr: *Node, RParen: *Token, MaybePtrPayload: ?*Node) *Node.While { const node = try parser.createNode(Node.While); node.while_token = arg1; node.condition = arg3; node.payload = arg5; result = node; } fn WhilePrefix(Keyword_while: *Token, LParen: *Token, Expr: *Node, RParen: *Token, MaybePtrPayload: ?*Node, Colon: *Token, LParen: *Token, AssignExpr: *Node, RParen: *Token) *Node.While { const node = try parser.createNode(Node.While); node.while_token = arg1; node.condition = arg3; node.payload = arg5; node.continue_expr = arg8; result = node; } // Payloads fn MaybePayload() ?*Node; fn MaybePayload(Pipe: *Token, Identifier: *Token, Pipe: *Token) ?*Node { const name = try parser.createNode(Node.Identifier); name.token = arg2; const node = try parser.createNode(Node.Payload); node.lpipe = arg1; node.error_symbol = &name.base; node.rpipe = arg3; result = &node.base; } fn MaybePtrPayload() ?*Node; fn MaybePtrPayload(Pipe: *Token, Identifier: *Token, Pipe: *Token) ?*Node { const name = try parser.createNode(Node.Identifier); name.token = arg2; const node = try parser.createNode(Node.PointerPayload); node.lpipe = arg1; node.value_symbol = &name.base; node.rpipe = arg3; result = &node.base; } fn MaybePtrPayload(Pipe: *Token, Asterisk: *Token, Identifier: *Token, Pipe: *Token) ?*Node { const name = try parser.createNode(Node.Identifier); name.token = arg3; const node = try parser.createNode(Node.PointerPayload); node.lpipe = arg1; node.ptr_token = arg2; node.value_symbol = &name.base; node.rpipe = arg4; result = &node.base; } fn PtrIndexPayload(Pipe: *Token, Identifier: *Token, Pipe: *Token) *Node { const name = try parser.createNode(Node.Identifier); name.token = arg2; const node = try parser.createNode(Node.PointerIndexPayload); node.lpipe = arg1; node.value_symbol = &name.base; node.rpipe = arg3; result = &node.base; } fn PtrIndexPayload(Pipe: *Token, Asterisk: *Token, Identifier: *Token, Pipe: *Token) *Node { const name = try parser.createNode(Node.Identifier); name.token = arg3; const node = try parser.createNode(Node.PointerIndexPayload); node.lpipe = arg1; node.ptr_token = arg2; node.value_symbol = &name.base; node.rpipe = arg4; result = &node.base; } fn PtrIndexPayload(Pipe: *Token, Identifier: *Token, Comma: *Token, Identifier: *Token, Pipe: *Token) *Node { const name = try parser.createNode(Node.Identifier); name.token = arg2; const index = try parser.createNode(Node.Identifier); index.token = arg4; const node = try parser.createNode(Node.PointerIndexPayload); node.lpipe = arg1; node.value_symbol = &name.base; node.index_symbol = &index.base; node.rpipe = arg5; result = &node.base; } fn PtrIndexPayload(Pipe: *Token, Asterisk: *Token, Identifier: *Token, Comma: *Token, Identifier: *Token, Pipe: *Token) *Node { const name = try parser.createNode(Node.Identifier); name.token = arg3; const index = try parser.createNode(Node.Identifier); index.token = arg5; const node = try parser.createNode(Node.PointerIndexPayload); node.lpipe = arg1; node.ptr_token = arg2; node.value_symbol = &name.base; node.index_symbol = &index.base; node.rpipe = arg6; result = &node.base; } // Switch specific fn SwitchProng(SwitchCase: *Node.SwitchCase, EqualAngleBracketRight: *Token, MaybePtrPayload: ?*Node, AssignExpr: *Node) *Node { result = &arg1.base; arg1.arrow_token = arg2; arg1.payload = arg3; arg1.expr = arg4; } fn SwitchCase(Keyword_else: *Token) *Node.SwitchCase { const else_node = try parser.createNode(Node.SwitchElse); else_node.token = arg1; const node = try parser.createNode(Node.SwitchCase); node.items = NodeList.init(parser.allocator); try node.items.append(&else_node.base); result = node; } fn SwitchCase(SwitchItems: *NodeList, MaybeComma: ?*Token) *Node.SwitchCase { const node = try parser.createNode(Node.SwitchCase); node.items = arg1.*; result = node; } fn SwitchItems(SwitchItem: *Node) *NodeList { result = try parser.createListWithNode(NodeList, arg1); } fn SwitchItems(SwitchItems: *NodeList, Comma: *Token, SwitchItem: *Node) *NodeList { result = arg1; try arg1.append(arg3); } fn SwitchItem(Expr: *Node) *Node; fn SwitchItem(Expr: *Node, Ellipsis3: *Token, Expr: *Node) *Node { const node = try parser.createNode(Node.InfixOp); node.lhs = arg1; node.op_token = arg2; node.op = .Range; node.rhs = arg3; result = &node.base; } fn MaybeVolatile() ?*Token; fn MaybeVolatile(Keyword_volatile: *Token) ?*Token; fn MaybeAllowzero() ?*Token; fn MaybeAllowzero(Keyword_allowzero: *Token) ?*Token; // ContainerDecl specific fn ContainerDeclTypeEnum(LParen: *Token, Keyword_enum: *Token, RParen: *Token) ?*Node; fn ContainerDeclTypeEnum(LParen: *Token, Keyword_enum: *Token, LParen: *Token, Expr: *Node, RParen: *Token, RParen: *Token) ?*Node { result = arg4; } fn ContainerDeclTypeType(LParen: *Token, Expr: *Node, RParen: *Token) *Node { result = arg2; } fn ContainerDeclOp(Keyword_struct: *Token) *Token; fn ContainerDeclOp(Keyword_union: *Token) *Token; fn ContainerDeclOp(Keyword_enum: *Token) *Token; // Alignment fn MaybeByteAlign() ?*Node; fn MaybeByteAlign(Keyword_align: *Token, LParen: *Token, Expr: *Node, RParen: *Token) ?*Node { result = arg3; } fn MaybeAlign() ?*Node.PrefixOp.PtrInfo.Align; fn MaybeAlign(Keyword_align: *Token, LParen: *Token, Expr: *Node, RParen: *Token) ?*Node.PrefixOp.PtrInfo.Align { const value = try parser.createTemporary(Node.PrefixOp.PtrInfo.Align); value.node = arg3; result = value; } fn MaybeAlign(Keyword_align: *Token, LParen: *Token, Expr: *Node, Colon: *Token, IntegerLiteral: *Token, Colon: *Token, IntegerLiteral: *Token, RParen: *Token) ?*Node.PrefixOp.PtrInfo.Align { const start = try parser.createNode(Node.IntegerLiteral); start.token = arg5; const end = try parser.createNode(Node.IntegerLiteral); end.token = arg7; const value = try parser.createTemporary(Node.PrefixOp.PtrInfo.Align); value.node = arg3; value.bit_range = Node.PrefixOp.PtrInfo.Align.BitRange{ .start = &start.base, .end = &end.base }; result = value; } fn MaybeAlign(Keyword_align: *Token, LParen: *Token, Identifier: *Token, Colon: *Token, IntegerLiteral: *Token, Colon: *Token, IntegerLiteral: *Token, RParen: *Token) ?*Node.PrefixOp.PtrInfo.Align { const node = try parser.createNode(Node.Identifier); node.token = arg3; const start = try parser.createNode(Node.IntegerLiteral); start.token = arg5; const end = try parser.createNode(Node.IntegerLiteral); end.token = arg7; const value = try parser.createTemporary(Node.PrefixOp.PtrInfo.Align); value.node = &node.base; value.bit_range = Node.PrefixOp.PtrInfo.Align.BitRange{ .start = &start.base, .end = &end.base }; result = value; } // Lists fn ErrorTagList(MaybeDocComment: ?*Node.DocComment, Identifier: *Token) *NodeList { const node = try parser.createNode(Node.ErrorTag); node.doc_comments = arg1; node.name_token = arg2; result = try parser.createListWithNode(NodeList, &node.base); } fn ErrorTagList(ErrorTagList: *NodeList, Comma: *Token, MaybeDocComment: ?*Node.DocComment, Identifier: *Token) *NodeList { result = arg1; const node = try parser.createNode(Node.ErrorTag); node.doc_comments = arg3; node.name_token = arg4; try arg1.append(&node.base); } fn SwitchProngList(SwitchProng: *Node) *NodeList { result = try parser.createListWithNode(NodeList, arg1); } fn SwitchProngList(SwitchProngList: *NodeList, Comma: *Token, SwitchProng: *Node) *NodeList { result = arg1; try arg1.append(arg3); } fn AsmOutputList(AsmOutputItem: *Node) *NodeList { result = try parser.createListWithNode(NodeList, arg1); } fn AsmOutputList(AsmOutputList: *NodeList, Comma: *Token, AsmOutputItem: *Node) *NodeList { result = arg1; try arg1.append(arg3); } fn AsmInputList(AsmInputItem: *Node) *NodeList { result = try parser.createListWithNode(NodeList, arg1); } fn AsmInputList(AsmInputList: *NodeList, Comma: *Token, AsmInputItem: *Node) *NodeList { result = arg1; try arg1.append(arg3); } fn StringList(StringLiteral: *Token) *NodeList { const node = try parser.createNode(Node.StringLiteral); node.token = arg1; result = try parser.createListWithNode(NodeList, &node.base); } fn StringList(StringList: *NodeList, Comma: *Token, StringLiteral: *Token) *NodeList { result = arg1; const node = try parser.createNode(Node.StringLiteral); node.token = arg3; try arg1.append(&node.base); } fn MaybeParamDeclList() ?*NodeList; fn MaybeParamDeclList(ParamDeclList: *NodeList, MaybeComma: ?*Token) *NodeList { result = arg1; } fn ParamDeclList(MaybeDocComment: ?*Node.DocComment, ParamDecl: *Node.ParamDecl) *NodeList { arg2.doc_comments = arg1; result = try parser.createListWithNode(NodeList, &arg2.base); } fn ParamDeclList(ParamDeclList: *NodeList, Comma: *Token, MaybeDocComment: ?*Node.DocComment, ParamDecl: *Node.ParamDecl) *NodeList { result = arg1; arg4.doc_comments = arg3; try arg1.append(&arg4.base); } fn MaybeExprList() ?*NodeList {} fn MaybeExprList(ExprList: *NodeList, MaybeComma: ?*Token) ?*NodeList { result = arg1; } fn ExprList(Expr: *Node) *NodeList { result = try parser.createListWithNode(NodeList, arg1); } fn ExprList(ExprList: *NodeList, Comma: *Token, Expr: *Node) *NodeList { result = arg1; try arg1.append(arg3); } fn InitList(Expr: *Node) *NodeList { result = try parser.createListWithNode(NodeList, arg1); } fn InitList(Period: *Token, Identifier: *Token, Equal: *Token, Expr: *Node) *NodeList { const node = try parser.createNode(Node.FieldInitializer); node.period_token = arg1; node.name_token = arg2; node.expr = arg4; result = try parser.createListWithNode(NodeList, &node.base); } fn InitList(InitList: *NodeList, Comma: *Token, Expr: *Node) *NodeList { result = arg1; try arg1.append(arg3); } fn InitList(InitList: *NodeList, Comma: *Token, Period: *Token, Identifier: *Token, Equal: *Token, Expr: *Node) *NodeList { result = arg1; const node = try parser.createNode(Node.FieldInitializer); node.period_token = arg3; node.name_token = arg4; node.expr = arg6; try arg1.append(&node.base); } // Various helpers fn MaybePub() ?*Token; fn MaybePub(Keyword_pub: *Token) ?*Token; fn MaybeColonTypeExpr() ?*Node; fn MaybeColonTypeExpr(Colon: *Token, Expr: *Node) ?*Node { result = arg2; } fn MaybeExpr() ?*Node; fn MaybeExpr(Expr: *Node) ?*Node; fn MaybeNoalias() ?*Token; fn MaybeNoalias(Keyword_noalias: *Token) ?*Token; fn MaybeInline() ?*Token; fn MaybeInline(Keyword_inline: *Token) ?*Token; fn MaybeIdentifier() ?*Token; fn MaybeIdentifier(Identifier: *Token) ?*Token; fn MaybeComma() ?*Token; fn MaybeComma(Comma: *Token) ?*Token; fn MaybeConst() ?*Token; fn MaybeConst(Keyword_const: *Token) ?*Token; fn MultilineStringLiteral(LineString: *Token) *TokenList { result = try parser.createListWithToken(TokenList, arg1); } fn MultilineStringLiteral(MultilineStringLiteral: *TokenList, LineString: *Token) *TokenList { result = arg1; try arg1.append(arg2); } fn MultilineCStringLiteral(LineCString: *Token) *TokenList { result = try parser.createListWithToken(TokenList, arg1); } fn MultilineCStringLiteral(MultilineCStringLiteral: *TokenList, LineCString: *Token) *TokenList { result = arg1; try arg1.append(arg2); } };
zig/ziglang.zig
const std = @import("std"); const unitbounds = @import("unitbounds.zig"); const Allocator = std.mem.Allocator; pub fn Screen(comptime Cell: type) type { return struct { const Self = @This(); allocator: *Allocator, cells: []Cell, width: usize, height: usize, ub: unitbounds.Pos01ToIndex, pub fn init(allocator: *Allocator, width: usize, height: usize, default: Cell) !Self { const count = width * height; var cells = try allocator.alloc(Cell, count); errdefer allocator.free(cells); for (cells) |*cell| { cell.* = default; } return Self{ .allocator = allocator, .cells = cells, .width = width, .height = height, .ub = unitbounds.Pos01ToIndex.forCenter(width, height, 0), }; } pub fn deinit(self: *const Self) void { self.allocator.free(self.cells); } pub fn indexRef(self: *Self, i: ?usize) ?*Cell { if (i) |j| { return &self.cells[j]; } return null; } pub fn getIndex(self: *const Self, i: ?usize) ?Cell { if (i) |j| { return self.cells[j]; } return null; } pub fn ref(self: *Self, x: f64, y: f64) ?*Cell { return self.indexRef(self.ub.index(x, y)); } pub fn get(self: *const Self, x: f64, y: f64) ?Cell { return self.getIndex(self.ub.index(x, y)); } pub fn refi(self: *Self, xi: isize, yi: isize) ?*Cell { return self.indexRef(self.ub.res.indexi(xi, yi)); } pub fn geti(self: *const Self, xi: isize, yi: isize) ?Cell { return self.getIndex(self.ub.res.indexi(xi, yi)); } pub fn getOff(self: *const Self, x: f64, y: f64, xo: isize, yo: isize) ?Cell { return self.getIndex(self.ub.indexOff(x, y, xo, yo)); } pub fn refOff(self: *Self, x: f64, y: f64, xo: isize, yo: isize) ?*Cell { return self.indexRef(self.ub.indexOff(x, y, xo, yo)); } pub const Offset = unitbounds.Pos01ToIndex.Offset; pub fn getOffsets(self: *const Self, x: f64, y: f64, comptime n: usize, comptime offsets: [n]Offset) [n]?Cell { var result = [_]?Cell{null} ** n; for (self.ub.indexOffsets(x, y, n, offsets)) |index, i| { result[i] = self.getIndex(index); } return result; } pub fn refOffsets(self: *const Self, x: f64, y: f64, comptime n: usize, comptime offsets: [n]Offset) [n]?*Cell { var result = [_]?Cell{null} ** n; for (self.ub.indexOffsets(x, y, n, offsets)) |index, i| { result[i] = self.indexRef(index); } return result; } pub fn neighbors4(self: *const Self, x: f64, y: f64) [4]?Cell { return self.getOffsets(x, y, 4, unitbounds.Pos01ToIndex.neighbors4); } pub fn neighbors5(self: *const Self, x: f64, y: f64) [5]?Cell { return self.getOffsets(x, y, 5, unitbounds.Pos01ToIndex.neighbors5); } pub fn neighbors8(self: *const Self, x: f64, y: f64) [8]?Cell { return self.getOffsets(x, y, 8, unitbounds.Pos01ToIndex.neighbors8); } pub fn neighbors9(self: *const Self, x: f64, y: f64) [9]?Cell { return self.getOffsets(x, y, 9, unitbounds.Pos01ToIndex.neighbors9); } }; }
lib/screen.zig
const std = @import("std"); /// The only output of the tokenizer. pub const ZNodeToken = struct { const Self = @This(); /// 0 is root, 1 is top level children. depth: usize, /// The extent of the slice. start: usize, end: usize, }; /// Parses text outputting ZNodeTokens. Does not convert strings to numbers, and all strings are /// "as is", no escaping is performed. pub const StreamingParser = struct { const Self = @This(); state: State, start_index: usize, current_index: usize, // The maximum node depth. max_depth: usize, // The current line's depth. line_depth: usize, // The current node depth. node_depth: usize, /// Level of multiline string. open_string_level: usize, /// Current level of multiline string close. close_string_level: usize, /// Account for any extra spaces trailing at the end of a word. trailing_spaces: usize, pub const Error = error{ TooMuchIndentation, InvalidWhitespace, OddIndentationValue, InvalidQuotation, InvalidMultilineOpen, InvalidMultilineClose, InvalidNewLineInString, InvalidCharacterAfterString, SemicolonWentPastRoot, UnexpectedEof, }; pub const State = enum { /// Whether we're starting on an openline. OpenLine, ExpectZNode, Indent, OpenCharacter, Quotation, SingleLineCharacter, MultilineOpen0, MultilineOpen1, MultilineLevelOpen, MultilineLevelClose, MultilineClose0, MultilineCharacter, EndString, OpenComment, Comment, }; /// Returns a blank parser. pub fn init() Self { var self: StreamingParser = undefined; self.reset(); return self; } /// Resets the parser back to the beginning state. pub fn reset(self: *Self) void { self.state = .OpenLine; self.start_index = 0; self.current_index = 0; self.max_depth = 0; self.line_depth = 0; self.node_depth = 0; self.open_string_level = 0; self.close_string_level = 0; self.trailing_spaces = 0; } pub fn completeOrError(self: *const Self) !void { switch (self.state) { .ExpectZNode, .OpenLine, .EndString, .Comment, .OpenComment, .Indent => {}, else => return Error.UnexpectedEof, } } /// Feeds a character to the parser. May output a ZNode. Check "hasCompleted" to see if there /// are any unfinished strings. pub fn feed(self: *Self, c: u8) Error!?ZNodeToken { defer self.current_index += 1; //std.debug.print("FEED<{}> {} {} ({c})\n", .{self.state, self.current_index, c, c}); switch (self.state) { .OpenComment, .Comment => switch (c) { '\n' => { self.start_index = self.current_index + 1; // We're ending a line with nodes. if (self.state == .Comment) { self.max_depth = self.line_depth + 1; } self.node_depth = 0; self.line_depth = 0; self.state = .OpenLine; }, else => { // Skip. }, }, // All basically act the same except for a few minor differences. .ExpectZNode, .OpenLine, .EndString, .OpenCharacter => switch (c) { '#' => { if (self.state == .OpenLine) { self.state = .OpenComment; } else { defer self.state = .Comment; if (self.state == .OpenCharacter) { return ZNodeToken{ .depth = self.line_depth + self.node_depth + 1, .start = self.start_index, .end = self.current_index - self.trailing_spaces, }; } } }, // The tricky character (and other whitespace). ' ' => { if (self.state == .OpenLine) { if (self.line_depth >= self.max_depth) { return Error.TooMuchIndentation; } self.state = .Indent; } else if (self.state == .OpenCharacter) { self.trailing_spaces += 1; } else { // Skip spaces when expecting a node on a closed line, // including this one. self.start_index = self.current_index + 1; } }, ':' => { defer self.state = .ExpectZNode; const node = ZNodeToken{ .depth = self.line_depth + self.node_depth + 1, .start = self.start_index, .end = self.current_index - self.trailing_spaces, }; self.start_index = self.current_index + 1; self.node_depth += 1; // Only return when we're not at end of a string. if (self.state != .EndString) { return node; } }, ',' => { defer self.state = .ExpectZNode; const node = ZNodeToken{ .depth = self.line_depth + self.node_depth + 1, .start = self.start_index, .end = self.current_index - self.trailing_spaces, }; self.start_index = self.current_index + 1; // Only return when we're not at end of a string. if (self.state != .EndString) { return node; } }, ';' => { if (self.node_depth == 0) { return Error.SemicolonWentPastRoot; } defer self.state = .ExpectZNode; const node = ZNodeToken{ .depth = self.line_depth + self.node_depth + 1, .start = self.start_index, .end = self.current_index - self.trailing_spaces, }; self.start_index = self.current_index + 1; self.node_depth -= 1; // Only return when we're not at end of a string, or in semicolons // special case, when we don't have an empty string. if (self.state != .EndString and node.start < node.end) { return node; } }, '"' => { if (self.state == .EndString) { return Error.InvalidCharacterAfterString; } // Don't start another string. if (self.state == .OpenCharacter) { return null; } // We start here to account for the possibility of a string being "" self.start_index = self.current_index + 1; self.state = .Quotation; }, '[' => { if (self.state == .EndString) { return Error.InvalidCharacterAfterString; } // Don't start another string. if (self.state == .OpenCharacter) { return null; } self.open_string_level = 0; self.state = .MultilineOpen0; }, '\n' => { defer self.state = .OpenLine; const node = ZNodeToken{ .depth = self.line_depth + self.node_depth + 1, .start = self.start_index, .end = self.current_index - self.trailing_spaces, }; self.start_index = self.current_index + 1; // Only reset on a non open line. if (self.state != .OpenLine) { self.max_depth = self.line_depth + 1; self.line_depth = 0; } self.node_depth = 0; // Only return something if there is something. Quoted strings are good. if (self.state == .OpenCharacter) { return node; } }, '\t', '\r' => { return Error.InvalidWhitespace; }, else => { // We already have a string. if (self.state == .EndString) { return Error.InvalidCharacterAfterString; } // Don't reset if we're in a string. if (self.state != .OpenCharacter) { self.start_index = self.current_index; } self.trailing_spaces = 0; self.state = .OpenCharacter; }, }, .Indent => switch (c) { ' ' => { self.start_index = self.current_index + 1; self.line_depth += 1; self.state = .OpenLine; }, else => { return Error.OddIndentationValue; }, }, .Quotation => switch (c) { '"' => { self.state = .EndString; const node = ZNodeToken{ .depth = self.line_depth + self.node_depth + 1, .start = self.start_index, .end = self.current_index, }; // Reset because we're going to expecting nodes. self.start_index = self.current_index + 1; return node; }, else => { self.state = .SingleLineCharacter; }, }, .SingleLineCharacter => switch (c) { '"' => { self.state = .EndString; const node = ZNodeToken{ .depth = self.line_depth + self.node_depth + 1, .start = self.start_index, .end = self.current_index, }; // Reset because we're going to expecting nodes. self.start_index = self.current_index + 1; return node; }, '\n' => { return Error.InvalidNewLineInString; }, else => { // Consume. }, }, .MultilineOpen0, .MultilineLevelOpen => switch (c) { '=' => { self.open_string_level += 1; self.state = .MultilineLevelOpen; }, '[' => { self.start_index = self.current_index + 1; self.state = .MultilineOpen1; }, else => { return Error.InvalidMultilineOpen; }, }, .MultilineOpen1 => switch (c) { ']' => { self.state = .MultilineClose0; }, '\n' => { // Skip first newline. self.start_index = self.current_index + 1; }, else => { self.state = .MultilineCharacter; }, }, .MultilineCharacter => switch (c) { ']' => { self.close_string_level = 0; self.state = .MultilineClose0; }, else => { // Capture EVERYTHING. }, }, .MultilineClose0, .MultilineLevelClose => switch (c) { '=' => { self.close_string_level += 1; self.state = .MultilineLevelClose; }, ']' => { if (self.close_string_level == self.open_string_level) { self.state = .EndString; return ZNodeToken{ .depth = self.line_depth + self.node_depth + 1, .start = self.start_index, .end = self.current_index - self.open_string_level - 1, }; } self.state = .MultilineCharacter; }, else => { return Error.InvalidMultilineClose; }, }, } return null; } }; fn testNextTextOrError(stream: *StreamingParser, idx: *usize, text: []const u8) ![]const u8 { while (idx.* < text.len) { const node = try stream.feed(text[idx.*]); idx.* += 1; if (node) |n| { //std.debug.print("TOKEN {}\n", .{text[n.start..n.end]}); return text[n.start..n.end]; } } return error.ExhaustedLoop; } test "parsing slice output" { const testing = std.testing; const text = \\# woo comment \\mp:10 \\[[sy]] \\ # another \\ : n : "en" , [[m]] \\ "sc" : [[10]] , g #inline \\ [[]]:[==[ \\hi]==] ; var idx: usize = 0; var stream = StreamingParser.init(); try testing.expectEqualSlices(u8, "mp", try testNextTextOrError(&stream, &idx, text)); try testing.expectEqualSlices(u8, "10", try testNextTextOrError(&stream, &idx, text)); try testing.expectEqualSlices(u8, "sy", try testNextTextOrError(&stream, &idx, text)); try testing.expectEqualSlices(u8, "", try testNextTextOrError(&stream, &idx, text)); try testing.expectEqualSlices(u8, "n", try testNextTextOrError(&stream, &idx, text)); try testing.expectEqualSlices(u8, "en", try testNextTextOrError(&stream, &idx, text)); try testing.expectEqualSlices(u8, "m", try testNextTextOrError(&stream, &idx, text)); try testing.expectEqualSlices(u8, "sc", try testNextTextOrError(&stream, &idx, text)); try testing.expectEqualSlices(u8, "10", try testNextTextOrError(&stream, &idx, text)); try testing.expectEqualSlices(u8, "g", try testNextTextOrError(&stream, &idx, text)); try testing.expectEqualSlices(u8, "", try testNextTextOrError(&stream, &idx, text)); try testing.expectEqualSlices(u8, "hi", try testNextTextOrError(&stream, &idx, text)); } fn testNextLevelOrError(stream: *StreamingParser, idx: *usize, text: []const u8) !usize { while (idx.* < text.len) { const node = try stream.feed(text[idx.*]); idx.* += 1; if (node) |n| { return n.depth; } } return error.ExhaustedLoop; } test "parsing depths" { const testing = std.testing; const text = \\# woo comment \\mp:10 \\[[sy]] \\ # another \\ : n : "en" , [[m]] \\ # more \\ \\ # even more \\ \\ "sc" : [[10]] , g #inline \\ [[]]:[==[ \\hi]==] ; var idx: usize = 0; var stream = StreamingParser.init(); try testing.expectEqual(try testNextLevelOrError(&stream, &idx, text), 1); try testing.expectEqual(try testNextLevelOrError(&stream, &idx, text), 2); try testing.expectEqual(try testNextLevelOrError(&stream, &idx, text), 1); try testing.expectEqual(try testNextLevelOrError(&stream, &idx, text), 2); try testing.expectEqual(try testNextLevelOrError(&stream, &idx, text), 3); try testing.expectEqual(try testNextLevelOrError(&stream, &idx, text), 4); try testing.expectEqual(try testNextLevelOrError(&stream, &idx, text), 4); try testing.expectEqual(try testNextLevelOrError(&stream, &idx, text), 3); try testing.expectEqual(try testNextLevelOrError(&stream, &idx, text), 4); try testing.expectEqual(try testNextLevelOrError(&stream, &idx, text), 4); try testing.expectEqual(try testNextLevelOrError(&stream, &idx, text), 2); try testing.expectEqual(try testNextLevelOrError(&stream, &idx, text), 3); } /// Parses the stream, outputting ZNodeTokens which reference the text. pub fn parseStream(stream: *StreamingParser, idx: *usize, text: []const u8) !?ZNodeToken { while (idx.* <= text.len) { // Insert an extra newline at the end of the stream. const node = if (idx.* == text.len) try stream.feed('\n') else try stream.feed(text[idx.*]); idx.* += 1; if (node) |n| { return n; } } return null; } /// A `ZNode`'s value. pub const ZValue = union(enum) { const Self = @This(); Null, String: []const u8, Int: i32, Float: f32, Bool: bool, /// Checks a ZValues equality. pub fn equals(self: Self, other: Self) bool { if (self == .Null and other == .Null) { return true; } if (self == .String and other == .String) { return std.mem.eql(u8, self.String, other.String); } if (self == .Int and other == .Int) { return self.Int == other.Int; } if (self == .Float and other == .Float) { return std.math.approxEq(f32, self.Float, other.Float, std.math.f32_epsilon); } if (self == .Bool and other == .Bool) { return self.Bool == other.Bool; } return false; } /// Outputs a value to the `out_stream`. This output is parsable. pub fn stringify(self: Self, out_stream: anytype) @TypeOf(out_stream).Error!void { switch (self) { .Null => { // Skip. }, .String => { const find = std.mem.indexOfScalar; const chars = "\"\n\t\r,:;"; const chars_count = @sizeOf(@TypeOf(chars)); var need_escape = false; var found = [_]bool{false} ** chars_count; for ("\"\n\t\r,:;") |ch, i| { const f = find(u8, self.String, ch); if (f != null) { found[i] = true; need_escape = true; } } // TODO: Escaping ]] in string. if (need_escape) { // 0=" 1=\n if (found[0] or found[1]) { // Escape with Lua. try out_stream.writeAll("[["); const ret = try out_stream.writeAll(self.String); try out_stream.writeAll("]]"); return ret; } else { // Escape with basic quotes. try out_stream.writeAll("\""); const ret = try out_stream.writeAll(self.String); try out_stream.writeAll("\""); return ret; } } return try out_stream.writeAll(self.String); }, .Int => { return std.fmt.formatIntValue(self.Int, "", std.fmt.FormatOptions{}, out_stream); }, .Float => { return std.fmt.formatFloatScientific(self.Float, std.fmt.FormatOptions{}, out_stream); }, .Bool => { return out_stream.writeAll(if (self.Bool) "true" else "false"); }, } } /// pub fn format(self: Self, comptime fmt: []const u8, options: std.fmt.FormatOptions, writer: anytype) !void { _ = fmt; _ = options; switch (self) { .Null => try std.fmt.format(writer, ".Null", .{}), .String => try std.fmt.format(writer, ".String({s})", .{self.String}), .Int => try std.fmt.format(writer, ".Int({})", .{self.Int}), .Float => try std.fmt.format(writer, ".Float({})", .{self.Float}), .Bool => try std.fmt.format(writer, ".Bool({})", .{self.Bool}), } } }; /// Result of imprinting pub fn Imprint(comptime T: type) type { return struct { result: T, arena: std.heap.ArenaAllocator, }; } pub const ImprintError = error{ ExpectedBoolNode, ExpectedFloatNode, ExpectedUnsignedIntNode, ExpectedIntNode, ExpectedIntOrStringNode, ExpectedStringNode, FailedToConvertStringToEnum, FailedToConvertIntToEnum, FieldNodeDoesNotExist, ValueNodeDoesNotExist, ArrayElemDoesNotExist, OutOfMemory, InvalidPointerType, InvalidType, }; /// Represents a node in a static tree. Nodes have a parent, child, and sibling pointer /// to a spot in the array. pub const ZNode = struct { const Self = @This(); value: ZValue = .Null, parent: ?*ZNode = null, sibling: ?*ZNode = null, child: ?*ZNode = null, /// Returns the next Node in the tree. Will return Null after reaching root. For nodes further /// down the tree, they will bubble up, resulting in a negative depth. Self is considered to be /// at depth 0. pub fn next(self: *const Self, depth: *isize) ?*ZNode { if (self.child) |c| { depth.* += 1; return c; } else if (self.sibling) |c| { return c; } else { // Go up and forward. var iter: ?*const ZNode = self; while (iter != null) { iter = iter.?.parent; if (iter != null) { depth.* -= 1; if (iter.?.sibling) |c| { return c; } } } return null; } } /// Returns the next node in the tree until reaching root or the stopper node. pub fn nextUntil(self: *const Self, stopper: *const ZNode, depth: *isize) ?*ZNode { if (self.child) |c| { if (c == stopper) { return null; } depth.* += 1; return c; } else if (self.sibling) |c| { if (c == stopper) { return null; } return c; } else { // Go up and forward. var iter: ?*const ZNode = self; while (iter != null) { iter = iter.?.parent; // All these checks. :/ if (iter == stopper) { return null; } if (iter != null) { depth.* -= 1; if (iter.?.sibling) |c| { if (c == stopper) { return null; } return c; } } } return null; } } /// Iterates this node's children. Pass null to start. `iter = node.nextChild(iter);` pub fn nextChild(self: *const Self, iter: ?*const ZNode) ?*ZNode { if (iter) |it| { return it.sibling; } else { return self.child; } } /// Returns the nth child's value. Or null if neither the node or child exist. pub fn getChildValue(self: *const Self, nth: usize) ?Value { var count: usize = 0; var iter: ?*ZNode = self.child; while (iter) |n| { if (count == nth) { if (n.child) |c| { return c.value; } else { return null; } } count += 1; iter = n.sibling; } return null; } /// Returns the nth child. O(n) pub fn getChild(self: *const Self, nth: usize) ?*ZNode { var count: usize = 0; var iter: ?*ZNode = self.child; while (iter) |n| { if (count == nth) { return n; } count += 1; iter = n.sibling; } return null; } /// Returns the number of children. O(n) pub fn getChildCount(self: *const Self) usize { var count: usize = 0; var iter: ?*ZNode = self.child; while (iter) |n| { count += 1; iter = n.sibling; } return count; } /// Finds the next child after the given iterator. This is good for when you can guess the order /// of the nodes, which can cut down on starting from the beginning. Passing null starts over /// from the beginning. Returns the found node or null (it will loop back around). pub fn findNextChild(self: *const Self, start: ?*const ZNode, value: ZValue) ?*ZNode { var iter: ?*ZNode = self.child; if (start) |si| { iter = si.sibling; } while (iter != start) { if (iter) |it| { if (it.value.equals(value)) { return it; } iter = it.sibling; } else { // Loop back. iter = self.child; } } return null; } /// Finds the nth child node with a specific tag. pub fn findNthAny(self: *const Self, nth: usize, tag: std.meta.Tag(ZValue)) ?*ZNode { var count: usize = 0; var iter: ?*ZNode = self.child; while (iter) |n| { if (n.value == tag) { if (count == nth) { return n; } count += 1; } iter = n.sibling; } return null; } /// Finds the nth child node with a specific value. pub fn findNth(self: *const Self, nth: usize, value: ZValue) ?*ZNode { var count: usize = 0; var iter: ?*ZNode = self.child orelse return null; while (iter) |n| { if (n.value.equals(value)) { if (count == nth) { return n; } count += 1; } iter = n.sibling; } return null; } /// Traverses descendants until a node with the tag is found. pub fn findNthAnyDescendant(self: *const Self, nth: usize, value: std.meta.Tag(ZValue)) ?*ZNode { _ = value; var depth: isize = 0; var count: usize = 0; var iter: *const ZNode = self; while (iter.nextUntil(self, &depth)) |n| : (iter = n) { if (n.value == tag) { if (count == nth) { return n; } count += 1; } } return null; } /// Traverses descendants until a node with the specific value is found. pub fn findNthDescendant(self: *const Self, nth: usize, value: ZValue) ?*ZNode { var depth: isize = 0; var count: usize = 0; var iter: *const ZNode = self; while (iter.nextUntil(self, &depth)) |n| : (iter = n) { if (n.value.equals(value)) { if (count == nth) { return n; } count += 1; } } return null; } /// Converts strings to specific types. This just tries converting the string to an int, then /// float, then bool. Booleans are only the string values "true" or "false". pub fn convertStrings(self: *const Self) void { var depth: isize = 0; var iter: *const ZNode = self; while (iter.nextUntil(self, &depth)) |c| : (iter = c) { if (c.value != .String) { continue; } // Try to cast to numbers, then true/false checks, then string. const slice = c.value.String; const integer = std.fmt.parseInt(i32, slice, 10) catch { const float = std.fmt.parseFloat(f32, slice) catch { if (std.mem.eql(u8, "true", slice)) { c.value = ZValue{ .Bool = true }; } else if (std.mem.eql(u8, "false", slice)) { c.value = ZValue{ .Bool = false }; } else { // Keep the value. } continue; }; c.value = ZValue{ .Float = float }; continue; }; c.value = ZValue{ .Int = integer }; } } fn imprint_(self: *const Self, comptime T: type, allocator: ?*std.mem.Allocator) ImprintError!T { const TI = @typeInfo(T); switch (TI) { .Void => {}, .Bool => { return switch (self.value) { .Bool => |b| b, else => ImprintError.ExpectedBoolNode, }; }, .Float, .ComptimeFloat => { return switch (self.value) { .Float => |n| @floatCast(T, n), .Int => |n| @intToFloat(T, n), else => ImprintError.ExpectedFloatNode, }; }, .Int, .ComptimeInt => { const is_signed = (TI == .Int and TI.Int.signedness == .signed) or (TI == .ComptimeInt and TI.CompTimeInt.is_signed); switch (self.value) { .Int => |n| { if (is_signed) { return @intCast(T, n); } else { if (n < 0) { return ImprintError.ExpectedUnsignedIntNode; } return @intCast(T, n); } }, else => return ImprintError.ExpectedIntNode, } }, .Enum => { switch (self.value) { .Int => |int| { return std.meta.intToEnum(T, int) catch { return ImprintError.FailedToConvertIntToEnum; }; }, .String => { if (std.meta.stringToEnum(T, self.value.String)) |e| { return e; } else { return ImprintError.FailedToConvertStringToEnum; } }, else => return ImprintError.ExpectedIntOrStringNode, } }, .Optional => |opt_info| { const CI = @typeInfo(opt_info.child); // Aggregate types have a null root, so could still exist. if (self.value != .Null or CI == .Array or CI == .Struct or (CI == .Pointer and CI.Pointer.size == .Slice)) { return try self.imprint_(opt_info.child, allocator); } else { return null; } }, .Struct => |struct_info| { var iter: ?*const ZNode = null; var result: T = .{}; inline for (struct_info.fields) |field| { // Skip underscores. if (field.name[0] == '_') { continue; } const found = self.findNextChild(iter, .{ .String = field.name }); if (found) |child_node| { if (@typeInfo(field.field_type) == .Struct) { @field(result, field.name) = try child_node.imprint_(field.field_type, allocator); } else { if (child_node.child) |value_node| { @field(result, field.name) = try value_node.imprint_(field.field_type, allocator); } } // Found, set the iterator here. iter = found; } } return result; }, // Only handle [N]?T, where T is any other valid type. .Array => |array_info| { // Arrays are weird. They work on siblings. // TODO: For some types this causes a crash like [N]fn() void types. var r: T = std.mem.zeroes(T); var iter: ?*const ZNode = self; comptime var i: usize = 0; inline while (i < array_info.len) : (i += 1) { if (iter) |it| { r[i] = try it.imprint_(array_info.child, allocator); } if (iter) |it| { iter = it.sibling; } } return r; }, .Pointer => |ptr_info| { switch (ptr_info.size) { .One => { if (ptr_info.child == ZNode) { // This is an odd case because we usually pass the child of a node // for the value, but here since we explicitely asked for the node, // it likely means the top. By taking the parent we force ZNodes // only working when part of a large struct and not stand alone. // // Something like this wouldn't work: ``` // root.imprint(*ZNode); // ``` return self.parent.?; } else if (allocator) |alloc| { var ptr = try alloc.create(ptr_info.child); ptr.* = try self.imprint_(ptr_info.child, allocator); return ptr; } else { return ImprintError.InvalidPointerType; } }, .Slice => { if (ptr_info.child == u8) { switch (self.value) { .String => { if (allocator) |alloc| { return try std.mem.dupe(alloc, u8, self.value.String); } else { return self.value.String; } }, else => return ImprintError.ExpectedStringNode, } } else if (allocator) |alloc| { // Same as pointer above. We take parent. var ret = try alloc.alloc(ptr_info.child, self.parent.?.getChildCount()); var iter: ?*const ZNode = self; var i: usize = 0; while (i < ret.len) : (i += 1) { if (iter) |it| { ret[i] = try it.imprint_(ptr_info.child, allocator); } else { if (@typeInfo(ptr_info.child) == .Optional) { ret[i] = null; } else { return ImprintError.ArrayElemDoesNotExist; } } if (iter) |it| { iter = it.sibling; } } return ret; } else { return ImprintError.InvalidType; } }, else => return ImprintError.InvalidType, } }, else => return ImprintError.InvalidType, } } pub fn imprint(self: *const Self, comptime T: type) ImprintError!T { return try self.imprint_(T, null); } pub fn imprintAlloc(self: *const Self, comptime T: type, allocator: *std.mem.Allocator) ImprintError!Imprint(T) { var arena = std.heap.ArenaAllocator.init(allocator); errdefer { // Free everything. arena.deinit(); } return Imprint(T){ .result = try self.imprint_(T, &arena.allocator), .arena = arena, }; } /// Outputs a `ZNode` and its children on a single line. This can be parsed back. pub fn stringify(self: *const Self, out_stream: anytype) @TypeOf(out_stream).Error!void { // Likely not root. if (self.value != .Null) { try self.value.stringify(out_stream); try out_stream.writeAll(":"); } var depth: isize = 0; var last_depth: isize = 1; var iter = self; while (iter.nextUntil(self, &depth)) |n| : (iter = n) { if (depth > last_depth) { last_depth = depth; try out_stream.writeAll(":"); } else if (depth < last_depth) { while (depth < last_depth) { try out_stream.writeAll(";"); last_depth -= 1; } } else if (depth > 1) { try out_stream.writeAll(","); } try n.value.stringify(out_stream); } } /// Returns true if node has more than one descendant (child, grandchild, etc). fn _moreThanOneDescendant(self: *const Self) bool { var depth: isize = 0; var count: usize = 0; var iter: *const ZNode = self; while (iter.nextUntil(self, &depth)) |n| : (iter = n) { count += 1; if (count > 1) { return true; } } return false; } fn _stringifyPretty(self: *const Self, out_stream: anytype) @TypeOf(out_stream).Error!void { try self.value.stringify(out_stream); try out_stream.writeAll(":"); var depth: isize = 0; var last_depth: isize = 1; var iter = self; while (iter.nextUntil(self, &depth)) |n| : (iter = n) { if (depth > last_depth) { last_depth = depth; try out_stream.writeAll(":"); // Likely an array. if (n.parent.?.value == .Null) { try out_stream.writeAll(" "); } else if (n.parent.?._moreThanOneDescendant()) { try out_stream.writeAll("\n"); try out_stream.writeByteNTimes(' ', 2 * @bitCast(usize, depth)); } else { try out_stream.writeAll(" "); } } else if (depth < last_depth) { while (depth < last_depth) { last_depth -= 1; } try out_stream.writeAll("\n"); try out_stream.writeByteNTimes(' ', 2 * @bitCast(usize, depth)); } else { try out_stream.writeAll("\n"); try out_stream.writeByteNTimes(' ', 2 * @bitCast(usize, depth)); } try n.value.stringify(out_stream); } } /// Outputs a `ZNode`s children on multiple lines. Excludes this node as root. /// Arrays with children that have: /// - null elements, separate lines /// - non-null, same line pub fn stringifyPretty(self: *const Self, out_stream: anytype) @TypeOf(out_stream).Error!void { // Assume root, so don't print this node. var iter: ?*const ZNode = self.child; while (iter) |n| { try n._stringifyPretty(out_stream); try out_stream.writeAll("\n"); iter = n.sibling; } } /// Debug print the node. pub fn show(self: *const Self) void { std.debug.print("{}\n", .{self.value}); var depth: isize = 0; var iter: *const ZNode = self; while (iter.nextUntil(self, &depth)) |c| : (iter = c) { var i: isize = 0; while (i < depth) : (i += 1) { std.debug.print(" ", .{}); } std.debug.print("{}\n", .{c.value}); } } }; pub const ZTreeError = error{ TreeFull, TooManyRoots, }; /// ZTree errors. pub const ZError = StreamingParser.Error || ZTreeError; /// Represents a static fixed-size zzz tree. Values are slices over the text passed. pub fn ZTree(comptime R: usize, comptime S: usize) type { return struct { const Self = @This(); roots: [R]*ZNode = undefined, root_count: usize = 0, nodes: [S]ZNode = [_]ZNode{.{}} ** S, node_count: usize = 0, /// Appends correct zzz text to the tree, creating a new root. pub fn appendText(self: *Self, text: []const u8) ZError!*ZNode { const current_node_count = self.node_count; var root = try self.addNode(null, .Null); // Undo everything we did if we encounter an error. errdefer { // Undo adding root above. self.root_count -= 1; // Reset to node count before adding root. self.node_count = current_node_count; } // If we error, undo adding any of this. var current = root; var current_depth: usize = 0; var stream = StreamingParser.init(); var idx: usize = 0; while (try parseStream(&stream, &idx, text)) |token| { const slice = text[token.start..token.end]; const value: ZValue = if (slice.len == 0) .Null else .{ .String = slice }; const new_depth = token.depth; if (new_depth <= current_depth) { // Ascend. while (current_depth > new_depth) { current = current.parent orelse unreachable; current_depth -= 1; } // Sibling. const new = try self.addNode(current.parent, value); current.sibling = new; current = new; } else if (new_depth == current_depth + 1) { // Descend. current_depth += 1; const new = try self.addNode(current, value); current.child = new; current = new; } else { // Levels shouldn't increase by more than one. unreachable; } } try stream.completeOrError(); return root; } /// Clears the entire tree. pub fn clear(self: *Self) void { self.root_count = 0; self.node_count = 0; } /// Returns a slice of active roots. pub fn rootSlice(self: *const Self) []const *ZNode { return self.roots[0..self.root_count]; } /// Adds a node given a parent. Null parent starts a new root. When adding nodes manually /// care must be taken to ensure tree is left in known state after erroring from being full. /// Either reset to root_count/node_count when an error occurs, or leave as is (unfinished). pub fn addNode(self: *Self, parent: ?*ZNode, value: ZValue) ZError!*ZNode { if (self.node_count >= S) { return ZError.TreeFull; } var node = &self.nodes[self.node_count]; if (parent == null) { if (self.root_count >= R) { return ZError.TooManyRoots; } self.roots[self.root_count] = node; self.root_count += 1; } self.node_count += 1; node.value = value; node.parent = parent; node.sibling = null; node.child = null; // Add to end. if (parent) |p| { if (p.child) |child| { var iter = child; while (iter.sibling) |sib| : (iter = sib) {} iter.sibling = node; } else { p.child = node; } } return node; } /// Recursively copies a node from another part of the tree onto a new parent. Strings will /// be by reference. pub fn copyNode(self: *Self, parent: ?*ZNode, node: *const ZNode) ZError!*ZNode { const current_root_count = self.root_count; const current_node_count = self.node_count; // Likely because tree was full. errdefer { self.root_count = current_root_count; self.node_count = current_node_count; } var last_depth: isize = 1; var depth: isize = 0; var iter = node; var piter: ?*ZNode = parent; var plast: ?*ZNode = null; var pfirst: ?*ZNode = null; while (iter.next(&depth)) |child| : (iter = child) { if (depth > last_depth) { piter = plast; last_depth = depth; } else if (depth < last_depth) { plast = piter; while (last_depth != depth) { piter = piter.?.parent; last_depth -= 1; } } plast = try self.addNode(piter, child.value); if (pfirst == null) { pfirst = plast; } } return pfirst.?; } /// Debug print the tree and all of its roots. pub fn show(self: *const Self) void { for (self.rootSlice()) |rt| { rt.show(); } } /// Extract a struct's values onto a tree with a new root. Performs no allocations so any strings /// are by reference. pub fn extract(self: *Self, root: ?*ZNode, from_ptr: anytype) anyerror!void { if (root == null) { return self.extract(try self.addNode(null, .Null), from_ptr); } if (@typeInfo(@TypeOf(from_ptr)) != .Pointer) { @compileError("Passed struct must be a pointer."); } const T = @typeInfo(@TypeOf(from_ptr)).Pointer.child; const TI = @typeInfo(T); switch (TI) { .Void => { // No need. }, .Bool => { _ = try self.addNode(root, .{ .Bool = from_ptr.* }); }, .Float, .ComptimeFloat => { _ = try self.addNode(root, .{ .Float = @floatCast(f32, from_ptr.*) }); }, .Int, .ComptimeInt => { _ = try self.addNode(root, .{ .Int = @intCast(i32, from_ptr.*) }); }, .Enum => { _ = try self.addNode(root, .{ .String = std.meta.tagName(from_ptr.*) }); }, .Optional => { if (from_ptr.* != null) { return self.extract(root, &from_ptr.*.?); } }, .Struct => |struct_info| { inline for (struct_info.fields) |field| { if (field.name[field.name.len - 1] == '_') { continue; } var field_node = try self.addNode(root, .{ .String = field.name }); try self.extract(field_node, &@field(from_ptr.*, field.name)); } }, .Array => |array_info| { comptime var i: usize = 0; inline while (i < array_info.len) : (i += 1) { var null_node = try self.addNode(root, .Null); try self.extract(null_node, &from_ptr.*[i]); } }, .Pointer => |ptr_info| { switch (ptr_info.size) { .One => { if (ptr_info.child == ZNode) { _ = try self.copyNode(root, from_ptr.*); } else { try self.extract(root, &from_ptr.*.*); } }, .Slice => { if (ptr_info.child != u8) { for (from_ptr.*) |_, i| { var null_node = try self.addNode(root, .Null); try self.extract(null_node, &from_ptr.*[i]); } } else { _ = try self.addNode(root, .{ .String = from_ptr.* }); } return; }, else => return error.InvalidType, } }, else => return error.InvalidType, } } }; } test "stable after error" { const testing = std.testing; var tree = ZTree(2, 6){}; // Using 1 root, 3 nodes (+1 for root). _ = try tree.appendText("foo:bar"); try testing.expectEqual(@as(usize, 1), tree.root_count); try testing.expectEqual(@as(usize, 3), tree.node_count); try testing.expectError(ZError.TreeFull, tree.appendText("bar:foo:baz:ha:ha")); try testing.expectEqual(@as(usize, 1), tree.root_count); try testing.expectEqual(@as(usize, 3), tree.node_count); // Using +1 root, +2 node = 2 roots, 5 nodes. _ = try tree.appendText("bar"); try testing.expectEqual(@as(usize, 2), tree.root_count); try testing.expectEqual(@as(usize, 5), tree.node_count); try testing.expectError(ZError.TooManyRoots, tree.appendText("foo")); try testing.expectEqual(@as(usize, 2), tree.root_count); try testing.expectEqual(@as(usize, 5), tree.node_count); } test "static tree" { const testing = std.testing; const text = \\max_particles: 100 \\texture: circle \\en: Foo \\systems: \\ : name:Emitter \\ params: \\ some,stuff,hehe \\ : name:Fire ; var tree = ZTree(1, 100){}; const node = try tree.appendText(text); node.convertStrings(); var iter = node.findNextChild(null, .{ .String = "max_particles" }); try testing.expect(iter != null); iter = node.findNextChild(iter, .{ .String = "texture" }); try testing.expect(iter != null); iter = node.findNextChild(iter, .{ .String = "max_particles" }); try testing.expect(iter != null); iter = node.findNextChild(iter, .{ .String = "systems" }); try testing.expect(iter != null); iter = node.findNextChild(iter, .{ .Int = 42 }); try testing.expect(iter == null); } test "node appending and searching" { const testing = std.testing; var tree = ZTree(1, 100){}; var root = try tree.addNode(null, .Null); _ = try tree.addNode(root, .Null); _ = try tree.addNode(root, .{ .String = "Hello" }); _ = try tree.addNode(root, .{ .String = "foo" }); _ = try tree.addNode(root, .{ .Int = 42 }); _ = try tree.addNode(root, .{ .Float = 3.14 }); try testing.expectEqual(@as(usize, 6), root.getChildCount()); try testing.expect(root.findNth(0, .Null) != null); try testing.expect(root.findNth(0, .{ .String = "Hello" }) != null); try testing.expect(root.findNth(0, .{ .String = "foo" }) != null); try testing.expect(root.findNth(1, .{ .String = "Hello" }) == null); try testing.expect(root.findNth(1, .{ .String = "foo" }) == null); try testing.expect(root.findNthAny(0, .String) != null); try testing.expect(root.findNthAny(1, .String) != null); try testing.expect(root.findNthAny(2, .String) == null); try testing.expect(root.findNth(0, .{ .Int = 42 }) != null); try testing.expect(root.findNth(0, .{ .Int = 41 }) == null); try testing.expect(root.findNth(1, .{ .Int = 42 }) == null); try testing.expect(root.findNthAny(0, .Int) != null); try testing.expect(root.findNthAny(1, .Int) == null); try testing.expect(root.findNth(0, .{ .Float = 3.14 }) != null); try testing.expect(root.findNth(0, .{ .Float = 3.13 }) == null); try testing.expect(root.findNth(1, .{ .Float = 3.14 }) == null); try testing.expect(root.findNthAny(0, .Float) != null); try testing.expect(root.findNthAny(1, .Float) == null); try testing.expect(root.findNthAny(0, .Bool) != null); try testing.expect(root.findNth(0, .{ .Bool = true }) != null); try testing.expect(root.findNthAny(1, .Bool) == null); try testing.expect(root.findNth(1, .{ .Bool = true }) == null); } test "node conforming imprint" { const text = \\max_particles: 100 \\texture: circle \\en: Foo \\systems: \\ : name:Emitter \\ params: \\ some,stuff,hehe \\ : name:Fire \\ params \\exists: anything here ; var tree = ZTree(1, 100){}; var node = try tree.appendText(text); node.convertStrings(); //const example = try node.imprint(ConformingStruct); //testing.expectEqual(@as(i32, 100), example.max_particles.?); //testing.expectEqualSlices(u8, "circle", example.texture); //testing.expect(null != example.systems[0]); //testing.expect(null != example.systems[1]); //testing.expectEqual(@as(?ConformingSubStruct, null), example.systems[2]); //testing.expectEqual(ConformingEnum.Foo, example.en.?); //testing.expectEqualSlices(u8, "params", example.systems[0].?.params.?.value.String); } test "node nonconforming imprint" { const testing = std.testing; const NonConformingStruct = struct { max_particles: bool = false, }; const text = \\max_particles: 100 \\texture: circle \\en: Foo \\systems: \\ : name:Emitter \\ params: \\ some,stuff,hehe \\ : name:Fire ; var tree = ZTree(1, 100){}; var node = try tree.appendText(text); node.convertStrings(); try testing.expectError(ImprintError.ExpectedBoolNode, node.imprint(NonConformingStruct)); } test "imprint allocations" { const testing = std.testing; const Embedded = struct { name: []const u8 = "", count: u32 = 0, }; const SysAlloc = struct { name: []const u8 = "", params: ?*const ZNode = null, }; const FooAlloc = struct { max_particles: ?*i32 = null, texture: []const u8 = "", systems: []SysAlloc = undefined, embedded: Embedded = .{}, }; const text = \\max_particles: 100 \\texture: circle \\en: Foo \\systems: \\ : name:Emitter \\ params: \\ some,stuff,hehe \\ : name:Fire \\ params \\embedded: \\ name: creator \\ count: 12345 \\ ; var tree = ZTree(1, 100){}; var node = try tree.appendText(text); node.convertStrings(); var imprint = try node.imprintAlloc(FooAlloc, testing.allocator); try testing.expectEqual(@as(i32, 100), imprint.result.max_particles.?.*); for (imprint.result.systems) |sys, i| { try testing.expectEqualSlices(u8, ([_][]const u8{ "Emitter", "Fire" })[i], sys.name); } imprint.arena.deinit(); } test "extract" { var text_tree = ZTree(1, 100){}; var text_root = try text_tree.appendText("foo:bar:baz;;42"); const FooNested = struct { a_bool: bool = true, a_int: i32 = 42, a_float: f32 = 3.14, }; const foo_struct = struct { foo: ?i32 = null, hi: []const u8 = "lol", arr: [2]FooNested = [_]FooNested{.{}} ** 2, slice: []const FooNested = &[_]FooNested{ .{}, .{}, .{} }, ptr: *const FooNested = &FooNested{}, a_node: *ZNode = undefined, }{ .a_node = text_root, }; var tree = ZTree(1, 100){}; try tree.extract(null, &foo_struct); } /// A minimal factory for creating structs. The type passed should be an interface. Register structs /// with special declarations and instantiate them with ZNodes. Required declarations: /// - ZNAME: []const u8 // name of the struct referenced in zzz /// - zinit: fn(allocator: *std.mem.Allocator, argz: *const ZNode) anyerror!*T // constructor called pub fn ZFactory(comptime T: type) type { return struct { const Self = @This(); const Ctor = struct { func: fn (allocator: *std.mem.Allocator, argz: *const ZNode) anyerror!*T, }; registered: std.StringHashMap(Ctor), /// Create the factory. The allocator is for the internal HashMap. Instantiated objects /// can have their own allocator. pub fn init(allocator: *std.mem.Allocator) Self { return Self{ .registered = std.StringHashMap(Ctor).init(allocator), }; } /// pub fn deinit(self: *Self) void { self.registered.deinit(); } /// Registers an implementor of the interface. Requires ZNAME and a zinit /// method. pub fn register(self: *Self, comptime S: anytype) !void { const SI = @typeInfo(S); if (SI != .Struct) { @compileError("Expected struct got: " ++ @typeName(S)); } if (!@hasDecl(S, "zinit")) { @compileError("Missing `zinit` on registered struct, it could be private: " ++ @typeName(S)); } if (!@hasDecl(S, "ZNAME")) { @compileError("Missing `ZNAME` on registered struct, it could be private: " ++ @typeName(S)); } const ctor = Ctor{ .func = S.zinit, }; try self.registered.put(S.ZNAME, ctor); } /// Instantiates an object with ZNode. The ZNode's first child must have a string value of /// "name" with the child node's value being the name of the registered struct. The node is /// then passed to zinit. /// /// The caller is responsible for the memory. pub fn instantiate(self: *Self, allocator: *std.mem.Allocator, node: *const ZNode) !*T { const name = node.findNth(0, .{ .String = "name" }) orelse return error.ZNodeMissingName; const value_node = name.getChild(0) orelse return error.ZNodeMissingValueUnderName; if (value_node.value != .String) { return error.ZNodeNameValueNotString; } const ctor = self.registered.get(value_node.value.String) orelse return error.StructNotFound; return try ctor.func(allocator, node); } }; } const FooInterface = struct { const Self = @This(); allocator: ?*std.mem.Allocator = null, default: i32 = 100, fooFn: ?fn (*Self) void = null, deinitFn: ?fn (*const Self) void = null, pub fn foo(self: *Self) void { return self.fooFn.?(self); } pub fn deinit(self: *const Self) void { self.deinitFn.?(self); } }; const FooBar = struct { const Self = @This(); const ZNAME = "Foo"; interface: FooInterface = .{}, bar: i32 = 0, pub fn zinit(allocator: *std.mem.Allocator, argz: *const ZNode) !*FooInterface { _ = argz; var self = try allocator.create(Self); self.* = .{ .interface = .{ .allocator = allocator, .fooFn = foo, .deinitFn = deinit, }, }; //const imprint = try argz.imprint(FooBar); //self.bar = imprint.bar; return &self.interface; } pub fn deinit(interface: *const FooInterface) void { const self = @fieldParentPtr(Self, "interface", interface); interface.allocator.?.destroy(self); } pub fn foo(interface: *FooInterface) void { var self = @fieldParentPtr(FooBar, "interface", interface); _ = self; } }; test "factory" { const testing = std.testing; const text = \\name:Foo \\bar:42 ; var tree = ZTree(1, 100){}; var root = try tree.appendText(text); root.convertStrings(); var factory = ZFactory(FooInterface).init(testing.allocator); defer factory.deinit(); try factory.register(FooBar); const foobar = try factory.instantiate(testing.allocator, root); foobar.foo(); defer foobar.deinit(); }
src/main.zig
const std = @import("std"); const assert = std.debug.assert; const print = std.debug.print; const tools = @import("tools"); const Vec2 = tools.Vec2; const stride: usize = 11; const width = 10; const height = 10; const Border = u10; const Map = struct { ident: u32, map: []const u8, borders: ?struct { canon: [4]Border, transformed: [8][4]Border }, }; fn push_bit(v: *u10, tile: u8) void { v.* = (v.* << 1) | (if (tile == '.') @as(u1, 0) else @as(u1, 1)); } fn extractBorders(map: []const u8) [4]Border { var b: [4]Border = undefined; var i: usize = 0; while (i < width) : (i += 1) { push_bit(&b[0], map[i]); push_bit(&b[1], map[i * stride + (width - 1)]); push_bit(&b[2], map[i + (height - 1) * stride]); push_bit(&b[3], map[i * stride + 0]); } return b; } // tranforme la "map" de t par rapport à son centre. fn transform(in: Map, t: Vec2.Transfo, out_buf: []u8) Map { const r = Vec2.referential(t); const c2 = Vec2{ .x = width - 1, .y = height - 1 }; // coordonées doublées pour avoir le centre entre deux cases. var j: i32 = 0; while (j < height) : (j += 1) { var i: i32 = 0; while (i < width) : (i += 1) { const o2 = Vec2{ .x = i * 2 - c2.x, .y = j * 2 - c2.y }; const p2 = Vec2.add(Vec2.scale(o2.x, r.x), Vec2.scale(o2.y, r.y)); const p = Vec2{ .x = @intCast(u16, p2.x + c2.x) / 2, .y = @intCast(u16, p2.y + c2.y) / 2 }; // print("{} <- {} == {}\n", .{ o2, p2, w }); out_buf[@intCast(u32, i) + @intCast(u32, j) * stride] = in.map[@intCast(u32, p.x) + @intCast(u32, p.y) * stride]; } out_buf[width + @intCast(u32, j) * stride] = '\n'; } return Map{ .ident = in.ident, .map = out_buf[0 .. height * stride], .borders = null, }; } fn computeTransormedBorders(in: *Map) void { var borders: [8][4]Border = undefined; for (Vec2.all_tranfos) |t| { var buf: [stride * height]u8 = undefined; const m = transform(in.*, t, &buf); borders[@enumToInt(t)] = extractBorders(m.map); } var canon: [4]Border = undefined; for (canon) |*it, i| { it.* = if (borders[0][i] < @bitReverse(Border, borders[0][i])) borders[0][i] else @bitReverse(Border, borders[0][i]); } const b = borders[0]; assert((b[0] | b[1] | b[2] | b[3]) != 0); // valeur spéciale reservée in.borders = .{ .canon = canon, .transformed = borders }; } fn debugPrint(m: Map) void { print("map n°{}: borders={b},{b},{b},{b}\n", .{ m.ident, m.borders[0], m.borders[1], m.borders[2], m.borders[3] }); print("{}", .{m.map}); } const State = struct { placed: u8, list: [150]struct { map_idx: u8, t: Vec2.Transfo }, }; fn bigPosFromIndex(idx: usize, big_stride: usize) Vec2 { if (true) { // sens de lecture -> permet de placer un coin dès le debut au bon endroit. return Vec2{ .y = @intCast(i32, idx / big_stride), .x = @intCast(i32, idx % big_stride) }; } else { // spirale partant du centre. const c = Vec2{ .y = @intCast(i32, big_stride / 2), .x = @intCast(i32, big_stride / 2) }; const p = Vec2.add(c, tools.posFromSpiralIndex(idx)); const s = @intCast(i32, big_stride); return Vec2{ .x = @intCast(i32, @mod(p.x, s)), .y = @intCast(i32, @mod(p.y, s)) }; // gère le fait que c'est décentré si la taille est paire } } fn checkValid(s: State, maps: []const Map) bool { const big_stride = std.math.sqrt(maps.len); var borders_mem = [_][4]Border{.{ 0, 0, 0, 0 }} ** (16 * 16); var borders = borders_mem[0 .. big_stride * big_stride]; for (s.list[0..s.placed]) |it, i| { const p = bigPosFromIndex(i, big_stride); assert(p.y >= 0 and p.y < big_stride and p.x >= 0 and p.x < big_stride); borders[@intCast(usize, p.x) + @intCast(usize, p.y) * big_stride] = maps[it.map_idx].borders.?.transformed[@enumToInt(it.t)]; } for (borders[0 .. big_stride * big_stride]) |b, i| { if ((b[0] | b[1] | b[2] | b[3]) == 0) continue; const p = Vec2{ .x = @intCast(i32, i % big_stride), .y = @intCast(i32, i / big_stride) }; const border_list = [_]struct { this: u8, other: u8, d: Vec2 }{ .{ .this = 0, .other = 2, .d = Vec2{ .x = 0, .y = -1 } }, .{ .this = 3, .other = 1, .d = Vec2{ .x = -1, .y = 0 } }, .{ .this = 1, .other = 3, .d = Vec2{ .x = 1, .y = 0 } }, .{ .this = 2, .other = 0, .d = Vec2{ .x = 0, .y = 1 } }, }; for (border_list) |it| { const n = Vec2.add(p, it.d); const neib = if (n.y >= 0 and n.y < big_stride and n.x >= 0 and n.x < big_stride) borders[@intCast(usize, n.x) + @intCast(usize, n.y) * big_stride] else [4]Border{ 0, 0, 0, 0 }; const empty = ((neib[0] | neib[1] | neib[2] | neib[3]) == 0); if (!empty and b[it.this] != neib[it.other]) return false; } } return true; } fn replaceIfMatches(pat: []const []const u8, p: Vec2, t: Vec2.Transfo, map: []u8, w: usize, h: usize) void { const r = Vec2.referential(t); // check if pattern matches... for (pat) |line, j| { for (line) |c, i| { if (c == ' ') continue; assert(c == '#'); const p1 = p.add(Vec2.scale(@intCast(i32, i), r.x)).add(Vec2.scale(@intCast(i32, j), r.y)); if (p1.x < 0 or p1.x >= w) return; if (p1.y < 0 or p1.y >= h) return; if (map[@intCast(usize, p1.y) * w + @intCast(usize, p1.x)] != c) return; } } // .. if ok, replace pattern for (pat) |line, j| { for (line) |c, i| { if (c == ' ') continue; const p1 = p.add(Vec2.scale(@intCast(i32, i), r.x)).add(Vec2.scale(@intCast(i32, j), r.y)); map[@intCast(usize, p1.y) * w + @intCast(usize, p1.x)] = '0'; } } } pub fn run(input_text: []const u8, allocator: std.mem.Allocator) ![2][]const u8 { var arena = std.heap.ArenaAllocator.init(allocator); defer arena.deinit(); const param: struct { maps: []const Map, big_stride: usize, } = blk: { var maps = std.ArrayList(Map).init(arena.allocator()); var ident: ?u32 = null; var it = std.mem.tokenize(u8, input_text, "\n\r"); while (it.next()) |line| { if (tools.match_pattern("Tile {}:", line)) |fields| { ident = @intCast(u32, fields[0].imm); } else { const w = std.mem.indexOfScalar(u8, input_text, '\n').?; assert(w == width); assert(ident != null); var map = line; map.len = stride * height; var m = Map{ .ident = ident.?, .map = map, .borders = null }; computeTransormedBorders(&m); try maps.append(m); var h: usize = 1; while (h < height) : (h += 1) { _ = it.next(); } ident = null; } } //print("{}\n", .{maps.items.len}); break :blk .{ .maps = maps.items, .big_stride = std.math.sqrt(maps.items.len), }; }; // corner candidate pieces: const corners: []u8 = blk: { const occurences = try allocator.alloc(u8, 1 << 10); defer allocator.free(occurences); std.mem.set(u8, occurences, 0); for (param.maps) |m| { for (m.borders.?.canon) |b| occurences[b] += 1; } for (occurences) |it| assert(it <= 2); // pff en fait il n'y a pas d'ambiguités... var corners = std.ArrayList(u8).init(arena.allocator()); for (param.maps) |m, i| { var uniq: u32 = 0; for (m.borders.?.canon) |b| uniq += @boolToInt(occurences[b] == 1); assert(uniq <= 2); if (uniq == 2) // deux bords uniques -> coin! try corners.append(@intCast(u8, i)); } //print("found corner pieces: {}\n", .{corners.items}); break :blk corners.items; }; var final_state: State = undefined; const ans1 = ans: { // nb: vu qu'il n'y a pas d'ambiguité, on pourrait juste faire corners[0]*..*corner[3] pour ans1. const BFS = tools.BestFirstSearch(State, void); var bfs = BFS.init(allocator); defer bfs.deinit(); const initial_state = blk: { var s = State{ .placed = 0, .list = undefined }; for (s.list) |*m, i| { m.map_idx = if (i < param.maps.len) @intCast(u8, i) else undefined; m.t = .r0; } // comment avec un coin, ça permet de trouver direct une bonne solution s.list[0].map_idx = corners[0]; s.list[corners[0]].map_idx = 0; break :blk s; }; try bfs.insert(BFS.Node{ .state = initial_state, .trace = {}, .rating = @intCast(i32, param.maps.len), .cost = 0 }); final_state = result: while (bfs.pop()) |n| { //print("agenda: {}, steps:{}\n", .{ bfs.agenda.count(), n.cost }); var next_candidate = n.state.placed; while (next_candidate < param.maps.len) : (next_candidate += 1) { var next = n; next.cost = n.cost + 1; next.rating = n.rating - 1; next.state.list[n.state.placed] = n.state.list[next_candidate]; next.state.list[next_candidate] = n.state.list[n.state.placed]; next.state.placed = n.state.placed + 1; for (Vec2.all_tranfos) |t| { if (n.cost == 0 and t != .r0) continue; // pas la peine d'explorer les 8 sytémetries et trouver 8 resultats.. next.state.list[n.state.placed].t = t; if (!checkValid(next.state, param.maps)) continue; if (next.state.placed == param.maps.len) break :result next.state; // bingo! try bfs.insert(next); } } } else unreachable; if (false) { print("final state: ", .{}); for (final_state.list[0..param.maps.len]) |it, i| { const p = bigPosFromIndex(i, param.big_stride); print("{}:{}{}, ", .{ p, param.maps[it.map_idx].ident, it.t }); } print("\n", .{}); } var checksum: u64 = 1; checksum *= param.maps[final_state.list[0].map_idx].ident; checksum *= param.maps[final_state.list[param.big_stride - 1].map_idx].ident; checksum *= param.maps[final_state.list[param.maps.len - 1].map_idx].ident; checksum *= param.maps[final_state.list[param.maps.len - param.big_stride].map_idx].ident; break :ans checksum; }; const ans2 = ans: { const h = (height - 2) * param.big_stride; const w = (width - 2) * param.big_stride; var big = try allocator.alloc(u8, w * h); defer allocator.free(big); // build merged map for (final_state.list[0..final_state.placed]) |it, i| { const big_p = bigPosFromIndex(i, param.big_stride); var buf: [stride * height]u8 = undefined; const m = transform(param.maps[it.map_idx], it.t, &buf); var j: usize = 0; while (j < height - 2) : (j += 1) { const o = ((@intCast(u32, big_p.y) * (height - 2) + j) * w + @intCast(u32, big_p.x) * (width - 2)); std.mem.copy(u8, big[o .. o + (width - 2)], m.map[(j + 1) * stride + 1 .. (j + 1) * stride + 1 + (width - 2)]); } } { const monster = [_][]const u8{ " # ", "# ## ## ###", " # # # # # # ", }; for (Vec2.all_tranfos) |t| { var j: i32 = 0; while (j < h) : (j += 1) { var i: i32 = 0; while (i < w) : (i += 1) { replaceIfMatches(&monster, Vec2{ .x = i, .y = j }, t, big, w, h); } } } if (false) { print("bigmap: \n", .{}); var j: usize = 0; while (j < h) : (j += 1) { print("{}\n", .{big[j * w .. (j + 1) * w]}); } } } var nb_rocks: usize = 0; for (big) |it| { if (it == '#') nb_rocks += 1; } break :ans nb_rocks; }; return [_][]const u8{ try std.fmt.allocPrint(allocator, "{}", .{ans1}), try std.fmt.allocPrint(allocator, "{}", .{ans2}), }; } pub const main = tools.defaultMain("2020/input_day20.txt", run);
2020/day20.zig
const std = @import("std"); const Arena = std.heap.ArenaAllocator; const expectEqual = std.testing.expectEqual; const expectEqualStrings = std.testing.expectEqualStrings; const yeti = @import("yeti"); const initCodebase = yeti.initCodebase; const tokenize = yeti.tokenize; const parse = yeti.parse; const analyzeSemantics = yeti.analyzeSemantics; const codegen = yeti.codegen; const printWasm = yeti.printWasm; const components = yeti.components; const literalOf = yeti.query.literalOf; const typeOf = yeti.query.typeOf; const MockFileSystem = yeti.FileSystem; test "tokenize string" { var arena = Arena.init(std.heap.page_allocator); defer arena.deinit(); var codebase = try initCodebase(&arena); const module = try codebase.createEntity(.{}); const code = \\"hello" "world" ; var tokens = try tokenize(module, code); { const token = tokens.next().?; try expectEqual(token.get(components.TokenKind), .string); try expectEqualStrings(literalOf(token), "hello"); try expectEqual(token.get(components.Span), .{ .begin = .{ .column = 0, .row = 0 }, .end = .{ .column = 6, .row = 0 }, }); } { const token = tokens.next().?; try expectEqual(token.get(components.TokenKind), .string); try expectEqualStrings(literalOf(token), "world"); try expectEqual(token.get(components.Span), .{ .begin = .{ .column = 8, .row = 0 }, .end = .{ .column = 14, .row = 0 }, }); } try expectEqual(tokens.next(), null); } test "tokenize multiline string" { var arena = Arena.init(std.heap.page_allocator); defer arena.deinit(); var codebase = try initCodebase(&arena); const module = try codebase.createEntity(.{}); const code = \\"hello \\world" ; var tokens = try tokenize(module, code); { const token = tokens.next().?; try expectEqual(token.get(components.TokenKind), .string); try expectEqualStrings(literalOf(token), "hello\nworld"); try expectEqual(token.get(components.Span), .{ .begin = .{ .column = 0, .row = 0 }, .end = .{ .column = 6, .row = 1 }, }); } try expectEqual(tokens.next(), null); } test "parse string literal" { var arena = Arena.init(std.heap.page_allocator); defer arena.deinit(); var codebase = try initCodebase(&arena); const module = try codebase.createEntity(.{}); const code = \\start() []u8 { \\ "hello world" \\} ; var tokens = try tokenize(module, code); try parse(module, &tokens); const top_level = module.get(components.TopLevel); const overloads = top_level.findString("start").get(components.Overloads).slice(); try expectEqual(overloads.len, 1); const start = overloads[0]; const return_type = start.get(components.ReturnTypeAst).entity; try expectEqual(return_type.get(components.AstKind), .array); try expectEqualStrings(literalOf(return_type.get(components.Value).entity), "u8"); const body = overloads[0].get(components.Body).slice(); try expectEqual(body.len, 1); const hello_world = body[0]; try expectEqual(hello_world.get(components.AstKind), .string); try expectEqualStrings(literalOf(hello_world), "hello world"); } test "parse array index" { var arena = Arena.init(std.heap.page_allocator); defer arena.deinit(); var codebase = try initCodebase(&arena); const module = try codebase.createEntity(.{}); const code = \\start() u8 { \\ text = "hello world" \\ text[0] \\} ; var tokens = try tokenize(module, code); try parse(module, &tokens); const top_level = module.get(components.TopLevel); const overloads = top_level.findString("start").get(components.Overloads).slice(); try expectEqual(overloads.len, 1); const start = overloads[0]; const return_type = start.get(components.ReturnTypeAst).entity; try expectEqual(return_type.get(components.AstKind), .symbol); try expectEqualStrings(literalOf(return_type), "u8"); const body = overloads[0].get(components.Body).slice(); try expectEqual(body.len, 2); const define = body[0]; try expectEqual(define.get(components.AstKind), .define); try expectEqualStrings(literalOf(define.get(components.Name).entity), "text"); const hello_world = define.get(components.Value).entity; try expectEqual(hello_world.get(components.AstKind), .string); try expectEqualStrings(literalOf(hello_world), "hello world"); const index = body[1]; try expectEqual(index.get(components.AstKind), .index); const arguments = index.get(components.Arguments).slice(); try expectEqual(arguments.len, 2); try expectEqualStrings(literalOf(arguments[0]), "text"); try expectEqualStrings(literalOf(arguments[1]), "0"); } test "analyze semantics of string literal" { var arena = Arena.init(std.heap.page_allocator); defer arena.deinit(); var codebase = try initCodebase(&arena); var fs = try MockFileSystem.init(&arena); _ = try fs.newFile("foo.yeti", \\start() []u8 { \\ "hello world" \\} ); _ = try analyzeSemantics(codebase, fs, "foo.yeti"); const module = try analyzeSemantics(codebase, fs, "foo.yeti"); const top_level = module.get(components.TopLevel); const start = top_level.findString("start").get(components.Overloads).slice()[0]; try expectEqualStrings(literalOf(start.get(components.Module).entity), "foo"); try expectEqualStrings(literalOf(start.get(components.Name).entity), "start"); try expectEqual(start.get(components.Parameters).len(), 0); const return_type = start.get(components.ReturnType).entity; try expectEqualStrings(literalOf(return_type), "[]u8"); const body = start.get(components.Body).slice(); try expectEqual(body.len, 1); const hello_world = body[0]; try expectEqual(hello_world.get(components.AstKind), .string); try expectEqual(typeOf(hello_world), return_type); try expectEqualStrings(literalOf(hello_world), "hello world"); } test "analyze semantics of array index" { var arena = Arena.init(std.heap.page_allocator); defer arena.deinit(); var codebase = try initCodebase(&arena); const builtins = codebase.get(components.Builtins); var fs = try MockFileSystem.init(&arena); _ = try fs.newFile("foo.yeti", \\start() u8 { \\ text = "hello world" \\ text[0] \\} ); _ = try analyzeSemantics(codebase, fs, "foo.yeti"); const module = try analyzeSemantics(codebase, fs, "foo.yeti"); const top_level = module.get(components.TopLevel); const start = top_level.findString("start").get(components.Overloads).slice()[0]; try expectEqualStrings(literalOf(start.get(components.Module).entity), "foo"); try expectEqualStrings(literalOf(start.get(components.Name).entity), "start"); try expectEqual(start.get(components.Parameters).len(), 0); try expectEqual(start.get(components.ReturnType).entity, builtins.U8); const body = start.get(components.Body).slice(); try expectEqual(body.len, 2); const define = body[0]; try expectEqual(define.get(components.AstKind), .define); try expectEqual(typeOf(define), builtins.Void); const local = define.get(components.Local).entity; try expectEqual(local.get(components.AstKind), .local); try expectEqualStrings(literalOf(local.get(components.Name).entity), "text"); const hello_world = define.get(components.Value).entity; try expectEqual(hello_world.get(components.AstKind), .string); try expectEqualStrings(literalOf(typeOf(hello_world)), "[]u8"); try expectEqualStrings(literalOf(hello_world), "hello world"); const index = body[1]; try expectEqual(index.get(components.AstKind), .index); try expectEqual(typeOf(index), builtins.U8); const arguments = index.get(components.Arguments).slice(); try expectEqual(arguments[0], local); try expectEqualStrings(literalOf(arguments[1]), "0"); } test "codegen of string literal" { var arena = Arena.init(std.heap.page_allocator); defer arena.deinit(); var codebase = try initCodebase(&arena); var fs = try MockFileSystem.init(&arena); _ = try fs.newFile("foo.yeti", \\start() []u8 { \\ "hello world" \\} ); const module = try analyzeSemantics(codebase, fs, "foo.yeti"); try codegen(module); const top_level = module.get(components.TopLevel); const start = top_level.findString("start").get(components.Overloads).slice()[0]; const wasm_instructions = start.get(components.WasmInstructions).slice(); try expectEqual(wasm_instructions.len, 2); { const constant = wasm_instructions[0]; try expectEqual(constant.get(components.WasmInstructionKind), .i32_const); try expectEqualStrings(literalOf(constant.get(components.Constant).entity), "0"); } { const constant = wasm_instructions[1]; try expectEqual(constant.get(components.WasmInstructionKind), .i32_const); try expectEqualStrings(literalOf(constant.get(components.Constant).entity), "11"); } const data_segment = codebase.get(components.DataSegment); try expectEqual(data_segment.end, 88); const entities = data_segment.entities.slice(); try expectEqual(entities.len, 1); try expectEqualStrings(literalOf(entities[0]), "hello world"); } test "codegen of array index" { var arena = Arena.init(std.heap.page_allocator); defer arena.deinit(); var codebase = try initCodebase(&arena); var fs = try MockFileSystem.init(&arena); _ = try fs.newFile("foo.yeti", \\start() u8 { \\ text = "hello world" \\ text[0] \\} ); const module = try analyzeSemantics(codebase, fs, "foo.yeti"); try codegen(module); const top_level = module.get(components.TopLevel); const start = top_level.findString("start").get(components.Overloads).slice()[0]; const wasm_instructions = start.get(components.WasmInstructions).slice(); try expectEqual(wasm_instructions.len, 9); { const constant = wasm_instructions[0]; try expectEqual(constant.get(components.WasmInstructionKind), .i32_const); try expectEqualStrings(literalOf(constant.get(components.Constant).entity), "0"); } { const constant = wasm_instructions[1]; try expectEqual(constant.get(components.WasmInstructionKind), .i32_const); try expectEqualStrings(literalOf(constant.get(components.Constant).entity), "11"); } { const local_set = wasm_instructions[2]; try expectEqual(local_set.get(components.WasmInstructionKind), .local_set); try expectEqualStrings(literalOf(local_set.get(components.Local).entity.get(components.Name).entity), "text"); } { const field = wasm_instructions[3]; try expectEqual(field.get(components.WasmInstructionKind), .field); try expectEqualStrings(literalOf(field.get(components.Local).entity.get(components.Name).entity), "text"); try expectEqualStrings(literalOf(field.get(components.Field).entity), "ptr"); } { const constant = wasm_instructions[4]; try expectEqual(constant.get(components.WasmInstructionKind), .i32_const); try expectEqualStrings(literalOf(constant.get(components.Constant).entity), "0"); } { const constant = wasm_instructions[5]; try expectEqual(constant.get(components.WasmInstructionKind), .i32_const); try expectEqualStrings(literalOf(constant.get(components.Constant).entity), "1"); } try expectEqual(wasm_instructions[6].get(components.WasmInstructionKind), .i32_mul); try expectEqual(wasm_instructions[7].get(components.WasmInstructionKind), .i32_add); try expectEqual(wasm_instructions[8].get(components.WasmInstructionKind), .i32_load8_u); const data_segment = codebase.get(components.DataSegment); try expectEqual(data_segment.end, 88); const entities = data_segment.entities.slice(); try expectEqual(entities.len, 1); try expectEqualStrings(literalOf(entities[0]), "hello world"); } test "print wasm string literal" { var arena = Arena.init(std.heap.page_allocator); defer arena.deinit(); var codebase = try initCodebase(&arena); var fs = try MockFileSystem.init(&arena); _ = try fs.newFile("foo.yeti", \\start() []u8 { \\ "hello world" \\} ); const module = try analyzeSemantics(codebase, fs, "foo.yeti"); try codegen(module); const wasm = try printWasm(module); try expectEqualStrings(wasm, \\(module \\ \\ (func $foo/start (result i32 i32) \\ (i32.const 0) \\ (i32.const 11)) \\ \\ (export "_start" (func $foo/start)) \\ \\ (data (i32.const 0) "hello world") \\ \\ (memory 1) \\ (export "memory" (memory 0))) ); } test "print wasm multi line string literal" { var arena = Arena.init(std.heap.page_allocator); defer arena.deinit(); var codebase = try initCodebase(&arena); var fs = try MockFileSystem.init(&arena); _ = try fs.newFile("foo.yeti", \\start() []u8 { \\ " \\ hello \\ world \\ " \\} ); const module = try analyzeSemantics(codebase, fs, "foo.yeti"); try codegen(module); const wasm = try printWasm(module); try expectEqualStrings(wasm, \\(module \\ \\ (func $foo/start (result i32 i32) \\ (i32.const 0) \\ (i32.const 19)) \\ \\ (export "_start" (func $foo/start)) \\ \\ (data (i32.const 0) "\n hello\n world\n ") \\ \\ (memory 1) \\ (export "memory" (memory 0))) ); } test "print wasm assign string literal to variable" { var arena = Arena.init(std.heap.page_allocator); defer arena.deinit(); var codebase = try initCodebase(&arena); var fs = try MockFileSystem.init(&arena); _ = try fs.newFile("foo.yeti", \\start() []u8 { \\ text = "hello world" \\ text \\} ); const module = try analyzeSemantics(codebase, fs, "foo.yeti"); try codegen(module); const wasm = try printWasm(module); try expectEqualStrings(wasm, \\(module \\ \\ (func $foo/start (result i32 i32) \\ (local $text.ptr i32) \\ (local $text.len i32) \\ (i32.const 0) \\ (i32.const 11) \\ (local.set $text.len) \\ (local.set $text.ptr) \\ (local.get $text.ptr) \\ (local.get $text.len)) \\ \\ (export "_start" (func $foo/start)) \\ \\ (data (i32.const 0) "hello world") \\ \\ (memory 1) \\ (export "memory" (memory 0))) ); } test "print wasm pass string literal as argument" { var arena = Arena.init(std.heap.page_allocator); defer arena.deinit(); var codebase = try initCodebase(&arena); var fs = try MockFileSystem.init(&arena); _ = try fs.newFile("foo.yeti", \\first(text: []u8) u8 { \\ *text.ptr \\} \\ \\start() u8 { \\ first("hello world") \\} ); const module = try analyzeSemantics(codebase, fs, "foo.yeti"); try codegen(module); const wasm = try printWasm(module); try expectEqualStrings(wasm, \\(module \\ \\ (func $foo/start (result i32) \\ (i32.const 0) \\ (i32.const 11) \\ (call $foo/first..text.array.u8)) \\ \\ (func $foo/first..text.array.u8 (param $text.ptr i32) (param $text.len i32) (result i32) \\ (local.get $text.ptr) \\ i32.load8_u) \\ \\ (export "_start" (func $foo/start)) \\ \\ (data (i32.const 0) "hello world") \\ \\ (memory 1) \\ (export "memory" (memory 0))) ); } test "print wasm dereference string literal" { var arena = Arena.init(std.heap.page_allocator); defer arena.deinit(); var codebase = try initCodebase(&arena); var fs = try MockFileSystem.init(&arena); _ = try fs.newFile("foo.yeti", \\start() u8 { \\ text = "hello world" \\ *text.ptr \\} ); const module = try analyzeSemantics(codebase, fs, "foo.yeti"); try codegen(module); const wasm = try printWasm(module); try expectEqualStrings(wasm, \\(module \\ \\ (func $foo/start (result i32) \\ (local $text.ptr i32) \\ (local $text.len i32) \\ (i32.const 0) \\ (i32.const 11) \\ (local.set $text.len) \\ (local.set $text.ptr) \\ (local.get $text.ptr) \\ i32.load8_u) \\ \\ (export "_start" (func $foo/start)) \\ \\ (data (i32.const 0) "hello world") \\ \\ (memory 1) \\ (export "memory" (memory 0))) ); } test "print wasm write through **u8" { var arena = Arena.init(std.heap.page_allocator); defer arena.deinit(); var codebase = try initCodebase(&arena); var fs = try MockFileSystem.init(&arena); _ = try fs.newFile("foo.yeti", \\start() void { \\ text = "<NAME>" \\ ptr = cast(**u8, 100) \\ *ptr = text.ptr \\} ); const module = try analyzeSemantics(codebase, fs, "foo.yeti"); try codegen(module); const wasm = try printWasm(module); try expectEqualStrings(wasm, \\(module \\ \\ (func $foo/start \\ (local $text.ptr i32) \\ (local $text.len i32) \\ (local $ptr i32) \\ (i32.const 0) \\ (i32.const 11) \\ (local.set $text.len) \\ (local.set $text.ptr) \\ (i32.const 100) \\ (local.set $ptr) \\ (local.get $ptr) \\ (local.get $text.ptr) \\ i32.store) \\ \\ (export "_start" (func $foo/start)) \\ \\ (data (i32.const 0) "hello world") \\ \\ (memory 1) \\ (export "memory" (memory 0))) ); }
src/tests/test_strings.zig
const std = @import("std"); const builtin = @import("builtin"); const mem = std.mem; const expect = std.testing.expect; const expectEqualStrings = std.testing.expectEqualStrings; test "call result of if else expression" { try expect(mem.eql(u8, f2(true), "a")); try expect(mem.eql(u8, f2(false), "b")); } fn f2(x: bool) []const u8 { return (if (x) fA else fB)(); } fn fA() []const u8 { return "a"; } fn fB() []const u8 { return "b"; } test "memcpy and memset intrinsics" { try testMemcpyMemset(); // TODO add comptime test coverage //comptime try testMemcpyMemset(); } fn testMemcpyMemset() !void { var foo: [20]u8 = undefined; var bar: [20]u8 = undefined; @memset(&foo, 'A', foo.len); @memcpy(&bar, &foo, bar.len); try expect(bar[0] == 'A'); try expect(bar[11] == 'A'); try expect(bar[19] == 'A'); } const OpaqueA = opaque {}; const OpaqueB = opaque {}; test "variable is allowed to be a pointer to an opaque type" { var x: i32 = 1234; _ = hereIsAnOpaqueType(@ptrCast(*OpaqueA, &x)); } fn hereIsAnOpaqueType(ptr: *OpaqueA) *OpaqueA { var a = ptr; return a; } test "take address of parameter" { try testTakeAddressOfParameter(12.34); } fn testTakeAddressOfParameter(f: f32) !void { const f_ptr = &f; try expect(f_ptr.* == 12.34); } test "pointer to void return type" { try testPointerToVoidReturnType(); } fn testPointerToVoidReturnType() anyerror!void { const a = testPointerToVoidReturnType2(); return a.*; } const test_pointer_to_void_return_type_x = void{}; fn testPointerToVoidReturnType2() *const void { return &test_pointer_to_void_return_type_x; } test "array 2D const double ptr" { const rect_2d_vertexes = [_][1]f32{ [_]f32{1.0}, [_]f32{2.0}, }; try testArray2DConstDoublePtr(&rect_2d_vertexes[0][0]); } fn testArray2DConstDoublePtr(ptr: *const f32) !void { const ptr2 = @ptrCast([*]const f32, ptr); try expect(ptr2[0] == 1.0); try expect(ptr2[1] == 2.0); } test "double implicit cast in same expression" { var x = @as(i32, @as(u16, nine())); try expect(x == 9); } fn nine() u8 { return 9; } test "struct inside function" { try testStructInFn(); comptime try testStructInFn(); } fn testStructInFn() !void { const BlockKind = u32; const Block = struct { kind: BlockKind, }; var block = Block{ .kind = 1234 }; block.kind += 1; try expect(block.kind == 1235); } test "fn call returning scalar optional in equality expression" { try expect(getNull() == null); } fn getNull() ?*i32 { return null; } var global_foo: *i32 = undefined; test "global variable assignment with optional unwrapping with var initialized to undefined" { const S = struct { var data: i32 = 1234; fn foo() ?*i32 { return &data; } }; global_foo = S.foo() orelse { @panic("bad"); }; try expect(global_foo.* == 1234); } test "peer result location with typed parent, runtime condition, comptime prongs" { const S = struct { fn doTheTest(arg: i32) i32 { const st = Structy{ .bleh = if (arg == 1) 1 else 1, }; if (st.bleh == 1) return 1234; return 0; } const Structy = struct { bleh: i32, }; }; try expect(S.doTheTest(0) == 1234); try expect(S.doTheTest(1) == 1234); } fn ZA() type { return struct { b: B(), const Self = @This(); fn B() type { return struct { const Self = @This(); }; } }; } test "non-ambiguous reference of shadowed decls" { try expect(ZA().B().Self != ZA().Self); } test "use of declaration with same name as primitive" { const S = struct { const @"u8" = u16; const alias = @"u8"; }; const a: S.u8 = 300; try expect(a == 300); const b: S.alias = 300; try expect(b == 300); const @"u8" = u16; const c: @"u8" = 300; try expect(c == 300); } fn emptyFn() void {} test "constant equal function pointers" { const alias = emptyFn; try expect(comptime x: { break :x emptyFn == alias; }); } test "multiline string literal is null terminated" { const s1 = \\one \\two) \\three ; const s2 = "one\ntwo)\nthree"; try expect(std.cstr.cmp(s1, s2) == 0); } test "self reference through fn ptr field" { const S = struct { const A = struct { f: fn (A) u8, }; fn foo(a: A) u8 { _ = a; return 12; } }; var a: S.A = undefined; a.f = S.foo; try expect(a.f(a) == 12); } test "global variable initialized to global variable array element" { try expect(global_ptr == &gdt[0]); } const GDTEntry = struct { field: i32, }; var gdt = [_]GDTEntry{ GDTEntry{ .field = 1 }, GDTEntry{ .field = 2 }, }; var global_ptr = &gdt[0]; test "global constant is loaded with a runtime-known index" { const S = struct { fn doTheTest() !void { var index: usize = 1; const ptr = &pieces[index].field; try expect(ptr.* == 2); } const Piece = struct { field: i32, }; const pieces = [_]Piece{ Piece{ .field = 1 }, Piece{ .field = 2 }, Piece{ .field = 3 } }; }; try S.doTheTest(); }
test/behavior/basic_llvm.zig
const builtin = @import("builtin"); const std = @import("std"); const math = std.math; const assert = std.debug.assert; const testing = std.testing; pub fn powci(comptime x: comptime_int, y: comptime_int) comptime_int { return if (y == 0) 1 else switch (x) { 0 => 0, 1 => 1, else => blk: { if (x == -1) { return if (y % 2 == 0) 1 else -1; } comptime var base = x; comptime var exp = y; comptime var acc = 1; while (exp > 1) { if (exp & 1 == 1) { acc = acc * base; } exp >>= 1; base = base * base; } if (exp == 1) { acc = acc * base; } break :blk acc; }, }; } // tests from zig std powi test "math.powci" { testing.expect(powci(-5, 3) == -125); testing.expect(powci(-16, 3) == -4096); testing.expect(powci(-91, 3) == -753571); testing.expect(powci(-36, 6) == 2176782336); testing.expect(powci(-2, 15) == -32768); testing.expect(powci(-5, 7) == -78125); testing.expect(powci(6, 2) == 36); testing.expect(powci(5, 4) == 625); testing.expect(powci(12, 6) == 2985984); testing.expect(powci(34, 2) == 1156); testing.expect(powci(16, 3) == 4096); testing.expect(powci(34, 6) == 1544804416); } test "math.powci.special" { testing.expect(powci(-1, 3) == -1); testing.expect(powci(-1, 2) == 1); testing.expect(powci(-1, 16) == 1); testing.expect(powci(-1, 6) == 1); testing.expect(powci(-1, 15) == -1); testing.expect(powci(-1, 7) == -1); testing.expect(powci(1, 2) == 1); testing.expect(powci(1, 4) == 1); testing.expect(powci(1, 6) == 1); testing.expect(powci(1, 2) == 1); testing.expect(powci(1, 3) == 1); testing.expect(powci(1, 6) == 1); testing.expect(powci(6, 0) == 1); testing.expect(powci(5, 0) == 1); testing.expect(powci(12, 0) == 1); testing.expect(powci(34, 0) == 1); testing.expect(powci(16, 0) == 1); testing.expect(powci(34, 0) == 1); }
src/powci.zig
const std = @import( "std" ); const min = std.math.min; const max = std.math.max; const sqrt = std.math.sqrt; const minInt = std.math.minInt; const Atomic = std.atomic.Atomic; const milliTimestamp = std.time.milliTimestamp; usingnamespace @import( "core/util.zig" ); pub fn SimConfig( comptime N: usize, comptime P: usize ) type { return struct { frameInterval_MILLIS: i64, timestep: f64, xLimits: [N]Interval, particles: [P]Particle(N), accelerators: []*const Accelerator(N,P), }; } pub fn Accelerator( comptime N: usize, comptime P: usize ) type { return struct { const Self = @This(); addAccelerationFn: fn ( self: *const Self, xs: *const [N*P]f64, ms: *const [P]f64, p: usize, x: [N]f64, aSum_OUT: *[N]f64 ) void, computePotentialEnergyFn: fn ( self: *const Self, xs: *const [N*P]f64, ms: *const [P]f64 ) f64, pub fn addAcceleration( self: *const Self, xs: *const [N*P]f64, ms: *const [P]f64, p: usize, x: [N]f64, aSum_OUT: *[N]f64 ) void { return self.addAccelerationFn( self, xs, ms, p, x, aSum_OUT ); } pub fn computePotentialEnergy( self: *const Self, xs: *const [N*P]f64, ms: *const [P]f64 ) f64 { return self.computePotentialEnergyFn( self, xs, ms ); } }; } pub fn Particle( comptime N: usize ) type { return struct { const Self = @This(); m: f64, x: [N]f64, v: [N]f64, pub fn init( m: f64, x: [N]f64, v: [N]f64 ) Self { return .{ .m = m, .x = x, .v = v, }; } }; } pub fn SimFrame( comptime N: usize, comptime P: usize ) type { return struct { config: *const SimConfig(N,P), t: f64, ms: *const [P]f64, xs: *const [N*P]f64, vs: *const [N*P]f64, }; } pub fn SimListener( comptime N: usize, comptime P: usize ) type { return struct { const Self = @This(); handleFrameFn: fn ( self: *Self, simFrame: *const SimFrame(N,P) ) anyerror!void, pub fn handleFrame( self: *Self, simFrame: *const SimFrame(N,P) ) !void { return self.handleFrameFn( self, simFrame ); } }; } /// Caller must ensure that locations pointed to by input /// args remain valid until after this fn returns. pub fn runSimulation( comptime N: usize, comptime P: usize, config: *const SimConfig(N,P), listeners: []const *SimListener(N,P), running: *const Atomic(bool), ) !void { // TODO: Use SIMD Vectors? // TODO: Multi-thread? (If so, avoid false sharing) const tFull = config.timestep; const tHalf = 0.5*tFull; const accelerators = config.accelerators; var msArray = @as( [P]f64, undefined ); var xsStart = @as( [N*P]f64, undefined ); var vsStart = @as( [N*P]f64, undefined ); for ( config.particles ) |particle, p| { msArray[p] = particle.m; xsStart[ p*N.. ][ 0..N ].* = particle.x; vsStart[ p*N.. ][ 0..N ].* = particle.v; } const ms = &msArray; var xMins = @as( [N]f64, undefined ); var xMaxs = @as( [N]f64, undefined ); for ( config.xLimits ) |xLimit, n| { const xLimitA = xLimit.start; const xLimitB = xLimit.start + xLimit.span; xMins[n] = min( xLimitA, xLimitB ); xMaxs[n] = max( xLimitA, xLimitB ); } // Pre-compute the index of the first coord of each particle, for easy iteration later var particleFirstCoordIndices = @as( [P]usize, undefined ); { var p = @as( usize, 0 ); while ( p < P ) : ( p += 1 ) { particleFirstCoordIndices[p] = p * N; } } var coordArrays = @as( [7][N*P]f64, undefined ); var xsCurr = &coordArrays[0]; var xsNext = &coordArrays[1]; var vsCurr = &coordArrays[2]; var vsHalf = &coordArrays[3]; var vsNext = &coordArrays[4]; var asCurr = &coordArrays[5]; var asNext = &coordArrays[6]; xsCurr[ 0..N*P ].* = xsStart; vsCurr[ 0..N*P ].* = vsStart; for ( particleFirstCoordIndices ) |c0, p| { const xCurr = xsCurr[ c0.. ][ 0..N ]; var aCurr = asCurr[ c0.. ][ 0..N ]; aCurr.* = [1]f64 { 0.0 } ** N; for ( accelerators ) |accelerator| { accelerator.addAcceleration( xsCurr, ms, p, xCurr.*, aCurr ); } } const frameInterval_MILLIS = config.frameInterval_MILLIS; var nextFrame_PMILLIS = @as( i64, minInt( i64 ) ); var tElapsed = @as( f64, 0 ); while ( running.load( .SeqCst ) ) : ( tElapsed += tFull ) { // Send particle coords to the listener periodically const now_PMILLIS = milliTimestamp( ); if ( now_PMILLIS >= nextFrame_PMILLIS ) { const frame = SimFrame(N,P) { .config = config, .t = tElapsed, .ms = ms, .xs = xsCurr, .vs = vsCurr, }; for ( listeners ) |listener| { try listener.handleFrame( &frame ); } nextFrame_PMILLIS = now_PMILLIS + frameInterval_MILLIS; } // Update particle coords, but without checking for bounces for ( vsCurr ) |vCurr, c| { vsHalf[c] = vCurr + asCurr[c]*tHalf; } for ( xsCurr ) |xCurr, c| { xsNext[c] = xCurr + vsHalf[c]*tFull; } for ( particleFirstCoordIndices ) |c0, p| { var xNext = xsNext[ c0.. ][ 0..N ]; var aNext = asNext[ c0.. ][ 0..N ]; aNext.* = [1]f64 { 0.0 } ** N; for ( accelerators ) |accelerator| { accelerator.addAcceleration( xsCurr, ms, p, xNext.*, aNext ); } } for ( vsHalf ) |vHalf, c| { vsNext[c] = vHalf + asNext[c]*tHalf; } // Handle bounces for ( particleFirstCoordIndices ) |c0, p| { // TODO: Profile, speed up var xNext = xsNext[ c0.. ][ 0..N ]; // Bail immediately in the common case with no bounce var hasBounce = false; for ( xNext ) |xNext_n, n| { if ( xNext_n <= xMins[n] or xNext_n >= xMaxs[n] ) { hasBounce = true; break; } const aCurr_n = asCurr[ c0 + n ]; const vCurr_n = vsCurr[ c0 + n ]; const tTip_n = vCurr_n / ( -2.0 * aCurr_n ); if ( 0 <= tTip_n and tTip_n < tFull ) { const xCurr_n = xsCurr[ c0 + n ]; const xTip_n = xCurr_n + vCurr_n*tTip_n + 0.5*aCurr_n*tTip_n*tTip_n; if ( xTip_n <= xMins[n] or xTip_n >= xMaxs[n] ) { hasBounce = true; break; } } } if ( !hasBounce ) { continue; } var aNext = asNext[ c0.. ][ 0..N ]; var vNext = vsNext[ c0.. ][ 0..N ]; var vHalf = vsHalf[ c0.. ][ 0..N ]; var aCurr = @as( [N]f64, undefined ); var vCurr = @as( [N]f64, undefined ); var xCurr = @as( [N]f64, undefined ); aCurr = asCurr[ c0.. ][ 0..N ].*; vCurr = vsCurr[ c0.. ][ 0..N ].*; xCurr = xsCurr[ c0.. ][ 0..N ].*; while ( true ) { // Time of soonest bounce, and what to multiply each velocity coord by at that time var tBounce = std.math.inf( f64 ); var vBounceFactor = [1]f64 { 1.0 } ** N; for ( xNext ) |xNext_n, n| { var hasMinBounce = false; var hasMaxBounce = false; if ( xNext_n <= xMins[n] ) { hasMinBounce = true; } else if ( xNext_n >= xMaxs[n] ) { hasMaxBounce = true; } const tTip_n = vCurr[n] / ( -2.0 * aCurr[n] ); if ( 0 <= tTip_n and tTip_n < tFull ) { const xTip_n = xCurr[n] + vCurr[n]*tTip_n + 0.5*aCurr[n]*tTip_n*tTip_n; if ( xTip_n <= xMins[n] ) { hasMinBounce = true; } else if ( xTip_n >= xMaxs[n] ) { hasMaxBounce = true; } } // At most 4 bounce times will be appended var tsBounce_n_ = @as( [4]f64, undefined ); var tsBounce_n = Buffer.init( &tsBounce_n_ ); if ( hasMinBounce ) { appendBounceTimes( xCurr[n], vCurr[n], aCurr[n], xMins[n], &tsBounce_n ); } if ( hasMaxBounce ) { appendBounceTimes( xCurr[n], vCurr[n], aCurr[n], xMaxs[n], &tsBounce_n ); } for ( tsBounce_n.items[ 0..tsBounce_n.size ] ) |tBounce_n| { if ( 0 <= tBounce_n and tBounce_n < tFull ) { if ( tBounce_n < tBounce ) { tBounce = tBounce_n; vBounceFactor = [1]f64 { 1.0 } ** N; vBounceFactor[n] = -1.0; } else if ( tBounce_n == tBounce ) { vBounceFactor[n] = -1.0; } } } } // If soonest bounce is after timestep end, then bounce update is done if ( tBounce > tFull ) { break; } // Update from 0 to tBounce { var tFull_ = tBounce; var tHalf_ = 0.5 * tFull_; var aNext_ = @as( [N]f64, undefined ); var vNext_ = @as( [N]f64, undefined ); var xNext_ = @as( [N]f64, undefined ); for ( vCurr ) |vCurr_n, n| { vHalf[n] = vCurr_n + aCurr[n]*tHalf_; } for ( xCurr ) |xCurr_n, n| { xNext_[n] = xCurr_n + vHalf[n]*tFull_; } aNext_ = [1]f64 { 0.0 } ** N; for ( accelerators ) |accelerator| { accelerator.addAcceleration( xsCurr, ms, p, xNext_, &aNext_ ); } for ( vHalf ) |vHalf_n, n| { vNext_[n] = vHalf_n + aNext_[n]*tHalf_; } aCurr = aNext_; for ( vNext_ ) |vNext_n, n| { vCurr[n] = vBounceFactor[n] * vNext_n; } xCurr = xNext_; } // Update from tBounce to tFull { var tFull_ = tFull - tBounce; var tHalf_ = 0.5 * tFull_; for ( vCurr ) |vCurr_n, n| { vHalf[n] = vCurr_n + aCurr[n]*tHalf_; } for ( xCurr ) |xCurr_n, n| { xNext[n] = xCurr_n + vHalf[n]*tFull_; } aNext.* = [1]f64 { 0.0 } ** N; for ( accelerators ) |accelerator| { accelerator.addAcceleration( xsCurr, ms, p, xNext.*, aNext ); } for ( vHalf ) |vHalf_n, n| { vNext[n] = vHalf_n + aNext[n]*tHalf_; } } } } // Rotate slices swap( *[N*P]f64, &asCurr, &asNext ); swap( *[N*P]f64, &vsCurr, &vsNext ); swap( *[N*P]f64, &xsCurr, &xsNext ); } } const Buffer = struct { items: []f64, size: usize, pub fn init( items: []f64 ) Buffer { return Buffer { .items = items, .size = 0, }; } pub fn append( self: *Buffer, item: f64 ) void { if ( self.size < 0 or self.size >= self.items.len ) { std.debug.panic( "Failed to append to buffer: capacity = {d}, size = {d}", .{ self.items.len, self.size } ); } self.items[ self.size ] = item; self.size += 1; } }; /// May append up to 2 values to tsWall_OUT. fn appendBounceTimes( x: f64, v: f64, a: f64, xWall: f64, tsWall_OUT: *Buffer ) void { const A = 0.5*a; const B = v; const C = x - xWall; if ( A == 0.0 ) { // Bt + C = 0 const tWall = -C / B; tsWall_OUT.append( tWall ); } else { // At² + Bt + C = 0 const D = B*B - 4.0*A*C; if ( D >= 0.0 ) { const sqrtD = sqrt( D ); const oneOverTwoA = 0.5 / A; const tWallPlus = ( -B + sqrtD )*oneOverTwoA; const tWallMinus = ( -B - sqrtD )*oneOverTwoA; tsWall_OUT.append( tWallPlus ); tsWall_OUT.append( tWallMinus ); } } } fn swap( comptime T: type, a: *T, b: *T ) void { const temp = a.*; a.* = b.*; b.* = temp; }
src/sim.zig
const ImageReader = zigimg.ImageReader; const ImageSeekStream = zigimg.ImageSeekStream; const PixelFormat = zigimg.PixelFormat; const assert = std.debug.assert; const color = zigimg.color; const errors = zigimg.errors; const png = zigimg.png; const std = @import("std"); const testing = std.testing; const zigimg = @import("zigimg"); const helpers = @import("../helpers.zig"); test "Read bgai4a08 properly" { const file = try helpers.testOpenFile(helpers.zigimg_test_allocator, "tests/fixtures/png/bgai4a08.png"); defer file.close(); var stream_source = std.io.StreamSource{ .file = file }; var pngFile = png.PNG.init(helpers.zigimg_test_allocator); defer pngFile.deinit(); var pixelsOpt: ?color.ColorStorage = null; try pngFile.read(stream_source.reader(), stream_source.seekableStream(), &pixelsOpt); defer { if (pixelsOpt) |pixels| { pixels.deinit(helpers.zigimg_test_allocator); } } try testing.expect(pngFile.getBackgroundColorChunk() == null); try testing.expect(pixelsOpt != null); if (pixelsOpt) |pixels| { try testing.expect(pixels == .Grayscale8Alpha); try helpers.expectEq(pixels.Grayscale8Alpha[0].value, 255); try helpers.expectEq(pixels.Grayscale8Alpha[0].alpha, 0); try helpers.expectEq(pixels.Grayscale8Alpha[31].value, 255); try helpers.expectEq(pixels.Grayscale8Alpha[31].alpha, 255); try helpers.expectEq(pixels.Grayscale8Alpha[15 * 32 + 15].value, 131); try helpers.expectEq(pixels.Grayscale8Alpha[15 * 32 + 15].alpha, 123); try helpers.expectEq(pixels.Grayscale8Alpha[31 * 32 + 31].value, 0); try helpers.expectEq(pixels.Grayscale8Alpha[31 * 32 + 31].alpha, 255); } } test "Read bgbn4a08 properly" { const file = try helpers.testOpenFile(helpers.zigimg_test_allocator, "tests/fixtures/png/bgbn4a08.png"); defer file.close(); var stream_source = std.io.StreamSource{ .file = file }; var pngFile = png.PNG.init(helpers.zigimg_test_allocator); defer pngFile.deinit(); var pixelsOpt: ?color.ColorStorage = null; try pngFile.read(stream_source.reader(), stream_source.seekableStream(), &pixelsOpt); defer { if (pixelsOpt) |pixels| { pixels.deinit(helpers.zigimg_test_allocator); } } try testing.expect(pngFile.getBackgroundColorChunk() != null); if (pngFile.getBackgroundColorChunk()) |bkgd_chunk| { try testing.expect(bkgd_chunk.color == .Grayscale); try helpers.expectEq(bkgd_chunk.grayscale, 0); } try testing.expect(pixelsOpt != null); if (pixelsOpt) |pixels| { try testing.expect(pixels == .Grayscale8Alpha); try helpers.expectEq(pixels.Grayscale8Alpha[0].value, 255); try helpers.expectEq(pixels.Grayscale8Alpha[0].alpha, 0); try helpers.expectEq(pixels.Grayscale8Alpha[31].value, 255); try helpers.expectEq(pixels.Grayscale8Alpha[31].alpha, 255); try helpers.expectEq(pixels.Grayscale8Alpha[15 * 32 + 15].value, 131); try helpers.expectEq(pixels.Grayscale8Alpha[15 * 32 + 15].alpha, 123); try helpers.expectEq(pixels.Grayscale8Alpha[31 * 32 + 31].value, 0); try helpers.expectEq(pixels.Grayscale8Alpha[31 * 32 + 31].alpha, 255); } } test "Read bgai4a16 properly" { const file = try helpers.testOpenFile(helpers.zigimg_test_allocator, "tests/fixtures/png/bgai4a16.png"); defer file.close(); var stream_source = std.io.StreamSource{ .file = file }; var pngFile = png.PNG.init(helpers.zigimg_test_allocator); defer pngFile.deinit(); var pixelsOpt: ?color.ColorStorage = null; try pngFile.read(stream_source.reader(), stream_source.seekableStream(), &pixelsOpt); defer { if (pixelsOpt) |pixels| { pixels.deinit(helpers.zigimg_test_allocator); } } try testing.expect(pngFile.getBackgroundColorChunk() == null); try testing.expect(pixelsOpt != null); if (pixelsOpt) |pixels| { try testing.expect(pixels == .Grayscale16Alpha); try helpers.expectEq(pixels.Grayscale16Alpha[0].value, 0); try helpers.expectEq(pixels.Grayscale16Alpha[0].alpha, 0); try helpers.expectEq(pixels.Grayscale16Alpha[31].value, 0); try helpers.expectEq(pixels.Grayscale16Alpha[31].alpha, 0); try helpers.expectEq(pixels.Grayscale16Alpha[15 * 32 + 15].value, 0); try helpers.expectEq(pixels.Grayscale16Alpha[15 * 32 + 15].alpha, 63421); try helpers.expectEq(pixels.Grayscale16Alpha[31 * 32 + 31].value, 0); try helpers.expectEq(pixels.Grayscale16Alpha[31 * 32 + 31].alpha, 0); } } test "Read bggn4a16 properly" { const file = try helpers.testOpenFile(helpers.zigimg_test_allocator, "tests/fixtures/png/bggn4a16.png"); defer file.close(); var stream_source = std.io.StreamSource{ .file = file }; var pngFile = png.PNG.init(helpers.zigimg_test_allocator); defer pngFile.deinit(); var pixelsOpt: ?color.ColorStorage = null; try pngFile.read(stream_source.reader(), stream_source.seekableStream(), &pixelsOpt); defer { if (pixelsOpt) |pixels| { pixels.deinit(helpers.zigimg_test_allocator); } } try testing.expect(pngFile.getBackgroundColorChunk() != null); if (pngFile.getBackgroundColorChunk()) |bkgd_chunk| { try testing.expect(bkgd_chunk.color == .Grayscale); try helpers.expectEq(bkgd_chunk.grayscale, 43908); } try testing.expect(pixelsOpt != null); if (pixelsOpt) |pixels| { try testing.expect(pixels == .Grayscale16Alpha); try helpers.expectEq(pixels.Grayscale16Alpha[0].value, 0); try helpers.expectEq(pixels.Grayscale16Alpha[0].alpha, 0); try helpers.expectEq(pixels.Grayscale16Alpha[31].value, 0); try helpers.expectEq(pixels.Grayscale16Alpha[31].alpha, 0); try helpers.expectEq(pixels.Grayscale16Alpha[15 * 32 + 15].value, 0); try helpers.expectEq(pixels.Grayscale16Alpha[15 * 32 + 15].alpha, 63421); try helpers.expectEq(pixels.Grayscale16Alpha[31 * 32 + 31].value, 0); try helpers.expectEq(pixels.Grayscale16Alpha[31 * 32 + 31].alpha, 0); } } test "Read bgan6a08 properly" { const file = try helpers.testOpenFile(helpers.zigimg_test_allocator, "tests/fixtures/png/bgan6a08.png"); defer file.close(); var stream_source = std.io.StreamSource{ .file = file }; var pngFile = png.PNG.init(helpers.zigimg_test_allocator); defer pngFile.deinit(); var pixelsOpt: ?color.ColorStorage = null; try pngFile.read(stream_source.reader(), stream_source.seekableStream(), &pixelsOpt); defer { if (pixelsOpt) |pixels| { pixels.deinit(helpers.zigimg_test_allocator); } } try testing.expect(pngFile.getBackgroundColorChunk() == null); try testing.expect(pixelsOpt != null); if (pixelsOpt) |pixels| { try testing.expect(pixels == .Rgba32); try helpers.expectEq(pixels.Rgba32[0].R, 255); try helpers.expectEq(pixels.Rgba32[0].G, 0); try helpers.expectEq(pixels.Rgba32[0].B, 8); try helpers.expectEq(pixels.Rgba32[0].A, 0); try helpers.expectEq(pixels.Rgba32[31].R, 255); try helpers.expectEq(pixels.Rgba32[31].G, 0); try helpers.expectEq(pixels.Rgba32[31].B, 8); try helpers.expectEq(pixels.Rgba32[31].A, 255); try helpers.expectEq(pixels.Rgba32[15 * 32 + 15].R, 32); try helpers.expectEq(pixels.Rgba32[15 * 32 + 15].G, 255); try helpers.expectEq(pixels.Rgba32[15 * 32 + 15].B, 4); try helpers.expectEq(pixels.Rgba32[15 * 32 + 15].A, 123); try helpers.expectEq(pixels.Rgba32[31 * 32 + 31].R, 0); try helpers.expectEq(pixels.Rgba32[31 * 32 + 31].G, 32); try helpers.expectEq(pixels.Rgba32[31 * 32 + 31].B, 255); try helpers.expectEq(pixels.Rgba32[31 * 32 + 31].A, 255); } } test "Read bgwn6a08 properly" { const file = try helpers.testOpenFile(helpers.zigimg_test_allocator, "tests/fixtures/png/bgwn6a08.png"); defer file.close(); var stream_source = std.io.StreamSource{ .file = file }; var pngFile = png.PNG.init(helpers.zigimg_test_allocator); defer pngFile.deinit(); var pixelsOpt: ?color.ColorStorage = null; try pngFile.read(stream_source.reader(), stream_source.seekableStream(), &pixelsOpt); defer { if (pixelsOpt) |pixels| { pixels.deinit(helpers.zigimg_test_allocator); } } try testing.expect(pngFile.getBackgroundColorChunk() != null); if (pngFile.getBackgroundColorChunk()) |bkgd_chunk| { try testing.expect(bkgd_chunk.color == .TrueColor); try helpers.expectEq(bkgd_chunk.red, 255); try helpers.expectEq(bkgd_chunk.green, 255); try helpers.expectEq(bkgd_chunk.blue, 255); } try testing.expect(pixelsOpt != null); if (pixelsOpt) |pixels| { try testing.expect(pixels == .Rgba32); try helpers.expectEq(pixels.Rgba32[0].R, 255); try helpers.expectEq(pixels.Rgba32[0].G, 0); try helpers.expectEq(pixels.Rgba32[0].B, 8); try helpers.expectEq(pixels.Rgba32[0].A, 0); try helpers.expectEq(pixels.Rgba32[31].R, 255); try helpers.expectEq(pixels.Rgba32[31].G, 0); try helpers.expectEq(pixels.Rgba32[31].B, 8); try helpers.expectEq(pixels.Rgba32[31].A, 255); try helpers.expectEq(pixels.Rgba32[15 * 32 + 15].R, 32); try helpers.expectEq(pixels.Rgba32[15 * 32 + 15].G, 255); try helpers.expectEq(pixels.Rgba32[15 * 32 + 15].B, 4); try helpers.expectEq(pixels.Rgba32[15 * 32 + 15].A, 123); try helpers.expectEq(pixels.Rgba32[31 * 32 + 31].R, 0); try helpers.expectEq(pixels.Rgba32[31 * 32 + 31].G, 32); try helpers.expectEq(pixels.Rgba32[31 * 32 + 31].B, 255); try helpers.expectEq(pixels.Rgba32[31 * 32 + 31].A, 255); } } test "Read bgan6a16 properly" { const file = try helpers.testOpenFile(helpers.zigimg_test_allocator, "tests/fixtures/png/bgan6a16.png"); defer file.close(); var stream_source = std.io.StreamSource{ .file = file }; var pngFile = png.PNG.init(helpers.zigimg_test_allocator); defer pngFile.deinit(); var pixelsOpt: ?color.ColorStorage = null; try pngFile.read(stream_source.reader(), stream_source.seekableStream(), &pixelsOpt); defer { if (pixelsOpt) |pixels| { pixels.deinit(helpers.zigimg_test_allocator); } } try testing.expect(pngFile.getBackgroundColorChunk() == null); try testing.expect(pixelsOpt != null); if (pixelsOpt) |pixels| { try testing.expect(pixels == .Rgba64); try helpers.expectEq(pixels.Rgba64[0].R, 65535); try helpers.expectEq(pixels.Rgba64[0].G, 65535); try helpers.expectEq(pixels.Rgba64[0].B, 0); try helpers.expectEq(pixels.Rgba64[0].A, 0); try helpers.expectEq(pixels.Rgba64[31].R, 0); try helpers.expectEq(pixels.Rgba64[31].G, 65535); try helpers.expectEq(pixels.Rgba64[31].B, 0); try helpers.expectEq(pixels.Rgba64[31].A, 0); try helpers.expectEq(pixels.Rgba64[15 * 32 + 15].R, 65535); try helpers.expectEq(pixels.Rgba64[15 * 32 + 15].G, 65535); try helpers.expectEq(pixels.Rgba64[15 * 32 + 15].B, 0); try helpers.expectEq(pixels.Rgba64[15 * 32 + 15].A, 63421); try helpers.expectEq(pixels.Rgba64[31 * 32 + 31].R, 0); try helpers.expectEq(pixels.Rgba64[31 * 32 + 31].G, 0); try helpers.expectEq(pixels.Rgba64[31 * 32 + 31].B, 65535); try helpers.expectEq(pixels.Rgba64[31 * 32 + 31].A, 0); } } test "Read bgyn6a16 properly" { const file = try helpers.testOpenFile(helpers.zigimg_test_allocator, "tests/fixtures/png/bgyn6a16.png"); defer file.close(); var stream_source = std.io.StreamSource{ .file = file }; var pngFile = png.PNG.init(helpers.zigimg_test_allocator); defer pngFile.deinit(); var pixelsOpt: ?color.ColorStorage = null; try pngFile.read(stream_source.reader(), stream_source.seekableStream(), &pixelsOpt); defer { if (pixelsOpt) |pixels| { pixels.deinit(helpers.zigimg_test_allocator); } } try testing.expect(pngFile.getBackgroundColorChunk() != null); if (pngFile.getBackgroundColorChunk()) |bkgd_chunk| { try testing.expect(bkgd_chunk.color == .TrueColor); try helpers.expectEq(bkgd_chunk.red, 65535); try helpers.expectEq(bkgd_chunk.green, 65535); try helpers.expectEq(bkgd_chunk.blue, 0); } try testing.expect(pixelsOpt != null); if (pixelsOpt) |pixels| { try testing.expect(pixels == .Rgba64); try helpers.expectEq(pixels.Rgba64[0].R, 65535); try helpers.expectEq(pixels.Rgba64[0].G, 65535); try helpers.expectEq(pixels.Rgba64[0].B, 0); try helpers.expectEq(pixels.Rgba64[0].A, 0); try helpers.expectEq(pixels.Rgba64[31].R, 0); try helpers.expectEq(pixels.Rgba64[31].G, 65535); try helpers.expectEq(pixels.Rgba64[31].B, 0); try helpers.expectEq(pixels.Rgba64[31].A, 0); try helpers.expectEq(pixels.Rgba64[15 * 32 + 15].R, 65535); try helpers.expectEq(pixels.Rgba64[15 * 32 + 15].G, 65535); try helpers.expectEq(pixels.Rgba64[15 * 32 + 15].B, 0); try helpers.expectEq(pixels.Rgba64[15 * 32 + 15].A, 63421); try helpers.expectEq(pixels.Rgba64[31 * 32 + 31].R, 0); try helpers.expectEq(pixels.Rgba64[31 * 32 + 31].G, 0); try helpers.expectEq(pixels.Rgba64[31 * 32 + 31].B, 65535); try helpers.expectEq(pixels.Rgba64[31 * 32 + 31].A, 0); } }
tests/formats/png_bkgd_test.zig
const std = @import("std.zig"); const assert = std.debug.assert; const testing = std.testing; const Order = std.math.Order; pub fn Treap(comptime Key: type, comptime compareFn: anytype) type { return struct { const Self = @This(); // Allow for compareFn to be fn(anytype, anytype) anytype // which allows the convenient use of std.math.order. fn compare(a: Key, b: Key) Order { return compareFn(a, b); } root: ?*Node = null, prng: Prng = .{}, /// A customized pseudo random number generator for the treap. /// This just helps reducing the memory size of the treap itself /// as std.rand.DefaultPrng requires larger state (while producing better entropy for randomness to be fair). const Prng = struct { xorshift: usize = 0, fn random(self: *Prng, seed: usize) usize { // Lazily seed the prng state if (self.xorshift == 0) { self.xorshift = seed; } // Since we're using usize, decide the shifts by the integer's bit width. const shifts = switch (@bitSizeOf(usize)) { 64 => .{ 13, 7, 17 }, 32 => .{ 13, 17, 5 }, 16 => .{ 7, 9, 8 }, else => @compileError("platform not supported"), }; self.xorshift ^= self.xorshift >> shifts[0]; self.xorshift ^= self.xorshift << shifts[1]; self.xorshift ^= self.xorshift >> shifts[2]; assert(self.xorshift != 0); return self.xorshift; } }; /// A Node represents an item or point in the treap with a uniquely associated key. pub const Node = struct { key: Key, priority: usize, parent: ?*Node, children: [2]?*Node, }; /// Returns the smallest Node by key in the treap if there is one. /// Use `getEntryForExisting()` to replace/remove this Node from the treap. pub fn getMin(self: Self) ?*Node { var node = self.root; while (node) |current| { node = current.children[0] orelse break; } return node; } /// Returns the largest Node by key in the treap if there is one. /// Use `getEntryForExisting()` to replace/remove this Node from the treap. pub fn getMax(self: Self) ?*Node { var node = self.root; while (node) |current| { node = current.children[1] orelse break; } return node; } /// Lookup the Entry for the given key in the treap. /// The Entry act's as a slot in the treap to insert/replace/remove the node associated with the key. pub fn getEntryFor(self: *Self, key: Key) Entry { var parent: ?*Node = undefined; const node = self.find(key, &parent); return Entry{ .key = key, .treap = self, .node = node, .context = .{ .inserted_under = parent }, }; } /// Get an entry for a Node that currently exists in the treap. /// It is undefined behavior if the Node is not currently inserted in the treap. /// The Entry act's as a slot in the treap to insert/replace/remove the node associated with the key. pub fn getEntryForExisting(self: *Self, node: *Node) Entry { assert(node.priority != 0); return Entry{ .key = node.key, .treap = self, .node = node, .context = .{ .inserted_under = node.parent }, }; } /// An Entry represents a slot in the treap associated with a given key. pub const Entry = struct { /// The associated key for this entry. key: Key, /// A reference to the treap this entry is apart of. treap: *Self, /// The current node at this entry. node: ?*Node, /// The current state of the entry. context: union(enum) { /// A find() was called for this entry and the position in the treap is known. inserted_under: ?*Node, /// The entry's node was removed from the treap and a lookup must occur again for modification. removed, }, /// Update's the Node at this Entry in the treap with the new node. pub fn set(self: *Entry, new_node: ?*Node) void { // Update the entry's node reference after updating the treap below. defer self.node = new_node; if (self.node) |old| { if (new_node) |new| { self.treap.replace(old, new); return; } self.treap.remove(old); self.context = .removed; return; } if (new_node) |new| { // A previous treap.remove() could have rebalanced the nodes // so when inserting after a removal, we have to re-lookup the parent again. // This lookup shouldn't find a node because we're yet to insert it.. var parent: ?*Node = undefined; switch (self.context) { .inserted_under => |p| parent = p, .removed => assert(self.treap.find(self.key, &parent) == null), } self.treap.insert(self.key, parent, new); self.context = .{ .inserted_under = parent }; } } }; fn find(self: Self, key: Key, parent_ref: *?*Node) ?*Node { var node = self.root; parent_ref.* = null; // basic binary search while tracking the parent. while (node) |current| { const order = compare(key, current.key); if (order == .eq) break; parent_ref.* = current; node = current.children[@boolToInt(order == .gt)]; } return node; } fn insert(self: *Self, key: Key, parent: ?*Node, node: *Node) void { // generate a random priority & prepare the node to be inserted into the tree node.key = key; node.priority = self.prng.random(@ptrToInt(node)); node.parent = parent; node.children = [_]?*Node{ null, null }; // point the parent at the new node const link = if (parent) |p| &p.children[@boolToInt(compare(key, p.key) == .gt)] else &self.root; assert(link.* == null); link.* = node; // rotate the node up into the tree to balance it according to its priority while (node.parent) |p| { if (p.priority <= node.priority) break; const is_right = p.children[1] == node; assert(p.children[@boolToInt(is_right)] == node); const rotate_right = !is_right; self.rotate(p, rotate_right); } } fn replace(self: *Self, old: *Node, new: *Node) void { // copy over the values from the old node new.key = old.key; new.priority = old.priority; new.parent = old.parent; new.children = old.children; // point the parent at the new node const link = if (old.parent) |p| &p.children[@boolToInt(p.children[1] == old)] else &self.root; assert(link.* == old); link.* = new; // point the children's parent at the new node for (old.children) |child_node| { const child = child_node orelse continue; assert(child.parent == old); child.parent = new; } } fn remove(self: *Self, node: *Node) void { // rotate the node down to be a leaf of the tree for removal, respecting priorities. while (node.children[0] orelse node.children[1]) |_| { self.rotate(node, rotate_right: { const right = node.children[1] orelse break :rotate_right true; const left = node.children[0] orelse break :rotate_right false; break :rotate_right (left.priority < right.priority); }); } // node is a now a leaf; remove by nulling out the parent's reference to it. const link = if (node.parent) |p| &p.children[@boolToInt(p.children[1] == node)] else &self.root; assert(link.* == node); link.* = null; // clean up after ourselves node.key = undefined; node.priority = 0; node.parent = null; node.children = [_]?*Node{ null, null }; } fn rotate(self: *Self, node: *Node, right: bool) void { // if right, converts the following: // parent -> (node (target YY adjacent) XX) // parent -> (target YY (node adjacent XX)) // // if left (!right), converts the following: // parent -> (node (target YY adjacent) XX) // parent -> (target YY (node adjacent XX)) const parent = node.parent; const target = node.children[@boolToInt(!right)] orelse unreachable; const adjacent = target.children[@boolToInt(right)]; // rotate the children target.children[@boolToInt(right)] = node; node.children[@boolToInt(!right)] = adjacent; // rotate the parents node.parent = target; target.parent = parent; if (adjacent) |adj| adj.parent = node; // fix the parent link const link = if (parent) |p| &p.children[@boolToInt(p.children[1] == node)] else &self.root; assert(link.* == node); link.* = target; } }; } // For iterating a slice in a random order // https://lemire.me/blog/2017/09/18/visiting-all-values-in-an-array-exactly-once-in-random-order/ fn SliceIterRandomOrder(comptime T: type) type { return struct { rng: std.rand.Random, slice: []T, index: usize = undefined, offset: usize = undefined, co_prime: usize, const Self = @This(); pub fn init(slice: []T, rng: std.rand.Random) Self { return Self{ .rng = rng, .slice = slice, .co_prime = blk: { if (slice.len == 0) break :blk 0; var prime = slice.len / 2; while (prime < slice.len) : (prime += 1) { var gcd = [_]usize{ prime, slice.len }; while (gcd[1] != 0) { const temp = gcd; gcd = [_]usize{ temp[1], temp[0] % temp[1] }; } if (gcd[0] == 1) break; } break :blk prime; }, }; } pub fn reset(self: *Self) void { self.index = 0; self.offset = self.rng.int(usize); } pub fn next(self: *Self) ?*T { if (self.index >= self.slice.len) return null; defer self.index += 1; return &self.slice[((self.index *% self.co_prime) +% self.offset) % self.slice.len]; } }; } const TestTreap = Treap(u64, std.math.order); const TestNode = TestTreap.Node; test "std.Treap: insert, find, replace, remove" { var treap = TestTreap{}; var nodes: [10]TestNode = undefined; var prng = std.rand.DefaultPrng.init(0xdeadbeef); var iter = SliceIterRandomOrder(TestNode).init(&nodes, prng.random()); // insert check iter.reset(); while (iter.next()) |node| { const key = prng.random().int(u64); // make sure the current entry is empty. var entry = treap.getEntryFor(key); try testing.expectEqual(entry.key, key); try testing.expectEqual(entry.node, null); // insert the entry and make sure the fields are correct. entry.set(node); try testing.expectEqual(node.key, key); try testing.expectEqual(entry.key, key); try testing.expectEqual(entry.node, node); } // find check iter.reset(); while (iter.next()) |node| { const key = node.key; // find the entry by-key and by-node after having been inserted. var entry = treap.getEntryFor(node.key); try testing.expectEqual(entry.key, key); try testing.expectEqual(entry.node, node); try testing.expectEqual(entry.node, treap.getEntryForExisting(node).node); } // replace check iter.reset(); while (iter.next()) |node| { const key = node.key; // find the entry by node since we already know it exists var entry = treap.getEntryForExisting(node); try testing.expectEqual(entry.key, key); try testing.expectEqual(entry.node, node); var stub_node: TestNode = undefined; // replace the node with a stub_node and ensure future finds point to the stub_node. entry.set(&stub_node); try testing.expectEqual(entry.node, &stub_node); try testing.expectEqual(entry.node, treap.getEntryFor(key).node); try testing.expectEqual(entry.node, treap.getEntryForExisting(&stub_node).node); // replace the stub_node back to the node and ensure future finds point to the old node. entry.set(node); try testing.expectEqual(entry.node, node); try testing.expectEqual(entry.node, treap.getEntryFor(key).node); try testing.expectEqual(entry.node, treap.getEntryForExisting(node).node); } // remove check iter.reset(); while (iter.next()) |node| { const key = node.key; // find the entry by node since we already know it exists var entry = treap.getEntryForExisting(node); try testing.expectEqual(entry.key, key); try testing.expectEqual(entry.node, node); // remove the node at the entry and ensure future finds point to it being removed. entry.set(null); try testing.expectEqual(entry.node, null); try testing.expectEqual(entry.node, treap.getEntryFor(key).node); // insert the node back and ensure future finds point to the inserted node entry.set(node); try testing.expectEqual(entry.node, node); try testing.expectEqual(entry.node, treap.getEntryFor(key).node); try testing.expectEqual(entry.node, treap.getEntryForExisting(node).node); // remove the node again and make sure it was cleared after the insert entry.set(null); try testing.expectEqual(entry.node, null); try testing.expectEqual(entry.node, treap.getEntryFor(key).node); } }
lib/std/treap.zig
const __muloti4 = @import("muloti4.zig").__muloti4; const testing = @import("std").testing; fn test__muloti4(a: i128, b: i128, expected: i128, expected_overflow: c_int) void { var overflow: c_int = undefined; const x = __muloti4(a, b, &overflow); testing.expect(overflow == expected_overflow and (expected_overflow != 0 or x == expected)); } test "muloti4" { test__muloti4(0, 0, 0, 0); test__muloti4(0, 1, 0, 0); test__muloti4(1, 0, 0, 0); test__muloti4(0, 10, 0, 0); test__muloti4(10, 0, 0, 0); test__muloti4(0, 81985529216486895, 0, 0); test__muloti4(81985529216486895, 0, 0, 0); test__muloti4(0, -1, 0, 0); test__muloti4(-1, 0, 0, 0); test__muloti4(0, -10, 0, 0); test__muloti4(-10, 0, 0, 0); test__muloti4(0, -81985529216486895, 0, 0); test__muloti4(-81985529216486895, 0, 0, 0); test__muloti4(3037000499, 3037000499, 9223372030926249001, 0); test__muloti4(-3037000499, 3037000499, -9223372030926249001, 0); test__muloti4(3037000499, -3037000499, -9223372030926249001, 0); test__muloti4(-3037000499, -3037000499, 9223372030926249001, 0); test__muloti4(4398046511103, 2097152, 9223372036852678656, 0); test__muloti4(-4398046511103, 2097152, -9223372036852678656, 0); test__muloti4(4398046511103, -2097152, -9223372036852678656, 0); test__muloti4(-4398046511103, -2097152, 9223372036852678656, 0); test__muloti4(2097152, 4398046511103, 9223372036852678656, 0); test__muloti4(-2097152, 4398046511103, -9223372036852678656, 0); test__muloti4(2097152, -4398046511103, -9223372036852678656, 0); test__muloti4(-2097152, -4398046511103, 9223372036852678656, 0); test__muloti4(@bitCast(i128, @as(u128, 0x00000000000000B504F333F9DE5BE000)), @bitCast(i128, @as(u128, 0x000000000000000000B504F333F9DE5B)), @bitCast(i128, @as(u128, 0x7FFFFFFFFFFFF328DF915DA296E8A000)), 0); test__muloti4(@bitCast(i128, @as(u128, 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF)), -2, @bitCast(i128, @as(u128, 0x80000000000000000000000000000001)), 1); test__muloti4(-2, @bitCast(i128, @as(u128, 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF)), @bitCast(i128, @as(u128, 0x80000000000000000000000000000001)), 1); test__muloti4(@bitCast(i128, @as(u128, 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF)), -1, @bitCast(i128, @as(u128, 0x80000000000000000000000000000001)), 0); test__muloti4(-1, @bitCast(i128, @as(u128, 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF)), @bitCast(i128, @as(u128, 0x80000000000000000000000000000001)), 0); test__muloti4(@bitCast(i128, @as(u128, 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF)), 0, 0, 0); test__muloti4(0, @bitCast(i128, @as(u128, 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF)), 0, 0); test__muloti4(@bitCast(i128, @as(u128, 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF)), 1, @bitCast(i128, @as(u128, 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF)), 0); test__muloti4(1, @bitCast(i128, @as(u128, 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF)), @bitCast(i128, @as(u128, 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF)), 0); test__muloti4(@bitCast(i128, @as(u128, 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF)), 2, @bitCast(i128, @as(u128, 0x80000000000000000000000000000001)), 1); test__muloti4(2, @bitCast(i128, @as(u128, 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF)), @bitCast(i128, @as(u128, 0x80000000000000000000000000000001)), 1); test__muloti4(@bitCast(i128, @as(u128, 0x80000000000000000000000000000000)), -2, @bitCast(i128, @as(u128, 0x80000000000000000000000000000000)), 1); test__muloti4(-2, @bitCast(i128, @as(u128, 0x80000000000000000000000000000000)), @bitCast(i128, @as(u128, 0x80000000000000000000000000000000)), 1); test__muloti4(@bitCast(i128, @as(u128, 0x80000000000000000000000000000000)), -1, @bitCast(i128, @as(u128, 0x80000000000000000000000000000000)), 1); test__muloti4(-1, @bitCast(i128, @as(u128, 0x80000000000000000000000000000000)), @bitCast(i128, @as(u128, 0x80000000000000000000000000000000)), 1); test__muloti4(@bitCast(i128, @as(u128, 0x80000000000000000000000000000000)), 0, 0, 0); test__muloti4(0, @bitCast(i128, @as(u128, 0x80000000000000000000000000000000)), 0, 0); test__muloti4(@bitCast(i128, @as(u128, 0x80000000000000000000000000000000)), 1, @bitCast(i128, @as(u128, 0x80000000000000000000000000000000)), 0); test__muloti4(1, @bitCast(i128, @as(u128, 0x80000000000000000000000000000000)), @bitCast(i128, @as(u128, 0x80000000000000000000000000000000)), 0); test__muloti4(@bitCast(i128, @as(u128, 0x80000000000000000000000000000000)), 2, @bitCast(i128, @as(u128, 0x80000000000000000000000000000000)), 1); test__muloti4(2, @bitCast(i128, @as(u128, 0x80000000000000000000000000000000)), @bitCast(i128, @as(u128, 0x80000000000000000000000000000000)), 1); test__muloti4(@bitCast(i128, @as(u128, 0x80000000000000000000000000000001)), -2, @bitCast(i128, @as(u128, 0x80000000000000000000000000000001)), 1); test__muloti4(-2, @bitCast(i128, @as(u128, 0x80000000000000000000000000000001)), @bitCast(i128, @as(u128, 0x80000000000000000000000000000001)), 1); test__muloti4(@bitCast(i128, @as(u128, 0x80000000000000000000000000000001)), -1, @bitCast(i128, @as(u128, 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF)), 0); test__muloti4(-1, @bitCast(i128, @as(u128, 0x80000000000000000000000000000001)), @bitCast(i128, @as(u128, 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF)), 0); test__muloti4(@bitCast(i128, @as(u128, 0x80000000000000000000000000000001)), 0, 0, 0); test__muloti4(0, @bitCast(i128, @as(u128, 0x80000000000000000000000000000001)), 0, 0); test__muloti4(@bitCast(i128, @as(u128, 0x80000000000000000000000000000001)), 1, @bitCast(i128, @as(u128, 0x80000000000000000000000000000001)), 0); test__muloti4(1, @bitCast(i128, @as(u128, 0x80000000000000000000000000000001)), @bitCast(i128, @as(u128, 0x80000000000000000000000000000001)), 0); test__muloti4(@bitCast(i128, @as(u128, 0x80000000000000000000000000000001)), 2, @bitCast(i128, @as(u128, 0x80000000000000000000000000000000)), 1); test__muloti4(2, @bitCast(i128, @as(u128, 0x80000000000000000000000000000001)), @bitCast(i128, @as(u128, 0x80000000000000000000000000000000)), 1); }
lib/std/special/compiler_rt/muloti4_test.zig
const util = @import("../sdf_util.zig"); pub const info: util.SdfInfo = .{ .name = "Transform", .data_size = @sizeOf(Data), .function_definition = "", .enter_command_fn = enterCommand, .exit_command_fn = exitCommand, .sphere_bound_fn = sphereBound, }; pub const Data = struct { rotation: util.math.vec3, translation: util.math.vec3, transform_matrix: util.math.mat4x4, }; pub fn initZero(buffer: *[]u8) void { const data: *Data = @ptrCast(*Data, @alignCast(@alignOf(Data), buffer.ptr)); data.rotation = util.math.Vec3.zeros(); data.translation = util.math.Vec3.zeros(); data.transform_matrix = util.math.Mat4x4.identity(); } pub fn translate(buffer: *[]u8, v: util.math.vec3) void { const data: *Data = @ptrCast(*Data, @alignCast(@alignOf(Data), buffer.ptr)); data.translation += v; } pub fn updateMatrix(buffer: *[]u8) void { const data: *Data = @ptrCast(*Data, @alignCast(@alignOf(Data), buffer.ptr)); data.transform_matrix = util.math.Mat4x4.identity(); util.math.Transform.rotateX(&data.transform_matrix, -data.rotation[0]); util.math.Transform.rotateY(&data.transform_matrix, -data.rotation[1]); util.math.Transform.rotateZ(&data.transform_matrix, -data.rotation[2]); util.math.Transform.translate(&data.transform_matrix, -data.translation); } fn enterCommand(ctxt: *util.IterationContext, iter: usize, mat_offset: usize, buffer: *[]u8) []const u8 { _ = mat_offset; const data: *Data = @ptrCast(*Data, @alignCast(@alignOf(Data), buffer.ptr)); const next_point: []const u8 = util.std.fmt.allocPrint(ctxt.allocator, "p{d}", .{iter}) catch unreachable; const temp: []const u8 = util.std.fmt.allocPrint(ctxt.allocator, "mat4({d:.5},{d:.5},{d:.5},{d:.5}, {d:.5},{d:.5},{d:.5},{d:.5}, {d:.5},{d:.5},{d:.5},{d:.5}, {d:.5},{d:.5},{d:.5},{d:.5})", .{ data.transform_matrix[0][0], data.transform_matrix[0][1], data.transform_matrix[0][2], data.transform_matrix[0][3], data.transform_matrix[1][0], data.transform_matrix[1][1], data.transform_matrix[1][2], data.transform_matrix[1][3], data.transform_matrix[2][0], data.transform_matrix[2][1], data.transform_matrix[2][2], data.transform_matrix[2][3], data.transform_matrix[3][0], data.transform_matrix[3][1], data.transform_matrix[3][2], data.transform_matrix[3][3], }) catch unreachable; const format: []const u8 = "vec3 {s} = ({s} * vec4({s}, 1.)).xyz;"; const res: []const u8 = util.std.fmt.allocPrint(ctxt.allocator, format, .{ next_point, temp, ctxt.cur_point_name, }) catch unreachable; ctxt.pushPointName(next_point); ctxt.allocator.free(temp); return res; } fn exitCommand(ctxt: *util.IterationContext, iter: usize, buffer: *[]u8) []const u8 { _ = iter; _ = buffer; ctxt.popPointName(); return util.std.fmt.allocPrint(ctxt.allocator, "", .{}) catch unreachable; } fn sphereBound(buffer: *[]u8, bound: *util.math.sphereBound, children: []util.math.sphereBound) void { const data: *Data = @ptrCast(*Data, @alignCast(@alignOf(Data), buffer.ptr)); bound.* = children[0]; bound.*.pos += data.translation; }
src/sdf/modifiers/transform.zig
const std = @import("std"); const assert = std.debug.assert; const math = std.math; const mem = std.mem; const sort = std.sort; const testing = std.testing; const Allocator = std.mem.Allocator; const bu = @import("bits_utils.zig"); const deflate_const = @import("deflate_const.zig"); const max_bits_limit = 16; const LiteralNode = struct { literal: u16, freq: u16, }; // Describes the state of the constructed tree for a given depth. const LevelInfo = struct { // Our level. for better printing level: u32, // The frequency of the last node at this level last_freq: u32, // The frequency of the next character to add to this level next_char_freq: u32, // The frequency of the next pair (from level below) to add to this level. // Only valid if the "needed" value of the next lower level is 0. next_pair_freq: u32, // The number of chains remaining to generate for this level before moving // up to the next level needed: u32, }; // hcode is a huffman code with a bit code and bit length. pub const HuffCode = struct { code: u16 = 0, len: u16 = 0, // set sets the code and length of an hcode. fn set(self: *HuffCode, code: u16, length: u16) void { self.len = length; self.code = code; } }; pub const HuffmanEncoder = struct { codes: []HuffCode, freq_cache: []LiteralNode = undefined, bit_count: [17]u32 = undefined, lns: []LiteralNode = undefined, // sorted by literal, stored to avoid repeated allocation in generate lfs: []LiteralNode = undefined, // sorted by frequency, stored to avoid repeated allocation in generate allocator: Allocator, pub fn deinit(self: *HuffmanEncoder) void { self.allocator.free(self.codes); self.allocator.free(self.freq_cache); } // Update this Huffman Code object to be the minimum code for the specified frequency count. // // freq An array of frequencies, in which frequency[i] gives the frequency of literal i. // max_bits The maximum number of bits to use for any literal. pub fn generate(self: *HuffmanEncoder, freq: []u16, max_bits: u32) void { var list = self.freq_cache[0 .. freq.len + 1]; // Number of non-zero literals var count: u32 = 0; // Set list to be the set of all non-zero literals and their frequencies for (freq) |f, i| { if (f != 0) { list[count] = LiteralNode{ .literal = @intCast(u16, i), .freq = f }; count += 1; } else { list[count] = LiteralNode{ .literal = 0x00, .freq = 0 }; self.codes[i].len = 0; } } list[freq.len] = LiteralNode{ .literal = 0x00, .freq = 0 }; list = list[0..count]; if (count <= 2) { // Handle the small cases here, because they are awkward for the general case code. With // two or fewer literals, everything has bit length 1. for (list) |node, i| { // "list" is in order of increasing literal value. self.codes[node.literal].set(@intCast(u16, i), 1); } return; } self.lfs = list; sort.sort(LiteralNode, self.lfs, {}, byFreq); // Get the number of literals for each bit count var bit_count = self.bitCounts(list, max_bits); // And do the assignment self.assignEncodingAndSize(bit_count, list); } pub fn bitLength(self: *HuffmanEncoder, freq: []u16) u32 { var total: u32 = 0; for (freq) |f, i| { if (f != 0) { total += @intCast(u32, f) * @intCast(u32, self.codes[i].len); } } return total; } // Return the number of literals assigned to each bit size in the Huffman encoding // // This method is only called when list.len >= 3 // The cases of 0, 1, and 2 literals are handled by special case code. // // list: An array of the literals with non-zero frequencies // and their associated frequencies. The array is in order of increasing // frequency, and has as its last element a special element with frequency // std.math.maxInt(i32) // // max_bits: The maximum number of bits that should be used to encode any literal. // Must be less than 16. // // Returns an integer array in which array[i] indicates the number of literals // that should be encoded in i bits. fn bitCounts(self: *HuffmanEncoder, list: []LiteralNode, max_bits_to_use: usize) []u32 { var max_bits = max_bits_to_use; var n = list.len; assert(max_bits < max_bits_limit); // The tree can't have greater depth than n - 1, no matter what. This // saves a little bit of work in some small cases max_bits = @minimum(max_bits, n - 1); // Create information about each of the levels. // A bogus "Level 0" whose sole purpose is so that // level1.prev.needed == 0. This makes level1.next_pair_freq // be a legitimate value that never gets chosen. var levels: [max_bits_limit]LevelInfo = mem.zeroes([max_bits_limit]LevelInfo); // leaf_counts[i] counts the number of literals at the left // of ancestors of the rightmost node at level i. // leaf_counts[i][j] is the number of literals at the left // of the level j ancestor. var leaf_counts: [max_bits_limit][max_bits_limit]u32 = mem.zeroes([max_bits_limit][max_bits_limit]u32); { var level = @as(u32, 1); while (level <= max_bits) : (level += 1) { // For every level, the first two items are the first two characters. // We initialize the levels as if we had already figured this out. levels[level] = LevelInfo{ .level = level, .last_freq = list[1].freq, .next_char_freq = list[2].freq, .next_pair_freq = list[0].freq + list[1].freq, .needed = 0, }; leaf_counts[level][level] = 2; if (level == 1) { levels[level].next_pair_freq = math.maxInt(i32); } } } // We need a total of 2*n - 2 items at top level and have already generated 2. levels[max_bits].needed = 2 * @intCast(u32, n) - 4; { var level = max_bits; while (true) { var l = &levels[level]; if (l.next_pair_freq == math.maxInt(i32) and l.next_char_freq == math.maxInt(i32)) { // We've run out of both leafs and pairs. // End all calculations for this level. // To make sure we never come back to this level or any lower level, // set next_pair_freq impossibly large. l.needed = 0; levels[level + 1].next_pair_freq = math.maxInt(i32); level += 1; continue; } var prev_freq = l.last_freq; if (l.next_char_freq < l.next_pair_freq) { // The next item on this row is a leaf node. var next = leaf_counts[level][level] + 1; l.last_freq = l.next_char_freq; // Lower leaf_counts are the same of the previous node. leaf_counts[level][level] = next; if (next >= list.len) { l.next_char_freq = maxNode().freq; } else { l.next_char_freq = list[next].freq; } } else { // The next item on this row is a pair from the previous row. // next_pair_freq isn't valid until we generate two // more values in the level below l.last_freq = l.next_pair_freq; // Take leaf counts from the lower level, except counts[level] remains the same. mem.copy(u32, leaf_counts[level][0..level], leaf_counts[level - 1][0..level]); levels[l.level - 1].needed = 2; } l.needed -= 1; if (l.needed == 0) { // We've done everything we need to do for this level. // Continue calculating one level up. Fill in next_pair_freq // of that level with the sum of the two nodes we've just calculated on // this level. if (l.level == max_bits) { // All done! break; } levels[l.level + 1].next_pair_freq = prev_freq + l.last_freq; level += 1; } else { // If we stole from below, move down temporarily to replenish it. while (levels[level - 1].needed > 0) { level -= 1; if (level == 0) { break; } } } } } // Somethings is wrong if at the end, the top level is null or hasn't used // all of the leaves. assert(leaf_counts[max_bits][max_bits] == n); var bit_count = self.bit_count[0 .. max_bits + 1]; var bits: u32 = 1; var counts = &leaf_counts[max_bits]; { var level = max_bits; while (level > 0) : (level -= 1) { // counts[level] gives the number of literals requiring at least "bits" // bits to encode. bit_count[bits] = counts[level] - counts[level - 1]; bits += 1; if (level == 0) { break; } } } return bit_count; } // Look at the leaves and assign them a bit count and an encoding as specified // in RFC 1951 3.2.2 fn assignEncodingAndSize(self: *HuffmanEncoder, bit_count: []u32, list_arg: []LiteralNode) void { var code = @as(u16, 0); var list = list_arg; for (bit_count) |bits, n| { code <<= 1; if (n == 0 or bits == 0) { continue; } // The literals list[list.len-bits] .. list[list.len-bits] // are encoded using "bits" bits, and get the values // code, code + 1, .... The code values are // assigned in literal order (not frequency order). var chunk = list[list.len - @intCast(u32, bits) ..]; self.lns = chunk; sort.sort(LiteralNode, self.lns, {}, byLiteral); for (chunk) |node| { self.codes[node.literal] = HuffCode{ .code = bu.bitReverse(u16, code, @intCast(u5, n)), .len = @intCast(u16, n), }; code += 1; } list = list[0 .. list.len - @intCast(u32, bits)]; } } }; fn maxNode() LiteralNode { return LiteralNode{ .literal = math.maxInt(u16), .freq = math.maxInt(u16), }; } pub fn newHuffmanEncoder(allocator: Allocator, size: u32) !HuffmanEncoder { return HuffmanEncoder{ .codes = try allocator.alloc(HuffCode, size), // Allocate a reusable buffer with the longest possible frequency table. // (deflate_const.max_num_frequencies). .freq_cache = try allocator.alloc(LiteralNode, deflate_const.max_num_frequencies + 1), .allocator = allocator, }; } // Generates a HuffmanCode corresponding to the fixed literal table pub fn generateFixedLiteralEncoding(allocator: Allocator) !HuffmanEncoder { var h = try newHuffmanEncoder(allocator, deflate_const.max_num_frequencies); var codes = h.codes; var ch: u16 = 0; while (ch < deflate_const.max_num_frequencies) : (ch += 1) { var bits: u16 = undefined; var size: u16 = undefined; switch (ch) { 0...143 => { // size 8, 000110000 .. 10111111 bits = ch + 48; size = 8; }, 144...255 => { // size 9, 110010000 .. 111111111 bits = ch + 400 - 144; size = 9; }, 256...279 => { // size 7, 0000000 .. 0010111 bits = ch - 256; size = 7; }, else => { // size 8, 11000000 .. 11000111 bits = ch + 192 - 280; size = 8; }, } codes[ch] = HuffCode{ .code = bu.bitReverse(u16, bits, @intCast(u5, size)), .len = size }; } return h; } pub fn generateFixedOffsetEncoding(allocator: Allocator) !HuffmanEncoder { var h = try newHuffmanEncoder(allocator, 30); var codes = h.codes; for (codes) |_, ch| { codes[ch] = HuffCode{ .code = bu.bitReverse(u16, @intCast(u16, ch), 5), .len = 5 }; } return h; } fn byLiteral(context: void, a: LiteralNode, b: LiteralNode) bool { _ = context; return a.literal < b.literal; } fn byFreq(context: void, a: LiteralNode, b: LiteralNode) bool { _ = context; if (a.freq == b.freq) { return a.literal < b.literal; } return a.freq < b.freq; } test "generate a Huffman code from an array of frequencies" { var freqs: [19]u16 = [_]u16{ 8, // 0 1, // 1 1, // 2 2, // 3 5, // 4 10, // 5 9, // 6 1, // 7 0, // 8 0, // 9 0, // 10 0, // 11 0, // 12 0, // 13 0, // 14 0, // 15 1, // 16 3, // 17 5, // 18 }; var enc = try newHuffmanEncoder(testing.allocator, freqs.len); defer enc.deinit(); enc.generate(freqs[0..], 7); try testing.expect(enc.bitLength(freqs[0..]) == 141); try testing.expect(enc.codes[0].len == 3); try testing.expect(enc.codes[1].len == 6); try testing.expect(enc.codes[2].len == 6); try testing.expect(enc.codes[3].len == 5); try testing.expect(enc.codes[4].len == 3); try testing.expect(enc.codes[5].len == 2); try testing.expect(enc.codes[6].len == 2); try testing.expect(enc.codes[7].len == 6); try testing.expect(enc.codes[8].len == 0); try testing.expect(enc.codes[9].len == 0); try testing.expect(enc.codes[10].len == 0); try testing.expect(enc.codes[11].len == 0); try testing.expect(enc.codes[12].len == 0); try testing.expect(enc.codes[13].len == 0); try testing.expect(enc.codes[14].len == 0); try testing.expect(enc.codes[15].len == 0); try testing.expect(enc.codes[16].len == 6); try testing.expect(enc.codes[17].len == 5); try testing.expect(enc.codes[18].len == 3); try testing.expect(enc.codes[5].code == 0x0); try testing.expect(enc.codes[6].code == 0x2); try testing.expect(enc.codes[0].code == 0x1); try testing.expect(enc.codes[4].code == 0x5); try testing.expect(enc.codes[18].code == 0x3); try testing.expect(enc.codes[3].code == 0x7); try testing.expect(enc.codes[17].code == 0x17); try testing.expect(enc.codes[1].code == 0x0f); try testing.expect(enc.codes[2].code == 0x2f); try testing.expect(enc.codes[7].code == 0x1f); try testing.expect(enc.codes[16].code == 0x3f); } test "generate a Huffman code for the fixed litteral table specific to Deflate" { var enc = try generateFixedLiteralEncoding(testing.allocator); defer enc.deinit(); } test "generate a Huffman code for the 30 possible relative offsets (LZ77 distances) of Deflate" { var enc = try generateFixedOffsetEncoding(testing.allocator); defer enc.deinit(); }
lib/std/compress/deflate/huffman_code.zig
const std = @import("std"); const Allocator = std.mem.Allocator; const assert = std.debug.assert; const print = std.debug.print; const data = @embedFile("data/day24.txt"); const EntriesList = std.ArrayList(Record); const Map = std.AutoHashMap(Record, void); const Record = extern struct { x: i32 = 0, y: i32 = 0, fn min(a: Record, b: Record) Record { return .{ .x = if (a.x < b.x) a.x else b.x, .y = if (a.y < b.y) a.y else b.y, }; } fn max(a: Record, b: Record) Record { return .{ .x = if (a.x > b.x) a.x else b.x, .y = if (a.y > b.y) a.y else b.y, }; } fn add(a: Record, b: Record) Record { return .{ .x = a.x + b.x, .y = a.y + b.y, }; } }; pub fn main() !void { var arena = std.heap.ArenaAllocator.init(std.heap.page_allocator); const ally = &arena.allocator; var lines = std.mem.tokenize(data, "\r\n"); var entries = EntriesList.init(ally); try entries.ensureCapacity(400); var map = Map.init(ally); var result: usize = 0; var min = Record{}; var max = Record{}; while (lines.next()) |line| { if (line.len == 0) continue; var pos = Record{}; var rest = line; while (rest.len > 0) { switch (rest[0]) { 's' => { pos.y -= 1; pos.x -= @intCast(i32, @boolToInt(rest[1] == 'w')); rest = rest[2..]; }, 'n' => { pos.y += 1; pos.x += @intCast(i32, @boolToInt(rest[1] == 'e')); rest = rest[2..]; }, 'e' => { pos.x += 1; rest = rest[1..]; }, 'w' => { pos.x -= 1; rest = rest[1..]; }, else => unreachable, } } if (map.remove(pos)) |_| { } else { try map.put(pos, {}); min = min.min(pos); max = max.max(pos); } } var next_map = Map.init(ally); const neighbors = [_]Record{ .{ .x = 0, .y = 1 }, .{ .x = 1, .y = 1 }, .{ .x = -1, .y = 0 }, .{ .x = 1, .y = 0 }, .{ .x = -1, .y = -1 }, .{ .x = 0, .y = -1 }, }; print("initial: {}\n", .{map.count()}); dump_map(map, min, max); var iteration: usize = 0; while (iteration < 100) : (iteration += 1) { var next_min = Record{}; var next_max = Record{}; var y = min.y-1; while (y <= max.y+1) : (y += 1) { var x = min.x-1; while (x <= max.x+1) : (x += 1) { const self = Record{ .x = x, .y = y }; var num_neigh: usize = 0; for (neighbors) |offset| { var pos = offset.add(self); if (map.contains(pos)) { num_neigh += 1; } } if (map.contains(self)) { if (num_neigh == 1 or num_neigh == 2) { try next_map.put(self, {}); next_max = next_max.max(self); next_min = next_min.min(self); } } else { if (num_neigh == 2) { try next_map.put(self, {}); next_max = next_max.max(self); next_min = next_min.min(self); } } } } min = next_min; max = next_max; const tmp = next_map; next_map = map; map = tmp; next_map.clearRetainingCapacity(); const day = iteration + 1; if (day <= 10 or day % 10 == 0) { print("day {: >2}: {}\n", .{day, map.count()}); //dump_map(map, min, max); } } print("Result: {}\n", .{map.count()}); } fn dump_map(map: Map, min: Record, max: Record) void { print("map @ ({}, {})\n", .{min.x-1, max.x-1}); var y = min.y-1; while (y <= max.y+1) : (y += 1) { var offset = (max.y+1) - y; var i: i32 = 0; while (i < offset) : (i += 1) { print(" ", .{}); } var x = min.x-1; while (x <= max.x+1) : (x += 1) { if (map.contains(.{.x = x, .y = y})) { print("# ", .{}); } else { print(". ", .{}); } } print("\n", .{}); } print("\n", .{}); }
src/day24.zig
const std = @import("std"); const SplitResult = struct { lower: ?*Node, equal: ?*Node, greater: ?*Node, }; const NodePair = struct { first: ?*Node, second: ?*Node, }; const Node = struct { x: usize, y: usize, left: ?*Node = null, right: ?*Node = null, var rng = std.rand.DefaultPrng.init(0x1234); fn init(x: usize) Node { return .{ .x = x, .y = rng.random.int(usize) }; } fn merge(lower: ?*Node, greater: ?*Node) ?*Node { if (lower == null) return greater; if (greater == null) return lower; const lower_ = lower.?; const greater_ = greater.?; if (lower_.y < greater_.y) { lower_.right = merge(lower_.right, greater); return lower; } else { greater_.left = merge(lower, greater_.left); return greater; } } fn splitBinary(orig: ?*Node, value: usize) NodePair { if (orig) |orig_| { if (orig_.x < value) { const split_pair = splitBinary(orig_.right, value); orig_.right = split_pair.first; return .{ .first = orig, .second = split_pair.second }; } else { const split_pair = splitBinary(orig_.left, value); orig_.left = split_pair.second; return .{ .first = split_pair.first, .second = orig }; } } else { return .{ .first = null, .second = null }; } } fn merge3(lower: ?*Node, equal: ?*Node, greater: ?*Node) ?*Node { return merge(merge(lower, equal), greater); } fn split(orig: ?*Node, value: usize) SplitResult { const lower_other = splitBinary(orig, value); const equal_greater = splitBinary(lower_other.second, value + 1); return .{ .lower = lower_other.first, .equal = equal_greater.first, .greater = equal_greater.second }; } }; const Tree = struct { root: ?*Node = null, allocator: *std.mem.Allocator, fn init(allocator: *std.mem.Allocator) Tree { return .{ .allocator = allocator }; } fn hasValue(self: *Tree, x: usize) bool { const splited = Node.split(self.root, x); const result = splited.equal != null; self.root = Node.merge3(splited.lower, splited.equal, splited.greater); return result; } fn insert(self: *Tree, x: usize) !void { var splited = Node.split(self.root, x); if (splited.equal == null) { const node = try self.allocator.create(Node); node.* = Node.init(x); splited.equal = node; } self.root = Node.merge3(splited.lower, splited.equal, splited.greater); } fn erase(self: *Tree, x: usize) void { const splited = Node.split(self.root, x); self.root = Node.merge(splited.lower, splited.greater); } }; pub fn main() !void { Node.rng.seed(std.time.milliTimestamp()); var arena = std.heap.ArenaAllocator.init(std.heap.page_allocator); defer arena.deinit(); var tree = Tree.init(&arena.allocator); var cur: usize = 5; var res: usize = 0; var i: usize = 1; while (i < 1000000) : (i += 1) { cur = (cur * 57 + 43) % 10007; switch (i % 3) { 0 => try tree.insert(cur), 1 => tree.erase(cur), 2 => { const hasVal = tree.hasValue(cur); if (hasVal) res += 1; }, else => unreachable, } } std.debug.warn("{}\n", .{res}); }
zig/main.zig
const sf = struct { pub usingnamespace @import("../sfml.zig"); pub usingnamespace sf.system; pub usingnamespace sf.graphics; }; const std = @import("std"); const assert = std.debug.assert; const TextureType = enum { _ptr, _const_ptr }; pub const Texture = union(TextureType) { // Constructor/destructor /// Creates a texture from nothing pub fn create(size: sf.Vector2u) !Texture { const tex = sf.c.sfTexture_create(@intCast(c_uint, size.x), @intCast(c_uint, size.y)); if (tex == null) return sf.Error.nullptrUnknownReason; return Texture{ ._ptr = tex.? }; } /// Loads a texture from a file pub fn createFromFile(path: [:0]const u8) !Texture { const tex = sf.c.sfTexture_createFromFile(path, null); if (tex == null) return sf.Error.resourceLoadingError; return Texture{ ._ptr = tex.? }; } /// Creates an texture from an image pub fn createFromImage(image: sf.Image, area: ?sf.IntRect) !Texture { const tex = if (area) |a| sf.c.sfTexture_createFromImage(image._ptr, &a._toCSFML()) else sf.c.sfTexture_createFromImage(image._ptr, null); if (tex == null) return sf.Error.nullptrUnknownReason; return Texture{ ._ptr = tex.? }; } /// Destroys a texture /// Be careful, you can only destroy non const textures pub fn destroy(self: *Texture) void { // TODO : is it possible to detect that comptime? // Should this panic? if (self.* == ._const_ptr) @panic("Can't destroy a const texture pointer"); sf.c.sfTexture_destroy(self._ptr); } // Getters/Setters /// Gets a const pointer to this texture /// For inner workings pub fn _get(self: Texture) *const sf.c.sfTexture { return switch (self) { ._ptr => self._ptr, ._const_ptr => self._const_ptr, }; } /// Clones this texture (the clone won't be const) pub fn copy(self: Texture) !Texture { const cpy = sf.c.sfTexture_copy(self._get()); if (cpy == null) return sf.Error.nullptrUnknownReason; return Texture{ ._ptr = cpy.? }; } /// Copy this texture to an image in ram pub fn copyToImage(self: Texture) sf.Image { return .{ ._ptr = sf.c.sfTexture_copyToImage(self._get()).? }; } /// Makes this texture constant (I don't know why you would do that) pub fn makeConst(self: *Texture) void { self.* = Texture{ ._const_ptr = self._get() }; } /// Gets the size of this image pub fn getSize(self: Texture) sf.Vector2u { const size = sf.c.sfTexture_getSize(self._get()); return sf.Vector2u{ .x = size.x, .y = size.y }; } /// Gets the pixel count of this image pub fn getPixelCount(self: Texture) usize { const dim = self.getSize(); return dim.x * dim.y; } /// Updates the pixels of the image from an array of pixels (colors) pub fn updateFromPixels(self: *Texture, pixels: []const sf.Color, zone: ?sf.Rect(c_uint)) !void { if (self.* == ._const_ptr) @panic("Can't set pixels on a const texture"); if (self.isSrgb()) @panic("Updating an srgb from a pixel array isn't implemented"); var real_zone: sf.Rect(c_uint) = undefined; var size = self.getSize(); if (zone) |z| { // Check if the given zone is fully inside the image var intersection = z.intersects(sf.Rect(c_uint).init(0, 0, size.x, size.y)); if (intersection) |i| { if (!i.equals(z)) return sf.Error.areaDoesNotFit; } else return sf.Error.areaDoesNotFit; real_zone = z; } else { real_zone.left = 0; real_zone.top = 0; real_zone.width = size.x; real_zone.height = size.y; } // Check if there is enough data if (pixels.len < real_zone.width * real_zone.height) return sf.Error.notEnoughData; sf.c.sfTexture_updateFromPixels(self._ptr, @ptrCast([*]const u8, pixels.ptr), real_zone.width, real_zone.height, real_zone.left, real_zone.top); } /// Updates the pixels of the image from an other texture pub fn updateFromTexture(self: *Texture, other: Texture, copy_pos: ?sf.Vector2u) void { if (self == ._const_ptr) @panic("Can't set pixels on a const texture"); var pos = if (copy_pos) |a| a else sf.Vector2u{ .x = 0, .y = 0 }; var max = other.getSize().add(pos); var size = self.getSize(); assert(max.x <= size.x and max.y <= size.y); sf.c.sfTexture_updateFromTexture(self._ptr, other._get(), pos.x, pos.y); } /// Updates the pixels of the image from an image pub fn updateFromImage(self: *Texture, image: sf.Image, copy_pos: ?sf.Vector2u) void { if (self.* == ._const_ptr) @panic("Can't set pixels on a const texture"); var pos = if (copy_pos) |a| a else sf.Vector2u{ .x = 0, .y = 0 }; var max = image.getSize().add(pos); var size = self.getSize(); assert(max.x <= size.x and max.y <= size.y); sf.c.sfTexture_updateFromImage(self._ptr, image._ptr, pos.x, pos.y); } /// Tells whether or not this texture is to be smoothed pub fn isSmooth(self: Texture) bool { return sf.c.sfTexture_isSmooth(self._ptr) != 0; } /// Enables or disables texture smoothing pub fn setSmooth(self: *Texture, smooth: bool) void { if (self.* == ._const_ptr) @panic("Can't set properties on a const texture"); sf.c.sfTexture_setSmooth(self._ptr, @boolToInt(smooth)); } /// Tells whether or not this texture should repeat when rendering outside its bounds pub fn isRepeated(self: Texture) bool { return sf.c.sfTexture_isRepeated(self._ptr) != 0; } /// Enables or disables texture repeating pub fn setRepeated(self: *Texture, repeated: bool) void { if (self.* == ._const_ptr) @panic("Can't set properties on a const texture"); sf.c.sfTexture_setRepeated(self._ptr, @boolToInt(repeated)); } /// Tells whether or not this texture has colors in the SRGB format /// SRGB functions arent implemented yet pub fn isSrgb(self: Texture) bool { return sf.c.sfTexture_isSrgb(self._ptr) != 0; } /// Enables or disables SRGB pub fn setSrgb(self: *Texture, srgb: bool) void { if (self.* == ._const_ptr) @panic("Can't set properties on a const texture"); sf.c.sfTexture_setSrgb(self._ptr, @boolToInt(srgb)); } /// Swaps this texture's contents with an other texture pub fn swap(self: *Texture, other: *Texture) void { if (self.* == ._const_ptr or other.* == ._const_ptr) @panic("Texture swapping must be done between two non const textures"); sf.c.sfTexture_swap(self._ptr, other._ptr); } // Others /// Generates a mipmap for the current texture data, returns true if the operation succeeded pub fn generateMipmap(self: *Texture) bool { if (self == ._const_ptr) @panic("Can't act on a const texture"); return sf.c.sfTexture_generateMipmap(self._ptr) != 0; } /// Pointer to the csfml texture _ptr: *sf.c.sfTexture, /// Const pointer to the csfml texture _const_ptr: *const sf.c.sfTexture }; test "texture: sane getters and setters" { const tst = std.testing; const allocator = std.heap.page_allocator; var tex = try Texture.create(.{ .x = 12, .y = 10 }); defer tex.destroy(); var size = tex.getSize(); tex.setSrgb(false); tex.setSmooth(true); tex.setRepeated(true); try tst.expectEqual(@as(u32, 12), size.x); try tst.expectEqual(@as(u32, 10), size.y); try tst.expectEqual(@as(usize, 120), tex.getPixelCount()); var pixel_data = try allocator.alloc(sf.Color, 120); defer allocator.free(pixel_data); for (pixel_data) |*c, i| { c.* = sf.graphics.Color.fromHSVA(@intToFloat(f32, i) / 144 * 360, 100, 100, 1); } pixel_data[0] = sf.Color.Green; try tex.updateFromPixels(pixel_data, null); try tst.expect(!tex.isSrgb()); try tst.expect(tex.isSmooth()); try tst.expect(tex.isRepeated()); var img = tex.copyToImage(); defer img.destroy(); try tst.expectEqual(sf.Color.Green, img.getPixel(.{ .x = 0, .y = 0 })); tex.updateFromImage(img, null); var t = tex; t.makeConst(); var copy = try t.copy(); try tst.expectEqual(@as(usize, 120), copy.getPixelCount()); var tex2 = try Texture.create(.{ .x = 100, .y = 100 }); defer tex2.destroy(); copy.swap(&tex2); try tst.expectEqual(@as(usize, 100 * 100), copy.getPixelCount()); try tst.expectEqual(@as(usize, 120), tex2.getPixelCount()); }
src/sfml/graphics/texture.zig
const std = @import("std"); const w4 = @import("wasm4.zig"); pub const Point = struct { x: i32, y: i32, pub fn init(x: i32, y: i32) @This() { return @This(){ .x = x, .y = y, }; } pub fn equals(this: @This(), other: @This()) bool { return (this.x == other.x) and (this.y == other.y); } }; pub const Snake = struct { body: std.BoundedArray(Point, 400), direction: Point, pub fn init() @This() { return @This(){ .body = std.BoundedArray(Point, 400).fromSlice(&.{ Point.init(2, 0), Point.init(1, 0), Point.init(0, 0), }) catch @panic("couldn't init snake body"), .direction = Point.init(1, 0), }; } pub fn draw(this: @This()) void { w4.DRAW_COLORS.* = 0x0043; for (this.body.constSlice()) |part| { w4.rect(.{ part.x * 8, part.y * 8 }, .{ 8, 8 }); } w4.DRAW_COLORS.* = 0x0004; w4.rect(.{ this.body.get(0).x * 8, this.body.get(0).y * 8 }, .{ 8, 8 }); } pub fn update(this: *@This()) void { const part = this.body.slice(); var i: u32 = part.len - 1; while (i > 0) : (i -= 1) { part[i].x = part[i - 1].x; part[i].y = part[i - 1].y; } part[0].x = @mod((part[0].x + this.direction.x), 20); part[0].y = @mod((part[0].y + this.direction.y), 20); if (part[0].x < 0) part[0].x = 19; if (part[0].y < 0) part[0].y = 19; } pub fn up(this: *@This()) void { if (this.direction.y == 0) { this.direction.x = 0; this.direction.y = -1; } } pub fn down(this: *@This()) void { if (this.direction.y == 0) { this.direction.x = 0; this.direction.y = 1; } } pub fn left(this: *@This()) void { if (this.direction.x == 0) { this.direction.x = -1; this.direction.y = 0; } } pub fn right(this: *@This()) void { if (this.direction.x == 0) { this.direction.x = 1; this.direction.y = 0; } } };
src/snake.zig
const builtin = @import("builtin"); const std = @import("std"); const expect = std.testing.expect; const expectEqualStrings = std.testing.expectEqualStrings; const expectStringStartsWith = std.testing.expectStringStartsWith; // Most tests here can be comptime but use runtime so that a stacktrace // can show failure location. // // Note certain results of `@typeName()` expect `behavior.zig` to be the // root file. Running a test against this file as root will result in // failures. test "anon fn param" { if (builtin.zig_backend == .stage1) { // stage1 uses line/column for the names but we're moving away from that for // incremental compilation purposes. return error.SkipZigTest; } if (builtin.zig_backend == .stage2_c) return error.SkipZigTest; // TODO if (builtin.zig_backend == .stage2_x86_64) return error.SkipZigTest; // TODO if (builtin.zig_backend == .stage2_aarch64) return error.SkipZigTest; // TODO if (builtin.zig_backend == .stage2_arm) return error.SkipZigTest; // TODO // https://github.com/ziglang/zig/issues/9339 try expectEqualStringsIgnoreDigits( "behavior.typename.TypeFromFn(behavior.typename.test.anon fn param__struct_0)", @typeName(TypeFromFn(struct {})), ); try expectEqualStringsIgnoreDigits( "behavior.typename.TypeFromFn(behavior.typename.test.anon fn param__union_0)", @typeName(TypeFromFn(union { unused: u8 })), ); try expectEqualStringsIgnoreDigits( "behavior.typename.TypeFromFn(behavior.typename.test.anon fn param__enum_0)", @typeName(TypeFromFn(enum { unused })), ); try expectEqualStringsIgnoreDigits( "behavior.typename.TypeFromFnB(behavior.typename.test.anon fn param__struct_0,behavior.typename.test.anon fn param__union_0,behavior.typename.test.anon fn param__enum_0)", @typeName(TypeFromFnB(struct {}, union { unused: u8 }, enum { unused })), ); } test "anon field init" { if (builtin.zig_backend == .stage1) { // stage1 uses line/column for the names but we're moving away from that for // incremental compilation purposes. return error.SkipZigTest; } if (builtin.zig_backend == .stage2_c) return error.SkipZigTest; // TODO if (builtin.zig_backend == .stage2_x86_64) return error.SkipZigTest; // TODO if (builtin.zig_backend == .stage2_aarch64) return error.SkipZigTest; // TODO if (builtin.zig_backend == .stage2_arm) return error.SkipZigTest; // TODO const Foo = .{ .T1 = struct {}, .T2 = union { unused: u8 }, .T3 = enum { unused }, }; try expectEqualStringsIgnoreDigits( "behavior.typename.test.anon field init__struct_0", @typeName(Foo.T1), ); try expectEqualStringsIgnoreDigits( "behavior.typename.test.anon field init__union_0", @typeName(Foo.T2), ); try expectEqualStringsIgnoreDigits( "behavior.typename.test.anon field init__enum_0", @typeName(Foo.T3), ); } test "basic" { if (builtin.zig_backend == .stage2_c) return error.SkipZigTest; // TODO if (builtin.zig_backend == .stage2_x86_64) return error.SkipZigTest; // TODO if (builtin.zig_backend == .stage2_aarch64) return error.SkipZigTest; // TODO if (builtin.zig_backend == .stage2_arm) return error.SkipZigTest; // TODO try expectEqualStrings(@typeName(i64), "i64"); try expectEqualStrings(@typeName(*usize), "*usize"); try expectEqualStrings(@typeName([]u8), "[]u8"); } test "top level decl" { if (builtin.zig_backend == .stage1) { // stage1 fails to return fully qualified namespaces. return error.SkipZigTest; } if (builtin.zig_backend == .stage2_c) return error.SkipZigTest; // TODO if (builtin.zig_backend == .stage2_x86_64) return error.SkipZigTest; // TODO if (builtin.zig_backend == .stage2_aarch64) return error.SkipZigTest; // TODO if (builtin.zig_backend == .stage2_arm) return error.SkipZigTest; // TODO try expectEqualStrings( "behavior.typename.A_Struct", @typeName(A_Struct), ); try expectEqualStrings( "behavior.typename.A_Union", @typeName(A_Union), ); try expectEqualStrings( "behavior.typename.A_Enum", @typeName(A_Enum), ); // regular fn, without error try expectEqualStrings( "fn() void", @typeName(@TypeOf(regular)), ); // regular fn inside struct, with error try expectEqualStrings( "fn() @typeInfo(@typeInfo(@TypeOf(behavior.typename.B.doTest)).Fn.return_type.?).ErrorUnion.error_set!void", @typeName(@TypeOf(B.doTest)), ); // generic fn try expectEqualStrings( "fn(type) type", @typeName(@TypeOf(TypeFromFn)), ); } const A_Struct = struct {}; const A_Union = union { unused: u8, }; const A_Enum = enum { unused, }; fn regular() void {} test "fn body decl" { if (builtin.zig_backend == .stage1) { // stage1 fails to return fully qualified namespaces. return error.SkipZigTest; } if (builtin.zig_backend == .stage2_c) return error.SkipZigTest; // TODO if (builtin.zig_backend == .stage2_x86_64) return error.SkipZigTest; // TODO if (builtin.zig_backend == .stage2_aarch64) return error.SkipZigTest; // TODO if (builtin.zig_backend == .stage2_arm) return error.SkipZigTest; // TODO try B.doTest(); } const B = struct { fn doTest() !void { const B_Struct = struct {}; const B_Union = union { unused: u8, }; const B_Enum = enum { unused, }; try expectEqualStringsIgnoreDigits( "behavior.typename.B.doTest__struct_0", @typeName(B_Struct), ); try expectEqualStringsIgnoreDigits( "behavior.typename.B.doTest__union_0", @typeName(B_Union), ); try expectEqualStringsIgnoreDigits( "behavior.typename.B.doTest__enum_0", @typeName(B_Enum), ); } }; test "fn param" { if (builtin.zig_backend == .stage2_c) return error.SkipZigTest; // TODO if (builtin.zig_backend == .stage2_x86_64) return error.SkipZigTest; // TODO if (builtin.zig_backend == .stage2_aarch64) return error.SkipZigTest; // TODO if (builtin.zig_backend == .stage2_arm) return error.SkipZigTest; // TODO // https://github.com/ziglang/zig/issues/675 try expectEqualStrings( "behavior.typename.TypeFromFn(u8)", @typeName(TypeFromFn(u8)), ); try expectEqualStrings( "behavior.typename.TypeFromFn(behavior.typename.A_Struct)", @typeName(TypeFromFn(A_Struct)), ); try expectEqualStrings( "behavior.typename.TypeFromFn(behavior.typename.A_Union)", @typeName(TypeFromFn(A_Union)), ); try expectEqualStrings( "behavior.typename.TypeFromFn(behavior.typename.A_Enum)", @typeName(TypeFromFn(A_Enum)), ); try expectEqualStrings( "behavior.typename.TypeFromFn2(u8,bool)", @typeName(TypeFromFn2(u8, bool)), ); } fn TypeFromFn(comptime T: type) type { _ = T; return struct {}; } fn TypeFromFn2(comptime T1: type, comptime T2: type) type { _ = T1; _ = T2; return struct {}; } fn TypeFromFnB(comptime T1: type, comptime T2: type, comptime T3: type) type { _ = T1; _ = T2; _ = T3; return struct {}; } /// Replaces integers in `actual` with '0' before doing the test. pub fn expectEqualStringsIgnoreDigits(expected: []const u8, actual: []const u8) !void { var actual_buf: [1024]u8 = undefined; var actual_i: usize = 0; var last_digit = false; for (actual) |byte| { switch (byte) { '0'...'9' => { if (last_digit) continue; last_digit = true; actual_buf[actual_i] = '0'; actual_i += 1; }, else => { last_digit = false; actual_buf[actual_i] = byte; actual_i += 1; }, } } return expectEqualStrings(expected, actual_buf[0..actual_i]); }
test/behavior/typename.zig
const std = @import("std"); const expect = std.testing.expect; const expectEqualSlices = std.testing.expectEqualSlices; const expectEqual = std.testing.expectEqual; const mem = std.mem; const x = @intToPtr([*]i32, 0x1000)[0..0x500]; const y = x[0x100..]; test "compile time slice of pointer to hard coded address" { expect(@ptrToInt(x) == 0x1000); expect(x.len == 0x500); expect(@ptrToInt(y) == 0x1100); expect(y.len == 0x400); } test "runtime safety lets us slice from len..len" { var an_array = [_]u8{ 1, 2, 3, }; expect(mem.eql(u8, sliceFromLenToLen(an_array[0..], 3, 3), "")); } fn sliceFromLenToLen(a_slice: []u8, start: usize, end: usize) []u8 { return a_slice[start..end]; } test "implicitly cast array of size 0 to slice" { var msg = [_]u8{}; assertLenIsZero(&msg); } fn assertLenIsZero(msg: []const u8) void { expect(msg.len == 0); } test "C pointer" { var buf: [*c]const u8 = "kjdhfkjdhfdkjhfkfjhdfkjdhfkdjhfdkjhf"; var len: u32 = 10; var slice = buf[0..len]; expectEqualSlices(u8, "kjdhfkjdhf", slice); } test "C pointer slice access" { var buf: [10]u32 = [1]u32{42} ** 10; const c_ptr = @ptrCast([*c]const u32, &buf); var runtime_zero: usize = 0; comptime expectEqual([]const u32, @TypeOf(c_ptr[runtime_zero..1])); comptime expectEqual(*const [1]u32, @TypeOf(c_ptr[0..1])); for (c_ptr[0..5]) |*cl| { expectEqual(@as(u32, 42), cl.*); } } fn sliceSum(comptime q: []const u8) i32 { comptime var result = 0; inline for (q) |item| { result += item; } return result; } test "comptime slices are disambiguated" { expect(sliceSum(&[_]u8{ 1, 2 }) == 3); expect(sliceSum(&[_]u8{ 3, 4 }) == 7); } test "slice type with custom alignment" { const LazilyResolvedType = struct { anything: i32, }; var slice: []align(32) LazilyResolvedType = undefined; var array: [10]LazilyResolvedType align(32) = undefined; slice = &array; slice[1].anything = 42; expect(array[1].anything == 42); } test "access len index of sentinel-terminated slice" { const S = struct { fn doTheTest() void { var slice: [:0]const u8 = "hello"; expect(slice.len == 5); expect(slice[5] == 0); } }; S.doTheTest(); comptime S.doTheTest(); } test "obtaining a null terminated slice" { // here we have a normal array var buf: [50]u8 = undefined; buf[0] = 'a'; buf[1] = 'b'; buf[2] = 'c'; buf[3] = 0; // now we obtain a null terminated slice: const ptr = buf[0..3 :0]; var runtime_len: usize = 3; const ptr2 = buf[0..runtime_len :0]; // ptr2 is a null-terminated slice comptime expect(@TypeOf(ptr2) == [:0]u8); comptime expect(@TypeOf(ptr2[0..2]) == *[2]u8); var runtime_zero: usize = 0; comptime expect(@TypeOf(ptr2[runtime_zero..2]) == []u8); } test "empty array to slice" { const S = struct { fn doTheTest() void { const empty: []align(16) u8 = &[_]u8{}; const align_1: []align(1) u8 = empty; const align_4: []align(4) u8 = empty; const align_16: []align(16) u8 = empty; expectEqual(1, @typeInfo(@TypeOf(align_1)).Pointer.alignment); expectEqual(4, @typeInfo(@TypeOf(align_4)).Pointer.alignment); expectEqual(16, @typeInfo(@TypeOf(align_16)).Pointer.alignment); } }; S.doTheTest(); comptime S.doTheTest(); } test "@ptrCast slice to pointer" { const S = struct { fn doTheTest() void { var array align(@alignOf(u16)) = [5]u8{ 0xff, 0xff, 0xff, 0xff, 0xff }; var slice: []u8 = &array; var ptr = @ptrCast(*u16, slice); expect(ptr.* == 65535); } }; S.doTheTest(); comptime S.doTheTest(); } test "slice syntax resulting in pointer-to-array" { const S = struct { fn doTheTest() void { testArray(); testArrayZ(); testArray0(); testArrayAlign(); testPointer(); testPointerZ(); testPointer0(); testPointerAlign(); testSlice(); testSliceZ(); testSlice0(); testSliceOpt(); testSliceAlign(); } fn testArray() void { var array = [5]u8{ 1, 2, 3, 4, 5 }; var slice = array[1..3]; comptime expect(@TypeOf(slice) == *[2]u8); expect(slice[0] == 2); expect(slice[1] == 3); } fn testArrayZ() void { var array = [5:0]u8{ 1, 2, 3, 4, 5 }; comptime expect(@TypeOf(array[1..3]) == *[2]u8); comptime expect(@TypeOf(array[1..5]) == *[4:0]u8); comptime expect(@TypeOf(array[1..]) == *[4:0]u8); comptime expect(@TypeOf(array[1..3 :4]) == *[2:4]u8); } fn testArray0() void { { var array = [0]u8{}; var slice = array[0..0]; comptime expect(@TypeOf(slice) == *[0]u8); } { var array = [0:0]u8{}; var slice = array[0..0]; comptime expect(@TypeOf(slice) == *[0:0]u8); expect(slice[0] == 0); } } fn testArrayAlign() void { var array align(4) = [5]u8{ 1, 2, 3, 4, 5 }; var slice = array[4..5]; comptime expect(@TypeOf(slice) == *align(4) [1]u8); expect(slice[0] == 5); comptime expect(@TypeOf(array[0..2]) == *align(4) [2]u8); } fn testPointer() void { var array = [5]u8{ 1, 2, 3, 4, 5 }; var pointer: [*]u8 = &array; var slice = pointer[1..3]; comptime expect(@TypeOf(slice) == *[2]u8); expect(slice[0] == 2); expect(slice[1] == 3); } fn testPointerZ() void { var array = [5:0]u8{ 1, 2, 3, 4, 5 }; var pointer: [*:0]u8 = &array; comptime expect(@TypeOf(pointer[1..3]) == *[2]u8); comptime expect(@TypeOf(pointer[1..3 :4]) == *[2:4]u8); } fn testPointer0() void { var pointer: [*]const u0 = &[1]u0{0}; var slice = pointer[0..1]; comptime expect(@TypeOf(slice) == *const [1]u0); expect(slice[0] == 0); } fn testPointerAlign() void { var array align(4) = [5]u8{ 1, 2, 3, 4, 5 }; var pointer: [*]align(4) u8 = &array; var slice = pointer[4..5]; comptime expect(@TypeOf(slice) == *align(4) [1]u8); expect(slice[0] == 5); comptime expect(@TypeOf(pointer[0..2]) == *align(4) [2]u8); } fn testSlice() void { var array = [5]u8{ 1, 2, 3, 4, 5 }; var src_slice: []u8 = &array; var slice = src_slice[1..3]; comptime expect(@TypeOf(slice) == *[2]u8); expect(slice[0] == 2); expect(slice[1] == 3); } fn testSliceZ() void { var array = [5:0]u8{ 1, 2, 3, 4, 5 }; var slice: [:0]u8 = &array; comptime expect(@TypeOf(slice[1..3]) == *[2]u8); comptime expect(@TypeOf(slice[1..]) == [:0]u8); comptime expect(@TypeOf(slice[1..3 :4]) == *[2:4]u8); } fn testSliceOpt() void { var array: [2]u8 = [2]u8{ 1, 2 }; var slice: ?[]u8 = &array; comptime expect(@TypeOf(&array, slice) == ?[]u8); comptime expect(@TypeOf(slice.?[0..2]) == *[2]u8); } fn testSlice0() void { { var array = [0]u8{}; var src_slice: []u8 = &array; var slice = src_slice[0..0]; comptime expect(@TypeOf(slice) == *[0]u8); } { var array = [0:0]u8{}; var src_slice: [:0]u8 = &array; var slice = src_slice[0..0]; comptime expect(@TypeOf(slice) == *[0]u8); } } fn testSliceAlign() void { var array align(4) = [5]u8{ 1, 2, 3, 4, 5 }; var src_slice: []align(4) u8 = &array; var slice = src_slice[4..5]; comptime expect(@TypeOf(slice) == *align(4) [1]u8); expect(slice[0] == 5); comptime expect(@TypeOf(src_slice[0..2]) == *align(4) [2]u8); } fn testConcatStrLiterals() void { expectEqualSlices("a"[0..] ++ "b"[0..], "ab"); expectEqualSlices("a"[0..:0] ++ "b"[0..:0], "ab"); } }; S.doTheTest(); comptime S.doTheTest(); } test "slice of hardcoded address to pointer" { const S = struct { fn doTheTest() void { const pointer = @intToPtr([*]u8, 0x04)[0..2]; comptime expect(@TypeOf(pointer) == *[2]u8); const slice: []const u8 = pointer; expect(@ptrToInt(slice.ptr) == 4); expect(slice.len == 2); } }; S.doTheTest(); } test "type coercion of pointer to anon struct literal to pointer to slice" { const S = struct { const U = union{ a: u32, b: bool, c: []const u8, }; fn doTheTest() void { var x1: u8 = 42; const t1 = &.{ x1, 56, 54 }; var slice1: []const u8 = t1; expect(slice1.len == 3); expect(slice1[0] == 42); expect(slice1[1] == 56); expect(slice1[2] == 54); var x2: []const u8 = "hello"; const t2 = &.{ x2, ", ", "world!" }; // @compileLog(@TypeOf(t2)); var slice2: []const []const u8 = t2; expect(slice2.len == 3); expect(mem.eql(u8, slice2[0], "hello")); expect(mem.eql(u8, slice2[1], ", ")); expect(mem.eql(u8, slice2[2], "world!")); } }; // S.doTheTest(); comptime S.doTheTest(); }
test/stage1/behavior/slice.zig
const std = @import("std"); const assert = std.debug.assert; const panic = std.debug.panic; const zp = @import("../../zplay.zig"); const gl = zp.deps.gl; const Self = @This(); pub const Error = error{ TextureUnitUsed, }; pub const TextureType = enum(c_uint) { texture_1d = gl.GL_TEXTURE_1D, texture_2d = gl.GL_TEXTURE_2D, texture_3d = gl.GL_TEXTURE_3D, texture_1d_array = gl.GL_TEXTURE_1D_ARRAY, texture_2d_array = gl.GL_TEXTURE_2D_ARRAY, texture_rectangle = gl.GL_TEXTURE_RECTANGLE, texture_cube_map = gl.GL_TEXTURE_CUBE_MAP, texture_buffer = gl.GL_TEXTURE_BUFFER, texture_2d_multisample = gl.GL_TEXTURE_2D_MULTISAMPLE, texture_2d_multisample_array = gl.GL_TEXTURE_2D_MULTISAMPLE_ARRAY, }; pub const UpdateTarget = enum(c_uint) { /// 1d texture_1d = gl.GL_TEXTURE_1D, proxy_texture_1d = gl.GL_PROXY_TEXTURE_1D, /// 2d texture_2d = gl.GL_TEXTURE_2D, proxy_texture_2d = gl.GL_PROXY_TEXTURE_2D, texture_1d_array = gl.GL_TEXTURE_1D_ARRAY, proxy_texture_1d_array = gl.GL_PROXY_TEXTURE_1D_ARRAY, texture_rectangle = gl.GL_TEXTURE_RECTANGLE, proxy_texture_rectangle = gl.GL_PROXY_TEXTURE_RECTANGLE, texture_cube_map_positive_x = gl.GL_TEXTURE_CUBE_MAP_POSITIVE_X, texture_cube_map_negative_x = gl.GL_TEXTURE_CUBE_MAP_NEGATIVE_X, texture_cube_map_positive_y = gl.GL_TEXTURE_CUBE_MAP_POSITIVE_Y, texture_cube_map_negative_y = gl.GL_TEXTURE_CUBE_MAP_NEGATIVE_Y, texture_cube_map_positive_z = gl.GL_TEXTURE_CUBE_MAP_POSITIVE_Z, texture_cube_map_negative_z = gl.GL_TEXTURE_CUBE_MAP_NEGATIVE_Z, proxy_texture_cube_map = gl.GL_PROXY_TEXTURE_CUBE_MAP, /// 3d texture_3d = gl.GL_TEXTURE_3D, proxy_texture_3d = gl.GL_PROXY_TEXTURE_3D, texture_2d_array = gl.GL_TEXTURE_2D_ARRAY, proxy_texture_2d_array = gl.GL_PROXY_TEXTURE_2D_ARRAY, }; pub const TextureMultisampleTarget = enum(c_uint) { /// 2d multisample texture_2d_multisample = gl.GL_TEXTURE_2D_MULTISAMPLE, proxy_texture_2d_multisample = gl.GL_PROXY_TEXTURE_2D_MULTISAMPLE, /// 3d multisample texture_2d_multisample_array = gl.GL_TEXTURE_2D_MULTISAMPLE_ARRAY, proxy_texture_2d_multisample_array = gl.GL_PROXY_TEXTURE_2D_MULTISAMPLE_ARRAY, }; pub const TextureFormat = enum(c_int) { red = gl.GL_RED, rg = gl.GL_RG, rgb = gl.GL_RGB, rgba = gl.GL_RGBA, depth_component = gl.GL_DEPTH_COMPONENT, depth_stencil = gl.GL_DEPTH_STENCIL, compressed_red = gl.GL_COMPRESSED_RED, compressed_rg = gl.GL_COMPRESSED_RG, compressed_rgb = gl.GL_COMPRESSED_RGB, compressed_rgba = gl.GL_COMPRESSED_RGBA, compressed_srgb = gl.GL_COMPRESSED_SRGB, compressed_srgb_alpha = gl.GL_COMPRESSED_SRGB_ALPHA, }; pub const ImageFormat = enum(c_uint) { red = gl.GL_RED, rg = gl.GL_RG, rgb = gl.GL_RGB, bgr = gl.GL_BGR, rgba = gl.GL_RGBA, bgra = gl.GL_BGRA, depth_component = gl.GL_DEPTH_COMPONENT, depth_stencil = gl.GL_DEPTH_STENCIL, pub fn getChannels(self: @This()) u32 { return switch (self) { .red => 1, .rg => 2, .rgb => 3, .bgr => 3, .rgba => 4, .bgra => 4, else => { panic("not image format!", .{}); }, }; } }; pub const TextureUnit = enum(c_uint) { texture_unit_0 = gl.GL_TEXTURE0, texture_unit_1 = gl.GL_TEXTURE1, texture_unit_2 = gl.GL_TEXTURE2, texture_unit_3 = gl.GL_TEXTURE3, texture_unit_4 = gl.GL_TEXTURE4, texture_unit_5 = gl.GL_TEXTURE5, texture_unit_6 = gl.GL_TEXTURE6, texture_unit_7 = gl.GL_TEXTURE7, texture_unit_8 = gl.GL_TEXTURE8, texture_unit_9 = gl.GL_TEXTURE9, texture_unit_10 = gl.GL_TEXTURE10, texture_unit_11 = gl.GL_TEXTURE11, texture_unit_12 = gl.GL_TEXTURE12, texture_unit_13 = gl.GL_TEXTURE13, texture_unit_14 = gl.GL_TEXTURE14, texture_unit_15 = gl.GL_TEXTURE15, texture_unit_16 = gl.GL_TEXTURE16, texture_unit_17 = gl.GL_TEXTURE17, texture_unit_18 = gl.GL_TEXTURE18, texture_unit_19 = gl.GL_TEXTURE19, texture_unit_20 = gl.GL_TEXTURE20, texture_unit_21 = gl.GL_TEXTURE21, texture_unit_22 = gl.GL_TEXTURE22, texture_unit_23 = gl.GL_TEXTURE23, texture_unit_24 = gl.GL_TEXTURE24, texture_unit_25 = gl.GL_TEXTURE25, texture_unit_26 = gl.GL_TEXTURE26, texture_unit_27 = gl.GL_TEXTURE27, texture_unit_28 = gl.GL_TEXTURE28, texture_unit_29 = gl.GL_TEXTURE29, texture_unit_30 = gl.GL_TEXTURE30, texture_unit_31 = gl.GL_TEXTURE31, const Unit = @This(); pub fn fromInt(int: i32) Unit { return @intToEnum(Unit, int + gl.GL_TEXTURE0); } pub fn toInt(self: Unit) i32 { return @intCast(i32, @enumToInt(self) - gl.GL_TEXTURE0); } // mark where texture unit is allocated to var alloc_map = std.EnumArray(Unit, ?*Self).initFill(null); fn alloc(unit: Unit, tex: *Self) void { if (alloc_map.get(unit)) |t| { if (tex == t) return; t.tu = null; // detach unit from old texture } tex.tu = unit; alloc_map.set(unit, tex); } fn free(unit: Unit) void { if (alloc_map.get(unit)) |t| { t.tu = null; // detach unit from old texture alloc_map.set(unit, null); } } }; pub const WrappingCoord = enum(c_uint) { s = gl.GL_TEXTURE_WRAP_S, t = gl.GL_TEXTURE_WRAP_T, r = gl.GL_TEXTURE_WRAP_R, }; pub const WrappingMode = enum(c_int) { repeat = gl.GL_REPEAT, mirrored_repeat = gl.GL_MIRRORED_REPEAT, clamp_to_edge = gl.GL_CLAMP_TO_EDGE, clamp_to_border = gl.GL_CLAMP_TO_BORDER, }; pub const FilteringSituation = enum(c_uint) { minifying = gl.GL_TEXTURE_MIN_FILTER, magnifying = gl.GL_TEXTURE_MAG_FILTER, }; pub const FilteringMode = enum(c_int) { nearest = gl.GL_NEAREST, linear = gl.GL_LINEAR, nearest_mipmap_nearest = gl.GL_NEAREST_MIPMAP_NEAREST, nearest_mipmap_linear = gl.GL_NEAREST_MIPMAP_LINEAR, linear_mipmap_nearest = gl.GL_LINEAR_MIPMAP_NEAREST, linear_mipmap_linear = gl.GL_LINEAR_MIPMAP_LINEAR, }; /// allocator allocator: std.mem.Allocator, /// texture id id: gl.GLuint = undefined, /// texture type tt: TextureType, /// texture unit tu: ?TextureUnit = null, /// internal format format: TextureFormat = undefined, /// size of texture width: u32 = undefined, height: ?u32 = null, depth: ?u32 = null, pub fn init(allocator: std.mem.Allocator, tt: TextureType) !*Self { const self = try allocator.create(Self); self.tt = tt; gl.genTextures(1, &self.id); gl.util.checkError(); return self; } pub fn deinit(self: *Self) void { if (self.tu) |u| { TextureUnit.free(u); } gl.deleteTextures(1, &self.id); gl.util.checkError(); } /// activate and bind to given texture unit /// NOTE: because a texture unit can be stolen anytime /// by other textures, we just blindly bind them everytime. /// Maybe we need to look out for performance issue. pub fn bindToTextureUnit(self: *Self, unit: TextureUnit) void { TextureUnit.alloc(unit, self); gl.activeTexture(@enumToInt(self.tu.?)); defer gl.activeTexture(gl.GL_TEXTURE0); gl.bindTexture(@enumToInt(self.tt), self.id); gl.util.checkError(); } /// get binded texture unit pub fn getTextureUnit(self: Self) i32 { return @intCast(i32, @enumToInt(self.tu.?) - gl.GL_TEXTURE0); } /// set texture wrapping mode pub fn setWrappingMode(self: Self, coord: WrappingCoord, mode: WrappingMode) void { assert(self.tt == .texture_2d or self.tt == .texture_cube_map); gl.bindTexture(@enumToInt(self.tt), self.id); defer gl.bindTexture(@enumToInt(self.tt), 0); gl.texParameteri(@enumToInt(self.tt), @enumToInt(coord), @enumToInt(mode)); gl.util.checkError(); } /// set border color, useful when using `WrappingMode.clamp_to_border` pub fn setBorderColor(self: Self, color: [4]f32) void { assert(self.tt == .texture_2d); gl.bindTexture(@enumToInt(self.tt), self.id); defer gl.bindTexture(@enumToInt(self.tt), 0); gl.texParameterfv(@enumToInt(self.tt), gl.GL_TEXTURE_BORDER_COLOR, &color); gl.util.checkError(); } /// set filtering mode pub fn setFilteringMode(self: Self, situation: FilteringSituation, mode: FilteringMode) void { assert(self.tt == .texture_2d or self.tt == .texture_cube_map); if (situation == .magnifying and (mode == .linear_mipmap_nearest or mode == .linear_mipmap_linear or mode == .nearest_mipmap_nearest or mode == .nearest_mipmap_linear)) { panic("meaningless filtering parameters!", .{}); } gl.bindTexture(@enumToInt(self.tt), self.id); defer gl.bindTexture(@enumToInt(self.tt), 0); gl.texParameteri(@enumToInt(self.tt), @enumToInt(situation), @enumToInt(mode)); gl.util.checkError(); } /// update image data pub fn updateImageData( self: *Self, target: UpdateTarget, mipmap_level: i32, texture_format: TextureFormat, width: u32, height: ?u32, depth: ?u32, image_format: ImageFormat, comptime T: type, data: ?[*]const T, gen_mipmap: bool, ) void { gl.bindTexture(@enumToInt(self.tt), self.id); defer gl.bindTexture(@enumToInt(self.tt), 0); switch (self.tt) { .texture_1d => { assert(target == .texture_1d or target == .proxy_texture_1d); gl.texImage1D( @enumToInt(target), mipmap_level, @enumToInt(texture_format), @intCast(c_int, width), 0, @enumToInt(image_format), gl.util.dataType(T), data, ); }, .texture_2d => { assert(target == .texture_2d or target == .proxy_texture_2d); gl.texImage2D( @enumToInt(target), mipmap_level, @enumToInt(texture_format), @intCast(c_int, width), @intCast(c_int, height.?), 0, @enumToInt(image_format), gl.util.dataType(T), data, ); }, .texture_1d_array => { assert(target == .texture_1d or target == .proxy_texture_1d); gl.texImage2D( @enumToInt(target), mipmap_level, @enumToInt(texture_format), @intCast(c_int, width), @intCast(c_int, height.?), 0, @enumToInt(image_format), gl.util.dataType(T), data, ); }, .texture_rectangle => { assert(target == .texture_rectangle or target == .proxy_texture_rectangle); gl.texImage2D( @enumToInt(target), mipmap_level, @enumToInt(texture_format), @intCast(c_int, width), @intCast(c_int, height.?), 0, @enumToInt(image_format), gl.util.dataType(T), data, ); }, .texture_cube_map => { assert(target == .texture_cube_map_positive_x or target == .texture_cube_map_negative_x or target == .texture_cube_map_positive_y or target == .texture_cube_map_negative_y or target == .texture_cube_map_positive_z or target == .texture_cube_map_negative_z or target == .proxy_texture_cube_map); gl.texImage2D( @enumToInt(target), mipmap_level, @enumToInt(texture_format), @intCast(c_int, width), @intCast(c_int, height.?), 0, @enumToInt(image_format), gl.util.dataType(T), data, ); }, .texture_3d => { assert(target == .texture_3d or target == .proxy_texture_3d); gl.texImage3D( @enumToInt(target), mipmap_level, @enumToInt(texture_format), @intCast(c_int, width), @intCast(c_int, height.?), @intCast(c_int, depth.?), 0, @enumToInt(image_format), gl.util.dataType(T), data, ); }, .texture_2d_array => { assert(target == .texture_2d_array or target == .proxy_texture_2d_array); gl.texImage3D( @enumToInt(target), mipmap_level, @enumToInt(texture_format), @intCast(c_int, width), @intCast(c_int, height.?), @intCast(c_int, depth.?), 0, @enumToInt(image_format), gl.util.dataType(T), data, ); }, else => { panic("invalid operation!", .{}); }, } gl.util.checkError(); if (self.tt != .texture_rectangle and gen_mipmap) { gl.generateMipmap(@enumToInt(self.tt)); gl.util.checkError(); } self.format = texture_format; self.width = width; self.height = height; self.depth = depth; } /// update multisample data pub fn updateMultisampleData( self: Self, target: UpdateTarget, samples: u32, texture_format: TextureFormat, width: u32, height: u32, depth: ?u32, fixed_sample_location: bool, ) void { switch (self.tt) { .texture_2d_multisample => { assert(target == .texture_2d_multisample or target == .proxy_texture_2d_multisample); gl.texImage2DMultisample( @enumToInt(target), samples, @enumToInt(texture_format), width, height, gl.util.boolType(fixed_sample_location), ); }, .texture_2d_multisample_array => { assert(target == .texture_2d_multisample_array or target == .proxy_texture_2d_multisample_array); gl.texImage3DMultisample( @enumToInt(target), samples, @enumToInt(texture_format), width, height, depth.?, gl.util.boolType(fixed_sample_location), ); }, else => { panic("invalid operation!", .{}); }, } gl.util.checkError(); } /// update buffer texture data pub fn updateBufferTexture( self: Self, texture_format: TextureFormat, vbo: gl.Uint, ) void { assert(self.tt == .texture_buffer); gl.texBuffer(@enumToInt(self.tt), @enumToInt(texture_format), vbo); gl.util.checkError(); }
src/graphics/common/Texture.zig
const std = @import("std"); const testing = std.testing; const allocator = std.testing.allocator; // TIMES // // Dijkstra optimized: // part 1: 0.037 seconds (answer: 707) // part 2: 0.719 seconds (answer: 2942) // // A*: // part 1: 0.052 seconds (answer: 707) // part 2: 1.034 seconds (answer: 2942) pub const Map = struct { pub const Mode = enum { Small, Large }; pub const Algo = enum { Dijkstra, AStar }; const Pos = struct { x: usize, y: usize, pub fn init(x: usize, y: usize) Pos { var self = Pos{ .x = x, .y = y }; return self; } pub fn deinit(_: *Pos) void {} pub fn equal(self: Pos, other: Pos) bool { return self.x == other.x and self.y == other.y; } }; const Node = struct { pos: Pos, cost: usize, pub fn init(pos: Pos, cost: usize) Node { var self = Node{ .pos = pos, .cost = cost }; return self; } fn lessThan(l: Node, r: Node) std.math.Order { return std.math.order(l.cost, r.cost); } }; const Dir = enum { N, S, E, W }; const Path = std.AutoHashMap(Pos, Node); mode: Mode, algo: Algo, enlarged: bool, width: usize, height: usize, grid: std.AutoHashMap(Pos, usize), pub fn init(mode: Mode, algo: Algo) Map { var self = Map{ .mode = mode, .algo = algo, .enlarged = false, .width = 0, .height = 0, .grid = std.AutoHashMap(Pos, usize).init(allocator), }; return self; } pub fn deinit(self: *Map) void { self.grid.deinit(); } pub fn process_line(self: *Map, data: []const u8) !void { if (self.width == 0) self.width = data.len; if (self.width != data.len) unreachable; const y = self.height; for (data) |num, x| { const n = num - '0'; const p = Pos.init(x, y); try self.grid.put(p, n); } self.height += 1; } pub fn get_total_risk(self: *Map) !usize { if (self.mode == Mode.Large and !self.enlarged) { try self.enlarge(); self.enlarged = true; } const start = Pos.init(0, 0); const goal = Pos.init(self.width - 1, self.height - 1); var cameFrom = Path.init(allocator); defer cameFrom.deinit(); switch (self.algo) { Algo.Dijkstra => try self.walk_dijkstra(start, goal, &cameFrom), Algo.AStar => try self.walk_astar(start, goal, &cameFrom), } var risk: usize = 0; var pos = goal; while (true) { // std.debug.warn("PATH {}\n", .{pos}); if (pos.equal(start)) break; risk += self.grid.get(pos).?; const node = cameFrom.get(pos).?; pos = node.pos; } // std.debug.warn("SHORTEST {}\n", .{risk}); return risk; } fn walk_dijkstra(self: *Map, start: Pos, goal: Pos, cameFrom: *Path) !void { var pending = std.PriorityQueue(Node, Node.lessThan).init(allocator); defer pending.deinit(); var score = std.AutoHashMap(Pos, usize).init(allocator); defer score.deinit(); // We begin the route at the start node try pending.add(Node.init(start, 0)); while (pending.count() != 0) { const min_node = pending.remove(); const u: Pos = min_node.pos; if (u.equal(goal)) { // found target -- yay! break; } const su = min_node.cost; // update score for all neighbours of u // add closest neighbour of u to the path for (std.enums.values(Dir)) |dir| { if (self.get_neighbor(u, dir)) |v| { const duv = self.grid.get(v).?; const tentative = su + duv; var sv: usize = std.math.maxInt(usize); if (score.getEntry(v)) |e| { sv = e.value_ptr.*; } if (tentative >= sv) continue; try pending.add(Node.init(v, tentative)); try score.put(v, tentative); try cameFrom.put(v, Node.init(u, duv)); } } } } // Implemented this because I thought it would make a major difference with // Dijkstra (back when the code was NOT using a priority queue), but there // is actually not much difference. and this is much more complicated. fn walk_astar(self: *Map, start: Pos, goal: Pos, cameFrom: *Path) !void { var pending = std.PriorityQueue(Node, Node.lessThan).init(allocator); defer pending.deinit(); var gScore = std.AutoHashMap(Pos, usize).init(allocator); defer gScore.deinit(); var hScore = std.AutoHashMap(Pos, usize).init(allocator); defer hScore.deinit(); // Fill hScore for all nodes // fScore and gScore are infinite by default var y: usize = 0; while (y < self.height) : (y += 1) { var x: usize = 0; while (x < self.width) : (x += 1) { const p = Pos.init(x, y); try hScore.put(p, self.height - y + self.width - x); } } try gScore.put(start, 0); try pending.add(Node.init(start, 0)); while (pending.count() != 0) { const min_node = pending.remove(); const u: Pos = min_node.pos; if (u.equal(goal)) { // found target -- yay! break; } // update score for all neighbours of u // add closest neighbour of u to the path var gu: usize = std.math.maxInt(usize); if (gScore.getEntry(u)) |e| { gu = e.value_ptr.*; } for (std.enums.values(Dir)) |dir| { if (self.get_neighbor(u, dir)) |v| { const duv = self.grid.get(v).?; const tentative = gu + duv; var gv: usize = std.math.maxInt(usize); if (gScore.getEntry(v)) |e| { gv = e.value_ptr.*; } if (tentative >= gv) continue; try pending.add(Node.init(v, tentative)); try gScore.put(v, tentative); try cameFrom.put(v, Node.init(u, duv)); } } } } fn enlarge(self: *Map) !void { var y: usize = 0; while (y < self.height) : (y += 1) { var x: usize = 0; while (x < self.width) : (x += 1) { const p = Pos.init(x, y); var m = self.grid.get(p).?; var dy: usize = 0; while (dy < 5) : (dy += 1) { var n = m; var dx: usize = 0; while (dx < 5) : (dx += 1) { const q = Pos.init(x + self.width * dx, y + self.height * dy); // std.debug.warn("ENLARGE {} = {}\n", .{ q, n }); try self.grid.put(q, n); n += 1; if (n > 9) n = 1; } m += 1; if (m > 9) m = 1; } } } self.width *= 5; self.height *= 5; } fn get_neighbor(self: *Map, u: Pos, dir: Dir) ?Pos { var dx: isize = 0; var dy: isize = 0; switch (dir) { Dir.N => dy = -1, Dir.S => dy = 1, Dir.E => dx = 1, Dir.W => dx = -1, } const sx = @intCast(isize, u.x) + dx; if (sx < 0 or sx >= self.width) return null; const sy = @intCast(isize, u.y) + dy; if (sy < 0 or sy >= self.height) return null; var v = Pos.init(@intCast(usize, sx), @intCast(usize, sy)); if (!self.grid.contains(v)) return null; return v; } }; test "sample gonzo Dijkstra" { const data: []const u8 = \\1199 \\9199 \\1199 \\1999 \\1111 ; var map = Map.init(Map.Mode.Small, Map.Algo.Dijkstra); defer map.deinit(); var it = std.mem.split(u8, data, "\n"); while (it.next()) |line| { try map.process_line(line); } const risk = try map.get_total_risk(); try testing.expect(risk == 9); } test "sample gonzo A*" { const data: []const u8 = \\1199 \\9199 \\1199 \\1999 \\1111 ; var map = Map.init(Map.Mode.Small, Map.Algo.AStar); defer map.deinit(); var it = std.mem.split(u8, data, "\n"); while (it.next()) |line| { try map.process_line(line); } const risk = try map.get_total_risk(); try testing.expect(risk == 9); } test "sample part a Dijkstra" { const data: []const u8 = \\1163751742 \\1381373672 \\2136511328 \\3694931569 \\7463417111 \\1319128137 \\1359912421 \\3125421639 \\1293138521 \\2311944581 ; var map = Map.init(Map.Mode.Small, Map.Algo.Dijkstra); defer map.deinit(); var it = std.mem.split(u8, data, "\n"); while (it.next()) |line| { try map.process_line(line); } const risk = try map.get_total_risk(); try testing.expect(risk == 40); } test "sample part a A*" { const data: []const u8 = \\1163751742 \\1381373672 \\2136511328 \\3694931569 \\7463417111 \\1319128137 \\1359912421 \\3125421639 \\1293138521 \\2311944581 ; var map = Map.init(Map.Mode.Small, Map.Algo.AStar); defer map.deinit(); var it = std.mem.split(u8, data, "\n"); while (it.next()) |line| { try map.process_line(line); } const risk = try map.get_total_risk(); try testing.expect(risk == 40); } test "sample part b Dijkstra" { const data: []const u8 = \\1163751742 \\1381373672 \\2136511328 \\3694931569 \\7463417111 \\1319128137 \\1359912421 \\3125421639 \\1293138521 \\2311944581 ; var map = Map.init(Map.Mode.Large, Map.Algo.Dijkstra); defer map.deinit(); var it = std.mem.split(u8, data, "\n"); while (it.next()) |line| { try map.process_line(line); } const risk = try map.get_total_risk(); try testing.expect(risk == 315); } test "sample part b A*" { const data: []const u8 = \\1163751742 \\1381373672 \\2136511328 \\3694931569 \\7463417111 \\1319128137 \\1359912421 \\3125421639 \\1293138521 \\2311944581 ; var map = Map.init(Map.Mode.Large, Map.Algo.AStar); defer map.deinit(); var it = std.mem.split(u8, data, "\n"); while (it.next()) |line| { try map.process_line(line); } const risk = try map.get_total_risk(); try testing.expect(risk == 315); }
2021/p15/map.zig
const std = @import("std"); const assert = std.debug.assert; // I borrowed this name from HLSL fn all(vector: anytype) bool { const type_info = @typeInfo(@TypeOf(vector)); assert(type_info.Vector.child == bool); assert(type_info.Vector.len > 1); return @reduce(.And, vector); } fn any(vector: anytype) bool { const type_info = @typeInfo(@TypeOf(vector)); assert(type_info.Vector.child == bool); assert(type_info.Vector.len > 1); return @reduce(.Or, vector); } pub const @"u32_2" = std.meta.Vector(2, u32); pub const f32_2 = std.meta.Vector(2, f32); pub const f32_3 = std.meta.Vector(3, f32); pub const f32_4 = std.meta.Vector(4, f32); // FIXME Zig doesn't seem to have a suitable matrix construct yet pub const f32_3x3 = [3]f32_3; pub const f32_4x3 = [4]f32_3; pub const f32_4x4 = [4]f32_4; const FrameBufferPixelFormat = f32_4; const FramebufferExtentMin = u32_2{ 16, 16 }; const FramebufferExtentMax = u32_2{ 2048, 2048 }; const RenderTileSize = u32_2{ 16, 16 }; const MaxWorkItemCount: u32 = 2048; const diffuse_sample_count: u32 = 16; const WorkItem = struct { position_start: u32_2, position_end: u32_2, }; const RayQuery = struct { direction_ws: f32_3, accum: FrameBufferPixelFormat = .{}, }; pub const RaytracerState = struct { frame_extent: u32_2, framebuffer: [][]FrameBufferPixelFormat, work_queue: []WorkItem, // Work item should be taken from the end work_queue_size: u32 = 0, ray_queries: []RayQuery, // FIXME Put in worker context ray_query_count: u32 = 0, rng: std.rand.Xoroshiro128, // Hardcode PRNG type for forward compatibility }; pub fn create_raytracer_state(allocator: std.mem.Allocator, extent: u32_2, seed: u64) !RaytracerState { assert(all(extent >= FramebufferExtentMin)); assert(all(extent <= FramebufferExtentMax)); // Allocate framebuffer const framebuffer = try allocator.alloc([]FrameBufferPixelFormat, extent[0]); errdefer allocator.free(framebuffer); for (framebuffer) |*column| { column.* = try allocator.alloc(FrameBufferPixelFormat, extent[1]); errdefer allocator.free(column); for (column.*) |*cell| { cell.* = .{ 0.0, 0.0, 0.0, 0.0 }; } } // Allocate work item queue const work_queue = try allocator.alloc(WorkItem, MaxWorkItemCount); errdefer allocator.free(work_queue); const ray_queries = try allocator.alloc(RayQuery, RenderTileSize[0] * RenderTileSize[1] * 1024); errdefer allocator.free(ray_queries); return RaytracerState{ .frame_extent = extent, .framebuffer = framebuffer, .work_queue = work_queue, .ray_queries = ray_queries, .rng = std.rand.Xoroshiro128.init(seed), }; } pub fn destroy_raytracer_state(allocator: std.mem.Allocator, rt: *RaytracerState) void { allocator.free(rt.ray_queries); allocator.free(rt.work_queue); for (rt.framebuffer) |column| { allocator.free(column); } allocator.free(rt.framebuffer); } // Cut the screen into tiles and create a workload item for each pub fn add_fullscreen_workload(rt: *RaytracerState) void { const tile_count = (rt.frame_extent + RenderTileSize - u32_2{ 1, 1 }) / RenderTileSize; var tile_index: u32_2 = .{ 0, undefined }; while (tile_index[0] < tile_count[0]) : (tile_index[0] += 1) { tile_index[1] = 0; while (tile_index[1] < tile_count[1]) : (tile_index[1] += 1) { const tile_min = tile_index * RenderTileSize; const tile_max = (tile_index + @splat(2, @as(u32, 1))) * RenderTileSize; const tile_max_clamped = u32_2{ std.math.min(tile_max[0], rt.frame_extent[0]), std.math.min(tile_max[1], rt.frame_extent[1]), }; rt.work_queue[rt.work_queue_size] = WorkItem{ .position_start = tile_min, .position_end = tile_max_clamped, }; rt.work_queue_size += 1; } } } // Renders some of the internal workload items and returns if everything is finished pub fn render_workload(rt: *RaytracerState, item_count: u32) bool { const count = std.math.min(item_count, rt.work_queue_size); const end = rt.work_queue_size; const start = end - count; for (rt.work_queue[start..end]) |work_item| { render_work_item(rt, work_item); } rt.work_queue_size = start; return rt.work_queue_size == 0; } const Material = struct { albedo: f32_3, metalness: f32, fake_texture: bool, }; const Pi: f32 = 3.14159265; const DegToRad: f32 = Pi / 180.0; const RayHitThreshold: f32 = 0.001; const Ray = struct { origin: f32_3, direction: f32_3, // Not normalized }; const Sphere = struct { origin: f32_3, radius: f32, material: *const Material, }; const Scene = struct { spheres: [8]*const Sphere, }; // TODO annoying fn u32_2_to_f32_2(v: u32_2) f32_2 { return .{ @intToFloat(f32, v[0]), @intToFloat(f32, v[1]), }; } fn dot(a: f32_3, b: f32_3) f32 { return @reduce(.Add, a * b); } fn cross(v1: f32_3, v2: f32_3) f32_3 { return .{ v1[1] * v2[2] - v1[2] * v2[1], v1[2] * v2[0] - v1[0] * v2[2], v1[0] * v2[1] - v1[1] * v2[0], }; } // normal should be normalized fn reflect(v: f32_3, normal: f32_3) f32_3 { return v - normal * @splat(3, 2.0 * dot(v, normal)); } fn mul(m: f32_3x3, v: f32_3) f32_3 { return f32_3{ dot(.{ m[0][0], m[1][0], m[2][0] }, v), dot(.{ m[0][1], m[1][1], m[2][1] }, v), dot(.{ m[0][2], m[1][2], m[2][2] }, v), }; } fn normalize(v: f32_3) f32_3 { const length = std.math.sqrt(dot(v, v)); const lengthInv = 1.0 / length; return v * @splat(3, lengthInv); } fn sign(value: f32) f32 { return if (value >= 0.0) 1.0 else -1.0; } fn lookAt(viewPosition: f32_3, targetPosition: f32_3, upDirection: f32_3) f32_3x3 { const viewForward = -normalize(targetPosition - viewPosition); const viewRight = normalize(cross(upDirection, viewForward)); const viewUp = cross(viewForward, viewRight); return .{ viewRight, viewUp, viewForward, }; } fn sampleDistribution(normal: f32_3, sample: f32_3) f32_3 { const sampleOriented = sample * @splat(3, sign(dot(normal, sample))); return sampleOriented; } fn render_work_item(rt: *RaytracerState, work_item: WorkItem) void { const fovDegrees: f32 = 100.0; const maxSteps: u32 = 2; const mat1Mirror = Material{ .albedo = .{ 0.2, 0.2, 0.2 }, .metalness = 1.0, .fake_texture = false }; const mat2 = Material{ .albedo = .{ 0.2, 0.2, 0.2 }, .metalness = 0.2, .fake_texture = true }; const mat3Diffuse = Material{ .albedo = .{ 0.2, 0.2, 0.2 }, .metalness = 0.4, .fake_texture = false }; const mat4 = Material{ .albedo = .{ 10.0, 10.0, 4.0 }, .metalness = 0.0, .fake_texture = false }; const mat5 = Material{ .albedo = .{ 10.0, 1.0, 1.0 }, .metalness = 0.0, .fake_texture = false }; const mat6EmissiveGreen = Material{ .albedo = .{ 1.0, 14.0, 1.0 }, .metalness = 0.0, .fake_texture = false }; const s1 = Sphere{ .origin = .{ 0.0, 0.0, 0.0 }, .radius = 1.0, .material = &mat1Mirror }; const s2 = Sphere{ .origin = .{ 0.0, -301.0, 0.0 }, .radius = 300.0, .material = &mat2 }; const s3 = Sphere{ .origin = .{ -2.0, 0.5, -2.0 }, .radius = 1.5, .material = &mat3Diffuse }; const s4 = Sphere{ .origin = .{ 2.0, -0.1, 1.0 }, .radius = 0.9, .material = &mat3Diffuse }; const s5 = Sphere{ .origin = .{ -4.0, 0.0, 0.0 }, .radius = 1.0, .material = &mat4 }; const sphereEmissiveRed = Sphere{ .origin = .{ 4.0, -0.2, 1.0 }, .radius = 0.8, .material = &mat5 }; const sphereEmissiveGreen = Sphere{ .origin = .{ -1.3, -0.5, 1.5 }, .radius = 0.5, .material = &mat6EmissiveGreen }; const sphereMirror2 = Sphere{ .origin = .{ -3.0, 1.0, 4.0 }, .radius = 2.0, .material = &mat1Mirror }; const spheres = [_]*const Sphere{ &s1, &s2, &s3, &s4, &s5, &sphereEmissiveRed, &sphereEmissiveGreen, &sphereMirror2 }; const scene = Scene{ .spheres = spheres }; const cameraPositionWS = f32_3{ 3.0, 3.0, 6.0 }; const cameraTargetWS = f32_3{ 0.0, -1.0, 0.0 }; const cameraUpVector = f32_3{ 0.0, 1.0, 0.0 }; const camera_orientation_ws = lookAt(cameraPositionWS, cameraTargetWS, cameraUpVector); const aspectRatioInv = @intToFloat(f32, rt.frame_extent[1]) / @intToFloat(f32, rt.frame_extent[0]); const tanHFov: f32 = std.math.tan((fovDegrees * 0.5) * DegToRad); const viewportTransform = f32_2{ tanHFov, -tanHFov * aspectRatioInv }; const imageSizeFloat = u32_2_to_f32_2(rt.frame_extent); // FOR TODO var pos_ts: u32_2 = .{ work_item.position_start[0], undefined }; while (pos_ts[0] < work_item.position_end[0]) : (pos_ts[0] += 1) { pos_ts[1] = work_item.position_start[1]; while (pos_ts[1] < work_item.position_end[1]) : (pos_ts[1] += 1) { const rayIndex = u32_2_to_f32_2(pos_ts) + @splat(2, @as(f32, 0.5)); const ray_dir_vs = ((rayIndex - imageSizeFloat * @splat(2, @as(f32, 0.5))) / imageSizeFloat) * viewportTransform; const ray_origin_vs: f32_3 = @splat(3, @as(f32, 0.0)); const ray_vs = Ray{ .origin = ray_origin_vs, .direction = .{ ray_dir_vs[0], ray_dir_vs[1], -1.0 }, }; const ray_ws = Ray{ .origin = ray_vs.origin + cameraPositionWS, .direction = mul(camera_orientation_ws, ray_vs.direction), }; const color = shade(scene, &rt.rng, ray_ws, maxSteps); rt.framebuffer[pos_ts[0]][pos_ts[1]] += f32_4{ color[0], color[1], color[2], 1 }; } } } const RayHit = struct { t: f32, mat: *const Material, position_ws: f32_3, normal_ws: f32_3, }; fn shade(scene: Scene, rng: *std.rand.Xoroshiro128, ray: Ray, steps: u32) f32_3 { var hitResult: RayHit = undefined; if (traverse_scene(scene, ray, &hitResult)) { const mat = hitResult.mat; if (steps > 0) { if (mat.metalness == 1.0) { const reflectedRay = Ray{ .origin = hitResult.position_ws, .direction = reflect(ray.direction, hitResult.normal_ws) }; return shade(scene, rng, reflectedRay, steps - 1); } else { var albedo = mat.albedo; if (mat.fake_texture) { // Checkerboard formula const size: f32 = 1.0; const modx1: f32 = (std.math.mod(f32, std.math.absFloat(hitResult.position_ws[0]) + size * 0.5, size * 2.0) catch 0.0) - size; const mody1: f32 = (std.math.mod(f32, std.math.absFloat(hitResult.position_ws[2]) + size * 0.5, size * 2.0) catch 0.0) - size; if (modx1 * mody1 > 0.0) albedo = f32_3{ 0.1, 0.1, 0.15 }; } var i: u32 = 0; var accum: f32_3 = .{}; while (i < diffuse_sample_count) : (i += 1) { const random_f32_3 = f32_3{ rng.random().float(f32) * 2.0 - 1.0, rng.random().float(f32) * 2.0 - 1.0, rng.random().float(f32) * 2.0 - 1.0, }; var randomSample = normalize(random_f32_3); randomSample = sampleDistribution(hitResult.normal_ws, randomSample); const reflectedRay = Ray{ .origin = hitResult.position_ws, .direction = randomSample }; accum += shade(scene, rng, reflectedRay, steps - 1); } // Shade result return albedo * accum / @splat(3, @intToFloat(f32, diffuse_sample_count)); } } else return mat.albedo; } // No hit -> fake skybox const normalizedDirection = normalize(ray.direction); const t: f32 = 0.5 * (normalizedDirection[1] + 1.0); return f32_3{ 1.0, 1.0, 1.0 } * @splat(3, 1.0 - t) + f32_3{ 0.5, 0.7, 1.0 } * @splat(3, t); } fn traverse_scene(s: Scene, ray: Ray, hit: *RayHit) bool { var bestHit: f32 = 0.0; for (s.spheres) |sphere_ws| { const t = hit_sphere(sphere_ws.*, ray); if (isBetterHit(t, bestHit)) { bestHit = t; const ray_hit_ws = ray.origin + ray.direction * @splat(3, t); hit.normal_ws = (ray_hit_ws - sphere_ws.origin) / @splat(3, sphere_ws.radius); hit.position_ws = ray_hit_ws; hit.mat = sphere_ws.material; } } hit.t = bestHit; return bestHit > RayHitThreshold; } fn hit_sphere(sphere: Sphere, ray: Ray) f32 { const originToCenter = ray.origin - sphere.origin; const a = dot(ray.direction, ray.direction); const b = 2.0 * dot(originToCenter, ray.direction); const c = dot(originToCenter, originToCenter) - sphere.radius * sphere.radius; const discriminant = b * b - 4.0 * a * c; if (discriminant < 0.0) { return -1.0; } else { return ((-b - std.math.sqrt(discriminant)) * 0.5) / a; } } fn isBetterHit(value: f32, base: f32) bool { return value > RayHitThreshold and (!(base > RayHitThreshold) or value < base); }
src/raytracer.zig
const std = @import("std"); const assert = std.debug.assert; pub const DNA = struct { pub const Unit = "nt"; pub const SupportsStrands = true; pub fn complement(letter: u8) u8 { return switch (letter) { 'A' => 'T', 'G' => 'C', 'C' => 'G', 'T', 'U' => 'A', 'Y' => 'R', 'R' => 'Y', 'W' => 'W', 'S' => 'S', 'K' => 'M', 'M' => 'K', 'D' => 'H', 'V' => 'B', 'H' => 'D', 'B' => 'V', 'N' => 'N', else => letter, }; } pub fn mapToBits(letter: u8) ?u2 { return switch (letter) { 'A' => 0b00, 'C' => 0b01, 'U', 'T' => 0b10, 'G' => 0b11, else => null, }; } const ScoreMatrixSize = 26; const ScoreMatrix = [ScoreMatrixSize][ScoreMatrixSize]i8{ [_]i8{ 2, -4, -4, 2, 0, 0, -4, 2, 0, 0, -4, 0, 2, 2, 0, 0, 0, 2, -4, -4, -4, 2, 2, 0, -4, 0 }, [_]i8{ -4, 2, 2, 2, 0, 0, 2, 2, 0, 0, 2, 0, 2, 2, 0, 0, 0, 2, 2, 2, 2, 2, 2, 0, 2, 0 }, [_]i8{ -4, 2, 2, -4, 0, 0, -4, 2, 0, 0, -4, 0, 2, 2, 0, 0, 0, -4, 2, -4, -4, 2, -4, 0, 2, 0 }, [_]i8{ 2, 2, -4, 2, 0, 0, 2, 2, 0, 0, 2, 0, 2, 2, 0, 0, 0, 2, 2, 2, 2, 2, 2, 0, 2, 0 }, [_]i8{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, [_]i8{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, [_]i8{ -4, 2, -4, 2, 0, 0, 2, -4, 0, 0, 2, 0, -4, 2, 0, 0, 0, 2, 2, -4, -4, 2, -4, 0, -4, 0 }, [_]i8{ 2, 2, 2, 2, 0, 0, -4, 2, 0, 0, 2, 0, 2, 2, 0, 0, 0, 2, 2, 2, 2, 2, 2, 0, 2, 0 }, [_]i8{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, [_]i8{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, [_]i8{ -4, 2, -4, 2, 0, 0, 2, 2, 0, 0, 2, 0, -4, 2, 0, 0, 0, 2, 2, 2, 2, 2, 2, 0, 2, 0 }, [_]i8{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, [_]i8{ 2, 2, 2, 2, 0, 0, -4, 2, 0, 0, -4, 0, 2, 2, 0, 0, 0, 2, 2, -4, -4, 2, 2, 0, 2, 0 }, [_]i8{ 2, 2, 2, 2, 0, 0, 2, 2, 0, 0, 2, 0, 2, 2, 0, 0, 0, 2, 2, 2, 2, 2, 2, 0, 2, 0 }, [_]i8{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, [_]i8{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, [_]i8{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, [_]i8{ 2, 2, -4, 2, 0, 0, 2, 2, 0, 0, 2, 0, 2, 2, 0, 0, 0, 2, 2, -4, -4, 2, 2, 0, -4, 0 }, [_]i8{ -4, 2, 2, 2, 0, 0, 2, 2, 0, 0, 2, 0, 2, 2, 0, 0, 0, 2, 2, -4, -4, 2, -4, 0, 2, 0 }, [_]i8{ -4, 2, -4, 2, 0, 0, -4, 2, 0, 0, 2, 0, -4, 2, 0, 0, 0, -4, -4, 2, 2, -4, 2, 0, 2, 0 }, [_]i8{ -4, 2, -4, 2, 0, 0, -4, 2, 0, 0, 2, 0, -4, 2, 0, 0, 0, -4, -4, 2, 2, -4, 2, 0, 2, 0 }, [_]i8{ 2, 2, 2, 2, 0, 0, 2, 2, 0, 0, 2, 0, 2, 2, 0, 0, 0, 2, 2, -4, -4, 2, 2, 0, 2, 0 }, [_]i8{ 2, 2, -4, 2, 0, 0, -4, 2, 0, 0, 2, 0, 2, 2, 0, 0, 0, 2, -4, 2, 2, 2, 2, 0, 2, 0 }, [_]i8{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, [_]i8{ -4, 2, 2, 2, 0, 0, -4, 2, 0, 0, 2, 0, 2, 2, 0, 0, 0, -4, 2, 2, 2, 2, 2, 0, 2, 0 }, [_]i8{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, }; pub fn score(a: u8, b: u8) i8 { const idx1: usize = a - 'A'; const idx2: usize = b - 'A'; assert(idx1 <= ScoreMatrixSize and idx2 <= ScoreMatrixSize); return ScoreMatrix[idx1][idx2]; } pub fn match(a: u8, b: u8) bool { return score(a, b) > 0; } pub fn matchSymbol(a: u8, b: u8) u8 { if (a == b) return '|'; if (match(a, b)) return '+'; return ' '; } }; test "complement" { try std.testing.expectEqual(DNA.complement('A'), 'T'); try std.testing.expectEqual(DNA.complement('G'), 'C'); try std.testing.expectEqual(DNA.complement('C'), 'G'); try std.testing.expectEqual(DNA.complement('T'), 'A'); try std.testing.expectEqual(DNA.complement('U'), 'A'); } test "bit mapping" { try std.testing.expectEqual(DNA.mapToBits('A'), 0b00); try std.testing.expectEqual(DNA.mapToBits('C'), 0b01); try std.testing.expectEqual(DNA.mapToBits('U'), 0b10); try std.testing.expectEqual(DNA.mapToBits('T'), 0b10); try std.testing.expectEqual(DNA.mapToBits('G'), 0b11); try std.testing.expectEqual(DNA.mapToBits('N'), null); } test "scoring" { try std.testing.expectEqual(DNA.score('A', 'A'), 2); try std.testing.expectEqual(DNA.score('A', 'T'), -4); try std.testing.expectEqual(DNA.score('A', 'M'), 2); // M = amino (A, C) } test "match" { try std.testing.expectEqual(DNA.match('A', 'A'), true); try std.testing.expectEqual(DNA.match('C', 'G'), false); try std.testing.expectEqual(DNA.match('G', 'G'), true); try std.testing.expectEqual(DNA.match('K', 'U'), true); // K = keto (T/U G) try std.testing.expectEqual(DNA.match('K', 'M'), false); }
src/bio/alphabet/dna.zig
const std = @import("std"); const ast = std.zig.ast; const Tree = ast.Tree; const Node = ast.Node; const full = ast.full; const assert = std.debug.assert; fn fullPtrType(tree: Tree, info: full.PtrType.Ast) full.PtrType { const token_tags = tree.tokens.items(.tag); // TODO: looks like stage1 isn't quite smart enough to handle enum // literals in some places here const Size = std.builtin.TypeInfo.Pointer.Size; const size: Size = switch (token_tags[info.main_token]) { .asterisk, .asterisk_asterisk, => switch (token_tags[info.main_token + 1]) { .r_bracket, .colon => .Many, .identifier => if (token_tags[info.main_token - 1] == .l_bracket) Size.C else .One, else => .One, }, .l_bracket => Size.Slice, else => unreachable, }; var result: full.PtrType = .{ .size = size, .allowzero_token = null, .const_token = null, .volatile_token = null, .ast = info, }; // We need to be careful that we don't iterate over any sub-expressions // here while looking for modifiers as that could result in false // positives. Therefore, start after a sentinel if there is one and // skip over any align node and bit range nodes. var i = if (info.sentinel != 0) lastToken(tree, info.sentinel) + 1 else info.main_token; const end = tree.firstToken(info.child_type); while (i < end) : (i += 1) { switch (token_tags[i]) { .keyword_allowzero => result.allowzero_token = i, .keyword_const => result.const_token = i, .keyword_volatile => result.volatile_token = i, .keyword_align => { assert(info.align_node != 0); if (info.bit_range_end != 0) { assert(info.bit_range_start != 0); i = lastToken(tree, info.bit_range_end) + 1; } else { i = lastToken(tree, info.align_node) + 1; } }, else => {}, } } return result; } pub fn ptrTypeSimple(tree: Tree, node: Node.Index) full.PtrType { assert(tree.nodes.items(.tag)[node] == .ptr_type); const data = tree.nodes.items(.data)[node]; const extra = tree.extraData(data.lhs, Node.PtrType); return fullPtrType(tree, .{ .main_token = tree.nodes.items(.main_token)[node], .align_node = extra.align_node, .sentinel = extra.sentinel, .bit_range_start = 0, .bit_range_end = 0, .child_type = data.rhs, }); } pub fn ptrTypeSentinel(tree: Tree, node: Node.Index) full.PtrType { assert(tree.nodes.items(.tag)[node] == .ptr_type_sentinel); const data = tree.nodes.items(.data)[node]; return fullPtrType(tree, .{ .main_token = tree.nodes.items(.main_token)[node], .align_node = 0, .sentinel = data.lhs, .bit_range_start = 0, .bit_range_end = 0, .child_type = data.rhs, }); } pub fn ptrTypeAligned(tree: Tree, node: Node.Index) full.PtrType { assert(tree.nodes.items(.tag)[node] == .ptr_type_aligned); const data = tree.nodes.items(.data)[node]; return fullPtrType(tree, .{ .main_token = tree.nodes.items(.main_token)[node], .align_node = data.lhs, .sentinel = 0, .bit_range_start = 0, .bit_range_end = 0, .child_type = data.rhs, }); } pub fn ptrTypeBitRange(tree: Tree, node: Node.Index) full.PtrType { assert(tree.nodes.items(.tag)[node] == .ptr_type_bit_range); const data = tree.nodes.items(.data)[node]; const extra = tree.extraData(data.lhs, Node.PtrTypeBitRange); return fullPtrType(tree, .{ .main_token = tree.nodes.items(.main_token)[node], .align_node = extra.align_node, .sentinel = extra.sentinel, .bit_range_start = extra.bit_range_start, .bit_range_end = extra.bit_range_end, .child_type = data.rhs, }); } fn fullIf(tree: Tree, info: full.If.Ast) full.If { const token_tags = tree.tokens.items(.tag); var result: full.If = .{ .ast = info, .payload_token = null, .error_token = null, .else_token = undefined, }; // if (cond_expr) |x| // ^ ^ const payload_pipe = lastToken(tree, info.cond_expr) + 2; if (token_tags[payload_pipe] == .pipe) { result.payload_token = payload_pipe + 1; } if (info.else_expr != 0) { // then_expr else |x| // ^ ^ result.else_token = lastToken(tree, info.then_expr) + 1; if (token_tags[result.else_token + 1] == .pipe) { result.error_token = result.else_token + 2; } } return result; } pub fn ifFull(tree: Tree, node: Node.Index) full.If { const data = tree.nodes.items(.data)[node]; if (tree.nodes.items(.tag)[node] == .@"if") { const extra = tree.extraData(data.rhs, Node.If); return fullIf(tree, .{ .cond_expr = data.lhs, .then_expr = extra.then_expr, .else_expr = extra.else_expr, .if_token = tree.nodes.items(.main_token)[node], }); } else { assert(tree.nodes.items(.tag)[node] == .if_simple); return fullIf(tree, .{ .cond_expr = data.lhs, .then_expr = data.rhs, .else_expr = 0, .if_token = tree.nodes.items(.main_token)[node], }); } } fn fullWhile(tree: Tree, info: full.While.Ast) full.While { const token_tags = tree.tokens.items(.tag); var result: full.While = .{ .ast = info, .inline_token = null, .label_token = null, .payload_token = null, .else_token = undefined, .error_token = null, }; var tok_i = info.while_token - 1; if (token_tags[tok_i] == .keyword_inline) { result.inline_token = tok_i; tok_i -= 1; } if (token_tags[tok_i] == .colon and token_tags[tok_i - 1] == .identifier) { result.label_token = tok_i - 1; } const last_cond_token = lastToken(tree, info.cond_expr); if (token_tags[last_cond_token + 2] == .pipe) { result.payload_token = last_cond_token + 3; } if (info.else_expr != 0) { // then_expr else |x| // ^ ^ result.else_token = lastToken(tree, info.then_expr) + 1; if (token_tags[result.else_token + 1] == .pipe) { result.error_token = result.else_token + 2; } } return result; } pub fn whileSimple(tree: Tree, node: Node.Index) full.While { const data = tree.nodes.items(.data)[node]; return fullWhile(tree, .{ .while_token = tree.nodes.items(.main_token)[node], .cond_expr = data.lhs, .cont_expr = 0, .then_expr = data.rhs, .else_expr = 0, }); } pub fn whileCont(tree: Tree, node: Node.Index) full.While { const data = tree.nodes.items(.data)[node]; const extra = tree.extraData(data.rhs, Node.WhileCont); return fullWhile(tree, .{ .while_token = tree.nodes.items(.main_token)[node], .cond_expr = data.lhs, .cont_expr = extra.cont_expr, .then_expr = extra.then_expr, .else_expr = 0, }); } pub fn whileFull(tree: Tree, node: Node.Index) full.While { const data = tree.nodes.items(.data)[node]; const extra = tree.extraData(data.rhs, Node.While); return fullWhile(tree, .{ .while_token = tree.nodes.items(.main_token)[node], .cond_expr = data.lhs, .cont_expr = extra.cont_expr, .then_expr = extra.then_expr, .else_expr = extra.else_expr, }); } pub fn forSimple(tree: Tree, node: Node.Index) full.While { const data = tree.nodes.items(.data)[node]; return fullWhile(tree, .{ .while_token = tree.nodes.items(.main_token)[node], .cond_expr = data.lhs, .cont_expr = 0, .then_expr = data.rhs, .else_expr = 0, }); } pub fn forFull(tree: Tree, node: Node.Index) full.While { const data = tree.nodes.items(.data)[node]; const extra = tree.extraData(data.rhs, Node.If); return fullWhile(tree, .{ .while_token = tree.nodes.items(.main_token)[node], .cond_expr = data.lhs, .cont_expr = 0, .then_expr = extra.then_expr, .else_expr = extra.else_expr, }); } pub fn lastToken(tree: ast.Tree, node: ast.Node.Index) ast.TokenIndex { const TokenIndex = ast.TokenIndex; const tags = tree.nodes.items(.tag); const datas = tree.nodes.items(.data); const main_tokens = tree.nodes.items(.main_token); const token_starts = tree.tokens.items(.start); const token_tags = tree.tokens.items(.tag); var n = node; var end_offset: TokenIndex = 0; while (true) switch (tags[n]) { .root => return @intCast(TokenIndex, tree.tokens.len - 1), .@"usingnamespace" => { // lhs is the expression if (datas[n].lhs == 0) { return main_tokens[n] + end_offset; } else { n = datas[n].lhs; } }, .test_decl => { // rhs is the block // lhs is the name if (datas[n].rhs != 0) { n = datas[n].rhs; } else if (datas[n].lhs != 0) { n = datas[n].lhs; } else { return main_tokens[n] + end_offset; } }, .global_var_decl => { // rhs is init node if (datas[n].rhs != 0) { n = datas[n].rhs; } else { const extra = tree.extraData(datas[n].lhs, Node.GlobalVarDecl); if (extra.section_node != 0) { end_offset += 1; // for the rparen n = extra.section_node; } else if (extra.align_node != 0) { end_offset += 1; // for the rparen n = extra.align_node; } else if (extra.type_node != 0) { n = extra.type_node; } else { end_offset += 1; // from mut token to name return main_tokens[n] + end_offset; } } }, .local_var_decl => { // rhs is init node if (datas[n].rhs != 0) { n = datas[n].rhs; } else { const extra = tree.extraData(datas[n].lhs, Node.LocalVarDecl); if (extra.align_node != 0) { end_offset += 1; // for the rparen n = extra.align_node; } else if (extra.type_node != 0) { n = extra.type_node; } else { end_offset += 1; // from mut token to name return main_tokens[n] + end_offset; } } }, .simple_var_decl => { // rhs is init node if (datas[n].rhs != 0) { n = datas[n].rhs; } else if (datas[n].lhs != 0) { n = datas[n].lhs; } else { end_offset += 1; // from mut token to name return main_tokens[n] + end_offset; } }, .aligned_var_decl => { // rhs is init node, lhs is align node if (datas[n].rhs != 0) { n = datas[n].rhs; } else if (datas[n].lhs != 0) { end_offset += 1; // for the rparen n = datas[n].lhs; } else { end_offset += 1; // from mut token to name return main_tokens[n] + end_offset; } }, .@"errdefer" => { // lhs is the token payload, rhs is the expression if (datas[n].rhs != 0) { n = datas[n].rhs; } else if (datas[n].lhs != 0) { // right pipe end_offset += 1; n = datas[n].lhs; } else { return main_tokens[n] + end_offset; } }, .@"defer" => { // rhs is the defered expr if (datas[n].rhs != 0) { n = datas[n].rhs; } else { return main_tokens[n] + end_offset; } }, .bool_not, .negation, .bit_not, .negation_wrap, .address_of, .@"try", .@"await", .optional_type, .@"resume", .@"nosuspend", .@"comptime", => n = datas[n].lhs, .@"catch", .equal_equal, .bang_equal, .less_than, .greater_than, .less_or_equal, .greater_or_equal, .assign_mul, .assign_div, .assign_mod, .assign_add, .assign_sub, .assign_bit_shift_left, .assign_bit_shift_right, .assign_bit_and, .assign_bit_xor, .assign_bit_or, .assign_mul_wrap, .assign_add_wrap, .assign_sub_wrap, .assign, .merge_error_sets, .mul, .div, .mod, .array_mult, .mul_wrap, .add, .sub, .array_cat, .add_wrap, .sub_wrap, .bit_shift_left, .bit_shift_right, .bit_and, .bit_xor, .bit_or, .@"orelse", .bool_and, .bool_or, .anyframe_type, .error_union, .if_simple, .while_simple, .for_simple, .ptr_type_aligned, .ptr_type_sentinel, .ptr_type, .ptr_type_bit_range, .array_type, .switch_case_one, .switch_case, .switch_range, => n = datas[n].rhs, .field_access, .unwrap_optional, .grouped_expression, .multiline_string_literal, .error_set_decl, .asm_simple, .asm_output, .asm_input, .error_value, => return datas[n].rhs + end_offset, .@"anytype", .anyframe_literal, .char_literal, .integer_literal, .float_literal, .unreachable_literal, .identifier, .deref, .enum_literal, .string_literal, => return main_tokens[n] + end_offset, .@"return" => if (datas[n].lhs != 0) { n = datas[n].lhs; } else { return main_tokens[n] + end_offset; }, .call, .async_call => { end_offset += 1; // for the rparen const params = tree.extraData(datas[n].rhs, Node.SubRange); if (params.end - params.start == 0) { return main_tokens[n] + end_offset; } n = tree.extra_data[params.end - 1]; // last parameter }, .tagged_union_enum_tag => { const members = tree.extraData(datas[n].rhs, Node.SubRange); if (members.end - members.start == 0) { end_offset += 4; // for the rparen + rparen + lbrace + rbrace n = datas[n].lhs; } else { end_offset += 1; // for the rbrace n = tree.extra_data[members.end - 1]; // last parameter } }, .call_comma, .async_call_comma, .tagged_union_enum_tag_trailing, => { end_offset += 2; // for the comma/semicolon + rparen/rbrace const params = tree.extraData(datas[n].rhs, Node.SubRange); std.debug.assert(params.end > params.start); n = tree.extra_data[params.end - 1]; // last parameter }, .@"switch" => { const cases = tree.extraData(datas[n].rhs, Node.SubRange); if (cases.end - cases.start == 0) { end_offset += 3; // rparen, lbrace, rbrace n = datas[n].lhs; // condition expression } else { end_offset += 1; // for the rbrace n = tree.extra_data[cases.end - 1]; // last case } }, .container_decl_arg => { const members = tree.extraData(datas[n].rhs, Node.SubRange); if (members.end - members.start == 0) { end_offset += 3; // for the rparen + lbrace + rbrace n = datas[n].lhs; } else { end_offset += 1; // for the rbrace n = tree.extra_data[members.end - 1]; // last parameter } }, .@"asm" => { const extra = tree.extraData(datas[n].rhs, Node.Asm); return extra.rparen + end_offset; }, .array_init, .struct_init, => { const elements = tree.extraData(datas[n].rhs, Node.SubRange); std.debug.assert(elements.end - elements.start > 0); end_offset += 1; // for the rbrace n = tree.extra_data[elements.end - 1]; // last element }, .array_init_comma, .struct_init_comma, .container_decl_arg_trailing, .switch_comma, => { const members = tree.extraData(datas[n].rhs, Node.SubRange); std.debug.assert(members.end - members.start > 0); end_offset += 2; // for the comma + rbrace n = tree.extra_data[members.end - 1]; // last parameter }, .array_init_dot, .struct_init_dot, .block, .container_decl, .tagged_union, .builtin_call, => { std.debug.assert(datas[n].rhs - datas[n].lhs > 0); end_offset += 1; // for the rbrace n = tree.extra_data[datas[n].rhs - 1]; // last statement }, .array_init_dot_comma, .struct_init_dot_comma, .block_semicolon, .container_decl_trailing, .tagged_union_trailing, .builtin_call_comma, => { std.debug.assert(datas[n].rhs - datas[n].lhs > 0); end_offset += 2; // for the comma/semicolon + rbrace/rparen n = tree.extra_data[datas[n].rhs - 1]; // last member }, .call_one, .async_call_one, .array_access, => { end_offset += 1; // for the rparen/rbracket if (datas[n].rhs == 0) { return main_tokens[n] + end_offset; } n = datas[n].rhs; }, .array_init_dot_two, .block_two, .builtin_call_two, .struct_init_dot_two, .container_decl_two, .tagged_union_two, => { if (datas[n].rhs != 0) { end_offset += 1; // for the rparen/rbrace n = datas[n].rhs; } else if (datas[n].lhs != 0) { end_offset += 1; // for the rparen/rbrace n = datas[n].lhs; } else { switch (tags[n]) { .array_init_dot_two, .block_two, .struct_init_dot_two, => end_offset += 1, // rbrace .builtin_call_two => end_offset += 2, // lparen/lbrace + rparen/rbrace .container_decl_two => { var i: u32 = 2; // lbrace + rbrace while (token_tags[main_tokens[n] + i] == .container_doc_comment) i += 1; end_offset += i; }, .tagged_union_two => { var i: u32 = 5; // (enum) {} while (token_tags[main_tokens[n] + i] == .container_doc_comment) i += 1; end_offset += i; }, else => unreachable, } return main_tokens[n] + end_offset; } }, .array_init_dot_two_comma, .builtin_call_two_comma, .block_two_semicolon, .struct_init_dot_two_comma, .container_decl_two_trailing, .tagged_union_two_trailing, => { end_offset += 2; // for the comma/semicolon + rbrace/rparen if (datas[n].rhs != 0) { n = datas[n].rhs; } else if (datas[n].lhs != 0) { n = datas[n].lhs; } else { return main_tokens[n] + end_offset; // returns { } } }, .container_field_init => { if (datas[n].rhs != 0) { n = datas[n].rhs; } else if (datas[n].lhs != 0) { n = datas[n].lhs; } else { return main_tokens[n] + end_offset; } }, .container_field_align => { if (datas[n].rhs != 0) { end_offset += 1; // for the rparen n = datas[n].rhs; } else if (datas[n].lhs != 0) { n = datas[n].lhs; } else { return main_tokens[n] + end_offset; } }, .container_field => { const extra = tree.extraData(datas[n].rhs, Node.ContainerField); if (extra.value_expr != 0) { n = extra.value_expr; } else if (extra.align_expr != 0) { end_offset += 1; // for the rparen n = extra.align_expr; } else if (datas[n].lhs != 0) { n = datas[n].lhs; } else { return main_tokens[n] + end_offset; } }, .array_init_one, .struct_init_one, => { end_offset += 1; // rbrace if (datas[n].rhs == 0) { return main_tokens[n] + end_offset; } else { n = datas[n].rhs; } }, .slice_open, .call_one_comma, .async_call_one_comma, .array_init_one_comma, .struct_init_one_comma, => { end_offset += 2; // ellipsis2 + rbracket, or comma + rparen n = datas[n].rhs; std.debug.assert(n != 0); }, .slice => { const extra = tree.extraData(datas[n].rhs, Node.Slice); std.debug.assert(extra.end != 0); // should have used slice_open end_offset += 1; // rbracket n = extra.end; }, .slice_sentinel => { const extra = tree.extraData(datas[n].rhs, Node.SliceSentinel); if (extra.sentinel != 0) { end_offset += 1; // right bracket n = extra.sentinel; } else if (extra.end != 0) { end_offset += 2; // colon, right bracket n = extra.end; } else { // Assume both sentinel and end are completely devoid of tokens end_offset += 3; // ellipsis, colon, right bracket n = extra.start; } }, .@"continue" => { if (datas[n].lhs != 0) { return datas[n].lhs + end_offset; } else { return main_tokens[n] + end_offset; } }, .@"break" => { if (datas[n].rhs != 0) { n = datas[n].rhs; } else if (datas[n].lhs != 0) { return datas[n].lhs + end_offset; } else { return main_tokens[n] + end_offset; } }, .fn_decl => { if (datas[n].rhs != 0) { n = datas[n].rhs; } else { n = datas[n].lhs; } }, .fn_proto_multi => { const extra = tree.extraData(datas[n].lhs, Node.SubRange); // rhs can be 0 when no return type is provided if (datas[n].rhs != 0) { n = datas[n].rhs; } else { // Use the last argument and skip right paren n = tree.extra_data[extra.end - 1]; end_offset += 1; } }, .fn_proto_simple => { // rhs can be 0 when no return type is provided // lhs can be 0 when no parameter is provided if (datas[n].rhs != 0) { n = datas[n].rhs; } else if (datas[n].lhs != 0) { n = datas[n].lhs; // Skip right paren end_offset += 1; } else { // Skip left and right paren return main_tokens[n] + end_offset + 2; } }, .fn_proto_one => { const extra = tree.extraData(datas[n].lhs, Node.FnProtoOne); // linksection, callconv, align can appear in any order, so we // find the last one here. // rhs can be zero if no return type is provided var max_node: Node.Index = 0; var max_start: u32 = 0; if (datas[n].rhs != 0) { max_node = datas[n].rhs; max_start = token_starts[main_tokens[max_node]]; } var max_offset: TokenIndex = 0; if (extra.align_expr != 0) { const start = token_starts[main_tokens[extra.align_expr]]; if (start > max_start) { max_node = extra.align_expr; max_start = start; max_offset = 1; // for the rparen } } if (extra.section_expr != 0) { const start = token_starts[main_tokens[extra.section_expr]]; if (start > max_start) { max_node = extra.section_expr; max_start = start; max_offset = 1; // for the rparen } } if (extra.callconv_expr != 0) { const start = token_starts[main_tokens[extra.callconv_expr]]; if (start > max_start) { max_node = extra.callconv_expr; max_start = start; max_offset = 1; // for the rparen } } if (max_node == 0) { std.debug.assert(max_offset == 0); // No linksection, callconv, align, return type if (extra.param != 0) { n = extra.param; end_offset += 1; } else { // Skip left and right parens return main_tokens[n] + end_offset + 2; } } else { n = max_node; end_offset += max_offset; } }, .fn_proto => { const extra = tree.extraData(datas[n].lhs, Node.FnProto); // linksection, callconv, align can appear in any order, so we // find the last one here. // rhs can be zero if no return type is provided var max_node: Node.Index = 0; var max_start: u32 = 0; if (datas[n].rhs != 0) { max_node = datas[n].rhs; max_start = token_starts[main_tokens[max_node]]; } var max_offset: TokenIndex = 0; if (extra.align_expr != 0) { const start = token_starts[main_tokens[extra.align_expr]]; if (start > max_start) { max_node = extra.align_expr; max_start = start; max_offset = 1; // for the rparen } } if (extra.section_expr != 0) { const start = token_starts[main_tokens[extra.section_expr]]; if (start > max_start) { max_node = extra.section_expr; max_start = start; max_offset = 1; // for the rparen } } if (extra.callconv_expr != 0) { const start = token_starts[main_tokens[extra.callconv_expr]]; if (start > max_start) { max_node = extra.callconv_expr; max_start = start; max_offset = 1; // for the rparen } } if (max_node == 0) { std.debug.assert(max_offset == 0); // No linksection, callconv, align, return type // Use the last parameter and skip one extra token for the right paren n = extra.params_end; end_offset += 1; } else { n = max_node; end_offset += max_offset; } }, .while_cont => { const extra = tree.extraData(datas[n].rhs, Node.WhileCont); std.debug.assert(extra.then_expr != 0); n = extra.then_expr; }, .@"while" => { const extra = tree.extraData(datas[n].rhs, Node.While); std.debug.assert(extra.else_expr != 0); n = extra.else_expr; }, .@"if", .@"for" => { const extra = tree.extraData(datas[n].rhs, Node.If); std.debug.assert(extra.else_expr != 0); n = extra.else_expr; }, .@"suspend" => { if (datas[n].lhs != 0) { n = datas[n].lhs; } else { return main_tokens[n] + end_offset; } }, .array_type_sentinel => { const extra = tree.extraData(datas[n].rhs, Node.ArrayTypeSentinel); n = extra.elem_type; }, }; } pub fn containerField(tree: ast.Tree, node: ast.Node.Index) ?ast.full.ContainerField { return switch (tree.nodes.items(.tag)[node]) { .container_field => tree.containerField(node), .container_field_init => tree.containerFieldInit(node), .container_field_align => tree.containerFieldAlign(node), else => null, }; } pub fn ptrType(tree: ast.Tree, node: ast.Node.Index) ?ast.full.PtrType { return switch (tree.nodes.items(.tag)[node]) { .ptr_type => ptrTypeSimple(tree, node), .ptr_type_aligned => ptrTypeAligned(tree, node), .ptr_type_bit_range => ptrTypeBitRange(tree, node), .ptr_type_sentinel => ptrTypeSentinel(tree, node), else => null, }; } pub fn whileAst(tree: ast.Tree, node: ast.Node.Index) ?ast.full.While { return switch (tree.nodes.items(.tag)[node]) { .@"while" => whileFull(tree, node), .while_simple => whileSimple(tree, node), .while_cont => whileCont(tree, node), .@"for" => forFull(tree, node), .for_simple => forSimple(tree, node), else => null, }; } pub fn isContainer(tree: ast.Tree, node: ast.Node.Index) bool { return switch (tree.nodes.items(.tag)[node]) { .container_decl, .container_decl_trailing, .container_decl_arg, .container_decl_arg_trailing, .container_decl_two, .container_decl_two_trailing, .tagged_union, .tagged_union_trailing, .tagged_union_two, .tagged_union_two_trailing, .tagged_union_enum_tag, .tagged_union_enum_tag_trailing, .root, .error_set_decl, => true, else => false, }; } /// Returns the member indices of a given declaration container. /// Asserts given `tag` is a container node pub fn declMembers(tree: ast.Tree, node_idx: ast.Node.Index, buffer: *[2]ast.Node.Index) []const ast.Node.Index { std.debug.assert(isContainer(tree, node_idx)); return switch (tree.nodes.items(.tag)[node_idx]) { .container_decl, .container_decl_trailing => tree.containerDecl(node_idx).ast.members, .container_decl_arg, .container_decl_arg_trailing => tree.containerDeclArg(node_idx).ast.members, .container_decl_two, .container_decl_two_trailing => tree.containerDeclTwo(buffer, node_idx).ast.members, .tagged_union, .tagged_union_trailing => tree.taggedUnion(node_idx).ast.members, .tagged_union_enum_tag, .tagged_union_enum_tag_trailing => tree.taggedUnionEnumTag(node_idx).ast.members, .tagged_union_two, .tagged_union_two_trailing => tree.taggedUnionTwo(buffer, node_idx).ast.members, .root => tree.rootDecls(), .error_set_decl => &[_]ast.Node.Index{}, else => unreachable, }; } /// Returns an `ast.full.VarDecl` for a given node index. /// Returns null if the tag doesn't match pub fn varDecl(tree: ast.Tree, node_idx: ast.Node.Index) ?ast.full.VarDecl { return switch (tree.nodes.items(.tag)[node_idx]) { .global_var_decl => tree.globalVarDecl(node_idx), .local_var_decl => tree.localVarDecl(node_idx), .aligned_var_decl => tree.alignedVarDecl(node_idx), .simple_var_decl => tree.simpleVarDecl(node_idx), else => null, }; } pub fn isBuiltinCall(tree: ast.Tree, node: ast.Node.Index) bool { return switch (tree.nodes.items(.tag)[node]) { .builtin_call, .builtin_call_comma, .builtin_call_two, .builtin_call_two_comma, => true, else => false, }; } pub fn isCall(tree: ast.Tree, node: ast.Node.Index) bool { return switch (tree.nodes.items(.tag)[node]) { .call, .call_comma, .call_one, .call_one_comma, .async_call, .async_call_comma, .async_call_one, .async_call_one_comma, => true, else => false, }; } pub fn fnProto(tree: ast.Tree, node: ast.Node.Index, buf: *[1]ast.Node.Index) ?ast.full.FnProto { return switch (tree.nodes.items(.tag)[node]) { .fn_proto => tree.fnProto(node), .fn_proto_multi => tree.fnProtoMulti(node), .fn_proto_one => tree.fnProtoOne(buf, node), .fn_proto_simple => tree.fnProtoSimple(buf, node), .fn_decl => fnProto(tree, tree.nodes.items(.data)[node].lhs, buf), else => null, }; } pub fn callFull(tree: ast.Tree, node: ast.Node.Index, buf: *[1]ast.Node.Index) ?ast.full.Call { return switch (tree.nodes.items(.tag)[node]) { .call, .call_comma, .async_call, .async_call_comma, => tree.callFull(node), .call_one, .call_one_comma, .async_call_one, .async_call_one_comma, => tree.callOne(buf, node), else => null, }; }
src/ast.zig
const std = @import("std"); const t = @import("testing.zig"); const Input = @import("input.zig"); usingnamespace @import("ghost_party.zig"); usingnamespace @import("meta.zig"); usingnamespace @import("result.zig"); usingnamespace @import("string_parser.zig"); /// /// Base type constructor for ParZig parsers /// /// Constructs a parser from a partial parser. /// /// Arguments: /// `P`: parser type struct /// `P.T`: value type of parse results /// `P.parse`: parser function `Input -> Result(T)` /// /// Returns: /// `Parser{ .T = P.T } /// pub fn Parser(comptime P: type) type { return struct { // Keep in sync with `meta.isParser` const Self = @This(); /// Value type of parse results pub const T = ParseResult(P).T; pub usingnamespace (P); /// /// Functor `map` combinator /// /// Constructs a parser that calls a function `f` to transform a parse /// `Result(T)` to a parse `Result(U)`. /// /// Arguments: /// `f`: transform function `Self.T -> U` /// /// Returns: /// `Parser{ .T = U }` /// pub fn Map(comptime U: type, comptime map: anytype) type { return Parser(struct { pub fn parse(input: Input) Result(U) { switch (Self.parse(input)) { .Some => |r| return Result(U).some(map(r.value), r.tail), .None => |r| return Result(U).fail(r), } } }); } /// /// Alternative sequence combinator `<|>` /// /// Constructs a parser that runs two parsers and returns the leftmost /// successful result, or the rightmost failure reason. /// /// Arguments: /// `R`: right side parser /// /// Conditions: /// `Self.T == R.T` /// /// Returns: /// `Result(T)` /// pub fn Alt(comptime R: type) type { return Parser(struct { pub fn parse(input: Input) Result(T) { const r = Self.parse(input); if (.Some == r) return r; return R.parse(input); } }); } /// /// Left sequence combinator `<*` /// /// Constructs a parser that runs two parsers, returning the left /// result when both are successful. If either parser fails, the /// leftmost failure is returned. /// /// Arguments: /// `R`: right side parser /// /// Returns: /// `Parser{.T = Self.T}` /// pub fn SeqL(comptime R: type) type { return Parser(struct { pub fn parse(input: Input) Result(T) { switch (Self.parse(input)) { .None => |r| return Result(T).fail(r), .Some => |left| // switch (R.parse(left.tail)) { .None => |r| return Result(T).fail(r), .Some => // return Result(T){ .Some = left }, }, } } }); } /// /// Right sequence combinator `*>` /// /// Constructs a parser that runs two parsers, returning the right /// result when both are successful. If either parser fails, the /// leftmost failure is returned, wrapped as the right result. /// /// Arguments: /// `R`: right side parser /// /// Returns: /// `Parser{.T = R.T}` /// pub fn SeqR(comptime R: type) type { const U = R.T; return Parser(struct { pub fn parse(input: Input) Result(U) { switch (Self.parse(input)) { .None => |r| return Result(U).fail(r), .Some => |left| // switch (R.parse(left.tail)) { .None => |r| return Result(U).fail(r), .Some => |right| // return Result(U){ .Some = right }, }, } } }); } /// /// Monadic `bind` combinator `>>=` /// /// Constructs a parser that calls a function `f` to transform a parse /// `Result(T)` to a parse `Result(U)`. /// /// Arguments: /// `U`: result value type /// `f`: transform function `Self.T -> Result(U)` /// /// Returns: /// `Parser{ .T = U }` /// pub fn Bind(comptime U: type, comptime f: anytype) type { return Self.Map(Result(U), f).Join; } /// /// Monadic `join` combinator /// /// Constructs a parser that unwraps a nested result type /// `Result(Result(U))`, to `Result(U)`. /// /// Arguments: none /// /// Conditions: /// `Self{.T = Result(U)}` /// /// Returns: /// `Parser{ .T = U }` /// pub const Join = Parser(struct { pub fn parse(input: Input) Result(U) { switch (Self.parse(input)) { .None => |r| return Result(U).fail(r), .Some => |r| return r, } } }); /// /// Parser runner /// /// Arguments: /// `bytes: []const u8` - input buffer to parse /// `label: ?[]const u8` - optional label (e.g. file name) /// /// Returns: /// `Result(Self.T)` /// pub fn run( bytes: []const u8, label: ?[]const u8, ) Result(T) { return Self.parse(Input.init(bytes, label)); } }; } /// /// Monadic `pure` constructor /// /// Constructs a parser that returns a constant successful result. /// /// Arguments: /// `v`: parse result value /// /// Returns: /// `Parser{ .T = @TypeOf(v) }` /// pub fn Pure(comptime v: anytype) type { const T = @TypeOf(v); return Parser(struct { pub fn parse(input: Input) Result(T) { return Result(T).some(v, input); } }); } /// /// Constant failure reason constructor /// /// Constructs a parser that always fails with the given reason. /// /// Arguments: /// `T`: parse result value type /// `why`: opptional reason for failure /// /// Returns: /// `Parser{ .T = T }` /// pub fn Fail(comptime T: type, comptime why: ?Reason) type { return Parser(struct { pub fn parse(input: Input) Result(T) { _ = input; return Result(T).fail(why); } }); } test "parse failure" { try t.expectNone(Fail(void, null), ""); } /// /// Singleton parser that successfully matches nothing /// pub const Nothing = Pure({}); test "parse nothing" { try t.expectSomeExactlyEqual({}, Nothing, ghost); try t.expectSomeTail(ghost, Nothing, ghost); } /// /// Singleton parser that only matches the end of input /// pub const End = Parser(struct { pub fn parse(input: Input) Result(void) { if (input.len() != 0) return Result(void).none(); return Result(void).some({}, input); } }); test "parse end of input" { try t.expectSomeEqual({}, End, ""); try t.expectNone(End, "👻"); } /// /// Look-ahead non-matching constructor /// /// Constructs a parser that never consumes input, and negates the result of /// the given parser. When it is successful, this parser returns a failed /// result without reason, and when it fails, this parser returns a successful /// void result. /// /// Arguments: /// `P`: the parser to be negated /// /// Returns: /// `Parser{ .T = void }` /// pub fn Not(comptime P: type) type { return Parser(struct { pub fn parse(input: Input) Result(void) { switch (P.parse(input)) { .Some => return Result(void).none(), .None => return Result(void).some({}, input), } } }); } test "non matching look-ahead" { try t.expectNone(Not(Char('👻')), ghost_party); try t.expectSomeEqual({}, Not(Char('🥳')), ghost_party); } /// /// Look-ahead constructor /// /// Constructs a parser that never consumes input, and maps any successful /// result of the given parser to void. /// /// Arguments: /// `P`: the parser to be tested /// /// Returns: /// `Parser{ .T = void }` /// pub fn Try(comptime P: type) type { return Parser(struct { pub fn parse(input: Input) Result(void) { switch (P.parse(input)) { .None => |r| return Result(void).fail(r), .Some => return Result(void).some({}, input), } } }); } test "matching look-ahead" { try t.expectNone(Try(Char('🥳')), ghost_party); try t.expectSomeEqual({}, Try(Char('👻')), ghost_party); } /// /// Optional parser constructor /// /// Constructs a parser that maps the result value type of the given parser /// to an optional, and maps any failures to a successful `null` result. /// /// Arguments: /// `P`: parser to be made optional /// /// Returns: /// `Parser { .T = ?P.T }` /// pub fn Optional(comptime P: anytype) type { const T = P.T; return Parser(struct { pub fn parse(input: Input) Result(?T) { switch (P.parse(input)) { .Some => |r| return Result(?T).some(r.value, r.tail), .None => return Result(?T).some(null, input), } } }); } test "optional" { try t.expectSomeEqualSliceOpt(u8, ghost, Optional(Char('👻')), ghost_party); try t.expectSomeEqual(null, Optional(Char('👻')), party_ghost); } //------------------------------------------------------------------------------ // // MARK: Tests for Parser combinators // //------------------------------------------------------------------------------ test "alternatives" { try t.expectSomeEqualSlice(u8, ghost, Char('🥳').Alt(Char('👻')), ghost_party); try t.expectSomeEqualSlice(u8, party, Char('🥳').Alt(Char('👻')), party_ghost); } test "sequence left" { try t.expectSomeEqualSlice(u8, party, Char('🥳').SeqL(Char('👻')), party_ghost); try t.expectNone(Char('🥳').SeqL(Char('👻')), ghost_party); } test "sequence right" { try t.expectSomeEqualSlice(u8, ghost, Char('🥳').SeqR(Char('👻')), party_ghost); try t.expectNone(Char('🥳').SeqR(Char('👻')), ghost_party); } test "compile" { std.testing.refAllDecls(@This()); }
src/parser.zig
const std = @import("std"); const util = @import("util.zig"); const data = @embedFile("../data/day05.txt"); // Takes in lines, returns number of intersections pub fn numberOfIntersections(lines: []const util.Line(i32), consider_diagonals: bool) !usize { var map = util.Map(util.Point(i32), usize).init(util.gpa); defer map.deinit(); for (lines) |line| { // Skip diagonals if requested const line_type = line.getType(); if (!consider_diagonals and line_type == .Diagonal) continue; // Diagonal lines must be 45 degrees per problem statement var delta = util.Point(i32).subtract(line.end, line.start); if (line_type == .Diagonal and try util.absInt(delta.x) != try util.absInt(delta.y)) return error.InvalidInput; // Turn delta into a number you can increment a position by to iterate along the line delta.x = if (delta.x == 0) @as(i32, 0) else if (delta.x < 0) @as(i32, -1) else @as(i32, 1); delta.y = if (delta.y == 0) @as(i32, 0) else if (delta.y < 0) @as(i32, -1) else @as(i32, 1); // Iterate over line. We need to ensure the end value allows us to _include_ the last point. var pos = line.start; const end = util.Point(i32){ .x = line.end.x + delta.x, .y = line.end.y + delta.y }; while (!std.meta.eql(pos, end)) : (pos = util.Point(i32).add(pos, delta)) { try map.put(pos, (map.get(pos) orelse 0) + 1); } } // Given that map, find the number of points that have 2 or more lines var num_intersections: usize = 0; var it = map.valueIterator(); while (it.next()) |value| { if (value.* >= 2) num_intersections += 1; } return num_intersections; } pub fn main() !void { defer { const leaks = util.gpa_impl.deinit(); std.debug.assert(!leaks); } var lines = util.List(util.Line(i32)).init(util.gpa); defer lines.deinit(); // Parse into lines var it = util.tokenize(u8, data, "\n"); while (it.next()) |line_data| { var point_it = util.tokenize(u8, line_data, "-> ,"); const line = util.Line(i32){ .start = util.Point(i32){ .x = util.parseInt(i32, point_it.next() orelse return error.InvalidInput, 10) catch { return error.InvalidInput; }, .y = util.parseInt(i32, point_it.next() orelse return error.InvalidInput, 10) catch { return error.InvalidInput; }, }, .end = util.Point(i32){ .x = util.parseInt(i32, point_it.next() orelse return error.InvalidInput, 10) catch { return error.InvalidInput; }, .y = util.parseInt(i32, point_it.next() orelse return error.InvalidInput, 10) catch { return error.InvalidInput; }, }, }; try lines.append(line); } // Part 1 var intersections_pt1 = try numberOfIntersections(lines.items, false); util.print("Part 1: Number of intersections: {d}\n", .{intersections_pt1}); // Part 2 var intersections_pt2 = try numberOfIntersections(lines.items, true); util.print("Part 2: Number of intersections: {d}\n", .{intersections_pt2}); }
src/day05.zig
const std = @import("../index.zig"); const builtin = @import("builtin"); const fmt = std.fmt; const Endian = builtin.Endian; const readIntSliceLittle = std.mem.readIntSliceLittle; const writeIntSliceLittle = std.mem.writeIntSliceLittle; // Based on Supercop's ref10 implementation. pub const X25519 = struct { pub const secret_length = 32; pub const minimum_key_length = 32; fn trimScalar(s: []u8) void { s[0] &= 248; s[31] &= 127; s[31] |= 64; } fn scalarBit(s: []const u8, i: usize) i32 { return (s[i >> 3] >> @intCast(u3, i & 7)) & 1; } pub fn create(out: []u8, private_key: []const u8, public_key: []const u8) bool { std.debug.assert(out.len >= secret_length); std.debug.assert(private_key.len >= minimum_key_length); std.debug.assert(public_key.len >= minimum_key_length); var storage: [7]Fe = undefined; var x1 = &storage[0]; var x2 = &storage[1]; var z2 = &storage[2]; var x3 = &storage[3]; var z3 = &storage[4]; var t0 = &storage[5]; var t1 = &storage[6]; // computes the scalar product Fe.fromBytes(x1, public_key); // restrict the possible scalar values var e: [32]u8 = undefined; for (e[0..]) |_, i| { e[i] = private_key[i]; } trimScalar(e[0..]); // computes the actual scalar product (the result is in x2 and z2) // Montgomery ladder // In projective coordinates, to avoid divisions: x = X / Z // We don't care about the y coordinate, it's only 1 bit of information Fe.init1(x2); Fe.init0(z2); // "zero" point Fe.copy(x3, x1); Fe.init1(z3); var swap: i32 = 0; var pos: isize = 254; while (pos >= 0) : (pos -= 1) { // constant time conditional swap before ladder step const b = scalarBit(e, @intCast(usize, pos)); swap ^= b; // xor trick avoids swapping at the end of the loop Fe.cswap(x2, x3, swap); Fe.cswap(z2, z3, swap); swap = b; // anticipates one last swap after the loop // Montgomery ladder step: replaces (P2, P3) by (P2*2, P2+P3) // with differential addition Fe.sub(t0, x3, z3); Fe.sub(t1, x2, z2); Fe.add(x2, x2, z2); Fe.add(z2, x3, z3); Fe.mul(z3, t0, x2); Fe.mul(z2, z2, t1); Fe.sq(t0, t1); Fe.sq(t1, x2); Fe.add(x3, z3, z2); Fe.sub(z2, z3, z2); Fe.mul(x2, t1, t0); Fe.sub(t1, t1, t0); Fe.sq(z2, z2); Fe.mulSmall(z3, t1, 121666); Fe.sq(x3, x3); Fe.add(t0, t0, z3); Fe.mul(z3, x1, z2); Fe.mul(z2, t1, t0); } // last swap is necessary to compensate for the xor trick // Note: after this swap, P3 == P2 + P1. Fe.cswap(x2, x3, swap); Fe.cswap(z2, z3, swap); // normalises the coordinates: x == X / Z Fe.invert(z2, z2); Fe.mul(x2, x2, z2); Fe.toBytes(out, x2); x1.secureZero(); x2.secureZero(); x3.secureZero(); t0.secureZero(); t1.secureZero(); z2.secureZero(); z3.secureZero(); std.mem.secureZero(u8, e[0..]); // Returns false if the output is all zero // (happens with some malicious public keys) return !zerocmp(u8, out); } pub fn createPublicKey(public_key: []u8, private_key: []const u8) bool { var base_point = []u8{9} ++ []u8{0} ** 31; return create(public_key, private_key, base_point); } }; // Constant time compare to zero. fn zerocmp(comptime T: type, a: []const T) bool { var s: T = 0; for (a) |b| { s |= b; } return s == 0; } //////////////////////////////////// /// Arithmetic modulo 2^255 - 19 /// //////////////////////////////////// // Taken from Supercop's ref10 implementation. // A bit bigger than TweetNaCl, over 4 times faster. // field element const Fe = struct { b: [10]i32, fn secureZero(self: *Fe) void { std.mem.secureZero(u8, @ptrCast([*]u8, self)[0..@sizeOf(Fe)]); } fn init0(h: *Fe) void { for (h.b) |*e| { e.* = 0; } } fn init1(h: *Fe) void { for (h.b[1..]) |*e| { e.* = 0; } h.b[0] = 1; } fn copy(h: *Fe, f: *const Fe) void { for (h.b) |_, i| { h.b[i] = f.b[i]; } } fn neg(h: *Fe, f: *const Fe) void { for (h.b) |_, i| { h.b[i] = -f.b[i]; } } fn add(h: *Fe, f: *const Fe, g: *const Fe) void { for (h.b) |_, i| { h.b[i] = f.b[i] + g.b[i]; } } fn sub(h: *Fe, f: *const Fe, g: *const Fe) void { for (h.b) |_, i| { h.b[i] = f.b[i] - g.b[i]; } } fn cswap(f: *Fe, g: *Fe, b: i32) void { for (f.b) |_, i| { const x = (f.b[i] ^ g.b[i]) & -b; f.b[i] ^= x; g.b[i] ^= x; } } fn ccopy(f: *Fe, g: *const Fe, b: i32) void { for (f.b) |_, i| { const x = (f.b[i] ^ g.b[i]) & -b; f.b[i] ^= x; } } inline fn carryRound(c: []i64, t: []i64, comptime i: comptime_int, comptime shift: comptime_int, comptime mult: comptime_int) void { const j = (i + 1) % 10; c[i] = (t[i] + (i64(1) << shift)) >> (shift + 1); t[j] += c[i] * mult; t[i] -= c[i] * (i64(1) << (shift + 1)); } fn carry1(h: *Fe, t: []i64) void { var c: [10]i64 = undefined; var sc = c[0..]; var st = t[0..]; carryRound(sc, st, 9, 24, 19); carryRound(sc, st, 1, 24, 1); carryRound(sc, st, 3, 24, 1); carryRound(sc, st, 5, 24, 1); carryRound(sc, st, 7, 24, 1); carryRound(sc, st, 0, 25, 1); carryRound(sc, st, 2, 25, 1); carryRound(sc, st, 4, 25, 1); carryRound(sc, st, 6, 25, 1); carryRound(sc, st, 8, 25, 1); for (h.b) |_, i| { h.b[i] = @intCast(i32, t[i]); } } fn carry2(h: *Fe, t: []i64) void { var c: [10]i64 = undefined; var sc = c[0..]; var st = t[0..]; carryRound(sc, st, 0, 25, 1); carryRound(sc, st, 4, 25, 1); carryRound(sc, st, 1, 24, 1); carryRound(sc, st, 5, 24, 1); carryRound(sc, st, 2, 25, 1); carryRound(sc, st, 6, 25, 1); carryRound(sc, st, 3, 24, 1); carryRound(sc, st, 7, 24, 1); carryRound(sc, st, 4, 25, 1); carryRound(sc, st, 8, 25, 1); carryRound(sc, st, 9, 24, 19); carryRound(sc, st, 0, 25, 1); for (h.b) |_, i| { h.b[i] = @intCast(i32, t[i]); } } fn fromBytes(h: *Fe, s: []const u8) void { std.debug.assert(s.len >= 32); var t: [10]i64 = undefined; t[0] = readIntSliceLittle(u32, s[0..4]); t[1] = u32(readIntSliceLittle(u24, s[4..7])) << 6; t[2] = u32(readIntSliceLittle(u24, s[7..10])) << 5; t[3] = u32(readIntSliceLittle(u24, s[10..13])) << 3; t[4] = u32(readIntSliceLittle(u24, s[13..16])) << 2; t[5] = readIntSliceLittle(u32, s[16..20]); t[6] = u32(readIntSliceLittle(u24, s[20..23])) << 7; t[7] = u32(readIntSliceLittle(u24, s[23..26])) << 5; t[8] = u32(readIntSliceLittle(u24, s[26..29])) << 4; t[9] = (u32(readIntSliceLittle(u24, s[29..32])) & 0x7fffff) << 2; carry1(h, t[0..]); } fn mulSmall(h: *Fe, f: *const Fe, comptime g: comptime_int) void { var t: [10]i64 = undefined; for (t[0..]) |_, i| { t[i] = i64(f.b[i]) * g; } carry1(h, t[0..]); } fn mul(h: *Fe, f1: *const Fe, g1: *const Fe) void { const f = f1.b; const g = g1.b; var F: [10]i32 = undefined; var G: [10]i32 = undefined; F[1] = f[1] * 2; F[3] = f[3] * 2; F[5] = f[5] * 2; F[7] = f[7] * 2; F[9] = f[9] * 2; G[1] = g[1] * 19; G[2] = g[2] * 19; G[3] = g[3] * 19; G[4] = g[4] * 19; G[5] = g[5] * 19; G[6] = g[6] * 19; G[7] = g[7] * 19; G[8] = g[8] * 19; G[9] = g[9] * 19; // t's become h var t: [10]i64 = undefined; t[0] = f[0] * i64(g[0]) + F[1] * i64(G[9]) + f[2] * i64(G[8]) + F[3] * i64(G[7]) + f[4] * i64(G[6]) + F[5] * i64(G[5]) + f[6] * i64(G[4]) + F[7] * i64(G[3]) + f[8] * i64(G[2]) + F[9] * i64(G[1]); t[1] = f[0] * i64(g[1]) + f[1] * i64(g[0]) + f[2] * i64(G[9]) + f[3] * i64(G[8]) + f[4] * i64(G[7]) + f[5] * i64(G[6]) + f[6] * i64(G[5]) + f[7] * i64(G[4]) + f[8] * i64(G[3]) + f[9] * i64(G[2]); t[2] = f[0] * i64(g[2]) + F[1] * i64(g[1]) + f[2] * i64(g[0]) + F[3] * i64(G[9]) + f[4] * i64(G[8]) + F[5] * i64(G[7]) + f[6] * i64(G[6]) + F[7] * i64(G[5]) + f[8] * i64(G[4]) + F[9] * i64(G[3]); t[3] = f[0] * i64(g[3]) + f[1] * i64(g[2]) + f[2] * i64(g[1]) + f[3] * i64(g[0]) + f[4] * i64(G[9]) + f[5] * i64(G[8]) + f[6] * i64(G[7]) + f[7] * i64(G[6]) + f[8] * i64(G[5]) + f[9] * i64(G[4]); t[4] = f[0] * i64(g[4]) + F[1] * i64(g[3]) + f[2] * i64(g[2]) + F[3] * i64(g[1]) + f[4] * i64(g[0]) + F[5] * i64(G[9]) + f[6] * i64(G[8]) + F[7] * i64(G[7]) + f[8] * i64(G[6]) + F[9] * i64(G[5]); t[5] = f[0] * i64(g[5]) + f[1] * i64(g[4]) + f[2] * i64(g[3]) + f[3] * i64(g[2]) + f[4] * i64(g[1]) + f[5] * i64(g[0]) + f[6] * i64(G[9]) + f[7] * i64(G[8]) + f[8] * i64(G[7]) + f[9] * i64(G[6]); t[6] = f[0] * i64(g[6]) + F[1] * i64(g[5]) + f[2] * i64(g[4]) + F[3] * i64(g[3]) + f[4] * i64(g[2]) + F[5] * i64(g[1]) + f[6] * i64(g[0]) + F[7] * i64(G[9]) + f[8] * i64(G[8]) + F[9] * i64(G[7]); t[7] = f[0] * i64(g[7]) + f[1] * i64(g[6]) + f[2] * i64(g[5]) + f[3] * i64(g[4]) + f[4] * i64(g[3]) + f[5] * i64(g[2]) + f[6] * i64(g[1]) + f[7] * i64(g[0]) + f[8] * i64(G[9]) + f[9] * i64(G[8]); t[8] = f[0] * i64(g[8]) + F[1] * i64(g[7]) + f[2] * i64(g[6]) + F[3] * i64(g[5]) + f[4] * i64(g[4]) + F[5] * i64(g[3]) + f[6] * i64(g[2]) + F[7] * i64(g[1]) + f[8] * i64(g[0]) + F[9] * i64(G[9]); t[9] = f[0] * i64(g[9]) + f[1] * i64(g[8]) + f[2] * i64(g[7]) + f[3] * i64(g[6]) + f[4] * i64(g[5]) + f[5] * i64(g[4]) + f[6] * i64(g[3]) + f[7] * i64(g[2]) + f[8] * i64(g[1]) + f[9] * i64(g[0]); carry2(h, t[0..]); } // we could use Fe.mul() for this, but this is significantly faster fn sq(h: *Fe, fz: *const Fe) void { const f0 = fz.b[0]; const f1 = fz.b[1]; const f2 = fz.b[2]; const f3 = fz.b[3]; const f4 = fz.b[4]; const f5 = fz.b[5]; const f6 = fz.b[6]; const f7 = fz.b[7]; const f8 = fz.b[8]; const f9 = fz.b[9]; const f0_2 = f0 * 2; const f1_2 = f1 * 2; const f2_2 = f2 * 2; const f3_2 = f3 * 2; const f4_2 = f4 * 2; const f5_2 = f5 * 2; const f6_2 = f6 * 2; const f7_2 = f7 * 2; const f5_38 = f5 * 38; const f6_19 = f6 * 19; const f7_38 = f7 * 38; const f8_19 = f8 * 19; const f9_38 = f9 * 38; var t: [10]i64 = undefined; t[0] = f0 * i64(f0) + f1_2 * i64(f9_38) + f2_2 * i64(f8_19) + f3_2 * i64(f7_38) + f4_2 * i64(f6_19) + f5 * i64(f5_38); t[1] = f0_2 * i64(f1) + f2 * i64(f9_38) + f3_2 * i64(f8_19) + f4 * i64(f7_38) + f5_2 * i64(f6_19); t[2] = f0_2 * i64(f2) + f1_2 * i64(f1) + f3_2 * i64(f9_38) + f4_2 * i64(f8_19) + f5_2 * i64(f7_38) + f6 * i64(f6_19); t[3] = f0_2 * i64(f3) + f1_2 * i64(f2) + f4 * i64(f9_38) + f5_2 * i64(f8_19) + f6 * i64(f7_38); t[4] = f0_2 * i64(f4) + f1_2 * i64(f3_2) + f2 * i64(f2) + f5_2 * i64(f9_38) + f6_2 * i64(f8_19) + f7 * i64(f7_38); t[5] = f0_2 * i64(f5) + f1_2 * i64(f4) + f2_2 * i64(f3) + f6 * i64(f9_38) + f7_2 * i64(f8_19); t[6] = f0_2 * i64(f6) + f1_2 * i64(f5_2) + f2_2 * i64(f4) + f3_2 * i64(f3) + f7_2 * i64(f9_38) + f8 * i64(f8_19); t[7] = f0_2 * i64(f7) + f1_2 * i64(f6) + f2_2 * i64(f5) + f3_2 * i64(f4) + f8 * i64(f9_38); t[8] = f0_2 * i64(f8) + f1_2 * i64(f7_2) + f2_2 * i64(f6) + f3_2 * i64(f5_2) + f4 * i64(f4) + f9 * i64(f9_38); t[9] = f0_2 * i64(f9) + f1_2 * i64(f8) + f2_2 * i64(f7) + f3_2 * i64(f6) + f4 * i64(f5_2); carry2(h, t[0..]); } fn sq2(h: *Fe, f: *const Fe) void { Fe.sq(h, f); Fe.mul_small(h, h, 2); } // This could be simplified, but it would be slower fn invert(out: *Fe, z: *const Fe) void { var i: usize = undefined; var t: [4]Fe = undefined; var t0 = &t[0]; var t1 = &t[1]; var t2 = &t[2]; var t3 = &t[3]; Fe.sq(t0, z); Fe.sq(t1, t0); Fe.sq(t1, t1); Fe.mul(t1, z, t1); Fe.mul(t0, t0, t1); Fe.sq(t2, t0); Fe.mul(t1, t1, t2); Fe.sq(t2, t1); i = 1; while (i < 5) : (i += 1) Fe.sq(t2, t2); Fe.mul(t1, t2, t1); Fe.sq(t2, t1); i = 1; while (i < 10) : (i += 1) Fe.sq(t2, t2); Fe.mul(t2, t2, t1); Fe.sq(t3, t2); i = 1; while (i < 20) : (i += 1) Fe.sq(t3, t3); Fe.mul(t2, t3, t2); Fe.sq(t2, t2); i = 1; while (i < 10) : (i += 1) Fe.sq(t2, t2); Fe.mul(t1, t2, t1); Fe.sq(t2, t1); i = 1; while (i < 50) : (i += 1) Fe.sq(t2, t2); Fe.mul(t2, t2, t1); Fe.sq(t3, t2); i = 1; while (i < 100) : (i += 1) Fe.sq(t3, t3); Fe.mul(t2, t3, t2); Fe.sq(t2, t2); i = 1; while (i < 50) : (i += 1) Fe.sq(t2, t2); Fe.mul(t1, t2, t1); Fe.sq(t1, t1); i = 1; while (i < 5) : (i += 1) Fe.sq(t1, t1); Fe.mul(out, t1, t0); t0.secureZero(); t1.secureZero(); t2.secureZero(); t3.secureZero(); } // This could be simplified, but it would be slower fn pow22523(out: *Fe, z: *const Fe) void { var i: usize = undefined; var t: [3]Fe = undefined; var t0 = &t[0]; var t1 = &t[1]; var t2 = &t[2]; Fe.sq(t0, z); Fe.sq(t1, t0); Fe.sq(t1, t1); Fe.mul(t1, z, t1); Fe.mul(t0, t0, t1); Fe.sq(t0, t0); Fe.mul(t0, t1, t0); Fe.sq(t1, t0); i = 1; while (i < 5) : (i += 1) Fe.sq(t1, t1); Fe.mul(t0, t1, t0); Fe.sq(t1, t0); i = 1; while (i < 10) : (i += 1) Fe.sq(t1, t1); Fe.mul(t1, t1, t0); Fe.sq(t2, t1); i = 1; while (i < 20) : (i += 1) Fe.sq(t2, t2); Fe.mul(t1, t2, t1); Fe.sq(t1, t1); i = 1; while (i < 10) : (i += 1) Fe.sq(t1, t1); Fe.mul(t0, t1, t0); Fe.sq(t1, t0); i = 1; while (i < 50) : (i += 1) Fe.sq(t1, t1); Fe.mul(t1, t1, t0); Fe.sq(t2, t1); i = 1; while (i < 100) : (i += 1) Fe.sq(t2, t2); Fe.mul(t1, t2, t1); Fe.sq(t1, t1); i = 1; while (i < 50) : (i += 1) Fe.sq(t1, t1); Fe.mul(t0, t1, t0); Fe.sq(t0, t0); i = 1; while (i < 2) : (i += 1) Fe.sq(t0, t0); Fe.mul(out, t0, z); t0.secureZero(); t1.secureZero(); t2.secureZero(); } inline fn toBytesRound(c: []i64, t: []i64, comptime i: comptime_int, comptime shift: comptime_int) void { c[i] = t[i] >> shift; if (i + 1 < 10) { t[i + 1] += c[i]; } t[i] -= c[i] * (i32(1) << shift); } fn toBytes(s: []u8, h: *const Fe) void { std.debug.assert(s.len >= 32); var t: [10]i64 = undefined; for (h.b[0..]) |_, i| { t[i] = h.b[i]; } var q = (19 * t[9] + ((i32(1) << 24))) >> 25; { var i: usize = 0; while (i < 5) : (i += 1) { q += t[2 * i]; q >>= 26; q += t[2 * i + 1]; q >>= 25; } } t[0] += 19 * q; var c: [10]i64 = undefined; var st = t[0..]; var sc = c[0..]; toBytesRound(sc, st, 0, 26); toBytesRound(sc, st, 1, 25); toBytesRound(sc, st, 2, 26); toBytesRound(sc, st, 3, 25); toBytesRound(sc, st, 4, 26); toBytesRound(sc, st, 5, 25); toBytesRound(sc, st, 6, 26); toBytesRound(sc, st, 7, 25); toBytesRound(sc, st, 8, 26); toBytesRound(sc, st, 9, 25); var ut: [10]u32 = undefined; for (ut[0..]) |_, i| { ut[i] = @bitCast(u32, @intCast(i32, t[i])); } // TODO https://github.com/ziglang/zig/issues/863 writeIntSliceLittle(u32, s[0..4], (ut[0] >> 0) | (ut[1] << 26)); writeIntSliceLittle(u32, s[4..8], (ut[1] >> 6) | (ut[2] << 19)); writeIntSliceLittle(u32, s[8..12], (ut[2] >> 13) | (ut[3] << 13)); writeIntSliceLittle(u32, s[12..16], (ut[3] >> 19) | (ut[4] << 6)); writeIntSliceLittle(u32, s[16..20], (ut[5] >> 0) | (ut[6] << 25)); writeIntSliceLittle(u32, s[20..24], (ut[6] >> 7) | (ut[7] << 19)); writeIntSliceLittle(u32, s[24..28], (ut[7] >> 13) | (ut[8] << 12)); writeIntSliceLittle(u32, s[28..], (ut[8] >> 20) | (ut[9] << 6)); std.mem.secureZero(i64, t[0..]); } // Parity check. Returns 0 if even, 1 if odd fn isNegative(f: *const Fe) bool { var s: [32]u8 = undefined; Fe.toBytes(s[0..], f); const isneg = s[0] & 1; s.secureZero(); return isneg; } fn isNonZero(f: *const Fe) bool { var s: [32]u8 = undefined; Fe.toBytes(s[0..], f); const isnonzero = zerocmp(u8, s[0..]); s.secureZero(); return isneg; } }; test "x25519 public key calculation from secret key" { var sk: [32]u8 = undefined; var pk_expected: [32]u8 = undefined; var pk_calculated: [32]u8 = undefined; try fmt.hexToBytes(sk[0..], "8052030376d47112be7f73ed7a019293dd12ad910b654455798b4667d73de166"); try fmt.hexToBytes(pk_expected[0..], "f1814f0e8ff1043d8a44d25babff3cedcae6c22c3edaa48f857ae70de2baae50"); std.debug.assert(X25519.createPublicKey(pk_calculated[0..], sk)); std.debug.assert(std.mem.eql(u8, pk_calculated, pk_expected)); } test "x25519 rfc7748 vector1" { const secret_key = <KEY>"; const public_key = <KEY>"; const expected_output = "\xc3\xda\x55\x37\x9d\xe9\xc6\x90\x8e\x94\xea\x4d\xf2\x8d\x08\x4f\x32\xec\xcf\x03\x49\x1c\x71\xf7\x54\xb4\x07\x55\x77\xa2\x85\x52"; var output: [32]u8 = undefined; std.debug.assert(X25519.create(output[0..], secret_key, public_key)); std.debug.assert(std.mem.eql(u8, output, expected_output)); } test "x25519 rfc7748 vector2" { const secret_key = <KEY>"; const public_key = <KEY>"; const expected_output = "\x95\xcb\xde\x94\x76\xe8\x90\x7d\x7a\xad\xe4\x5c\xb4\xb8\x73\xf8\x8b\x59\x5a\x68\x79\x9f\xa1\x52\xe6\xf8\xf7\x64\x7a\xac\x79\x57"; var output: [32]u8 = undefined; std.debug.assert(X25519.create(output[0..], secret_key, public_key)); std.debug.assert(std.mem.eql(u8, output, expected_output)); } test "x25519 rfc7748 one iteration" { const initial_value = "\x09\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00"; const expected_output = "\x42\x2c\x8e\x7a\x62\x27\xd7\xbc\xa1\x35\x0b\x3e\x2b\xb7\x27\x9f\x78\x97\xb8\x7b\xb6\x85\x4b\x78\x3c\x60\xe8\x03\x11\xae\x30\x79"; var k: [32]u8 = initial_value; var u: [32]u8 = initial_value; var i: usize = 0; while (i < 1) : (i += 1) { var output: [32]u8 = undefined; std.debug.assert(X25519.create(output[0..], k, u)); std.mem.copy(u8, u[0..], k[0..]); std.mem.copy(u8, k[0..], output[0..]); } std.debug.assert(std.mem.eql(u8, k[0..], expected_output)); } test "x25519 rfc7748 1,000 iterations" { // These iteration tests are slow so we always skip them. Results have been verified. if (true) { return error.SkipZigTest; } const initial_value = "\x09\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00"; const expected_output = "\x68\x4c\xf5\x9b\xa8\x33\x09\x55\x28\x00\xef\x56\x6f\x2f\x4d\x3c\x1c\x38\x87\xc4\x93\x60\xe3\x87\x5f\x2e\xb9\x4d\x99\x53\x2c\x51"; var k: [32]u8 = initial_value; var u: [32]u8 = initial_value; var i: usize = 0; while (i < 1000) : (i += 1) { var output: [32]u8 = undefined; std.debug.assert(X25519.create(output[0..], k, u)); std.mem.copy(u8, u[0..], k[0..]); std.mem.copy(u8, k[0..], output[0..]); } std.debug.assert(std.mem.eql(u8, k[0..], expected_output)); } test "x25519 rfc7748 1,000,000 iterations" { if (true) { return error.SkipZigTest; } const initial_value = "\x09\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00"; const expected_output = "\x7c\x39\x11\xe0\xab\x25\x86\xfd\x86\x44\x97\x29\x7e\x57\x5e\x6f\x3b\xc6\x01\xc0\x88\x3c\x30\xdf\x5f\x4d\xd2\xd2\x4f\x66\x54\x24"; var k: [32]u8 = initial_value; var u: [32]u8 = initial_value; var i: usize = 0; while (i < 1000000) : (i += 1) { var output: [32]u8 = undefined; std.debug.assert(X25519.create(output[0..], k, u)); std.mem.copy(u8, u[0..], k[0..]); std.mem.copy(u8, k[0..], output[0..]); } std.debug.assert(std.mem.eql(u8, k[0..], expected_output)); }
std/crypto/x25519.zig
const fmath = @import("index.zig"); pub fn isInf(x: var) -> bool { const T = @typeOf(x); switch (T) { f32 => { const bits = @bitCast(u32, x); bits & 0x7FFFFFFF == 0x7F800000 }, f64 => { const bits = @bitCast(u64, x); bits & (@maxValue(u64) >> 1) == (0x7FF << 52) }, else => { @compileError("isInf not implemented for " ++ @typeName(T)); }, } } pub fn isPositiveInf(x: var) -> bool { const T = @typeOf(x); switch (T) { f32 => { @bitCast(u32, x) == 0x7F800000 }, f64 => { @bitCast(u64, x) == 0x7FF << 52 }, else => { @compileError("isPositiveInf not implemented for " ++ @typeName(T)); }, } } pub fn isNegativeInf(x: var) -> bool { const T = @typeOf(x); switch (T) { f32 => { @bitCast(u32, x) == 0xFF800000 }, f64 => { @bitCast(u64, x) == 0xFFF << 52 }, else => { @compileError("isNegativeInf not implemented for " ++ @typeName(T)); }, } } test "isInf" { fmath.assert(!isInf(f32(0.0))); fmath.assert(!isInf(f32(-0.0))); fmath.assert(!isInf(f64(0.0))); fmath.assert(!isInf(f64(-0.0))); fmath.assert(isInf(fmath.inf(f32))); fmath.assert(isInf(-fmath.inf(f32))); fmath.assert(isInf(fmath.inf(f64))); fmath.assert(isInf(-fmath.inf(f64))); } test "isPositiveInf" { fmath.assert(!isPositiveInf(f32(0.0))); fmath.assert(!isPositiveInf(f32(-0.0))); fmath.assert(!isPositiveInf(f64(0.0))); fmath.assert(!isPositiveInf(f64(-0.0))); fmath.assert(isPositiveInf(fmath.inf(f32))); fmath.assert(!isPositiveInf(-fmath.inf(f32))); fmath.assert(isPositiveInf(fmath.inf(f64))); fmath.assert(!isPositiveInf(-fmath.inf(f64))); } test "isNegativeInf" { fmath.assert(!isNegativeInf(f32(0.0))); fmath.assert(!isNegativeInf(f32(-0.0))); fmath.assert(!isNegativeInf(f64(0.0))); fmath.assert(!isNegativeInf(f64(-0.0))); fmath.assert(!isNegativeInf(fmath.inf(f32))); fmath.assert(isNegativeInf(-fmath.inf(f32))); fmath.assert(!isNegativeInf(fmath.inf(f64))); fmath.assert(isNegativeInf(-fmath.inf(f64))); }
src/isinf.zig
const std = @import("std"); const expect = std.testing.expect; const expectEqual = std.testing.expectEqual; const Tag = std.meta.Tag; const Foo = union { float: f64, int: i32, }; test "basic unions" { var foo = Foo{ .int = 1 }; try expect(foo.int == 1); foo = Foo{ .float = 12.34 }; try expect(foo.float == 12.34); } test "init union with runtime value" { var foo: Foo = undefined; setFloat(&foo, 12.34); try expect(foo.float == 12.34); setInt(&foo, 42); try expect(foo.int == 42); } fn setFloat(foo: *Foo, x: f64) void { foo.* = Foo{ .float = x }; } fn setInt(foo: *Foo, x: i32) void { foo.* = Foo{ .int = x }; } test "comptime union field access" { comptime { var foo = Foo{ .int = 0 }; try expect(foo.int == 0); foo = Foo{ .float = 42.42 }; try expect(foo.float == 42.42); } } const FooExtern = extern union { float: f64, int: i32, }; test "basic extern unions" { var foo = FooExtern{ .int = 1 }; try expect(foo.int == 1); foo.float = 12.34; try expect(foo.float == 12.34); } const ExternPtrOrInt = extern union { ptr: *u8, int: u64, }; test "extern union size" { comptime try expect(@sizeOf(ExternPtrOrInt) == 8); } test "0-sized extern union definition" { const U = extern union { a: void, const f = 1; }; try expect(U.f == 1); } const Value = union(enum) { Int: u64, Array: [9]u8, }; const Agg = struct { val1: Value, val2: Value, }; const v1 = Value{ .Int = 1234 }; const v2 = Value{ .Array = [_]u8{3} ** 9 }; const err = @as(anyerror!Agg, Agg{ .val1 = v1, .val2 = v2, }); const array = [_]Value{ v1, v2, v1, v2 }; test "unions embedded in aggregate types" { switch (array[1]) { Value.Array => |arr| try expect(arr[4] == 3), else => unreachable, } switch ((err catch unreachable).val1) { Value.Int => |x| try expect(x == 1234), else => unreachable, } } test "access a member of tagged union with conflicting enum tag name" { const Bar = union(enum) { A: A, B: B, const A = u8; const B = void; }; comptime try expect(Bar.A == u8); } test "constant tagged union with payload" { var empty = TaggedUnionWithPayload{ .Empty = {} }; var full = TaggedUnionWithPayload{ .Full = 13 }; shouldBeEmpty(empty); shouldBeNotEmpty(full); } fn shouldBeEmpty(x: TaggedUnionWithPayload) void { switch (x) { TaggedUnionWithPayload.Empty => {}, else => unreachable, } } fn shouldBeNotEmpty(x: TaggedUnionWithPayload) void { switch (x) { TaggedUnionWithPayload.Empty => unreachable, else => {}, } } const TaggedUnionWithPayload = union(enum) { Empty: void, Full: i32, }; test "union alignment" { comptime { try expect(@alignOf(AlignTestTaggedUnion) >= @alignOf([9]u8)); try expect(@alignOf(AlignTestTaggedUnion) >= @alignOf(u64)); } } const AlignTestTaggedUnion = union(enum) { A: [9]u8, B: u64, };
test/behavior/union.zig
const std = @import("std"); const math = @import("../pkg/zlm.zig"); const assert = std.debug.assert; // Fair bit of code duplication here for specialized shape algorithms. // Much credit goes to this incredible resource: // http://www.jeffreythompson.org/collision-detection/index.php pub fn isPointInCircle(point: math.Vec2, circlePos: math.Vec2, circleRad: f32) bool { return point.distanceTo(circlePos) <= circleRad; } pub fn isPointInRect(point: math.Vec2, rect: math.Rect) bool { return rect.containsPoint(point); } pub fn isPointInLine(point: math.Vec2, lineStart: math.Vec2, lineEnd: math.Vec2) bool { const dist1 = point.distanceTo(lineStart); const dist2 = point.distanceTo(lineEnd); const len = lineStart.distanceTo(lineEnd); const buffer: f32 = 0.1; return dist1 + dist2 >= len - buffer and dist1 + dist2 <= len + buffer; } pub fn isPointInPoint(point1: math.Vec2, point2: math.Vec2) bool { return point1.distanceTo(point2) < 0.1; } pub fn isPointInPolygon(point: math.Vec2, polyPoint: math.Vec2, vertices: []math.Vec2) bool { var i: usize = 0; var j: usize = vertices.len - 1; var inside = false; while (i < vertices.len) { const polyI = polyPoint.add(vertices[i]); const polyJ = polyPoint.add(vertices[j]); if ((polyI.y > point.y) != (polyJ.y > point.y) and point.x < (polyJ.x - polyI.x) * (point.y - polyI.y) / (polyJ.y - polyI.y) + polyI.x) { inside = !inside; } // Continuation logic j = i; i += 1; } return inside; } pub fn isCircleInPolygon(circlePos: math.Vec2, radius: f32, polygonPos: math.Vec2, vertices: []math.Vec2) bool { for (vertices) |vert, i| { var next = if (i + 1 == vertices.len) polygonPos.add(vertices[0]) else polygonPos.add(vertices[i + 1]); if (isLineInCircle(vert.add(polygonPos), next, circlePos, radius)) return true; } return isPointInPolygon(circlePos, polygonPos, vertices); } pub fn isLineInPolygon(lineStart: math.Vec2, lineEnd: math.Vec2, polygonPos: math.Vec2, vertices: []math.Vec2) bool { for (vertices) |vert, i| { var next = if (i + 1 == vertices.len) polygonPos.add(vertices[0]) else polygonPos.add(vertices[i + 1]); if (isLineInLine(lineStart, lineEnd, vert.add(polygonPos), next)) return true; } return false; } pub fn isPolygonInPolygon(polygonPos: math.Vec2, vertices: []math.Vec2, polygon2Pos: math.Vec2, vertices2: []math.Vec2) bool { for (vertices) |vert, i| { var next = if (i + 1 == vertices.len) polygonPos.add(vertices[0]) else polygonPos.add(vertices[i + 1]); if (isLineInPolygon(vert.add(polygonPos), next, polygon2Pos, vertices2)) return true; } return isPointInPolygon(polygonPos, polygon2Pos, vertices2); } pub fn isRectInPolygon(rectangle: math.Rect, polygonPos: math.Vec2, vertices: []math.Vec2) bool { for (vertices) |vert, i| { var next = if (i + 1 == vertices.len) polygonPos.add(vertices[0]) else polygonPos.add(vertices[i + 1]); if (isLineInRect(vert.add(polygonPos), next, rectangle.position, rectangle.size)) return true; } return isPointInPolygon(rectangle.position, polygonPos, vertices); } pub fn isLineInLine(l1Start: math.Vec2, l1End: math.Vec2, l2Start: math.Vec2, l2End: math.Vec2) bool { var uA: f32 = ((l2End.x - l2Start.x) * (l1Start.y - l2Start.y) - (l2End.y - l2Start.y) * (l1Start.x - l2Start.x)) / ((l2End.y - l2Start.y) * (l1End.x - l1Start.x) - (l2End.x - l2Start.x) * (l1End.y - l1Start.y)); var uB: f32 = ((l1End.x - l1Start.x) * (l1Start.y - l2Start.y) - (l1End.y - l1Start.y) * (l1Start.x - l2Start.x)) / ((l2End.y - l2Start.y) * (l1End.x - l1Start.x) - (l2End.x - l2Start.x) * (l1End.y - l1Start.y)); return (uA >= 0 and uA <= 1 and uB >= 0 and uB <= 1); } pub fn isLineInRect(line1: math.Vec2, line2: math.Vec2, aabbPos: math.Vec2, aabbSize: math.Vec2) bool { const tl = aabbPos; const tr = aabbPos.add(.{ .x = aabbSize.x }); const br = aabbPos.add(aabbSize); const bl = aabbPos.add(.{ .y = aabbSize.y }); return isLineInLine(line1, line2, tl, tr) or isLineInLine(line1, line2, tl, bl) or isLineInLine(line1, line2, bl, br) or isLineInLine(line1, line2, tr, br); } pub fn isRectInRect(rect1Pos: math.Vec2, rect1Size: math.Vec2, rect2Pos: math.Vec2, rect2Size: math.Vec2) bool { return math.Rect.intersectsRect(.{ .position = rect1Pos, .size = rect1Size }, .{ .position = rect2Pos, .size = rect2Size }); } pub fn isCircleInRect(circPos: math.Vec2, radius: f32, rectPos: math.Vec2, rectSize: math.Vec2) bool { var testX = circPos.x; var testY = circPos.y; if (circPos.x < rectPos.x) { testX = rectPos.x; } else if (circPos.x > rectPos.x + rectSize.x) { testX = rectPos.x + rectSize.x; } if (circPos.y < rectPos.y) { testY = rectPos.y; } else if (circPos.y > rectPos.y + rectSize.y) { testY = rectPos.y + rectSize.y; } var distX = circPos.x - testX; var distY = circPos.y - testY; var dist = std.math.sqrt((distX * distX) + (distY * distY)); return dist <= radius; } pub fn isLineInCircle(lineStart: math.Vec2, lineEnd: math.Vec2, circlePos: math.Vec2, radius: f32) bool { // Early out if (isPointInCircle(lineStart, circlePos, radius)) { return true; } if (isPointInCircle(lineEnd, circlePos, radius)) { return true; } const len: f32 = lineStart.distanceTo(lineEnd); const dot = (((circlePos.x - lineStart.x) * (lineEnd.x - lineStart.x)) + ((circlePos.y - lineStart.y) * (lineEnd.y - lineStart.y))) / std.math.pow(f32, len, 2.0); const closestX = lineStart.x + (dot * (lineEnd.x - lineStart.x)); const closestY = lineStart.y + (dot * (lineEnd.y - lineStart.y)); var onSegment = isPointInLine(.{ .x = closestX, .y = closestY }, lineStart, lineEnd); if (!onSegment) return false; var closest = math.vec2(closestX - circlePos.x, closestY - circlePos.y); return closest.length() <= radius; } inline fn pointInCircle(point: Shape, pointPos: math.Vec2, circle: Shape, circlePos: math.Vec2) bool { assert(circle == .Circle); assert(point == .Point); return isPointInCircle(point.Point.add(pointPos), circlePos, circle.Circle.radius); } inline fn pointInPoint( point: Shape, pointPos: math.Vec2, point2: Shape, point2Pos: math.Vec2, ) bool { assert(point2 == .Point); assert(point == .Point); return isPointInPoint(pointPos.add(point.Point), point2Pos.add(point2.Point)); } inline fn pointInLine(point: Shape, pointPos: math.Vec2, line: Shape, linePos: math.Vec2) bool { assert(line == .Line); assert(point == .Point); const start = linePos.add(line.Line.start); const end = linePos.add(line.Line.end); return isPointInLine(pointPos.add(point.Point), start, end); } inline fn lineInLine(line: Shape, linePos: math.Vec2, line2: Shape, line2Pos: math.Vec2) bool { assert(line == .Line); assert(line2 == .Line); const start = linePos.add(line.Line.start); const end = linePos.add(line.Line.end); const start2 = line2Pos.add(line2.Line.start); const end2 = line2Pos.add(line2.Line.end); return isLineInLine(start, end, start2, end2); } inline fn lineInPolygon(line: Shape, linePos: math.Vec2, poly: Shape, polyPos: math.Vec2) bool { assert(line == .Line); assert(poly == .Polygon); const start = linePos.add(line.Line.start); const end = linePos.add(line.Line.end); return isLineInPolygon(start, end, polyPos, poly.Polygon.vertices); } inline fn pointInRect(point: Shape, pointPos: math.Vec2, rectangle: Shape, rectanglePos: math.Vec2) bool { assert(rectangle == .Rectangle); assert(point == .Point); const ppos: math.Vec2 = point.Point.add(pointPos); const rect: math.Rect = .{ .position = rectangle.Rectangle.position.add(rectanglePos), .size = rectangle.Rectangle.size, }; return isPointInRect(ppos, rect); } inline fn lineInRect(line: Shape, linePos: math.Vec2, rectangle: Shape, rectanglePos: math.Vec2) bool { assert(rectangle == .Rectangle); assert(line == .Line); const lineStart: math.Vec2 = linePos.add(line.Line.start); const lineEnd: math.Vec2 = linePos.add(line.Line.end); const rect: math.Rect = .{ .position = rectangle.Rectangle.position.add(rectanglePos), .size = rectangle.Rectangle.size, }; return isLineInRect(lineStart, lineEnd, rect.position, rect.size); } inline fn pointInPolygon(point: Shape, pointPos: math.Vec2, poly: Shape, polyPos: math.Vec2) bool { assert(poly == .Polygon); assert(point == .Point); return isPointInPolygon(pointPos.add(point.Point), polyPos, poly.Polygon.vertices); } inline fn circleInCircle(circle1: Shape, circle1Pos: math.Vec2, circle2: Shape, circle2Pos: math.Vec2) bool { assert(circle1 == .Circle); assert(circle2 == .Circle); return circle1Pos.distanceTo(circle2Pos) - circle1.Circle.radius <= circle2.Circle.radius; } inline fn circleInRect(circle: Shape, circlePos: math.Vec2, rectangle: Shape, rectanglePos: math.Vec2) bool { assert(circle == .Circle); assert(rectangle == .Rectangle); var rect = rectangle.Rectangle; rect.position = rect.position.add(rectanglePos); return isCircleInRect(circlePos, circle.Circle.radius, rect.position, rect.size); } inline fn circleInLine(circle: Shape, circlePos: math.Vec2, line: Shape, linePos: math.Vec2) bool { assert(circle == .Circle); // here assert(line == .Line); const lineStart: math.Vec2 = linePos.add(line.Line.start); const lineEnd: math.Vec2 = linePos.add(line.Line.end); return isLineInCircle(lineStart, lineEnd, circlePos, circle.Circle.radius); } inline fn circleInPoly(circle: Shape, circlePos: math.Vec2, poly: Shape, polyPos: math.Vec2) bool { assert(circle == .Circle); assert(poly == .Polygon); return isCircleInPolygon(circlePos, circle.Circle.radius, polyPos, poly.Polygon.vertices); } inline fn rectInRect(rect1: Shape, rect1Pos: math.Vec2, rect2: Shape, rect2Pos: math.Vec2) bool { assert(rect1 == .Rectangle); assert(rect2 == .Rectangle); return isRectInRect(rect1.Rectangle.position.add(rect1Pos), rect1.Rectangle.size, rect2.Rectangle.position.add(rect2Pos), rect2.Rectangle.size); } inline fn rectInPoly(rectangle: Shape, rectanglePos: math.Vec2, poly: Shape, polyPos: math.Vec2) bool { assert(rectangle == .Rectangle); assert(poly == .Polygon); var rect = rectangle.Rectangle; rect.position = rect.position.add(rectanglePos); return isRectInPolygon(rect, polyPos, poly.Polygon.vertices); } inline fn polyInPoly(poly: Shape, polyPos: math.Vec2, poly2: Shape, poly2Pos: math.Vec2) bool { assert(poly2 == .Polygon); assert(poly == .Polygon); return isPolygonInPolygon(polyPos, poly.Polygon.vertices, poly2Pos, poly2.Polygon.vertices); } /// Simple container of many shape types. By using a shape in your code you can test overlaps against any other shape. /// For simplicity sake, Rectangle is AABB, meaning it cannot be represented as rotated. For that you'll want to make your /// own polygon, which works with any other shape. /// Note that none of the shapes retain a position field, as position is supplied during the check functions to make this /// interface a little more versatile. As such, a Point's position and a Rectangle's position both refer to an offset from /// the position yet supplied. Polygon's vertices are as offsets from the position supplied. pub const Shape = union(enum) { Circle: Circle, Rectangle: Rectangle, Point: Point, Polygon: Polygon, Line: Line, pub const Circle = struct { radius: f32 }; pub const Rectangle = math.Rect; pub const Point = math.Vec2; pub const Polygon = struct { vertices: []math.Vec2 }; pub const Line = struct { start: math.Vec2, end: math.Vec2, }; pub fn circle(radius: f32) Shape { return .{ .Circle = .{ .radius = radius } }; } pub fn line(from: math.Vec2, to: math.Vec2) Shape { return .{ .Line = .{ .start = from, .end = to } }; } pub fn point(pos: math.Vec2) Shape { return .{ .Point = pos }; } pub fn rectangle(pos: math.Vec2, size: math.Vec2) Shape { return .{ .Rectangle = math.rect(pos.x, pos.y, size.x, size.y) }; } pub fn overlaps(self: Shape, selfPos: math.Vec2, other: Shape, otherPos: math.Vec2) bool { switch (self) { .Point => { switch (other) { .Circle => { return pointInCircle(self, selfPos, other, otherPos); }, .Rectangle => { return pointInRect(self, selfPos, other, otherPos); }, .Polygon => { return pointInPolygon(self, selfPos, other, otherPos); }, .Line => { return pointInLine(self, selfPos, other, otherPos); }, .Point => { return pointInPoint(self, selfPos, other, otherPos); }, } }, .Circle => { switch (other) { .Circle => { return circleInCircle(self, selfPos, other, otherPos); }, .Point => { return pointInCircle(other, otherPos, self, selfPos); }, .Rectangle => { return circleInRect(self, selfPos, other, otherPos); }, .Line => { return circleInLine(self, selfPos, other, otherPos); }, .Polygon => { return circleInPoly(self, selfPos, other, otherPos); }, } }, .Rectangle => { switch (other) { .Circle => { return circleInRect(other, otherPos, self, selfPos); }, .Point => { return pointInRect(other, otherPos, self, selfPos); }, .Rectangle => { return rectInRect(self, selfPos, other, otherPos); }, .Line => { return lineInRect(other, otherPos, self, selfPos); }, .Polygon => { return rectInPoly(self, selfPos, other, otherPos); }, } }, .Line => { switch (other) { .Circle => { return circleInLine(other, otherPos, self, selfPos); }, .Point => { return pointInLine(other, otherPos, self, selfPos); }, .Rectangle => { return lineInRect(self, selfPos, other, otherPos); }, .Line => { return lineInLine(self, selfPos, other, otherPos); }, .Polygon => { return lineInPolygon(self, selfPos, other, otherPos); }, } }, .Polygon => { switch (other) { .Circle => { return circleInPoly(other, otherPos, self, selfPos); }, .Point => { return pointInPolygon(other, otherPos, self, selfPos); }, .Rectangle => { return rectInPoly(other, otherPos, self, selfPos); }, .Line => { return lineInPolygon(other, otherPos, self, selfPos); }, .Polygon => { return polyInPoly(other, otherPos, self, selfPos); }, } }, } } }; test "Overlap methods" { var offsetPoint = Shape.point(.{ .x = -20 }); var testPoint = Shape.point(.{}); var testCircle = Shape.circle(10); var testRectangle = Shape.rectangle(.{}, .{ .x = 10, .y = 10 }); var offsetRectangle = Shape.rectangle(.{ .x = 20 }, .{ .x = 10, .y = 10 }); // Point -> Circle assert(isPointInCircle(.{}, .{}, 3)); assert(Shape.overlaps(testPoint, .{}, testCircle, .{})); assert(Shape.overlaps(testCircle, .{}, testPoint, .{})); assert(!Shape.overlaps(offsetPoint, .{}, testCircle, .{})); assert(!Shape.overlaps(testPoint, .{ .x = 15 }, testCircle, .{})); assert(!Shape.overlaps(testCircle, .{}, testPoint, .{ .x = 15 })); // Point -> Rectangle assert(isPointInRect(.{}, .{ .size = .{ .x = 10, .y = 10 } })); assert(Shape.overlaps(testPoint, .{}, testRectangle, .{})); assert(Shape.overlaps(testPoint, .{ .x = 25 }, offsetRectangle, .{})); assert(!Shape.overlaps(offsetPoint, .{}, testRectangle, .{})); assert(!Shape.overlaps(testPoint, .{}, offsetRectangle, .{})); // Point -> Poly var polygons: []math.Vec2 = &.{ math.vec2(-10, 0), math.vec2(0, -10), math.vec2(10, 0), math.vec2(0, 10), }; var testPoly = Shape{ .Polygon = .{ .vertices = polygons } }; assert(isPointInPolygon(.{}, .{}, polygons)); assert(!isPointInPolygon(math.vec2(-8, -8), .{}, polygons)); assert(Shape.overlaps(testPoint, .{}, testPoly, .{})); assert(!Shape.overlaps(testPoint, .{ .x = -8, .y = -8 }, testPoly, .{})); // Circle -> Circle assert(Shape.overlaps(testCircle, .{}, testCircle, .{})); assert(!Shape.overlaps(testCircle, .{ .x = 21 }, testCircle, .{})); // Circle -> Rectangle assert(Shape.overlaps(testRectangle, .{}, testCircle, .{})); assert(!Shape.overlaps(testRectangle, .{}, testCircle, .{ .x = -11 })); }
src/zt/physics.zig
const std = @import("std"); const expect = std.testing.expect; const expectEqual = std.testing.expectEqual; const builtin = @import("builtin"); test "atomic store" { var x: u32 = 0; @atomicStore(u32, &x, 1, .SeqCst); try expect(@atomicLoad(u32, &x, .SeqCst) == 1); @atomicStore(u32, &x, 12345678, .SeqCst); try expect(@atomicLoad(u32, &x, .SeqCst) == 12345678); } test "atomic store comptime" { comptime try testAtomicStore(); try testAtomicStore(); } fn testAtomicStore() !void { var x: u32 = 0; @atomicStore(u32, &x, 1, .SeqCst); try expect(@atomicLoad(u32, &x, .SeqCst) == 1); @atomicStore(u32, &x, 12345678, .SeqCst); try expect(@atomicLoad(u32, &x, .SeqCst) == 12345678); } test "atomicrmw with floats" { try testAtomicRmwFloat(); comptime try testAtomicRmwFloat(); } fn testAtomicRmwFloat() !void { var x: f32 = 0; try expect(x == 0); _ = @atomicRmw(f32, &x, .Xchg, 1, .SeqCst); try expect(x == 1); _ = @atomicRmw(f32, &x, .Add, 5, .SeqCst); try expect(x == 6); _ = @atomicRmw(f32, &x, .Sub, 2, .SeqCst); try expect(x == 4); } test "atomicrmw with ints" { try testAtomicRmwInt(); comptime try testAtomicRmwInt(); } fn testAtomicRmwInt() !void { var x: u8 = 1; var res = @atomicRmw(u8, &x, .Xchg, 3, .SeqCst); try expect(x == 3 and res == 1); _ = @atomicRmw(u8, &x, .Add, 3, .SeqCst); try expect(x == 6); _ = @atomicRmw(u8, &x, .Sub, 1, .SeqCst); try expect(x == 5); _ = @atomicRmw(u8, &x, .And, 4, .SeqCst); try expect(x == 4); _ = @atomicRmw(u8, &x, .Nand, 4, .SeqCst); try expect(x == 0xfb); _ = @atomicRmw(u8, &x, .Or, 6, .SeqCst); try expect(x == 0xff); _ = @atomicRmw(u8, &x, .Xor, 2, .SeqCst); try expect(x == 0xfd); _ = @atomicRmw(u8, &x, .Max, 1, .SeqCst); try expect(x == 0xfd); _ = @atomicRmw(u8, &x, .Min, 1, .SeqCst); try expect(x == 1); } test "atomics with different types" { try testAtomicsWithType(bool, true, false); inline for (.{ u1, i4, u5, i15, u24 }) |T| { try testAtomicsWithType(T, 0, 1); } try testAtomicsWithType(u0, 0, 0); try testAtomicsWithType(i0, 0, 0); } fn testAtomicsWithType(comptime T: type, a: T, b: T) !void { var x: T = b; @atomicStore(T, &x, a, .SeqCst); try expect(x == a); try expect(@atomicLoad(T, &x, .SeqCst) == a); try expect(@atomicRmw(T, &x, .Xchg, b, .SeqCst) == a); try expect(@cmpxchgStrong(T, &x, b, a, .SeqCst, .SeqCst) == null); if (@sizeOf(T) != 0) try expect(@cmpxchgStrong(T, &x, b, a, .SeqCst, .SeqCst).? == a); }
test/behavior/atomics_stage1.zig
const std = @import("std"); const mem = std.mem; const builtin = @import("builtin"); const expect = std.testing.expect; test "vector wrap operators" { const S = struct { fn doTheTest() void { var v: @Vector(4, i32) = [4]i32{ 2147483647, -2, 30, 40 }; var x: @Vector(4, i32) = [4]i32{ 1, 2147483647, 3, 4 }; expect(mem.eql(i32, ([4]i32)(v +% x), [4]i32{ -2147483648, 2147483645, 33, 44 })); expect(mem.eql(i32, ([4]i32)(v -% x), [4]i32{ 2147483646, 2147483647, 27, 36 })); expect(mem.eql(i32, ([4]i32)(v *% x), [4]i32{ 2147483647, 2, 90, 160 })); var z: @Vector(4, i32) = [4]i32{ 1, 2, 3, -2147483648 }; expect(mem.eql(i32, ([4]i32)(-%z), [4]i32{ -1, -2, -3, -2147483648 })); } }; S.doTheTest(); comptime S.doTheTest(); } test "vector int operators" { const S = struct { fn doTheTest() void { var v: @Vector(4, i32) = [4]i32{ 10, 20, 30, 40 }; var x: @Vector(4, i32) = [4]i32{ 1, 2, 3, 4 }; expect(mem.eql(i32, ([4]i32)(v + x), [4]i32{ 11, 22, 33, 44 })); expect(mem.eql(i32, ([4]i32)(v - x), [4]i32{ 9, 18, 27, 36 })); expect(mem.eql(i32, ([4]i32)(v * x), [4]i32{ 10, 40, 90, 160 })); expect(mem.eql(i32, ([4]i32)(-v), [4]i32{ -10, -20, -30, -40 })); } }; S.doTheTest(); comptime S.doTheTest(); } test "vector float operators" { const S = struct { fn doTheTest() void { var v: @Vector(4, f32) = [4]f32{ 10, 20, 30, 40 }; var x: @Vector(4, f32) = [4]f32{ 1, 2, 3, 4 }; expect(mem.eql(f32, ([4]f32)(v + x), [4]f32{ 11, 22, 33, 44 })); expect(mem.eql(f32, ([4]f32)(v - x), [4]f32{ 9, 18, 27, 36 })); expect(mem.eql(f32, ([4]f32)(v * x), [4]f32{ 10, 40, 90, 160 })); expect(mem.eql(f32, ([4]f32)(-x), [4]f32{ -1, -2, -3, -4 })); } }; S.doTheTest(); comptime S.doTheTest(); } test "vector bit operators" { const S = struct { fn doTheTest() void { var v: @Vector(4, u8) = [4]u8{ 0b10101010, 0b10101010, 0b10101010, 0b10101010 }; var x: @Vector(4, u8) = [4]u8{ 0b11110000, 0b00001111, 0b10101010, 0b01010101 }; expect(mem.eql(u8, ([4]u8)(v ^ x), [4]u8{ 0b01011010, 0b10100101, 0b00000000, 0b11111111 })); expect(mem.eql(u8, ([4]u8)(v | x), [4]u8{ 0b11111010, 0b10101111, 0b10101010, 0b11111111 })); expect(mem.eql(u8, ([4]u8)(v & x), [4]u8{ 0b10100000, 0b00001010, 0b10101010, 0b00000000 })); } }; S.doTheTest(); comptime S.doTheTest(); } test "implicit cast vector to array" { const S = struct { fn doTheTest() void { var a: @Vector(4, i32) = [_]i32{ 1, 2, 3, 4 }; var result_array: [4]i32 = a; result_array = a; expect(mem.eql(i32, result_array, [4]i32{ 1, 2, 3, 4 })); } }; S.doTheTest(); comptime S.doTheTest(); } test "array to vector" { var foo: f32 = 3.14; var arr = [4]f32{ foo, 1.5, 0.0, 0.0 }; var vec: @Vector(4, f32) = arr; } test "vector upcast" { const S = struct { fn doTheTest() void { { const v: @Vector(4, i16) = [4]i16{ 21, -2, 30, 40}; const x: @Vector(4, i32) = @Vector(4, i32)(v); expect(x[0] == 21); expect(x[1] == -2); expect(x[2] == 30); expect(x[3] == 40); } { const v: @Vector(4, u16) = [4]u16{ 21, 2, 30, 40}; const x: @Vector(4, u32) = @Vector(4, u32)(v); expect(x[0] == 21); expect(x[1] == 2); expect(x[2] == 30); expect(x[3] == 40); } { const v: @Vector(4, f16) = [4]f16{ 21, -2, 30, 40}; const x: @Vector(4, f32) = @Vector(4, f32)(v); expect(x[0] == 21); expect(x[1] == -2); expect(x[2] == 30); expect(x[3] == 40); } } }; S.doTheTest(); comptime S.doTheTest(); } test "vector truncate" { const S = struct { fn doTheTest() void { const v: @Vector(4, i32) = [4]i32{ 21, -2, 30, 40}; const x: @Vector(4, i16) = @truncate(@Vector(4, i16), v); expect(x[0] == 21); expect(x[1] == -2); expect(x[2] == 30); expect(x[3] == 40); } }; S.doTheTest(); comptime S.doTheTest(); } test "vector casts of sizes not divisable by 8" { const S = struct { fn doTheTest() void { { var v: @Vector(4, u3) = [4]u3{ 5, 2, 3, 0}; var x: [4]u3 = v; expect(mem.eql(u3, x, ([4]u3)(v))); } { var v: @Vector(4, u2) = [4]u2{ 1, 2, 3, 0}; var x: [4]u2 = v; expect(mem.eql(u2, x, ([4]u2)(v))); } { var v: @Vector(4, u1) = [4]u1{ 1, 0, 1, 0}; var x: [4]u1 = v; expect(mem.eql(u1, x, ([4]u1)(v))); } { var v: @Vector(4, bool) = [4]bool{ false, false, true, false}; var x: [4]bool = v; expect(mem.eql(bool, x, ([4]bool)(v))); } } }; S.doTheTest(); comptime S.doTheTest(); } test "implicit cast vector to array - bool" { const S = struct { fn doTheTest() void { const a: @Vector(4, bool) = [_]bool{ true, false, true, false }; const result_array: [4]bool = a; expect(mem.eql(bool, result_array, [4]bool{ true, false, true, false })); } }; S.doTheTest(); comptime S.doTheTest(); } test "vector bin compares with mem.eql" { const S = struct { fn doTheTest() void { var v: @Vector(4, i32) = [4]i32{ 2147483647, -2, 30, 40 }; var x: @Vector(4, i32) = [4]i32{ 1, 2147483647, 30, 4 }; expect(mem.eql(bool, ([4]bool)(v == x), [4]bool{ false, false, true, false})); expect(mem.eql(bool, ([4]bool)(v != x), [4]bool{ true, true, false, true})); expect(mem.eql(bool, ([4]bool)(v < x), [4]bool{ false, true, false, false})); expect(mem.eql(bool, ([4]bool)(v > x), [4]bool{ true, false, false, true})); expect(mem.eql(bool, ([4]bool)(v <= x), [4]bool{ false, true, true, false})); expect(mem.eql(bool, ([4]bool)(v >= x), [4]bool{ true, false, true, true})); } }; S.doTheTest(); comptime S.doTheTest(); } test "vector member field access" { const S = struct { fn doTheTest() void { const q: @Vector(4, u32) = undefined; expect(q.len == 4); const v = @Vector(4, i32); expect(v.len == 4); expect(v.bit_count == 32); expect(v.is_signed == true); const k = @Vector(2, bool); expect(k.len == 2); const x = @Vector(3, f32); expect(x.len == 3); expect(x.bit_count == 32); const z = @Vector(3, *align(4) u32); expect(z.len == 3); expect(z.Child == u32); // FIXME is this confusing? However vector alignment requirements are entirely // dependant on their size, and can be gotten with @alignOf(). expect(z.alignment == 4); } }; S.doTheTest(); comptime S.doTheTest(); } test "vector access elements - load" { { var a: @Vector(4, i32) = [_]i32{ 1, 2, 3, undefined }; expect(a[2] == 3); expect(a[1] == i32(2)); expect(3 == a[2]); } comptime { comptime var a: @Vector(4, i32) = [_]i32{ 1, 2, 3, undefined }; expect(a[0] == 1); expect(a[1] == i32(2)); expect(3 == a[2]); } } test "vector access elements - store" { { var a: @Vector(4, i32) = [_]i32{ 1, 5, 3, undefined }; a[2] = 1; expect(a[1] == 5); expect(a[2] == i32(1)); a[3] = -364; expect(-364 == a[3]); } comptime { comptime var a: @Vector(4, i32) = [_]i32{ 1, 2, 3, undefined }; a[2] = 5; expect(a[2] == i32(5)); a[3] = -364; expect(-364 == a[3]); } } test "vector @splat" { const S = struct { fn doTheTest() void { var v: u32 = 5; var x = @splat(4, v); expect(@typeOf(x) == @Vector(4, u32)); expect(x[0] == 5); expect(x[1] == 5); expect(x[2] == 5); expect(x[3] == 5); } }; S.doTheTest(); comptime S.doTheTest(); } test "vector @bitCast" { const S = struct { fn doTheTest() void { { const math = @import("std").math; const v: @Vector(4, u32) = [4]u32{ 0x7F800000, 0x7F800001, 0xFF800000, 0}; const x: @Vector(4, f32) = @bitCast(@Vector(4, f32), v); expect(x[0] == math.inf(f32)); expect(x[1] != x[1]); // NaN expect(x[2] == -math.inf(f32)); expect(x[3] == 0); } { const math = @import("std").math; const v: @Vector(2, u64) = [2]u64{ 0x7F8000017F800000, 0xFF800000}; const x: @Vector(4, f32) = @bitCast(@Vector(4, f32), v); expect(x[0] == math.inf(f32)); expect(x[1] != x[1]); // NaN expect(x[2] == -math.inf(f32)); expect(x[3] == 0); } { const v: @Vector(4, u8) = [_]u8{2, 1, 2, 1}; const x: u32 = @bitCast(u32, v); expect(x == 0x01020102); const z: @Vector(4, u8) = @bitCast(@Vector(4, u8), x); expect(z[0] == 2); expect(z[1] == 1); expect(z[2] == 2); expect(z[3] == 1); } { const v: @Vector(4, i8) = [_]i8{2, 1, 0, -128}; const x: u32 = @bitCast(u32, v); expect(x == 0x80000102); } { const v: @Vector(4, u1) = [_]u1{1, 1, 0, 1}; const x: u4 = @bitCast(u4, v); expect(x == 0b1011); } { const v: @Vector(4, u3) = [_]u3{0b100, 0b111, 0, 1}; const x: u12 = @bitCast(u12, v); expect(x == 0b001000111100); const z: @Vector(4, u3) = @bitCast(@Vector(4, u3), x); expect(z[0] == 0b100); expect(z[1] == 0b111); expect(z[2] == 0); expect(z[3] == 1); } { const v: @Vector(2, u9) = [_]u9{2, 1}; const x: u18 = @bitCast(u18, v); expect(x == 0b000000001000000010); const z: @Vector(2, u9) = @bitCast(@Vector(2, u9), x); expect(z[0] == 2); expect(z[1] == 1); } { const v: @Vector(4, bool) = [_]bool{false, true, false, true}; const x: u4 = @bitCast(u4, v); expect(x == 0b1010); const z: @Vector(4, bool) = @bitCast(@Vector(4, bool), x); expect(z[0] == false); expect(z[1] == true); expect(z[2] == false); expect(z[3] == true); } } }; S.doTheTest(); comptime S.doTheTest(); }
test/stage1/behavior/vector.zig
const std = @import("std"); const assert = std.debug.assert; const expect = std.testing.expect; const expectEqual = std.testing.expectEqual; const AutoHashMap = std.AutoHashMap; const Allocator = std.mem.Allocator; const ArrayList = std.ArrayList; const ExecError = error{ InvalidOpcode, InvalidParamMode, }; fn opcode(ins: Instr) Instr { return @rem(ins, 100); } test "opcode extraction" { expectEqual(opcode(1002), 2); } fn paramMode(ins: Instr, pos: Instr) Instr { var div: Instr = 100; // Mode of parameter 0 is in digit 3 var i: Instr = 0; while (i < pos) : (i += 1) { div *= 10; } return @rem(@divTrunc(ins, div), 10); } test "param mode extraction" { expectEqual(paramMode(1002, 0), 0); expectEqual(paramMode(1002, 1), 1); expectEqual(paramMode(1002, 2), 0); } pub const Instr = i64; pub const Intcode = []Instr; pub const Mem = struct { backend: ArrayList(Instr), const Self = @This(); pub fn init(intcode: Intcode, alloc: *Allocator) Self { return Self{ .backend = ArrayList(Instr).fromOwnedSlice(alloc, intcode), }; } pub fn get(self: Self, pos: usize) Instr { return if (pos < self.backend.items.len) self.backend.at(pos) else 0; } pub fn set(self: *Self, pos: usize, val: Instr) !void { if (pos < self.backend.items.len) { self.backend.set(pos, val); } else { const old_len = self.backend.items.len; try self.backend.resize(pos + 1); var i: usize = old_len; while (i < self.backend.items.len) : (i += 1) { self.backend.set(i, 0); } self.backend.set(pos, val); } } }; pub const IntcodeComputer = struct { mem: Mem, pc: usize, relative_base: Instr, state: State, input: ?Instr, output: ?Instr, const Self = @This(); pub const State = enum { Stopped, Running, AwaitingInput, AwaitingOutput, }; pub fn init(intcode: Intcode, alloc: *Allocator) Self { return Self{ .mem = Mem.init(intcode, alloc), .pc = 0, .relative_base = 0, .state = State.Running, .input = null, .output = null, }; } fn getParam(self: Self, n: usize, mode: Instr) !Instr { const val = self.mem.get(self.pc + 1 + n); return switch (mode) { 0 => self.mem.get(@intCast(usize, val)), 1 => val, 2 => self.mem.get(@intCast(usize, self.relative_base + val)), else => return error.InvalidParamMode, }; } fn getPos(self: Self, n: usize, mode: Instr) !usize { const val = self.mem.get(self.pc + 1 + n); return switch (mode) { 0 => @intCast(usize, val), 1 => return error.OutputParameterImmediateMode, 2 => @intCast(usize, self.relative_base + val), else => return error.InvalidParamMode, }; } pub fn exec(self: *Self) !void { const instr = self.mem.get(self.pc); switch (opcode(instr)) { 99 => self.state = State.Stopped, 1 => { const val_x = try self.getParam(0, paramMode(instr, 0)); const val_y = try self.getParam(1, paramMode(instr, 1)); const pos_result = try self.getPos(2, paramMode(instr, 2)); try self.mem.set(pos_result, val_x + val_y); self.pc += 4; }, 2 => { const val_x = try self.getParam(0, paramMode(instr, 0)); const val_y = try self.getParam(1, paramMode(instr, 1)); const pos_result = try self.getPos(2, paramMode(instr, 2)); try self.mem.set(pos_result, val_x * val_y); self.pc += 4; }, 3 => { const pos_x = try self.getPos(0, paramMode(instr, 0)); if (self.input) |val| { try self.mem.set(pos_x, val); self.pc += 2; self.input = null; } else { self.state = State.AwaitingInput; } }, 4 => { const val_x = try self.getParam(0, paramMode(instr, 0)); if (self.output) |_| { self.state = State.AwaitingOutput; } else { self.output = val_x; self.pc += 2; } }, 5 => { const val_x = try self.getParam(0, paramMode(instr, 0)); if (val_x != 0) { const val_y = try self.getParam(1, paramMode(instr, 1)); self.pc = @intCast(usize, val_y); } else { self.pc += 3; } }, 6 => { const val_x = try self.getParam(0, paramMode(instr, 0)); if (val_x == 0) { const val_y = try self.getParam(1, paramMode(instr, 1)); self.pc = @intCast(usize, val_y); } else { self.pc += 3; } }, 7 => { const val_x = try self.getParam(0, paramMode(instr, 0)); const val_y = try self.getParam(1, paramMode(instr, 1)); const pos_result = try self.getPos(2, paramMode(instr, 2)); try self.mem.set(pos_result, if (val_x < val_y) 1 else 0); self.pc += 4; }, 8 => { const val_x = try self.getParam(0, paramMode(instr, 0)); const val_y = try self.getParam(1, paramMode(instr, 1)); const pos_result = try self.getPos(2, paramMode(instr, 2)); try self.mem.set(pos_result, if (val_x == val_y) 1 else 0); self.pc += 4; }, 9 => { const val_x = try self.getParam(0, paramMode(instr, 0)); self.relative_base += val_x; self.pc += 2; }, else => { std.debug.warn("pos: {}, instr: {}\n", .{ self.pc, instr }); return error.InvalidOpcode; }, } } pub fn execUntilHalt(self: *Self) !void { // try to jump-start the computer if it was waiting for I/O if (self.state != State.Stopped) self.state = State.Running; while (self.state == State.Running) try self.exec(); } }; test "test exec 1" { var intcode = [_]Instr{ 1, 0, 0, 0, 99 }; var comp = IntcodeComputer.init(&intcode, std.testing.failing_allocator); try comp.execUntilHalt(); expectEqual(intcode[0], 2); } test "test exec 2" { var intcode = [_]Instr{ 2, 3, 0, 3, 99 }; var comp = IntcodeComputer.init(&intcode, std.testing.failing_allocator); try comp.execUntilHalt(); expectEqual(intcode[3], 6); } test "test exec 3" { var intcode = [_]Instr{ 2, 4, 4, 5, 99, 0 }; var comp = IntcodeComputer.init(&intcode, std.testing.failing_allocator); try comp.execUntilHalt(); expectEqual(intcode[5], 9801); } test "test exec with different param mode" { var intcode = [_]Instr{ 1002, 4, 3, 4, 33 }; var comp = IntcodeComputer.init(&intcode, std.testing.failing_allocator); try comp.execUntilHalt(); expectEqual(intcode[4], 99); } test "test exec with negative integers" { var intcode = [_]Instr{ 1101, 100, -1, 4, 0 }; var comp = IntcodeComputer.init(&intcode, std.testing.failing_allocator); try comp.execUntilHalt(); expectEqual(intcode[4], 99); } test "test equal 1" { var intcode = [_]Instr{ 3, 9, 8, 9, 10, 9, 4, 9, 99, -1, 8 }; var comp = IntcodeComputer.init(&intcode, std.testing.failing_allocator); comp.input = 8; try comp.execUntilHalt(); expectEqual(comp.output.?, 1); } test "test equal 2" { var intcode = [_]Instr{ 3, 9, 8, 9, 10, 9, 4, 9, 99, -1, 8 }; var comp = IntcodeComputer.init(&intcode, std.testing.failing_allocator); comp.input = 13; try comp.execUntilHalt(); expectEqual(comp.output.?, 0); } test "test less than 1" { var intcode = [_]Instr{ 3, 9, 7, 9, 10, 9, 4, 9, 99, -1, 8 }; var comp = IntcodeComputer.init(&intcode, std.testing.failing_allocator); comp.input = 5; try comp.execUntilHalt(); expectEqual(comp.output.?, 1); } test "test less than 2" { var intcode = [_]Instr{ 3, 9, 7, 9, 10, 9, 4, 9, 99, -1, 8 }; var comp = IntcodeComputer.init(&intcode, std.testing.failing_allocator); comp.input = 20; try comp.execUntilHalt(); expectEqual(comp.output.?, 0); } test "test equal immediate" { var intcode = [_]Instr{ 3, 3, 1108, -1, 8, 3, 4, 3, 99 }; var comp = IntcodeComputer.init(&intcode, std.testing.failing_allocator); comp.input = 8; try comp.execUntilHalt(); expectEqual(comp.output.?, 1); } test "test less than immediate" { var intcode = [_]Instr{ 3, 3, 1107, -1, 8, 3, 4, 3, 99 }; var comp = IntcodeComputer.init(&intcode, std.testing.failing_allocator); comp.input = 3; try comp.execUntilHalt(); expectEqual(comp.output.?, 1); } test "quine" { var arena = std.heap.ArenaAllocator.init(std.heap.page_allocator); const allocator = &arena.allocator; defer arena.deinit(); var intcode = [_]Instr{ 109, 1, 204, -1, 1001, 100, 1, 100, 1008, 100, 16, 101, 1006, 101, 0, 99 }; var comp = IntcodeComputer.init(&intcode, allocator); try comp.execUntilHalt(); } test "big number" { var intcode = [_]Instr{ 1102, 34915192, 34915192, 7, 4, 7, 99, 0 }; var comp = IntcodeComputer.init(&intcode, std.testing.failing_allocator); try comp.execUntilHalt(); } test "big number 2" { var intcode = [_]Instr{ 104, 1125899906842624, 99 }; var comp = IntcodeComputer.init(&intcode, std.testing.failing_allocator); try comp.execUntilHalt(); expectEqual(comp.output.?, 1125899906842624); } pub fn main() !void { var arena = std.heap.ArenaAllocator.init(std.heap.page_allocator); const allocator = &arena.allocator; defer arena.deinit(); const input_file = try std.fs.cwd().openFile("input19.txt", .{}); var input_stream = input_file.reader(); var buf: [1024]u8 = undefined; var ints = std.ArrayList(Instr).init(allocator); // read amp intcode into an int arraylist while (try input_stream.readUntilDelimiterOrEof(&buf, ',')) |item| { // add an empty element to the input file because I don't want to modify // this to discard newlines try ints.append(std.fmt.parseInt(Instr, item, 10) catch 0); } var points_affected: usize = 0; // scan area var y: Instr = 0; while (y < 50) : (y += 1) { var x: Instr = 0; while (x < 50) : (x += 1) { var ints_cpy = try std.mem.dupe(allocator, Instr, ints.items); defer allocator.free(ints_cpy); var comp = IntcodeComputer.init(ints_cpy, allocator); try comp.execUntilHalt(); comp.input = x; try comp.execUntilHalt(); comp.input = y; try comp.execUntilHalt(); const res = comp.output orelse return error.NoOutput; comp.output = null; if (res == 1) points_affected += 1; if (res == 1) { std.debug.warn("#", .{}); } else { if (x == 40) { std.debug.warn(":", .{}); } else if (y == 39) { std.debug.warn("-", .{}); } else { std.debug.warn(".", .{}); } } } std.debug.warn("\n", .{}); } std.debug.warn("points affected: {}\n", .{points_affected}); }
zig/19.zig
const std = @import("std"); const Fundude = @import("../main.zig"); const Op = @import("Op.zig"); test "DAA add" { const DAA = [3]u8{ 0x27, 0, 0 }; const OP_ADD_A = 0xC6; var cpu: Fundude.Cpu = undefined; var mmu: Fundude.Mmu = undefined; { cpu.reg._8.set(.A, 0x0); _ = cpu.opExecute(&mmu, .{ OP_ADD_A, 0x5, 0 }); std.testing.expectEqual(@as(u8, 0x5), cpu.reg._8.get(.A)); _ = cpu.opExecute(&mmu, DAA); std.testing.expectEqual(@as(u8, 0x5), cpu.reg._8.get(.A)); } { _ = cpu.opExecute(&mmu, .{ OP_ADD_A, 0x9, 0 }); std.testing.expectEqual(@as(u8, 0xE), cpu.reg._8.get(.A)); _ = cpu.opExecute(&mmu, DAA); std.testing.expectEqual(@as(u8, 0x14), cpu.reg._8.get(.A)); std.testing.expectEqual(@as(u1, 0), cpu.reg.flags.C); } { _ = cpu.opExecute(&mmu, .{ OP_ADD_A, 0x91, 0 }); std.testing.expectEqual(@as(u8, 0xA5), cpu.reg._8.get(.A)); std.testing.expectEqual(@as(u1, 0), cpu.reg.flags.C); _ = cpu.opExecute(&mmu, DAA); std.testing.expectEqual(@as(u8, 0x05), cpu.reg._8.get(.A)); std.testing.expectEqual(@as(u1, 1), cpu.reg.flags.C); } } test "DAA sub" { const DAA = [3]u8{ 0x27, 0, 0 }; const OP_SUB_A = 0xD6; var cpu: Fundude.Cpu = undefined; var mmu: Fundude.Mmu = undefined; { cpu.reg._8.set(.A, 0x45); _ = cpu.opExecute(&mmu, .{ OP_SUB_A, 0x2, 0 }); std.testing.expectEqual(@as(u8, 0x43), cpu.reg._8.get(.A)); _ = cpu.opExecute(&mmu, DAA); std.testing.expectEqual(@as(u8, 0x43), cpu.reg._8.get(.A)); } { _ = cpu.opExecute(&mmu, .{ OP_SUB_A, 0x5, 0 }); std.testing.expectEqual(@as(u8, 0x3E), cpu.reg._8.get(.A)); _ = cpu.opExecute(&mmu, DAA); std.testing.expectEqual(@as(u8, 0x38), cpu.reg._8.get(.A)); std.testing.expectEqual(@as(u1, 0), cpu.reg.flags.C); } { _ = cpu.opExecute(&mmu, .{ OP_SUB_A, 0x91, 0 }); std.testing.expectEqual(@as(u8, 0xA7), cpu.reg._8.get(.A)); std.testing.expectEqual(@as(u1, 1), cpu.reg.flags.C); _ = cpu.opExecute(&mmu, DAA); std.testing.expectEqual(@as(u8, 0x47), cpu.reg._8.get(.A)); std.testing.expectEqual(@as(u1, 1), cpu.reg.flags.C); } } fn testDaa( before_a: u8, before_flags: Fundude.Cpu.Flags, after_a: u8, after_flags: Fundude.Cpu.Flags, ) !void { var cpu: Fundude.Cpu = undefined; var mmu: Fundude.Mmu = undefined; const DAA = [3]u8{ 0x27, 0, 0 }; cpu.reg._8.set(.A, before_a); cpu.reg.flags = before_flags; _ = cpu.opExecute(&mmu, DAA); std.testing.expectEqual(after_a, cpu.reg._8.get(.A)); std.testing.expectEqual(after_flags.Z, cpu.reg.flags.Z); std.testing.expectEqual(after_flags.N, cpu.reg.flags.N); std.testing.expectEqual(after_flags.H, cpu.reg.flags.H); std.testing.expectEqual(after_flags.C, cpu.reg.flags.C); } fn f(raw: u4) Fundude.Cpu.Flags { return .{ .Z = (raw >> 3) & 1 == 1, .N = (raw >> 2) & 1 == 1, .H = @truncate(u1, raw >> 1), .C = @truncate(u1, raw >> 0), }; } test "gekkio" { try testDaa(0x00, f(0b0000), 0x00, f(0b1000)); try testDaa(0x00, f(0b0001), 0x60, f(0b0001)); try testDaa(0x00, f(0b0010), 0x06, f(0b0000)); try testDaa(0x00, f(0b0011), 0x66, f(0b0001)); try testDaa(0x00, f(0b0100), 0x00, f(0b1100)); try testDaa(0x00, f(0b0101), 0xa0, f(0b0101)); try testDaa(0x00, f(0b0110), 0xfa, f(0b0100)); try testDaa(0x00, f(0b0111), 0x9a, f(0b0101)); try testDaa(0x00, f(0b1000), 0x00, f(0b1000)); try testDaa(0x00, f(0b1001), 0x60, f(0b0001)); try testDaa(0x00, f(0b1010), 0x06, f(0b0000)); try testDaa(0x00, f(0b1011), 0x66, f(0b0001)); try testDaa(0x00, f(0b1100), 0x00, f(0b1100)); try testDaa(0x00, f(0b1101), 0xa0, f(0b0101)); try testDaa(0x00, f(0b1110), 0xfa, f(0b0100)); try testDaa(0x00, f(0b1111), 0x9a, f(0b0101)); try testDaa(0x01, f(0b0000), 0x01, f(0b0000)); try testDaa(0x01, f(0b0001), 0x61, f(0b0001)); try testDaa(0x01, f(0b0010), 0x07, f(0b0000)); try testDaa(0x01, f(0b0011), 0x67, f(0b0001)); try testDaa(0x01, f(0b0100), 0x01, f(0b0100)); try testDaa(0x01, f(0b0101), 0xa1, f(0b0101)); try testDaa(0x01, f(0b0110), 0xfb, f(0b0100)); try testDaa(0x01, f(0b0111), 0x9b, f(0b0101)); try testDaa(0x01, f(0b1000), 0x01, f(0b0000)); try testDaa(0x01, f(0b1001), 0x61, f(0b0001)); try testDaa(0x01, f(0b1010), 0x07, f(0b0000)); try testDaa(0x01, f(0b1011), 0x67, f(0b0001)); try testDaa(0x01, f(0b1100), 0x01, f(0b0100)); try testDaa(0x01, f(0b1101), 0xa1, f(0b0101)); try testDaa(0x01, f(0b1110), 0xfb, f(0b0100)); try testDaa(0x01, f(0b1111), 0x9b, f(0b0101)); try testDaa(0x02, f(0b0000), 0x02, f(0b0000)); try testDaa(0x02, f(0b0001), 0x62, f(0b0001)); try testDaa(0x02, f(0b0010), 0x08, f(0b0000)); try testDaa(0x02, f(0b0011), 0x68, f(0b0001)); try testDaa(0x02, f(0b0100), 0x02, f(0b0100)); try testDaa(0x02, f(0b0101), 0xa2, f(0b0101)); try testDaa(0x02, f(0b0110), 0xfc, f(0b0100)); try testDaa(0x02, f(0b0111), 0x9c, f(0b0101)); try testDaa(0x02, f(0b1000), 0x02, f(0b0000)); try testDaa(0x02, f(0b1001), 0x62, f(0b0001)); try testDaa(0x02, f(0b1010), 0x08, f(0b0000)); try testDaa(0x02, f(0b1011), 0x68, f(0b0001)); try testDaa(0x02, f(0b1100), 0x02, f(0b0100)); try testDaa(0x02, f(0b1101), 0xa2, f(0b0101)); try testDaa(0x02, f(0b1110), 0xfc, f(0b0100)); try testDaa(0x02, f(0b1111), 0x9c, f(0b0101)); try testDaa(0x03, f(0b0000), 0x03, f(0b0000)); try testDaa(0x03, f(0b0001), 0x63, f(0b0001)); try testDaa(0x03, f(0b0010), 0x09, f(0b0000)); try testDaa(0x03, f(0b0011), 0x69, f(0b0001)); try testDaa(0x03, f(0b0100), 0x03, f(0b0100)); try testDaa(0x03, f(0b0101), 0xa3, f(0b0101)); try testDaa(0x03, f(0b0110), 0xfd, f(0b0100)); try testDaa(0x03, f(0b0111), 0x9d, f(0b0101)); try testDaa(0x03, f(0b1000), 0x03, f(0b0000)); try testDaa(0x03, f(0b1001), 0x63, f(0b0001)); try testDaa(0x03, f(0b1010), 0x09, f(0b0000)); try testDaa(0x03, f(0b1011), 0x69, f(0b0001)); try testDaa(0x03, f(0b1100), 0x03, f(0b0100)); try testDaa(0x03, f(0b1101), 0xa3, f(0b0101)); try testDaa(0x03, f(0b1110), 0xfd, f(0b0100)); try testDaa(0x03, f(0b1111), 0x9d, f(0b0101)); try testDaa(0x04, f(0b0000), 0x04, f(0b0000)); try testDaa(0x04, f(0b0001), 0x64, f(0b0001)); try testDaa(0x04, f(0b0010), 0x0a, f(0b0000)); try testDaa(0x04, f(0b0011), 0x6a, f(0b0001)); try testDaa(0x04, f(0b0100), 0x04, f(0b0100)); try testDaa(0x04, f(0b0101), 0xa4, f(0b0101)); try testDaa(0x04, f(0b0110), 0xfe, f(0b0100)); try testDaa(0x04, f(0b0111), 0x9e, f(0b0101)); try testDaa(0x04, f(0b1000), 0x04, f(0b0000)); try testDaa(0x04, f(0b1001), 0x64, f(0b0001)); try testDaa(0x04, f(0b1010), 0x0a, f(0b0000)); try testDaa(0x04, f(0b1011), 0x6a, f(0b0001)); try testDaa(0x04, f(0b1100), 0x04, f(0b0100)); try testDaa(0x04, f(0b1101), 0xa4, f(0b0101)); try testDaa(0x04, f(0b1110), 0xfe, f(0b0100)); try testDaa(0x04, f(0b1111), 0x9e, f(0b0101)); try testDaa(0x05, f(0b0000), 0x05, f(0b0000)); try testDaa(0x05, f(0b0001), 0x65, f(0b0001)); try testDaa(0x05, f(0b0010), 0x0b, f(0b0000)); try testDaa(0x05, f(0b0011), 0x6b, f(0b0001)); try testDaa(0x05, f(0b0100), 0x05, f(0b0100)); try testDaa(0x05, f(0b0101), 0xa5, f(0b0101)); try testDaa(0x05, f(0b0110), 0xff, f(0b0100)); try testDaa(0x05, f(0b0111), 0x9f, f(0b0101)); try testDaa(0x05, f(0b1000), 0x05, f(0b0000)); try testDaa(0x05, f(0b1001), 0x65, f(0b0001)); try testDaa(0x05, f(0b1010), 0x0b, f(0b0000)); try testDaa(0x05, f(0b1011), 0x6b, f(0b0001)); try testDaa(0x05, f(0b1100), 0x05, f(0b0100)); try testDaa(0x05, f(0b1101), 0xa5, f(0b0101)); try testDaa(0x05, f(0b1110), 0xff, f(0b0100)); try testDaa(0x05, f(0b1111), 0x9f, f(0b0101)); try testDaa(0x06, f(0b0000), 0x06, f(0b0000)); try testDaa(0x06, f(0b0001), 0x66, f(0b0001)); try testDaa(0x06, f(0b0010), 0x0c, f(0b0000)); try testDaa(0x06, f(0b0011), 0x6c, f(0b0001)); try testDaa(0x06, f(0b0100), 0x06, f(0b0100)); try testDaa(0x06, f(0b0101), 0xa6, f(0b0101)); try testDaa(0x06, f(0b0110), 0x00, f(0b1100)); try testDaa(0x06, f(0b0111), 0xa0, f(0b0101)); try testDaa(0x06, f(0b1000), 0x06, f(0b0000)); try testDaa(0x06, f(0b1001), 0x66, f(0b0001)); try testDaa(0x06, f(0b1010), 0x0c, f(0b0000)); try testDaa(0x06, f(0b1011), 0x6c, f(0b0001)); try testDaa(0x06, f(0b1100), 0x06, f(0b0100)); try testDaa(0x06, f(0b1101), 0xa6, f(0b0101)); try testDaa(0x06, f(0b1110), 0x00, f(0b1100)); try testDaa(0x06, f(0b1111), 0xa0, f(0b0101)); try testDaa(0x07, f(0b0000), 0x07, f(0b0000)); try testDaa(0x07, f(0b0001), 0x67, f(0b0001)); try testDaa(0x07, f(0b0010), 0x0d, f(0b0000)); try testDaa(0x07, f(0b0011), 0x6d, f(0b0001)); try testDaa(0x07, f(0b0100), 0x07, f(0b0100)); try testDaa(0x07, f(0b0101), 0xa7, f(0b0101)); try testDaa(0x07, f(0b0110), 0x01, f(0b0100)); try testDaa(0x07, f(0b0111), 0xa1, f(0b0101)); try testDaa(0x07, f(0b1000), 0x07, f(0b0000)); try testDaa(0x07, f(0b1001), 0x67, f(0b0001)); try testDaa(0x07, f(0b1010), 0x0d, f(0b0000)); try testDaa(0x07, f(0b1011), 0x6d, f(0b0001)); try testDaa(0x07, f(0b1100), 0x07, f(0b0100)); try testDaa(0x07, f(0b1101), 0xa7, f(0b0101)); try testDaa(0x07, f(0b1110), 0x01, f(0b0100)); try testDaa(0x07, f(0b1111), 0xa1, f(0b0101)); try testDaa(0x08, f(0b0000), 0x08, f(0b0000)); try testDaa(0x08, f(0b0001), 0x68, f(0b0001)); try testDaa(0x08, f(0b0010), 0x0e, f(0b0000)); try testDaa(0x08, f(0b0011), 0x6e, f(0b0001)); try testDaa(0x08, f(0b0100), 0x08, f(0b0100)); try testDaa(0x08, f(0b0101), 0xa8, f(0b0101)); try testDaa(0x08, f(0b0110), 0x02, f(0b0100)); try testDaa(0x08, f(0b0111), 0xa2, f(0b0101)); try testDaa(0x08, f(0b1000), 0x08, f(0b0000)); try testDaa(0x08, f(0b1001), 0x68, f(0b0001)); try testDaa(0x08, f(0b1010), 0x0e, f(0b0000)); try testDaa(0x08, f(0b1011), 0x6e, f(0b0001)); try testDaa(0x08, f(0b1100), 0x08, f(0b0100)); try testDaa(0x08, f(0b1101), 0xa8, f(0b0101)); try testDaa(0x08, f(0b1110), 0x02, f(0b0100)); try testDaa(0x08, f(0b1111), 0xa2, f(0b0101)); try testDaa(0x09, f(0b0000), 0x09, f(0b0000)); try testDaa(0x09, f(0b0001), 0x69, f(0b0001)); try testDaa(0x09, f(0b0010), 0x0f, f(0b0000)); try testDaa(0x09, f(0b0011), 0x6f, f(0b0001)); try testDaa(0x09, f(0b0100), 0x09, f(0b0100)); try testDaa(0x09, f(0b0101), 0xa9, f(0b0101)); try testDaa(0x09, f(0b0110), 0x03, f(0b0100)); try testDaa(0x09, f(0b0111), 0xa3, f(0b0101)); try testDaa(0x09, f(0b1000), 0x09, f(0b0000)); try testDaa(0x09, f(0b1001), 0x69, f(0b0001)); try testDaa(0x09, f(0b1010), 0x0f, f(0b0000)); try testDaa(0x09, f(0b1011), 0x6f, f(0b0001)); try testDaa(0x09, f(0b1100), 0x09, f(0b0100)); try testDaa(0x09, f(0b1101), 0xa9, f(0b0101)); try testDaa(0x09, f(0b1110), 0x03, f(0b0100)); try testDaa(0x09, f(0b1111), 0xa3, f(0b0101)); try testDaa(0x0a, f(0b0000), 0x10, f(0b0000)); try testDaa(0x0a, f(0b0001), 0x70, f(0b0001)); try testDaa(0x0a, f(0b0010), 0x10, f(0b0000)); try testDaa(0x0a, f(0b0011), 0x70, f(0b0001)); try testDaa(0x0a, f(0b0100), 0x0a, f(0b0100)); try testDaa(0x0a, f(0b0101), 0xaa, f(0b0101)); try testDaa(0x0a, f(0b0110), 0x04, f(0b0100)); try testDaa(0x0a, f(0b0111), 0xa4, f(0b0101)); try testDaa(0x0a, f(0b1000), 0x10, f(0b0000)); try testDaa(0x0a, f(0b1001), 0x70, f(0b0001)); try testDaa(0x0a, f(0b1010), 0x10, f(0b0000)); try testDaa(0x0a, f(0b1011), 0x70, f(0b0001)); try testDaa(0x0a, f(0b1100), 0x0a, f(0b0100)); try testDaa(0x0a, f(0b1101), 0xaa, f(0b0101)); try testDaa(0x0a, f(0b1110), 0x04, f(0b0100)); try testDaa(0x0a, f(0b1111), 0xa4, f(0b0101)); try testDaa(0x0b, f(0b0000), 0x11, f(0b0000)); try testDaa(0x0b, f(0b0001), 0x71, f(0b0001)); try testDaa(0x0b, f(0b0010), 0x11, f(0b0000)); try testDaa(0x0b, f(0b0011), 0x71, f(0b0001)); try testDaa(0x0b, f(0b0100), 0x0b, f(0b0100)); try testDaa(0x0b, f(0b0101), 0xab, f(0b0101)); try testDaa(0x0b, f(0b0110), 0x05, f(0b0100)); try testDaa(0x0b, f(0b0111), 0xa5, f(0b0101)); try testDaa(0x0b, f(0b1000), 0x11, f(0b0000)); try testDaa(0x0b, f(0b1001), 0x71, f(0b0001)); try testDaa(0x0b, f(0b1010), 0x11, f(0b0000)); try testDaa(0x0b, f(0b1011), 0x71, f(0b0001)); try testDaa(0x0b, f(0b1100), 0x0b, f(0b0100)); try testDaa(0x0b, f(0b1101), 0xab, f(0b0101)); try testDaa(0x0b, f(0b1110), 0x05, f(0b0100)); try testDaa(0x0b, f(0b1111), 0xa5, f(0b0101)); try testDaa(0x0c, f(0b0000), 0x12, f(0b0000)); try testDaa(0x0c, f(0b0001), 0x72, f(0b0001)); try testDaa(0x0c, f(0b0010), 0x12, f(0b0000)); try testDaa(0x0c, f(0b0011), 0x72, f(0b0001)); try testDaa(0x0c, f(0b0100), 0x0c, f(0b0100)); try testDaa(0x0c, f(0b0101), 0xac, f(0b0101)); try testDaa(0x0c, f(0b0110), 0x06, f(0b0100)); try testDaa(0x0c, f(0b0111), 0xa6, f(0b0101)); try testDaa(0x0c, f(0b1000), 0x12, f(0b0000)); try testDaa(0x0c, f(0b1001), 0x72, f(0b0001)); try testDaa(0x0c, f(0b1010), 0x12, f(0b0000)); try testDaa(0x0c, f(0b1011), 0x72, f(0b0001)); try testDaa(0x0c, f(0b1100), 0x0c, f(0b0100)); try testDaa(0x0c, f(0b1101), 0xac, f(0b0101)); try testDaa(0x0c, f(0b1110), 0x06, f(0b0100)); try testDaa(0x0c, f(0b1111), 0xa6, f(0b0101)); try testDaa(0x0d, f(0b0000), 0x13, f(0b0000)); try testDaa(0x0d, f(0b0001), 0x73, f(0b0001)); try testDaa(0x0d, f(0b0010), 0x13, f(0b0000)); try testDaa(0x0d, f(0b0011), 0x73, f(0b0001)); try testDaa(0x0d, f(0b0100), 0x0d, f(0b0100)); try testDaa(0x0d, f(0b0101), 0xad, f(0b0101)); try testDaa(0x0d, f(0b0110), 0x07, f(0b0100)); try testDaa(0x0d, f(0b0111), 0xa7, f(0b0101)); try testDaa(0x0d, f(0b1000), 0x13, f(0b0000)); try testDaa(0x0d, f(0b1001), 0x73, f(0b0001)); try testDaa(0x0d, f(0b1010), 0x13, f(0b0000)); try testDaa(0x0d, f(0b1011), 0x73, f(0b0001)); try testDaa(0x0d, f(0b1100), 0x0d, f(0b0100)); try testDaa(0x0d, f(0b1101), 0xad, f(0b0101)); try testDaa(0x0d, f(0b1110), 0x07, f(0b0100)); try testDaa(0x0d, f(0b1111), 0xa7, f(0b0101)); try testDaa(0x0e, f(0b0000), 0x14, f(0b0000)); try testDaa(0x0e, f(0b0001), 0x74, f(0b0001)); try testDaa(0x0e, f(0b0010), 0x14, f(0b0000)); try testDaa(0x0e, f(0b0011), 0x74, f(0b0001)); try testDaa(0x0e, f(0b0100), 0x0e, f(0b0100)); try testDaa(0x0e, f(0b0101), 0xae, f(0b0101)); try testDaa(0x0e, f(0b0110), 0x08, f(0b0100)); try testDaa(0x0e, f(0b0111), 0xa8, f(0b0101)); try testDaa(0x0e, f(0b1000), 0x14, f(0b0000)); try testDaa(0x0e, f(0b1001), 0x74, f(0b0001)); try testDaa(0x0e, f(0b1010), 0x14, f(0b0000)); try testDaa(0x0e, f(0b1011), 0x74, f(0b0001)); try testDaa(0x0e, f(0b1100), 0x0e, f(0b0100)); try testDaa(0x0e, f(0b1101), 0xae, f(0b0101)); try testDaa(0x0e, f(0b1110), 0x08, f(0b0100)); try testDaa(0x0e, f(0b1111), 0xa8, f(0b0101)); try testDaa(0x0f, f(0b0000), 0x15, f(0b0000)); try testDaa(0x0f, f(0b0001), 0x75, f(0b0001)); try testDaa(0x0f, f(0b0010), 0x15, f(0b0000)); try testDaa(0x0f, f(0b0011), 0x75, f(0b0001)); try testDaa(0x0f, f(0b0100), 0x0f, f(0b0100)); try testDaa(0x0f, f(0b0101), 0xaf, f(0b0101)); try testDaa(0x0f, f(0b0110), 0x09, f(0b0100)); try testDaa(0x0f, f(0b0111), 0xa9, f(0b0101)); try testDaa(0x0f, f(0b1000), 0x15, f(0b0000)); try testDaa(0x0f, f(0b1001), 0x75, f(0b0001)); try testDaa(0x0f, f(0b1010), 0x15, f(0b0000)); try testDaa(0x0f, f(0b1011), 0x75, f(0b0001)); try testDaa(0x0f, f(0b1100), 0x0f, f(0b0100)); try testDaa(0x0f, f(0b1101), 0xaf, f(0b0101)); try testDaa(0x0f, f(0b1110), 0x09, f(0b0100)); try testDaa(0x0f, f(0b1111), 0xa9, f(0b0101)); try testDaa(0x10, f(0b0000), 0x10, f(0b0000)); try testDaa(0x10, f(0b0001), 0x70, f(0b0001)); try testDaa(0x10, f(0b0010), 0x16, f(0b0000)); try testDaa(0x10, f(0b0011), 0x76, f(0b0001)); try testDaa(0x10, f(0b0100), 0x10, f(0b0100)); try testDaa(0x10, f(0b0101), 0xb0, f(0b0101)); try testDaa(0x10, f(0b0110), 0x0a, f(0b0100)); try testDaa(0x10, f(0b0111), 0xaa, f(0b0101)); try testDaa(0x10, f(0b1000), 0x10, f(0b0000)); try testDaa(0x10, f(0b1001), 0x70, f(0b0001)); try testDaa(0x10, f(0b1010), 0x16, f(0b0000)); try testDaa(0x10, f(0b1011), 0x76, f(0b0001)); try testDaa(0x10, f(0b1100), 0x10, f(0b0100)); try testDaa(0x10, f(0b1101), 0xb0, f(0b0101)); try testDaa(0x10, f(0b1110), 0x0a, f(0b0100)); try testDaa(0x10, f(0b1111), 0xaa, f(0b0101)); try testDaa(0x11, f(0b0000), 0x11, f(0b0000)); try testDaa(0x11, f(0b0001), 0x71, f(0b0001)); try testDaa(0x11, f(0b0010), 0x17, f(0b0000)); try testDaa(0x11, f(0b0011), 0x77, f(0b0001)); try testDaa(0x11, f(0b0100), 0x11, f(0b0100)); try testDaa(0x11, f(0b0101), 0xb1, f(0b0101)); try testDaa(0x11, f(0b0110), 0x0b, f(0b0100)); try testDaa(0x11, f(0b0111), 0xab, f(0b0101)); try testDaa(0x11, f(0b1000), 0x11, f(0b0000)); try testDaa(0x11, f(0b1001), 0x71, f(0b0001)); try testDaa(0x11, f(0b1010), 0x17, f(0b0000)); try testDaa(0x11, f(0b1011), 0x77, f(0b0001)); try testDaa(0x11, f(0b1100), 0x11, f(0b0100)); try testDaa(0x11, f(0b1101), 0xb1, f(0b0101)); try testDaa(0x11, f(0b1110), 0x0b, f(0b0100)); try testDaa(0x11, f(0b1111), 0xab, f(0b0101)); try testDaa(0x12, f(0b0000), 0x12, f(0b0000)); try testDaa(0x12, f(0b0001), 0x72, f(0b0001)); try testDaa(0x12, f(0b0010), 0x18, f(0b0000)); try testDaa(0x12, f(0b0011), 0x78, f(0b0001)); try testDaa(0x12, f(0b0100), 0x12, f(0b0100)); try testDaa(0x12, f(0b0101), 0xb2, f(0b0101)); try testDaa(0x12, f(0b0110), 0x0c, f(0b0100)); try testDaa(0x12, f(0b0111), 0xac, f(0b0101)); try testDaa(0x12, f(0b1000), 0x12, f(0b0000)); try testDaa(0x12, f(0b1001), 0x72, f(0b0001)); try testDaa(0x12, f(0b1010), 0x18, f(0b0000)); try testDaa(0x12, f(0b1011), 0x78, f(0b0001)); try testDaa(0x12, f(0b1100), 0x12, f(0b0100)); try testDaa(0x12, f(0b1101), 0xb2, f(0b0101)); try testDaa(0x12, f(0b1110), 0x0c, f(0b0100)); try testDaa(0x12, f(0b1111), 0xac, f(0b0101)); try testDaa(0x13, f(0b0000), 0x13, f(0b0000)); try testDaa(0x13, f(0b0001), 0x73, f(0b0001)); try testDaa(0x13, f(0b0010), 0x19, f(0b0000)); try testDaa(0x13, f(0b0011), 0x79, f(0b0001)); try testDaa(0x13, f(0b0100), 0x13, f(0b0100)); try testDaa(0x13, f(0b0101), 0xb3, f(0b0101)); try testDaa(0x13, f(0b0110), 0x0d, f(0b0100)); try testDaa(0x13, f(0b0111), 0xad, f(0b0101)); try testDaa(0x13, f(0b1000), 0x13, f(0b0000)); try testDaa(0x13, f(0b1001), 0x73, f(0b0001)); try testDaa(0x13, f(0b1010), 0x19, f(0b0000)); try testDaa(0x13, f(0b1011), 0x79, f(0b0001)); try testDaa(0x13, f(0b1100), 0x13, f(0b0100)); try testDaa(0x13, f(0b1101), 0xb3, f(0b0101)); try testDaa(0x13, f(0b1110), 0x0d, f(0b0100)); try testDaa(0x13, f(0b1111), 0xad, f(0b0101)); try testDaa(0x14, f(0b0000), 0x14, f(0b0000)); try testDaa(0x14, f(0b0001), 0x74, f(0b0001)); try testDaa(0x14, f(0b0010), 0x1a, f(0b0000)); try testDaa(0x14, f(0b0011), 0x7a, f(0b0001)); try testDaa(0x14, f(0b0100), 0x14, f(0b0100)); try testDaa(0x14, f(0b0101), 0xb4, f(0b0101)); try testDaa(0x14, f(0b0110), 0x0e, f(0b0100)); try testDaa(0x14, f(0b0111), 0xae, f(0b0101)); try testDaa(0x14, f(0b1000), 0x14, f(0b0000)); try testDaa(0x14, f(0b1001), 0x74, f(0b0001)); try testDaa(0x14, f(0b1010), 0x1a, f(0b0000)); try testDaa(0x14, f(0b1011), 0x7a, f(0b0001)); try testDaa(0x14, f(0b1100), 0x14, f(0b0100)); try testDaa(0x14, f(0b1101), 0xb4, f(0b0101)); try testDaa(0x14, f(0b1110), 0x0e, f(0b0100)); try testDaa(0x14, f(0b1111), 0xae, f(0b0101)); try testDaa(0x15, f(0b0000), 0x15, f(0b0000)); try testDaa(0x15, f(0b0001), 0x75, f(0b0001)); try testDaa(0x15, f(0b0010), 0x1b, f(0b0000)); try testDaa(0x15, f(0b0011), 0x7b, f(0b0001)); try testDaa(0x15, f(0b0100), 0x15, f(0b0100)); try testDaa(0x15, f(0b0101), 0xb5, f(0b0101)); try testDaa(0x15, f(0b0110), 0x0f, f(0b0100)); try testDaa(0x15, f(0b0111), 0xaf, f(0b0101)); try testDaa(0x15, f(0b1000), 0x15, f(0b0000)); try testDaa(0x15, f(0b1001), 0x75, f(0b0001)); try testDaa(0x15, f(0b1010), 0x1b, f(0b0000)); try testDaa(0x15, f(0b1011), 0x7b, f(0b0001)); try testDaa(0x15, f(0b1100), 0x15, f(0b0100)); try testDaa(0x15, f(0b1101), 0xb5, f(0b0101)); try testDaa(0x15, f(0b1110), 0x0f, f(0b0100)); try testDaa(0x15, f(0b1111), 0xaf, f(0b0101)); try testDaa(0x16, f(0b0000), 0x16, f(0b0000)); try testDaa(0x16, f(0b0001), 0x76, f(0b0001)); try testDaa(0x16, f(0b0010), 0x1c, f(0b0000)); try testDaa(0x16, f(0b0011), 0x7c, f(0b0001)); try testDaa(0x16, f(0b0100), 0x16, f(0b0100)); try testDaa(0x16, f(0b0101), 0xb6, f(0b0101)); try testDaa(0x16, f(0b0110), 0x10, f(0b0100)); try testDaa(0x16, f(0b0111), 0xb0, f(0b0101)); try testDaa(0x16, f(0b1000), 0x16, f(0b0000)); try testDaa(0x16, f(0b1001), 0x76, f(0b0001)); try testDaa(0x16, f(0b1010), 0x1c, f(0b0000)); try testDaa(0x16, f(0b1011), 0x7c, f(0b0001)); try testDaa(0x16, f(0b1100), 0x16, f(0b0100)); try testDaa(0x16, f(0b1101), 0xb6, f(0b0101)); try testDaa(0x16, f(0b1110), 0x10, f(0b0100)); try testDaa(0x16, f(0b1111), 0xb0, f(0b0101)); try testDaa(0x17, f(0b0000), 0x17, f(0b0000)); try testDaa(0x17, f(0b0001), 0x77, f(0b0001)); try testDaa(0x17, f(0b0010), 0x1d, f(0b0000)); try testDaa(0x17, f(0b0011), 0x7d, f(0b0001)); try testDaa(0x17, f(0b0100), 0x17, f(0b0100)); try testDaa(0x17, f(0b0101), 0xb7, f(0b0101)); try testDaa(0x17, f(0b0110), 0x11, f(0b0100)); try testDaa(0x17, f(0b0111), 0xb1, f(0b0101)); try testDaa(0x17, f(0b1000), 0x17, f(0b0000)); try testDaa(0x17, f(0b1001), 0x77, f(0b0001)); try testDaa(0x17, f(0b1010), 0x1d, f(0b0000)); try testDaa(0x17, f(0b1011), 0x7d, f(0b0001)); try testDaa(0x17, f(0b1100), 0x17, f(0b0100)); try testDaa(0x17, f(0b1101), 0xb7, f(0b0101)); try testDaa(0x17, f(0b1110), 0x11, f(0b0100)); try testDaa(0x17, f(0b1111), 0xb1, f(0b0101)); try testDaa(0x18, f(0b0000), 0x18, f(0b0000)); try testDaa(0x18, f(0b0001), 0x78, f(0b0001)); try testDaa(0x18, f(0b0010), 0x1e, f(0b0000)); try testDaa(0x18, f(0b0011), 0x7e, f(0b0001)); try testDaa(0x18, f(0b0100), 0x18, f(0b0100)); try testDaa(0x18, f(0b0101), 0xb8, f(0b0101)); try testDaa(0x18, f(0b0110), 0x12, f(0b0100)); try testDaa(0x18, f(0b0111), 0xb2, f(0b0101)); try testDaa(0x18, f(0b1000), 0x18, f(0b0000)); try testDaa(0x18, f(0b1001), 0x78, f(0b0001)); try testDaa(0x18, f(0b1010), 0x1e, f(0b0000)); try testDaa(0x18, f(0b1011), 0x7e, f(0b0001)); try testDaa(0x18, f(0b1100), 0x18, f(0b0100)); try testDaa(0x18, f(0b1101), 0xb8, f(0b0101)); try testDaa(0x18, f(0b1110), 0x12, f(0b0100)); try testDaa(0x18, f(0b1111), 0xb2, f(0b0101)); try testDaa(0x19, f(0b0000), 0x19, f(0b0000)); try testDaa(0x19, f(0b0001), 0x79, f(0b0001)); try testDaa(0x19, f(0b0010), 0x1f, f(0b0000)); try testDaa(0x19, f(0b0011), 0x7f, f(0b0001)); try testDaa(0x19, f(0b0100), 0x19, f(0b0100)); try testDaa(0x19, f(0b0101), 0xb9, f(0b0101)); try testDaa(0x19, f(0b0110), 0x13, f(0b0100)); try testDaa(0x19, f(0b0111), 0xb3, f(0b0101)); try testDaa(0x19, f(0b1000), 0x19, f(0b0000)); try testDaa(0x19, f(0b1001), 0x79, f(0b0001)); try testDaa(0x19, f(0b1010), 0x1f, f(0b0000)); try testDaa(0x19, f(0b1011), 0x7f, f(0b0001)); try testDaa(0x19, f(0b1100), 0x19, f(0b0100)); try testDaa(0x19, f(0b1101), 0xb9, f(0b0101)); try testDaa(0x19, f(0b1110), 0x13, f(0b0100)); try testDaa(0x19, f(0b1111), 0xb3, f(0b0101)); try testDaa(0x1a, f(0b0000), 0x20, f(0b0000)); try testDaa(0x1a, f(0b0001), 0x80, f(0b0001)); try testDaa(0x1a, f(0b0010), 0x20, f(0b0000)); try testDaa(0x1a, f(0b0011), 0x80, f(0b0001)); try testDaa(0x1a, f(0b0100), 0x1a, f(0b0100)); try testDaa(0x1a, f(0b0101), 0xba, f(0b0101)); try testDaa(0x1a, f(0b0110), 0x14, f(0b0100)); try testDaa(0x1a, f(0b0111), 0xb4, f(0b0101)); try testDaa(0x1a, f(0b1000), 0x20, f(0b0000)); try testDaa(0x1a, f(0b1001), 0x80, f(0b0001)); try testDaa(0x1a, f(0b1010), 0x20, f(0b0000)); try testDaa(0x1a, f(0b1011), 0x80, f(0b0001)); try testDaa(0x1a, f(0b1100), 0x1a, f(0b0100)); try testDaa(0x1a, f(0b1101), 0xba, f(0b0101)); try testDaa(0x1a, f(0b1110), 0x14, f(0b0100)); try testDaa(0x1a, f(0b1111), 0xb4, f(0b0101)); try testDaa(0x1b, f(0b0000), 0x21, f(0b0000)); try testDaa(0x1b, f(0b0001), 0x81, f(0b0001)); try testDaa(0x1b, f(0b0010), 0x21, f(0b0000)); try testDaa(0x1b, f(0b0011), 0x81, f(0b0001)); try testDaa(0x1b, f(0b0100), 0x1b, f(0b0100)); try testDaa(0x1b, f(0b0101), 0xbb, f(0b0101)); try testDaa(0x1b, f(0b0110), 0x15, f(0b0100)); try testDaa(0x1b, f(0b0111), 0xb5, f(0b0101)); try testDaa(0x1b, f(0b1000), 0x21, f(0b0000)); try testDaa(0x1b, f(0b1001), 0x81, f(0b0001)); try testDaa(0x1b, f(0b1010), 0x21, f(0b0000)); try testDaa(0x1b, f(0b1011), 0x81, f(0b0001)); try testDaa(0x1b, f(0b1100), 0x1b, f(0b0100)); try testDaa(0x1b, f(0b1101), 0xbb, f(0b0101)); try testDaa(0x1b, f(0b1110), 0x15, f(0b0100)); try testDaa(0x1b, f(0b1111), 0xb5, f(0b0101)); try testDaa(0x1c, f(0b0000), 0x22, f(0b0000)); try testDaa(0x1c, f(0b0001), 0x82, f(0b0001)); try testDaa(0x1c, f(0b0010), 0x22, f(0b0000)); try testDaa(0x1c, f(0b0011), 0x82, f(0b0001)); try testDaa(0x1c, f(0b0100), 0x1c, f(0b0100)); try testDaa(0x1c, f(0b0101), 0xbc, f(0b0101)); try testDaa(0x1c, f(0b0110), 0x16, f(0b0100)); try testDaa(0x1c, f(0b0111), 0xb6, f(0b0101)); try testDaa(0x1c, f(0b1000), 0x22, f(0b0000)); try testDaa(0x1c, f(0b1001), 0x82, f(0b0001)); try testDaa(0x1c, f(0b1010), 0x22, f(0b0000)); try testDaa(0x1c, f(0b1011), 0x82, f(0b0001)); try testDaa(0x1c, f(0b1100), 0x1c, f(0b0100)); try testDaa(0x1c, f(0b1101), 0xbc, f(0b0101)); try testDaa(0x1c, f(0b1110), 0x16, f(0b0100)); try testDaa(0x1c, f(0b1111), 0xb6, f(0b0101)); try testDaa(0x1d, f(0b0000), 0x23, f(0b0000)); try testDaa(0x1d, f(0b0001), 0x83, f(0b0001)); try testDaa(0x1d, f(0b0010), 0x23, f(0b0000)); try testDaa(0x1d, f(0b0011), 0x83, f(0b0001)); try testDaa(0x1d, f(0b0100), 0x1d, f(0b0100)); try testDaa(0x1d, f(0b0101), 0xbd, f(0b0101)); try testDaa(0x1d, f(0b0110), 0x17, f(0b0100)); try testDaa(0x1d, f(0b0111), 0xb7, f(0b0101)); try testDaa(0x1d, f(0b1000), 0x23, f(0b0000)); try testDaa(0x1d, f(0b1001), 0x83, f(0b0001)); try testDaa(0x1d, f(0b1010), 0x23, f(0b0000)); try testDaa(0x1d, f(0b1011), 0x83, f(0b0001)); try testDaa(0x1d, f(0b1100), 0x1d, f(0b0100)); try testDaa(0x1d, f(0b1101), 0xbd, f(0b0101)); try testDaa(0x1d, f(0b1110), 0x17, f(0b0100)); try testDaa(0x1d, f(0b1111), 0xb7, f(0b0101)); try testDaa(0x1e, f(0b0000), 0x24, f(0b0000)); try testDaa(0x1e, f(0b0001), 0x84, f(0b0001)); try testDaa(0x1e, f(0b0010), 0x24, f(0b0000)); try testDaa(0x1e, f(0b0011), 0x84, f(0b0001)); try testDaa(0x1e, f(0b0100), 0x1e, f(0b0100)); try testDaa(0x1e, f(0b0101), 0xbe, f(0b0101)); try testDaa(0x1e, f(0b0110), 0x18, f(0b0100)); try testDaa(0x1e, f(0b0111), 0xb8, f(0b0101)); try testDaa(0x1e, f(0b1000), 0x24, f(0b0000)); try testDaa(0x1e, f(0b1001), 0x84, f(0b0001)); try testDaa(0x1e, f(0b1010), 0x24, f(0b0000)); try testDaa(0x1e, f(0b1011), 0x84, f(0b0001)); try testDaa(0x1e, f(0b1100), 0x1e, f(0b0100)); try testDaa(0x1e, f(0b1101), 0xbe, f(0b0101)); try testDaa(0x1e, f(0b1110), 0x18, f(0b0100)); try testDaa(0x1e, f(0b1111), 0xb8, f(0b0101)); try testDaa(0x1f, f(0b0000), 0x25, f(0b0000)); try testDaa(0x1f, f(0b0001), 0x85, f(0b0001)); try testDaa(0x1f, f(0b0010), 0x25, f(0b0000)); try testDaa(0x1f, f(0b0011), 0x85, f(0b0001)); try testDaa(0x1f, f(0b0100), 0x1f, f(0b0100)); try testDaa(0x1f, f(0b0101), 0xbf, f(0b0101)); try testDaa(0x1f, f(0b0110), 0x19, f(0b0100)); try testDaa(0x1f, f(0b0111), 0xb9, f(0b0101)); try testDaa(0x1f, f(0b1000), 0x25, f(0b0000)); try testDaa(0x1f, f(0b1001), 0x85, f(0b0001)); try testDaa(0x1f, f(0b1010), 0x25, f(0b0000)); try testDaa(0x1f, f(0b1011), 0x85, f(0b0001)); try testDaa(0x1f, f(0b1100), 0x1f, f(0b0100)); try testDaa(0x1f, f(0b1101), 0xbf, f(0b0101)); try testDaa(0x1f, f(0b1110), 0x19, f(0b0100)); try testDaa(0x1f, f(0b1111), 0xb9, f(0b0101)); try testDaa(0x20, f(0b0000), 0x20, f(0b0000)); try testDaa(0x20, f(0b0001), 0x80, f(0b0001)); try testDaa(0x20, f(0b0010), 0x26, f(0b0000)); try testDaa(0x20, f(0b0011), 0x86, f(0b0001)); try testDaa(0x20, f(0b0100), 0x20, f(0b0100)); try testDaa(0x20, f(0b0101), 0xc0, f(0b0101)); try testDaa(0x20, f(0b0110), 0x1a, f(0b0100)); try testDaa(0x20, f(0b0111), 0xba, f(0b0101)); try testDaa(0x20, f(0b1000), 0x20, f(0b0000)); try testDaa(0x20, f(0b1001), 0x80, f(0b0001)); try testDaa(0x20, f(0b1010), 0x26, f(0b0000)); try testDaa(0x20, f(0b1011), 0x86, f(0b0001)); try testDaa(0x20, f(0b1100), 0x20, f(0b0100)); try testDaa(0x20, f(0b1101), 0xc0, f(0b0101)); try testDaa(0x20, f(0b1110), 0x1a, f(0b0100)); try testDaa(0x20, f(0b1111), 0xba, f(0b0101)); try testDaa(0x21, f(0b0000), 0x21, f(0b0000)); try testDaa(0x21, f(0b0001), 0x81, f(0b0001)); try testDaa(0x21, f(0b0010), 0x27, f(0b0000)); try testDaa(0x21, f(0b0011), 0x87, f(0b0001)); try testDaa(0x21, f(0b0100), 0x21, f(0b0100)); try testDaa(0x21, f(0b0101), 0xc1, f(0b0101)); try testDaa(0x21, f(0b0110), 0x1b, f(0b0100)); try testDaa(0x21, f(0b0111), 0xbb, f(0b0101)); try testDaa(0x21, f(0b1000), 0x21, f(0b0000)); try testDaa(0x21, f(0b1001), 0x81, f(0b0001)); try testDaa(0x21, f(0b1010), 0x27, f(0b0000)); try testDaa(0x21, f(0b1011), 0x87, f(0b0001)); try testDaa(0x21, f(0b1100), 0x21, f(0b0100)); try testDaa(0x21, f(0b1101), 0xc1, f(0b0101)); try testDaa(0x21, f(0b1110), 0x1b, f(0b0100)); try testDaa(0x21, f(0b1111), 0xbb, f(0b0101)); try testDaa(0x22, f(0b0000), 0x22, f(0b0000)); try testDaa(0x22, f(0b0001), 0x82, f(0b0001)); try testDaa(0x22, f(0b0010), 0x28, f(0b0000)); try testDaa(0x22, f(0b0011), 0x88, f(0b0001)); try testDaa(0x22, f(0b0100), 0x22, f(0b0100)); try testDaa(0x22, f(0b0101), 0xc2, f(0b0101)); try testDaa(0x22, f(0b0110), 0x1c, f(0b0100)); try testDaa(0x22, f(0b0111), 0xbc, f(0b0101)); try testDaa(0x22, f(0b1000), 0x22, f(0b0000)); try testDaa(0x22, f(0b1001), 0x82, f(0b0001)); try testDaa(0x22, f(0b1010), 0x28, f(0b0000)); try testDaa(0x22, f(0b1011), 0x88, f(0b0001)); try testDaa(0x22, f(0b1100), 0x22, f(0b0100)); try testDaa(0x22, f(0b1101), 0xc2, f(0b0101)); try testDaa(0x22, f(0b1110), 0x1c, f(0b0100)); try testDaa(0x22, f(0b1111), 0xbc, f(0b0101)); try testDaa(0x23, f(0b0000), 0x23, f(0b0000)); try testDaa(0x23, f(0b0001), 0x83, f(0b0001)); try testDaa(0x23, f(0b0010), 0x29, f(0b0000)); try testDaa(0x23, f(0b0011), 0x89, f(0b0001)); try testDaa(0x23, f(0b0100), 0x23, f(0b0100)); try testDaa(0x23, f(0b0101), 0xc3, f(0b0101)); try testDaa(0x23, f(0b0110), 0x1d, f(0b0100)); try testDaa(0x23, f(0b0111), 0xbd, f(0b0101)); try testDaa(0x23, f(0b1000), 0x23, f(0b0000)); try testDaa(0x23, f(0b1001), 0x83, f(0b0001)); try testDaa(0x23, f(0b1010), 0x29, f(0b0000)); try testDaa(0x23, f(0b1011), 0x89, f(0b0001)); try testDaa(0x23, f(0b1100), 0x23, f(0b0100)); try testDaa(0x23, f(0b1101), 0xc3, f(0b0101)); try testDaa(0x23, f(0b1110), 0x1d, f(0b0100)); try testDaa(0x23, f(0b1111), 0xbd, f(0b0101)); try testDaa(0x24, f(0b0000), 0x24, f(0b0000)); try testDaa(0x24, f(0b0001), 0x84, f(0b0001)); try testDaa(0x24, f(0b0010), 0x2a, f(0b0000)); try testDaa(0x24, f(0b0011), 0x8a, f(0b0001)); try testDaa(0x24, f(0b0100), 0x24, f(0b0100)); try testDaa(0x24, f(0b0101), 0xc4, f(0b0101)); try testDaa(0x24, f(0b0110), 0x1e, f(0b0100)); try testDaa(0x24, f(0b0111), 0xbe, f(0b0101)); try testDaa(0x24, f(0b1000), 0x24, f(0b0000)); try testDaa(0x24, f(0b1001), 0x84, f(0b0001)); try testDaa(0x24, f(0b1010), 0x2a, f(0b0000)); try testDaa(0x24, f(0b1011), 0x8a, f(0b0001)); try testDaa(0x24, f(0b1100), 0x24, f(0b0100)); try testDaa(0x24, f(0b1101), 0xc4, f(0b0101)); try testDaa(0x24, f(0b1110), 0x1e, f(0b0100)); try testDaa(0x24, f(0b1111), 0xbe, f(0b0101)); try testDaa(0x25, f(0b0000), 0x25, f(0b0000)); try testDaa(0x25, f(0b0001), 0x85, f(0b0001)); try testDaa(0x25, f(0b0010), 0x2b, f(0b0000)); try testDaa(0x25, f(0b0011), 0x8b, f(0b0001)); try testDaa(0x25, f(0b0100), 0x25, f(0b0100)); try testDaa(0x25, f(0b0101), 0xc5, f(0b0101)); try testDaa(0x25, f(0b0110), 0x1f, f(0b0100)); try testDaa(0x25, f(0b0111), 0xbf, f(0b0101)); try testDaa(0x25, f(0b1000), 0x25, f(0b0000)); try testDaa(0x25, f(0b1001), 0x85, f(0b0001)); try testDaa(0x25, f(0b1010), 0x2b, f(0b0000)); try testDaa(0x25, f(0b1011), 0x8b, f(0b0001)); try testDaa(0x25, f(0b1100), 0x25, f(0b0100)); try testDaa(0x25, f(0b1101), 0xc5, f(0b0101)); try testDaa(0x25, f(0b1110), 0x1f, f(0b0100)); try testDaa(0x25, f(0b1111), 0xbf, f(0b0101)); try testDaa(0x26, f(0b0000), 0x26, f(0b0000)); try testDaa(0x26, f(0b0001), 0x86, f(0b0001)); try testDaa(0x26, f(0b0010), 0x2c, f(0b0000)); try testDaa(0x26, f(0b0011), 0x8c, f(0b0001)); try testDaa(0x26, f(0b0100), 0x26, f(0b0100)); try testDaa(0x26, f(0b0101), 0xc6, f(0b0101)); try testDaa(0x26, f(0b0110), 0x20, f(0b0100)); try testDaa(0x26, f(0b0111), 0xc0, f(0b0101)); try testDaa(0x26, f(0b1000), 0x26, f(0b0000)); try testDaa(0x26, f(0b1001), 0x86, f(0b0001)); try testDaa(0x26, f(0b1010), 0x2c, f(0b0000)); try testDaa(0x26, f(0b1011), 0x8c, f(0b0001)); try testDaa(0x26, f(0b1100), 0x26, f(0b0100)); try testDaa(0x26, f(0b1101), 0xc6, f(0b0101)); try testDaa(0x26, f(0b1110), 0x20, f(0b0100)); try testDaa(0x26, f(0b1111), 0xc0, f(0b0101)); try testDaa(0x27, f(0b0000), 0x27, f(0b0000)); try testDaa(0x27, f(0b0001), 0x87, f(0b0001)); try testDaa(0x27, f(0b0010), 0x2d, f(0b0000)); try testDaa(0x27, f(0b0011), 0x8d, f(0b0001)); try testDaa(0x27, f(0b0100), 0x27, f(0b0100)); try testDaa(0x27, f(0b0101), 0xc7, f(0b0101)); try testDaa(0x27, f(0b0110), 0x21, f(0b0100)); try testDaa(0x27, f(0b0111), 0xc1, f(0b0101)); try testDaa(0x27, f(0b1000), 0x27, f(0b0000)); try testDaa(0x27, f(0b1001), 0x87, f(0b0001)); try testDaa(0x27, f(0b1010), 0x2d, f(0b0000)); try testDaa(0x27, f(0b1011), 0x8d, f(0b0001)); try testDaa(0x27, f(0b1100), 0x27, f(0b0100)); try testDaa(0x27, f(0b1101), 0xc7, f(0b0101)); try testDaa(0x27, f(0b1110), 0x21, f(0b0100)); try testDaa(0x27, f(0b1111), 0xc1, f(0b0101)); try testDaa(0x28, f(0b0000), 0x28, f(0b0000)); try testDaa(0x28, f(0b0001), 0x88, f(0b0001)); try testDaa(0x28, f(0b0010), 0x2e, f(0b0000)); try testDaa(0x28, f(0b0011), 0x8e, f(0b0001)); try testDaa(0x28, f(0b0100), 0x28, f(0b0100)); try testDaa(0x28, f(0b0101), 0xc8, f(0b0101)); try testDaa(0x28, f(0b0110), 0x22, f(0b0100)); try testDaa(0x28, f(0b0111), 0xc2, f(0b0101)); try testDaa(0x28, f(0b1000), 0x28, f(0b0000)); try testDaa(0x28, f(0b1001), 0x88, f(0b0001)); try testDaa(0x28, f(0b1010), 0x2e, f(0b0000)); try testDaa(0x28, f(0b1011), 0x8e, f(0b0001)); try testDaa(0x28, f(0b1100), 0x28, f(0b0100)); try testDaa(0x28, f(0b1101), 0xc8, f(0b0101)); try testDaa(0x28, f(0b1110), 0x22, f(0b0100)); try testDaa(0x28, f(0b1111), 0xc2, f(0b0101)); try testDaa(0x29, f(0b0000), 0x29, f(0b0000)); try testDaa(0x29, f(0b0001), 0x89, f(0b0001)); try testDaa(0x29, f(0b0010), 0x2f, f(0b0000)); try testDaa(0x29, f(0b0011), 0x8f, f(0b0001)); try testDaa(0x29, f(0b0100), 0x29, f(0b0100)); try testDaa(0x29, f(0b0101), 0xc9, f(0b0101)); try testDaa(0x29, f(0b0110), 0x23, f(0b0100)); try testDaa(0x29, f(0b0111), 0xc3, f(0b0101)); try testDaa(0x29, f(0b1000), 0x29, f(0b0000)); try testDaa(0x29, f(0b1001), 0x89, f(0b0001)); try testDaa(0x29, f(0b1010), 0x2f, f(0b0000)); try testDaa(0x29, f(0b1011), 0x8f, f(0b0001)); try testDaa(0x29, f(0b1100), 0x29, f(0b0100)); try testDaa(0x29, f(0b1101), 0xc9, f(0b0101)); try testDaa(0x29, f(0b1110), 0x23, f(0b0100)); try testDaa(0x29, f(0b1111), 0xc3, f(0b0101)); try testDaa(0x2a, f(0b0000), 0x30, f(0b0000)); try testDaa(0x2a, f(0b0001), 0x90, f(0b0001)); try testDaa(0x2a, f(0b0010), 0x30, f(0b0000)); try testDaa(0x2a, f(0b0011), 0x90, f(0b0001)); try testDaa(0x2a, f(0b0100), 0x2a, f(0b0100)); try testDaa(0x2a, f(0b0101), 0xca, f(0b0101)); try testDaa(0x2a, f(0b0110), 0x24, f(0b0100)); try testDaa(0x2a, f(0b0111), 0xc4, f(0b0101)); try testDaa(0x2a, f(0b1000), 0x30, f(0b0000)); try testDaa(0x2a, f(0b1001), 0x90, f(0b0001)); try testDaa(0x2a, f(0b1010), 0x30, f(0b0000)); try testDaa(0x2a, f(0b1011), 0x90, f(0b0001)); try testDaa(0x2a, f(0b1100), 0x2a, f(0b0100)); try testDaa(0x2a, f(0b1101), 0xca, f(0b0101)); try testDaa(0x2a, f(0b1110), 0x24, f(0b0100)); try testDaa(0x2a, f(0b1111), 0xc4, f(0b0101)); try testDaa(0x2b, f(0b0000), 0x31, f(0b0000)); try testDaa(0x2b, f(0b0001), 0x91, f(0b0001)); try testDaa(0x2b, f(0b0010), 0x31, f(0b0000)); try testDaa(0x2b, f(0b0011), 0x91, f(0b0001)); try testDaa(0x2b, f(0b0100), 0x2b, f(0b0100)); try testDaa(0x2b, f(0b0101), 0xcb, f(0b0101)); try testDaa(0x2b, f(0b0110), 0x25, f(0b0100)); try testDaa(0x2b, f(0b0111), 0xc5, f(0b0101)); try testDaa(0x2b, f(0b1000), 0x31, f(0b0000)); try testDaa(0x2b, f(0b1001), 0x91, f(0b0001)); try testDaa(0x2b, f(0b1010), 0x31, f(0b0000)); try testDaa(0x2b, f(0b1011), 0x91, f(0b0001)); try testDaa(0x2b, f(0b1100), 0x2b, f(0b0100)); try testDaa(0x2b, f(0b1101), 0xcb, f(0b0101)); try testDaa(0x2b, f(0b1110), 0x25, f(0b0100)); try testDaa(0x2b, f(0b1111), 0xc5, f(0b0101)); try testDaa(0x2c, f(0b0000), 0x32, f(0b0000)); try testDaa(0x2c, f(0b0001), 0x92, f(0b0001)); try testDaa(0x2c, f(0b0010), 0x32, f(0b0000)); try testDaa(0x2c, f(0b0011), 0x92, f(0b0001)); try testDaa(0x2c, f(0b0100), 0x2c, f(0b0100)); try testDaa(0x2c, f(0b0101), 0xcc, f(0b0101)); try testDaa(0x2c, f(0b0110), 0x26, f(0b0100)); try testDaa(0x2c, f(0b0111), 0xc6, f(0b0101)); try testDaa(0x2c, f(0b1000), 0x32, f(0b0000)); try testDaa(0x2c, f(0b1001), 0x92, f(0b0001)); try testDaa(0x2c, f(0b1010), 0x32, f(0b0000)); try testDaa(0x2c, f(0b1011), 0x92, f(0b0001)); try testDaa(0x2c, f(0b1100), 0x2c, f(0b0100)); try testDaa(0x2c, f(0b1101), 0xcc, f(0b0101)); try testDaa(0x2c, f(0b1110), 0x26, f(0b0100)); try testDaa(0x2c, f(0b1111), 0xc6, f(0b0101)); try testDaa(0x2d, f(0b0000), 0x33, f(0b0000)); try testDaa(0x2d, f(0b0001), 0x93, f(0b0001)); try testDaa(0x2d, f(0b0010), 0x33, f(0b0000)); try testDaa(0x2d, f(0b0011), 0x93, f(0b0001)); try testDaa(0x2d, f(0b0100), 0x2d, f(0b0100)); try testDaa(0x2d, f(0b0101), 0xcd, f(0b0101)); try testDaa(0x2d, f(0b0110), 0x27, f(0b0100)); try testDaa(0x2d, f(0b0111), 0xc7, f(0b0101)); try testDaa(0x2d, f(0b1000), 0x33, f(0b0000)); try testDaa(0x2d, f(0b1001), 0x93, f(0b0001)); try testDaa(0x2d, f(0b1010), 0x33, f(0b0000)); try testDaa(0x2d, f(0b1011), 0x93, f(0b0001)); try testDaa(0x2d, f(0b1100), 0x2d, f(0b0100)); try testDaa(0x2d, f(0b1101), 0xcd, f(0b0101)); try testDaa(0x2d, f(0b1110), 0x27, f(0b0100)); try testDaa(0x2d, f(0b1111), 0xc7, f(0b0101)); try testDaa(0x2e, f(0b0000), 0x34, f(0b0000)); try testDaa(0x2e, f(0b0001), 0x94, f(0b0001)); try testDaa(0x2e, f(0b0010), 0x34, f(0b0000)); try testDaa(0x2e, f(0b0011), 0x94, f(0b0001)); try testDaa(0x2e, f(0b0100), 0x2e, f(0b0100)); try testDaa(0x2e, f(0b0101), 0xce, f(0b0101)); try testDaa(0x2e, f(0b0110), 0x28, f(0b0100)); try testDaa(0x2e, f(0b0111), 0xc8, f(0b0101)); try testDaa(0x2e, f(0b1000), 0x34, f(0b0000)); try testDaa(0x2e, f(0b1001), 0x94, f(0b0001)); try testDaa(0x2e, f(0b1010), 0x34, f(0b0000)); try testDaa(0x2e, f(0b1011), 0x94, f(0b0001)); try testDaa(0x2e, f(0b1100), 0x2e, f(0b0100)); try testDaa(0x2e, f(0b1101), 0xce, f(0b0101)); try testDaa(0x2e, f(0b1110), 0x28, f(0b0100)); try testDaa(0x2e, f(0b1111), 0xc8, f(0b0101)); try testDaa(0x2f, f(0b0000), 0x35, f(0b0000)); try testDaa(0x2f, f(0b0001), 0x95, f(0b0001)); try testDaa(0x2f, f(0b0010), 0x35, f(0b0000)); try testDaa(0x2f, f(0b0011), 0x95, f(0b0001)); try testDaa(0x2f, f(0b0100), 0x2f, f(0b0100)); try testDaa(0x2f, f(0b0101), 0xcf, f(0b0101)); try testDaa(0x2f, f(0b0110), 0x29, f(0b0100)); try testDaa(0x2f, f(0b0111), 0xc9, f(0b0101)); try testDaa(0x2f, f(0b1000), 0x35, f(0b0000)); try testDaa(0x2f, f(0b1001), 0x95, f(0b0001)); try testDaa(0x2f, f(0b1010), 0x35, f(0b0000)); try testDaa(0x2f, f(0b1011), 0x95, f(0b0001)); try testDaa(0x2f, f(0b1100), 0x2f, f(0b0100)); try testDaa(0x2f, f(0b1101), 0xcf, f(0b0101)); try testDaa(0x2f, f(0b1110), 0x29, f(0b0100)); try testDaa(0x2f, f(0b1111), 0xc9, f(0b0101)); try testDaa(0x30, f(0b0000), 0x30, f(0b0000)); try testDaa(0x30, f(0b0001), 0x90, f(0b0001)); try testDaa(0x30, f(0b0010), 0x36, f(0b0000)); try testDaa(0x30, f(0b0011), 0x96, f(0b0001)); try testDaa(0x30, f(0b0100), 0x30, f(0b0100)); try testDaa(0x30, f(0b0101), 0xd0, f(0b0101)); try testDaa(0x30, f(0b0110), 0x2a, f(0b0100)); try testDaa(0x30, f(0b0111), 0xca, f(0b0101)); try testDaa(0x30, f(0b1000), 0x30, f(0b0000)); try testDaa(0x30, f(0b1001), 0x90, f(0b0001)); try testDaa(0x30, f(0b1010), 0x36, f(0b0000)); try testDaa(0x30, f(0b1011), 0x96, f(0b0001)); try testDaa(0x30, f(0b1100), 0x30, f(0b0100)); try testDaa(0x30, f(0b1101), 0xd0, f(0b0101)); try testDaa(0x30, f(0b1110), 0x2a, f(0b0100)); try testDaa(0x30, f(0b1111), 0xca, f(0b0101)); try testDaa(0x31, f(0b0000), 0x31, f(0b0000)); try testDaa(0x31, f(0b0001), 0x91, f(0b0001)); try testDaa(0x31, f(0b0010), 0x37, f(0b0000)); try testDaa(0x31, f(0b0011), 0x97, f(0b0001)); try testDaa(0x31, f(0b0100), 0x31, f(0b0100)); try testDaa(0x31, f(0b0101), 0xd1, f(0b0101)); try testDaa(0x31, f(0b0110), 0x2b, f(0b0100)); try testDaa(0x31, f(0b0111), 0xcb, f(0b0101)); try testDaa(0x31, f(0b1000), 0x31, f(0b0000)); try testDaa(0x31, f(0b1001), 0x91, f(0b0001)); try testDaa(0x31, f(0b1010), 0x37, f(0b0000)); try testDaa(0x31, f(0b1011), 0x97, f(0b0001)); try testDaa(0x31, f(0b1100), 0x31, f(0b0100)); try testDaa(0x31, f(0b1101), 0xd1, f(0b0101)); try testDaa(0x31, f(0b1110), 0x2b, f(0b0100)); try testDaa(0x31, f(0b1111), 0xcb, f(0b0101)); try testDaa(0x32, f(0b0000), 0x32, f(0b0000)); try testDaa(0x32, f(0b0001), 0x92, f(0b0001)); try testDaa(0x32, f(0b0010), 0x38, f(0b0000)); try testDaa(0x32, f(0b0011), 0x98, f(0b0001)); try testDaa(0x32, f(0b0100), 0x32, f(0b0100)); try testDaa(0x32, f(0b0101), 0xd2, f(0b0101)); try testDaa(0x32, f(0b0110), 0x2c, f(0b0100)); try testDaa(0x32, f(0b0111), 0xcc, f(0b0101)); try testDaa(0x32, f(0b1000), 0x32, f(0b0000)); try testDaa(0x32, f(0b1001), 0x92, f(0b0001)); try testDaa(0x32, f(0b1010), 0x38, f(0b0000)); try testDaa(0x32, f(0b1011), 0x98, f(0b0001)); try testDaa(0x32, f(0b1100), 0x32, f(0b0100)); try testDaa(0x32, f(0b1101), 0xd2, f(0b0101)); try testDaa(0x32, f(0b1110), 0x2c, f(0b0100)); try testDaa(0x32, f(0b1111), 0xcc, f(0b0101)); try testDaa(0x33, f(0b0000), 0x33, f(0b0000)); try testDaa(0x33, f(0b0001), 0x93, f(0b0001)); try testDaa(0x33, f(0b0010), 0x39, f(0b0000)); try testDaa(0x33, f(0b0011), 0x99, f(0b0001)); try testDaa(0x33, f(0b0100), 0x33, f(0b0100)); try testDaa(0x33, f(0b0101), 0xd3, f(0b0101)); try testDaa(0x33, f(0b0110), 0x2d, f(0b0100)); try testDaa(0x33, f(0b0111), 0xcd, f(0b0101)); try testDaa(0x33, f(0b1000), 0x33, f(0b0000)); try testDaa(0x33, f(0b1001), 0x93, f(0b0001)); try testDaa(0x33, f(0b1010), 0x39, f(0b0000)); try testDaa(0x33, f(0b1011), 0x99, f(0b0001)); try testDaa(0x33, f(0b1100), 0x33, f(0b0100)); try testDaa(0x33, f(0b1101), 0xd3, f(0b0101)); try testDaa(0x33, f(0b1110), 0x2d, f(0b0100)); try testDaa(0x33, f(0b1111), 0xcd, f(0b0101)); try testDaa(0x34, f(0b0000), 0x34, f(0b0000)); try testDaa(0x34, f(0b0001), 0x94, f(0b0001)); try testDaa(0x34, f(0b0010), 0x3a, f(0b0000)); try testDaa(0x34, f(0b0011), 0x9a, f(0b0001)); try testDaa(0x34, f(0b0100), 0x34, f(0b0100)); try testDaa(0x34, f(0b0101), 0xd4, f(0b0101)); try testDaa(0x34, f(0b0110), 0x2e, f(0b0100)); try testDaa(0x34, f(0b0111), 0xce, f(0b0101)); try testDaa(0x34, f(0b1000), 0x34, f(0b0000)); try testDaa(0x34, f(0b1001), 0x94, f(0b0001)); try testDaa(0x34, f(0b1010), 0x3a, f(0b0000)); try testDaa(0x34, f(0b1011), 0x9a, f(0b0001)); try testDaa(0x34, f(0b1100), 0x34, f(0b0100)); try testDaa(0x34, f(0b1101), 0xd4, f(0b0101)); try testDaa(0x34, f(0b1110), 0x2e, f(0b0100)); try testDaa(0x34, f(0b1111), 0xce, f(0b0101)); try testDaa(0x35, f(0b0000), 0x35, f(0b0000)); try testDaa(0x35, f(0b0001), 0x95, f(0b0001)); try testDaa(0x35, f(0b0010), 0x3b, f(0b0000)); try testDaa(0x35, f(0b0011), 0x9b, f(0b0001)); try testDaa(0x35, f(0b0100), 0x35, f(0b0100)); try testDaa(0x35, f(0b0101), 0xd5, f(0b0101)); try testDaa(0x35, f(0b0110), 0x2f, f(0b0100)); try testDaa(0x35, f(0b0111), 0xcf, f(0b0101)); try testDaa(0x35, f(0b1000), 0x35, f(0b0000)); try testDaa(0x35, f(0b1001), 0x95, f(0b0001)); try testDaa(0x35, f(0b1010), 0x3b, f(0b0000)); try testDaa(0x35, f(0b1011), 0x9b, f(0b0001)); try testDaa(0x35, f(0b1100), 0x35, f(0b0100)); try testDaa(0x35, f(0b1101), 0xd5, f(0b0101)); try testDaa(0x35, f(0b1110), 0x2f, f(0b0100)); try testDaa(0x35, f(0b1111), 0xcf, f(0b0101)); try testDaa(0x36, f(0b0000), 0x36, f(0b0000)); try testDaa(0x36, f(0b0001), 0x96, f(0b0001)); try testDaa(0x36, f(0b0010), 0x3c, f(0b0000)); try testDaa(0x36, f(0b0011), 0x9c, f(0b0001)); try testDaa(0x36, f(0b0100), 0x36, f(0b0100)); try testDaa(0x36, f(0b0101), 0xd6, f(0b0101)); try testDaa(0x36, f(0b0110), 0x30, f(0b0100)); try testDaa(0x36, f(0b0111), 0xd0, f(0b0101)); try testDaa(0x36, f(0b1000), 0x36, f(0b0000)); try testDaa(0x36, f(0b1001), 0x96, f(0b0001)); try testDaa(0x36, f(0b1010), 0x3c, f(0b0000)); try testDaa(0x36, f(0b1011), 0x9c, f(0b0001)); try testDaa(0x36, f(0b1100), 0x36, f(0b0100)); try testDaa(0x36, f(0b1101), 0xd6, f(0b0101)); try testDaa(0x36, f(0b1110), 0x30, f(0b0100)); try testDaa(0x36, f(0b1111), 0xd0, f(0b0101)); try testDaa(0x37, f(0b0000), 0x37, f(0b0000)); try testDaa(0x37, f(0b0001), 0x97, f(0b0001)); try testDaa(0x37, f(0b0010), 0x3d, f(0b0000)); try testDaa(0x37, f(0b0011), 0x9d, f(0b0001)); try testDaa(0x37, f(0b0100), 0x37, f(0b0100)); try testDaa(0x37, f(0b0101), 0xd7, f(0b0101)); try testDaa(0x37, f(0b0110), 0x31, f(0b0100)); try testDaa(0x37, f(0b0111), 0xd1, f(0b0101)); try testDaa(0x37, f(0b1000), 0x37, f(0b0000)); try testDaa(0x37, f(0b1001), 0x97, f(0b0001)); try testDaa(0x37, f(0b1010), 0x3d, f(0b0000)); try testDaa(0x37, f(0b1011), 0x9d, f(0b0001)); try testDaa(0x37, f(0b1100), 0x37, f(0b0100)); try testDaa(0x37, f(0b1101), 0xd7, f(0b0101)); try testDaa(0x37, f(0b1110), 0x31, f(0b0100)); try testDaa(0x37, f(0b1111), 0xd1, f(0b0101)); try testDaa(0x38, f(0b0000), 0x38, f(0b0000)); try testDaa(0x38, f(0b0001), 0x98, f(0b0001)); try testDaa(0x38, f(0b0010), 0x3e, f(0b0000)); try testDaa(0x38, f(0b0011), 0x9e, f(0b0001)); try testDaa(0x38, f(0b0100), 0x38, f(0b0100)); try testDaa(0x38, f(0b0101), 0xd8, f(0b0101)); try testDaa(0x38, f(0b0110), 0x32, f(0b0100)); try testDaa(0x38, f(0b0111), 0xd2, f(0b0101)); try testDaa(0x38, f(0b1000), 0x38, f(0b0000)); try testDaa(0x38, f(0b1001), 0x98, f(0b0001)); try testDaa(0x38, f(0b1010), 0x3e, f(0b0000)); try testDaa(0x38, f(0b1011), 0x9e, f(0b0001)); try testDaa(0x38, f(0b1100), 0x38, f(0b0100)); try testDaa(0x38, f(0b1101), 0xd8, f(0b0101)); try testDaa(0x38, f(0b1110), 0x32, f(0b0100)); try testDaa(0x38, f(0b1111), 0xd2, f(0b0101)); try testDaa(0x39, f(0b0000), 0x39, f(0b0000)); try testDaa(0x39, f(0b0001), 0x99, f(0b0001)); try testDaa(0x39, f(0b0010), 0x3f, f(0b0000)); try testDaa(0x39, f(0b0011), 0x9f, f(0b0001)); try testDaa(0x39, f(0b0100), 0x39, f(0b0100)); try testDaa(0x39, f(0b0101), 0xd9, f(0b0101)); try testDaa(0x39, f(0b0110), 0x33, f(0b0100)); try testDaa(0x39, f(0b0111), 0xd3, f(0b0101)); try testDaa(0x39, f(0b1000), 0x39, f(0b0000)); try testDaa(0x39, f(0b1001), 0x99, f(0b0001)); try testDaa(0x39, f(0b1010), 0x3f, f(0b0000)); try testDaa(0x39, f(0b1011), 0x9f, f(0b0001)); try testDaa(0x39, f(0b1100), 0x39, f(0b0100)); try testDaa(0x39, f(0b1101), 0xd9, f(0b0101)); try testDaa(0x39, f(0b1110), 0x33, f(0b0100)); try testDaa(0x39, f(0b1111), 0xd3, f(0b0101)); try testDaa(0x3a, f(0b0000), 0x40, f(0b0000)); try testDaa(0x3a, f(0b0001), 0xa0, f(0b0001)); try testDaa(0x3a, f(0b0010), 0x40, f(0b0000)); try testDaa(0x3a, f(0b0011), 0xa0, f(0b0001)); try testDaa(0x3a, f(0b0100), 0x3a, f(0b0100)); try testDaa(0x3a, f(0b0101), 0xda, f(0b0101)); try testDaa(0x3a, f(0b0110), 0x34, f(0b0100)); try testDaa(0x3a, f(0b0111), 0xd4, f(0b0101)); try testDaa(0x3a, f(0b1000), 0x40, f(0b0000)); try testDaa(0x3a, f(0b1001), 0xa0, f(0b0001)); try testDaa(0x3a, f(0b1010), 0x40, f(0b0000)); try testDaa(0x3a, f(0b1011), 0xa0, f(0b0001)); try testDaa(0x3a, f(0b1100), 0x3a, f(0b0100)); try testDaa(0x3a, f(0b1101), 0xda, f(0b0101)); try testDaa(0x3a, f(0b1110), 0x34, f(0b0100)); try testDaa(0x3a, f(0b1111), 0xd4, f(0b0101)); try testDaa(0x3b, f(0b0000), 0x41, f(0b0000)); try testDaa(0x3b, f(0b0001), 0xa1, f(0b0001)); try testDaa(0x3b, f(0b0010), 0x41, f(0b0000)); try testDaa(0x3b, f(0b0011), 0xa1, f(0b0001)); try testDaa(0x3b, f(0b0100), 0x3b, f(0b0100)); try testDaa(0x3b, f(0b0101), 0xdb, f(0b0101)); try testDaa(0x3b, f(0b0110), 0x35, f(0b0100)); try testDaa(0x3b, f(0b0111), 0xd5, f(0b0101)); try testDaa(0x3b, f(0b1000), 0x41, f(0b0000)); try testDaa(0x3b, f(0b1001), 0xa1, f(0b0001)); try testDaa(0x3b, f(0b1010), 0x41, f(0b0000)); try testDaa(0x3b, f(0b1011), 0xa1, f(0b0001)); try testDaa(0x3b, f(0b1100), 0x3b, f(0b0100)); try testDaa(0x3b, f(0b1101), 0xdb, f(0b0101)); try testDaa(0x3b, f(0b1110), 0x35, f(0b0100)); try testDaa(0x3b, f(0b1111), 0xd5, f(0b0101)); try testDaa(0x3c, f(0b0000), 0x42, f(0b0000)); try testDaa(0x3c, f(0b0001), 0xa2, f(0b0001)); try testDaa(0x3c, f(0b0010), 0x42, f(0b0000)); try testDaa(0x3c, f(0b0011), 0xa2, f(0b0001)); try testDaa(0x3c, f(0b0100), 0x3c, f(0b0100)); try testDaa(0x3c, f(0b0101), 0xdc, f(0b0101)); try testDaa(0x3c, f(0b0110), 0x36, f(0b0100)); try testDaa(0x3c, f(0b0111), 0xd6, f(0b0101)); try testDaa(0x3c, f(0b1000), 0x42, f(0b0000)); try testDaa(0x3c, f(0b1001), 0xa2, f(0b0001)); try testDaa(0x3c, f(0b1010), 0x42, f(0b0000)); try testDaa(0x3c, f(0b1011), 0xa2, f(0b0001)); try testDaa(0x3c, f(0b1100), 0x3c, f(0b0100)); try testDaa(0x3c, f(0b1101), 0xdc, f(0b0101)); try testDaa(0x3c, f(0b1110), 0x36, f(0b0100)); try testDaa(0x3c, f(0b1111), 0xd6, f(0b0101)); try testDaa(0x3d, f(0b0000), 0x43, f(0b0000)); try testDaa(0x3d, f(0b0001), 0xa3, f(0b0001)); try testDaa(0x3d, f(0b0010), 0x43, f(0b0000)); try testDaa(0x3d, f(0b0011), 0xa3, f(0b0001)); try testDaa(0x3d, f(0b0100), 0x3d, f(0b0100)); try testDaa(0x3d, f(0b0101), 0xdd, f(0b0101)); try testDaa(0x3d, f(0b0110), 0x37, f(0b0100)); try testDaa(0x3d, f(0b0111), 0xd7, f(0b0101)); try testDaa(0x3d, f(0b1000), 0x43, f(0b0000)); try testDaa(0x3d, f(0b1001), 0xa3, f(0b0001)); try testDaa(0x3d, f(0b1010), 0x43, f(0b0000)); try testDaa(0x3d, f(0b1011), 0xa3, f(0b0001)); try testDaa(0x3d, f(0b1100), 0x3d, f(0b0100)); try testDaa(0x3d, f(0b1101), 0xdd, f(0b0101)); try testDaa(0x3d, f(0b1110), 0x37, f(0b0100)); try testDaa(0x3d, f(0b1111), 0xd7, f(0b0101)); try testDaa(0x3e, f(0b0000), 0x44, f(0b0000)); try testDaa(0x3e, f(0b0001), 0xa4, f(0b0001)); try testDaa(0x3e, f(0b0010), 0x44, f(0b0000)); try testDaa(0x3e, f(0b0011), 0xa4, f(0b0001)); try testDaa(0x3e, f(0b0100), 0x3e, f(0b0100)); try testDaa(0x3e, f(0b0101), 0xde, f(0b0101)); try testDaa(0x3e, f(0b0110), 0x38, f(0b0100)); try testDaa(0x3e, f(0b0111), 0xd8, f(0b0101)); try testDaa(0x3e, f(0b1000), 0x44, f(0b0000)); try testDaa(0x3e, f(0b1001), 0xa4, f(0b0001)); try testDaa(0x3e, f(0b1010), 0x44, f(0b0000)); try testDaa(0x3e, f(0b1011), 0xa4, f(0b0001)); try testDaa(0x3e, f(0b1100), 0x3e, f(0b0100)); try testDaa(0x3e, f(0b1101), 0xde, f(0b0101)); try testDaa(0x3e, f(0b1110), 0x38, f(0b0100)); try testDaa(0x3e, f(0b1111), 0xd8, f(0b0101)); try testDaa(0x3f, f(0b0000), 0x45, f(0b0000)); try testDaa(0x3f, f(0b0001), 0xa5, f(0b0001)); try testDaa(0x3f, f(0b0010), 0x45, f(0b0000)); try testDaa(0x3f, f(0b0011), 0xa5, f(0b0001)); try testDaa(0x3f, f(0b0100), 0x3f, f(0b0100)); try testDaa(0x3f, f(0b0101), 0xdf, f(0b0101)); try testDaa(0x3f, f(0b0110), 0x39, f(0b0100)); try testDaa(0x3f, f(0b0111), 0xd9, f(0b0101)); try testDaa(0x3f, f(0b1000), 0x45, f(0b0000)); try testDaa(0x3f, f(0b1001), 0xa5, f(0b0001)); try testDaa(0x3f, f(0b1010), 0x45, f(0b0000)); try testDaa(0x3f, f(0b1011), 0xa5, f(0b0001)); try testDaa(0x3f, f(0b1100), 0x3f, f(0b0100)); try testDaa(0x3f, f(0b1101), 0xdf, f(0b0101)); try testDaa(0x3f, f(0b1110), 0x39, f(0b0100)); try testDaa(0x3f, f(0b1111), 0xd9, f(0b0101)); try testDaa(0x40, f(0b0000), 0x40, f(0b0000)); try testDaa(0x40, f(0b0001), 0xa0, f(0b0001)); try testDaa(0x40, f(0b0010), 0x46, f(0b0000)); try testDaa(0x40, f(0b0011), 0xa6, f(0b0001)); try testDaa(0x40, f(0b0100), 0x40, f(0b0100)); try testDaa(0x40, f(0b0101), 0xe0, f(0b0101)); try testDaa(0x40, f(0b0110), 0x3a, f(0b0100)); try testDaa(0x40, f(0b0111), 0xda, f(0b0101)); try testDaa(0x40, f(0b1000), 0x40, f(0b0000)); try testDaa(0x40, f(0b1001), 0xa0, f(0b0001)); try testDaa(0x40, f(0b1010), 0x46, f(0b0000)); try testDaa(0x40, f(0b1011), 0xa6, f(0b0001)); try testDaa(0x40, f(0b1100), 0x40, f(0b0100)); try testDaa(0x40, f(0b1101), 0xe0, f(0b0101)); try testDaa(0x40, f(0b1110), 0x3a, f(0b0100)); try testDaa(0x40, f(0b1111), 0xda, f(0b0101)); try testDaa(0x41, f(0b0000), 0x41, f(0b0000)); try testDaa(0x41, f(0b0001), 0xa1, f(0b0001)); try testDaa(0x41, f(0b0010), 0x47, f(0b0000)); try testDaa(0x41, f(0b0011), 0xa7, f(0b0001)); try testDaa(0x41, f(0b0100), 0x41, f(0b0100)); try testDaa(0x41, f(0b0101), 0xe1, f(0b0101)); try testDaa(0x41, f(0b0110), 0x3b, f(0b0100)); try testDaa(0x41, f(0b0111), 0xdb, f(0b0101)); try testDaa(0x41, f(0b1000), 0x41, f(0b0000)); try testDaa(0x41, f(0b1001), 0xa1, f(0b0001)); try testDaa(0x41, f(0b1010), 0x47, f(0b0000)); try testDaa(0x41, f(0b1011), 0xa7, f(0b0001)); try testDaa(0x41, f(0b1100), 0x41, f(0b0100)); try testDaa(0x41, f(0b1101), 0xe1, f(0b0101)); try testDaa(0x41, f(0b1110), 0x3b, f(0b0100)); try testDaa(0x41, f(0b1111), 0xdb, f(0b0101)); try testDaa(0x42, f(0b0000), 0x42, f(0b0000)); try testDaa(0x42, f(0b0001), 0xa2, f(0b0001)); try testDaa(0x42, f(0b0010), 0x48, f(0b0000)); try testDaa(0x42, f(0b0011), 0xa8, f(0b0001)); try testDaa(0x42, f(0b0100), 0x42, f(0b0100)); try testDaa(0x42, f(0b0101), 0xe2, f(0b0101)); try testDaa(0x42, f(0b0110), 0x3c, f(0b0100)); try testDaa(0x42, f(0b0111), 0xdc, f(0b0101)); try testDaa(0x42, f(0b1000), 0x42, f(0b0000)); try testDaa(0x42, f(0b1001), 0xa2, f(0b0001)); try testDaa(0x42, f(0b1010), 0x48, f(0b0000)); try testDaa(0x42, f(0b1011), 0xa8, f(0b0001)); try testDaa(0x42, f(0b1100), 0x42, f(0b0100)); try testDaa(0x42, f(0b1101), 0xe2, f(0b0101)); try testDaa(0x42, f(0b1110), 0x3c, f(0b0100)); try testDaa(0x42, f(0b1111), 0xdc, f(0b0101)); try testDaa(0x43, f(0b0000), 0x43, f(0b0000)); try testDaa(0x43, f(0b0001), 0xa3, f(0b0001)); try testDaa(0x43, f(0b0010), 0x49, f(0b0000)); try testDaa(0x43, f(0b0011), 0xa9, f(0b0001)); try testDaa(0x43, f(0b0100), 0x43, f(0b0100)); try testDaa(0x43, f(0b0101), 0xe3, f(0b0101)); try testDaa(0x43, f(0b0110), 0x3d, f(0b0100)); try testDaa(0x43, f(0b0111), 0xdd, f(0b0101)); try testDaa(0x43, f(0b1000), 0x43, f(0b0000)); try testDaa(0x43, f(0b1001), 0xa3, f(0b0001)); try testDaa(0x43, f(0b1010), 0x49, f(0b0000)); try testDaa(0x43, f(0b1011), 0xa9, f(0b0001)); try testDaa(0x43, f(0b1100), 0x43, f(0b0100)); try testDaa(0x43, f(0b1101), 0xe3, f(0b0101)); try testDaa(0x43, f(0b1110), 0x3d, f(0b0100)); try testDaa(0x43, f(0b1111), 0xdd, f(0b0101)); try testDaa(0x44, f(0b0000), 0x44, f(0b0000)); try testDaa(0x44, f(0b0001), 0xa4, f(0b0001)); try testDaa(0x44, f(0b0010), 0x4a, f(0b0000)); try testDaa(0x44, f(0b0011), 0xaa, f(0b0001)); try testDaa(0x44, f(0b0100), 0x44, f(0b0100)); try testDaa(0x44, f(0b0101), 0xe4, f(0b0101)); try testDaa(0x44, f(0b0110), 0x3e, f(0b0100)); try testDaa(0x44, f(0b0111), 0xde, f(0b0101)); try testDaa(0x44, f(0b1000), 0x44, f(0b0000)); try testDaa(0x44, f(0b1001), 0xa4, f(0b0001)); try testDaa(0x44, f(0b1010), 0x4a, f(0b0000)); try testDaa(0x44, f(0b1011), 0xaa, f(0b0001)); try testDaa(0x44, f(0b1100), 0x44, f(0b0100)); try testDaa(0x44, f(0b1101), 0xe4, f(0b0101)); try testDaa(0x44, f(0b1110), 0x3e, f(0b0100)); try testDaa(0x44, f(0b1111), 0xde, f(0b0101)); try testDaa(0x45, f(0b0000), 0x45, f(0b0000)); try testDaa(0x45, f(0b0001), 0xa5, f(0b0001)); try testDaa(0x45, f(0b0010), 0x4b, f(0b0000)); try testDaa(0x45, f(0b0011), 0xab, f(0b0001)); try testDaa(0x45, f(0b0100), 0x45, f(0b0100)); try testDaa(0x45, f(0b0101), 0xe5, f(0b0101)); try testDaa(0x45, f(0b0110), 0x3f, f(0b0100)); try testDaa(0x45, f(0b0111), 0xdf, f(0b0101)); try testDaa(0x45, f(0b1000), 0x45, f(0b0000)); try testDaa(0x45, f(0b1001), 0xa5, f(0b0001)); try testDaa(0x45, f(0b1010), 0x4b, f(0b0000)); try testDaa(0x45, f(0b1011), 0xab, f(0b0001)); try testDaa(0x45, f(0b1100), 0x45, f(0b0100)); try testDaa(0x45, f(0b1101), 0xe5, f(0b0101)); try testDaa(0x45, f(0b1110), 0x3f, f(0b0100)); try testDaa(0x45, f(0b1111), 0xdf, f(0b0101)); try testDaa(0x46, f(0b0000), 0x46, f(0b0000)); try testDaa(0x46, f(0b0001), 0xa6, f(0b0001)); try testDaa(0x46, f(0b0010), 0x4c, f(0b0000)); try testDaa(0x46, f(0b0011), 0xac, f(0b0001)); try testDaa(0x46, f(0b0100), 0x46, f(0b0100)); try testDaa(0x46, f(0b0101), 0xe6, f(0b0101)); try testDaa(0x46, f(0b0110), 0x40, f(0b0100)); try testDaa(0x46, f(0b0111), 0xe0, f(0b0101)); try testDaa(0x46, f(0b1000), 0x46, f(0b0000)); try testDaa(0x46, f(0b1001), 0xa6, f(0b0001)); try testDaa(0x46, f(0b1010), 0x4c, f(0b0000)); try testDaa(0x46, f(0b1011), 0xac, f(0b0001)); try testDaa(0x46, f(0b1100), 0x46, f(0b0100)); try testDaa(0x46, f(0b1101), 0xe6, f(0b0101)); try testDaa(0x46, f(0b1110), 0x40, f(0b0100)); try testDaa(0x46, f(0b1111), 0xe0, f(0b0101)); try testDaa(0x47, f(0b0000), 0x47, f(0b0000)); try testDaa(0x47, f(0b0001), 0xa7, f(0b0001)); try testDaa(0x47, f(0b0010), 0x4d, f(0b0000)); try testDaa(0x47, f(0b0011), 0xad, f(0b0001)); try testDaa(0x47, f(0b0100), 0x47, f(0b0100)); try testDaa(0x47, f(0b0101), 0xe7, f(0b0101)); try testDaa(0x47, f(0b0110), 0x41, f(0b0100)); try testDaa(0x47, f(0b0111), 0xe1, f(0b0101)); try testDaa(0x47, f(0b1000), 0x47, f(0b0000)); try testDaa(0x47, f(0b1001), 0xa7, f(0b0001)); try testDaa(0x47, f(0b1010), 0x4d, f(0b0000)); try testDaa(0x47, f(0b1011), 0xad, f(0b0001)); try testDaa(0x47, f(0b1100), 0x47, f(0b0100)); try testDaa(0x47, f(0b1101), 0xe7, f(0b0101)); try testDaa(0x47, f(0b1110), 0x41, f(0b0100)); try testDaa(0x47, f(0b1111), 0xe1, f(0b0101)); try testDaa(0x48, f(0b0000), 0x48, f(0b0000)); try testDaa(0x48, f(0b0001), 0xa8, f(0b0001)); try testDaa(0x48, f(0b0010), 0x4e, f(0b0000)); try testDaa(0x48, f(0b0011), 0xae, f(0b0001)); try testDaa(0x48, f(0b0100), 0x48, f(0b0100)); try testDaa(0x48, f(0b0101), 0xe8, f(0b0101)); try testDaa(0x48, f(0b0110), 0x42, f(0b0100)); try testDaa(0x48, f(0b0111), 0xe2, f(0b0101)); try testDaa(0x48, f(0b1000), 0x48, f(0b0000)); try testDaa(0x48, f(0b1001), 0xa8, f(0b0001)); try testDaa(0x48, f(0b1010), 0x4e, f(0b0000)); try testDaa(0x48, f(0b1011), 0xae, f(0b0001)); try testDaa(0x48, f(0b1100), 0x48, f(0b0100)); try testDaa(0x48, f(0b1101), 0xe8, f(0b0101)); try testDaa(0x48, f(0b1110), 0x42, f(0b0100)); try testDaa(0x48, f(0b1111), 0xe2, f(0b0101)); try testDaa(0x49, f(0b0000), 0x49, f(0b0000)); try testDaa(0x49, f(0b0001), 0xa9, f(0b0001)); try testDaa(0x49, f(0b0010), 0x4f, f(0b0000)); try testDaa(0x49, f(0b0011), 0xaf, f(0b0001)); try testDaa(0x49, f(0b0100), 0x49, f(0b0100)); try testDaa(0x49, f(0b0101), 0xe9, f(0b0101)); try testDaa(0x49, f(0b0110), 0x43, f(0b0100)); try testDaa(0x49, f(0b0111), 0xe3, f(0b0101)); try testDaa(0x49, f(0b1000), 0x49, f(0b0000)); try testDaa(0x49, f(0b1001), 0xa9, f(0b0001)); try testDaa(0x49, f(0b1010), 0x4f, f(0b0000)); try testDaa(0x49, f(0b1011), 0xaf, f(0b0001)); try testDaa(0x49, f(0b1100), 0x49, f(0b0100)); try testDaa(0x49, f(0b1101), 0xe9, f(0b0101)); try testDaa(0x49, f(0b1110), 0x43, f(0b0100)); try testDaa(0x49, f(0b1111), 0xe3, f(0b0101)); try testDaa(0x4a, f(0b0000), 0x50, f(0b0000)); try testDaa(0x4a, f(0b0001), 0xb0, f(0b0001)); try testDaa(0x4a, f(0b0010), 0x50, f(0b0000)); try testDaa(0x4a, f(0b0011), 0xb0, f(0b0001)); try testDaa(0x4a, f(0b0100), 0x4a, f(0b0100)); try testDaa(0x4a, f(0b0101), 0xea, f(0b0101)); try testDaa(0x4a, f(0b0110), 0x44, f(0b0100)); try testDaa(0x4a, f(0b0111), 0xe4, f(0b0101)); try testDaa(0x4a, f(0b1000), 0x50, f(0b0000)); try testDaa(0x4a, f(0b1001), 0xb0, f(0b0001)); try testDaa(0x4a, f(0b1010), 0x50, f(0b0000)); try testDaa(0x4a, f(0b1011), 0xb0, f(0b0001)); try testDaa(0x4a, f(0b1100), 0x4a, f(0b0100)); try testDaa(0x4a, f(0b1101), 0xea, f(0b0101)); try testDaa(0x4a, f(0b1110), 0x44, f(0b0100)); try testDaa(0x4a, f(0b1111), 0xe4, f(0b0101)); try testDaa(0x4b, f(0b0000), 0x51, f(0b0000)); try testDaa(0x4b, f(0b0001), 0xb1, f(0b0001)); try testDaa(0x4b, f(0b0010), 0x51, f(0b0000)); try testDaa(0x4b, f(0b0011), 0xb1, f(0b0001)); try testDaa(0x4b, f(0b0100), 0x4b, f(0b0100)); try testDaa(0x4b, f(0b0101), 0xeb, f(0b0101)); try testDaa(0x4b, f(0b0110), 0x45, f(0b0100)); try testDaa(0x4b, f(0b0111), 0xe5, f(0b0101)); try testDaa(0x4b, f(0b1000), 0x51, f(0b0000)); try testDaa(0x4b, f(0b1001), 0xb1, f(0b0001)); try testDaa(0x4b, f(0b1010), 0x51, f(0b0000)); try testDaa(0x4b, f(0b1011), 0xb1, f(0b0001)); try testDaa(0x4b, f(0b1100), 0x4b, f(0b0100)); try testDaa(0x4b, f(0b1101), 0xeb, f(0b0101)); try testDaa(0x4b, f(0b1110), 0x45, f(0b0100)); try testDaa(0x4b, f(0b1111), 0xe5, f(0b0101)); try testDaa(0x4c, f(0b0000), 0x52, f(0b0000)); try testDaa(0x4c, f(0b0001), 0xb2, f(0b0001)); try testDaa(0x4c, f(0b0010), 0x52, f(0b0000)); try testDaa(0x4c, f(0b0011), 0xb2, f(0b0001)); try testDaa(0x4c, f(0b0100), 0x4c, f(0b0100)); try testDaa(0x4c, f(0b0101), 0xec, f(0b0101)); try testDaa(0x4c, f(0b0110), 0x46, f(0b0100)); try testDaa(0x4c, f(0b0111), 0xe6, f(0b0101)); try testDaa(0x4c, f(0b1000), 0x52, f(0b0000)); try testDaa(0x4c, f(0b1001), 0xb2, f(0b0001)); try testDaa(0x4c, f(0b1010), 0x52, f(0b0000)); try testDaa(0x4c, f(0b1011), 0xb2, f(0b0001)); try testDaa(0x4c, f(0b1100), 0x4c, f(0b0100)); try testDaa(0x4c, f(0b1101), 0xec, f(0b0101)); try testDaa(0x4c, f(0b1110), 0x46, f(0b0100)); try testDaa(0x4c, f(0b1111), 0xe6, f(0b0101)); try testDaa(0x4d, f(0b0000), 0x53, f(0b0000)); try testDaa(0x4d, f(0b0001), 0xb3, f(0b0001)); try testDaa(0x4d, f(0b0010), 0x53, f(0b0000)); try testDaa(0x4d, f(0b0011), 0xb3, f(0b0001)); try testDaa(0x4d, f(0b0100), 0x4d, f(0b0100)); try testDaa(0x4d, f(0b0101), 0xed, f(0b0101)); try testDaa(0x4d, f(0b0110), 0x47, f(0b0100)); try testDaa(0x4d, f(0b0111), 0xe7, f(0b0101)); try testDaa(0x4d, f(0b1000), 0x53, f(0b0000)); try testDaa(0x4d, f(0b1001), 0xb3, f(0b0001)); try testDaa(0x4d, f(0b1010), 0x53, f(0b0000)); try testDaa(0x4d, f(0b1011), 0xb3, f(0b0001)); try testDaa(0x4d, f(0b1100), 0x4d, f(0b0100)); try testDaa(0x4d, f(0b1101), 0xed, f(0b0101)); try testDaa(0x4d, f(0b1110), 0x47, f(0b0100)); try testDaa(0x4d, f(0b1111), 0xe7, f(0b0101)); try testDaa(0x4e, f(0b0000), 0x54, f(0b0000)); try testDaa(0x4e, f(0b0001), 0xb4, f(0b0001)); try testDaa(0x4e, f(0b0010), 0x54, f(0b0000)); try testDaa(0x4e, f(0b0011), 0xb4, f(0b0001)); try testDaa(0x4e, f(0b0100), 0x4e, f(0b0100)); try testDaa(0x4e, f(0b0101), 0xee, f(0b0101)); try testDaa(0x4e, f(0b0110), 0x48, f(0b0100)); try testDaa(0x4e, f(0b0111), 0xe8, f(0b0101)); try testDaa(0x4e, f(0b1000), 0x54, f(0b0000)); try testDaa(0x4e, f(0b1001), 0xb4, f(0b0001)); try testDaa(0x4e, f(0b1010), 0x54, f(0b0000)); try testDaa(0x4e, f(0b1011), 0xb4, f(0b0001)); try testDaa(0x4e, f(0b1100), 0x4e, f(0b0100)); try testDaa(0x4e, f(0b1101), 0xee, f(0b0101)); try testDaa(0x4e, f(0b1110), 0x48, f(0b0100)); try testDaa(0x4e, f(0b1111), 0xe8, f(0b0101)); try testDaa(0x4f, f(0b0000), 0x55, f(0b0000)); try testDaa(0x4f, f(0b0001), 0xb5, f(0b0001)); try testDaa(0x4f, f(0b0010), 0x55, f(0b0000)); try testDaa(0x4f, f(0b0011), 0xb5, f(0b0001)); try testDaa(0x4f, f(0b0100), 0x4f, f(0b0100)); try testDaa(0x4f, f(0b0101), 0xef, f(0b0101)); try testDaa(0x4f, f(0b0110), 0x49, f(0b0100)); try testDaa(0x4f, f(0b0111), 0xe9, f(0b0101)); try testDaa(0x4f, f(0b1000), 0x55, f(0b0000)); try testDaa(0x4f, f(0b1001), 0xb5, f(0b0001)); try testDaa(0x4f, f(0b1010), 0x55, f(0b0000)); try testDaa(0x4f, f(0b1011), 0xb5, f(0b0001)); try testDaa(0x4f, f(0b1100), 0x4f, f(0b0100)); try testDaa(0x4f, f(0b1101), 0xef, f(0b0101)); try testDaa(0x4f, f(0b1110), 0x49, f(0b0100)); try testDaa(0x4f, f(0b1111), 0xe9, f(0b0101)); try testDaa(0x50, f(0b0000), 0x50, f(0b0000)); try testDaa(0x50, f(0b0001), 0xb0, f(0b0001)); try testDaa(0x50, f(0b0010), 0x56, f(0b0000)); try testDaa(0x50, f(0b0011), 0xb6, f(0b0001)); try testDaa(0x50, f(0b0100), 0x50, f(0b0100)); try testDaa(0x50, f(0b0101), 0xf0, f(0b0101)); try testDaa(0x50, f(0b0110), 0x4a, f(0b0100)); try testDaa(0x50, f(0b0111), 0xea, f(0b0101)); try testDaa(0x50, f(0b1000), 0x50, f(0b0000)); try testDaa(0x50, f(0b1001), 0xb0, f(0b0001)); try testDaa(0x50, f(0b1010), 0x56, f(0b0000)); try testDaa(0x50, f(0b1011), 0xb6, f(0b0001)); try testDaa(0x50, f(0b1100), 0x50, f(0b0100)); try testDaa(0x50, f(0b1101), 0xf0, f(0b0101)); try testDaa(0x50, f(0b1110), 0x4a, f(0b0100)); try testDaa(0x50, f(0b1111), 0xea, f(0b0101)); try testDaa(0x51, f(0b0000), 0x51, f(0b0000)); try testDaa(0x51, f(0b0001), 0xb1, f(0b0001)); try testDaa(0x51, f(0b0010), 0x57, f(0b0000)); try testDaa(0x51, f(0b0011), 0xb7, f(0b0001)); try testDaa(0x51, f(0b0100), 0x51, f(0b0100)); try testDaa(0x51, f(0b0101), 0xf1, f(0b0101)); try testDaa(0x51, f(0b0110), 0x4b, f(0b0100)); try testDaa(0x51, f(0b0111), 0xeb, f(0b0101)); try testDaa(0x51, f(0b1000), 0x51, f(0b0000)); try testDaa(0x51, f(0b1001), 0xb1, f(0b0001)); try testDaa(0x51, f(0b1010), 0x57, f(0b0000)); try testDaa(0x51, f(0b1011), 0xb7, f(0b0001)); try testDaa(0x51, f(0b1100), 0x51, f(0b0100)); try testDaa(0x51, f(0b1101), 0xf1, f(0b0101)); try testDaa(0x51, f(0b1110), 0x4b, f(0b0100)); try testDaa(0x51, f(0b1111), 0xeb, f(0b0101)); try testDaa(0x52, f(0b0000), 0x52, f(0b0000)); try testDaa(0x52, f(0b0001), 0xb2, f(0b0001)); try testDaa(0x52, f(0b0010), 0x58, f(0b0000)); try testDaa(0x52, f(0b0011), 0xb8, f(0b0001)); try testDaa(0x52, f(0b0100), 0x52, f(0b0100)); try testDaa(0x52, f(0b0101), 0xf2, f(0b0101)); try testDaa(0x52, f(0b0110), 0x4c, f(0b0100)); try testDaa(0x52, f(0b0111), 0xec, f(0b0101)); try testDaa(0x52, f(0b1000), 0x52, f(0b0000)); try testDaa(0x52, f(0b1001), 0xb2, f(0b0001)); try testDaa(0x52, f(0b1010), 0x58, f(0b0000)); try testDaa(0x52, f(0b1011), 0xb8, f(0b0001)); try testDaa(0x52, f(0b1100), 0x52, f(0b0100)); try testDaa(0x52, f(0b1101), 0xf2, f(0b0101)); try testDaa(0x52, f(0b1110), 0x4c, f(0b0100)); try testDaa(0x52, f(0b1111), 0xec, f(0b0101)); try testDaa(0x53, f(0b0000), 0x53, f(0b0000)); try testDaa(0x53, f(0b0001), 0xb3, f(0b0001)); try testDaa(0x53, f(0b0010), 0x59, f(0b0000)); try testDaa(0x53, f(0b0011), 0xb9, f(0b0001)); try testDaa(0x53, f(0b0100), 0x53, f(0b0100)); try testDaa(0x53, f(0b0101), 0xf3, f(0b0101)); try testDaa(0x53, f(0b0110), 0x4d, f(0b0100)); try testDaa(0x53, f(0b0111), 0xed, f(0b0101)); try testDaa(0x53, f(0b1000), 0x53, f(0b0000)); try testDaa(0x53, f(0b1001), 0xb3, f(0b0001)); try testDaa(0x53, f(0b1010), 0x59, f(0b0000)); try testDaa(0x53, f(0b1011), 0xb9, f(0b0001)); try testDaa(0x53, f(0b1100), 0x53, f(0b0100)); try testDaa(0x53, f(0b1101), 0xf3, f(0b0101)); try testDaa(0x53, f(0b1110), 0x4d, f(0b0100)); try testDaa(0x53, f(0b1111), 0xed, f(0b0101)); try testDaa(0x54, f(0b0000), 0x54, f(0b0000)); try testDaa(0x54, f(0b0001), 0xb4, f(0b0001)); try testDaa(0x54, f(0b0010), 0x5a, f(0b0000)); try testDaa(0x54, f(0b0011), 0xba, f(0b0001)); try testDaa(0x54, f(0b0100), 0x54, f(0b0100)); try testDaa(0x54, f(0b0101), 0xf4, f(0b0101)); try testDaa(0x54, f(0b0110), 0x4e, f(0b0100)); try testDaa(0x54, f(0b0111), 0xee, f(0b0101)); try testDaa(0x54, f(0b1000), 0x54, f(0b0000)); try testDaa(0x54, f(0b1001), 0xb4, f(0b0001)); try testDaa(0x54, f(0b1010), 0x5a, f(0b0000)); try testDaa(0x54, f(0b1011), 0xba, f(0b0001)); try testDaa(0x54, f(0b1100), 0x54, f(0b0100)); try testDaa(0x54, f(0b1101), 0xf4, f(0b0101)); try testDaa(0x54, f(0b1110), 0x4e, f(0b0100)); try testDaa(0x54, f(0b1111), 0xee, f(0b0101)); try testDaa(0x55, f(0b0000), 0x55, f(0b0000)); try testDaa(0x55, f(0b0001), 0xb5, f(0b0001)); try testDaa(0x55, f(0b0010), 0x5b, f(0b0000)); try testDaa(0x55, f(0b0011), 0xbb, f(0b0001)); try testDaa(0x55, f(0b0100), 0x55, f(0b0100)); try testDaa(0x55, f(0b0101), 0xf5, f(0b0101)); try testDaa(0x55, f(0b0110), 0x4f, f(0b0100)); try testDaa(0x55, f(0b0111), 0xef, f(0b0101)); try testDaa(0x55, f(0b1000), 0x55, f(0b0000)); try testDaa(0x55, f(0b1001), 0xb5, f(0b0001)); try testDaa(0x55, f(0b1010), 0x5b, f(0b0000)); try testDaa(0x55, f(0b1011), 0xbb, f(0b0001)); try testDaa(0x55, f(0b1100), 0x55, f(0b0100)); try testDaa(0x55, f(0b1101), 0xf5, f(0b0101)); try testDaa(0x55, f(0b1110), 0x4f, f(0b0100)); try testDaa(0x55, f(0b1111), 0xef, f(0b0101)); try testDaa(0x56, f(0b0000), 0x56, f(0b0000)); try testDaa(0x56, f(0b0001), 0xb6, f(0b0001)); try testDaa(0x56, f(0b0010), 0x5c, f(0b0000)); try testDaa(0x56, f(0b0011), 0xbc, f(0b0001)); try testDaa(0x56, f(0b0100), 0x56, f(0b0100)); try testDaa(0x56, f(0b0101), 0xf6, f(0b0101)); try testDaa(0x56, f(0b0110), 0x50, f(0b0100)); try testDaa(0x56, f(0b0111), 0xf0, f(0b0101)); try testDaa(0x56, f(0b1000), 0x56, f(0b0000)); try testDaa(0x56, f(0b1001), 0xb6, f(0b0001)); try testDaa(0x56, f(0b1010), 0x5c, f(0b0000)); try testDaa(0x56, f(0b1011), 0xbc, f(0b0001)); try testDaa(0x56, f(0b1100), 0x56, f(0b0100)); try testDaa(0x56, f(0b1101), 0xf6, f(0b0101)); try testDaa(0x56, f(0b1110), 0x50, f(0b0100)); try testDaa(0x56, f(0b1111), 0xf0, f(0b0101)); try testDaa(0x57, f(0b0000), 0x57, f(0b0000)); try testDaa(0x57, f(0b0001), 0xb7, f(0b0001)); try testDaa(0x57, f(0b0010), 0x5d, f(0b0000)); try testDaa(0x57, f(0b0011), 0xbd, f(0b0001)); try testDaa(0x57, f(0b0100), 0x57, f(0b0100)); try testDaa(0x57, f(0b0101), 0xf7, f(0b0101)); try testDaa(0x57, f(0b0110), 0x51, f(0b0100)); try testDaa(0x57, f(0b0111), 0xf1, f(0b0101)); try testDaa(0x57, f(0b1000), 0x57, f(0b0000)); try testDaa(0x57, f(0b1001), 0xb7, f(0b0001)); try testDaa(0x57, f(0b1010), 0x5d, f(0b0000)); try testDaa(0x57, f(0b1011), 0xbd, f(0b0001)); try testDaa(0x57, f(0b1100), 0x57, f(0b0100)); try testDaa(0x57, f(0b1101), 0xf7, f(0b0101)); try testDaa(0x57, f(0b1110), 0x51, f(0b0100)); try testDaa(0x57, f(0b1111), 0xf1, f(0b0101)); try testDaa(0x58, f(0b0000), 0x58, f(0b0000)); try testDaa(0x58, f(0b0001), 0xb8, f(0b0001)); try testDaa(0x58, f(0b0010), 0x5e, f(0b0000)); try testDaa(0x58, f(0b0011), 0xbe, f(0b0001)); try testDaa(0x58, f(0b0100), 0x58, f(0b0100)); try testDaa(0x58, f(0b0101), 0xf8, f(0b0101)); try testDaa(0x58, f(0b0110), 0x52, f(0b0100)); try testDaa(0x58, f(0b0111), 0xf2, f(0b0101)); try testDaa(0x58, f(0b1000), 0x58, f(0b0000)); try testDaa(0x58, f(0b1001), 0xb8, f(0b0001)); try testDaa(0x58, f(0b1010), 0x5e, f(0b0000)); try testDaa(0x58, f(0b1011), 0xbe, f(0b0001)); try testDaa(0x58, f(0b1100), 0x58, f(0b0100)); try testDaa(0x58, f(0b1101), 0xf8, f(0b0101)); try testDaa(0x58, f(0b1110), 0x52, f(0b0100)); try testDaa(0x58, f(0b1111), 0xf2, f(0b0101)); try testDaa(0x59, f(0b0000), 0x59, f(0b0000)); try testDaa(0x59, f(0b0001), 0xb9, f(0b0001)); try testDaa(0x59, f(0b0010), 0x5f, f(0b0000)); try testDaa(0x59, f(0b0011), 0xbf, f(0b0001)); try testDaa(0x59, f(0b0100), 0x59, f(0b0100)); try testDaa(0x59, f(0b0101), 0xf9, f(0b0101)); try testDaa(0x59, f(0b0110), 0x53, f(0b0100)); try testDaa(0x59, f(0b0111), 0xf3, f(0b0101)); try testDaa(0x59, f(0b1000), 0x59, f(0b0000)); try testDaa(0x59, f(0b1001), 0xb9, f(0b0001)); try testDaa(0x59, f(0b1010), 0x5f, f(0b0000)); try testDaa(0x59, f(0b1011), 0xbf, f(0b0001)); try testDaa(0x59, f(0b1100), 0x59, f(0b0100)); try testDaa(0x59, f(0b1101), 0xf9, f(0b0101)); try testDaa(0x59, f(0b1110), 0x53, f(0b0100)); try testDaa(0x59, f(0b1111), 0xf3, f(0b0101)); try testDaa(0x5a, f(0b0000), 0x60, f(0b0000)); try testDaa(0x5a, f(0b0001), 0xc0, f(0b0001)); try testDaa(0x5a, f(0b0010), 0x60, f(0b0000)); try testDaa(0x5a, f(0b0011), 0xc0, f(0b0001)); try testDaa(0x5a, f(0b0100), 0x5a, f(0b0100)); try testDaa(0x5a, f(0b0101), 0xfa, f(0b0101)); try testDaa(0x5a, f(0b0110), 0x54, f(0b0100)); try testDaa(0x5a, f(0b0111), 0xf4, f(0b0101)); try testDaa(0x5a, f(0b1000), 0x60, f(0b0000)); try testDaa(0x5a, f(0b1001), 0xc0, f(0b0001)); try testDaa(0x5a, f(0b1010), 0x60, f(0b0000)); try testDaa(0x5a, f(0b1011), 0xc0, f(0b0001)); try testDaa(0x5a, f(0b1100), 0x5a, f(0b0100)); try testDaa(0x5a, f(0b1101), 0xfa, f(0b0101)); try testDaa(0x5a, f(0b1110), 0x54, f(0b0100)); try testDaa(0x5a, f(0b1111), 0xf4, f(0b0101)); try testDaa(0x5b, f(0b0000), 0x61, f(0b0000)); try testDaa(0x5b, f(0b0001), 0xc1, f(0b0001)); try testDaa(0x5b, f(0b0010), 0x61, f(0b0000)); try testDaa(0x5b, f(0b0011), 0xc1, f(0b0001)); try testDaa(0x5b, f(0b0100), 0x5b, f(0b0100)); try testDaa(0x5b, f(0b0101), 0xfb, f(0b0101)); try testDaa(0x5b, f(0b0110), 0x55, f(0b0100)); try testDaa(0x5b, f(0b0111), 0xf5, f(0b0101)); try testDaa(0x5b, f(0b1000), 0x61, f(0b0000)); try testDaa(0x5b, f(0b1001), 0xc1, f(0b0001)); try testDaa(0x5b, f(0b1010), 0x61, f(0b0000)); try testDaa(0x5b, f(0b1011), 0xc1, f(0b0001)); try testDaa(0x5b, f(0b1100), 0x5b, f(0b0100)); try testDaa(0x5b, f(0b1101), 0xfb, f(0b0101)); try testDaa(0x5b, f(0b1110), 0x55, f(0b0100)); try testDaa(0x5b, f(0b1111), 0xf5, f(0b0101)); try testDaa(0x5c, f(0b0000), 0x62, f(0b0000)); try testDaa(0x5c, f(0b0001), 0xc2, f(0b0001)); try testDaa(0x5c, f(0b0010), 0x62, f(0b0000)); try testDaa(0x5c, f(0b0011), 0xc2, f(0b0001)); try testDaa(0x5c, f(0b0100), 0x5c, f(0b0100)); try testDaa(0x5c, f(0b0101), 0xfc, f(0b0101)); try testDaa(0x5c, f(0b0110), 0x56, f(0b0100)); try testDaa(0x5c, f(0b0111), 0xf6, f(0b0101)); try testDaa(0x5c, f(0b1000), 0x62, f(0b0000)); try testDaa(0x5c, f(0b1001), 0xc2, f(0b0001)); try testDaa(0x5c, f(0b1010), 0x62, f(0b0000)); try testDaa(0x5c, f(0b1011), 0xc2, f(0b0001)); try testDaa(0x5c, f(0b1100), 0x5c, f(0b0100)); try testDaa(0x5c, f(0b1101), 0xfc, f(0b0101)); try testDaa(0x5c, f(0b1110), 0x56, f(0b0100)); try testDaa(0x5c, f(0b1111), 0xf6, f(0b0101)); try testDaa(0x5d, f(0b0000), 0x63, f(0b0000)); try testDaa(0x5d, f(0b0001), 0xc3, f(0b0001)); try testDaa(0x5d, f(0b0010), 0x63, f(0b0000)); try testDaa(0x5d, f(0b0011), 0xc3, f(0b0001)); try testDaa(0x5d, f(0b0100), 0x5d, f(0b0100)); try testDaa(0x5d, f(0b0101), 0xfd, f(0b0101)); try testDaa(0x5d, f(0b0110), 0x57, f(0b0100)); try testDaa(0x5d, f(0b0111), 0xf7, f(0b0101)); try testDaa(0x5d, f(0b1000), 0x63, f(0b0000)); try testDaa(0x5d, f(0b1001), 0xc3, f(0b0001)); try testDaa(0x5d, f(0b1010), 0x63, f(0b0000)); try testDaa(0x5d, f(0b1011), 0xc3, f(0b0001)); try testDaa(0x5d, f(0b1100), 0x5d, f(0b0100)); try testDaa(0x5d, f(0b1101), 0xfd, f(0b0101)); try testDaa(0x5d, f(0b1110), 0x57, f(0b0100)); try testDaa(0x5d, f(0b1111), 0xf7, f(0b0101)); try testDaa(0x5e, f(0b0000), 0x64, f(0b0000)); try testDaa(0x5e, f(0b0001), 0xc4, f(0b0001)); try testDaa(0x5e, f(0b0010), 0x64, f(0b0000)); try testDaa(0x5e, f(0b0011), 0xc4, f(0b0001)); try testDaa(0x5e, f(0b0100), 0x5e, f(0b0100)); try testDaa(0x5e, f(0b0101), 0xfe, f(0b0101)); try testDaa(0x5e, f(0b0110), 0x58, f(0b0100)); try testDaa(0x5e, f(0b0111), 0xf8, f(0b0101)); try testDaa(0x5e, f(0b1000), 0x64, f(0b0000)); try testDaa(0x5e, f(0b1001), 0xc4, f(0b0001)); try testDaa(0x5e, f(0b1010), 0x64, f(0b0000)); try testDaa(0x5e, f(0b1011), 0xc4, f(0b0001)); try testDaa(0x5e, f(0b1100), 0x5e, f(0b0100)); try testDaa(0x5e, f(0b1101), 0xfe, f(0b0101)); try testDaa(0x5e, f(0b1110), 0x58, f(0b0100)); try testDaa(0x5e, f(0b1111), 0xf8, f(0b0101)); try testDaa(0x5f, f(0b0000), 0x65, f(0b0000)); try testDaa(0x5f, f(0b0001), 0xc5, f(0b0001)); try testDaa(0x5f, f(0b0010), 0x65, f(0b0000)); try testDaa(0x5f, f(0b0011), 0xc5, f(0b0001)); try testDaa(0x5f, f(0b0100), 0x5f, f(0b0100)); try testDaa(0x5f, f(0b0101), 0xff, f(0b0101)); try testDaa(0x5f, f(0b0110), 0x59, f(0b0100)); try testDaa(0x5f, f(0b0111), 0xf9, f(0b0101)); try testDaa(0x5f, f(0b1000), 0x65, f(0b0000)); try testDaa(0x5f, f(0b1001), 0xc5, f(0b0001)); try testDaa(0x5f, f(0b1010), 0x65, f(0b0000)); try testDaa(0x5f, f(0b1011), 0xc5, f(0b0001)); try testDaa(0x5f, f(0b1100), 0x5f, f(0b0100)); try testDaa(0x5f, f(0b1101), 0xff, f(0b0101)); try testDaa(0x5f, f(0b1110), 0x59, f(0b0100)); try testDaa(0x5f, f(0b1111), 0xf9, f(0b0101)); try testDaa(0x60, f(0b0000), 0x60, f(0b0000)); try testDaa(0x60, f(0b0001), 0xc0, f(0b0001)); try testDaa(0x60, f(0b0010), 0x66, f(0b0000)); try testDaa(0x60, f(0b0011), 0xc6, f(0b0001)); try testDaa(0x60, f(0b0100), 0x60, f(0b0100)); try testDaa(0x60, f(0b0101), 0x00, f(0b1101)); try testDaa(0x60, f(0b0110), 0x5a, f(0b0100)); try testDaa(0x60, f(0b0111), 0xfa, f(0b0101)); try testDaa(0x60, f(0b1000), 0x60, f(0b0000)); try testDaa(0x60, f(0b1001), 0xc0, f(0b0001)); try testDaa(0x60, f(0b1010), 0x66, f(0b0000)); try testDaa(0x60, f(0b1011), 0xc6, f(0b0001)); try testDaa(0x60, f(0b1100), 0x60, f(0b0100)); try testDaa(0x60, f(0b1101), 0x00, f(0b1101)); try testDaa(0x60, f(0b1110), 0x5a, f(0b0100)); try testDaa(0x60, f(0b1111), 0xfa, f(0b0101)); try testDaa(0x61, f(0b0000), 0x61, f(0b0000)); try testDaa(0x61, f(0b0001), 0xc1, f(0b0001)); try testDaa(0x61, f(0b0010), 0x67, f(0b0000)); try testDaa(0x61, f(0b0011), 0xc7, f(0b0001)); try testDaa(0x61, f(0b0100), 0x61, f(0b0100)); try testDaa(0x61, f(0b0101), 0x01, f(0b0101)); try testDaa(0x61, f(0b0110), 0x5b, f(0b0100)); try testDaa(0x61, f(0b0111), 0xfb, f(0b0101)); try testDaa(0x61, f(0b1000), 0x61, f(0b0000)); try testDaa(0x61, f(0b1001), 0xc1, f(0b0001)); try testDaa(0x61, f(0b1010), 0x67, f(0b0000)); try testDaa(0x61, f(0b1011), 0xc7, f(0b0001)); try testDaa(0x61, f(0b1100), 0x61, f(0b0100)); try testDaa(0x61, f(0b1101), 0x01, f(0b0101)); try testDaa(0x61, f(0b1110), 0x5b, f(0b0100)); try testDaa(0x61, f(0b1111), 0xfb, f(0b0101)); try testDaa(0x62, f(0b0000), 0x62, f(0b0000)); try testDaa(0x62, f(0b0001), 0xc2, f(0b0001)); try testDaa(0x62, f(0b0010), 0x68, f(0b0000)); try testDaa(0x62, f(0b0011), 0xc8, f(0b0001)); try testDaa(0x62, f(0b0100), 0x62, f(0b0100)); try testDaa(0x62, f(0b0101), 0x02, f(0b0101)); try testDaa(0x62, f(0b0110), 0x5c, f(0b0100)); try testDaa(0x62, f(0b0111), 0xfc, f(0b0101)); try testDaa(0x62, f(0b1000), 0x62, f(0b0000)); try testDaa(0x62, f(0b1001), 0xc2, f(0b0001)); try testDaa(0x62, f(0b1010), 0x68, f(0b0000)); try testDaa(0x62, f(0b1011), 0xc8, f(0b0001)); try testDaa(0x62, f(0b1100), 0x62, f(0b0100)); try testDaa(0x62, f(0b1101), 0x02, f(0b0101)); try testDaa(0x62, f(0b1110), 0x5c, f(0b0100)); try testDaa(0x62, f(0b1111), 0xfc, f(0b0101)); try testDaa(0x63, f(0b0000), 0x63, f(0b0000)); try testDaa(0x63, f(0b0001), 0xc3, f(0b0001)); try testDaa(0x63, f(0b0010), 0x69, f(0b0000)); try testDaa(0x63, f(0b0011), 0xc9, f(0b0001)); try testDaa(0x63, f(0b0100), 0x63, f(0b0100)); try testDaa(0x63, f(0b0101), 0x03, f(0b0101)); try testDaa(0x63, f(0b0110), 0x5d, f(0b0100)); try testDaa(0x63, f(0b0111), 0xfd, f(0b0101)); try testDaa(0x63, f(0b1000), 0x63, f(0b0000)); try testDaa(0x63, f(0b1001), 0xc3, f(0b0001)); try testDaa(0x63, f(0b1010), 0x69, f(0b0000)); try testDaa(0x63, f(0b1011), 0xc9, f(0b0001)); try testDaa(0x63, f(0b1100), 0x63, f(0b0100)); try testDaa(0x63, f(0b1101), 0x03, f(0b0101)); try testDaa(0x63, f(0b1110), 0x5d, f(0b0100)); try testDaa(0x63, f(0b1111), 0xfd, f(0b0101)); try testDaa(0x64, f(0b0000), 0x64, f(0b0000)); try testDaa(0x64, f(0b0001), 0xc4, f(0b0001)); try testDaa(0x64, f(0b0010), 0x6a, f(0b0000)); try testDaa(0x64, f(0b0011), 0xca, f(0b0001)); try testDaa(0x64, f(0b0100), 0x64, f(0b0100)); try testDaa(0x64, f(0b0101), 0x04, f(0b0101)); try testDaa(0x64, f(0b0110), 0x5e, f(0b0100)); try testDaa(0x64, f(0b0111), 0xfe, f(0b0101)); try testDaa(0x64, f(0b1000), 0x64, f(0b0000)); try testDaa(0x64, f(0b1001), 0xc4, f(0b0001)); try testDaa(0x64, f(0b1010), 0x6a, f(0b0000)); try testDaa(0x64, f(0b1011), 0xca, f(0b0001)); try testDaa(0x64, f(0b1100), 0x64, f(0b0100)); try testDaa(0x64, f(0b1101), 0x04, f(0b0101)); try testDaa(0x64, f(0b1110), 0x5e, f(0b0100)); try testDaa(0x64, f(0b1111), 0xfe, f(0b0101)); try testDaa(0x65, f(0b0000), 0x65, f(0b0000)); try testDaa(0x65, f(0b0001), 0xc5, f(0b0001)); try testDaa(0x65, f(0b0010), 0x6b, f(0b0000)); try testDaa(0x65, f(0b0011), 0xcb, f(0b0001)); try testDaa(0x65, f(0b0100), 0x65, f(0b0100)); try testDaa(0x65, f(0b0101), 0x05, f(0b0101)); try testDaa(0x65, f(0b0110), 0x5f, f(0b0100)); try testDaa(0x65, f(0b0111), 0xff, f(0b0101)); try testDaa(0x65, f(0b1000), 0x65, f(0b0000)); try testDaa(0x65, f(0b1001), 0xc5, f(0b0001)); try testDaa(0x65, f(0b1010), 0x6b, f(0b0000)); try testDaa(0x65, f(0b1011), 0xcb, f(0b0001)); try testDaa(0x65, f(0b1100), 0x65, f(0b0100)); try testDaa(0x65, f(0b1101), 0x05, f(0b0101)); try testDaa(0x65, f(0b1110), 0x5f, f(0b0100)); try testDaa(0x65, f(0b1111), 0xff, f(0b0101)); try testDaa(0x66, f(0b0000), 0x66, f(0b0000)); try testDaa(0x66, f(0b0001), 0xc6, f(0b0001)); try testDaa(0x66, f(0b0010), 0x6c, f(0b0000)); try testDaa(0x66, f(0b0011), 0xcc, f(0b0001)); try testDaa(0x66, f(0b0100), 0x66, f(0b0100)); try testDaa(0x66, f(0b0101), 0x06, f(0b0101)); try testDaa(0x66, f(0b0110), 0x60, f(0b0100)); try testDaa(0x66, f(0b0111), 0x00, f(0b1101)); try testDaa(0x66, f(0b1000), 0x66, f(0b0000)); try testDaa(0x66, f(0b1001), 0xc6, f(0b0001)); try testDaa(0x66, f(0b1010), 0x6c, f(0b0000)); try testDaa(0x66, f(0b1011), 0xcc, f(0b0001)); try testDaa(0x66, f(0b1100), 0x66, f(0b0100)); try testDaa(0x66, f(0b1101), 0x06, f(0b0101)); try testDaa(0x66, f(0b1110), 0x60, f(0b0100)); try testDaa(0x66, f(0b1111), 0x00, f(0b1101)); try testDaa(0x67, f(0b0000), 0x67, f(0b0000)); try testDaa(0x67, f(0b0001), 0xc7, f(0b0001)); try testDaa(0x67, f(0b0010), 0x6d, f(0b0000)); try testDaa(0x67, f(0b0011), 0xcd, f(0b0001)); try testDaa(0x67, f(0b0100), 0x67, f(0b0100)); try testDaa(0x67, f(0b0101), 0x07, f(0b0101)); try testDaa(0x67, f(0b0110), 0x61, f(0b0100)); try testDaa(0x67, f(0b0111), 0x01, f(0b0101)); try testDaa(0x67, f(0b1000), 0x67, f(0b0000)); try testDaa(0x67, f(0b1001), 0xc7, f(0b0001)); try testDaa(0x67, f(0b1010), 0x6d, f(0b0000)); try testDaa(0x67, f(0b1011), 0xcd, f(0b0001)); try testDaa(0x67, f(0b1100), 0x67, f(0b0100)); try testDaa(0x67, f(0b1101), 0x07, f(0b0101)); try testDaa(0x67, f(0b1110), 0x61, f(0b0100)); try testDaa(0x67, f(0b1111), 0x01, f(0b0101)); try testDaa(0x68, f(0b0000), 0x68, f(0b0000)); try testDaa(0x68, f(0b0001), 0xc8, f(0b0001)); try testDaa(0x68, f(0b0010), 0x6e, f(0b0000)); try testDaa(0x68, f(0b0011), 0xce, f(0b0001)); try testDaa(0x68, f(0b0100), 0x68, f(0b0100)); try testDaa(0x68, f(0b0101), 0x08, f(0b0101)); try testDaa(0x68, f(0b0110), 0x62, f(0b0100)); try testDaa(0x68, f(0b0111), 0x02, f(0b0101)); try testDaa(0x68, f(0b1000), 0x68, f(0b0000)); try testDaa(0x68, f(0b1001), 0xc8, f(0b0001)); try testDaa(0x68, f(0b1010), 0x6e, f(0b0000)); try testDaa(0x68, f(0b1011), 0xce, f(0b0001)); try testDaa(0x68, f(0b1100), 0x68, f(0b0100)); try testDaa(0x68, f(0b1101), 0x08, f(0b0101)); try testDaa(0x68, f(0b1110), 0x62, f(0b0100)); try testDaa(0x68, f(0b1111), 0x02, f(0b0101)); try testDaa(0x69, f(0b0000), 0x69, f(0b0000)); try testDaa(0x69, f(0b0001), 0xc9, f(0b0001)); try testDaa(0x69, f(0b0010), 0x6f, f(0b0000)); try testDaa(0x69, f(0b0011), 0xcf, f(0b0001)); try testDaa(0x69, f(0b0100), 0x69, f(0b0100)); try testDaa(0x69, f(0b0101), 0x09, f(0b0101)); try testDaa(0x69, f(0b0110), 0x63, f(0b0100)); try testDaa(0x69, f(0b0111), 0x03, f(0b0101)); try testDaa(0x69, f(0b1000), 0x69, f(0b0000)); try testDaa(0x69, f(0b1001), 0xc9, f(0b0001)); try testDaa(0x69, f(0b1010), 0x6f, f(0b0000)); try testDaa(0x69, f(0b1011), 0xcf, f(0b0001)); try testDaa(0x69, f(0b1100), 0x69, f(0b0100)); try testDaa(0x69, f(0b1101), 0x09, f(0b0101)); try testDaa(0x69, f(0b1110), 0x63, f(0b0100)); try testDaa(0x69, f(0b1111), 0x03, f(0b0101)); try testDaa(0x6a, f(0b0000), 0x70, f(0b0000)); try testDaa(0x6a, f(0b0001), 0xd0, f(0b0001)); try testDaa(0x6a, f(0b0010), 0x70, f(0b0000)); try testDaa(0x6a, f(0b0011), 0xd0, f(0b0001)); try testDaa(0x6a, f(0b0100), 0x6a, f(0b0100)); try testDaa(0x6a, f(0b0101), 0x0a, f(0b0101)); try testDaa(0x6a, f(0b0110), 0x64, f(0b0100)); try testDaa(0x6a, f(0b0111), 0x04, f(0b0101)); try testDaa(0x6a, f(0b1000), 0x70, f(0b0000)); try testDaa(0x6a, f(0b1001), 0xd0, f(0b0001)); try testDaa(0x6a, f(0b1010), 0x70, f(0b0000)); try testDaa(0x6a, f(0b1011), 0xd0, f(0b0001)); try testDaa(0x6a, f(0b1100), 0x6a, f(0b0100)); try testDaa(0x6a, f(0b1101), 0x0a, f(0b0101)); try testDaa(0x6a, f(0b1110), 0x64, f(0b0100)); try testDaa(0x6a, f(0b1111), 0x04, f(0b0101)); try testDaa(0x6b, f(0b0000), 0x71, f(0b0000)); try testDaa(0x6b, f(0b0001), 0xd1, f(0b0001)); try testDaa(0x6b, f(0b0010), 0x71, f(0b0000)); try testDaa(0x6b, f(0b0011), 0xd1, f(0b0001)); try testDaa(0x6b, f(0b0100), 0x6b, f(0b0100)); try testDaa(0x6b, f(0b0101), 0x0b, f(0b0101)); try testDaa(0x6b, f(0b0110), 0x65, f(0b0100)); try testDaa(0x6b, f(0b0111), 0x05, f(0b0101)); try testDaa(0x6b, f(0b1000), 0x71, f(0b0000)); try testDaa(0x6b, f(0b1001), 0xd1, f(0b0001)); try testDaa(0x6b, f(0b1010), 0x71, f(0b0000)); try testDaa(0x6b, f(0b1011), 0xd1, f(0b0001)); try testDaa(0x6b, f(0b1100), 0x6b, f(0b0100)); try testDaa(0x6b, f(0b1101), 0x0b, f(0b0101)); try testDaa(0x6b, f(0b1110), 0x65, f(0b0100)); try testDaa(0x6b, f(0b1111), 0x05, f(0b0101)); try testDaa(0x6c, f(0b0000), 0x72, f(0b0000)); try testDaa(0x6c, f(0b0001), 0xd2, f(0b0001)); try testDaa(0x6c, f(0b0010), 0x72, f(0b0000)); try testDaa(0x6c, f(0b0011), 0xd2, f(0b0001)); try testDaa(0x6c, f(0b0100), 0x6c, f(0b0100)); try testDaa(0x6c, f(0b0101), 0x0c, f(0b0101)); try testDaa(0x6c, f(0b0110), 0x66, f(0b0100)); try testDaa(0x6c, f(0b0111), 0x06, f(0b0101)); try testDaa(0x6c, f(0b1000), 0x72, f(0b0000)); try testDaa(0x6c, f(0b1001), 0xd2, f(0b0001)); try testDaa(0x6c, f(0b1010), 0x72, f(0b0000)); try testDaa(0x6c, f(0b1011), 0xd2, f(0b0001)); try testDaa(0x6c, f(0b1100), 0x6c, f(0b0100)); try testDaa(0x6c, f(0b1101), 0x0c, f(0b0101)); try testDaa(0x6c, f(0b1110), 0x66, f(0b0100)); try testDaa(0x6c, f(0b1111), 0x06, f(0b0101)); try testDaa(0x6d, f(0b0000), 0x73, f(0b0000)); try testDaa(0x6d, f(0b0001), 0xd3, f(0b0001)); try testDaa(0x6d, f(0b0010), 0x73, f(0b0000)); try testDaa(0x6d, f(0b0011), 0xd3, f(0b0001)); try testDaa(0x6d, f(0b0100), 0x6d, f(0b0100)); try testDaa(0x6d, f(0b0101), 0x0d, f(0b0101)); try testDaa(0x6d, f(0b0110), 0x67, f(0b0100)); try testDaa(0x6d, f(0b0111), 0x07, f(0b0101)); try testDaa(0x6d, f(0b1000), 0x73, f(0b0000)); try testDaa(0x6d, f(0b1001), 0xd3, f(0b0001)); try testDaa(0x6d, f(0b1010), 0x73, f(0b0000)); try testDaa(0x6d, f(0b1011), 0xd3, f(0b0001)); try testDaa(0x6d, f(0b1100), 0x6d, f(0b0100)); try testDaa(0x6d, f(0b1101), 0x0d, f(0b0101)); try testDaa(0x6d, f(0b1110), 0x67, f(0b0100)); try testDaa(0x6d, f(0b1111), 0x07, f(0b0101)); try testDaa(0x6e, f(0b0000), 0x74, f(0b0000)); try testDaa(0x6e, f(0b0001), 0xd4, f(0b0001)); try testDaa(0x6e, f(0b0010), 0x74, f(0b0000)); try testDaa(0x6e, f(0b0011), 0xd4, f(0b0001)); try testDaa(0x6e, f(0b0100), 0x6e, f(0b0100)); try testDaa(0x6e, f(0b0101), 0x0e, f(0b0101)); try testDaa(0x6e, f(0b0110), 0x68, f(0b0100)); try testDaa(0x6e, f(0b0111), 0x08, f(0b0101)); try testDaa(0x6e, f(0b1000), 0x74, f(0b0000)); try testDaa(0x6e, f(0b1001), 0xd4, f(0b0001)); try testDaa(0x6e, f(0b1010), 0x74, f(0b0000)); try testDaa(0x6e, f(0b1011), 0xd4, f(0b0001)); try testDaa(0x6e, f(0b1100), 0x6e, f(0b0100)); try testDaa(0x6e, f(0b1101), 0x0e, f(0b0101)); try testDaa(0x6e, f(0b1110), 0x68, f(0b0100)); try testDaa(0x6e, f(0b1111), 0x08, f(0b0101)); try testDaa(0x6f, f(0b0000), 0x75, f(0b0000)); try testDaa(0x6f, f(0b0001), 0xd5, f(0b0001)); try testDaa(0x6f, f(0b0010), 0x75, f(0b0000)); try testDaa(0x6f, f(0b0011), 0xd5, f(0b0001)); try testDaa(0x6f, f(0b0100), 0x6f, f(0b0100)); try testDaa(0x6f, f(0b0101), 0x0f, f(0b0101)); try testDaa(0x6f, f(0b0110), 0x69, f(0b0100)); try testDaa(0x6f, f(0b0111), 0x09, f(0b0101)); try testDaa(0x6f, f(0b1000), 0x75, f(0b0000)); try testDaa(0x6f, f(0b1001), 0xd5, f(0b0001)); try testDaa(0x6f, f(0b1010), 0x75, f(0b0000)); try testDaa(0x6f, f(0b1011), 0xd5, f(0b0001)); try testDaa(0x6f, f(0b1100), 0x6f, f(0b0100)); try testDaa(0x6f, f(0b1101), 0x0f, f(0b0101)); try testDaa(0x6f, f(0b1110), 0x69, f(0b0100)); try testDaa(0x6f, f(0b1111), 0x09, f(0b0101)); try testDaa(0x70, f(0b0000), 0x70, f(0b0000)); try testDaa(0x70, f(0b0001), 0xd0, f(0b0001)); try testDaa(0x70, f(0b0010), 0x76, f(0b0000)); try testDaa(0x70, f(0b0011), 0xd6, f(0b0001)); try testDaa(0x70, f(0b0100), 0x70, f(0b0100)); try testDaa(0x70, f(0b0101), 0x10, f(0b0101)); try testDaa(0x70, f(0b0110), 0x6a, f(0b0100)); try testDaa(0x70, f(0b0111), 0x0a, f(0b0101)); try testDaa(0x70, f(0b1000), 0x70, f(0b0000)); try testDaa(0x70, f(0b1001), 0xd0, f(0b0001)); try testDaa(0x70, f(0b1010), 0x76, f(0b0000)); try testDaa(0x70, f(0b1011), 0xd6, f(0b0001)); try testDaa(0x70, f(0b1100), 0x70, f(0b0100)); try testDaa(0x70, f(0b1101), 0x10, f(0b0101)); try testDaa(0x70, f(0b1110), 0x6a, f(0b0100)); try testDaa(0x70, f(0b1111), 0x0a, f(0b0101)); try testDaa(0x71, f(0b0000), 0x71, f(0b0000)); try testDaa(0x71, f(0b0001), 0xd1, f(0b0001)); try testDaa(0x71, f(0b0010), 0x77, f(0b0000)); try testDaa(0x71, f(0b0011), 0xd7, f(0b0001)); try testDaa(0x71, f(0b0100), 0x71, f(0b0100)); try testDaa(0x71, f(0b0101), 0x11, f(0b0101)); try testDaa(0x71, f(0b0110), 0x6b, f(0b0100)); try testDaa(0x71, f(0b0111), 0x0b, f(0b0101)); try testDaa(0x71, f(0b1000), 0x71, f(0b0000)); try testDaa(0x71, f(0b1001), 0xd1, f(0b0001)); try testDaa(0x71, f(0b1010), 0x77, f(0b0000)); try testDaa(0x71, f(0b1011), 0xd7, f(0b0001)); try testDaa(0x71, f(0b1100), 0x71, f(0b0100)); try testDaa(0x71, f(0b1101), 0x11, f(0b0101)); try testDaa(0x71, f(0b1110), 0x6b, f(0b0100)); try testDaa(0x71, f(0b1111), 0x0b, f(0b0101)); try testDaa(0x72, f(0b0000), 0x72, f(0b0000)); try testDaa(0x72, f(0b0001), 0xd2, f(0b0001)); try testDaa(0x72, f(0b0010), 0x78, f(0b0000)); try testDaa(0x72, f(0b0011), 0xd8, f(0b0001)); try testDaa(0x72, f(0b0100), 0x72, f(0b0100)); try testDaa(0x72, f(0b0101), 0x12, f(0b0101)); try testDaa(0x72, f(0b0110), 0x6c, f(0b0100)); try testDaa(0x72, f(0b0111), 0x0c, f(0b0101)); try testDaa(0x72, f(0b1000), 0x72, f(0b0000)); try testDaa(0x72, f(0b1001), 0xd2, f(0b0001)); try testDaa(0x72, f(0b1010), 0x78, f(0b0000)); try testDaa(0x72, f(0b1011), 0xd8, f(0b0001)); try testDaa(0x72, f(0b1100), 0x72, f(0b0100)); try testDaa(0x72, f(0b1101), 0x12, f(0b0101)); try testDaa(0x72, f(0b1110), 0x6c, f(0b0100)); try testDaa(0x72, f(0b1111), 0x0c, f(0b0101)); try testDaa(0x73, f(0b0000), 0x73, f(0b0000)); try testDaa(0x73, f(0b0001), 0xd3, f(0b0001)); try testDaa(0x73, f(0b0010), 0x79, f(0b0000)); try testDaa(0x73, f(0b0011), 0xd9, f(0b0001)); try testDaa(0x73, f(0b0100), 0x73, f(0b0100)); try testDaa(0x73, f(0b0101), 0x13, f(0b0101)); try testDaa(0x73, f(0b0110), 0x6d, f(0b0100)); try testDaa(0x73, f(0b0111), 0x0d, f(0b0101)); try testDaa(0x73, f(0b1000), 0x73, f(0b0000)); try testDaa(0x73, f(0b1001), 0xd3, f(0b0001)); try testDaa(0x73, f(0b1010), 0x79, f(0b0000)); try testDaa(0x73, f(0b1011), 0xd9, f(0b0001)); try testDaa(0x73, f(0b1100), 0x73, f(0b0100)); try testDaa(0x73, f(0b1101), 0x13, f(0b0101)); try testDaa(0x73, f(0b1110), 0x6d, f(0b0100)); try testDaa(0x73, f(0b1111), 0x0d, f(0b0101)); try testDaa(0x74, f(0b0000), 0x74, f(0b0000)); try testDaa(0x74, f(0b0001), 0xd4, f(0b0001)); try testDaa(0x74, f(0b0010), 0x7a, f(0b0000)); try testDaa(0x74, f(0b0011), 0xda, f(0b0001)); try testDaa(0x74, f(0b0100), 0x74, f(0b0100)); try testDaa(0x74, f(0b0101), 0x14, f(0b0101)); try testDaa(0x74, f(0b0110), 0x6e, f(0b0100)); try testDaa(0x74, f(0b0111), 0x0e, f(0b0101)); try testDaa(0x74, f(0b1000), 0x74, f(0b0000)); try testDaa(0x74, f(0b1001), 0xd4, f(0b0001)); try testDaa(0x74, f(0b1010), 0x7a, f(0b0000)); try testDaa(0x74, f(0b1011), 0xda, f(0b0001)); try testDaa(0x74, f(0b1100), 0x74, f(0b0100)); try testDaa(0x74, f(0b1101), 0x14, f(0b0101)); try testDaa(0x74, f(0b1110), 0x6e, f(0b0100)); try testDaa(0x74, f(0b1111), 0x0e, f(0b0101)); try testDaa(0x75, f(0b0000), 0x75, f(0b0000)); try testDaa(0x75, f(0b0001), 0xd5, f(0b0001)); try testDaa(0x75, f(0b0010), 0x7b, f(0b0000)); try testDaa(0x75, f(0b0011), 0xdb, f(0b0001)); try testDaa(0x75, f(0b0100), 0x75, f(0b0100)); try testDaa(0x75, f(0b0101), 0x15, f(0b0101)); try testDaa(0x75, f(0b0110), 0x6f, f(0b0100)); try testDaa(0x75, f(0b0111), 0x0f, f(0b0101)); try testDaa(0x75, f(0b1000), 0x75, f(0b0000)); try testDaa(0x75, f(0b1001), 0xd5, f(0b0001)); try testDaa(0x75, f(0b1010), 0x7b, f(0b0000)); try testDaa(0x75, f(0b1011), 0xdb, f(0b0001)); try testDaa(0x75, f(0b1100), 0x75, f(0b0100)); try testDaa(0x75, f(0b1101), 0x15, f(0b0101)); try testDaa(0x75, f(0b1110), 0x6f, f(0b0100)); try testDaa(0x75, f(0b1111), 0x0f, f(0b0101)); try testDaa(0x76, f(0b0000), 0x76, f(0b0000)); try testDaa(0x76, f(0b0001), 0xd6, f(0b0001)); try testDaa(0x76, f(0b0010), 0x7c, f(0b0000)); try testDaa(0x76, f(0b0011), 0xdc, f(0b0001)); try testDaa(0x76, f(0b0100), 0x76, f(0b0100)); try testDaa(0x76, f(0b0101), 0x16, f(0b0101)); try testDaa(0x76, f(0b0110), 0x70, f(0b0100)); try testDaa(0x76, f(0b0111), 0x10, f(0b0101)); try testDaa(0x76, f(0b1000), 0x76, f(0b0000)); try testDaa(0x76, f(0b1001), 0xd6, f(0b0001)); try testDaa(0x76, f(0b1010), 0x7c, f(0b0000)); try testDaa(0x76, f(0b1011), 0xdc, f(0b0001)); try testDaa(0x76, f(0b1100), 0x76, f(0b0100)); try testDaa(0x76, f(0b1101), 0x16, f(0b0101)); try testDaa(0x76, f(0b1110), 0x70, f(0b0100)); try testDaa(0x76, f(0b1111), 0x10, f(0b0101)); try testDaa(0x77, f(0b0000), 0x77, f(0b0000)); try testDaa(0x77, f(0b0001), 0xd7, f(0b0001)); try testDaa(0x77, f(0b0010), 0x7d, f(0b0000)); try testDaa(0x77, f(0b0011), 0xdd, f(0b0001)); try testDaa(0x77, f(0b0100), 0x77, f(0b0100)); try testDaa(0x77, f(0b0101), 0x17, f(0b0101)); try testDaa(0x77, f(0b0110), 0x71, f(0b0100)); try testDaa(0x77, f(0b0111), 0x11, f(0b0101)); try testDaa(0x77, f(0b1000), 0x77, f(0b0000)); try testDaa(0x77, f(0b1001), 0xd7, f(0b0001)); try testDaa(0x77, f(0b1010), 0x7d, f(0b0000)); try testDaa(0x77, f(0b1011), 0xdd, f(0b0001)); try testDaa(0x77, f(0b1100), 0x77, f(0b0100)); try testDaa(0x77, f(0b1101), 0x17, f(0b0101)); try testDaa(0x77, f(0b1110), 0x71, f(0b0100)); try testDaa(0x77, f(0b1111), 0x11, f(0b0101)); try testDaa(0x78, f(0b0000), 0x78, f(0b0000)); try testDaa(0x78, f(0b0001), 0xd8, f(0b0001)); try testDaa(0x78, f(0b0010), 0x7e, f(0b0000)); try testDaa(0x78, f(0b0011), 0xde, f(0b0001)); try testDaa(0x78, f(0b0100), 0x78, f(0b0100)); try testDaa(0x78, f(0b0101), 0x18, f(0b0101)); try testDaa(0x78, f(0b0110), 0x72, f(0b0100)); try testDaa(0x78, f(0b0111), 0x12, f(0b0101)); try testDaa(0x78, f(0b1000), 0x78, f(0b0000)); try testDaa(0x78, f(0b1001), 0xd8, f(0b0001)); try testDaa(0x78, f(0b1010), 0x7e, f(0b0000)); try testDaa(0x78, f(0b1011), 0xde, f(0b0001)); try testDaa(0x78, f(0b1100), 0x78, f(0b0100)); try testDaa(0x78, f(0b1101), 0x18, f(0b0101)); try testDaa(0x78, f(0b1110), 0x72, f(0b0100)); try testDaa(0x78, f(0b1111), 0x12, f(0b0101)); try testDaa(0x79, f(0b0000), 0x79, f(0b0000)); try testDaa(0x79, f(0b0001), 0xd9, f(0b0001)); try testDaa(0x79, f(0b0010), 0x7f, f(0b0000)); try testDaa(0x79, f(0b0011), 0xdf, f(0b0001)); try testDaa(0x79, f(0b0100), 0x79, f(0b0100)); try testDaa(0x79, f(0b0101), 0x19, f(0b0101)); try testDaa(0x79, f(0b0110), 0x73, f(0b0100)); try testDaa(0x79, f(0b0111), 0x13, f(0b0101)); try testDaa(0x79, f(0b1000), 0x79, f(0b0000)); try testDaa(0x79, f(0b1001), 0xd9, f(0b0001)); try testDaa(0x79, f(0b1010), 0x7f, f(0b0000)); try testDaa(0x79, f(0b1011), 0xdf, f(0b0001)); try testDaa(0x79, f(0b1100), 0x79, f(0b0100)); try testDaa(0x79, f(0b1101), 0x19, f(0b0101)); try testDaa(0x79, f(0b1110), 0x73, f(0b0100)); try testDaa(0x79, f(0b1111), 0x13, f(0b0101)); try testDaa(0x7a, f(0b0000), 0x80, f(0b0000)); try testDaa(0x7a, f(0b0001), 0xe0, f(0b0001)); try testDaa(0x7a, f(0b0010), 0x80, f(0b0000)); try testDaa(0x7a, f(0b0011), 0xe0, f(0b0001)); try testDaa(0x7a, f(0b0100), 0x7a, f(0b0100)); try testDaa(0x7a, f(0b0101), 0x1a, f(0b0101)); try testDaa(0x7a, f(0b0110), 0x74, f(0b0100)); try testDaa(0x7a, f(0b0111), 0x14, f(0b0101)); try testDaa(0x7a, f(0b1000), 0x80, f(0b0000)); try testDaa(0x7a, f(0b1001), 0xe0, f(0b0001)); try testDaa(0x7a, f(0b1010), 0x80, f(0b0000)); try testDaa(0x7a, f(0b1011), 0xe0, f(0b0001)); try testDaa(0x7a, f(0b1100), 0x7a, f(0b0100)); try testDaa(0x7a, f(0b1101), 0x1a, f(0b0101)); try testDaa(0x7a, f(0b1110), 0x74, f(0b0100)); try testDaa(0x7a, f(0b1111), 0x14, f(0b0101)); try testDaa(0x7b, f(0b0000), 0x81, f(0b0000)); try testDaa(0x7b, f(0b0001), 0xe1, f(0b0001)); try testDaa(0x7b, f(0b0010), 0x81, f(0b0000)); try testDaa(0x7b, f(0b0011), 0xe1, f(0b0001)); try testDaa(0x7b, f(0b0100), 0x7b, f(0b0100)); try testDaa(0x7b, f(0b0101), 0x1b, f(0b0101)); try testDaa(0x7b, f(0b0110), 0x75, f(0b0100)); try testDaa(0x7b, f(0b0111), 0x15, f(0b0101)); try testDaa(0x7b, f(0b1000), 0x81, f(0b0000)); try testDaa(0x7b, f(0b1001), 0xe1, f(0b0001)); try testDaa(0x7b, f(0b1010), 0x81, f(0b0000)); try testDaa(0x7b, f(0b1011), 0xe1, f(0b0001)); try testDaa(0x7b, f(0b1100), 0x7b, f(0b0100)); try testDaa(0x7b, f(0b1101), 0x1b, f(0b0101)); try testDaa(0x7b, f(0b1110), 0x75, f(0b0100)); try testDaa(0x7b, f(0b1111), 0x15, f(0b0101)); try testDaa(0x7c, f(0b0000), 0x82, f(0b0000)); try testDaa(0x7c, f(0b0001), 0xe2, f(0b0001)); try testDaa(0x7c, f(0b0010), 0x82, f(0b0000)); try testDaa(0x7c, f(0b0011), 0xe2, f(0b0001)); try testDaa(0x7c, f(0b0100), 0x7c, f(0b0100)); try testDaa(0x7c, f(0b0101), 0x1c, f(0b0101)); try testDaa(0x7c, f(0b0110), 0x76, f(0b0100)); try testDaa(0x7c, f(0b0111), 0x16, f(0b0101)); try testDaa(0x7c, f(0b1000), 0x82, f(0b0000)); try testDaa(0x7c, f(0b1001), 0xe2, f(0b0001)); try testDaa(0x7c, f(0b1010), 0x82, f(0b0000)); try testDaa(0x7c, f(0b1011), 0xe2, f(0b0001)); try testDaa(0x7c, f(0b1100), 0x7c, f(0b0100)); try testDaa(0x7c, f(0b1101), 0x1c, f(0b0101)); try testDaa(0x7c, f(0b1110), 0x76, f(0b0100)); try testDaa(0x7c, f(0b1111), 0x16, f(0b0101)); try testDaa(0x7d, f(0b0000), 0x83, f(0b0000)); try testDaa(0x7d, f(0b0001), 0xe3, f(0b0001)); try testDaa(0x7d, f(0b0010), 0x83, f(0b0000)); try testDaa(0x7d, f(0b0011), 0xe3, f(0b0001)); try testDaa(0x7d, f(0b0100), 0x7d, f(0b0100)); try testDaa(0x7d, f(0b0101), 0x1d, f(0b0101)); try testDaa(0x7d, f(0b0110), 0x77, f(0b0100)); try testDaa(0x7d, f(0b0111), 0x17, f(0b0101)); try testDaa(0x7d, f(0b1000), 0x83, f(0b0000)); try testDaa(0x7d, f(0b1001), 0xe3, f(0b0001)); try testDaa(0x7d, f(0b1010), 0x83, f(0b0000)); try testDaa(0x7d, f(0b1011), 0xe3, f(0b0001)); try testDaa(0x7d, f(0b1100), 0x7d, f(0b0100)); try testDaa(0x7d, f(0b1101), 0x1d, f(0b0101)); try testDaa(0x7d, f(0b1110), 0x77, f(0b0100)); try testDaa(0x7d, f(0b1111), 0x17, f(0b0101)); try testDaa(0x7e, f(0b0000), 0x84, f(0b0000)); try testDaa(0x7e, f(0b0001), 0xe4, f(0b0001)); try testDaa(0x7e, f(0b0010), 0x84, f(0b0000)); try testDaa(0x7e, f(0b0011), 0xe4, f(0b0001)); try testDaa(0x7e, f(0b0100), 0x7e, f(0b0100)); try testDaa(0x7e, f(0b0101), 0x1e, f(0b0101)); try testDaa(0x7e, f(0b0110), 0x78, f(0b0100)); try testDaa(0x7e, f(0b0111), 0x18, f(0b0101)); try testDaa(0x7e, f(0b1000), 0x84, f(0b0000)); try testDaa(0x7e, f(0b1001), 0xe4, f(0b0001)); try testDaa(0x7e, f(0b1010), 0x84, f(0b0000)); try testDaa(0x7e, f(0b1011), 0xe4, f(0b0001)); try testDaa(0x7e, f(0b1100), 0x7e, f(0b0100)); try testDaa(0x7e, f(0b1101), 0x1e, f(0b0101)); try testDaa(0x7e, f(0b1110), 0x78, f(0b0100)); try testDaa(0x7e, f(0b1111), 0x18, f(0b0101)); try testDaa(0x7f, f(0b0000), 0x85, f(0b0000)); try testDaa(0x7f, f(0b0001), 0xe5, f(0b0001)); try testDaa(0x7f, f(0b0010), 0x85, f(0b0000)); try testDaa(0x7f, f(0b0011), 0xe5, f(0b0001)); try testDaa(0x7f, f(0b0100), 0x7f, f(0b0100)); try testDaa(0x7f, f(0b0101), 0x1f, f(0b0101)); try testDaa(0x7f, f(0b0110), 0x79, f(0b0100)); try testDaa(0x7f, f(0b0111), 0x19, f(0b0101)); try testDaa(0x7f, f(0b1000), 0x85, f(0b0000)); try testDaa(0x7f, f(0b1001), 0xe5, f(0b0001)); try testDaa(0x7f, f(0b1010), 0x85, f(0b0000)); try testDaa(0x7f, f(0b1011), 0xe5, f(0b0001)); try testDaa(0x7f, f(0b1100), 0x7f, f(0b0100)); try testDaa(0x7f, f(0b1101), 0x1f, f(0b0101)); try testDaa(0x7f, f(0b1110), 0x79, f(0b0100)); try testDaa(0x7f, f(0b1111), 0x19, f(0b0101)); try testDaa(0x80, f(0b0000), 0x80, f(0b0000)); try testDaa(0x80, f(0b0001), 0xe0, f(0b0001)); try testDaa(0x80, f(0b0010), 0x86, f(0b0000)); try testDaa(0x80, f(0b0011), 0xe6, f(0b0001)); try testDaa(0x80, f(0b0100), 0x80, f(0b0100)); try testDaa(0x80, f(0b0101), 0x20, f(0b0101)); try testDaa(0x80, f(0b0110), 0x7a, f(0b0100)); try testDaa(0x80, f(0b0111), 0x1a, f(0b0101)); try testDaa(0x80, f(0b1000), 0x80, f(0b0000)); try testDaa(0x80, f(0b1001), 0xe0, f(0b0001)); try testDaa(0x80, f(0b1010), 0x86, f(0b0000)); try testDaa(0x80, f(0b1011), 0xe6, f(0b0001)); try testDaa(0x80, f(0b1100), 0x80, f(0b0100)); try testDaa(0x80, f(0b1101), 0x20, f(0b0101)); try testDaa(0x80, f(0b1110), 0x7a, f(0b0100)); try testDaa(0x80, f(0b1111), 0x1a, f(0b0101)); try testDaa(0x81, f(0b0000), 0x81, f(0b0000)); try testDaa(0x81, f(0b0001), 0xe1, f(0b0001)); try testDaa(0x81, f(0b0010), 0x87, f(0b0000)); try testDaa(0x81, f(0b0011), 0xe7, f(0b0001)); try testDaa(0x81, f(0b0100), 0x81, f(0b0100)); try testDaa(0x81, f(0b0101), 0x21, f(0b0101)); try testDaa(0x81, f(0b0110), 0x7b, f(0b0100)); try testDaa(0x81, f(0b0111), 0x1b, f(0b0101)); try testDaa(0x81, f(0b1000), 0x81, f(0b0000)); try testDaa(0x81, f(0b1001), 0xe1, f(0b0001)); try testDaa(0x81, f(0b1010), 0x87, f(0b0000)); try testDaa(0x81, f(0b1011), 0xe7, f(0b0001)); try testDaa(0x81, f(0b1100), 0x81, f(0b0100)); try testDaa(0x81, f(0b1101), 0x21, f(0b0101)); try testDaa(0x81, f(0b1110), 0x7b, f(0b0100)); try testDaa(0x81, f(0b1111), 0x1b, f(0b0101)); try testDaa(0x82, f(0b0000), 0x82, f(0b0000)); try testDaa(0x82, f(0b0001), 0xe2, f(0b0001)); try testDaa(0x82, f(0b0010), 0x88, f(0b0000)); try testDaa(0x82, f(0b0011), 0xe8, f(0b0001)); try testDaa(0x82, f(0b0100), 0x82, f(0b0100)); try testDaa(0x82, f(0b0101), 0x22, f(0b0101)); try testDaa(0x82, f(0b0110), 0x7c, f(0b0100)); try testDaa(0x82, f(0b0111), 0x1c, f(0b0101)); try testDaa(0x82, f(0b1000), 0x82, f(0b0000)); try testDaa(0x82, f(0b1001), 0xe2, f(0b0001)); try testDaa(0x82, f(0b1010), 0x88, f(0b0000)); try testDaa(0x82, f(0b1011), 0xe8, f(0b0001)); try testDaa(0x82, f(0b1100), 0x82, f(0b0100)); try testDaa(0x82, f(0b1101), 0x22, f(0b0101)); try testDaa(0x82, f(0b1110), 0x7c, f(0b0100)); try testDaa(0x82, f(0b1111), 0x1c, f(0b0101)); try testDaa(0x83, f(0b0000), 0x83, f(0b0000)); try testDaa(0x83, f(0b0001), 0xe3, f(0b0001)); try testDaa(0x83, f(0b0010), 0x89, f(0b0000)); try testDaa(0x83, f(0b0011), 0xe9, f(0b0001)); try testDaa(0x83, f(0b0100), 0x83, f(0b0100)); try testDaa(0x83, f(0b0101), 0x23, f(0b0101)); try testDaa(0x83, f(0b0110), 0x7d, f(0b0100)); try testDaa(0x83, f(0b0111), 0x1d, f(0b0101)); try testDaa(0x83, f(0b1000), 0x83, f(0b0000)); try testDaa(0x83, f(0b1001), 0xe3, f(0b0001)); try testDaa(0x83, f(0b1010), 0x89, f(0b0000)); try testDaa(0x83, f(0b1011), 0xe9, f(0b0001)); try testDaa(0x83, f(0b1100), 0x83, f(0b0100)); try testDaa(0x83, f(0b1101), 0x23, f(0b0101)); try testDaa(0x83, f(0b1110), 0x7d, f(0b0100)); try testDaa(0x83, f(0b1111), 0x1d, f(0b0101)); try testDaa(0x84, f(0b0000), 0x84, f(0b0000)); try testDaa(0x84, f(0b0001), 0xe4, f(0b0001)); try testDaa(0x84, f(0b0010), 0x8a, f(0b0000)); try testDaa(0x84, f(0b0011), 0xea, f(0b0001)); try testDaa(0x84, f(0b0100), 0x84, f(0b0100)); try testDaa(0x84, f(0b0101), 0x24, f(0b0101)); try testDaa(0x84, f(0b0110), 0x7e, f(0b0100)); try testDaa(0x84, f(0b0111), 0x1e, f(0b0101)); try testDaa(0x84, f(0b1000), 0x84, f(0b0000)); try testDaa(0x84, f(0b1001), 0xe4, f(0b0001)); try testDaa(0x84, f(0b1010), 0x8a, f(0b0000)); try testDaa(0x84, f(0b1011), 0xea, f(0b0001)); try testDaa(0x84, f(0b1100), 0x84, f(0b0100)); try testDaa(0x84, f(0b1101), 0x24, f(0b0101)); try testDaa(0x84, f(0b1110), 0x7e, f(0b0100)); try testDaa(0x84, f(0b1111), 0x1e, f(0b0101)); try testDaa(0x85, f(0b0000), 0x85, f(0b0000)); try testDaa(0x85, f(0b0001), 0xe5, f(0b0001)); try testDaa(0x85, f(0b0010), 0x8b, f(0b0000)); try testDaa(0x85, f(0b0011), 0xeb, f(0b0001)); try testDaa(0x85, f(0b0100), 0x85, f(0b0100)); try testDaa(0x85, f(0b0101), 0x25, f(0b0101)); try testDaa(0x85, f(0b0110), 0x7f, f(0b0100)); try testDaa(0x85, f(0b0111), 0x1f, f(0b0101)); try testDaa(0x85, f(0b1000), 0x85, f(0b0000)); try testDaa(0x85, f(0b1001), 0xe5, f(0b0001)); try testDaa(0x85, f(0b1010), 0x8b, f(0b0000)); try testDaa(0x85, f(0b1011), 0xeb, f(0b0001)); try testDaa(0x85, f(0b1100), 0x85, f(0b0100)); try testDaa(0x85, f(0b1101), 0x25, f(0b0101)); try testDaa(0x85, f(0b1110), 0x7f, f(0b0100)); try testDaa(0x85, f(0b1111), 0x1f, f(0b0101)); try testDaa(0x86, f(0b0000), 0x86, f(0b0000)); try testDaa(0x86, f(0b0001), 0xe6, f(0b0001)); try testDaa(0x86, f(0b0010), 0x8c, f(0b0000)); try testDaa(0x86, f(0b0011), 0xec, f(0b0001)); try testDaa(0x86, f(0b0100), 0x86, f(0b0100)); try testDaa(0x86, f(0b0101), 0x26, f(0b0101)); try testDaa(0x86, f(0b0110), 0x80, f(0b0100)); try testDaa(0x86, f(0b0111), 0x20, f(0b0101)); try testDaa(0x86, f(0b1000), 0x86, f(0b0000)); try testDaa(0x86, f(0b1001), 0xe6, f(0b0001)); try testDaa(0x86, f(0b1010), 0x8c, f(0b0000)); try testDaa(0x86, f(0b1011), 0xec, f(0b0001)); try testDaa(0x86, f(0b1100), 0x86, f(0b0100)); try testDaa(0x86, f(0b1101), 0x26, f(0b0101)); try testDaa(0x86, f(0b1110), 0x80, f(0b0100)); try testDaa(0x86, f(0b1111), 0x20, f(0b0101)); try testDaa(0x87, f(0b0000), 0x87, f(0b0000)); try testDaa(0x87, f(0b0001), 0xe7, f(0b0001)); try testDaa(0x87, f(0b0010), 0x8d, f(0b0000)); try testDaa(0x87, f(0b0011), 0xed, f(0b0001)); try testDaa(0x87, f(0b0100), 0x87, f(0b0100)); try testDaa(0x87, f(0b0101), 0x27, f(0b0101)); try testDaa(0x87, f(0b0110), 0x81, f(0b0100)); try testDaa(0x87, f(0b0111), 0x21, f(0b0101)); try testDaa(0x87, f(0b1000), 0x87, f(0b0000)); try testDaa(0x87, f(0b1001), 0xe7, f(0b0001)); try testDaa(0x87, f(0b1010), 0x8d, f(0b0000)); try testDaa(0x87, f(0b1011), 0xed, f(0b0001)); try testDaa(0x87, f(0b1100), 0x87, f(0b0100)); try testDaa(0x87, f(0b1101), 0x27, f(0b0101)); try testDaa(0x87, f(0b1110), 0x81, f(0b0100)); try testDaa(0x87, f(0b1111), 0x21, f(0b0101)); try testDaa(0x88, f(0b0000), 0x88, f(0b0000)); try testDaa(0x88, f(0b0001), 0xe8, f(0b0001)); try testDaa(0x88, f(0b0010), 0x8e, f(0b0000)); try testDaa(0x88, f(0b0011), 0xee, f(0b0001)); try testDaa(0x88, f(0b0100), 0x88, f(0b0100)); try testDaa(0x88, f(0b0101), 0x28, f(0b0101)); try testDaa(0x88, f(0b0110), 0x82, f(0b0100)); try testDaa(0x88, f(0b0111), 0x22, f(0b0101)); try testDaa(0x88, f(0b1000), 0x88, f(0b0000)); try testDaa(0x88, f(0b1001), 0xe8, f(0b0001)); try testDaa(0x88, f(0b1010), 0x8e, f(0b0000)); try testDaa(0x88, f(0b1011), 0xee, f(0b0001)); try testDaa(0x88, f(0b1100), 0x88, f(0b0100)); try testDaa(0x88, f(0b1101), 0x28, f(0b0101)); try testDaa(0x88, f(0b1110), 0x82, f(0b0100)); try testDaa(0x88, f(0b1111), 0x22, f(0b0101)); try testDaa(0x89, f(0b0000), 0x89, f(0b0000)); try testDaa(0x89, f(0b0001), 0xe9, f(0b0001)); try testDaa(0x89, f(0b0010), 0x8f, f(0b0000)); try testDaa(0x89, f(0b0011), 0xef, f(0b0001)); try testDaa(0x89, f(0b0100), 0x89, f(0b0100)); try testDaa(0x89, f(0b0101), 0x29, f(0b0101)); try testDaa(0x89, f(0b0110), 0x83, f(0b0100)); try testDaa(0x89, f(0b0111), 0x23, f(0b0101)); try testDaa(0x89, f(0b1000), 0x89, f(0b0000)); try testDaa(0x89, f(0b1001), 0xe9, f(0b0001)); try testDaa(0x89, f(0b1010), 0x8f, f(0b0000)); try testDaa(0x89, f(0b1011), 0xef, f(0b0001)); try testDaa(0x89, f(0b1100), 0x89, f(0b0100)); try testDaa(0x89, f(0b1101), 0x29, f(0b0101)); try testDaa(0x89, f(0b1110), 0x83, f(0b0100)); try testDaa(0x89, f(0b1111), 0x23, f(0b0101)); try testDaa(0x8a, f(0b0000), 0x90, f(0b0000)); try testDaa(0x8a, f(0b0001), 0xf0, f(0b0001)); try testDaa(0x8a, f(0b0010), 0x90, f(0b0000)); try testDaa(0x8a, f(0b0011), 0xf0, f(0b0001)); try testDaa(0x8a, f(0b0100), 0x8a, f(0b0100)); try testDaa(0x8a, f(0b0101), 0x2a, f(0b0101)); try testDaa(0x8a, f(0b0110), 0x84, f(0b0100)); try testDaa(0x8a, f(0b0111), 0x24, f(0b0101)); try testDaa(0x8a, f(0b1000), 0x90, f(0b0000)); try testDaa(0x8a, f(0b1001), 0xf0, f(0b0001)); try testDaa(0x8a, f(0b1010), 0x90, f(0b0000)); try testDaa(0x8a, f(0b1011), 0xf0, f(0b0001)); try testDaa(0x8a, f(0b1100), 0x8a, f(0b0100)); try testDaa(0x8a, f(0b1101), 0x2a, f(0b0101)); try testDaa(0x8a, f(0b1110), 0x84, f(0b0100)); try testDaa(0x8a, f(0b1111), 0x24, f(0b0101)); try testDaa(0x8b, f(0b0000), 0x91, f(0b0000)); try testDaa(0x8b, f(0b0001), 0xf1, f(0b0001)); try testDaa(0x8b, f(0b0010), 0x91, f(0b0000)); try testDaa(0x8b, f(0b0011), 0xf1, f(0b0001)); try testDaa(0x8b, f(0b0100), 0x8b, f(0b0100)); try testDaa(0x8b, f(0b0101), 0x2b, f(0b0101)); try testDaa(0x8b, f(0b0110), 0x85, f(0b0100)); try testDaa(0x8b, f(0b0111), 0x25, f(0b0101)); try testDaa(0x8b, f(0b1000), 0x91, f(0b0000)); try testDaa(0x8b, f(0b1001), 0xf1, f(0b0001)); try testDaa(0x8b, f(0b1010), 0x91, f(0b0000)); try testDaa(0x8b, f(0b1011), 0xf1, f(0b0001)); try testDaa(0x8b, f(0b1100), 0x8b, f(0b0100)); try testDaa(0x8b, f(0b1101), 0x2b, f(0b0101)); try testDaa(0x8b, f(0b1110), 0x85, f(0b0100)); try testDaa(0x8b, f(0b1111), 0x25, f(0b0101)); try testDaa(0x8c, f(0b0000), 0x92, f(0b0000)); try testDaa(0x8c, f(0b0001), 0xf2, f(0b0001)); try testDaa(0x8c, f(0b0010), 0x92, f(0b0000)); try testDaa(0x8c, f(0b0011), 0xf2, f(0b0001)); try testDaa(0x8c, f(0b0100), 0x8c, f(0b0100)); try testDaa(0x8c, f(0b0101), 0x2c, f(0b0101)); try testDaa(0x8c, f(0b0110), 0x86, f(0b0100)); try testDaa(0x8c, f(0b0111), 0x26, f(0b0101)); try testDaa(0x8c, f(0b1000), 0x92, f(0b0000)); try testDaa(0x8c, f(0b1001), 0xf2, f(0b0001)); try testDaa(0x8c, f(0b1010), 0x92, f(0b0000)); try testDaa(0x8c, f(0b1011), 0xf2, f(0b0001)); try testDaa(0x8c, f(0b1100), 0x8c, f(0b0100)); try testDaa(0x8c, f(0b1101), 0x2c, f(0b0101)); try testDaa(0x8c, f(0b1110), 0x86, f(0b0100)); try testDaa(0x8c, f(0b1111), 0x26, f(0b0101)); try testDaa(0x8d, f(0b0000), 0x93, f(0b0000)); try testDaa(0x8d, f(0b0001), 0xf3, f(0b0001)); try testDaa(0x8d, f(0b0010), 0x93, f(0b0000)); try testDaa(0x8d, f(0b0011), 0xf3, f(0b0001)); try testDaa(0x8d, f(0b0100), 0x8d, f(0b0100)); try testDaa(0x8d, f(0b0101), 0x2d, f(0b0101)); try testDaa(0x8d, f(0b0110), 0x87, f(0b0100)); try testDaa(0x8d, f(0b0111), 0x27, f(0b0101)); try testDaa(0x8d, f(0b1000), 0x93, f(0b0000)); try testDaa(0x8d, f(0b1001), 0xf3, f(0b0001)); try testDaa(0x8d, f(0b1010), 0x93, f(0b0000)); try testDaa(0x8d, f(0b1011), 0xf3, f(0b0001)); try testDaa(0x8d, f(0b1100), 0x8d, f(0b0100)); try testDaa(0x8d, f(0b1101), 0x2d, f(0b0101)); try testDaa(0x8d, f(0b1110), 0x87, f(0b0100)); try testDaa(0x8d, f(0b1111), 0x27, f(0b0101)); try testDaa(0x8e, f(0b0000), 0x94, f(0b0000)); try testDaa(0x8e, f(0b0001), 0xf4, f(0b0001)); try testDaa(0x8e, f(0b0010), 0x94, f(0b0000)); try testDaa(0x8e, f(0b0011), 0xf4, f(0b0001)); try testDaa(0x8e, f(0b0100), 0x8e, f(0b0100)); try testDaa(0x8e, f(0b0101), 0x2e, f(0b0101)); try testDaa(0x8e, f(0b0110), 0x88, f(0b0100)); try testDaa(0x8e, f(0b0111), 0x28, f(0b0101)); try testDaa(0x8e, f(0b1000), 0x94, f(0b0000)); try testDaa(0x8e, f(0b1001), 0xf4, f(0b0001)); try testDaa(0x8e, f(0b1010), 0x94, f(0b0000)); try testDaa(0x8e, f(0b1011), 0xf4, f(0b0001)); try testDaa(0x8e, f(0b1100), 0x8e, f(0b0100)); try testDaa(0x8e, f(0b1101), 0x2e, f(0b0101)); try testDaa(0x8e, f(0b1110), 0x88, f(0b0100)); try testDaa(0x8e, f(0b1111), 0x28, f(0b0101)); try testDaa(0x8f, f(0b0000), 0x95, f(0b0000)); try testDaa(0x8f, f(0b0001), 0xf5, f(0b0001)); try testDaa(0x8f, f(0b0010), 0x95, f(0b0000)); try testDaa(0x8f, f(0b0011), 0xf5, f(0b0001)); try testDaa(0x8f, f(0b0100), 0x8f, f(0b0100)); try testDaa(0x8f, f(0b0101), 0x2f, f(0b0101)); try testDaa(0x8f, f(0b0110), 0x89, f(0b0100)); try testDaa(0x8f, f(0b0111), 0x29, f(0b0101)); try testDaa(0x8f, f(0b1000), 0x95, f(0b0000)); try testDaa(0x8f, f(0b1001), 0xf5, f(0b0001)); try testDaa(0x8f, f(0b1010), 0x95, f(0b0000)); try testDaa(0x8f, f(0b1011), 0xf5, f(0b0001)); try testDaa(0x8f, f(0b1100), 0x8f, f(0b0100)); try testDaa(0x8f, f(0b1101), 0x2f, f(0b0101)); try testDaa(0x8f, f(0b1110), 0x89, f(0b0100)); try testDaa(0x8f, f(0b1111), 0x29, f(0b0101)); try testDaa(0x90, f(0b0000), 0x90, f(0b0000)); try testDaa(0x90, f(0b0001), 0xf0, f(0b0001)); try testDaa(0x90, f(0b0010), 0x96, f(0b0000)); try testDaa(0x90, f(0b0011), 0xf6, f(0b0001)); try testDaa(0x90, f(0b0100), 0x90, f(0b0100)); try testDaa(0x90, f(0b0101), 0x30, f(0b0101)); try testDaa(0x90, f(0b0110), 0x8a, f(0b0100)); try testDaa(0x90, f(0b0111), 0x2a, f(0b0101)); try testDaa(0x90, f(0b1000), 0x90, f(0b0000)); try testDaa(0x90, f(0b1001), 0xf0, f(0b0001)); try testDaa(0x90, f(0b1010), 0x96, f(0b0000)); try testDaa(0x90, f(0b1011), 0xf6, f(0b0001)); try testDaa(0x90, f(0b1100), 0x90, f(0b0100)); try testDaa(0x90, f(0b1101), 0x30, f(0b0101)); try testDaa(0x90, f(0b1110), 0x8a, f(0b0100)); try testDaa(0x90, f(0b1111), 0x2a, f(0b0101)); try testDaa(0x91, f(0b0000), 0x91, f(0b0000)); try testDaa(0x91, f(0b0001), 0xf1, f(0b0001)); try testDaa(0x91, f(0b0010), 0x97, f(0b0000)); try testDaa(0x91, f(0b0011), 0xf7, f(0b0001)); try testDaa(0x91, f(0b0100), 0x91, f(0b0100)); try testDaa(0x91, f(0b0101), 0x31, f(0b0101)); try testDaa(0x91, f(0b0110), 0x8b, f(0b0100)); try testDaa(0x91, f(0b0111), 0x2b, f(0b0101)); try testDaa(0x91, f(0b1000), 0x91, f(0b0000)); try testDaa(0x91, f(0b1001), 0xf1, f(0b0001)); try testDaa(0x91, f(0b1010), 0x97, f(0b0000)); try testDaa(0x91, f(0b1011), 0xf7, f(0b0001)); try testDaa(0x91, f(0b1100), 0x91, f(0b0100)); try testDaa(0x91, f(0b1101), 0x31, f(0b0101)); try testDaa(0x91, f(0b1110), 0x8b, f(0b0100)); try testDaa(0x91, f(0b1111), 0x2b, f(0b0101)); try testDaa(0x92, f(0b0000), 0x92, f(0b0000)); try testDaa(0x92, f(0b0001), 0xf2, f(0b0001)); try testDaa(0x92, f(0b0010), 0x98, f(0b0000)); try testDaa(0x92, f(0b0011), 0xf8, f(0b0001)); try testDaa(0x92, f(0b0100), 0x92, f(0b0100)); try testDaa(0x92, f(0b0101), 0x32, f(0b0101)); try testDaa(0x92, f(0b0110), 0x8c, f(0b0100)); try testDaa(0x92, f(0b0111), 0x2c, f(0b0101)); try testDaa(0x92, f(0b1000), 0x92, f(0b0000)); try testDaa(0x92, f(0b1001), 0xf2, f(0b0001)); try testDaa(0x92, f(0b1010), 0x98, f(0b0000)); try testDaa(0x92, f(0b1011), 0xf8, f(0b0001)); try testDaa(0x92, f(0b1100), 0x92, f(0b0100)); try testDaa(0x92, f(0b1101), 0x32, f(0b0101)); try testDaa(0x92, f(0b1110), 0x8c, f(0b0100)); try testDaa(0x92, f(0b1111), 0x2c, f(0b0101)); try testDaa(0x93, f(0b0000), 0x93, f(0b0000)); try testDaa(0x93, f(0b0001), 0xf3, f(0b0001)); try testDaa(0x93, f(0b0010), 0x99, f(0b0000)); try testDaa(0x93, f(0b0011), 0xf9, f(0b0001)); try testDaa(0x93, f(0b0100), 0x93, f(0b0100)); try testDaa(0x93, f(0b0101), 0x33, f(0b0101)); try testDaa(0x93, f(0b0110), 0x8d, f(0b0100)); try testDaa(0x93, f(0b0111), 0x2d, f(0b0101)); try testDaa(0x93, f(0b1000), 0x93, f(0b0000)); try testDaa(0x93, f(0b1001), 0xf3, f(0b0001)); try testDaa(0x93, f(0b1010), 0x99, f(0b0000)); try testDaa(0x93, f(0b1011), 0xf9, f(0b0001)); try testDaa(0x93, f(0b1100), 0x93, f(0b0100)); try testDaa(0x93, f(0b1101), 0x33, f(0b0101)); try testDaa(0x93, f(0b1110), 0x8d, f(0b0100)); try testDaa(0x93, f(0b1111), 0x2d, f(0b0101)); try testDaa(0x94, f(0b0000), 0x94, f(0b0000)); try testDaa(0x94, f(0b0001), 0xf4, f(0b0001)); try testDaa(0x94, f(0b0010), 0x9a, f(0b0000)); try testDaa(0x94, f(0b0011), 0xfa, f(0b0001)); try testDaa(0x94, f(0b0100), 0x94, f(0b0100)); try testDaa(0x94, f(0b0101), 0x34, f(0b0101)); try testDaa(0x94, f(0b0110), 0x8e, f(0b0100)); try testDaa(0x94, f(0b0111), 0x2e, f(0b0101)); try testDaa(0x94, f(0b1000), 0x94, f(0b0000)); try testDaa(0x94, f(0b1001), 0xf4, f(0b0001)); try testDaa(0x94, f(0b1010), 0x9a, f(0b0000)); try testDaa(0x94, f(0b1011), 0xfa, f(0b0001)); try testDaa(0x94, f(0b1100), 0x94, f(0b0100)); try testDaa(0x94, f(0b1101), 0x34, f(0b0101)); try testDaa(0x94, f(0b1110), 0x8e, f(0b0100)); try testDaa(0x94, f(0b1111), 0x2e, f(0b0101)); try testDaa(0x95, f(0b0000), 0x95, f(0b0000)); try testDaa(0x95, f(0b0001), 0xf5, f(0b0001)); try testDaa(0x95, f(0b0010), 0x9b, f(0b0000)); try testDaa(0x95, f(0b0011), 0xfb, f(0b0001)); try testDaa(0x95, f(0b0100), 0x95, f(0b0100)); try testDaa(0x95, f(0b0101), 0x35, f(0b0101)); try testDaa(0x95, f(0b0110), 0x8f, f(0b0100)); try testDaa(0x95, f(0b0111), 0x2f, f(0b0101)); try testDaa(0x95, f(0b1000), 0x95, f(0b0000)); try testDaa(0x95, f(0b1001), 0xf5, f(0b0001)); try testDaa(0x95, f(0b1010), 0x9b, f(0b0000)); try testDaa(0x95, f(0b1011), 0xfb, f(0b0001)); try testDaa(0x95, f(0b1100), 0x95, f(0b0100)); try testDaa(0x95, f(0b1101), 0x35, f(0b0101)); try testDaa(0x95, f(0b1110), 0x8f, f(0b0100)); try testDaa(0x95, f(0b1111), 0x2f, f(0b0101)); try testDaa(0x96, f(0b0000), 0x96, f(0b0000)); try testDaa(0x96, f(0b0001), 0xf6, f(0b0001)); try testDaa(0x96, f(0b0010), 0x9c, f(0b0000)); try testDaa(0x96, f(0b0011), 0xfc, f(0b0001)); try testDaa(0x96, f(0b0100), 0x96, f(0b0100)); try testDaa(0x96, f(0b0101), 0x36, f(0b0101)); try testDaa(0x96, f(0b0110), 0x90, f(0b0100)); try testDaa(0x96, f(0b0111), 0x30, f(0b0101)); try testDaa(0x96, f(0b1000), 0x96, f(0b0000)); try testDaa(0x96, f(0b1001), 0xf6, f(0b0001)); try testDaa(0x96, f(0b1010), 0x9c, f(0b0000)); try testDaa(0x96, f(0b1011), 0xfc, f(0b0001)); try testDaa(0x96, f(0b1100), 0x96, f(0b0100)); try testDaa(0x96, f(0b1101), 0x36, f(0b0101)); try testDaa(0x96, f(0b1110), 0x90, f(0b0100)); try testDaa(0x96, f(0b1111), 0x30, f(0b0101)); try testDaa(0x97, f(0b0000), 0x97, f(0b0000)); try testDaa(0x97, f(0b0001), 0xf7, f(0b0001)); try testDaa(0x97, f(0b0010), 0x9d, f(0b0000)); try testDaa(0x97, f(0b0011), 0xfd, f(0b0001)); try testDaa(0x97, f(0b0100), 0x97, f(0b0100)); try testDaa(0x97, f(0b0101), 0x37, f(0b0101)); try testDaa(0x97, f(0b0110), 0x91, f(0b0100)); try testDaa(0x97, f(0b0111), 0x31, f(0b0101)); try testDaa(0x97, f(0b1000), 0x97, f(0b0000)); try testDaa(0x97, f(0b1001), 0xf7, f(0b0001)); try testDaa(0x97, f(0b1010), 0x9d, f(0b0000)); try testDaa(0x97, f(0b1011), 0xfd, f(0b0001)); try testDaa(0x97, f(0b1100), 0x97, f(0b0100)); try testDaa(0x97, f(0b1101), 0x37, f(0b0101)); try testDaa(0x97, f(0b1110), 0x91, f(0b0100)); try testDaa(0x97, f(0b1111), 0x31, f(0b0101)); try testDaa(0x98, f(0b0000), 0x98, f(0b0000)); try testDaa(0x98, f(0b0001), 0xf8, f(0b0001)); try testDaa(0x98, f(0b0010), 0x9e, f(0b0000)); try testDaa(0x98, f(0b0011), 0xfe, f(0b0001)); try testDaa(0x98, f(0b0100), 0x98, f(0b0100)); try testDaa(0x98, f(0b0101), 0x38, f(0b0101)); try testDaa(0x98, f(0b0110), 0x92, f(0b0100)); try testDaa(0x98, f(0b0111), 0x32, f(0b0101)); try testDaa(0x98, f(0b1000), 0x98, f(0b0000)); try testDaa(0x98, f(0b1001), 0xf8, f(0b0001)); try testDaa(0x98, f(0b1010), 0x9e, f(0b0000)); try testDaa(0x98, f(0b1011), 0xfe, f(0b0001)); try testDaa(0x98, f(0b1100), 0x98, f(0b0100)); try testDaa(0x98, f(0b1101), 0x38, f(0b0101)); try testDaa(0x98, f(0b1110), 0x92, f(0b0100)); try testDaa(0x98, f(0b1111), 0x32, f(0b0101)); try testDaa(0x99, f(0b0000), 0x99, f(0b0000)); try testDaa(0x99, f(0b0001), 0xf9, f(0b0001)); try testDaa(0x99, f(0b0010), 0x9f, f(0b0000)); try testDaa(0x99, f(0b0011), 0xff, f(0b0001)); try testDaa(0x99, f(0b0100), 0x99, f(0b0100)); try testDaa(0x99, f(0b0101), 0x39, f(0b0101)); try testDaa(0x99, f(0b0110), 0x93, f(0b0100)); try testDaa(0x99, f(0b0111), 0x33, f(0b0101)); try testDaa(0x99, f(0b1000), 0x99, f(0b0000)); try testDaa(0x99, f(0b1001), 0xf9, f(0b0001)); try testDaa(0x99, f(0b1010), 0x9f, f(0b0000)); try testDaa(0x99, f(0b1011), 0xff, f(0b0001)); try testDaa(0x99, f(0b1100), 0x99, f(0b0100)); try testDaa(0x99, f(0b1101), 0x39, f(0b0101)); try testDaa(0x99, f(0b1110), 0x93, f(0b0100)); try testDaa(0x99, f(0b1111), 0x33, f(0b0101)); try testDaa(0x9a, f(0b0000), 0x00, f(0b1001)); try testDaa(0x9a, f(0b0001), 0x00, f(0b1001)); try testDaa(0x9a, f(0b0010), 0x00, f(0b1001)); try testDaa(0x9a, f(0b0011), 0x00, f(0b1001)); try testDaa(0x9a, f(0b0100), 0x9a, f(0b0100)); try testDaa(0x9a, f(0b0101), 0x3a, f(0b0101)); try testDaa(0x9a, f(0b0110), 0x94, f(0b0100)); try testDaa(0x9a, f(0b0111), 0x34, f(0b0101)); try testDaa(0x9a, f(0b1000), 0x00, f(0b1001)); try testDaa(0x9a, f(0b1001), 0x00, f(0b1001)); try testDaa(0x9a, f(0b1010), 0x00, f(0b1001)); try testDaa(0x9a, f(0b1011), 0x00, f(0b1001)); try testDaa(0x9a, f(0b1100), 0x9a, f(0b0100)); try testDaa(0x9a, f(0b1101), 0x3a, f(0b0101)); try testDaa(0x9a, f(0b1110), 0x94, f(0b0100)); try testDaa(0x9a, f(0b1111), 0x34, f(0b0101)); try testDaa(0x9b, f(0b0000), 0x01, f(0b0001)); try testDaa(0x9b, f(0b0001), 0x01, f(0b0001)); try testDaa(0x9b, f(0b0010), 0x01, f(0b0001)); try testDaa(0x9b, f(0b0011), 0x01, f(0b0001)); try testDaa(0x9b, f(0b0100), 0x9b, f(0b0100)); try testDaa(0x9b, f(0b0101), 0x3b, f(0b0101)); try testDaa(0x9b, f(0b0110), 0x95, f(0b0100)); try testDaa(0x9b, f(0b0111), 0x35, f(0b0101)); try testDaa(0x9b, f(0b1000), 0x01, f(0b0001)); try testDaa(0x9b, f(0b1001), 0x01, f(0b0001)); try testDaa(0x9b, f(0b1010), 0x01, f(0b0001)); try testDaa(0x9b, f(0b1011), 0x01, f(0b0001)); try testDaa(0x9b, f(0b1100), 0x9b, f(0b0100)); try testDaa(0x9b, f(0b1101), 0x3b, f(0b0101)); try testDaa(0x9b, f(0b1110), 0x95, f(0b0100)); try testDaa(0x9b, f(0b1111), 0x35, f(0b0101)); try testDaa(0x9c, f(0b0000), 0x02, f(0b0001)); try testDaa(0x9c, f(0b0001), 0x02, f(0b0001)); try testDaa(0x9c, f(0b0010), 0x02, f(0b0001)); try testDaa(0x9c, f(0b0011), 0x02, f(0b0001)); try testDaa(0x9c, f(0b0100), 0x9c, f(0b0100)); try testDaa(0x9c, f(0b0101), 0x3c, f(0b0101)); try testDaa(0x9c, f(0b0110), 0x96, f(0b0100)); try testDaa(0x9c, f(0b0111), 0x36, f(0b0101)); try testDaa(0x9c, f(0b1000), 0x02, f(0b0001)); try testDaa(0x9c, f(0b1001), 0x02, f(0b0001)); try testDaa(0x9c, f(0b1010), 0x02, f(0b0001)); try testDaa(0x9c, f(0b1011), 0x02, f(0b0001)); try testDaa(0x9c, f(0b1100), 0x9c, f(0b0100)); try testDaa(0x9c, f(0b1101), 0x3c, f(0b0101)); try testDaa(0x9c, f(0b1110), 0x96, f(0b0100)); try testDaa(0x9c, f(0b1111), 0x36, f(0b0101)); try testDaa(0x9d, f(0b0000), 0x03, f(0b0001)); try testDaa(0x9d, f(0b0001), 0x03, f(0b0001)); try testDaa(0x9d, f(0b0010), 0x03, f(0b0001)); try testDaa(0x9d, f(0b0011), 0x03, f(0b0001)); try testDaa(0x9d, f(0b0100), 0x9d, f(0b0100)); try testDaa(0x9d, f(0b0101), 0x3d, f(0b0101)); try testDaa(0x9d, f(0b0110), 0x97, f(0b0100)); try testDaa(0x9d, f(0b0111), 0x37, f(0b0101)); try testDaa(0x9d, f(0b1000), 0x03, f(0b0001)); try testDaa(0x9d, f(0b1001), 0x03, f(0b0001)); try testDaa(0x9d, f(0b1010), 0x03, f(0b0001)); try testDaa(0x9d, f(0b1011), 0x03, f(0b0001)); try testDaa(0x9d, f(0b1100), 0x9d, f(0b0100)); try testDaa(0x9d, f(0b1101), 0x3d, f(0b0101)); try testDaa(0x9d, f(0b1110), 0x97, f(0b0100)); try testDaa(0x9d, f(0b1111), 0x37, f(0b0101)); try testDaa(0x9e, f(0b0000), 0x04, f(0b0001)); try testDaa(0x9e, f(0b0001), 0x04, f(0b0001)); try testDaa(0x9e, f(0b0010), 0x04, f(0b0001)); try testDaa(0x9e, f(0b0011), 0x04, f(0b0001)); try testDaa(0x9e, f(0b0100), 0x9e, f(0b0100)); try testDaa(0x9e, f(0b0101), 0x3e, f(0b0101)); try testDaa(0x9e, f(0b0110), 0x98, f(0b0100)); try testDaa(0x9e, f(0b0111), 0x38, f(0b0101)); try testDaa(0x9e, f(0b1000), 0x04, f(0b0001)); try testDaa(0x9e, f(0b1001), 0x04, f(0b0001)); try testDaa(0x9e, f(0b1010), 0x04, f(0b0001)); try testDaa(0x9e, f(0b1011), 0x04, f(0b0001)); try testDaa(0x9e, f(0b1100), 0x9e, f(0b0100)); try testDaa(0x9e, f(0b1101), 0x3e, f(0b0101)); try testDaa(0x9e, f(0b1110), 0x98, f(0b0100)); try testDaa(0x9e, f(0b1111), 0x38, f(0b0101)); try testDaa(0x9f, f(0b0000), 0x05, f(0b0001)); try testDaa(0x9f, f(0b0001), 0x05, f(0b0001)); try testDaa(0x9f, f(0b0010), 0x05, f(0b0001)); try testDaa(0x9f, f(0b0011), 0x05, f(0b0001)); try testDaa(0x9f, f(0b0100), 0x9f, f(0b0100)); try testDaa(0x9f, f(0b0101), 0x3f, f(0b0101)); try testDaa(0x9f, f(0b0110), 0x99, f(0b0100)); try testDaa(0x9f, f(0b0111), 0x39, f(0b0101)); try testDaa(0x9f, f(0b1000), 0x05, f(0b0001)); try testDaa(0x9f, f(0b1001), 0x05, f(0b0001)); try testDaa(0x9f, f(0b1010), 0x05, f(0b0001)); try testDaa(0x9f, f(0b1011), 0x05, f(0b0001)); try testDaa(0x9f, f(0b1100), 0x9f, f(0b0100)); try testDaa(0x9f, f(0b1101), 0x3f, f(0b0101)); try testDaa(0x9f, f(0b1110), 0x99, f(0b0100)); try testDaa(0x9f, f(0b1111), 0x39, f(0b0101)); try testDaa(0xa0, f(0b0000), 0x00, f(0b1001)); try testDaa(0xa0, f(0b0001), 0x00, f(0b1001)); try testDaa(0xa0, f(0b0010), 0x06, f(0b0001)); try testDaa(0xa0, f(0b0011), 0x06, f(0b0001)); try testDaa(0xa0, f(0b0100), 0xa0, f(0b0100)); try testDaa(0xa0, f(0b0101), 0x40, f(0b0101)); try testDaa(0xa0, f(0b0110), 0x9a, f(0b0100)); try testDaa(0xa0, f(0b0111), 0x3a, f(0b0101)); try testDaa(0xa0, f(0b1000), 0x00, f(0b1001)); try testDaa(0xa0, f(0b1001), 0x00, f(0b1001)); try testDaa(0xa0, f(0b1010), 0x06, f(0b0001)); try testDaa(0xa0, f(0b1011), 0x06, f(0b0001)); try testDaa(0xa0, f(0b1100), 0xa0, f(0b0100)); try testDaa(0xa0, f(0b1101), 0x40, f(0b0101)); try testDaa(0xa0, f(0b1110), 0x9a, f(0b0100)); try testDaa(0xa0, f(0b1111), 0x3a, f(0b0101)); try testDaa(0xa1, f(0b0000), 0x01, f(0b0001)); try testDaa(0xa1, f(0b0001), 0x01, f(0b0001)); try testDaa(0xa1, f(0b0010), 0x07, f(0b0001)); try testDaa(0xa1, f(0b0011), 0x07, f(0b0001)); try testDaa(0xa1, f(0b0100), 0xa1, f(0b0100)); try testDaa(0xa1, f(0b0101), 0x41, f(0b0101)); try testDaa(0xa1, f(0b0110), 0x9b, f(0b0100)); try testDaa(0xa1, f(0b0111), 0x3b, f(0b0101)); try testDaa(0xa1, f(0b1000), 0x01, f(0b0001)); try testDaa(0xa1, f(0b1001), 0x01, f(0b0001)); try testDaa(0xa1, f(0b1010), 0x07, f(0b0001)); try testDaa(0xa1, f(0b1011), 0x07, f(0b0001)); try testDaa(0xa1, f(0b1100), 0xa1, f(0b0100)); try testDaa(0xa1, f(0b1101), 0x41, f(0b0101)); try testDaa(0xa1, f(0b1110), 0x9b, f(0b0100)); try testDaa(0xa1, f(0b1111), 0x3b, f(0b0101)); try testDaa(0xa2, f(0b0000), 0x02, f(0b0001)); try testDaa(0xa2, f(0b0001), 0x02, f(0b0001)); try testDaa(0xa2, f(0b0010), 0x08, f(0b0001)); try testDaa(0xa2, f(0b0011), 0x08, f(0b0001)); try testDaa(0xa2, f(0b0100), 0xa2, f(0b0100)); try testDaa(0xa2, f(0b0101), 0x42, f(0b0101)); try testDaa(0xa2, f(0b0110), 0x9c, f(0b0100)); try testDaa(0xa2, f(0b0111), 0x3c, f(0b0101)); try testDaa(0xa2, f(0b1000), 0x02, f(0b0001)); try testDaa(0xa2, f(0b1001), 0x02, f(0b0001)); try testDaa(0xa2, f(0b1010), 0x08, f(0b0001)); try testDaa(0xa2, f(0b1011), 0x08, f(0b0001)); try testDaa(0xa2, f(0b1100), 0xa2, f(0b0100)); try testDaa(0xa2, f(0b1101), 0x42, f(0b0101)); try testDaa(0xa2, f(0b1110), 0x9c, f(0b0100)); try testDaa(0xa2, f(0b1111), 0x3c, f(0b0101)); try testDaa(0xa3, f(0b0000), 0x03, f(0b0001)); try testDaa(0xa3, f(0b0001), 0x03, f(0b0001)); try testDaa(0xa3, f(0b0010), 0x09, f(0b0001)); try testDaa(0xa3, f(0b0011), 0x09, f(0b0001)); try testDaa(0xa3, f(0b0100), 0xa3, f(0b0100)); try testDaa(0xa3, f(0b0101), 0x43, f(0b0101)); try testDaa(0xa3, f(0b0110), 0x9d, f(0b0100)); try testDaa(0xa3, f(0b0111), 0x3d, f(0b0101)); try testDaa(0xa3, f(0b1000), 0x03, f(0b0001)); try testDaa(0xa3, f(0b1001), 0x03, f(0b0001)); try testDaa(0xa3, f(0b1010), 0x09, f(0b0001)); try testDaa(0xa3, f(0b1011), 0x09, f(0b0001)); try testDaa(0xa3, f(0b1100), 0xa3, f(0b0100)); try testDaa(0xa3, f(0b1101), 0x43, f(0b0101)); try testDaa(0xa3, f(0b1110), 0x9d, f(0b0100)); try testDaa(0xa3, f(0b1111), 0x3d, f(0b0101)); try testDaa(0xa4, f(0b0000), 0x04, f(0b0001)); try testDaa(0xa4, f(0b0001), 0x04, f(0b0001)); try testDaa(0xa4, f(0b0010), 0x0a, f(0b0001)); try testDaa(0xa4, f(0b0011), 0x0a, f(0b0001)); try testDaa(0xa4, f(0b0100), 0xa4, f(0b0100)); try testDaa(0xa4, f(0b0101), 0x44, f(0b0101)); try testDaa(0xa4, f(0b0110), 0x9e, f(0b0100)); try testDaa(0xa4, f(0b0111), 0x3e, f(0b0101)); try testDaa(0xa4, f(0b1000), 0x04, f(0b0001)); try testDaa(0xa4, f(0b1001), 0x04, f(0b0001)); try testDaa(0xa4, f(0b1010), 0x0a, f(0b0001)); try testDaa(0xa4, f(0b1011), 0x0a, f(0b0001)); try testDaa(0xa4, f(0b1100), 0xa4, f(0b0100)); try testDaa(0xa4, f(0b1101), 0x44, f(0b0101)); try testDaa(0xa4, f(0b1110), 0x9e, f(0b0100)); try testDaa(0xa4, f(0b1111), 0x3e, f(0b0101)); try testDaa(0xa5, f(0b0000), 0x05, f(0b0001)); try testDaa(0xa5, f(0b0001), 0x05, f(0b0001)); try testDaa(0xa5, f(0b0010), 0x0b, f(0b0001)); try testDaa(0xa5, f(0b0011), 0x0b, f(0b0001)); try testDaa(0xa5, f(0b0100), 0xa5, f(0b0100)); try testDaa(0xa5, f(0b0101), 0x45, f(0b0101)); try testDaa(0xa5, f(0b0110), 0x9f, f(0b0100)); try testDaa(0xa5, f(0b0111), 0x3f, f(0b0101)); try testDaa(0xa5, f(0b1000), 0x05, f(0b0001)); try testDaa(0xa5, f(0b1001), 0x05, f(0b0001)); try testDaa(0xa5, f(0b1010), 0x0b, f(0b0001)); try testDaa(0xa5, f(0b1011), 0x0b, f(0b0001)); try testDaa(0xa5, f(0b1100), 0xa5, f(0b0100)); try testDaa(0xa5, f(0b1101), 0x45, f(0b0101)); try testDaa(0xa5, f(0b1110), 0x9f, f(0b0100)); try testDaa(0xa5, f(0b1111), 0x3f, f(0b0101)); try testDaa(0xa6, f(0b0000), 0x06, f(0b0001)); try testDaa(0xa6, f(0b0001), 0x06, f(0b0001)); try testDaa(0xa6, f(0b0010), 0x0c, f(0b0001)); try testDaa(0xa6, f(0b0011), 0x0c, f(0b0001)); try testDaa(0xa6, f(0b0100), 0xa6, f(0b0100)); try testDaa(0xa6, f(0b0101), 0x46, f(0b0101)); try testDaa(0xa6, f(0b0110), 0xa0, f(0b0100)); try testDaa(0xa6, f(0b0111), 0x40, f(0b0101)); try testDaa(0xa6, f(0b1000), 0x06, f(0b0001)); try testDaa(0xa6, f(0b1001), 0x06, f(0b0001)); try testDaa(0xa6, f(0b1010), 0x0c, f(0b0001)); try testDaa(0xa6, f(0b1011), 0x0c, f(0b0001)); try testDaa(0xa6, f(0b1100), 0xa6, f(0b0100)); try testDaa(0xa6, f(0b1101), 0x46, f(0b0101)); try testDaa(0xa6, f(0b1110), 0xa0, f(0b0100)); try testDaa(0xa6, f(0b1111), 0x40, f(0b0101)); try testDaa(0xa7, f(0b0000), 0x07, f(0b0001)); try testDaa(0xa7, f(0b0001), 0x07, f(0b0001)); try testDaa(0xa7, f(0b0010), 0x0d, f(0b0001)); try testDaa(0xa7, f(0b0011), 0x0d, f(0b0001)); try testDaa(0xa7, f(0b0100), 0xa7, f(0b0100)); try testDaa(0xa7, f(0b0101), 0x47, f(0b0101)); try testDaa(0xa7, f(0b0110), 0xa1, f(0b0100)); try testDaa(0xa7, f(0b0111), 0x41, f(0b0101)); try testDaa(0xa7, f(0b1000), 0x07, f(0b0001)); try testDaa(0xa7, f(0b1001), 0x07, f(0b0001)); try testDaa(0xa7, f(0b1010), 0x0d, f(0b0001)); try testDaa(0xa7, f(0b1011), 0x0d, f(0b0001)); try testDaa(0xa7, f(0b1100), 0xa7, f(0b0100)); try testDaa(0xa7, f(0b1101), 0x47, f(0b0101)); try testDaa(0xa7, f(0b1110), 0xa1, f(0b0100)); try testDaa(0xa7, f(0b1111), 0x41, f(0b0101)); try testDaa(0xa8, f(0b0000), 0x08, f(0b0001)); try testDaa(0xa8, f(0b0001), 0x08, f(0b0001)); try testDaa(0xa8, f(0b0010), 0x0e, f(0b0001)); try testDaa(0xa8, f(0b0011), 0x0e, f(0b0001)); try testDaa(0xa8, f(0b0100), 0xa8, f(0b0100)); try testDaa(0xa8, f(0b0101), 0x48, f(0b0101)); try testDaa(0xa8, f(0b0110), 0xa2, f(0b0100)); try testDaa(0xa8, f(0b0111), 0x42, f(0b0101)); try testDaa(0xa8, f(0b1000), 0x08, f(0b0001)); try testDaa(0xa8, f(0b1001), 0x08, f(0b0001)); try testDaa(0xa8, f(0b1010), 0x0e, f(0b0001)); try testDaa(0xa8, f(0b1011), 0x0e, f(0b0001)); try testDaa(0xa8, f(0b1100), 0xa8, f(0b0100)); try testDaa(0xa8, f(0b1101), 0x48, f(0b0101)); try testDaa(0xa8, f(0b1110), 0xa2, f(0b0100)); try testDaa(0xa8, f(0b1111), 0x42, f(0b0101)); try testDaa(0xa9, f(0b0000), 0x09, f(0b0001)); try testDaa(0xa9, f(0b0001), 0x09, f(0b0001)); try testDaa(0xa9, f(0b0010), 0x0f, f(0b0001)); try testDaa(0xa9, f(0b0011), 0x0f, f(0b0001)); try testDaa(0xa9, f(0b0100), 0xa9, f(0b0100)); try testDaa(0xa9, f(0b0101), 0x49, f(0b0101)); try testDaa(0xa9, f(0b0110), 0xa3, f(0b0100)); try testDaa(0xa9, f(0b0111), 0x43, f(0b0101)); try testDaa(0xa9, f(0b1000), 0x09, f(0b0001)); try testDaa(0xa9, f(0b1001), 0x09, f(0b0001)); try testDaa(0xa9, f(0b1010), 0x0f, f(0b0001)); try testDaa(0xa9, f(0b1011), 0x0f, f(0b0001)); try testDaa(0xa9, f(0b1100), 0xa9, f(0b0100)); try testDaa(0xa9, f(0b1101), 0x49, f(0b0101)); try testDaa(0xa9, f(0b1110), 0xa3, f(0b0100)); try testDaa(0xa9, f(0b1111), 0x43, f(0b0101)); try testDaa(0xaa, f(0b0000), 0x10, f(0b0001)); try testDaa(0xaa, f(0b0001), 0x10, f(0b0001)); try testDaa(0xaa, f(0b0010), 0x10, f(0b0001)); try testDaa(0xaa, f(0b0011), 0x10, f(0b0001)); try testDaa(0xaa, f(0b0100), 0xaa, f(0b0100)); try testDaa(0xaa, f(0b0101), 0x4a, f(0b0101)); try testDaa(0xaa, f(0b0110), 0xa4, f(0b0100)); try testDaa(0xaa, f(0b0111), 0x44, f(0b0101)); try testDaa(0xaa, f(0b1000), 0x10, f(0b0001)); try testDaa(0xaa, f(0b1001), 0x10, f(0b0001)); try testDaa(0xaa, f(0b1010), 0x10, f(0b0001)); try testDaa(0xaa, f(0b1011), 0x10, f(0b0001)); try testDaa(0xaa, f(0b1100), 0xaa, f(0b0100)); try testDaa(0xaa, f(0b1101), 0x4a, f(0b0101)); try testDaa(0xaa, f(0b1110), 0xa4, f(0b0100)); try testDaa(0xaa, f(0b1111), 0x44, f(0b0101)); try testDaa(0xab, f(0b0000), 0x11, f(0b0001)); try testDaa(0xab, f(0b0001), 0x11, f(0b0001)); try testDaa(0xab, f(0b0010), 0x11, f(0b0001)); try testDaa(0xab, f(0b0011), 0x11, f(0b0001)); try testDaa(0xab, f(0b0100), 0xab, f(0b0100)); try testDaa(0xab, f(0b0101), 0x4b, f(0b0101)); try testDaa(0xab, f(0b0110), 0xa5, f(0b0100)); try testDaa(0xab, f(0b0111), 0x45, f(0b0101)); try testDaa(0xab, f(0b1000), 0x11, f(0b0001)); try testDaa(0xab, f(0b1001), 0x11, f(0b0001)); try testDaa(0xab, f(0b1010), 0x11, f(0b0001)); try testDaa(0xab, f(0b1011), 0x11, f(0b0001)); try testDaa(0xab, f(0b1100), 0xab, f(0b0100)); try testDaa(0xab, f(0b1101), 0x4b, f(0b0101)); try testDaa(0xab, f(0b1110), 0xa5, f(0b0100)); try testDaa(0xab, f(0b1111), 0x45, f(0b0101)); try testDaa(0xac, f(0b0000), 0x12, f(0b0001)); try testDaa(0xac, f(0b0001), 0x12, f(0b0001)); try testDaa(0xac, f(0b0010), 0x12, f(0b0001)); try testDaa(0xac, f(0b0011), 0x12, f(0b0001)); try testDaa(0xac, f(0b0100), 0xac, f(0b0100)); try testDaa(0xac, f(0b0101), 0x4c, f(0b0101)); try testDaa(0xac, f(0b0110), 0xa6, f(0b0100)); try testDaa(0xac, f(0b0111), 0x46, f(0b0101)); try testDaa(0xac, f(0b1000), 0x12, f(0b0001)); try testDaa(0xac, f(0b1001), 0x12, f(0b0001)); try testDaa(0xac, f(0b1010), 0x12, f(0b0001)); try testDaa(0xac, f(0b1011), 0x12, f(0b0001)); try testDaa(0xac, f(0b1100), 0xac, f(0b0100)); try testDaa(0xac, f(0b1101), 0x4c, f(0b0101)); try testDaa(0xac, f(0b1110), 0xa6, f(0b0100)); try testDaa(0xac, f(0b1111), 0x46, f(0b0101)); try testDaa(0xad, f(0b0000), 0x13, f(0b0001)); try testDaa(0xad, f(0b0001), 0x13, f(0b0001)); try testDaa(0xad, f(0b0010), 0x13, f(0b0001)); try testDaa(0xad, f(0b0011), 0x13, f(0b0001)); try testDaa(0xad, f(0b0100), 0xad, f(0b0100)); try testDaa(0xad, f(0b0101), 0x4d, f(0b0101)); try testDaa(0xad, f(0b0110), 0xa7, f(0b0100)); try testDaa(0xad, f(0b0111), 0x47, f(0b0101)); try testDaa(0xad, f(0b1000), 0x13, f(0b0001)); try testDaa(0xad, f(0b1001), 0x13, f(0b0001)); try testDaa(0xad, f(0b1010), 0x13, f(0b0001)); try testDaa(0xad, f(0b1011), 0x13, f(0b0001)); try testDaa(0xad, f(0b1100), 0xad, f(0b0100)); try testDaa(0xad, f(0b1101), 0x4d, f(0b0101)); try testDaa(0xad, f(0b1110), 0xa7, f(0b0100)); try testDaa(0xad, f(0b1111), 0x47, f(0b0101)); try testDaa(0xae, f(0b0000), 0x14, f(0b0001)); try testDaa(0xae, f(0b0001), 0x14, f(0b0001)); try testDaa(0xae, f(0b0010), 0x14, f(0b0001)); try testDaa(0xae, f(0b0011), 0x14, f(0b0001)); try testDaa(0xae, f(0b0100), 0xae, f(0b0100)); try testDaa(0xae, f(0b0101), 0x4e, f(0b0101)); try testDaa(0xae, f(0b0110), 0xa8, f(0b0100)); try testDaa(0xae, f(0b0111), 0x48, f(0b0101)); try testDaa(0xae, f(0b1000), 0x14, f(0b0001)); try testDaa(0xae, f(0b1001), 0x14, f(0b0001)); try testDaa(0xae, f(0b1010), 0x14, f(0b0001)); try testDaa(0xae, f(0b1011), 0x14, f(0b0001)); try testDaa(0xae, f(0b1100), 0xae, f(0b0100)); try testDaa(0xae, f(0b1101), 0x4e, f(0b0101)); try testDaa(0xae, f(0b1110), 0xa8, f(0b0100)); try testDaa(0xae, f(0b1111), 0x48, f(0b0101)); try testDaa(0xaf, f(0b0000), 0x15, f(0b0001)); try testDaa(0xaf, f(0b0001), 0x15, f(0b0001)); try testDaa(0xaf, f(0b0010), 0x15, f(0b0001)); try testDaa(0xaf, f(0b0011), 0x15, f(0b0001)); try testDaa(0xaf, f(0b0100), 0xaf, f(0b0100)); try testDaa(0xaf, f(0b0101), 0x4f, f(0b0101)); try testDaa(0xaf, f(0b0110), 0xa9, f(0b0100)); try testDaa(0xaf, f(0b0111), 0x49, f(0b0101)); try testDaa(0xaf, f(0b1000), 0x15, f(0b0001)); try testDaa(0xaf, f(0b1001), 0x15, f(0b0001)); try testDaa(0xaf, f(0b1010), 0x15, f(0b0001)); try testDaa(0xaf, f(0b1011), 0x15, f(0b0001)); try testDaa(0xaf, f(0b1100), 0xaf, f(0b0100)); try testDaa(0xaf, f(0b1101), 0x4f, f(0b0101)); try testDaa(0xaf, f(0b1110), 0xa9, f(0b0100)); try testDaa(0xaf, f(0b1111), 0x49, f(0b0101)); try testDaa(0xb0, f(0b0000), 0x10, f(0b0001)); try testDaa(0xb0, f(0b0001), 0x10, f(0b0001)); try testDaa(0xb0, f(0b0010), 0x16, f(0b0001)); try testDaa(0xb0, f(0b0011), 0x16, f(0b0001)); try testDaa(0xb0, f(0b0100), 0xb0, f(0b0100)); try testDaa(0xb0, f(0b0101), 0x50, f(0b0101)); try testDaa(0xb0, f(0b0110), 0xaa, f(0b0100)); try testDaa(0xb0, f(0b0111), 0x4a, f(0b0101)); try testDaa(0xb0, f(0b1000), 0x10, f(0b0001)); try testDaa(0xb0, f(0b1001), 0x10, f(0b0001)); try testDaa(0xb0, f(0b1010), 0x16, f(0b0001)); try testDaa(0xb0, f(0b1011), 0x16, f(0b0001)); try testDaa(0xb0, f(0b1100), 0xb0, f(0b0100)); try testDaa(0xb0, f(0b1101), 0x50, f(0b0101)); try testDaa(0xb0, f(0b1110), 0xaa, f(0b0100)); try testDaa(0xb0, f(0b1111), 0x4a, f(0b0101)); try testDaa(0xb1, f(0b0000), 0x11, f(0b0001)); try testDaa(0xb1, f(0b0001), 0x11, f(0b0001)); try testDaa(0xb1, f(0b0010), 0x17, f(0b0001)); try testDaa(0xb1, f(0b0011), 0x17, f(0b0001)); try testDaa(0xb1, f(0b0100), 0xb1, f(0b0100)); try testDaa(0xb1, f(0b0101), 0x51, f(0b0101)); try testDaa(0xb1, f(0b0110), 0xab, f(0b0100)); try testDaa(0xb1, f(0b0111), 0x4b, f(0b0101)); try testDaa(0xb1, f(0b1000), 0x11, f(0b0001)); try testDaa(0xb1, f(0b1001), 0x11, f(0b0001)); try testDaa(0xb1, f(0b1010), 0x17, f(0b0001)); try testDaa(0xb1, f(0b1011), 0x17, f(0b0001)); try testDaa(0xb1, f(0b1100), 0xb1, f(0b0100)); try testDaa(0xb1, f(0b1101), 0x51, f(0b0101)); try testDaa(0xb1, f(0b1110), 0xab, f(0b0100)); try testDaa(0xb1, f(0b1111), 0x4b, f(0b0101)); try testDaa(0xb2, f(0b0000), 0x12, f(0b0001)); try testDaa(0xb2, f(0b0001), 0x12, f(0b0001)); try testDaa(0xb2, f(0b0010), 0x18, f(0b0001)); try testDaa(0xb2, f(0b0011), 0x18, f(0b0001)); try testDaa(0xb2, f(0b0100), 0xb2, f(0b0100)); try testDaa(0xb2, f(0b0101), 0x52, f(0b0101)); try testDaa(0xb2, f(0b0110), 0xac, f(0b0100)); try testDaa(0xb2, f(0b0111), 0x4c, f(0b0101)); try testDaa(0xb2, f(0b1000), 0x12, f(0b0001)); try testDaa(0xb2, f(0b1001), 0x12, f(0b0001)); try testDaa(0xb2, f(0b1010), 0x18, f(0b0001)); try testDaa(0xb2, f(0b1011), 0x18, f(0b0001)); try testDaa(0xb2, f(0b1100), 0xb2, f(0b0100)); try testDaa(0xb2, f(0b1101), 0x52, f(0b0101)); try testDaa(0xb2, f(0b1110), 0xac, f(0b0100)); try testDaa(0xb2, f(0b1111), 0x4c, f(0b0101)); try testDaa(0xb3, f(0b0000), 0x13, f(0b0001)); try testDaa(0xb3, f(0b0001), 0x13, f(0b0001)); try testDaa(0xb3, f(0b0010), 0x19, f(0b0001)); try testDaa(0xb3, f(0b0011), 0x19, f(0b0001)); try testDaa(0xb3, f(0b0100), 0xb3, f(0b0100)); try testDaa(0xb3, f(0b0101), 0x53, f(0b0101)); try testDaa(0xb3, f(0b0110), 0xad, f(0b0100)); try testDaa(0xb3, f(0b0111), 0x4d, f(0b0101)); try testDaa(0xb3, f(0b1000), 0x13, f(0b0001)); try testDaa(0xb3, f(0b1001), 0x13, f(0b0001)); try testDaa(0xb3, f(0b1010), 0x19, f(0b0001)); try testDaa(0xb3, f(0b1011), 0x19, f(0b0001)); try testDaa(0xb3, f(0b1100), 0xb3, f(0b0100)); try testDaa(0xb3, f(0b1101), 0x53, f(0b0101)); try testDaa(0xb3, f(0b1110), 0xad, f(0b0100)); try testDaa(0xb3, f(0b1111), 0x4d, f(0b0101)); try testDaa(0xb4, f(0b0000), 0x14, f(0b0001)); try testDaa(0xb4, f(0b0001), 0x14, f(0b0001)); try testDaa(0xb4, f(0b0010), 0x1a, f(0b0001)); try testDaa(0xb4, f(0b0011), 0x1a, f(0b0001)); try testDaa(0xb4, f(0b0100), 0xb4, f(0b0100)); try testDaa(0xb4, f(0b0101), 0x54, f(0b0101)); try testDaa(0xb4, f(0b0110), 0xae, f(0b0100)); try testDaa(0xb4, f(0b0111), 0x4e, f(0b0101)); try testDaa(0xb4, f(0b1000), 0x14, f(0b0001)); try testDaa(0xb4, f(0b1001), 0x14, f(0b0001)); try testDaa(0xb4, f(0b1010), 0x1a, f(0b0001)); try testDaa(0xb4, f(0b1011), 0x1a, f(0b0001)); try testDaa(0xb4, f(0b1100), 0xb4, f(0b0100)); try testDaa(0xb4, f(0b1101), 0x54, f(0b0101)); try testDaa(0xb4, f(0b1110), 0xae, f(0b0100)); try testDaa(0xb4, f(0b1111), 0x4e, f(0b0101)); try testDaa(0xb5, f(0b0000), 0x15, f(0b0001)); try testDaa(0xb5, f(0b0001), 0x15, f(0b0001)); try testDaa(0xb5, f(0b0010), 0x1b, f(0b0001)); try testDaa(0xb5, f(0b0011), 0x1b, f(0b0001)); try testDaa(0xb5, f(0b0100), 0xb5, f(0b0100)); try testDaa(0xb5, f(0b0101), 0x55, f(0b0101)); try testDaa(0xb5, f(0b0110), 0xaf, f(0b0100)); try testDaa(0xb5, f(0b0111), 0x4f, f(0b0101)); try testDaa(0xb5, f(0b1000), 0x15, f(0b0001)); try testDaa(0xb5, f(0b1001), 0x15, f(0b0001)); try testDaa(0xb5, f(0b1010), 0x1b, f(0b0001)); try testDaa(0xb5, f(0b1011), 0x1b, f(0b0001)); try testDaa(0xb5, f(0b1100), 0xb5, f(0b0100)); try testDaa(0xb5, f(0b1101), 0x55, f(0b0101)); try testDaa(0xb5, f(0b1110), 0xaf, f(0b0100)); try testDaa(0xb5, f(0b1111), 0x4f, f(0b0101)); try testDaa(0xb6, f(0b0000), 0x16, f(0b0001)); try testDaa(0xb6, f(0b0001), 0x16, f(0b0001)); try testDaa(0xb6, f(0b0010), 0x1c, f(0b0001)); try testDaa(0xb6, f(0b0011), 0x1c, f(0b0001)); try testDaa(0xb6, f(0b0100), 0xb6, f(0b0100)); try testDaa(0xb6, f(0b0101), 0x56, f(0b0101)); try testDaa(0xb6, f(0b0110), 0xb0, f(0b0100)); try testDaa(0xb6, f(0b0111), 0x50, f(0b0101)); try testDaa(0xb6, f(0b1000), 0x16, f(0b0001)); try testDaa(0xb6, f(0b1001), 0x16, f(0b0001)); try testDaa(0xb6, f(0b1010), 0x1c, f(0b0001)); try testDaa(0xb6, f(0b1011), 0x1c, f(0b0001)); try testDaa(0xb6, f(0b1100), 0xb6, f(0b0100)); try testDaa(0xb6, f(0b1101), 0x56, f(0b0101)); try testDaa(0xb6, f(0b1110), 0xb0, f(0b0100)); try testDaa(0xb6, f(0b1111), 0x50, f(0b0101)); try testDaa(0xb7, f(0b0000), 0x17, f(0b0001)); try testDaa(0xb7, f(0b0001), 0x17, f(0b0001)); try testDaa(0xb7, f(0b0010), 0x1d, f(0b0001)); try testDaa(0xb7, f(0b0011), 0x1d, f(0b0001)); try testDaa(0xb7, f(0b0100), 0xb7, f(0b0100)); try testDaa(0xb7, f(0b0101), 0x57, f(0b0101)); try testDaa(0xb7, f(0b0110), 0xb1, f(0b0100)); try testDaa(0xb7, f(0b0111), 0x51, f(0b0101)); try testDaa(0xb7, f(0b1000), 0x17, f(0b0001)); try testDaa(0xb7, f(0b1001), 0x17, f(0b0001)); try testDaa(0xb7, f(0b1010), 0x1d, f(0b0001)); try testDaa(0xb7, f(0b1011), 0x1d, f(0b0001)); try testDaa(0xb7, f(0b1100), 0xb7, f(0b0100)); try testDaa(0xb7, f(0b1101), 0x57, f(0b0101)); try testDaa(0xb7, f(0b1110), 0xb1, f(0b0100)); try testDaa(0xb7, f(0b1111), 0x51, f(0b0101)); try testDaa(0xb8, f(0b0000), 0x18, f(0b0001)); try testDaa(0xb8, f(0b0001), 0x18, f(0b0001)); try testDaa(0xb8, f(0b0010), 0x1e, f(0b0001)); try testDaa(0xb8, f(0b0011), 0x1e, f(0b0001)); try testDaa(0xb8, f(0b0100), 0xb8, f(0b0100)); try testDaa(0xb8, f(0b0101), 0x58, f(0b0101)); try testDaa(0xb8, f(0b0110), 0xb2, f(0b0100)); try testDaa(0xb8, f(0b0111), 0x52, f(0b0101)); try testDaa(0xb8, f(0b1000), 0x18, f(0b0001)); try testDaa(0xb8, f(0b1001), 0x18, f(0b0001)); try testDaa(0xb8, f(0b1010), 0x1e, f(0b0001)); try testDaa(0xb8, f(0b1011), 0x1e, f(0b0001)); try testDaa(0xb8, f(0b1100), 0xb8, f(0b0100)); try testDaa(0xb8, f(0b1101), 0x58, f(0b0101)); try testDaa(0xb8, f(0b1110), 0xb2, f(0b0100)); try testDaa(0xb8, f(0b1111), 0x52, f(0b0101)); try testDaa(0xb9, f(0b0000), 0x19, f(0b0001)); try testDaa(0xb9, f(0b0001), 0x19, f(0b0001)); try testDaa(0xb9, f(0b0010), 0x1f, f(0b0001)); try testDaa(0xb9, f(0b0011), 0x1f, f(0b0001)); try testDaa(0xb9, f(0b0100), 0xb9, f(0b0100)); try testDaa(0xb9, f(0b0101), 0x59, f(0b0101)); try testDaa(0xb9, f(0b0110), 0xb3, f(0b0100)); try testDaa(0xb9, f(0b0111), 0x53, f(0b0101)); try testDaa(0xb9, f(0b1000), 0x19, f(0b0001)); try testDaa(0xb9, f(0b1001), 0x19, f(0b0001)); try testDaa(0xb9, f(0b1010), 0x1f, f(0b0001)); try testDaa(0xb9, f(0b1011), 0x1f, f(0b0001)); try testDaa(0xb9, f(0b1100), 0xb9, f(0b0100)); try testDaa(0xb9, f(0b1101), 0x59, f(0b0101)); try testDaa(0xb9, f(0b1110), 0xb3, f(0b0100)); try testDaa(0xb9, f(0b1111), 0x53, f(0b0101)); try testDaa(0xba, f(0b0000), 0x20, f(0b0001)); try testDaa(0xba, f(0b0001), 0x20, f(0b0001)); try testDaa(0xba, f(0b0010), 0x20, f(0b0001)); try testDaa(0xba, f(0b0011), 0x20, f(0b0001)); try testDaa(0xba, f(0b0100), 0xba, f(0b0100)); try testDaa(0xba, f(0b0101), 0x5a, f(0b0101)); try testDaa(0xba, f(0b0110), 0xb4, f(0b0100)); try testDaa(0xba, f(0b0111), 0x54, f(0b0101)); try testDaa(0xba, f(0b1000), 0x20, f(0b0001)); try testDaa(0xba, f(0b1001), 0x20, f(0b0001)); try testDaa(0xba, f(0b1010), 0x20, f(0b0001)); try testDaa(0xba, f(0b1011), 0x20, f(0b0001)); try testDaa(0xba, f(0b1100), 0xba, f(0b0100)); try testDaa(0xba, f(0b1101), 0x5a, f(0b0101)); try testDaa(0xba, f(0b1110), 0xb4, f(0b0100)); try testDaa(0xba, f(0b1111), 0x54, f(0b0101)); try testDaa(0xbb, f(0b0000), 0x21, f(0b0001)); try testDaa(0xbb, f(0b0001), 0x21, f(0b0001)); try testDaa(0xbb, f(0b0010), 0x21, f(0b0001)); try testDaa(0xbb, f(0b0011), 0x21, f(0b0001)); try testDaa(0xbb, f(0b0100), 0xbb, f(0b0100)); try testDaa(0xbb, f(0b0101), 0x5b, f(0b0101)); try testDaa(0xbb, f(0b0110), 0xb5, f(0b0100)); try testDaa(0xbb, f(0b0111), 0x55, f(0b0101)); try testDaa(0xbb, f(0b1000), 0x21, f(0b0001)); try testDaa(0xbb, f(0b1001), 0x21, f(0b0001)); try testDaa(0xbb, f(0b1010), 0x21, f(0b0001)); try testDaa(0xbb, f(0b1011), 0x21, f(0b0001)); try testDaa(0xbb, f(0b1100), 0xbb, f(0b0100)); try testDaa(0xbb, f(0b1101), 0x5b, f(0b0101)); try testDaa(0xbb, f(0b1110), 0xb5, f(0b0100)); try testDaa(0xbb, f(0b1111), 0x55, f(0b0101)); try testDaa(0xbc, f(0b0000), 0x22, f(0b0001)); try testDaa(0xbc, f(0b0001), 0x22, f(0b0001)); try testDaa(0xbc, f(0b0010), 0x22, f(0b0001)); try testDaa(0xbc, f(0b0011), 0x22, f(0b0001)); try testDaa(0xbc, f(0b0100), 0xbc, f(0b0100)); try testDaa(0xbc, f(0b0101), 0x5c, f(0b0101)); try testDaa(0xbc, f(0b0110), 0xb6, f(0b0100)); try testDaa(0xbc, f(0b0111), 0x56, f(0b0101)); try testDaa(0xbc, f(0b1000), 0x22, f(0b0001)); try testDaa(0xbc, f(0b1001), 0x22, f(0b0001)); try testDaa(0xbc, f(0b1010), 0x22, f(0b0001)); try testDaa(0xbc, f(0b1011), 0x22, f(0b0001)); try testDaa(0xbc, f(0b1100), 0xbc, f(0b0100)); try testDaa(0xbc, f(0b1101), 0x5c, f(0b0101)); try testDaa(0xbc, f(0b1110), 0xb6, f(0b0100)); try testDaa(0xbc, f(0b1111), 0x56, f(0b0101)); try testDaa(0xbd, f(0b0000), 0x23, f(0b0001)); try testDaa(0xbd, f(0b0001), 0x23, f(0b0001)); try testDaa(0xbd, f(0b0010), 0x23, f(0b0001)); try testDaa(0xbd, f(0b0011), 0x23, f(0b0001)); try testDaa(0xbd, f(0b0100), 0xbd, f(0b0100)); try testDaa(0xbd, f(0b0101), 0x5d, f(0b0101)); try testDaa(0xbd, f(0b0110), 0xb7, f(0b0100)); try testDaa(0xbd, f(0b0111), 0x57, f(0b0101)); try testDaa(0xbd, f(0b1000), 0x23, f(0b0001)); try testDaa(0xbd, f(0b1001), 0x23, f(0b0001)); try testDaa(0xbd, f(0b1010), 0x23, f(0b0001)); try testDaa(0xbd, f(0b1011), 0x23, f(0b0001)); try testDaa(0xbd, f(0b1100), 0xbd, f(0b0100)); try testDaa(0xbd, f(0b1101), 0x5d, f(0b0101)); try testDaa(0xbd, f(0b1110), 0xb7, f(0b0100)); try testDaa(0xbd, f(0b1111), 0x57, f(0b0101)); try testDaa(0xbe, f(0b0000), 0x24, f(0b0001)); try testDaa(0xbe, f(0b0001), 0x24, f(0b0001)); try testDaa(0xbe, f(0b0010), 0x24, f(0b0001)); try testDaa(0xbe, f(0b0011), 0x24, f(0b0001)); try testDaa(0xbe, f(0b0100), 0xbe, f(0b0100)); try testDaa(0xbe, f(0b0101), 0x5e, f(0b0101)); try testDaa(0xbe, f(0b0110), 0xb8, f(0b0100)); try testDaa(0xbe, f(0b0111), 0x58, f(0b0101)); try testDaa(0xbe, f(0b1000), 0x24, f(0b0001)); try testDaa(0xbe, f(0b1001), 0x24, f(0b0001)); try testDaa(0xbe, f(0b1010), 0x24, f(0b0001)); try testDaa(0xbe, f(0b1011), 0x24, f(0b0001)); try testDaa(0xbe, f(0b1100), 0xbe, f(0b0100)); try testDaa(0xbe, f(0b1101), 0x5e, f(0b0101)); try testDaa(0xbe, f(0b1110), 0xb8, f(0b0100)); try testDaa(0xbe, f(0b1111), 0x58, f(0b0101)); try testDaa(0xbf, f(0b0000), 0x25, f(0b0001)); try testDaa(0xbf, f(0b0001), 0x25, f(0b0001)); try testDaa(0xbf, f(0b0010), 0x25, f(0b0001)); try testDaa(0xbf, f(0b0011), 0x25, f(0b0001)); try testDaa(0xbf, f(0b0100), 0xbf, f(0b0100)); try testDaa(0xbf, f(0b0101), 0x5f, f(0b0101)); try testDaa(0xbf, f(0b0110), 0xb9, f(0b0100)); try testDaa(0xbf, f(0b0111), 0x59, f(0b0101)); try testDaa(0xbf, f(0b1000), 0x25, f(0b0001)); try testDaa(0xbf, f(0b1001), 0x25, f(0b0001)); try testDaa(0xbf, f(0b1010), 0x25, f(0b0001)); try testDaa(0xbf, f(0b1011), 0x25, f(0b0001)); try testDaa(0xbf, f(0b1100), 0xbf, f(0b0100)); try testDaa(0xbf, f(0b1101), 0x5f, f(0b0101)); try testDaa(0xbf, f(0b1110), 0xb9, f(0b0100)); try testDaa(0xbf, f(0b1111), 0x59, f(0b0101)); try testDaa(0xc0, f(0b0000), 0x20, f(0b0001)); try testDaa(0xc0, f(0b0001), 0x20, f(0b0001)); try testDaa(0xc0, f(0b0010), 0x26, f(0b0001)); try testDaa(0xc0, f(0b0011), 0x26, f(0b0001)); try testDaa(0xc0, f(0b0100), 0xc0, f(0b0100)); try testDaa(0xc0, f(0b0101), 0x60, f(0b0101)); try testDaa(0xc0, f(0b0110), 0xba, f(0b0100)); try testDaa(0xc0, f(0b0111), 0x5a, f(0b0101)); try testDaa(0xc0, f(0b1000), 0x20, f(0b0001)); try testDaa(0xc0, f(0b1001), 0x20, f(0b0001)); try testDaa(0xc0, f(0b1010), 0x26, f(0b0001)); try testDaa(0xc0, f(0b1011), 0x26, f(0b0001)); try testDaa(0xc0, f(0b1100), 0xc0, f(0b0100)); try testDaa(0xc0, f(0b1101), 0x60, f(0b0101)); try testDaa(0xc0, f(0b1110), 0xba, f(0b0100)); try testDaa(0xc0, f(0b1111), 0x5a, f(0b0101)); try testDaa(0xc1, f(0b0000), 0x21, f(0b0001)); try testDaa(0xc1, f(0b0001), 0x21, f(0b0001)); try testDaa(0xc1, f(0b0010), 0x27, f(0b0001)); try testDaa(0xc1, f(0b0011), 0x27, f(0b0001)); try testDaa(0xc1, f(0b0100), 0xc1, f(0b0100)); try testDaa(0xc1, f(0b0101), 0x61, f(0b0101)); try testDaa(0xc1, f(0b0110), 0xbb, f(0b0100)); try testDaa(0xc1, f(0b0111), 0x5b, f(0b0101)); try testDaa(0xc1, f(0b1000), 0x21, f(0b0001)); try testDaa(0xc1, f(0b1001), 0x21, f(0b0001)); try testDaa(0xc1, f(0b1010), 0x27, f(0b0001)); try testDaa(0xc1, f(0b1011), 0x27, f(0b0001)); try testDaa(0xc1, f(0b1100), 0xc1, f(0b0100)); try testDaa(0xc1, f(0b1101), 0x61, f(0b0101)); try testDaa(0xc1, f(0b1110), 0xbb, f(0b0100)); try testDaa(0xc1, f(0b1111), 0x5b, f(0b0101)); try testDaa(0xc2, f(0b0000), 0x22, f(0b0001)); try testDaa(0xc2, f(0b0001), 0x22, f(0b0001)); try testDaa(0xc2, f(0b0010), 0x28, f(0b0001)); try testDaa(0xc2, f(0b0011), 0x28, f(0b0001)); try testDaa(0xc2, f(0b0100), 0xc2, f(0b0100)); try testDaa(0xc2, f(0b0101), 0x62, f(0b0101)); try testDaa(0xc2, f(0b0110), 0xbc, f(0b0100)); try testDaa(0xc2, f(0b0111), 0x5c, f(0b0101)); try testDaa(0xc2, f(0b1000), 0x22, f(0b0001)); try testDaa(0xc2, f(0b1001), 0x22, f(0b0001)); try testDaa(0xc2, f(0b1010), 0x28, f(0b0001)); try testDaa(0xc2, f(0b1011), 0x28, f(0b0001)); try testDaa(0xc2, f(0b1100), 0xc2, f(0b0100)); try testDaa(0xc2, f(0b1101), 0x62, f(0b0101)); try testDaa(0xc2, f(0b1110), 0xbc, f(0b0100)); try testDaa(0xc2, f(0b1111), 0x5c, f(0b0101)); try testDaa(0xc3, f(0b0000), 0x23, f(0b0001)); try testDaa(0xc3, f(0b0001), 0x23, f(0b0001)); try testDaa(0xc3, f(0b0010), 0x29, f(0b0001)); try testDaa(0xc3, f(0b0011), 0x29, f(0b0001)); try testDaa(0xc3, f(0b0100), 0xc3, f(0b0100)); try testDaa(0xc3, f(0b0101), 0x63, f(0b0101)); try testDaa(0xc3, f(0b0110), 0xbd, f(0b0100)); try testDaa(0xc3, f(0b0111), 0x5d, f(0b0101)); try testDaa(0xc3, f(0b1000), 0x23, f(0b0001)); try testDaa(0xc3, f(0b1001), 0x23, f(0b0001)); try testDaa(0xc3, f(0b1010), 0x29, f(0b0001)); try testDaa(0xc3, f(0b1011), 0x29, f(0b0001)); try testDaa(0xc3, f(0b1100), 0xc3, f(0b0100)); try testDaa(0xc3, f(0b1101), 0x63, f(0b0101)); try testDaa(0xc3, f(0b1110), 0xbd, f(0b0100)); try testDaa(0xc3, f(0b1111), 0x5d, f(0b0101)); try testDaa(0xc4, f(0b0000), 0x24, f(0b0001)); try testDaa(0xc4, f(0b0001), 0x24, f(0b0001)); try testDaa(0xc4, f(0b0010), 0x2a, f(0b0001)); try testDaa(0xc4, f(0b0011), 0x2a, f(0b0001)); try testDaa(0xc4, f(0b0100), 0xc4, f(0b0100)); try testDaa(0xc4, f(0b0101), 0x64, f(0b0101)); try testDaa(0xc4, f(0b0110), 0xbe, f(0b0100)); try testDaa(0xc4, f(0b0111), 0x5e, f(0b0101)); try testDaa(0xc4, f(0b1000), 0x24, f(0b0001)); try testDaa(0xc4, f(0b1001), 0x24, f(0b0001)); try testDaa(0xc4, f(0b1010), 0x2a, f(0b0001)); try testDaa(0xc4, f(0b1011), 0x2a, f(0b0001)); try testDaa(0xc4, f(0b1100), 0xc4, f(0b0100)); try testDaa(0xc4, f(0b1101), 0x64, f(0b0101)); try testDaa(0xc4, f(0b1110), 0xbe, f(0b0100)); try testDaa(0xc4, f(0b1111), 0x5e, f(0b0101)); try testDaa(0xc5, f(0b0000), 0x25, f(0b0001)); try testDaa(0xc5, f(0b0001), 0x25, f(0b0001)); try testDaa(0xc5, f(0b0010), 0x2b, f(0b0001)); try testDaa(0xc5, f(0b0011), 0x2b, f(0b0001)); try testDaa(0xc5, f(0b0100), 0xc5, f(0b0100)); try testDaa(0xc5, f(0b0101), 0x65, f(0b0101)); try testDaa(0xc5, f(0b0110), 0xbf, f(0b0100)); try testDaa(0xc5, f(0b0111), 0x5f, f(0b0101)); try testDaa(0xc5, f(0b1000), 0x25, f(0b0001)); try testDaa(0xc5, f(0b1001), 0x25, f(0b0001)); try testDaa(0xc5, f(0b1010), 0x2b, f(0b0001)); try testDaa(0xc5, f(0b1011), 0x2b, f(0b0001)); try testDaa(0xc5, f(0b1100), 0xc5, f(0b0100)); try testDaa(0xc5, f(0b1101), 0x65, f(0b0101)); try testDaa(0xc5, f(0b1110), 0xbf, f(0b0100)); try testDaa(0xc5, f(0b1111), 0x5f, f(0b0101)); try testDaa(0xc6, f(0b0000), 0x26, f(0b0001)); try testDaa(0xc6, f(0b0001), 0x26, f(0b0001)); try testDaa(0xc6, f(0b0010), 0x2c, f(0b0001)); try testDaa(0xc6, f(0b0011), 0x2c, f(0b0001)); try testDaa(0xc6, f(0b0100), 0xc6, f(0b0100)); try testDaa(0xc6, f(0b0101), 0x66, f(0b0101)); try testDaa(0xc6, f(0b0110), 0xc0, f(0b0100)); try testDaa(0xc6, f(0b0111), 0x60, f(0b0101)); try testDaa(0xc6, f(0b1000), 0x26, f(0b0001)); try testDaa(0xc6, f(0b1001), 0x26, f(0b0001)); try testDaa(0xc6, f(0b1010), 0x2c, f(0b0001)); try testDaa(0xc6, f(0b1011), 0x2c, f(0b0001)); try testDaa(0xc6, f(0b1100), 0xc6, f(0b0100)); try testDaa(0xc6, f(0b1101), 0x66, f(0b0101)); try testDaa(0xc6, f(0b1110), 0xc0, f(0b0100)); try testDaa(0xc6, f(0b1111), 0x60, f(0b0101)); try testDaa(0xc7, f(0b0000), 0x27, f(0b0001)); try testDaa(0xc7, f(0b0001), 0x27, f(0b0001)); try testDaa(0xc7, f(0b0010), 0x2d, f(0b0001)); try testDaa(0xc7, f(0b0011), 0x2d, f(0b0001)); try testDaa(0xc7, f(0b0100), 0xc7, f(0b0100)); try testDaa(0xc7, f(0b0101), 0x67, f(0b0101)); try testDaa(0xc7, f(0b0110), 0xc1, f(0b0100)); try testDaa(0xc7, f(0b0111), 0x61, f(0b0101)); try testDaa(0xc7, f(0b1000), 0x27, f(0b0001)); try testDaa(0xc7, f(0b1001), 0x27, f(0b0001)); try testDaa(0xc7, f(0b1010), 0x2d, f(0b0001)); try testDaa(0xc7, f(0b1011), 0x2d, f(0b0001)); try testDaa(0xc7, f(0b1100), 0xc7, f(0b0100)); try testDaa(0xc7, f(0b1101), 0x67, f(0b0101)); try testDaa(0xc7, f(0b1110), 0xc1, f(0b0100)); try testDaa(0xc7, f(0b1111), 0x61, f(0b0101)); try testDaa(0xc8, f(0b0000), 0x28, f(0b0001)); try testDaa(0xc8, f(0b0001), 0x28, f(0b0001)); try testDaa(0xc8, f(0b0010), 0x2e, f(0b0001)); try testDaa(0xc8, f(0b0011), 0x2e, f(0b0001)); try testDaa(0xc8, f(0b0100), 0xc8, f(0b0100)); try testDaa(0xc8, f(0b0101), 0x68, f(0b0101)); try testDaa(0xc8, f(0b0110), 0xc2, f(0b0100)); try testDaa(0xc8, f(0b0111), 0x62, f(0b0101)); try testDaa(0xc8, f(0b1000), 0x28, f(0b0001)); try testDaa(0xc8, f(0b1001), 0x28, f(0b0001)); try testDaa(0xc8, f(0b1010), 0x2e, f(0b0001)); try testDaa(0xc8, f(0b1011), 0x2e, f(0b0001)); try testDaa(0xc8, f(0b1100), 0xc8, f(0b0100)); try testDaa(0xc8, f(0b1101), 0x68, f(0b0101)); try testDaa(0xc8, f(0b1110), 0xc2, f(0b0100)); try testDaa(0xc8, f(0b1111), 0x62, f(0b0101)); try testDaa(0xc9, f(0b0000), 0x29, f(0b0001)); try testDaa(0xc9, f(0b0001), 0x29, f(0b0001)); try testDaa(0xc9, f(0b0010), 0x2f, f(0b0001)); try testDaa(0xc9, f(0b0011), 0x2f, f(0b0001)); try testDaa(0xc9, f(0b0100), 0xc9, f(0b0100)); try testDaa(0xc9, f(0b0101), 0x69, f(0b0101)); try testDaa(0xc9, f(0b0110), 0xc3, f(0b0100)); try testDaa(0xc9, f(0b0111), 0x63, f(0b0101)); try testDaa(0xc9, f(0b1000), 0x29, f(0b0001)); try testDaa(0xc9, f(0b1001), 0x29, f(0b0001)); try testDaa(0xc9, f(0b1010), 0x2f, f(0b0001)); try testDaa(0xc9, f(0b1011), 0x2f, f(0b0001)); try testDaa(0xc9, f(0b1100), 0xc9, f(0b0100)); try testDaa(0xc9, f(0b1101), 0x69, f(0b0101)); try testDaa(0xc9, f(0b1110), 0xc3, f(0b0100)); try testDaa(0xc9, f(0b1111), 0x63, f(0b0101)); try testDaa(0xca, f(0b0000), 0x30, f(0b0001)); try testDaa(0xca, f(0b0001), 0x30, f(0b0001)); try testDaa(0xca, f(0b0010), 0x30, f(0b0001)); try testDaa(0xca, f(0b0011), 0x30, f(0b0001)); try testDaa(0xca, f(0b0100), 0xca, f(0b0100)); try testDaa(0xca, f(0b0101), 0x6a, f(0b0101)); try testDaa(0xca, f(0b0110), 0xc4, f(0b0100)); try testDaa(0xca, f(0b0111), 0x64, f(0b0101)); try testDaa(0xca, f(0b1000), 0x30, f(0b0001)); try testDaa(0xca, f(0b1001), 0x30, f(0b0001)); try testDaa(0xca, f(0b1010), 0x30, f(0b0001)); try testDaa(0xca, f(0b1011), 0x30, f(0b0001)); try testDaa(0xca, f(0b1100), 0xca, f(0b0100)); try testDaa(0xca, f(0b1101), 0x6a, f(0b0101)); try testDaa(0xca, f(0b1110), 0xc4, f(0b0100)); try testDaa(0xca, f(0b1111), 0x64, f(0b0101)); try testDaa(0xcb, f(0b0000), 0x31, f(0b0001)); try testDaa(0xcb, f(0b0001), 0x31, f(0b0001)); try testDaa(0xcb, f(0b0010), 0x31, f(0b0001)); try testDaa(0xcb, f(0b0011), 0x31, f(0b0001)); try testDaa(0xcb, f(0b0100), 0xcb, f(0b0100)); try testDaa(0xcb, f(0b0101), 0x6b, f(0b0101)); try testDaa(0xcb, f(0b0110), 0xc5, f(0b0100)); try testDaa(0xcb, f(0b0111), 0x65, f(0b0101)); try testDaa(0xcb, f(0b1000), 0x31, f(0b0001)); try testDaa(0xcb, f(0b1001), 0x31, f(0b0001)); try testDaa(0xcb, f(0b1010), 0x31, f(0b0001)); try testDaa(0xcb, f(0b1011), 0x31, f(0b0001)); try testDaa(0xcb, f(0b1100), 0xcb, f(0b0100)); try testDaa(0xcb, f(0b1101), 0x6b, f(0b0101)); try testDaa(0xcb, f(0b1110), 0xc5, f(0b0100)); try testDaa(0xcb, f(0b1111), 0x65, f(0b0101)); try testDaa(0xcc, f(0b0000), 0x32, f(0b0001)); try testDaa(0xcc, f(0b0001), 0x32, f(0b0001)); try testDaa(0xcc, f(0b0010), 0x32, f(0b0001)); try testDaa(0xcc, f(0b0011), 0x32, f(0b0001)); try testDaa(0xcc, f(0b0100), 0xcc, f(0b0100)); try testDaa(0xcc, f(0b0101), 0x6c, f(0b0101)); try testDaa(0xcc, f(0b0110), 0xc6, f(0b0100)); try testDaa(0xcc, f(0b0111), 0x66, f(0b0101)); try testDaa(0xcc, f(0b1000), 0x32, f(0b0001)); try testDaa(0xcc, f(0b1001), 0x32, f(0b0001)); try testDaa(0xcc, f(0b1010), 0x32, f(0b0001)); try testDaa(0xcc, f(0b1011), 0x32, f(0b0001)); try testDaa(0xcc, f(0b1100), 0xcc, f(0b0100)); try testDaa(0xcc, f(0b1101), 0x6c, f(0b0101)); try testDaa(0xcc, f(0b1110), 0xc6, f(0b0100)); try testDaa(0xcc, f(0b1111), 0x66, f(0b0101)); try testDaa(0xcd, f(0b0000), 0x33, f(0b0001)); try testDaa(0xcd, f(0b0001), 0x33, f(0b0001)); try testDaa(0xcd, f(0b0010), 0x33, f(0b0001)); try testDaa(0xcd, f(0b0011), 0x33, f(0b0001)); try testDaa(0xcd, f(0b0100), 0xcd, f(0b0100)); try testDaa(0xcd, f(0b0101), 0x6d, f(0b0101)); try testDaa(0xcd, f(0b0110), 0xc7, f(0b0100)); try testDaa(0xcd, f(0b0111), 0x67, f(0b0101)); try testDaa(0xcd, f(0b1000), 0x33, f(0b0001)); try testDaa(0xcd, f(0b1001), 0x33, f(0b0001)); try testDaa(0xcd, f(0b1010), 0x33, f(0b0001)); try testDaa(0xcd, f(0b1011), 0x33, f(0b0001)); try testDaa(0xcd, f(0b1100), 0xcd, f(0b0100)); try testDaa(0xcd, f(0b1101), 0x6d, f(0b0101)); try testDaa(0xcd, f(0b1110), 0xc7, f(0b0100)); try testDaa(0xcd, f(0b1111), 0x67, f(0b0101)); try testDaa(0xce, f(0b0000), 0x34, f(0b0001)); try testDaa(0xce, f(0b0001), 0x34, f(0b0001)); try testDaa(0xce, f(0b0010), 0x34, f(0b0001)); try testDaa(0xce, f(0b0011), 0x34, f(0b0001)); try testDaa(0xce, f(0b0100), 0xce, f(0b0100)); try testDaa(0xce, f(0b0101), 0x6e, f(0b0101)); try testDaa(0xce, f(0b0110), 0xc8, f(0b0100)); try testDaa(0xce, f(0b0111), 0x68, f(0b0101)); try testDaa(0xce, f(0b1000), 0x34, f(0b0001)); try testDaa(0xce, f(0b1001), 0x34, f(0b0001)); try testDaa(0xce, f(0b1010), 0x34, f(0b0001)); try testDaa(0xce, f(0b1011), 0x34, f(0b0001)); try testDaa(0xce, f(0b1100), 0xce, f(0b0100)); try testDaa(0xce, f(0b1101), 0x6e, f(0b0101)); try testDaa(0xce, f(0b1110), 0xc8, f(0b0100)); try testDaa(0xce, f(0b1111), 0x68, f(0b0101)); try testDaa(0xcf, f(0b0000), 0x35, f(0b0001)); try testDaa(0xcf, f(0b0001), 0x35, f(0b0001)); try testDaa(0xcf, f(0b0010), 0x35, f(0b0001)); try testDaa(0xcf, f(0b0011), 0x35, f(0b0001)); try testDaa(0xcf, f(0b0100), 0xcf, f(0b0100)); try testDaa(0xcf, f(0b0101), 0x6f, f(0b0101)); try testDaa(0xcf, f(0b0110), 0xc9, f(0b0100)); try testDaa(0xcf, f(0b0111), 0x69, f(0b0101)); try testDaa(0xcf, f(0b1000), 0x35, f(0b0001)); try testDaa(0xcf, f(0b1001), 0x35, f(0b0001)); try testDaa(0xcf, f(0b1010), 0x35, f(0b0001)); try testDaa(0xcf, f(0b1011), 0x35, f(0b0001)); try testDaa(0xcf, f(0b1100), 0xcf, f(0b0100)); try testDaa(0xcf, f(0b1101), 0x6f, f(0b0101)); try testDaa(0xcf, f(0b1110), 0xc9, f(0b0100)); try testDaa(0xcf, f(0b1111), 0x69, f(0b0101)); try testDaa(0xd0, f(0b0000), 0x30, f(0b0001)); try testDaa(0xd0, f(0b0001), 0x30, f(0b0001)); try testDaa(0xd0, f(0b0010), 0x36, f(0b0001)); try testDaa(0xd0, f(0b0011), 0x36, f(0b0001)); try testDaa(0xd0, f(0b0100), 0xd0, f(0b0100)); try testDaa(0xd0, f(0b0101), 0x70, f(0b0101)); try testDaa(0xd0, f(0b0110), 0xca, f(0b0100)); try testDaa(0xd0, f(0b0111), 0x6a, f(0b0101)); try testDaa(0xd0, f(0b1000), 0x30, f(0b0001)); try testDaa(0xd0, f(0b1001), 0x30, f(0b0001)); try testDaa(0xd0, f(0b1010), 0x36, f(0b0001)); try testDaa(0xd0, f(0b1011), 0x36, f(0b0001)); try testDaa(0xd0, f(0b1100), 0xd0, f(0b0100)); try testDaa(0xd0, f(0b1101), 0x70, f(0b0101)); try testDaa(0xd0, f(0b1110), 0xca, f(0b0100)); try testDaa(0xd0, f(0b1111), 0x6a, f(0b0101)); try testDaa(0xd1, f(0b0000), 0x31, f(0b0001)); try testDaa(0xd1, f(0b0001), 0x31, f(0b0001)); try testDaa(0xd1, f(0b0010), 0x37, f(0b0001)); try testDaa(0xd1, f(0b0011), 0x37, f(0b0001)); try testDaa(0xd1, f(0b0100), 0xd1, f(0b0100)); try testDaa(0xd1, f(0b0101), 0x71, f(0b0101)); try testDaa(0xd1, f(0b0110), 0xcb, f(0b0100)); try testDaa(0xd1, f(0b0111), 0x6b, f(0b0101)); try testDaa(0xd1, f(0b1000), 0x31, f(0b0001)); try testDaa(0xd1, f(0b1001), 0x31, f(0b0001)); try testDaa(0xd1, f(0b1010), 0x37, f(0b0001)); try testDaa(0xd1, f(0b1011), 0x37, f(0b0001)); try testDaa(0xd1, f(0b1100), 0xd1, f(0b0100)); try testDaa(0xd1, f(0b1101), 0x71, f(0b0101)); try testDaa(0xd1, f(0b1110), 0xcb, f(0b0100)); try testDaa(0xd1, f(0b1111), 0x6b, f(0b0101)); try testDaa(0xd2, f(0b0000), 0x32, f(0b0001)); try testDaa(0xd2, f(0b0001), 0x32, f(0b0001)); try testDaa(0xd2, f(0b0010), 0x38, f(0b0001)); try testDaa(0xd2, f(0b0011), 0x38, f(0b0001)); try testDaa(0xd2, f(0b0100), 0xd2, f(0b0100)); try testDaa(0xd2, f(0b0101), 0x72, f(0b0101)); try testDaa(0xd2, f(0b0110), 0xcc, f(0b0100)); try testDaa(0xd2, f(0b0111), 0x6c, f(0b0101)); try testDaa(0xd2, f(0b1000), 0x32, f(0b0001)); try testDaa(0xd2, f(0b1001), 0x32, f(0b0001)); try testDaa(0xd2, f(0b1010), 0x38, f(0b0001)); try testDaa(0xd2, f(0b1011), 0x38, f(0b0001)); try testDaa(0xd2, f(0b1100), 0xd2, f(0b0100)); try testDaa(0xd2, f(0b1101), 0x72, f(0b0101)); try testDaa(0xd2, f(0b1110), 0xcc, f(0b0100)); try testDaa(0xd2, f(0b1111), 0x6c, f(0b0101)); try testDaa(0xd3, f(0b0000), 0x33, f(0b0001)); try testDaa(0xd3, f(0b0001), 0x33, f(0b0001)); try testDaa(0xd3, f(0b0010), 0x39, f(0b0001)); try testDaa(0xd3, f(0b0011), 0x39, f(0b0001)); try testDaa(0xd3, f(0b0100), 0xd3, f(0b0100)); try testDaa(0xd3, f(0b0101), 0x73, f(0b0101)); try testDaa(0xd3, f(0b0110), 0xcd, f(0b0100)); try testDaa(0xd3, f(0b0111), 0x6d, f(0b0101)); try testDaa(0xd3, f(0b1000), 0x33, f(0b0001)); try testDaa(0xd3, f(0b1001), 0x33, f(0b0001)); try testDaa(0xd3, f(0b1010), 0x39, f(0b0001)); try testDaa(0xd3, f(0b1011), 0x39, f(0b0001)); try testDaa(0xd3, f(0b1100), 0xd3, f(0b0100)); try testDaa(0xd3, f(0b1101), 0x73, f(0b0101)); try testDaa(0xd3, f(0b1110), 0xcd, f(0b0100)); try testDaa(0xd3, f(0b1111), 0x6d, f(0b0101)); try testDaa(0xd4, f(0b0000), 0x34, f(0b0001)); try testDaa(0xd4, f(0b0001), 0x34, f(0b0001)); try testDaa(0xd4, f(0b0010), 0x3a, f(0b0001)); try testDaa(0xd4, f(0b0011), 0x3a, f(0b0001)); try testDaa(0xd4, f(0b0100), 0xd4, f(0b0100)); try testDaa(0xd4, f(0b0101), 0x74, f(0b0101)); try testDaa(0xd4, f(0b0110), 0xce, f(0b0100)); try testDaa(0xd4, f(0b0111), 0x6e, f(0b0101)); try testDaa(0xd4, f(0b1000), 0x34, f(0b0001)); try testDaa(0xd4, f(0b1001), 0x34, f(0b0001)); try testDaa(0xd4, f(0b1010), 0x3a, f(0b0001)); try testDaa(0xd4, f(0b1011), 0x3a, f(0b0001)); try testDaa(0xd4, f(0b1100), 0xd4, f(0b0100)); try testDaa(0xd4, f(0b1101), 0x74, f(0b0101)); try testDaa(0xd4, f(0b1110), 0xce, f(0b0100)); try testDaa(0xd4, f(0b1111), 0x6e, f(0b0101)); try testDaa(0xd5, f(0b0000), 0x35, f(0b0001)); try testDaa(0xd5, f(0b0001), 0x35, f(0b0001)); try testDaa(0xd5, f(0b0010), 0x3b, f(0b0001)); try testDaa(0xd5, f(0b0011), 0x3b, f(0b0001)); try testDaa(0xd5, f(0b0100), 0xd5, f(0b0100)); try testDaa(0xd5, f(0b0101), 0x75, f(0b0101)); try testDaa(0xd5, f(0b0110), 0xcf, f(0b0100)); try testDaa(0xd5, f(0b0111), 0x6f, f(0b0101)); try testDaa(0xd5, f(0b1000), 0x35, f(0b0001)); try testDaa(0xd5, f(0b1001), 0x35, f(0b0001)); try testDaa(0xd5, f(0b1010), 0x3b, f(0b0001)); try testDaa(0xd5, f(0b1011), 0x3b, f(0b0001)); try testDaa(0xd5, f(0b1100), 0xd5, f(0b0100)); try testDaa(0xd5, f(0b1101), 0x75, f(0b0101)); try testDaa(0xd5, f(0b1110), 0xcf, f(0b0100)); try testDaa(0xd5, f(0b1111), 0x6f, f(0b0101)); try testDaa(0xd6, f(0b0000), 0x36, f(0b0001)); try testDaa(0xd6, f(0b0001), 0x36, f(0b0001)); try testDaa(0xd6, f(0b0010), 0x3c, f(0b0001)); try testDaa(0xd6, f(0b0011), 0x3c, f(0b0001)); try testDaa(0xd6, f(0b0100), 0xd6, f(0b0100)); try testDaa(0xd6, f(0b0101), 0x76, f(0b0101)); try testDaa(0xd6, f(0b0110), 0xd0, f(0b0100)); try testDaa(0xd6, f(0b0111), 0x70, f(0b0101)); try testDaa(0xd6, f(0b1000), 0x36, f(0b0001)); try testDaa(0xd6, f(0b1001), 0x36, f(0b0001)); try testDaa(0xd6, f(0b1010), 0x3c, f(0b0001)); try testDaa(0xd6, f(0b1011), 0x3c, f(0b0001)); try testDaa(0xd6, f(0b1100), 0xd6, f(0b0100)); try testDaa(0xd6, f(0b1101), 0x76, f(0b0101)); try testDaa(0xd6, f(0b1110), 0xd0, f(0b0100)); try testDaa(0xd6, f(0b1111), 0x70, f(0b0101)); try testDaa(0xd7, f(0b0000), 0x37, f(0b0001)); try testDaa(0xd7, f(0b0001), 0x37, f(0b0001)); try testDaa(0xd7, f(0b0010), 0x3d, f(0b0001)); try testDaa(0xd7, f(0b0011), 0x3d, f(0b0001)); try testDaa(0xd7, f(0b0100), 0xd7, f(0b0100)); try testDaa(0xd7, f(0b0101), 0x77, f(0b0101)); try testDaa(0xd7, f(0b0110), 0xd1, f(0b0100)); try testDaa(0xd7, f(0b0111), 0x71, f(0b0101)); try testDaa(0xd7, f(0b1000), 0x37, f(0b0001)); try testDaa(0xd7, f(0b1001), 0x37, f(0b0001)); try testDaa(0xd7, f(0b1010), 0x3d, f(0b0001)); try testDaa(0xd7, f(0b1011), 0x3d, f(0b0001)); try testDaa(0xd7, f(0b1100), 0xd7, f(0b0100)); try testDaa(0xd7, f(0b1101), 0x77, f(0b0101)); try testDaa(0xd7, f(0b1110), 0xd1, f(0b0100)); try testDaa(0xd7, f(0b1111), 0x71, f(0b0101)); try testDaa(0xd8, f(0b0000), 0x38, f(0b0001)); try testDaa(0xd8, f(0b0001), 0x38, f(0b0001)); try testDaa(0xd8, f(0b0010), 0x3e, f(0b0001)); try testDaa(0xd8, f(0b0011), 0x3e, f(0b0001)); try testDaa(0xd8, f(0b0100), 0xd8, f(0b0100)); try testDaa(0xd8, f(0b0101), 0x78, f(0b0101)); try testDaa(0xd8, f(0b0110), 0xd2, f(0b0100)); try testDaa(0xd8, f(0b0111), 0x72, f(0b0101)); try testDaa(0xd8, f(0b1000), 0x38, f(0b0001)); try testDaa(0xd8, f(0b1001), 0x38, f(0b0001)); try testDaa(0xd8, f(0b1010), 0x3e, f(0b0001)); try testDaa(0xd8, f(0b1011), 0x3e, f(0b0001)); try testDaa(0xd8, f(0b1100), 0xd8, f(0b0100)); try testDaa(0xd8, f(0b1101), 0x78, f(0b0101)); try testDaa(0xd8, f(0b1110), 0xd2, f(0b0100)); try testDaa(0xd8, f(0b1111), 0x72, f(0b0101)); try testDaa(0xd9, f(0b0000), 0x39, f(0b0001)); try testDaa(0xd9, f(0b0001), 0x39, f(0b0001)); try testDaa(0xd9, f(0b0010), 0x3f, f(0b0001)); try testDaa(0xd9, f(0b0011), 0x3f, f(0b0001)); try testDaa(0xd9, f(0b0100), 0xd9, f(0b0100)); try testDaa(0xd9, f(0b0101), 0x79, f(0b0101)); try testDaa(0xd9, f(0b0110), 0xd3, f(0b0100)); try testDaa(0xd9, f(0b0111), 0x73, f(0b0101)); try testDaa(0xd9, f(0b1000), 0x39, f(0b0001)); try testDaa(0xd9, f(0b1001), 0x39, f(0b0001)); try testDaa(0xd9, f(0b1010), 0x3f, f(0b0001)); try testDaa(0xd9, f(0b1011), 0x3f, f(0b0001)); try testDaa(0xd9, f(0b1100), 0xd9, f(0b0100)); try testDaa(0xd9, f(0b1101), 0x79, f(0b0101)); try testDaa(0xd9, f(0b1110), 0xd3, f(0b0100)); try testDaa(0xd9, f(0b1111), 0x73, f(0b0101)); try testDaa(0xda, f(0b0000), 0x40, f(0b0001)); try testDaa(0xda, f(0b0001), 0x40, f(0b0001)); try testDaa(0xda, f(0b0010), 0x40, f(0b0001)); try testDaa(0xda, f(0b0011), 0x40, f(0b0001)); try testDaa(0xda, f(0b0100), 0xda, f(0b0100)); try testDaa(0xda, f(0b0101), 0x7a, f(0b0101)); try testDaa(0xda, f(0b0110), 0xd4, f(0b0100)); try testDaa(0xda, f(0b0111), 0x74, f(0b0101)); try testDaa(0xda, f(0b1000), 0x40, f(0b0001)); try testDaa(0xda, f(0b1001), 0x40, f(0b0001)); try testDaa(0xda, f(0b1010), 0x40, f(0b0001)); try testDaa(0xda, f(0b1011), 0x40, f(0b0001)); try testDaa(0xda, f(0b1100), 0xda, f(0b0100)); try testDaa(0xda, f(0b1101), 0x7a, f(0b0101)); try testDaa(0xda, f(0b1110), 0xd4, f(0b0100)); try testDaa(0xda, f(0b1111), 0x74, f(0b0101)); try testDaa(0xdb, f(0b0000), 0x41, f(0b0001)); try testDaa(0xdb, f(0b0001), 0x41, f(0b0001)); try testDaa(0xdb, f(0b0010), 0x41, f(0b0001)); try testDaa(0xdb, f(0b0011), 0x41, f(0b0001)); try testDaa(0xdb, f(0b0100), 0xdb, f(0b0100)); try testDaa(0xdb, f(0b0101), 0x7b, f(0b0101)); try testDaa(0xdb, f(0b0110), 0xd5, f(0b0100)); try testDaa(0xdb, f(0b0111), 0x75, f(0b0101)); try testDaa(0xdb, f(0b1000), 0x41, f(0b0001)); try testDaa(0xdb, f(0b1001), 0x41, f(0b0001)); try testDaa(0xdb, f(0b1010), 0x41, f(0b0001)); try testDaa(0xdb, f(0b1011), 0x41, f(0b0001)); try testDaa(0xdb, f(0b1100), 0xdb, f(0b0100)); try testDaa(0xdb, f(0b1101), 0x7b, f(0b0101)); try testDaa(0xdb, f(0b1110), 0xd5, f(0b0100)); try testDaa(0xdb, f(0b1111), 0x75, f(0b0101)); try testDaa(0xdc, f(0b0000), 0x42, f(0b0001)); try testDaa(0xdc, f(0b0001), 0x42, f(0b0001)); try testDaa(0xdc, f(0b0010), 0x42, f(0b0001)); try testDaa(0xdc, f(0b0011), 0x42, f(0b0001)); try testDaa(0xdc, f(0b0100), 0xdc, f(0b0100)); try testDaa(0xdc, f(0b0101), 0x7c, f(0b0101)); try testDaa(0xdc, f(0b0110), 0xd6, f(0b0100)); try testDaa(0xdc, f(0b0111), 0x76, f(0b0101)); try testDaa(0xdc, f(0b1000), 0x42, f(0b0001)); try testDaa(0xdc, f(0b1001), 0x42, f(0b0001)); try testDaa(0xdc, f(0b1010), 0x42, f(0b0001)); try testDaa(0xdc, f(0b1011), 0x42, f(0b0001)); try testDaa(0xdc, f(0b1100), 0xdc, f(0b0100)); try testDaa(0xdc, f(0b1101), 0x7c, f(0b0101)); try testDaa(0xdc, f(0b1110), 0xd6, f(0b0100)); try testDaa(0xdc, f(0b1111), 0x76, f(0b0101)); try testDaa(0xdd, f(0b0000), 0x43, f(0b0001)); try testDaa(0xdd, f(0b0001), 0x43, f(0b0001)); try testDaa(0xdd, f(0b0010), 0x43, f(0b0001)); try testDaa(0xdd, f(0b0011), 0x43, f(0b0001)); try testDaa(0xdd, f(0b0100), 0xdd, f(0b0100)); try testDaa(0xdd, f(0b0101), 0x7d, f(0b0101)); try testDaa(0xdd, f(0b0110), 0xd7, f(0b0100)); try testDaa(0xdd, f(0b0111), 0x77, f(0b0101)); try testDaa(0xdd, f(0b1000), 0x43, f(0b0001)); try testDaa(0xdd, f(0b1001), 0x43, f(0b0001)); try testDaa(0xdd, f(0b1010), 0x43, f(0b0001)); try testDaa(0xdd, f(0b1011), 0x43, f(0b0001)); try testDaa(0xdd, f(0b1100), 0xdd, f(0b0100)); try testDaa(0xdd, f(0b1101), 0x7d, f(0b0101)); try testDaa(0xdd, f(0b1110), 0xd7, f(0b0100)); try testDaa(0xdd, f(0b1111), 0x77, f(0b0101)); try testDaa(0xde, f(0b0000), 0x44, f(0b0001)); try testDaa(0xde, f(0b0001), 0x44, f(0b0001)); try testDaa(0xde, f(0b0010), 0x44, f(0b0001)); try testDaa(0xde, f(0b0011), 0x44, f(0b0001)); try testDaa(0xde, f(0b0100), 0xde, f(0b0100)); try testDaa(0xde, f(0b0101), 0x7e, f(0b0101)); try testDaa(0xde, f(0b0110), 0xd8, f(0b0100)); try testDaa(0xde, f(0b0111), 0x78, f(0b0101)); try testDaa(0xde, f(0b1000), 0x44, f(0b0001)); try testDaa(0xde, f(0b1001), 0x44, f(0b0001)); try testDaa(0xde, f(0b1010), 0x44, f(0b0001)); try testDaa(0xde, f(0b1011), 0x44, f(0b0001)); try testDaa(0xde, f(0b1100), 0xde, f(0b0100)); try testDaa(0xde, f(0b1101), 0x7e, f(0b0101)); try testDaa(0xde, f(0b1110), 0xd8, f(0b0100)); try testDaa(0xde, f(0b1111), 0x78, f(0b0101)); try testDaa(0xdf, f(0b0000), 0x45, f(0b0001)); try testDaa(0xdf, f(0b0001), 0x45, f(0b0001)); try testDaa(0xdf, f(0b0010), 0x45, f(0b0001)); try testDaa(0xdf, f(0b0011), 0x45, f(0b0001)); try testDaa(0xdf, f(0b0100), 0xdf, f(0b0100)); try testDaa(0xdf, f(0b0101), 0x7f, f(0b0101)); try testDaa(0xdf, f(0b0110), 0xd9, f(0b0100)); try testDaa(0xdf, f(0b0111), 0x79, f(0b0101)); try testDaa(0xdf, f(0b1000), 0x45, f(0b0001)); try testDaa(0xdf, f(0b1001), 0x45, f(0b0001)); try testDaa(0xdf, f(0b1010), 0x45, f(0b0001)); try testDaa(0xdf, f(0b1011), 0x45, f(0b0001)); try testDaa(0xdf, f(0b1100), 0xdf, f(0b0100)); try testDaa(0xdf, f(0b1101), 0x7f, f(0b0101)); try testDaa(0xdf, f(0b1110), 0xd9, f(0b0100)); try testDaa(0xdf, f(0b1111), 0x79, f(0b0101)); try testDaa(0xe0, f(0b0000), 0x40, f(0b0001)); try testDaa(0xe0, f(0b0001), 0x40, f(0b0001)); try testDaa(0xe0, f(0b0010), 0x46, f(0b0001)); try testDaa(0xe0, f(0b0011), 0x46, f(0b0001)); try testDaa(0xe0, f(0b0100), 0xe0, f(0b0100)); try testDaa(0xe0, f(0b0101), 0x80, f(0b0101)); try testDaa(0xe0, f(0b0110), 0xda, f(0b0100)); try testDaa(0xe0, f(0b0111), 0x7a, f(0b0101)); try testDaa(0xe0, f(0b1000), 0x40, f(0b0001)); try testDaa(0xe0, f(0b1001), 0x40, f(0b0001)); try testDaa(0xe0, f(0b1010), 0x46, f(0b0001)); try testDaa(0xe0, f(0b1011), 0x46, f(0b0001)); try testDaa(0xe0, f(0b1100), 0xe0, f(0b0100)); try testDaa(0xe0, f(0b1101), 0x80, f(0b0101)); try testDaa(0xe0, f(0b1110), 0xda, f(0b0100)); try testDaa(0xe0, f(0b1111), 0x7a, f(0b0101)); try testDaa(0xe1, f(0b0000), 0x41, f(0b0001)); try testDaa(0xe1, f(0b0001), 0x41, f(0b0001)); try testDaa(0xe1, f(0b0010), 0x47, f(0b0001)); try testDaa(0xe1, f(0b0011), 0x47, f(0b0001)); try testDaa(0xe1, f(0b0100), 0xe1, f(0b0100)); try testDaa(0xe1, f(0b0101), 0x81, f(0b0101)); try testDaa(0xe1, f(0b0110), 0xdb, f(0b0100)); try testDaa(0xe1, f(0b0111), 0x7b, f(0b0101)); try testDaa(0xe1, f(0b1000), 0x41, f(0b0001)); try testDaa(0xe1, f(0b1001), 0x41, f(0b0001)); try testDaa(0xe1, f(0b1010), 0x47, f(0b0001)); try testDaa(0xe1, f(0b1011), 0x47, f(0b0001)); try testDaa(0xe1, f(0b1100), 0xe1, f(0b0100)); try testDaa(0xe1, f(0b1101), 0x81, f(0b0101)); try testDaa(0xe1, f(0b1110), 0xdb, f(0b0100)); try testDaa(0xe1, f(0b1111), 0x7b, f(0b0101)); try testDaa(0xe2, f(0b0000), 0x42, f(0b0001)); try testDaa(0xe2, f(0b0001), 0x42, f(0b0001)); try testDaa(0xe2, f(0b0010), 0x48, f(0b0001)); try testDaa(0xe2, f(0b0011), 0x48, f(0b0001)); try testDaa(0xe2, f(0b0100), 0xe2, f(0b0100)); try testDaa(0xe2, f(0b0101), 0x82, f(0b0101)); try testDaa(0xe2, f(0b0110), 0xdc, f(0b0100)); try testDaa(0xe2, f(0b0111), 0x7c, f(0b0101)); try testDaa(0xe2, f(0b1000), 0x42, f(0b0001)); try testDaa(0xe2, f(0b1001), 0x42, f(0b0001)); try testDaa(0xe2, f(0b1010), 0x48, f(0b0001)); try testDaa(0xe2, f(0b1011), 0x48, f(0b0001)); try testDaa(0xe2, f(0b1100), 0xe2, f(0b0100)); try testDaa(0xe2, f(0b1101), 0x82, f(0b0101)); try testDaa(0xe2, f(0b1110), 0xdc, f(0b0100)); try testDaa(0xe2, f(0b1111), 0x7c, f(0b0101)); try testDaa(0xe3, f(0b0000), 0x43, f(0b0001)); try testDaa(0xe3, f(0b0001), 0x43, f(0b0001)); try testDaa(0xe3, f(0b0010), 0x49, f(0b0001)); try testDaa(0xe3, f(0b0011), 0x49, f(0b0001)); try testDaa(0xe3, f(0b0100), 0xe3, f(0b0100)); try testDaa(0xe3, f(0b0101), 0x83, f(0b0101)); try testDaa(0xe3, f(0b0110), 0xdd, f(0b0100)); try testDaa(0xe3, f(0b0111), 0x7d, f(0b0101)); try testDaa(0xe3, f(0b1000), 0x43, f(0b0001)); try testDaa(0xe3, f(0b1001), 0x43, f(0b0001)); try testDaa(0xe3, f(0b1010), 0x49, f(0b0001)); try testDaa(0xe3, f(0b1011), 0x49, f(0b0001)); try testDaa(0xe3, f(0b1100), 0xe3, f(0b0100)); try testDaa(0xe3, f(0b1101), 0x83, f(0b0101)); try testDaa(0xe3, f(0b1110), 0xdd, f(0b0100)); try testDaa(0xe3, f(0b1111), 0x7d, f(0b0101)); try testDaa(0xe4, f(0b0000), 0x44, f(0b0001)); try testDaa(0xe4, f(0b0001), 0x44, f(0b0001)); try testDaa(0xe4, f(0b0010), 0x4a, f(0b0001)); try testDaa(0xe4, f(0b0011), 0x4a, f(0b0001)); try testDaa(0xe4, f(0b0100), 0xe4, f(0b0100)); try testDaa(0xe4, f(0b0101), 0x84, f(0b0101)); try testDaa(0xe4, f(0b0110), 0xde, f(0b0100)); try testDaa(0xe4, f(0b0111), 0x7e, f(0b0101)); try testDaa(0xe4, f(0b1000), 0x44, f(0b0001)); try testDaa(0xe4, f(0b1001), 0x44, f(0b0001)); try testDaa(0xe4, f(0b1010), 0x4a, f(0b0001)); try testDaa(0xe4, f(0b1011), 0x4a, f(0b0001)); try testDaa(0xe4, f(0b1100), 0xe4, f(0b0100)); try testDaa(0xe4, f(0b1101), 0x84, f(0b0101)); try testDaa(0xe4, f(0b1110), 0xde, f(0b0100)); try testDaa(0xe4, f(0b1111), 0x7e, f(0b0101)); try testDaa(0xe5, f(0b0000), 0x45, f(0b0001)); try testDaa(0xe5, f(0b0001), 0x45, f(0b0001)); try testDaa(0xe5, f(0b0010), 0x4b, f(0b0001)); try testDaa(0xe5, f(0b0011), 0x4b, f(0b0001)); try testDaa(0xe5, f(0b0100), 0xe5, f(0b0100)); try testDaa(0xe5, f(0b0101), 0x85, f(0b0101)); try testDaa(0xe5, f(0b0110), 0xdf, f(0b0100)); try testDaa(0xe5, f(0b0111), 0x7f, f(0b0101)); try testDaa(0xe5, f(0b1000), 0x45, f(0b0001)); try testDaa(0xe5, f(0b1001), 0x45, f(0b0001)); try testDaa(0xe5, f(0b1010), 0x4b, f(0b0001)); try testDaa(0xe5, f(0b1011), 0x4b, f(0b0001)); try testDaa(0xe5, f(0b1100), 0xe5, f(0b0100)); try testDaa(0xe5, f(0b1101), 0x85, f(0b0101)); try testDaa(0xe5, f(0b1110), 0xdf, f(0b0100)); try testDaa(0xe5, f(0b1111), 0x7f, f(0b0101)); try testDaa(0xe6, f(0b0000), 0x46, f(0b0001)); try testDaa(0xe6, f(0b0001), 0x46, f(0b0001)); try testDaa(0xe6, f(0b0010), 0x4c, f(0b0001)); try testDaa(0xe6, f(0b0011), 0x4c, f(0b0001)); try testDaa(0xe6, f(0b0100), 0xe6, f(0b0100)); try testDaa(0xe6, f(0b0101), 0x86, f(0b0101)); try testDaa(0xe6, f(0b0110), 0xe0, f(0b0100)); try testDaa(0xe6, f(0b0111), 0x80, f(0b0101)); try testDaa(0xe6, f(0b1000), 0x46, f(0b0001)); try testDaa(0xe6, f(0b1001), 0x46, f(0b0001)); try testDaa(0xe6, f(0b1010), 0x4c, f(0b0001)); try testDaa(0xe6, f(0b1011), 0x4c, f(0b0001)); try testDaa(0xe6, f(0b1100), 0xe6, f(0b0100)); try testDaa(0xe6, f(0b1101), 0x86, f(0b0101)); try testDaa(0xe6, f(0b1110), 0xe0, f(0b0100)); try testDaa(0xe6, f(0b1111), 0x80, f(0b0101)); try testDaa(0xe7, f(0b0000), 0x47, f(0b0001)); try testDaa(0xe7, f(0b0001), 0x47, f(0b0001)); try testDaa(0xe7, f(0b0010), 0x4d, f(0b0001)); try testDaa(0xe7, f(0b0011), 0x4d, f(0b0001)); try testDaa(0xe7, f(0b0100), 0xe7, f(0b0100)); try testDaa(0xe7, f(0b0101), 0x87, f(0b0101)); try testDaa(0xe7, f(0b0110), 0xe1, f(0b0100)); try testDaa(0xe7, f(0b0111), 0x81, f(0b0101)); try testDaa(0xe7, f(0b1000), 0x47, f(0b0001)); try testDaa(0xe7, f(0b1001), 0x47, f(0b0001)); try testDaa(0xe7, f(0b1010), 0x4d, f(0b0001)); try testDaa(0xe7, f(0b1011), 0x4d, f(0b0001)); try testDaa(0xe7, f(0b1100), 0xe7, f(0b0100)); try testDaa(0xe7, f(0b1101), 0x87, f(0b0101)); try testDaa(0xe7, f(0b1110), 0xe1, f(0b0100)); try testDaa(0xe7, f(0b1111), 0x81, f(0b0101)); try testDaa(0xe8, f(0b0000), 0x48, f(0b0001)); try testDaa(0xe8, f(0b0001), 0x48, f(0b0001)); try testDaa(0xe8, f(0b0010), 0x4e, f(0b0001)); try testDaa(0xe8, f(0b0011), 0x4e, f(0b0001)); try testDaa(0xe8, f(0b0100), 0xe8, f(0b0100)); try testDaa(0xe8, f(0b0101), 0x88, f(0b0101)); try testDaa(0xe8, f(0b0110), 0xe2, f(0b0100)); try testDaa(0xe8, f(0b0111), 0x82, f(0b0101)); try testDaa(0xe8, f(0b1000), 0x48, f(0b0001)); try testDaa(0xe8, f(0b1001), 0x48, f(0b0001)); try testDaa(0xe8, f(0b1010), 0x4e, f(0b0001)); try testDaa(0xe8, f(0b1011), 0x4e, f(0b0001)); try testDaa(0xe8, f(0b1100), 0xe8, f(0b0100)); try testDaa(0xe8, f(0b1101), 0x88, f(0b0101)); try testDaa(0xe8, f(0b1110), 0xe2, f(0b0100)); try testDaa(0xe8, f(0b1111), 0x82, f(0b0101)); try testDaa(0xe9, f(0b0000), 0x49, f(0b0001)); try testDaa(0xe9, f(0b0001), 0x49, f(0b0001)); try testDaa(0xe9, f(0b0010), 0x4f, f(0b0001)); try testDaa(0xe9, f(0b0011), 0x4f, f(0b0001)); try testDaa(0xe9, f(0b0100), 0xe9, f(0b0100)); try testDaa(0xe9, f(0b0101), 0x89, f(0b0101)); try testDaa(0xe9, f(0b0110), 0xe3, f(0b0100)); try testDaa(0xe9, f(0b0111), 0x83, f(0b0101)); try testDaa(0xe9, f(0b1000), 0x49, f(0b0001)); try testDaa(0xe9, f(0b1001), 0x49, f(0b0001)); try testDaa(0xe9, f(0b1010), 0x4f, f(0b0001)); try testDaa(0xe9, f(0b1011), 0x4f, f(0b0001)); try testDaa(0xe9, f(0b1100), 0xe9, f(0b0100)); try testDaa(0xe9, f(0b1101), 0x89, f(0b0101)); try testDaa(0xe9, f(0b1110), 0xe3, f(0b0100)); try testDaa(0xe9, f(0b1111), 0x83, f(0b0101)); try testDaa(0xea, f(0b0000), 0x50, f(0b0001)); try testDaa(0xea, f(0b0001), 0x50, f(0b0001)); try testDaa(0xea, f(0b0010), 0x50, f(0b0001)); try testDaa(0xea, f(0b0011), 0x50, f(0b0001)); try testDaa(0xea, f(0b0100), 0xea, f(0b0100)); try testDaa(0xea, f(0b0101), 0x8a, f(0b0101)); try testDaa(0xea, f(0b0110), 0xe4, f(0b0100)); try testDaa(0xea, f(0b0111), 0x84, f(0b0101)); try testDaa(0xea, f(0b1000), 0x50, f(0b0001)); try testDaa(0xea, f(0b1001), 0x50, f(0b0001)); try testDaa(0xea, f(0b1010), 0x50, f(0b0001)); try testDaa(0xea, f(0b1011), 0x50, f(0b0001)); try testDaa(0xea, f(0b1100), 0xea, f(0b0100)); try testDaa(0xea, f(0b1101), 0x8a, f(0b0101)); try testDaa(0xea, f(0b1110), 0xe4, f(0b0100)); try testDaa(0xea, f(0b1111), 0x84, f(0b0101)); try testDaa(0xeb, f(0b0000), 0x51, f(0b0001)); try testDaa(0xeb, f(0b0001), 0x51, f(0b0001)); try testDaa(0xeb, f(0b0010), 0x51, f(0b0001)); try testDaa(0xeb, f(0b0011), 0x51, f(0b0001)); try testDaa(0xeb, f(0b0100), 0xeb, f(0b0100)); try testDaa(0xeb, f(0b0101), 0x8b, f(0b0101)); try testDaa(0xeb, f(0b0110), 0xe5, f(0b0100)); try testDaa(0xeb, f(0b0111), 0x85, f(0b0101)); try testDaa(0xeb, f(0b1000), 0x51, f(0b0001)); try testDaa(0xeb, f(0b1001), 0x51, f(0b0001)); try testDaa(0xeb, f(0b1010), 0x51, f(0b0001)); try testDaa(0xeb, f(0b1011), 0x51, f(0b0001)); try testDaa(0xeb, f(0b1100), 0xeb, f(0b0100)); try testDaa(0xeb, f(0b1101), 0x8b, f(0b0101)); try testDaa(0xeb, f(0b1110), 0xe5, f(0b0100)); try testDaa(0xeb, f(0b1111), 0x85, f(0b0101)); try testDaa(0xec, f(0b0000), 0x52, f(0b0001)); try testDaa(0xec, f(0b0001), 0x52, f(0b0001)); try testDaa(0xec, f(0b0010), 0x52, f(0b0001)); try testDaa(0xec, f(0b0011), 0x52, f(0b0001)); try testDaa(0xec, f(0b0100), 0xec, f(0b0100)); try testDaa(0xec, f(0b0101), 0x8c, f(0b0101)); try testDaa(0xec, f(0b0110), 0xe6, f(0b0100)); try testDaa(0xec, f(0b0111), 0x86, f(0b0101)); try testDaa(0xec, f(0b1000), 0x52, f(0b0001)); try testDaa(0xec, f(0b1001), 0x52, f(0b0001)); try testDaa(0xec, f(0b1010), 0x52, f(0b0001)); try testDaa(0xec, f(0b1011), 0x52, f(0b0001)); try testDaa(0xec, f(0b1100), 0xec, f(0b0100)); try testDaa(0xec, f(0b1101), 0x8c, f(0b0101)); try testDaa(0xec, f(0b1110), 0xe6, f(0b0100)); try testDaa(0xec, f(0b1111), 0x86, f(0b0101)); try testDaa(0xed, f(0b0000), 0x53, f(0b0001)); try testDaa(0xed, f(0b0001), 0x53, f(0b0001)); try testDaa(0xed, f(0b0010), 0x53, f(0b0001)); try testDaa(0xed, f(0b0011), 0x53, f(0b0001)); try testDaa(0xed, f(0b0100), 0xed, f(0b0100)); try testDaa(0xed, f(0b0101), 0x8d, f(0b0101)); try testDaa(0xed, f(0b0110), 0xe7, f(0b0100)); try testDaa(0xed, f(0b0111), 0x87, f(0b0101)); try testDaa(0xed, f(0b1000), 0x53, f(0b0001)); try testDaa(0xed, f(0b1001), 0x53, f(0b0001)); try testDaa(0xed, f(0b1010), 0x53, f(0b0001)); try testDaa(0xed, f(0b1011), 0x53, f(0b0001)); try testDaa(0xed, f(0b1100), 0xed, f(0b0100)); try testDaa(0xed, f(0b1101), 0x8d, f(0b0101)); try testDaa(0xed, f(0b1110), 0xe7, f(0b0100)); try testDaa(0xed, f(0b1111), 0x87, f(0b0101)); try testDaa(0xee, f(0b0000), 0x54, f(0b0001)); try testDaa(0xee, f(0b0001), 0x54, f(0b0001)); try testDaa(0xee, f(0b0010), 0x54, f(0b0001)); try testDaa(0xee, f(0b0011), 0x54, f(0b0001)); try testDaa(0xee, f(0b0100), 0xee, f(0b0100)); try testDaa(0xee, f(0b0101), 0x8e, f(0b0101)); try testDaa(0xee, f(0b0110), 0xe8, f(0b0100)); try testDaa(0xee, f(0b0111), 0x88, f(0b0101)); try testDaa(0xee, f(0b1000), 0x54, f(0b0001)); try testDaa(0xee, f(0b1001), 0x54, f(0b0001)); try testDaa(0xee, f(0b1010), 0x54, f(0b0001)); try testDaa(0xee, f(0b1011), 0x54, f(0b0001)); try testDaa(0xee, f(0b1100), 0xee, f(0b0100)); try testDaa(0xee, f(0b1101), 0x8e, f(0b0101)); try testDaa(0xee, f(0b1110), 0xe8, f(0b0100)); try testDaa(0xee, f(0b1111), 0x88, f(0b0101)); try testDaa(0xef, f(0b0000), 0x55, f(0b0001)); try testDaa(0xef, f(0b0001), 0x55, f(0b0001)); try testDaa(0xef, f(0b0010), 0x55, f(0b0001)); try testDaa(0xef, f(0b0011), 0x55, f(0b0001)); try testDaa(0xef, f(0b0100), 0xef, f(0b0100)); try testDaa(0xef, f(0b0101), 0x8f, f(0b0101)); try testDaa(0xef, f(0b0110), 0xe9, f(0b0100)); try testDaa(0xef, f(0b0111), 0x89, f(0b0101)); try testDaa(0xef, f(0b1000), 0x55, f(0b0001)); try testDaa(0xef, f(0b1001), 0x55, f(0b0001)); try testDaa(0xef, f(0b1010), 0x55, f(0b0001)); try testDaa(0xef, f(0b1011), 0x55, f(0b0001)); try testDaa(0xef, f(0b1100), 0xef, f(0b0100)); try testDaa(0xef, f(0b1101), 0x8f, f(0b0101)); try testDaa(0xef, f(0b1110), 0xe9, f(0b0100)); try testDaa(0xef, f(0b1111), 0x89, f(0b0101)); try testDaa(0xf0, f(0b0000), 0x50, f(0b0001)); try testDaa(0xf0, f(0b0001), 0x50, f(0b0001)); try testDaa(0xf0, f(0b0010), 0x56, f(0b0001)); try testDaa(0xf0, f(0b0011), 0x56, f(0b0001)); try testDaa(0xf0, f(0b0100), 0xf0, f(0b0100)); try testDaa(0xf0, f(0b0101), 0x90, f(0b0101)); try testDaa(0xf0, f(0b0110), 0xea, f(0b0100)); try testDaa(0xf0, f(0b0111), 0x8a, f(0b0101)); try testDaa(0xf0, f(0b1000), 0x50, f(0b0001)); try testDaa(0xf0, f(0b1001), 0x50, f(0b0001)); try testDaa(0xf0, f(0b1010), 0x56, f(0b0001)); try testDaa(0xf0, f(0b1011), 0x56, f(0b0001)); try testDaa(0xf0, f(0b1100), 0xf0, f(0b0100)); try testDaa(0xf0, f(0b1101), 0x90, f(0b0101)); try testDaa(0xf0, f(0b1110), 0xea, f(0b0100)); try testDaa(0xf0, f(0b1111), 0x8a, f(0b0101)); try testDaa(0xf1, f(0b0000), 0x51, f(0b0001)); try testDaa(0xf1, f(0b0001), 0x51, f(0b0001)); try testDaa(0xf1, f(0b0010), 0x57, f(0b0001)); try testDaa(0xf1, f(0b0011), 0x57, f(0b0001)); try testDaa(0xf1, f(0b0100), 0xf1, f(0b0100)); try testDaa(0xf1, f(0b0101), 0x91, f(0b0101)); try testDaa(0xf1, f(0b0110), 0xeb, f(0b0100)); try testDaa(0xf1, f(0b0111), 0x8b, f(0b0101)); try testDaa(0xf1, f(0b1000), 0x51, f(0b0001)); try testDaa(0xf1, f(0b1001), 0x51, f(0b0001)); try testDaa(0xf1, f(0b1010), 0x57, f(0b0001)); try testDaa(0xf1, f(0b1011), 0x57, f(0b0001)); try testDaa(0xf1, f(0b1100), 0xf1, f(0b0100)); try testDaa(0xf1, f(0b1101), 0x91, f(0b0101)); try testDaa(0xf1, f(0b1110), 0xeb, f(0b0100)); try testDaa(0xf1, f(0b1111), 0x8b, f(0b0101)); try testDaa(0xf2, f(0b0000), 0x52, f(0b0001)); try testDaa(0xf2, f(0b0001), 0x52, f(0b0001)); try testDaa(0xf2, f(0b0010), 0x58, f(0b0001)); try testDaa(0xf2, f(0b0011), 0x58, f(0b0001)); try testDaa(0xf2, f(0b0100), 0xf2, f(0b0100)); try testDaa(0xf2, f(0b0101), 0x92, f(0b0101)); try testDaa(0xf2, f(0b0110), 0xec, f(0b0100)); try testDaa(0xf2, f(0b0111), 0x8c, f(0b0101)); try testDaa(0xf2, f(0b1000), 0x52, f(0b0001)); try testDaa(0xf2, f(0b1001), 0x52, f(0b0001)); try testDaa(0xf2, f(0b1010), 0x58, f(0b0001)); try testDaa(0xf2, f(0b1011), 0x58, f(0b0001)); try testDaa(0xf2, f(0b1100), 0xf2, f(0b0100)); try testDaa(0xf2, f(0b1101), 0x92, f(0b0101)); try testDaa(0xf2, f(0b1110), 0xec, f(0b0100)); try testDaa(0xf2, f(0b1111), 0x8c, f(0b0101)); try testDaa(0xf3, f(0b0000), 0x53, f(0b0001)); try testDaa(0xf3, f(0b0001), 0x53, f(0b0001)); try testDaa(0xf3, f(0b0010), 0x59, f(0b0001)); try testDaa(0xf3, f(0b0011), 0x59, f(0b0001)); try testDaa(0xf3, f(0b0100), 0xf3, f(0b0100)); try testDaa(0xf3, f(0b0101), 0x93, f(0b0101)); try testDaa(0xf3, f(0b0110), 0xed, f(0b0100)); try testDaa(0xf3, f(0b0111), 0x8d, f(0b0101)); try testDaa(0xf3, f(0b1000), 0x53, f(0b0001)); try testDaa(0xf3, f(0b1001), 0x53, f(0b0001)); try testDaa(0xf3, f(0b1010), 0x59, f(0b0001)); try testDaa(0xf3, f(0b1011), 0x59, f(0b0001)); try testDaa(0xf3, f(0b1100), 0xf3, f(0b0100)); try testDaa(0xf3, f(0b1101), 0x93, f(0b0101)); try testDaa(0xf3, f(0b1110), 0xed, f(0b0100)); try testDaa(0xf3, f(0b1111), 0x8d, f(0b0101)); try testDaa(0xf4, f(0b0000), 0x54, f(0b0001)); try testDaa(0xf4, f(0b0001), 0x54, f(0b0001)); try testDaa(0xf4, f(0b0010), 0x5a, f(0b0001)); try testDaa(0xf4, f(0b0011), 0x5a, f(0b0001)); try testDaa(0xf4, f(0b0100), 0xf4, f(0b0100)); try testDaa(0xf4, f(0b0101), 0x94, f(0b0101)); try testDaa(0xf4, f(0b0110), 0xee, f(0b0100)); try testDaa(0xf4, f(0b0111), 0x8e, f(0b0101)); try testDaa(0xf4, f(0b1000), 0x54, f(0b0001)); try testDaa(0xf4, f(0b1001), 0x54, f(0b0001)); try testDaa(0xf4, f(0b1010), 0x5a, f(0b0001)); try testDaa(0xf4, f(0b1011), 0x5a, f(0b0001)); try testDaa(0xf4, f(0b1100), 0xf4, f(0b0100)); try testDaa(0xf4, f(0b1101), 0x94, f(0b0101)); try testDaa(0xf4, f(0b1110), 0xee, f(0b0100)); try testDaa(0xf4, f(0b1111), 0x8e, f(0b0101)); try testDaa(0xf5, f(0b0000), 0x55, f(0b0001)); try testDaa(0xf5, f(0b0001), 0x55, f(0b0001)); try testDaa(0xf5, f(0b0010), 0x5b, f(0b0001)); try testDaa(0xf5, f(0b0011), 0x5b, f(0b0001)); try testDaa(0xf5, f(0b0100), 0xf5, f(0b0100)); try testDaa(0xf5, f(0b0101), 0x95, f(0b0101)); try testDaa(0xf5, f(0b0110), 0xef, f(0b0100)); try testDaa(0xf5, f(0b0111), 0x8f, f(0b0101)); try testDaa(0xf5, f(0b1000), 0x55, f(0b0001)); try testDaa(0xf5, f(0b1001), 0x55, f(0b0001)); try testDaa(0xf5, f(0b1010), 0x5b, f(0b0001)); try testDaa(0xf5, f(0b1011), 0x5b, f(0b0001)); try testDaa(0xf5, f(0b1100), 0xf5, f(0b0100)); try testDaa(0xf5, f(0b1101), 0x95, f(0b0101)); try testDaa(0xf5, f(0b1110), 0xef, f(0b0100)); try testDaa(0xf5, f(0b1111), 0x8f, f(0b0101)); try testDaa(0xf6, f(0b0000), 0x56, f(0b0001)); try testDaa(0xf6, f(0b0001), 0x56, f(0b0001)); try testDaa(0xf6, f(0b0010), 0x5c, f(0b0001)); try testDaa(0xf6, f(0b0011), 0x5c, f(0b0001)); try testDaa(0xf6, f(0b0100), 0xf6, f(0b0100)); try testDaa(0xf6, f(0b0101), 0x96, f(0b0101)); try testDaa(0xf6, f(0b0110), 0xf0, f(0b0100)); try testDaa(0xf6, f(0b0111), 0x90, f(0b0101)); try testDaa(0xf6, f(0b1000), 0x56, f(0b0001)); try testDaa(0xf6, f(0b1001), 0x56, f(0b0001)); try testDaa(0xf6, f(0b1010), 0x5c, f(0b0001)); try testDaa(0xf6, f(0b1011), 0x5c, f(0b0001)); try testDaa(0xf6, f(0b1100), 0xf6, f(0b0100)); try testDaa(0xf6, f(0b1101), 0x96, f(0b0101)); try testDaa(0xf6, f(0b1110), 0xf0, f(0b0100)); try testDaa(0xf6, f(0b1111), 0x90, f(0b0101)); try testDaa(0xf7, f(0b0000), 0x57, f(0b0001)); try testDaa(0xf7, f(0b0001), 0x57, f(0b0001)); try testDaa(0xf7, f(0b0010), 0x5d, f(0b0001)); try testDaa(0xf7, f(0b0011), 0x5d, f(0b0001)); try testDaa(0xf7, f(0b0100), 0xf7, f(0b0100)); try testDaa(0xf7, f(0b0101), 0x97, f(0b0101)); try testDaa(0xf7, f(0b0110), 0xf1, f(0b0100)); try testDaa(0xf7, f(0b0111), 0x91, f(0b0101)); try testDaa(0xf7, f(0b1000), 0x57, f(0b0001)); try testDaa(0xf7, f(0b1001), 0x57, f(0b0001)); try testDaa(0xf7, f(0b1010), 0x5d, f(0b0001)); try testDaa(0xf7, f(0b1011), 0x5d, f(0b0001)); try testDaa(0xf7, f(0b1100), 0xf7, f(0b0100)); try testDaa(0xf7, f(0b1101), 0x97, f(0b0101)); try testDaa(0xf7, f(0b1110), 0xf1, f(0b0100)); try testDaa(0xf7, f(0b1111), 0x91, f(0b0101)); try testDaa(0xf8, f(0b0000), 0x58, f(0b0001)); try testDaa(0xf8, f(0b0001), 0x58, f(0b0001)); try testDaa(0xf8, f(0b0010), 0x5e, f(0b0001)); try testDaa(0xf8, f(0b0011), 0x5e, f(0b0001)); try testDaa(0xf8, f(0b0100), 0xf8, f(0b0100)); try testDaa(0xf8, f(0b0101), 0x98, f(0b0101)); try testDaa(0xf8, f(0b0110), 0xf2, f(0b0100)); try testDaa(0xf8, f(0b0111), 0x92, f(0b0101)); try testDaa(0xf8, f(0b1000), 0x58, f(0b0001)); try testDaa(0xf8, f(0b1001), 0x58, f(0b0001)); try testDaa(0xf8, f(0b1010), 0x5e, f(0b0001)); try testDaa(0xf8, f(0b1011), 0x5e, f(0b0001)); try testDaa(0xf8, f(0b1100), 0xf8, f(0b0100)); try testDaa(0xf8, f(0b1101), 0x98, f(0b0101)); try testDaa(0xf8, f(0b1110), 0xf2, f(0b0100)); try testDaa(0xf8, f(0b1111), 0x92, f(0b0101)); try testDaa(0xf9, f(0b0000), 0x59, f(0b0001)); try testDaa(0xf9, f(0b0001), 0x59, f(0b0001)); try testDaa(0xf9, f(0b0010), 0x5f, f(0b0001)); try testDaa(0xf9, f(0b0011), 0x5f, f(0b0001)); try testDaa(0xf9, f(0b0100), 0xf9, f(0b0100)); try testDaa(0xf9, f(0b0101), 0x99, f(0b0101)); try testDaa(0xf9, f(0b0110), 0xf3, f(0b0100)); try testDaa(0xf9, f(0b0111), 0x93, f(0b0101)); try testDaa(0xf9, f(0b1000), 0x59, f(0b0001)); try testDaa(0xf9, f(0b1001), 0x59, f(0b0001)); try testDaa(0xf9, f(0b1010), 0x5f, f(0b0001)); try testDaa(0xf9, f(0b1011), 0x5f, f(0b0001)); try testDaa(0xf9, f(0b1100), 0xf9, f(0b0100)); try testDaa(0xf9, f(0b1101), 0x99, f(0b0101)); try testDaa(0xf9, f(0b1110), 0xf3, f(0b0100)); try testDaa(0xf9, f(0b1111), 0x93, f(0b0101)); try testDaa(0xfa, f(0b0000), 0x60, f(0b0001)); try testDaa(0xfa, f(0b0001), 0x60, f(0b0001)); try testDaa(0xfa, f(0b0010), 0x60, f(0b0001)); try testDaa(0xfa, f(0b0011), 0x60, f(0b0001)); try testDaa(0xfa, f(0b0100), 0xfa, f(0b0100)); try testDaa(0xfa, f(0b0101), 0x9a, f(0b0101)); try testDaa(0xfa, f(0b0110), 0xf4, f(0b0100)); try testDaa(0xfa, f(0b0111), 0x94, f(0b0101)); try testDaa(0xfa, f(0b1000), 0x60, f(0b0001)); try testDaa(0xfa, f(0b1001), 0x60, f(0b0001)); try testDaa(0xfa, f(0b1010), 0x60, f(0b0001)); try testDaa(0xfa, f(0b1011), 0x60, f(0b0001)); try testDaa(0xfa, f(0b1100), 0xfa, f(0b0100)); try testDaa(0xfa, f(0b1101), 0x9a, f(0b0101)); try testDaa(0xfa, f(0b1110), 0xf4, f(0b0100)); try testDaa(0xfa, f(0b1111), 0x94, f(0b0101)); try testDaa(0xfb, f(0b0000), 0x61, f(0b0001)); try testDaa(0xfb, f(0b0001), 0x61, f(0b0001)); try testDaa(0xfb, f(0b0010), 0x61, f(0b0001)); try testDaa(0xfb, f(0b0011), 0x61, f(0b0001)); try testDaa(0xfb, f(0b0100), 0xfb, f(0b0100)); try testDaa(0xfb, f(0b0101), 0x9b, f(0b0101)); try testDaa(0xfb, f(0b0110), 0xf5, f(0b0100)); try testDaa(0xfb, f(0b0111), 0x95, f(0b0101)); try testDaa(0xfb, f(0b1000), 0x61, f(0b0001)); try testDaa(0xfb, f(0b1001), 0x61, f(0b0001)); try testDaa(0xfb, f(0b1010), 0x61, f(0b0001)); try testDaa(0xfb, f(0b1011), 0x61, f(0b0001)); try testDaa(0xfb, f(0b1100), 0xfb, f(0b0100)); try testDaa(0xfb, f(0b1101), 0x9b, f(0b0101)); try testDaa(0xfb, f(0b1110), 0xf5, f(0b0100)); try testDaa(0xfb, f(0b1111), 0x95, f(0b0101)); try testDaa(0xfc, f(0b0000), 0x62, f(0b0001)); try testDaa(0xfc, f(0b0001), 0x62, f(0b0001)); try testDaa(0xfc, f(0b0010), 0x62, f(0b0001)); try testDaa(0xfc, f(0b0011), 0x62, f(0b0001)); try testDaa(0xfc, f(0b0100), 0xfc, f(0b0100)); try testDaa(0xfc, f(0b0101), 0x9c, f(0b0101)); try testDaa(0xfc, f(0b0110), 0xf6, f(0b0100)); try testDaa(0xfc, f(0b0111), 0x96, f(0b0101)); try testDaa(0xfc, f(0b1000), 0x62, f(0b0001)); try testDaa(0xfc, f(0b1001), 0x62, f(0b0001)); try testDaa(0xfc, f(0b1010), 0x62, f(0b0001)); try testDaa(0xfc, f(0b1011), 0x62, f(0b0001)); try testDaa(0xfc, f(0b1100), 0xfc, f(0b0100)); try testDaa(0xfc, f(0b1101), 0x9c, f(0b0101)); try testDaa(0xfc, f(0b1110), 0xf6, f(0b0100)); try testDaa(0xfc, f(0b1111), 0x96, f(0b0101)); try testDaa(0xfd, f(0b0000), 0x63, f(0b0001)); try testDaa(0xfd, f(0b0001), 0x63, f(0b0001)); try testDaa(0xfd, f(0b0010), 0x63, f(0b0001)); try testDaa(0xfd, f(0b0011), 0x63, f(0b0001)); try testDaa(0xfd, f(0b0100), 0xfd, f(0b0100)); try testDaa(0xfd, f(0b0101), 0x9d, f(0b0101)); try testDaa(0xfd, f(0b0110), 0xf7, f(0b0100)); try testDaa(0xfd, f(0b0111), 0x97, f(0b0101)); try testDaa(0xfd, f(0b1000), 0x63, f(0b0001)); try testDaa(0xfd, f(0b1001), 0x63, f(0b0001)); try testDaa(0xfd, f(0b1010), 0x63, f(0b0001)); try testDaa(0xfd, f(0b1011), 0x63, f(0b0001)); try testDaa(0xfd, f(0b1100), 0xfd, f(0b0100)); try testDaa(0xfd, f(0b1101), 0x9d, f(0b0101)); try testDaa(0xfd, f(0b1110), 0xf7, f(0b0100)); try testDaa(0xfd, f(0b1111), 0x97, f(0b0101)); try testDaa(0xfe, f(0b0000), 0x64, f(0b0001)); try testDaa(0xfe, f(0b0001), 0x64, f(0b0001)); try testDaa(0xfe, f(0b0010), 0x64, f(0b0001)); try testDaa(0xfe, f(0b0011), 0x64, f(0b0001)); try testDaa(0xfe, f(0b0100), 0xfe, f(0b0100)); try testDaa(0xfe, f(0b0101), 0x9e, f(0b0101)); try testDaa(0xfe, f(0b0110), 0xf8, f(0b0100)); try testDaa(0xfe, f(0b0111), 0x98, f(0b0101)); try testDaa(0xfe, f(0b1000), 0x64, f(0b0001)); try testDaa(0xfe, f(0b1001), 0x64, f(0b0001)); try testDaa(0xfe, f(0b1010), 0x64, f(0b0001)); try testDaa(0xfe, f(0b1011), 0x64, f(0b0001)); try testDaa(0xfe, f(0b1100), 0xfe, f(0b0100)); try testDaa(0xfe, f(0b1101), 0x9e, f(0b0101)); try testDaa(0xfe, f(0b1110), 0xf8, f(0b0100)); try testDaa(0xfe, f(0b1111), 0x98, f(0b0101)); try testDaa(0xff, f(0b0000), 0x65, f(0b0001)); try testDaa(0xff, f(0b0001), 0x65, f(0b0001)); try testDaa(0xff, f(0b0010), 0x65, f(0b0001)); try testDaa(0xff, f(0b0011), 0x65, f(0b0001)); try testDaa(0xff, f(0b0100), 0xff, f(0b0100)); try testDaa(0xff, f(0b0101), 0x9f, f(0b0101)); try testDaa(0xff, f(0b0110), 0xf9, f(0b0100)); try testDaa(0xff, f(0b0111), 0x99, f(0b0101)); try testDaa(0xff, f(0b1000), 0x65, f(0b0001)); try testDaa(0xff, f(0b1001), 0x65, f(0b0001)); try testDaa(0xff, f(0b1010), 0x65, f(0b0001)); try testDaa(0xff, f(0b1011), 0x65, f(0b0001)); try testDaa(0xff, f(0b1100), 0xff, f(0b0100)); try testDaa(0xff, f(0b1101), 0x9f, f(0b0101)); try testDaa(0xff, f(0b1110), 0xf9, f(0b0100)); try testDaa(0xff, f(0b1111), 0x99, f(0b0101)); }
src/Cpu/impl_daa_test.zig
const std = @import("std"); const assert = std.debug.assert; const log = std.log.scoped(.concurrent_ranges); pub const ConcurrentRanges = struct { name: []const u8, /// A queue of ranges acquired and in progress: acquired: ?*Range = null, pub fn acquire(self: *ConcurrentRanges, range: *Range) void { assert(range.status == .initialized); range.status = .acquiring; assert(range.prev == null); assert(range.next == null); assert(range.head == null); assert(range.tail == null); range.frame = @frame(); while (true) { if (self.has_overlapping_range(range)) |overlapping_range| { log.debug("{s}: range {} overlaps with concurrent range {}, enqueueing", .{ self.name, range, overlapping_range, }); overlapping_range.enqueue(range); suspend {} } else { break; } } // TODO This can be removed for performance down the line: assert(self.has_overlapping_range(range) == null); // Add the range to the linked list: if (self.acquired) |next| { range.next = next; next.prev = range; } self.acquired = range; range.status = .acquired; log.debug("{s}: acquired: {}", .{ self.name, range }); } pub fn release(self: *ConcurrentRanges, range: *Range) void { assert(range.status == .acquired); range.status = .releasing; log.debug("{s}: released: {}", .{ self.name, range }); // Remove the range from the linked list: // Connect the previous range to the next range: if (range.prev) |prev| { prev.next = range.next; } else { self.acquired = range.next; } // ... and connect the next range to the previous range: if (range.next) |next| { next.prev = range.prev; } range.prev = null; range.next = null; range.resume_queued_ranges(); } pub fn has_overlapping_range(self: *ConcurrentRanges, range: *const Range) ?*Range { var head = self.acquired; while (head) |concurrent_range| { head = concurrent_range.next; if (range.overlaps(concurrent_range)) return concurrent_range; } return null; } }; pub const Range = struct { offset: u64, len: u64, frame: anyframe = undefined, status: RangeStatus = .initialized, /// Links to concurrently executing sibling ranges: prev: ?*Range = null, next: ?*Range = null, /// A queue of child ranges waiting on this range to complete: head: ?*Range = null, tail: ?*Range = null, const RangeStatus = enum { initialized, acquiring, acquired, releasing, released, }; fn enqueue(self: *Range, range: *Range) void { assert(self.status == .acquired); assert(range.status == .acquiring); if (self.head == null) { assert(self.tail == null); self.head = range; self.tail = range; } else { self.tail.?.next = range; self.tail = range; } } fn overlaps(self: *const Range, range: *const Range) bool { if (self.offset < range.offset) { return self.offset + self.len > range.offset; } else { return range.offset + range.len > self.offset; } } fn resume_queued_ranges(self: *Range) void { assert(self.status == .releasing); self.status = .released; // This range should have been removed from the list of concurrent ranges: assert(self.prev == null); assert(self.next == null); var head = self.head; self.head = null; self.tail = null; while (head) |queued| { assert(queued.status == .acquiring); head = queued.next; resume queued.frame; } // This range should be finished executing and should no longer overlap or have any queue: assert(self.head == null); assert(self.tail == null); } pub fn format( value: Range, comptime fmt: []const u8, options: std.fmt.FormatOptions, writer: anytype, ) !void { try writer.print("offset={} len={}", .{ value.offset, value.len, }); } };
src/concurrent_ranges.zig
const sf = @import("../sfml.zig"); const std = @import("std"); const assert = std.debug.assert; pub const Image = struct { const Self = @This(); // Constructor/destructor /// Creates a new image pub fn init(size: sf.Vector2u, color: sf.Color) !Self { var img = sf.c.sfImage_createFromColor(size.x, size.y, color.toCSFML()); if (img == null) return sf.Error.nullptrUnknownReason; return Self{ .ptr = img.? }; } /// Creates an image from a pixel array pub fn initFromPixels(size: sf.Vector2u, pixels: []const sf.Color) !Self { // Check if there is enough data if (pixels.len < size.x * size.y) return sf.Error.notEnoughData; var img = sf.c.sfImage_createFromPixels(size.x, size.y, @ptrCast([*]const u8, pixels.ptr)); if (img == null) return sf.Error.nullptrUnknownReason; return Self{ .ptr = img.? }; } /// Loads an image from a file pub fn initFromFile(path: [:0]const u8) !Self { var img = sf.c.sfImage_createFromFile(path); if (img == null) return sf.Error.resourceLoadingError; return Self{ .ptr = img.? }; } /// Destroys an image pub fn deinit(self: Self) void { sf.c.sfImage_destroy(self.ptr); } // Getters/setters /// Gets a pixel from this image (bounds are only checked in an assertion) pub fn getPixel(self: Self, pixel_pos: sf.Vector2u) sf.Color { @compileError("This function causes a segfault, comment this out if you thing it will work (issue #2)"); const size = self.getSize(); assert(pixel_pos.x < size.x and pixel_pos.y < size.y); return sf.Color.fromCSFML(sf.c.sfImage_getPixel(self.ptr, pixel_pos.x, pixel_pos.y)); } /// Sets a pixel on this image (bounds are only checked in an assertion) pub fn setPixel(self: Self, pixel_pos: sf.Vector2u, color: sf.Color) void { const size = self.getSize(); assert(pixel_pos.x < size.x and pixel_pos.y < size.y); sf.c.sfImage_setPixel(self.ptr, pixel_pos.x, pixel_pos.y, color.toCSFML()); } /// Gets the size of this image pub fn getSize(self: Self) sf.Vector2u { // This is a hack _ = sf.c.sfImage_getSize(self.ptr); // Register Rax holds the return val of function calls that can fit in a register const rax: usize = asm volatile ("" : [ret] "={rax}" (-> usize) ); var x: u32 = @truncate(u32, (rax & 0x00000000FFFFFFFF) >> 00); var y: u32 = @truncate(u32, (rax & 0xFFFFFFFF00000000) >> 32); return sf.Vector2u{ .x = x, .y = y }; } /// Pointer to the csfml texture ptr: *sf.c.sfImage }; test "image: sane getters and setters" { const tst = std.testing; const allocator = std.heap.page_allocator; var pixel_data = try allocator.alloc(sf.Color, 30); defer allocator.free(pixel_data); for (pixel_data) |c, i| { pixel_data[i] = sf.Color.fromHSVA(@intToFloat(f32, i) / 30 * 360, 100, 100, 1); } var img = try sf.Image.initFromPixels(.{.x = 5, .y = 6}, pixel_data); defer img.deinit(); tst.expectEqual(sf.Vector2u{.x = 5, .y = 6}, img.getSize()); img.setPixel(.{.x = 1, .y = 2}, sf.Color.Cyan); //tst.expectEqual(sf.Color.Cyan, img.getPixel(.{.x = 1, .y = 2})); var tex = try sf.Texture.initFromImage(img, null); defer tex.deinit(); }
src/sfml/graphics/image.zig