code
stringlengths
38
801k
repo_path
stringlengths
6
263
const std = @import("std"); pub const MESSIBLE = @import("./fomu/messible.zig").MESSIBLE; pub const REBOOT = @import("./fomu/reboot.zig").REBOOT; pub const RGB = @import("./fomu/rgb.zig").RGB; pub const TIMER0 = @import("./fomu/timer0.zig").TIMER0; pub const TOUCH = @import("./fomu/touch.zig").TOUCH; pub const SYSTEM_CLOCK_FREQUENCY = 12000000; pub const start = @import("./fomu/start.zig"); // This forces start.zig file to be imported comptime { _ = start; } /// Panic function that sets LED to red and flashing + prints the panic message over messible pub fn panic(message: []const u8, stack_trace: ?*std.builtin.StackTrace) noreturn { @setCold(true); _ = stack_trace; // Put LED into non-raw flashing mode RGB.CTRL.* = .{ .EXE = true, .CURREN = true, .RGBLEDEN = true, .RRAW = false, .GRAW = false, .BRAW = false, }; // Set colour to red RGB.setColour(255, 0, 0); // Enable the LED driver, and set 250 Hz mode. RGB.setControlRegister(.{ .enable = true, .fr = .@"250", .quick_stop = false, .outskew = false, .output_polarity = .active_high, .pwm_mode = .linear, .BRMSBEXT = 0, }); messibleWriter.print("PANIC: {s}\r\n", .{message}) catch void; while (true) { @breakpoint(); } } const WriteError = error{}; fn messibleWrite(self: void, bytes: []const u8) WriteError!usize { _ = self; while (true) { const bytes_written = MESSIBLE.write(bytes); if (bytes_written != 0) return bytes_written; } } pub const messibleWriter = std.io.Writer(void, WriteError, messibleWrite){ .context = {} }; const ReadError = error{}; fn messibleRead(self: void, buffer: []u8) ReadError!usize { _ = self; while (true) { const bytes_read = MESSIBLE.read(buffer); if (bytes_read != 0) return bytes_read; } } pub const messibleReader = std.io.Reader(void, ReadError, messibleRead){ .context = {} };
riscv-zig-blink/src/fomu.zig
const std = @import("std"); const math = std.math; const mem = std.mem; const Allocator = std.mem.Allocator; const deflate_const = @import("deflate_const.zig"); const deflate = @import("compressor.zig"); const token = @import("token.zig"); const base_match_length = deflate_const.base_match_length; const base_match_offset = deflate_const.base_match_offset; const max_match_length = deflate_const.max_match_length; const max_match_offset = deflate_const.max_match_offset; const max_store_block_size = deflate_const.max_store_block_size; const table_bits = 14; // Bits used in the table. const table_mask = table_size - 1; // Mask for table indices. Redundant, but can eliminate bounds checks. const table_shift = 32 - table_bits; // Right-shift to get the table_bits most significant bits of a uint32. const table_size = 1 << table_bits; // Size of the table. // Reset the buffer offset when reaching this. // Offsets are stored between blocks as i32 values. // Since the offset we are checking against is at the beginning // of the buffer, we need to subtract the current and input // buffer to not risk overflowing the i32. const buffer_reset = math.maxInt(i32) - max_store_block_size * 2; fn load32(b: []u8, i: i32) u32 { var s = b[@intCast(usize, i) .. @intCast(usize, i) + 4]; return @intCast(u32, s[0]) | @intCast(u32, s[1]) << 8 | @intCast(u32, s[2]) << 16 | @intCast(u32, s[3]) << 24; } fn load64(b: []u8, i: i32) u64 { var s = b[@intCast(usize, i)..@intCast(usize, i + 8)]; return @intCast(u64, s[0]) | @intCast(u64, s[1]) << 8 | @intCast(u64, s[2]) << 16 | @intCast(u64, s[3]) << 24 | @intCast(u64, s[4]) << 32 | @intCast(u64, s[5]) << 40 | @intCast(u64, s[6]) << 48 | @intCast(u64, s[7]) << 56; } fn hash(u: u32) u32 { return (u *% 0x1e35a7bd) >> table_shift; } // These constants are defined by the Snappy implementation so that its // assembly implementation can fast-path some 16-bytes-at-a-time copies. // They aren't necessary in the pure Go implementation, and may not be // necessary in Zig, but using the same thresholds doesn't really hurt. const input_margin = 16 - 1; const min_non_literal_block_size = 1 + 1 + input_margin; const TableEntry = struct { val: u32, // Value at destination offset: i32, }; pub fn deflateFast() DeflateFast { return DeflateFast{ .table = [_]TableEntry{.{ .val = 0, .offset = 0 }} ** table_size, .prev = undefined, .prev_len = 0, .cur = max_store_block_size, .allocator = undefined, }; } // DeflateFast maintains the table for matches, // and the previous byte block for cross block matching. pub const DeflateFast = struct { table: [table_size]TableEntry, prev: []u8, // Previous block, zero length if unknown. prev_len: u32, // Previous block length cur: i32, // Current match offset. allocator: Allocator, const Self = @This(); pub fn init(self: *Self, allocator: Allocator) !void { self.allocator = allocator; self.prev = try allocator.alloc(u8, max_store_block_size); self.prev_len = 0; } pub fn deinit(self: *Self) void { self.allocator.free(self.prev); self.prev_len = 0; } // Encodes a block given in `src` and appends tokens to `dst` and returns the result. pub fn encode(self: *Self, dst: []token.Token, tokens_count: *u16, src: []u8) void { // Ensure that self.cur doesn't wrap. if (self.cur >= buffer_reset) { self.shiftOffsets(); } // This check isn't in the Snappy implementation, but there, the caller // instead of the callee handles this case. if (src.len < min_non_literal_block_size) { self.cur += max_store_block_size; self.prev_len = 0; emitLiteral(dst, tokens_count, src); return; } // s_limit is when to stop looking for offset/length copies. The input_margin // lets us use a fast path for emitLiteral in the main loop, while we are // looking for copies. var s_limit = @intCast(i32, src.len - input_margin); // next_emit is where in src the next emitLiteral should start from. var next_emit: i32 = 0; var s: i32 = 0; var cv: u32 = load32(src, s); var next_hash: u32 = hash(cv); outer: while (true) { // Copied from the C++ snappy implementation: // // Heuristic match skipping: If 32 bytes are scanned with no matches // found, start looking only at every other byte. If 32 more bytes are // scanned (or skipped), look at every third byte, etc.. When a match // is found, immediately go back to looking at every byte. This is a // small loss (~5% performance, ~0.1% density) for compressible data // due to more bookkeeping, but for non-compressible data (such as // JPEG) it's a huge win since the compressor quickly "realizes" the // data is incompressible and doesn't bother looking for matches // everywhere. // // The "skip" variable keeps track of how many bytes there are since // the last match; dividing it by 32 (ie. right-shifting by five) gives // the number of bytes to move ahead for each iteration. var skip: i32 = 32; var next_s: i32 = s; var candidate: TableEntry = undefined; while (true) { s = next_s; var bytes_between_hash_lookups = skip >> 5; next_s = s + bytes_between_hash_lookups; skip += bytes_between_hash_lookups; if (next_s > s_limit) { break :outer; } candidate = self.table[next_hash & table_mask]; var now = load32(src, next_s); self.table[next_hash & table_mask] = .{ .offset = s + self.cur, .val = cv }; next_hash = hash(now); var offset = s - (candidate.offset - self.cur); if (offset > max_match_offset or cv != candidate.val) { // Out of range or not matched. cv = now; continue; } break; } // A 4-byte match has been found. We'll later see if more than 4 bytes // match. But, prior to the match, src[next_emit..s] are unmatched. Emit // them as literal bytes. emitLiteral(dst, tokens_count, src[@intCast(usize, next_emit)..@intCast(usize, s)]); // Call emitCopy, and then see if another emitCopy could be our next // move. Repeat until we find no match for the input immediately after // what was consumed by the last emitCopy call. // // If we exit this loop normally then we need to call emitLiteral next, // though we don't yet know how big the literal will be. We handle that // by proceeding to the next iteration of the main loop. We also can // exit this loop via goto if we get close to exhausting the input. while (true) { // Invariant: we have a 4-byte match at s, and no need to emit any // literal bytes prior to s. // Extend the 4-byte match as long as possible. // s += 4; var t = candidate.offset - self.cur + 4; var l = self.matchLen(s, t, src); // matchToken is flate's equivalent of Snappy's emitCopy. (length,offset) dst[tokens_count.*] = token.matchToken( @intCast(u32, l + 4 - base_match_length), @intCast(u32, s - t - base_match_offset), ); tokens_count.* += 1; s += l; next_emit = s; if (s >= s_limit) { break :outer; } // We could immediately start working at s now, but to improve // compression we first update the hash table at s-1 and at s. If // another emitCopy is not our next move, also calculate next_hash // at s+1. At least on amd64 architecture, these three hash calculations // are faster as one load64 call (with some shifts) instead of // three load32 calls. var x = load64(src, s - 1); var prev_hash = hash(@truncate(u32, x)); self.table[prev_hash & table_mask] = TableEntry{ .offset = self.cur + s - 1, .val = @truncate(u32, x), }; x >>= 8; var curr_hash = hash(@truncate(u32, x)); candidate = self.table[curr_hash & table_mask]; self.table[curr_hash & table_mask] = TableEntry{ .offset = self.cur + s, .val = @truncate(u32, x), }; var offset = s - (candidate.offset - self.cur); if (offset > max_match_offset or @truncate(u32, x) != candidate.val) { cv = @truncate(u32, x >> 8); next_hash = hash(cv); s += 1; break; } } } if (@intCast(u32, next_emit) < src.len) { emitLiteral(dst, tokens_count, src[@intCast(usize, next_emit)..]); } self.cur += @intCast(i32, src.len); self.prev_len = @intCast(u32, src.len); mem.copy(u8, self.prev[0..self.prev_len], src); return; } fn emitLiteral(dst: []token.Token, tokens_count: *u16, lit: []u8) void { for (lit) |v| { dst[tokens_count.*] = token.literalToken(@intCast(u32, v)); tokens_count.* += 1; } return; } // matchLen returns the match length between src[s..] and src[t..]. // t can be negative to indicate the match is starting in self.prev. // We assume that src[s-4 .. s] and src[t-4 .. t] already match. fn matchLen(self: *Self, s: i32, t: i32, src: []u8) i32 { var s1 = @intCast(u32, s) + max_match_length - 4; if (s1 > src.len) { s1 = @intCast(u32, src.len); } // If we are inside the current block if (t >= 0) { var b = src[@intCast(usize, t)..]; var a = src[@intCast(usize, s)..@intCast(usize, s1)]; b = b[0..a.len]; // Extend the match to be as long as possible. for (a) |_, i| { if (a[i] != b[i]) { return @intCast(i32, i); } } return @intCast(i32, a.len); } // We found a match in the previous block. var tp = @intCast(i32, self.prev_len) + t; if (tp < 0) { return 0; } // Extend the match to be as long as possible. var a = src[@intCast(usize, s)..@intCast(usize, s1)]; var b = self.prev[@intCast(usize, tp)..@intCast(usize, self.prev_len)]; if (b.len > a.len) { b = b[0..a.len]; } a = a[0..b.len]; for (b) |_, i| { if (a[i] != b[i]) { return @intCast(i32, i); } } // If we reached our limit, we matched everything we are // allowed to in the previous block and we return. var n = @intCast(i32, b.len); if (@intCast(u32, s + n) == s1) { return n; } // Continue looking for more matches in the current block. a = src[@intCast(usize, s + n)..@intCast(usize, s1)]; b = src[0..a.len]; for (a) |_, i| { if (a[i] != b[i]) { return @intCast(i32, i) + n; } } return @intCast(i32, a.len) + n; } // Reset resets the encoding history. // This ensures that no matches are made to the previous block. pub fn reset(self: *Self) void { self.prev_len = 0; // Bump the offset, so all matches will fail distance check. // Nothing should be >= self.cur in the table. self.cur += max_match_offset; // Protect against self.cur wraparound. if (self.cur >= buffer_reset) { self.shiftOffsets(); } } // shiftOffsets will shift down all match offset. // This is only called in rare situations to prevent integer overflow. // // See https://golang.org/issue/18636 and https://golang.org/issues/34121. fn shiftOffsets(self: *Self) void { if (self.prev_len == 0) { // We have no history; just clear the table. for (self.table) |_, i| { self.table[i] = TableEntry{ .val = 0, .offset = 0 }; } self.cur = max_match_offset + 1; return; } // Shift down everything in the table that isn't already too far away. for (self.table) |_, i| { var v = self.table[i].offset - self.cur + max_match_offset + 1; if (v < 0) { // We want to reset self.cur to max_match_offset + 1, so we need to shift // all table entries down by (self.cur - (max_match_offset + 1)). // Because we ignore matches > max_match_offset, we can cap // any negative offsets at 0. v = 0; } self.table[i].offset = v; } self.cur = max_match_offset + 1; } }; test "best speed match 1/3" { const expect = std.testing.expect; { var previous = [_]u8{ 0, 0, 0, 1, 2 }; var e = DeflateFast{ .prev = &previous, .prev_len = previous.len, .table = undefined, .allocator = undefined, .cur = 0, }; var current = [_]u8{ 3, 4, 5, 0, 1, 2, 3, 4, 5 }; var got: i32 = e.matchLen(3, -3, &current); try expect(got == 6); } { var previous = [_]u8{ 0, 0, 0, 1, 2 }; var e = DeflateFast{ .prev = &previous, .prev_len = previous.len, .table = undefined, .allocator = undefined, .cur = 0, }; var current = [_]u8{ 2, 4, 5, 0, 1, 2, 3, 4, 5 }; var got: i32 = e.matchLen(3, -3, &current); try expect(got == 3); } { var previous = [_]u8{ 0, 0, 0, 1, 1 }; var e = DeflateFast{ .prev = &previous, .prev_len = previous.len, .table = undefined, .allocator = undefined, .cur = 0, }; var current = [_]u8{ 3, 4, 5, 0, 1, 2, 3, 4, 5 }; var got: i32 = e.matchLen(3, -3, &current); try expect(got == 2); } { var previous = [_]u8{ 0, 0, 0, 1, 2 }; var e = DeflateFast{ .prev = &previous, .prev_len = previous.len, .table = undefined, .allocator = undefined, .cur = 0, }; var current = [_]u8{ 2, 2, 2, 2, 1, 2, 3, 4, 5 }; var got: i32 = e.matchLen(0, -1, &current); try expect(got == 4); } { var previous = [_]u8{ 0, 0, 0, 1, 2, 3, 4, 5, 2, 2 }; var e = DeflateFast{ .prev = &previous, .prev_len = previous.len, .table = undefined, .allocator = undefined, .cur = 0, }; var current = [_]u8{ 2, 2, 2, 2, 1, 2, 3, 4, 5 }; var got: i32 = e.matchLen(4, -7, &current); try expect(got == 5); } { var previous = [_]u8{ 9, 9, 9, 9, 9 }; var e = DeflateFast{ .prev = &previous, .prev_len = previous.len, .table = undefined, .allocator = undefined, .cur = 0, }; var current = [_]u8{ 2, 2, 2, 2, 1, 2, 3, 4, 5 }; var got: i32 = e.matchLen(0, -1, &current); try expect(got == 0); } { var previous = [_]u8{ 9, 9, 9, 9, 9 }; var e = DeflateFast{ .prev = &previous, .prev_len = previous.len, .table = undefined, .allocator = undefined, .cur = 0, }; var current = [_]u8{ 9, 2, 2, 2, 1, 2, 3, 4, 5 }; var got: i32 = e.matchLen(1, 0, &current); try expect(got == 0); } } test "best speed match 2/3" { const expect = std.testing.expect; { var previous = [_]u8{}; var e = DeflateFast{ .prev = &previous, .prev_len = previous.len, .table = undefined, .allocator = undefined, .cur = 0, }; var current = [_]u8{ 9, 2, 2, 2, 1, 2, 3, 4, 5 }; var got: i32 = e.matchLen(1, -5, &current); try expect(got == 0); } { var previous = [_]u8{}; var e = DeflateFast{ .prev = &previous, .prev_len = previous.len, .table = undefined, .allocator = undefined, .cur = 0, }; var current = [_]u8{ 9, 2, 2, 2, 1, 2, 3, 4, 5 }; var got: i32 = e.matchLen(1, -1, &current); try expect(got == 0); } { var previous = [_]u8{}; var e = DeflateFast{ .prev = &previous, .prev_len = previous.len, .table = undefined, .allocator = undefined, .cur = 0, }; var current = [_]u8{ 2, 2, 2, 2, 1, 2, 3, 4, 5 }; var got: i32 = e.matchLen(1, 0, &current); try expect(got == 3); } { var previous = [_]u8{ 3, 4, 5 }; var e = DeflateFast{ .prev = &previous, .prev_len = previous.len, .table = undefined, .allocator = undefined, .cur = 0, }; var current = [_]u8{ 3, 4, 5 }; var got: i32 = e.matchLen(0, -3, &current); try expect(got == 3); } } test "best speed match 2/2" { const testing = std.testing; const expect = testing.expect; const Case = struct { previous: u32, current: u32, s: i32, t: i32, expected: i32, }; const cases = [_]Case{ .{ .previous = 1000, .current = 1000, .s = 0, .t = -1000, .expected = max_match_length - 4, }, .{ .previous = 200, .s = 0, .t = -200, .current = 500, .expected = max_match_length - 4, }, .{ .previous = 200, .s = 1, .t = 0, .current = 500, .expected = max_match_length - 4, }, .{ .previous = max_match_length - 4, .s = 0, .t = -(max_match_length - 4), .current = 500, .expected = max_match_length - 4, }, .{ .previous = 200, .s = 400, .t = -200, .current = 500, .expected = 100, }, .{ .previous = 10, .s = 400, .t = 200, .current = 500, .expected = 100, }, }; for (cases) |c| { var previous = try testing.allocator.alloc(u8, c.previous); defer testing.allocator.free(previous); mem.set(u8, previous, 0); var current = try testing.allocator.alloc(u8, c.current); defer testing.allocator.free(current); mem.set(u8, current, 0); var e = DeflateFast{ .prev = previous, .prev_len = @intCast(u32, previous.len), .table = undefined, .allocator = undefined, .cur = 0, }; var got: i32 = e.matchLen(c.s, c.t, current); try expect(got == c.expected); } } test "best speed shift offsets" { const testing = std.testing; const expect = std.testing.expect; // Test if shiftoffsets properly preserves matches and resets out-of-range matches // seen in https://github.com/golang/go/issues/4142 var enc = deflateFast(); try enc.init(testing.allocator); defer enc.deinit(); // test_data may not generate internal matches. var test_data = [32]u8{ 0xf5, 0x25, 0xf2, 0x55, 0xf6, 0xc1, 0x1f, 0x0b, 0x10, 0xa1, 0xd0, 0x77, 0x56, 0x38, 0xf1, 0x9c, 0x7f, 0x85, 0xc5, 0xbd, 0x16, 0x28, 0xd4, 0xf9, 0x03, 0xd4, 0xc0, 0xa1, 0x1e, 0x58, 0x5b, 0xc9, }; var tokens = [_]token.Token{0} ** 32; var tokens_count: u16 = 0; // Encode the testdata with clean state. // Second part should pick up matches from the first block. tokens_count = 0; enc.encode(&tokens, &tokens_count, &test_data); var want_first_tokens = tokens_count; tokens_count = 0; enc.encode(&tokens, &tokens_count, &test_data); var want_second_tokens = tokens_count; try expect(want_first_tokens > want_second_tokens); // Forward the current indicator to before wraparound. enc.cur = buffer_reset - @intCast(i32, test_data.len); // Part 1 before wrap, should match clean state. tokens_count = 0; enc.encode(&tokens, &tokens_count, &test_data); var got = tokens_count; try expect(want_first_tokens == got); // Verify we are about to wrap. try expect(enc.cur == buffer_reset); // Part 2 should match clean state as well even if wrapped. tokens_count = 0; enc.encode(&tokens, &tokens_count, &test_data); got = tokens_count; try expect(want_second_tokens == got); // Verify that we wrapped. try expect(enc.cur < buffer_reset); // Forward the current buffer, leaving the matches at the bottom. enc.cur = buffer_reset; enc.shiftOffsets(); // Ensure that no matches were picked up. tokens_count = 0; enc.encode(&tokens, &tokens_count, &test_data); got = tokens_count; try expect(want_first_tokens == got); } test "best speed reset" { // test that encoding is consistent across a warparound of the table offset. // See https://github.com/golang/go/issues/34121 const expect = std.testing.expect; const fmt = std.fmt; const testing = std.testing; const ArrayList = std.ArrayList; const input_size = 65536; var input = try testing.allocator.alloc(u8, input_size); defer testing.allocator.free(input); var i: usize = 0; while (i < input_size) : (i += 1) { _ = try fmt.bufPrint(input, "asdfasdfasdfasdf{d}{d}fghfgujyut{d}yutyu\n", .{ i, i, i }); } // This is specific to level 1 (best_speed). const level = .best_speed; const offset: usize = 1; // We do an encode with a clean buffer to compare. var want = ArrayList(u8).init(testing.allocator); defer want.deinit(); var clean_comp = try deflate.compressor( testing.allocator, want.writer(), .{ .level = level }, ); defer clean_comp.deinit(); // Write 3 times, close. try clean_comp.writer().writeAll(input); try clean_comp.writer().writeAll(input); try clean_comp.writer().writeAll(input); try clean_comp.close(); var o = offset; while (o <= 256) : (o *= 2) { var discard = ArrayList(u8).init(testing.allocator); defer discard.deinit(); var comp = try deflate.compressor( testing.allocator, discard.writer(), .{ .level = level }, ); defer comp.deinit(); // Reset until we are right before the wraparound. // Each reset adds max_match_offset to the offset. i = 0; var limit = (buffer_reset - input.len - o - max_match_offset) / max_match_offset; while (i < limit) : (i += 1) { // skip ahead to where we are close to wrap around... comp.reset(discard.writer()); } var got = ArrayList(u8).init(testing.allocator); defer got.deinit(); comp.reset(got.writer()); // Write 3 times, close. try comp.writer().writeAll(input); try comp.writer().writeAll(input); try comp.writer().writeAll(input); try comp.close(); // output must match at wraparound try expect(mem.eql(u8, got.items, want.items)); } }
lib/std/compress/deflate/deflate_fast.zig
const ImageInStream = zigimg.ImageInStream; const ImageSeekStream = zigimg.ImageSeekStream; const PixelFormat = zigimg.PixelFormat; const assert = std.debug.assert; const color = zigimg.color; const errors = zigimg.errors; const std = @import("std"); const testing = std.testing; const netpbm = zigimg.netpbm; const zigimg = @import("zigimg"); usingnamespace @import("helpers.zig"); test "Load ASCII PBM image" { const file = try testOpenFile(zigimg_test_allocator, "tests/fixtures/netpbm/pbm_ascii.pbm"); defer file.close(); var fileInStream = file.inStream(); var fileSeekStream = file.seekableStream(); var pbmFile = netpbm.PBM{}; var pixelsOpt: ?color.ColorStorage = null; try pbmFile.read(zigimg_test_allocator, @ptrCast(*ImageInStream, &fileInStream.stream), @ptrCast(*ImageSeekStream, &fileSeekStream.stream), &pixelsOpt); defer { if (pixelsOpt) |pixels| { pixels.deinit(zigimg_test_allocator); } } expectEq(pbmFile.header.width, 8); expectEq(pbmFile.header.height, 16); expectEq(pbmFile.pixel_format, PixelFormat.Monochrome); testing.expect(pixelsOpt != null); if (pixelsOpt) |pixels| { testing.expect(pixels == .Monochrome); expectEq(pixels.Monochrome[0].value, 0); expectEq(pixels.Monochrome[1].value, 1); expectEq(pixels.Monochrome[15 * 8 + 7].value, 1); } } test "Load binary PBM image" { const file = try testOpenFile(zigimg_test_allocator, "tests/fixtures/netpbm/pbm_binary.pbm"); defer file.close(); var fileInStream = file.inStream(); var fileSeekStream = file.seekableStream(); var pbmFile = netpbm.PBM{}; var pixelsOpt: ?color.ColorStorage = null; try pbmFile.read(zigimg_test_allocator, @ptrCast(*ImageInStream, &fileInStream.stream), @ptrCast(*ImageSeekStream, &fileSeekStream.stream), &pixelsOpt); defer { if (pixelsOpt) |pixels| { pixels.deinit(zigimg_test_allocator); } } expectEq(pbmFile.header.width, 8); expectEq(pbmFile.header.height, 16); expectEq(pbmFile.pixel_format, PixelFormat.Monochrome); testing.expect(pixelsOpt != null); if (pixelsOpt) |pixels| { testing.expect(pixels == .Monochrome); expectEq(pixels.Monochrome[0].value, 0); expectEq(pixels.Monochrome[1].value, 1); expectEq(pixels.Monochrome[15 * 8 + 7].value, 1); } } test "Load ASCII PGM 8-bit grayscale image" { const file = try testOpenFile(zigimg_test_allocator, "tests/fixtures/netpbm/pgm_ascii_grayscale8.pgm"); defer file.close(); var fileInStream = file.inStream(); var fileSeekStream = file.seekableStream(); var pgmFile = netpbm.PGM{}; var pixelsOpt: ?color.ColorStorage = null; try pgmFile.read(zigimg_test_allocator, @ptrCast(*ImageInStream, &fileInStream.stream), @ptrCast(*ImageSeekStream, &fileSeekStream.stream), &pixelsOpt); defer { if (pixelsOpt) |pixels| { pixels.deinit(zigimg_test_allocator); } } expectEq(pgmFile.header.width, 16); expectEq(pgmFile.header.height, 24); expectEq(pgmFile.pixel_format, PixelFormat.Grayscale8); testing.expect(pixelsOpt != null); if (pixelsOpt) |pixels| { testing.expect(pixels == .Grayscale8); expectEq(pixels.Grayscale8[0].value, 2); expectEq(pixels.Grayscale8[1].value, 5); expectEq(pixels.Grayscale8[383].value, 196); } } test "Load Binary PGM 8-bit grayscale image" { const file = try testOpenFile(zigimg_test_allocator, "tests/fixtures/netpbm/pgm_binary_grayscale8.pgm"); defer file.close(); var fileInStream = file.inStream(); var fileSeekStream = file.seekableStream(); var pgmFile = netpbm.PGM{}; var pixelsOpt: ?color.ColorStorage = null; try pgmFile.read(zigimg_test_allocator, @ptrCast(*ImageInStream, &fileInStream.stream), @ptrCast(*ImageSeekStream, &fileSeekStream.stream), &pixelsOpt); defer { if (pixelsOpt) |pixels| { pixels.deinit(zigimg_test_allocator); } } expectEq(pgmFile.header.width, 16); expectEq(pgmFile.header.height, 24); expectEq(pgmFile.pixel_format, PixelFormat.Grayscale8); testing.expect(pixelsOpt != null); if (pixelsOpt) |pixels| { testing.expect(pixels == .Grayscale8); expectEq(pixels.Grayscale8[0].value, 2); expectEq(pixels.Grayscale8[1].value, 5); expectEq(pixels.Grayscale8[383].value, 196); } } test "Load ASCII PGM 16-bit grayscale image" { const file = try testOpenFile(zigimg_test_allocator, "tests/fixtures/netpbm/pgm_ascii_grayscale16.pgm"); defer file.close(); var fileInStream = file.inStream(); var fileSeekStream = file.seekableStream(); var pgmFile = netpbm.PGM{}; var pixelsOpt: ?color.ColorStorage = null; try pgmFile.read(zigimg_test_allocator, @ptrCast(*ImageInStream, &fileInStream.stream), @ptrCast(*ImageSeekStream, &fileSeekStream.stream), &pixelsOpt); defer { if (pixelsOpt) |pixels| { pixels.deinit(zigimg_test_allocator); } } expectEq(pgmFile.header.width, 8); expectEq(pgmFile.header.height, 16); expectEq(pgmFile.pixel_format, PixelFormat.Grayscale8); testing.expect(pixelsOpt != null); if (pixelsOpt) |pixels| { testing.expect(pixels == .Grayscale8); expectEq(pixels.Grayscale8[0].value, 13); expectEq(pixels.Grayscale8[1].value, 16); expectEq(pixels.Grayscale8[127].value, 237); } } test "Load Binary PGM 16-bit grayscale image" { const file = try testOpenFile(zigimg_test_allocator, "tests/fixtures/netpbm/pgm_binary_grayscale16.pgm"); defer file.close(); var fileInStream = file.inStream(); var fileSeekStream = file.seekableStream(); var pgmFile = netpbm.PGM{}; var pixelsOpt: ?color.ColorStorage = null; try pgmFile.read(zigimg_test_allocator, @ptrCast(*ImageInStream, &fileInStream.stream), @ptrCast(*ImageSeekStream, &fileSeekStream.stream), &pixelsOpt); defer { if (pixelsOpt) |pixels| { pixels.deinit(zigimg_test_allocator); } } expectEq(pgmFile.header.width, 8); expectEq(pgmFile.header.height, 16); expectEq(pgmFile.pixel_format, PixelFormat.Grayscale8); testing.expect(pixelsOpt != null); if (pixelsOpt) |pixels| { testing.expect(pixels == .Grayscale8); expectEq(pixels.Grayscale8[0].value, 13); expectEq(pixels.Grayscale8[1].value, 16); expectEq(pixels.Grayscale8[127].value, 237); } } test "Load ASCII PPM image" { const file = try testOpenFile(zigimg_test_allocator, "tests/fixtures/netpbm/ppm_ascii_rgb24.ppm"); defer file.close(); var fileInStream = file.inStream(); var fileSeekStream = file.seekableStream(); var ppmFile = netpbm.PPM{}; var pixelsOpt: ?color.ColorStorage = null; try ppmFile.read(zigimg_test_allocator, @ptrCast(*ImageInStream, &fileInStream.stream), @ptrCast(*ImageSeekStream, &fileSeekStream.stream), &pixelsOpt); defer { if (pixelsOpt) |pixels| { pixels.deinit(zigimg_test_allocator); } } expectEq(ppmFile.header.width, 27); expectEq(ppmFile.header.height, 27); expectEq(ppmFile.pixel_format, PixelFormat.Rgb24); testing.expect(pixelsOpt != null); if (pixelsOpt) |pixels| { testing.expect(pixels == .Rgb24); expectEq(pixels.Rgb24[0].R, 0x34); expectEq(pixels.Rgb24[0].G, 0x53); expectEq(pixels.Rgb24[0].B, 0x9f); expectEq(pixels.Rgb24[1].R, 0x32); expectEq(pixels.Rgb24[1].G, 0x5b); expectEq(pixels.Rgb24[1].B, 0x96); expectEq(pixels.Rgb24[26].R, 0xa8); expectEq(pixels.Rgb24[26].G, 0x5a); expectEq(pixels.Rgb24[26].B, 0x78); expectEq(pixels.Rgb24[27].R, 0x2e); expectEq(pixels.Rgb24[27].G, 0x54); expectEq(pixels.Rgb24[27].B, 0x99); expectEq(pixels.Rgb24[26 * 27 + 26].R, 0x88); expectEq(pixels.Rgb24[26 * 27 + 26].G, 0xb7); expectEq(pixels.Rgb24[26 * 27 + 26].B, 0x55); } } test "Load binary PPM image" { const file = try testOpenFile(zigimg_test_allocator, "tests/fixtures/netpbm/ppm_binary_rgb24.ppm"); defer file.close(); var fileInStream = file.inStream(); var fileSeekStream = file.seekableStream(); var ppmFile = netpbm.PPM{}; var pixelsOpt: ?color.ColorStorage = null; try ppmFile.read(zigimg_test_allocator, @ptrCast(*ImageInStream, &fileInStream.stream), @ptrCast(*ImageSeekStream, &fileSeekStream.stream), &pixelsOpt); defer { if (pixelsOpt) |pixels| { pixels.deinit(zigimg_test_allocator); } } expectEq(ppmFile.header.width, 27); expectEq(ppmFile.header.height, 27); expectEq(ppmFile.pixel_format, PixelFormat.Rgb24); testing.expect(pixelsOpt != null); if (pixelsOpt) |pixels| { testing.expect(pixels == .Rgb24); expectEq(pixels.Rgb24[0].R, 0x34); expectEq(pixels.Rgb24[0].G, 0x53); expectEq(pixels.Rgb24[0].B, 0x9f); expectEq(pixels.Rgb24[1].R, 0x32); expectEq(pixels.Rgb24[1].G, 0x5b); expectEq(pixels.Rgb24[1].B, 0x96); expectEq(pixels.Rgb24[26].R, 0xa8); expectEq(pixels.Rgb24[26].G, 0x5a); expectEq(pixels.Rgb24[26].B, 0x78); expectEq(pixels.Rgb24[27].R, 0x2e); expectEq(pixels.Rgb24[27].G, 0x54); expectEq(pixels.Rgb24[27].B, 0x99); expectEq(pixels.Rgb24[26 * 27 + 26].R, 0x88); expectEq(pixels.Rgb24[26 * 27 + 26].G, 0xb7); expectEq(pixels.Rgb24[26 * 27 + 26].B, 0x55); } }
tests/netpbm_test.zig
const std = @import("std"); pub const ParamDescription = struct { name: []const u8, label: []const u8, automatable: bool = true, display: fn (f32, []u8) []const u8 = displayDefault, initial: f32 = 0, }; pub fn Parameters(comptime descriptions: []const ParamDescription) type { var initial_values: [descriptions.len]f32 = undefined; for (descriptions) |desc, i| initial_values[i] = desc.initial; return struct { pub const count = descriptions.len; values: [descriptions.len]f32 = initial_values, pub fn get(self: @This(), comptime name: []const u8) f32 { return inline for (descriptions) |desc, i| { if (comptime std.mem.eql(u8, name, desc.name)) return self.values[i]; } else @compileError("Unknown parameter '" ++ name ++ "'"); } pub fn set(self: *@This(), comptime name: []const u8, value: f32) void { self.values[index] = value; } pub fn displayByIndex(self: @This(), index: usize, buf: []u8) ?[]const u8 { const desc = getDescription(index) orelse return null; return desc.display(self.values[index], buf); } pub fn setByIndex(self: *@This(), index: usize, value: f32) void { if (index >= count) return; self.values[index] = value; } pub fn getByIndex(self: @This(), index: usize) ?f32 { if (index >= count) return null; return self.values[index]; } pub fn getDescription(index: usize) ?ParamDescription { if (index >= count) return null; return descriptions[index]; } }; } pub fn displayDefault(value: f32, out: []u8) []const u8 { return std.fmt.bufPrint(out, "{d:.5}", .{value}) catch return out; } pub fn displayPercentage(value: f32, out: []u8) []const u8 { return std.fmt.bufPrint(out, "{d:.2} %", .{value * 100}) catch return out; } fn identity(x: f32) f32 { return x; } const ParamDefinition = struct { name: []const u8, external: ?struct { label: []const u8, automatable: bool = true, display: fn (f32, []u8) []const u8 = displayDefault, } = null, }; pub fn ParamMapping(comptime T: type) type { return struct { from: fn (f32) T, to: fn (T) f32, }; } pub fn FloatRange(comptime min: f32, comptime max: f32) ParamMapping(f32) { const Helper = struct { pub fn from(raw: f32) f32 { return min + raw * (max - min); } pub fn to(value: f32) f32 { return (value - min) / (max - min); } }; return ParamMapping(f32){ .from = Helper.from, .to = Helper.to, }; } pub fn Param( comptime ParamT: type, def: ParamDefinition, comptime mapping: ParamMapping(ParamT), comptime init: ?ParamT, ) type { return struct { pub const T = ParamT; pub const definition = def; pub const initial = init; pub fn fromNormalized(value: f32) def.T { return mapping.from(value); } pub fn toNormalized(value: def.T) f32 { return mapping.to(value); } }; } pub fn EnumMapping(comptime EnumT: type) ParamMapping(EnumT) { const Helper = struct { pub fn from(raw: f32) EnumT { const fields = comptime std.meta.fields(EnumT); const f_idx = std.math.floor(raw * 0.99999 * @intToFloat(f32, fields.len)); const idx = @floatToInt(std.meta.Tag(EnumT), f_idx); return @intToEnum(EnumT, idx); } pub fn to(value: EnumT) f32 { const fields = comptime std.meta.fields(EnumT); const idx = @enumToInt(value); return @intToFloat(f32, idx) / @intToFloat(f32, fields.len - 1); } }; return ParamMapping(EnumT){ .from = Helper.from, .to = Helper.to, }; } pub fn Params(comptime params: anytype) type { var external_count = 0; var ext_index_to_index: [params.len]usize = undefined; var initial_values: [params.len]f32 = undefined; inline for (params) |param, i| { if (param.definition.external != null) { ext_index_to_index[external_count] = i; external_count += 1; } initial_values[i] = param.toNormalized(param.initial); } return struct { pub const external_param_count: usize = external_count; values: [params.len]f32 = initial_values, external: []const usize = ext_index_to_index[0..external_count], pub fn get(self: @This(), comptime name: []const u8) params[getIndex(name)].definition.T { const param = params[comptime getIndex(name)]; const raw = self.values[comptime getIndex(name)]; return param.fromNormalized(raw); } pub fn getExternal(self: @This(), idx: usize) fn getIndex(comptime name: []const u8) usize { return inline for (params) |param, i| { if (comptime std.mem.eql(u8, param.definition.name, name)) break i; } else @compileError("Unknown Parameter '" ++ name ++ "'"); } }; } const M = enum { Lissajous, Waterfall, Oscilloscope, };
src/util/parameters.zig
const ParsingError = @import("errors.zig").ParsingError; // ASCII codes accepted for an URI // Cf: Borrowed from Seamonstar's httparse library. // https://github.com/seanmonstar/httparse/blob/01e68542605d8a24a707536561c27a336d4090dc/src/lib.rs#L63 const URI_MAP = [_]bool{ false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, // \0 \t \n \r false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, // commands false, true, false, true, true, true, true, true, true, true, true, true, true, true, true, true, // \s ! " # $ % & ' ( ) * + , - . / true, true, true, true, true, true, true, true, true, true, true, true, false, true, false, true, // 0 1 2 3 4 5 6 7 8 9 : ; < = > ? true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, // @ A B C D E F G H I J K L M N O true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, // P Q R S T U V W X Y Z [ \ ] ^ _ true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, // ` a b c d e f g h i j k l m n o true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, false, // p q r s t u v w x y z { | } ~ del // ====== Extended ASCII (aka. obs-text) ====== false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, }; fn is_uri_token(char: u8) bool { return URI_MAP[char]; } pub fn readUri(buffer: []const u8) ParsingError![]const u8 { for (buffer) |char, i| { if (char == ' ') { return buffer[0..i]; } if (!is_uri_token(char)) { return error.Invalid; } } return error.Invalid; }
src/events/utils.zig
pub const ulaw_to_i16 = [256]i16{ -32124, -31100, -30076, -29052, -28028, -27004, -25980, -24956, -23932, -22908, -21884, -20860, -19836, -18812, -17788, -16764, -15996, -15484, -14972, -14460, -13948, -13436, -12924, -12412, -11900, -11388, -10876, -10364, -9852, -9340, -8828, -8316, -7932, -7676, -7420, -7164, -6908, -6652, -6396, -6140, -5884, -5628, -5372, -5116, -4860, -4604, -4348, -4092, -3900, -3772, -3644, -3516, -3388, -3260, -3132, -3004, -2876, -2748, -2620, -2492, -2364, -2236, -2108, -1980, -1884, -1820, -1756, -1692, -1628, -1564, -1500, -1436, -1372, -1308, -1244, -1180, -1116, -1052, -988, -924, -876, -844, -812, -780, -748, -716, -684, -652, -620, -588, -556, -524, -492, -460, -428, -396, -372, -356, -340, -324, -308, -292, -276, -260, -244, -228, -212, -196, -180, -164, -148, -132, -120, -112, -104, -96, -88, -80, -72, -64, -56, -48, -40, -32, -24, -16, -8, 0, 32124, 31100, 30076, 29052, 28028, 27004, 25980, 24956, 23932, 22908, 21884, 20860, 19836, 18812, 17788, 16764, 15996, 15484, 14972, 14460, 13948, 13436, 12924, 12412, 11900, 11388, 10876, 10364, 9852, 9340, 8828, 8316, 7932, 7676, 7420, 7164, 6908, 6652, 6396, 6140, 5884, 5628, 5372, 5116, 4860, 4604, 4348, 4092, 3900, 3772, 3644, 3516, 3388, 3260, 3132, 3004, 2876, 2748, 2620, 2492, 2364, 2236, 2108, 1980, 1884, 1820, 1756, 1692, 1628, 1564, 1500, 1436, 1372, 1308, 1244, 1180, 1116, 1052, 988, 924, 876, 844, 812, 780, 748, 716, 684, 652, 620, 588, 556, 524, 492, 460, 428, 396, 372, 356, 340, 324, 308, 292, 276, 260, 244, 228, 212, 196, 180, 164, 148, 132, 120, 112, 104, 96, 88, 80, 72, 64, 56, 48, 40, 32, 24, 16, 8, 0, }; // decodes alaw to int16 using a lookup table. pub const alaw_to_i16 = [256]i16{ -5504, -5248, -6016, -5760, -4480, -4224, -4992, -4736, -7552, -7296, -8064, -7808, -6528, -6272, -7040, -6784, -2752, -2624, -3008, -2880, -2240, -2112, -2496, -2368, -3776, -3648, -4032, -3904, -3264, -3136, -3520, -3392, -22016, -20992, -24064, -23040, -17920, -16896, -19968, -18944, -30208, -29184, -32256, -31232, -26112, -25088, -28160, -27136, -11008, -10496, -12032, -11520, -8960, -8448, -9984, -9472, -15104, -14592, -16128, -15616, -13056, -12544, -14080, -13568, -344, -328, -376, -360, -280, -264, -312, -296, -472, -456, -504, -488, -408, -392, -440, -424, -88, -72, -120, -104, -24, -8, -56, -40, -216, -200, -248, -232, -152, -136, -184, -168, -1376, -1312, -1504, -1440, -1120, -1056, -1248, -1184, -1888, -1824, -2016, -1952, -1632, -1568, -1760, -1696, -688, -656, -752, -720, -560, -528, -624, -592, -944, -912, -1008, -976, -816, -784, -880, -848, 5504, 5248, 6016, 5760, 4480, 4224, 4992, 4736, 7552, 7296, 8064, 7808, 6528, 6272, 7040, 6784, 2752, 2624, 3008, 2880, 2240, 2112, 2496, 2368, 3776, 3648, 4032, 3904, 3264, 3136, 3520, 3392, 22016, 20992, 24064, 23040, 17920, 16896, 19968, 18944, 30208, 29184, 32256, 31232, 26112, 25088, 28160, 27136, 11008, 10496, 12032, 11520, 8960, 8448, 9984, 9472, 15104, 14592, 16128, 15616, 13056, 12544, 14080, 13568, 344, 328, 376, 360, 280, 264, 312, 296, 472, 456, 504, 488, 408, 392, 440, 424, 88, 72, 120, 104, 24, 8, 56, 40, 216, 200, 248, 232, 152, 136, 184, 168, 1376, 1312, 1504, 1440, 1120, 1056, 1248, 1184, 1888, 1824, 2016, 1952, 1632, 1568, 1760, 1696, 688, 656, 752, 720, 560, 528, 624, 592, 944, 912, 1008, 976, 816, 784, 880, 848, };
src/wav/g711.zig
const std = @import("std"); const datetime = @import("datetime"); const Chat = @import("../Chat.zig"); const ParseResult = union(enum) { ping, clear: ?[]const u8, message: Chat.Message, }; pub fn parseMessage(data: []u8, alloc: std.mem.Allocator, tz: datetime.Timezone) !ParseResult { std.log.debug("data:\n{s}\n", .{data}); if (data.len == 0) return error.NoData; // Basic message structure: // <@metadata >:<prefix> <command> <params> :<trailing> // // Metadata and trailing are optional. Metadata starts with `@` and ends with a space. // Prefix is missing from PINGs, present otherwise, commands can have zero params. var remaining_data: []const u8 = data; const metadata: []const u8 = blk: { if (remaining_data[0] == '@') { // Message has metadata const end = std.mem.indexOf(u8, data, " :") orelse return error.NoChunks; const m = remaining_data[1..end]; // Skip the `@` remaining_data = remaining_data[end + 1 ..]; // Leave the colon there to unify the two cases break :blk m; } // Message has no metadata break :blk ""; }; std.log.debug("metadata: [{s}]", .{metadata}); // Prefix const prefix = blk: { if (remaining_data[0] == ':') { // Message has prefix const end = std.mem.indexOf(u8, remaining_data, " ") orelse return error.NoCommand; const p = remaining_data[1..end]; // Skip the colon remaining_data = remaining_data[end + 1 ..]; break :blk p; } // Message has no prefix break :blk ""; }; std.log.debug("prefix: [{s}]", .{prefix}); // Command and arguments const cmd_and_args = blk: { if (std.mem.indexOf(u8, remaining_data, " :")) |end| { // Message has trailer const cmd_and_args = remaining_data[0..end]; remaining_data = remaining_data[end + 2 ..]; // Skip the entire separator break :blk cmd_and_args; } // Message has no trailer const cmd_and_args = remaining_data; remaining_data = ""; break :blk cmd_and_args; }; std.log.debug("cmd and args: [{s}]", .{cmd_and_args}); // Trailer const trailer = remaining_data[0..]; // Empty string if no trailer std.log.debug("trailer: [{s}]", .{trailer}); var cmd_and_args_it = std.mem.tokenize(u8, cmd_and_args, " "); const cmd = cmd_and_args_it.next().?; // Calling the iterator once should never fail // Prepare fields common to multiple msg types var time: [5]u8 = undefined; var now = datetime.Datetime.now().shiftTimezone(&tz); _ = std.fmt.bufPrint(&time, "{d:0>2}:{d:0>2}", .{ now.time.hour, now.time.minute, }) catch unreachable; // we know we have the space // Switch over all possible message types if (std.mem.eql(u8, cmd, "PRIVMSG")) { // @badge-info=; // badges=; // client-nonce=69fcc90179a36691a27dcf8f91a706a9; // color=; // display-name=SebastianKeller_; // emotes=; // flags=; // id=77bcc67d-2941-4c9d-a281-f83f9cc4fad4; // mod=0; // room-id=102701971; // subscriber=0; // tmi-sent-ts=1633534241992; // turbo=0; // user-id=79632778; // user-type= :sebastiankeller_!<EMAIL>@<EMAIL>_.tmi.<EMAIL> // PRIVMSG #kristoff_it :im not, ban me const meta = try parseMetaSubsetLinear(metadata, [_][]const u8{ "badge-info", // 0 "display-name", // 1 "emotes", // 2 "mod", // 3 }); const sub_badge: Badge = if (meta[0].len > 0) try parseBadge(meta[0]) else Badge{ .name = "", .count = 0 }; const display_name = meta[1]; const emotes = try parseEmotes(meta[2], alloc); const is_mod = std.mem.eql(u8, meta[3], "1"); const highlight_pos = std.mem.indexOf(u8, metadata, "msg-id=highlighted-message;"); // Parse the proper login name, which is similar to the display name // but not exactly the same and it's needed for cleaning up messages // when banning somebody. const login_name = prefix[0..(std.mem.indexOfScalar(u8, prefix, '!') orelse 0)]; return ParseResult{ .message = Chat.Message{ .login_name = login_name, .time = time, .kind = .{ .chat = .{ .text = trailer, .display_name = display_name, .sub_months = sub_badge.count, .is_founder = std.mem.eql(u8, sub_badge.name, "founder"), .emotes = emotes, .is_mod = is_mod, .is_highlighted = highlight_pos != null, }, }, }, }; } else if (std.mem.eql(u8, cmd, "CLEARCHAT")) { // @ban-duration=600; // room-id=102701971; // target-user-id=137180345; // tmi-sent-ts=1625379632217 :tmi.twitch.tv CLEARCHAT #kristoff_it :soul_serpent return ParseResult{ .clear = if (trailer.len > 0) trailer else null, }; } else if (std.mem.eql(u8, cmd, "USERNOTICE")) { // Welcome to a new world of pain. // Here's another great protocol idea from Twitch: // Hidden deep inside the metadata there's the `msg-id` field, // which, in the case of USERNOTICE is not a unique id, but // a tag that identifies the event type among the following: // // sub, resub, subgift, anonsubgift, submysterygift, // giftpaidupgrade, rewardgift, anongiftpaidupgrade, // raid, unraid, ritual, bitsbadgetier // // If you read already other comments in this file you // probably know where this is going: each type has // different fields present, which makes our linear // scan strategy less applicable. // The solution in this case is to look twice: once to // get the message type and a second time to grab all the // fields we need. // // One might be tempted at this point to really implement // the sorted version of this algorithm NotLikeThis const msg_type = (try parseMetaSubsetLinear(metadata, [1][]const u8{"msg-id"}))[0]; if (std.mem.eql(u8, msg_type, "raid")) { // @badge-info=; // badges=; // color=#5F9EA0; // display-name=togglebit; // emotes=; // flags=; // id=20d2355b-92d6-4262-a5d5-c0ef7ccb8bad; // login=togglebit; // mod=0; // msg-id=raid; // msg-param-displayName=togglebit; // msg-param-login=togglebit; // msg-param-profileImageURL=https://static-cdn.jtvnw.net/jtv_user_pictures/0bb9c502-ab5d-4440-9c9d-14e5260ebf86-profile_image-70x70.png; // msg-param-viewerCount=126; // room-id=102701971; // subscriber=0; // system-msg=126\sraiders\sfrom\stogglebit\shave\sjoined!; // tmi-sent-ts=1619015565551; // user-id=474725923; // user-type= :tmi.twitch.tv USERNOTICE #kristoff_it const meta = try parseMetaSubsetLinear(metadata, [_][]const u8{ "display-name", // 0 "login", // 1 "msg-param-profileImageURL", // 2 "msg-param-viewerCount", // 3 }); const count = try std.fmt.parseInt(usize, meta[3], 10); return ParseResult{ .message = Chat.Message{ .login_name = meta[1], .time = time, .kind = .{ .raid = .{ .display_name = meta[0], .profile_picture_url = meta[2], .count = count, }, }, }, }; } if (std.mem.eql(u8, msg_type, "submysterygift")) { // @badge-info=founder/1; // badges=founder/0; // color=; // display-name=kristoff_it; // emotes=; // flags=; // id=47f6274d-970c-4f2e-ab10-6cf1474a0813; // login=kristoff_it; // mod=0; // msg-id=submysterygift; // msg-param-mass-gift-count=5; // msg-param-origin-id=d0\sf0\s99\s5b\s67\s87\s9d\s6e\s79\s92\se9\s25\sbf\s75\s40\s82\se0\s9b\sea\s2e; // msg-param-sender-count=5; // msg-param-sub-plan=1000; // room-id=180859114; // subscriber=1; // system-msg=kristoff_it\sis\sgifting\s5\sTier\s1\sSubs\sto\smattknite's\scommunity!\sThey've\sgifted\sa\stotal\sof\s5\sin\sthe\schannel!; // tmi-sent-ts=1609457534121; // user-id=102701971; // user-type= :tmi.twitch.tv USERNOTICE #mattknite const meta = try parseMetaSubsetLinear(metadata, [_][]const u8{ "display-name", // 0 "login", // 1 "msg-param-mass-gift-count", // 2 "msg-param-sub-plan", // 3 }); const count = try std.fmt.parseInt(usize, meta[2], 10); const tier = try parseSubTier(meta[3]); return ParseResult{ .message = Chat.Message{ .login_name = meta[1], .time = time, .kind = .{ .sub_mistery_gift = .{ .display_name = meta[0], .count = count, .tier = tier, }, }, }, }; } else if (std.mem.eql(u8, msg_type, "subgift")) { // @badge-info=founder/1; // badges=founder/0; // color=; // display-name=kristoff_it; // emotes=; // flags=; // id=b35bbd66-50e7-4b77-831c-fab505906551; // login=kristoff_it; // mod=0; // msg-id=subgift; // msg-param-gift-months=1; // msg-param-months=1; // msg-param-origin-id=da\s39\sa3\see\s5e\s6b\s4b\s0d\s32\s55\sbf\sef\s95\s60\s18\s90\saf\sd8\s07\s09; // msg-param-recipient-display-name=g_w1; // msg-param-recipient-id=203259404; // msg-param-recipient-user-name=g_w1; // msg-param-sender-count=0; // msg-param-sub-plan-name=Channel\sSubscription\s(mattknite); // msg-param-sub-plan=1000; // room-id=180859114; // subscriber=1; // system-msg=kristoff_it\sgifted\sa\sTier\s1\ssub\sto\sg_w1!; // tmi-sent-ts=1609457535209; // user-id=102701971; // user-type= :tmi.twitch.tv USERNOTICE #mattknite const meta = try parseMetaSubsetLinear(metadata, [_][]const u8{ "display-name", // 0 "login", // 1 "msg-param-gift-months", // 2 "msg-param-recipient-display-name", // 3 "msg-param-recipient-user-name", // 4 "msg-param-sub-plan", // 5 }); const months = try std.fmt.parseInt(usize, meta[2], 10); const tier = try parseSubTier(meta[5]); return ParseResult{ .message = Chat.Message{ .login_name = meta[1], .time = time, .kind = .{ .sub_gift = .{ .sender_display_name = meta[0], .months = months, .tier = tier, .recipient_display_name = meta[3], .recipient_login_name = meta[4], }, }, }, }; } else if (std.mem.eql(u8, msg_type, "sub")) { const meta = try parseMetaSubsetLinear(metadata, [_][]const u8{ "display-name", // 0 "login", // 1 "msg-param-sub-plan", // 2 }); const tier = try parseSubTier(meta[2]); return ParseResult{ .message = Chat.Message{ .login_name = meta[1], .time = time, .kind = .{ .sub = .{ .display_name = meta[0], .tier = tier, }, }, }, }; } else if (std.mem.eql(u8, msg_type, "resub")) { // **UNRELIABLE** From the spec **UNRELIABLE** // @badge-info=; // badges=staff/1,broadcaster/1,turbo/1; // color=#008000; // display-name=ronni; // emotes=; // id=db25007f-7a18-43eb-9379-80131e44d633; // login=ronni; // mod=0; // msg-id=resub; // msg-param-cumulative-months=6; // msg-param-streak-months=2; // msg-param-should-share-streak=1; // msg-param-sub-plan=Prime; // msg-param-sub-plan-name=Prime; // room-id=1337;subscriber=1; // system-msg=ronni\shas\ssubscribed\sfor\s6\smonths!; // tmi-sent-ts=1507246572675; // turbo=1; // user-id=1337; // user-type=staff :tmi.twitch.tv USERNOTICE #dallas :Great stream -- keep it up! const meta = try parseMetaSubsetLinear(metadata, [_][]const u8{ "display-name", // 0 "emotes", // 1 "login", // 2 "msg-param-cumulative-months", // 3 "msg-param-sub-plan", // 4 }); const tier = try parseSubTier(meta[4]); const count = try std.fmt.parseInt(usize, meta[3], 10); const emotes = try parseEmotes(meta[1], alloc); return ParseResult{ .message = Chat.Message{ .login_name = meta[2], .time = time, .kind = .{ .resub = .{ .display_name = meta[0], .count = count, .tier = tier, .resub_message = trailer, .resub_message_emotes = emotes, }, }, }, }; } else { return error.UnknownUsernotice; } // } else if (std.mem.eql(u8, cmd, "PING")) { // } else if (std.mem.eql(u8, cmd, "PING")) { // } else if (std.mem.eql(u8, cmd, "PING")) { } else if (std.mem.eql(u8, cmd, "PING")) { return .ping; } else { return error.UnknownMessage; } } fn parseSubTier(data: []const u8) !Chat.Message.SubTier { if (data.len == 0) return error.MissingSubTier; return switch (data[0]) { 'P' => .prime, '1' => .t1, '2' => .t2, '3' => .t3, else => error.BadSubTier, }; } fn parseEmotes(data: []const u8, allocator: std.mem.Allocator) ![]Chat.Message.Emote { // Small hack: count the dashes to know how many emotes // are present in the text. const count = std.mem.count(u8, data, "-"); var emotes = try allocator.alloc(Chat.Message.Emote, count); errdefer allocator.free(emotes); var emote_it = std.mem.tokenize(u8, data, "/"); var i: usize = 0; while (emote_it.next()) |e| { const colon_pos = std.mem.indexOf(u8, e, ":") orelse return error.NoColon; const emote_id = e[0..colon_pos]; var pos_it = std.mem.tokenize(u8, e[colon_pos + 1 ..], ","); while (pos_it.next()) |pos| : (i += 1) { var it = std.mem.tokenize(u8, pos, "-"); const start = blk: { const str = it.next() orelse return error.NoStart; break :blk try std.fmt.parseInt(usize, str, 10); }; const end = blk: { const str = it.next() orelse return error.NoEnd; break :blk try std.fmt.parseInt(usize, str, 10); }; if (it.rest().len != 0) return error.BadEmote; // result.emote_chars += end - start; emotes[i] = Chat.Message.Emote{ .twitch_id = emote_id, .start = start, .end = end, }; } } // Sort the array by start position std.sort.sort(Chat.Message.Emote, emotes, {}, Chat.Message.Emote.lessThan); for (emotes) |em| std.log.debug("{}", .{em}); return emotes; } const Badge = struct { name: []const u8, count: usize, }; fn parseBadge(data: []const u8) !Badge { var it = std.mem.tokenize(u8, data, "/"); return Badge{ .name = it.next().?, // first call will not fail .count = try std.fmt.parseInt(usize, it.rest(), 10), }; } /// `keys` must be an array of strings fn parseMetaSubsetLinear(meta: []const u8, keys: anytype) ![keys.len][]const u8 { // Given the starting fact that the Twitch IRC spec sucks ass, // we have an interesting conundrum on our hands. // Metadata is a series of key-value pairs (keys being simple names, // values being occasionally composite) that varies from message // type to message type. There's a few different message types // that we care about and each has a different set of kv pairs. // Unfortunately, as stated above, the Twitch IRC spec does indeed // suck major ass, and so we can't rely on it blindly, which means // that we can't just try to decode a struct and expect things to // go well. // Also, while we can make some assumptions about the protocol, // Twitch is going to make changes over time as it tries to refine // its product (after years of inaction lmao) to please the // insatiable Bezosaurus Rex that roams Twith's HQ. // Finally, one extra constraint comes from me: I don't want to // decode this thing into a hashmap. I would have written bork in // Perl if I wanted to do things that way. // // So, after this inequivocably necessary introduction, here's the // plan: we assume fields are always presented in the same order // (within each message type) and expect Twitch to add new fields // over time (fields that we don't care about in this version, that is). // // We expect the caller to provide the `keys` array sorted following // the same logic and we scan the tag list lineraly expecting to // match everything as we go. If we scan the full list and discover // we didn't find all fields, we then fall-back to a "scan everything" // strategy and print a warning to the logging system. // This will make the normal case O(n) and the fallback strat O(n^2). // I could sort and accept a O(nlogn) across the whole board, plus // maybe a bit of dynamic allocation, but hey go big or go home. // // Ah I almost forgot: some fields are present only when enabled, like // `emote-only` which is present when a message contains only emotes, // but disappears when there's also non-emote content. GJ Twitch! var values: [keys.len][]const u8 = undefined; var it = std.mem.tokenize(u8, meta, ";"); // linear scan var first_miss: usize = outer: for (keys) |k, i| { while (it.next()) |kv| { var kv_it = std.mem.tokenize(u8, kv, "="); const meta_k = kv_it.next().?; // First call will always succeed const meta_v = kv_it.rest(); if (std.mem.eql(u8, k, meta_k)) { values[i] = meta_v; continue :outer; } } // If we reach here we consumed all kv pairs // and couldn't find our key. Not good! break :outer i; } else { // Success: we found all keys in one go! return values; }; // Fallback to bad search, but first complain about it. std.log.debug("Linear scan of metadata failed! Let the maintainers know that Gondor calls for aid!", .{}); // bad scan outer: for (keys[first_miss..]) |k, i| { it = std.mem.tokenize(u8, meta, ";"); // we now reset every loop while (it.next()) |kv| { var kv_it = std.mem.tokenize(u8, kv, "="); const meta_k = kv_it.next().?; // First call will always succeed const meta_v = kv_it.rest(); if (std.mem.eql(u8, k, meta_k)) { values[i] = meta_v; continue :outer; } } // The key is really missing. return error.MissingKey; } return values; }
src/network/parser.zig
const std = @import("std"); const Allocator = std.mem.Allocator; const List = std.ArrayList; const Map = std.AutoHashMap; const StrMap = std.StringHashMap; const BitSet = std.DynamicBitSet; const Str = []const u8; const util = @import("util.zig"); const gpa = util.gpa; const data = @embedFile("../data/day05.txt"); const Point = struct { x: u32, y: u32, pub fn init(x: u32, y: u32) Point { return Point{ .x = x, .y = y }; } pub fn from_str(s: Str) !Point { var iter = tokenize(u8, s, " ,"); return Point.init( try parseInt(u32, iter.next().?, 10), try parseInt(u32, iter.next().?, 10), ); } }; const Line = struct { const Self = @This(); a: Point, b: Point, pub fn init(a: Point, b: Point) Line { return Line{ .a = a, .b = b }; } pub const Iterator = struct { line: *const Self, cur: ?Point = null, started: bool = false, pub fn next(it: *Iterator) ?Point { var dest = it.line.b; if (it.cur) |cur| { var newx: u32 = cur.x; var newy: u32 = cur.y; if (cur.x != dest.x) newx = if (cur.x < dest.x) newx + 1 else newx - 1; if (cur.y != dest.y) newy = if (cur.y < dest.y) newy + 1 else newy - 1; if ((newx != cur.x) or (newy != cur.y)) { it.cur = Point.init(newx, newy); } else { it.cur = null; } } else if (!it.started) { it.cur = it.line.a; } return it.cur; } }; pub fn iterator(self: Self) Iterator { return .{ .line = &self }; } pub fn part_1_iterator(self: Self) Iterator { // ignore the line if it's not horizontal or vertical if ((self.a.x != self.b.x) and (self.a.y != self.b.y)) return .{ .line = &Line.init(self.a, self.a), .started = true }; return .{ .line = &self }; } pub fn from_str(s: Str) !Line { var coord_splitter = split(u8, s, " -> "); return Line.init( try Point.from_str(coord_splitter.next().?), try Point.from_str(coord_splitter.next().?), ); } }; const Height = u2; const FloorMap = Map(Point, Height); fn floor_raise(map: *FloorMap, pt: Point) !void { var height = map.get(pt) orelse 0; height += 1; if (height > 2) return; try map.put(pt, height); } pub fn main() !void { print("starting\n", .{}); var arena = std.heap.ArenaAllocator.init(std.heap.page_allocator); // var gpa = std.heap.GeneralPurposeAllocator(.{}){}; var allocator = &arena.allocator; var floor: FloorMap = FloorMap.init(allocator); print("reading\n", .{}); var lines = util.strtok(data, "\n"); while (lines.next()) |line_text| { var line = try Line.from_str(line_text); var iter = line.iterator(); while (iter.next()) |pt| { try floor_raise(&floor, pt); } } print("counting\n", .{}); var total: u64 = 0; var floor_counter = floor.valueIterator(); while (floor_counter.next()) |val| { if (val.* >= 2) { total += 1; } } print("part 1: {d}\n", .{total}); } // Useful stdlib functions const tokenize = std.mem.tokenize; const split = std.mem.split; const indexOf = std.mem.indexOfScalar; const indexOfAny = std.mem.indexOfAny; const indexOfStr = std.mem.indexOfPosLinear; const lastIndexOf = std.mem.lastIndexOfScalar; const lastIndexOfAny = std.mem.lastIndexOfAny; const lastIndexOfStr = std.mem.lastIndexOfLinear; const trim = std.mem.trim; const sliceMin = std.mem.min; const sliceMax = std.mem.max; const parseInt = std.fmt.parseInt; const parseFloat = std.fmt.parseFloat; const min = std.math.min; const min3 = std.math.min3; const max = std.math.max; const max3 = std.math.max3; const print = std.debug.print; const assert = std.debug.assert; const sort = std.sort.sort; const asc = std.sort.asc; const desc = std.sort.desc;
src/day05.zig
usingnamespace @import("../engine/engine.zig"); const std = @import("std"); const testing = std.testing; const mem = std.mem; pub const LiteralContext = []const u8; pub const LiteralValue = struct { /// The `input` string itself. value: []const u8, pub fn deinit(self: *const @This(), allocator: *mem.Allocator) void {} }; /// Matches the literal `input` string. /// /// The `input` string must remain alive for as long as the `Literal` parser will be used. pub fn Literal(comptime Payload: type) type { return struct { parser: Parser(Payload, LiteralValue) = Parser(Payload, LiteralValue).init(parse, nodeName, null), input: LiteralContext, const Self = @This(); pub fn init(input: LiteralContext) Self { return Self{ .input = input }; } pub fn nodeName(parser: *const Parser(Payload, LiteralValue), node_name_cache: *std.AutoHashMap(usize, ParserNodeName)) Error!u64 { const self = @fieldParentPtr(Self, "parser", parser); var v = std.hash_map.hashString("Literal"); v +%= std.hash_map.hashString(self.input); return v; } pub fn parse(parser: *const Parser(Payload, LiteralValue), in_ctx: *const Context(Payload, LiteralValue)) callconv(.Async) !void { const self = @fieldParentPtr(Self, "parser", parser); var ctx = in_ctx.with(self.input); defer ctx.results.close(); const src = ctx.src[ctx.offset..]; if (!mem.startsWith(u8, src, ctx.input)) { // TODO(slimsag): include what literal was expected try ctx.results.add(Result(LiteralValue).initError(ctx.offset + 1, "expected literal")); return; } try ctx.results.add(Result(LiteralValue).init(ctx.offset + ctx.input.len, .{ .value = self.input })); return; } }; } test "literal" { nosuspend { const allocator = testing.allocator; const Payload = void; var ctx = try Context(Payload, LiteralValue).init(allocator, "hello world", {}); defer ctx.deinit(); var want = "hello"; var l = Literal(Payload).init(want); try l.parser.parse(&ctx); var sub = ctx.subscribe(); var first = sub.next().?; defer first.deinit(ctx.allocator); try testing.expectEqual(Result(LiteralValue).init(want.len, .{ .value = "hello" }), first); try testing.expect(sub.next() == null); } }
src/combn/parser/literal.zig
const getty = @import("lib.zig"); const std = @import("std"); /// Deserializer interface. pub usingnamespace @import("de/interface/deserializer.zig"); /// Namespace for deserialization-specific types and functions. pub const de = struct { /// Generic error set for `getty.de.Visitor` implementations. pub const Error = std.mem.Allocator.Error || error{ DuplicateField, InvalidLength, InvalidType, InvalidValue, MissingField, UnknownField, UnknownVariant, Unsupported, }; /// Map access and deserialization interface. pub usingnamespace @import("de/interface/map.zig"); /// Deserialization seed interface. pub usingnamespace @import("de/interface/seed.zig"); /// Sequence access and deserialization interface. pub usingnamespace @import("de/interface/seq.zig"); /// Visitor interface. pub usingnamespace @import("de/interface/visitor.zig"); /// Default deserialization seed implementation. pub usingnamespace @import("de/impl/seed/default.zig"); /// Frees resources allocated during Getty deserialization. pub fn free(allocator: std.mem.Allocator, value: anytype) void { const T = @TypeOf(value); const name = @typeName(T); switch (@typeInfo(T)) { .Bool, .Float, .ComptimeFloat, .Int, .ComptimeInt, .Enum, .EnumLiteral, .Null, .Void => {}, .Array => for (value) |v| free(allocator, v), .Optional => if (value) |v| free(allocator, v), .Pointer => |info| switch (comptime std.meta.trait.isZigString(T)) { true => allocator.free(value), false => switch (info.size) { .One => { free(allocator, value.*); allocator.destroy(value); }, .Slice => { for (value) |v| free(allocator, v); allocator.free(value); }, else => unreachable, }, }, .Union => |info| { if (info.tag_type) |Tag| { inline for (info.fields) |field| { if (value == @field(Tag, field.name)) { free(allocator, @field(value, field.name)); break; } } } else unreachable; }, .Struct => |info| { if (comptime std.mem.startsWith(u8, name, "std.array_list.ArrayListAlignedUnmanaged")) { for (value.items) |v| free(allocator, v); var mut = value; mut.deinit(allocator); } else if (comptime std.mem.startsWith(u8, name, "std.array_list.ArrayList")) { for (value.items) |v| free(allocator, v); value.deinit(); } else if (comptime std.mem.startsWith(u8, name, "std.hash_map.HashMapUnmanaged")) { var iterator = value.iterator(); while (iterator.next()) |entry| { free(allocator, entry.key_ptr.*); free(allocator, entry.value_ptr.*); } var mut = value; mut.deinit(allocator); } else if (comptime std.mem.startsWith(u8, name, "std.hash_map.HashMap")) { var iterator = value.iterator(); while (iterator.next()) |entry| { free(allocator, entry.key_ptr.*); free(allocator, entry.value_ptr.*); } var mut = value; mut.deinit(); } else if (comptime std.mem.startsWith(u8, name, "std.linked_list")) { var iterator = value.first; while (iterator) |node| { free(allocator, node.data); iterator = node.next; allocator.destroy(node); } } else { inline for (info.fields) |field| { if (!field.is_comptime) free(allocator, @field(value, field.name)); } } }, else => unreachable, } } /// Returns the highest priority Deserialization Block for a type given a /// deserializer type. pub fn find_db(comptime Deserializer: type, comptime T: type) type { comptime { getty.concepts.@"getty.Deserializer"(Deserializer); inline for (Deserializer.dt) |db| { if (db.is(T)) { return db; } } @compileError("type ` " ++ @typeName(T) ++ "` is not supported"); } } }; /// The default Deserialization Tuple. /// /// If a user or deserializer DT is provided, the default DT is appended to the /// end, thereby taking the lowest priority. pub const default_dt = .{ // std @import("de/with/array_list.zig"), @import("de/with/hash_map.zig"), @import("de/with/linked_list.zig"), @import("de/with/tail_queue.zig"), // primitives @import("de/with/array.zig"), @import("de/with/bool.zig"), @import("de/with/enum.zig"), @import("de/with/float.zig"), @import("de/with/int.zig"), @import("de/with/optional.zig"), @import("de/with/pointer.zig"), @import("de/with/slice.zig"), @import("de/with/struct.zig"), @import("de/with/tuple.zig"), @import("de/with/void.zig"), }; /// Deserializes a value from the given Getty deserializer. pub fn deserialize(allocator: ?std.mem.Allocator, comptime T: type, deserializer: anytype) blk: { const D = @TypeOf(deserializer); getty.concepts.@"getty.Deserializer"(D); break :blk D.Error!T; } { const db = de.find_db(@TypeOf(deserializer), T); var v = db.Visitor(T){}; return try _deserialize(allocator, T, deserializer, v.visitor()); } fn _deserialize(allocator: ?std.mem.Allocator, comptime T: type, deserializer: anytype, visitor: anytype) blk: { const D = @TypeOf(deserializer); const V = @TypeOf(visitor); getty.concepts.@"getty.Deserializer"(D); getty.concepts.@"getty.de.Visitor"(V); break :blk D.Error!V.Value; } { const db = de.find_db(@TypeOf(deserializer), T); return try db.deserialize(allocator, T, deserializer, visitor); }
src/de.zig
const ROM_DRIVER_TABLE_PTR_ADDR = 0x1FFF1FF8; const USART0_BASE_ADDR = 0x40064000; const USART1_BASE_ADDR = 0x40068000; const USART2_BASE_ADDR = 0x4006C000; const SYSAHBCLKCTRL_ADDR = 0x40048080; const PINASSIGN0_ADDR = 0x4000C000; pub const UartPort = enum { USART0, USART1, USART2, }; const UartConfig = extern struct { sys_clk_in_hz: u32, baudrate_in_hz: u32, config: u8, sync_mod: u8, error_en: u16, }; const UartParam = extern struct { buffer: [*]const u8, size: u32, transfer_mode: u16, driver_mode: u16, callback_func_pt: stdcallcc fn (err_code: u32, n: u32) void, }; const UartParamMutableBuffer = extern struct { buffer: [*]u8, size: u32, transfer_mode: u16, driver_mode: u16, callback_func_pt: stdcallcc fn (err_code: u32, n: u32) void, }; const UartDriverRoutines = extern struct { uart_get_mem_size: stdcallcc fn () u32, uart_setup: stdcallcc fn (base_addr: u32, ram: *[40]u8) *c_void, uart_init: stdcallcc fn (handle: *c_void, set: UartConfig) u32, uart_get_char: stdcallcc fn (handle: *c_void) u8, uart_put_char: stdcallcc fn (handle: *c_void, data: u8) void, uart_get_line: stdcallcc fn (handle: *c_void, param: UartParamMutableBuffer) u32, uart_put_line: stdcallcc fn (handle: *c_void, param: UartParam) u32, uart_isr: stdcallcc fn (handle: *c_void) void, }; const Uart = struct { // Assume required memory size is 40 bytes peripheral_ram: [40]u8, routine_table: *UartDriverRoutines, pub fn init_port(self: *Uart, port: UartPort) *c_void { return switch(port) { UartPort.USART0 => self.routine_table.uart_setup(USART0_BASE_ADDR, &(self.*.peripheral_ram)), UartPort.USART1 => self.routine_table.uart_setup(USART1_BASE_ADDR, &(self.*.peripheral_ram)), UartPort.USART2 => self.routine_table.uart_setup(USART2_BASE_ADDR, &(self.*.peripheral_ram)), }; } pub fn configure_port(self: Uart, port_handle: *c_void, baud_rate: u32) u32 { return self.routine_table.uart_init(port_handle, UartConfig { .sys_clk_in_hz = 12000000, .baudrate_in_hz = baud_rate, .config = 0b00000001, .sync_mod = 0b00000000, .error_en = 0x0000, }); } pub fn put_char(self: Uart, port_handle: *c_void, data: u8) void { self.routine_table.uart_put_char(port_handle, data); } pub fn println(self: Uart, port_handle: *c_void, data: [*]const u8, bufsize: u32) void { _ = self.routine_table.uart_put_line(port_handle, UartParam { .buffer = data, .size = bufsize, .transfer_mode = 0x0002, .driver_mode = 0x0000, .callback_func_pt = undefined, }); } pub fn gets(self: Uart, port_handle: *c_void, buf: [*]u8, bufsize: u32) void { _ = self.routine_table.uart_get_line(port_handle, UartParamMutableBuffer { .buffer = buf, .size = bufsize, .transfer_mode = 0x0002, .driver_mode = 0x0000, .callback_func_pt = undefined, }); } }; pub fn init_uart() Uart { // Source the clock to *all* the USART blocks const clk_ctl_ptr = @intToPtr(*volatile u32, SYSAHBCLKCTRL_ADDR); clk_ctl_ptr.* |= 0x0001C000; // Set the pin assignments const pin_assign0_ptr = @intToPtr(*volatile u32, PINASSIGN0_ADDR); pin_assign0_ptr.* = 0xFFFF0004; // CTS=none, RTS=none, RXD=P0_0, TXD=P0_4 const driver_table_addr = @intToPtr(*u32, ROM_DRIVER_TABLE_PTR_ADDR).*; const uart_driver_table_addr = @intToPtr(*u32, driver_table_addr + 0x24).*; const res = Uart { .peripheral_ram = [_]u8{0} ** 40, .routine_table = @intToPtr(*UartDriverRoutines, uart_driver_table_addr), }; return res; }
src/hal/uart.zig
const std = @import("std"); const util = @import("util.zig"); const time = std.time; const testing = std.testing; // Default would be read as 1970-01-01T00:00:00Z days: i64 = 0, hours: i64 = 0, minutes: i64 = 0, seconds: i64 = 0, const Self = @This(); const leap_year_months = [_]i64{31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31}; const normal_year_months = [_]i64{31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31}; pub const Timezone = struct { offset: Self, daylight: bool, pub const utc = Self { .hours = 0, }; pub const cst = Self { .hours = -6, }; }; pub const DateWithTimezone = struct { date: Self, // assumed to be UTC-0 timezone: Timezone, pub fn flatten(self: DateWithTimezone) Self { return self.dateWithTimezone().flatten(); } pub fn dateWithTimezone(self: DateWithTimezone) Self { if (self.timezone.daylight) { return self.date.add(self.timezone.offset).add(Self {.hours = 1}); } else { return self.date.add(self.timezone.offset); } } }; pub const Month = enum { january, february, march, april, may, june, july, august, september, october, november, december, }; pub const DayOfWeek = enum { monday, tuesday, wednesday, thursday, friday, saturday, sunday, }; pub fn nameToMonth(name: []const u8) DateError!?Month { const names_full = comptime util.enumFieldNames(Month); if (name.len < 3) return DateError.AmbiguousAbbr; inline for (names_full) |month_name, index| { if (std.mem.startsWith(u8, month_name, name)) { return @intToEnum(Month, @intCast(u4, index)); } } return null; } pub fn nameToDayOfWeek(name: []const u8) DateError!?DayOfWeek { const names_full = comptime util.enumFieldNames(DayOfWeek); if (name.len == 1 and (name[0] == 's' or name[1] == 't')) { return DateError.AmbiguousAbbr; } inline for (names_full) |day_name, index| { if (std.mem.startsWith(u8, day_name, name)) { return @intToEnum(DayOfWeek, @intCast(u4, index)); } } return null; } pub const DateError = error { AmbiguousAbbr, InvalidDate, }; /// m = 0 = January /// d = 0 = 1st pub fn init(y: u32, m: u32, d: u32) DateError!Self { if (m > 11) { return DateError.InvalidDate; } const months = if (isLeapYear(y)) leap_year_months else normal_year_months; if (d >= months[m]) { return DateError.InvalidDate; } const days = @floatToInt(i64, @ceil(365.24 * @intToFloat(f64, (y - 1970)))) + if (m == 0) d else d + sum(months[0..m]); return Self { .days = days, }; } /// Get the current date pub fn now() Self { return epochToDate(time.timestamp()); } /// Convert epoch to date pub fn epochToDate(unix_time: i64) Self { const seconds_since_epoch: f64 = @intToFloat(f64, unix_time); const seconds_since_last_day = @rem(seconds_since_epoch, time.s_per_day); const minutes_since_last_day = seconds_since_last_day / 60; const hours_since_last_day = minutes_since_last_day / 60; const days_since_epoch = @floatToInt(i64, seconds_since_epoch / time.s_per_day); const hours = @floatToInt(i64, hours_since_last_day); const minutes = @floatToInt(i64, minutes_since_last_day) - hours * 60; const seconds = @floatToInt(i64, seconds_since_last_day) - hours * 3600 - minutes * 60; return Self { .days = days_since_epoch, .hours = hours, .minutes = minutes, .seconds = seconds, }; } /// Return the same time but without hours, minutes, or seconds /// Assumes the date is normalized pub fn flatten(self: Self) Self { return Self { .days = self.days, .hours = 0, .minutes = 0, .seconds = 0, }; } /// Convert date to epoch time pub fn dateToEpoch(self: Self) i64 { const days = @intCast(i64, self.days); const hours = @intCast(i64, self.hours); const minutes = @intCast(i64, self.minutes); const seconds = @intCast(i64, self.seconds); return days * time.s_per_day + hours * time.s_per_hour + minutes * time.s_per_min + seconds; } /// If it's divisible by 4, then it's a leap year /// Unless it's divisible by 100 /// Unless it's divisible by 400 pub fn isLeapYear(y: i64) bool { if (@rem(y, 4) == 0) { if (@rem(y, 100) == 0) { return @rem(y, 400) == 0; } return true; } return false; } /// Checks if the date falls under a leap year pub fn isLeap(self: Self) bool { return isLeapYear(self.year()); } /// Returns a slice of all the days in each month pub fn yearMonths(self: Self) []const i64 { return if (self.isLeap()) leap_year_months[0..] else normal_year_months[0..]; } /// Assumes normalized date // 0 is january 1st pub fn dayOfYear(self: Self) i64 { const result = self.days - self.dayToLastYear(); return result; } fn dayToLastYear(self: Self) i64 { return @floatToInt(i64, @ceil(@intToFloat(f64, self.year() - 1970) * 365.24)); } /// Get the year /// 0 is 1 BC /// Assumes normalized date pub fn year(self: Self) u32 { return @floatToInt(u32, @divTrunc(@intToFloat(f64, self.days), 365.24)) + 1970; } /// Assumes normalized date // 0 is january pub fn month(self: Self) usize { const months = self.yearMonths(); const m = indexBeforeSumExceedsValue(self.dayOfYear(), months); return @intCast(usize, m); } /// Assumes normalized date /// Returns 0 if it's January 1st pub fn day(self: Self) i64 { const index = self.month(); return self.days - sum(self.yearMonths()[0..index]) - self.dayToLastYear(); } /// Assumes normalized date pub fn dayOfWeek(self: Self) DayOfWeek { // Epoch time is on a Thursday morning! // (I used this: https://www.timeanddate.com/date/weekday.html) return @intToEnum(DayOfWeek, @intCast(u3, @rem(3 + self.days, 7))); } /// Returns the name of the month pub fn monthName(self: Self) []const u8 { return @tagName(@intToEnum(Month, @intCast(u4, self.month()))); } /// Obviously not for adding dates. /// Rather, it's to add a duration to date. /// Example: add an hour for one hour later /// or add 7 days for a week later pub fn add(self: Self, other: Self) Self { const result = Self { .days = self.days + other.days, .hours = self.hours + other.hours, .minutes = self.minutes + other.minutes, .seconds = self.seconds + other.seconds, }; return result.normalize(); } /// If a date is NOT in UTC, convert it by specifying the timezone which represents the date pub fn toUtc(self: Self, timezone: Timezone) Self { return (Self { .days = self.days - timezone.offset.days, .hours = self.hours - timezone.offset.hours - (if (timezone.daylight) @as(i64, 1) else @as(i64, 0)), .minutes = self.minutes - timezone.offset.minutes, .seconds = self.seconds - timezone.offset.seconds, }).normalize(); } /// Normalizes a date, so that all values are within their range pub fn normalize(self: Self) Self { var days = self.days; var hours = self.hours; var minutes = self.minutes; var seconds = self.seconds; if (seconds > 59 or seconds < 0) { minutes += @divFloor(seconds, 60); seconds = @rem(seconds, 60); if (seconds < 0) seconds = 60 + seconds; } if (minutes > 59 or minutes < 0) { hours += @divFloor(minutes, 60); minutes = @rem(minutes, 60); if (minutes < 0) minutes = 60 + minutes; } if (hours > 23 or hours < 0) { days += @divFloor(hours, 24); hours = @rem(hours, 24); if (hours < 0) hours = 24 + hours; } return Self { .days = days, .hours = hours, .minutes = minutes, .seconds = seconds, }; } /// If result > 0, then self > other, aka later /// if result == 0, then self == other, aka same /// else, result < other, aka sooner pub fn compare(self: Self, other: Self) i64 { return self.dateToEpoch() - other.dateToEpoch(); } pub fn format( self: Self, comptime fmt: []const u8, options: std.fmt.FormatOptions, writer: anytype ) !void { try writer.print("{s}: {s} {d}, {d}", .{@tagName(self.dayOfWeek()), self.monthName(), self.day() + 1, self.year()}); } fn indexBeforeSumExceedsValue(val: i64, list: []const i64) usize { var s: i64 = 0; for (list) |v, i| { s += v; if (s > val) { return i; } } return list.len - 1; } fn sum(list: []const i64) i64 { var s: i64 = 0; for (list) |val, i| { s += val; } return s; } test "date.monthName" { const date = Self { .days = 18725, .hours = 13, .minutes = 44, .seconds = 08, }; testing.expectEqualSlices(u8, "april", date.monthName()); } test "date.nameToMonth" { const name = "sept"; testing.expectEqual(Month.september, (try nameToMonth(name)).?); } test "date.init" { { const date = try init(1970, 0, 0); const expected = Self {}; testing.expectEqual(expected, date); testing.expectEqual(DayOfWeek.thursday, date.dayOfWeek()); testing.expectEqual(@as(i64, 0), date.day()); } { const date = try init(1970, 1, 1); const expected = Self { .days = 31 + 1 }; testing.expectEqual(expected, date); testing.expectEqual(DayOfWeek.monday, date.dayOfWeek()); testing.expectEqual(@as(i64, 1), date.day()); } { testing.expectError(DateError.InvalidDate, init(1970, 12, 2)); // testing.expectError(DateError.InvalidDate, init(1970, -1, 2)); testing.expectError(DateError.InvalidDate, init(1970, 1, 31)); // testing.expectError(DateError.InvalidDate, init(1970, 1, -1)); } } test "date.Sum" { const list = [_]i64{1, 2, 3, 4, 5}; const wow = sum(list[0..1]); testing.expectEqual(wow, 1); } test "date.Index before sum exceeds value" { const list = [_]i64{1, 2, 3, 4, 5}; testing.expectEqual(@as(usize, 1), indexBeforeSumExceedsValue(2, list[0..])); } test "date.Epoch To Date" { { const epoch: i64 = 1617889448; const date = epochToDate(epoch); const expectedDate = Self { .days = 18725, .hours = 13, .minutes = 44, .seconds = 08, }; testing.expectEqual(expectedDate, date); testing.expectEqual(@as(usize, 3), date.month()); testing.expectEqual(@as(i64, 7), date.day()); } { const epoch: i64 = 1621595250; const date = epochToDate(epoch); testing.expectEqual(@as(i64, 2021), date.year()); testing.expectEqual(@as(usize, 4), date.month()); testing.expectEqual(@as(i64, 20), date.day()); } } test "date.Normalize" { { const date = Self { .days = 18725, .hours = 25, }; const normalized = date.normalize(); const expected_date = Self { .days = 18725 + 1, .hours = 1, }; testing.expectEqual(expected_date, normalized); } { const date = Self { .days = 18725, .hours = -1, }; const normalized = date.normalize(); const expected_date = Self { .days = 18725 - 1, .hours = 23, }; testing.expectEqual(expected_date, normalized); } } test "date.Date to epoch" { const date = Self { .days = 18725, .hours = 13, .minutes = 44, .seconds = 08, }; const expectedEpoch: i64 = 1617889448; testing.expectEqual(expectedEpoch, date.dateToEpoch()); } test "date.Adding date" { const date = Self { .days = 18725, .hours = 13, .minutes = 44, .seconds = 08, }; const duration = Self { .days = 6, .hours = 25, }; const result = date.add(duration); const expected = Self { .days = 18725 + 7, .hours = 13 + 1, .minutes = 44, .seconds = 08, }; testing.expectEqual(expected, result); } test "date.Get year, month, and day" { { const date = Self { .days = 18767, .hours = 13, .minutes = 44, .seconds = 08, }; testing.expectEqual(@as(i64, 2021), date.year()); testing.expectEqual(@as(usize, 4), date.month()); testing.expectEqual(@as(i64, 19), date.day()); testing.expectEqual(Month.may, @intToEnum(Month, @intCast(u4, date.month()))); } } test "date.Timezones" { const date = DateWithTimezone { .date = (try Self.init(2021, 04, 20)).add(Self {.hours = 3}), .timezone = Timezone { .offset = Timezone.cst, .daylight = true, }, }; const expected_date = (try Self.init(2021, 04, 19)).add(Self {.hours = 22}); testing.expectEqual(expected_date, date.dateWithTimezone()); testing.expectEqual(@as(i64, 2021), date.flatten().year()); testing.expectEqual(@as(usize, 4), date.flatten().month()); testing.expectEqual(@as(i64, 19), date.flatten().day()); }
src/date.zig
const std = @import("std"); const c = @cImport(@cInclude("blake3.h")); const fmt = std.fmt; const mem = std.mem; const testing = std.testing; pub fn addTo(step: *std.build.LibExeObjStep, comptime dir: []const u8) void { step.linkLibC(); step.addIncludeDir(dir ++ "/lib/c"); var defines: std.ArrayListUnmanaged([]const u8) = .{}; defer defines.deinit(step.builder.allocator); if (std.Target.x86.featureSetHas(step.target.getCpuFeatures(), .sse2)) { step.addAssemblyFile(dir ++ "/lib/c/blake3_sse2_x86-64_unix.S"); } else { defines.append(step.builder.allocator, "-DBLAKE3_NO_SSE2") catch unreachable; } if (std.Target.x86.featureSetHas(step.target.getCpuFeatures(), .sse4_1)) { step.addAssemblyFile(dir ++ "/lib/c/blake3_sse41_x86-64_unix.S"); } else { defines.append(step.builder.allocator, "-DBLAKE3_NO_SSE41") catch unreachable; } if (std.Target.x86.featureSetHas(step.target.getCpuFeatures(), .avx2)) { step.addAssemblyFile(dir ++ "/lib/c/blake3_avx2_x86-64_unix.S"); } else { defines.append(step.builder.allocator, "-DBLAKE3_NO_AVX2") catch unreachable; } if (std.Target.x86.featureSetHasAll(step.target.getCpuFeatures(), .{ .avx512f, .avx512vl })) { step.addAssemblyFile(dir ++ "/lib/c/blake3_avx512_x86-64_unix.S"); } else { defines.append(step.builder.allocator, "-DBLAKE3_NO_AVX512") catch unreachable; } step.addCSourceFile(dir ++ "/lib/c/blake3.c", defines.items); step.addCSourceFile(dir ++ "/lib/c/blake3_dispatch.c", defines.items); step.addCSourceFile(dir ++ "/lib/c/blake3_portable.c", defines.items); } pub const Hasher = struct { state: c.blake3_hasher = undefined, pub fn init() callconv(.Inline) Hasher { var state: c.blake3_hasher = undefined; c.blake3_hasher_init(&state); return Hasher{ .state = state }; } pub fn update(self: *Hasher, buf: []const u8) callconv(.Inline) void { c.blake3_hasher_update(&self.state, buf.ptr, buf.len); } pub fn final(self: *Hasher, dst: []u8) callconv(.Inline) void { c.blake3_hasher_finalize(&self.state, dst.ptr, dst.len); } }; pub fn hash(buf: []const u8) callconv(.Inline) [32]u8 { var hasher = Hasher.init(); hasher.update(buf); var dst: [32]u8 = undefined; hasher.final(&dst); return dst; } test "blake3: hash 'hello world" { try testing.expectFmt("d74981efa70a0c880b8d8c1985d075dbcbf679b99a5f9914e5aaf96b831a9e24", "{s}", .{fmt.fmtSliceHexLower(&hash("hello world"))}); }
blake3/blake3.zig
const Allocator = std.mem.Allocator; const FormatInterface = @import("../format_interface.zig").FormatInterface; const ImageFormat = image.ImageFormat; const ImageReader = image.ImageReader; const ImageInfo = image.ImageInfo; const ImageSeekStream = image.ImageSeekStream; const PixelFormat = @import("../pixel_format.zig").PixelFormat; const color = @import("../color.zig"); const errors = @import("../errors.zig"); const fs = std.fs; const image = @import("../image.zig"); const io = std.io; const mem = std.mem; const path = std.fs.path; const std = @import("std"); const utils = @import("../utils.zig"); pub const QoiColor = extern struct { r: u8, g: u8, b: u8, a: u8 = 0xFF, fn hash(c: QoiColor) u6 { return @truncate(u6, c.r *% 3 +% c.g *% 5 +% c.b *% 7 +% c.a *% 11); } pub fn eql(a: QoiColor, b: QoiColor) bool { return std.meta.eql(a, b); } pub fn toRgb24(self: QoiColor) color.Rgb24 { return color.Rgb24{ .R = self.r, .G = self.g, .B = self.b, }; } pub fn toRgba32(self: QoiColor) color.Rgba32 { return color.Rgba32{ .R = self.r, .G = self.g, .B = self.b, .A = self.a, }; } pub fn from(pixel: anytype) QoiColor { if (@TypeOf(pixel) == color.Rgb24) { return QoiColor{ .r = pixel.R, .g = pixel.G, .b = pixel.B, }; } else if (@TypeOf(pixel) == color.Rgba32) { return QoiColor{ .r = pixel.R, .g = pixel.G, .b = pixel.B, .a = pixel.A, }; } else { unreachable; } } }; pub const Colorspace = enum(u8) { /// sRGB color, linear alpha sRGB = 0, /// Every channel is linear linear = 1, }; pub const Format = enum(u8) { rgb = 3, rgba = 4, }; pub const Header = packed struct { const size = 14; const correct_magic = [4]u8{ 'q', 'o', 'i', 'f' }; width: u32, height: u32, format: Format, colorspace: Colorspace, fn encode(header: Header) [size]u8 { var result: [size]u8 = undefined; std.mem.copy(u8, result[0..4], &correct_magic); std.mem.writeIntBig(u32, result[4..8], header.width); std.mem.writeIntBig(u32, result[8..12], header.height); result[12] = @enumToInt(header.format); result[13] = @enumToInt(header.colorspace); return result; } }; pub const QOI = struct { header: Header = undefined, pub const EncoderOptions = struct { colorspace: Colorspace, }; const Self = @This(); pub fn formatInterface() FormatInterface { return FormatInterface{ .format = @ptrCast(FormatInterface.FormatFn, format), .formatDetect = @ptrCast(FormatInterface.FormatDetectFn, formatDetect), .readForImage = @ptrCast(FormatInterface.ReadForImageFn, readForImage), .writeForImage = @ptrCast(FormatInterface.WriteForImageFn, writeForImage), }; } pub fn format() ImageFormat { return ImageFormat.Qoi; } pub fn formatDetect(reader: ImageReader, seek_stream: ImageSeekStream) !bool { _ = seek_stream; var magic_buffer: [std.mem.len(Header.correct_magic)]u8 = undefined; _ = try reader.read(magic_buffer[0..]); return std.mem.eql(u8, magic_buffer[0..], Header.correct_magic[0..]); } pub fn readForImage(allocator: Allocator, reader: ImageReader, seek_stream: ImageSeekStream, pixels: *?color.ColorStorage) !ImageInfo { var qoi = Self{}; try qoi.read(allocator, reader, seek_stream, pixels); var image_info = ImageInfo{}; image_info.width = qoi.width(); image_info.height = qoi.height(); return image_info; } pub fn writeForImage(allocator: Allocator, write_stream: image.ImageWriterStream, seek_stream: ImageSeekStream, pixels: color.ColorStorage, save_info: image.ImageSaveInfo) !void { _ = allocator; var qoi = Self{}; qoi.header.width = @truncate(u32, save_info.width); qoi.header.height = @truncate(u32, save_info.height); qoi.header.format = switch (pixels) { .Rgb24 => Format.rgb, .Rgba32 => Format.rgba, else => return errors.ImageError.UnsupportedPixelFormat, }; switch (save_info.encoder_options) { .qoi => |qoi_encode_options| { qoi.header.colorspace = qoi_encode_options.colorspace; }, else => { qoi.header.colorspace = .sRGB; }, } try qoi.write(write_stream, seek_stream, pixels); } pub fn width(self: Self) usize { return self.header.width; } pub fn height(self: Self) usize { return self.header.height; } pub fn pixelFormat(self: Self) !PixelFormat { return switch (self.header.format) { .rgb => PixelFormat.Rgb24, .rgba => PixelFormat.Rgba32, }; } pub fn read(self: *Self, allocator: Allocator, reader: ImageReader, seek_stream: ImageSeekStream, pixels_opt: *?color.ColorStorage) !void { _ = seek_stream; var magic_buffer: [std.mem.len(Header.correct_magic)]u8 = undefined; _ = try reader.read(magic_buffer[0..]); if (!std.mem.eql(u8, magic_buffer[0..], Header.correct_magic[0..])) { return errors.ImageError.InvalidMagicHeader; } self.header = try utils.readStructBig(reader, Header); const pixel_format = try self.pixelFormat(); pixels_opt.* = try color.ColorStorage.init(allocator, pixel_format, self.width() * self.height()); var current_color = QoiColor{ .r = 0, .g = 0, .b = 0, .a = 0xFF }; var color_lut = std.mem.zeroes([64]QoiColor); var index: usize = 0; const pixels_size: usize = @as(usize, self.header.width) * @as(usize, self.header.height); while (index < pixels_size) { var byte = try reader.readByte(); var new_color = current_color; var count: usize = 1; if (byte == 0b11111110) { // QOI_OP_RGB new_color.r = try reader.readByte(); new_color.g = try reader.readByte(); new_color.b = try reader.readByte(); } else if (byte == 0b11111111) { // QOI_OP_RGBA new_color.r = try reader.readByte(); new_color.g = try reader.readByte(); new_color.b = try reader.readByte(); new_color.a = try reader.readByte(); } else if (hasPrefix(byte, u2, 0b00)) { // QOI_OP_INDEX const color_index = @truncate(u6, byte); new_color = color_lut[color_index]; } else if (hasPrefix(byte, u2, 0b01)) { // QOI_OP_DIFF const diff_r = unmapRange2(byte >> 4); const diff_g = unmapRange2(byte >> 2); const diff_b = unmapRange2(byte >> 0); add8(&new_color.r, diff_r); add8(&new_color.g, diff_g); add8(&new_color.b, diff_b); } else if (hasPrefix(byte, u2, 0b10)) { // QOI_OP_LUMA const diff_g = unmapRange6(byte); const diff_rg_rb = try reader.readByte(); const diff_rg = unmapRange4(diff_rg_rb >> 4); const diff_rb = unmapRange4(diff_rg_rb >> 0); const diff_r = @as(i8, diff_g) + diff_rg; const diff_b = @as(i8, diff_g) + diff_rb; add8(&new_color.r, diff_r); add8(&new_color.g, diff_g); add8(&new_color.b, diff_b); } else if (hasPrefix(byte, u2, 0b11)) { // QOI_OP_RUN count = @as(usize, @truncate(u6, byte)) + 1; std.debug.assert(count >= 1 and count <= 62); } else { // we have covered all possibilities. unreachable; } // this will happen when a file has an invalid run length // and we would decode more pixels than there are in the image. if (index + count > pixels_size) { return error.InvalidData; } while (count > 0) { count -= 1; switch (pixels_opt.*.?) { .Rgb24 => |data| { data[index] = new_color.toRgb24(); }, .Rgba32 => |data| { data[index] = new_color.toRgba32(); }, else => {}, } index += 1; } color_lut[new_color.hash()] = new_color; current_color = new_color; } } pub fn write(self: Self, write_stream: image.ImageWriterStream, seek_stream: ImageSeekStream, pixels: color.ColorStorage) !void { _ = seek_stream; try write_stream.writeAll(&self.header.encode()); switch (pixels) { .Rgb24 => |data| { try writeData(write_stream, data); }, .Rgba32 => |data| { try writeData(write_stream, data); }, else => { return errors.ImageError.UnsupportedPixelFormat; }, } try write_stream.writeAll(&[8]u8{ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, }); } fn writeData(write_stream: image.ImageWriterStream, pixels_data: anytype) !void { var color_lut = std.mem.zeroes([64]QoiColor); var previous_pixel = QoiColor{ .r = 0, .g = 0, .b = 0, .a = 0xFF }; var run_length: usize = 0; for (pixels_data) |current_color, i| { const pixel = QoiColor.from(current_color); defer previous_pixel = pixel; const same_pixel = pixel.eql(previous_pixel); if (same_pixel) { run_length += 1; } if (run_length > 0 and (run_length == 62 or !same_pixel or (i == (pixels_data.len - 1)))) { // QOI_OP_RUN std.debug.assert(run_length >= 1 and run_length <= 62); try write_stream.writeByte(0b1100_0000 | @truncate(u8, run_length - 1)); run_length = 0; } if (!same_pixel) { const hash = pixel.hash(); if (color_lut[hash].eql(pixel)) { // QOI_OP_INDEX try write_stream.writeByte(0b0000_0000 | hash); } else { color_lut[hash] = pixel; const diff_r = @as(i16, pixel.r) - @as(i16, previous_pixel.r); const diff_g = @as(i16, pixel.g) - @as(i16, previous_pixel.g); const diff_b = @as(i16, pixel.b) - @as(i16, previous_pixel.b); const diff_a = @as(i16, pixel.a) - @as(i16, previous_pixel.a); const diff_rg = diff_r - diff_g; const diff_rb = diff_b - diff_g; if (diff_a == 0 and inRange2(diff_r) and inRange2(diff_g) and inRange2(diff_b)) { // QOI_OP_DIFF const byte = 0b0100_0000 | (mapRange2(diff_r) << 4) | (mapRange2(diff_g) << 2) | (mapRange2(diff_b) << 0); try write_stream.writeByte(byte); } else if (diff_a == 0 and inRange6(diff_g) and inRange4(diff_rg) and inRange4(diff_rb)) { // QOI_OP_LUMA try write_stream.writeAll(&[2]u8{ 0b1000_0000 | mapRange6(diff_g), (mapRange4(diff_rg) << 4) | (mapRange4(diff_rb) << 0), }); } else if (diff_a == 0) { // QOI_OP_RGB try write_stream.writeAll(&[4]u8{ 0b1111_1110, pixel.r, pixel.g, pixel.b, }); } else { // QOI_OP_RGBA try write_stream.writeAll(&[5]u8{ 0b1111_1111, pixel.r, pixel.g, pixel.b, pixel.a, }); } } } } } fn mapRange2(val: i16) u8 { return @intCast(u2, val + 2); } fn mapRange4(val: i16) u8 { return @intCast(u4, val + 8); } fn mapRange6(val: i16) u8 { return @intCast(u6, val + 32); } fn unmapRange2(val: u32) i2 { return @intCast(i2, @as(i8, @truncate(u2, val)) - 2); } fn unmapRange4(val: u32) i4 { return @intCast(i4, @as(i8, @truncate(u4, val)) - 8); } fn unmapRange6(val: u32) i6 { return @intCast(i6, @as(i8, @truncate(u6, val)) - 32); } fn inRange2(val: i16) bool { return (val >= -2) and (val <= 1); } fn inRange4(val: i16) bool { return (val >= -8) and (val <= 7); } fn inRange6(val: i16) bool { return (val >= -32) and (val <= 31); } fn add8(dst: *u8, diff: i8) void { dst.* +%= @bitCast(u8, diff); } fn hasPrefix(value: u8, comptime T: type, prefix: T) bool { return (@truncate(T, value >> (8 - @bitSizeOf(T))) == prefix); } };
src/formats/qoi.zig
pub const mach_header = extern struct { magic: u32, cputype: cpu_type_t, cpusubtype: cpu_subtype_t, filetype: u32, ncmds: u32, sizeofcmds: u32, flags: u32, }; pub const mach_header_64 = extern struct { magic: u32, cputype: cpu_type_t, cpusubtype: cpu_subtype_t, filetype: u32, ncmds: u32, sizeofcmds: u32, flags: u32, reserved: u32, }; pub const load_command = extern struct { cmd: u32, cmdsize: u32, }; /// The uuid load command contains a single 128-bit unique random number that /// identifies an object produced by the static link editor. pub const uuid_command = extern struct { /// LC_UUID cmd: u32, /// sizeof(struct uuid_command) cmdsize: u32, /// the 128-bit uuid uuid: [16]u8, }; /// The version_min_command contains the min OS version on which this /// binary was built to run. pub const version_min_command = extern struct { /// LC_VERSION_MIN_MACOSX or LC_VERSION_MIN_IPHONEOS or LC_VERSION_MIN_WATCHOS or LC_VERSION_MIN_TVOS cmd: u32, /// sizeof(struct version_min_command) cmdsize: u32, /// X.Y.Z is encoded in nibbles xxxx.yy.zz version: u32, /// X.Y.Z is encoded in nibbles xxxx.yy.zz sdk: u32, }; /// The source_version_command is an optional load command containing /// the version of the sources used to build the binary. pub const source_version_command = extern struct { /// LC_SOURCE_VERSION cmd: u32, /// sizeof(source_version_command) cmdsize: u32, /// A.B.C.D.E packed as a24.b10.c10.d10.e10 version: u64, }; /// The entry_point_command is a replacement for thread_command. /// It is used for main executables to specify the location (file offset) /// of main(). If -stack_size was used at link time, the stacksize /// field will contain the stack size needed for the main thread. pub const entry_point_command = extern struct { /// LC_MAIN only used in MH_EXECUTE filetypes cmd: u32, /// sizeof(struct entry_point_command) cmdsize: u32, /// file (__TEXT) offset of main() entryoff: u64, /// if not zero, initial stack size stacksize: u64, }; /// The symtab_command contains the offsets and sizes of the link-edit 4.3BSD /// "stab" style symbol table information as described in the header files /// <nlist.h> and <stab.h>. pub const symtab_command = extern struct { /// LC_SYMTAB cmd: u32, /// sizeof(struct symtab_command) cmdsize: u32, /// symbol table offset symoff: u32, /// number of symbol table entries nsyms: u32, /// string table offset stroff: u32, /// string table size in bytes strsize: u32, }; /// This is the second set of the symbolic information which is used to support /// the data structures for the dynamically link editor. /// /// The original set of symbolic information in the symtab_command which contains /// the symbol and string tables must also be present when this load command is /// present. When this load command is present the symbol table is organized /// into three groups of symbols: /// local symbols (static and debugging symbols) - grouped by module /// defined external symbols - grouped by module (sorted by name if not lib) /// undefined external symbols (sorted by name if MH_BINDATLOAD is not set, /// and in order the were seen by the static /// linker if MH_BINDATLOAD is set) /// In this load command there are offsets and counts to each of the three groups /// of symbols. /// /// This load command contains a the offsets and sizes of the following new /// symbolic information tables: /// table of contents /// module table /// reference symbol table /// indirect symbol table /// The first three tables above (the table of contents, module table and /// reference symbol table) are only present if the file is a dynamically linked /// shared library. For executable and object modules, which are files /// containing only one module, the information that would be in these three /// tables is determined as follows: /// table of contents - the defined external symbols are sorted by name /// module table - the file contains only one module so everything in the /// file is part of the module. /// reference symbol table - is the defined and undefined external symbols /// /// For dynamically linked shared library files this load command also contains /// offsets and sizes to the pool of relocation entries for all sections /// separated into two groups: /// external relocation entries /// local relocation entries /// For executable and object modules the relocation entries continue to hang /// off the section structures. pub const dysymtab_command = extern struct { /// LC_DYSYMTAB cmd: u32, /// sizeof(struct dysymtab_command) cmdsize: u32, // The symbols indicated by symoff and nsyms of the LC_SYMTAB load command // are grouped into the following three groups: // local symbols (further grouped by the module they are from) // defined external symbols (further grouped by the module they are from) // undefined symbols // // The local symbols are used only for debugging. The dynamic binding // process may have to use them to indicate to the debugger the local // symbols for a module that is being bound. // // The last two groups are used by the dynamic binding process to do the // binding (indirectly through the module table and the reference symbol // table when this is a dynamically linked shared library file). /// index of local symbols ilocalsym: u32, /// number of local symbols nlocalsym: u32, /// index to externally defined symbols iextdefsym: u32, /// number of externally defined symbols nextdefsym: u32, /// index to undefined symbols iundefsym: u32, /// number of undefined symbols nundefsym: u32, // For the for the dynamic binding process to find which module a symbol // is defined in the table of contents is used (analogous to the ranlib // structure in an archive) which maps defined external symbols to modules // they are defined in. This exists only in a dynamically linked shared // library file. For executable and object modules the defined external // symbols are sorted by name and is use as the table of contents. /// file offset to table of contents tocoff: u32, /// number of entries in table of contents ntoc: u32, // To support dynamic binding of "modules" (whole object files) the symbol // table must reflect the modules that the file was created from. This is // done by having a module table that has indexes and counts into the merged // tables for each module. The module structure that these two entries // refer to is described below. This exists only in a dynamically linked // shared library file. For executable and object modules the file only // contains one module so everything in the file belongs to the module. /// file offset to module table modtaboff: u32, /// number of module table entries nmodtab: u32, // To support dynamic module binding the module structure for each module // indicates the external references (defined and undefined) each module // makes. For each module there is an offset and a count into the // reference symbol table for the symbols that the module references. // This exists only in a dynamically linked shared library file. For // executable and object modules the defined external symbols and the // undefined external symbols indicates the external references. /// offset to referenced symbol table extrefsymoff: u32, /// number of referenced symbol table entries nextrefsyms: u32, // The sections that contain "symbol pointers" and "routine stubs" have // indexes and (implied counts based on the size of the section and fixed // size of the entry) into the "indirect symbol" table for each pointer // and stub. For every section of these two types the index into the // indirect symbol table is stored in the section header in the field // reserved1. An indirect symbol table entry is simply a 32bit index into // the symbol table to the symbol that the pointer or stub is referring to. // The indirect symbol table is ordered to match the entries in the section. /// file offset to the indirect symbol table indirectsymoff: u32, /// number of indirect symbol table entries nindirectsyms: u32, // To support relocating an individual module in a library file quickly the // external relocation entries for each module in the library need to be // accessed efficiently. Since the relocation entries can't be accessed // through the section headers for a library file they are separated into // groups of local and external entries further grouped by module. In this // case the presents of this load command who's extreloff, nextrel, // locreloff and nlocrel fields are non-zero indicates that the relocation // entries of non-merged sections are not referenced through the section // structures (and the reloff and nreloc fields in the section headers are // set to zero). // // Since the relocation entries are not accessed through the section headers // this requires the r_address field to be something other than a section // offset to identify the item to be relocated. In this case r_address is // set to the offset from the vmaddr of the first LC_SEGMENT command. // For MH_SPLIT_SEGS images r_address is set to the the offset from the // vmaddr of the first read-write LC_SEGMENT command. // // The relocation entries are grouped by module and the module table // entries have indexes and counts into them for the group of external // relocation entries for that the module. // // For sections that are merged across modules there must not be any // remaining external relocation entries for them (for merged sections // remaining relocation entries must be local). /// offset to external relocation entries extreloff: u32, /// number of external relocation entries nextrel: u32, // All the local relocation entries are grouped together (they are not // grouped by their module since they are only used if the object is moved // from it staticly link edited address). /// offset to local relocation entries locreloff: u32, /// number of local relocation entries nlocrel: u32, }; /// The linkedit_data_command contains the offsets and sizes of a blob /// of data in the __LINKEDIT segment. pub const linkedit_data_command = extern struct { /// LC_CODE_SIGNATURE, LC_SEGMENT_SPLIT_INFO, LC_FUNCTION_STARTS, LC_DATA_IN_CODE, LC_DYLIB_CODE_SIGN_DRS or LC_LINKER_OPTIMIZATION_HINT. cmd: u32, /// sizeof(struct linkedit_data_command) cmdsize: u32, /// file offset of data in __LINKEDIT segment dataoff: u32, /// file size of data in __LINKEDIT segment datasize: u32, }; /// The dyld_info_command contains the file offsets and sizes of /// the new compressed form of the information dyld needs to /// load the image. This information is used by dyld on Mac OS X /// 10.6 and later. All information pointed to by this command /// is encoded using byte streams, so no endian swapping is needed /// to interpret it. pub const dyld_info_command = extern struct { /// LC_DYLD_INFO or LC_DYLD_INFO_ONLY cmd: u32, /// sizeof(struct dyld_info_command) cmdsize: u32, // Dyld rebases an image whenever dyld loads it at an address different // from its preferred address. The rebase information is a stream // of byte sized opcodes whose symbolic names start with REBASE_OPCODE_. // Conceptually the rebase information is a table of tuples: // <seg-index, seg-offset, type> // The opcodes are a compressed way to encode the table by only // encoding when a column changes. In addition simple patterns // like "every n'th offset for m times" can be encoded in a few // bytes. /// file offset to rebase info rebase_off: u32, /// size of rebase info rebase_size: u32, // Dyld binds an image during the loading process, if the image // requires any pointers to be initialized to symbols in other images. // The bind information is a stream of byte sized // opcodes whose symbolic names start with BIND_OPCODE_. // Conceptually the bind information is a table of tuples: // <seg-index, seg-offset, type, symbol-library-ordinal, symbol-name, addend> // The opcodes are a compressed way to encode the table by only // encoding when a column changes. In addition simple patterns // like for runs of pointers initialzed to the same value can be // encoded in a few bytes. /// file offset to binding info bind_off: u32, /// size of binding info bind_size: u32, // Some C++ programs require dyld to unique symbols so that all // images in the process use the same copy of some code/data. // This step is done after binding. The content of the weak_bind // info is an opcode stream like the bind_info. But it is sorted // alphabetically by symbol name. This enable dyld to walk // all images with weak binding information in order and look // for collisions. If there are no collisions, dyld does // no updating. That means that some fixups are also encoded // in the bind_info. For instance, all calls to "operator new" // are first bound to libstdc++.dylib using the information // in bind_info. Then if some image overrides operator new // that is detected when the weak_bind information is processed // and the call to operator new is then rebound. /// file offset to weak binding info weak_bind_off: u32, /// size of weak binding info weak_bind_size: u32, // Some uses of external symbols do not need to be bound immediately. // Instead they can be lazily bound on first use. The lazy_bind // are contains a stream of BIND opcodes to bind all lazy symbols. // Normal use is that dyld ignores the lazy_bind section when // loading an image. Instead the static linker arranged for the // lazy pointer to initially point to a helper function which // pushes the offset into the lazy_bind area for the symbol // needing to be bound, then jumps to dyld which simply adds // the offset to lazy_bind_off to get the information on what // to bind. /// file offset to lazy binding info lazy_bind_off: u32, /// size of lazy binding info lazy_bind_size: u32, // The symbols exported by a dylib are encoded in a trie. This // is a compact representation that factors out common prefixes. // It also reduces LINKEDIT pages in RAM because it encodes all // information (name, address, flags) in one small, contiguous range. // The export area is a stream of nodes. The first node sequentially // is the start node for the trie. // // Nodes for a symbol start with a uleb128 that is the length of // the exported symbol information for the string so far. // If there is no exported symbol, the node starts with a zero byte. // If there is exported info, it follows the length. // // First is a uleb128 containing flags. Normally, it is followed by // a uleb128 encoded offset which is location of the content named // by the symbol from the mach_header for the image. If the flags // is EXPORT_SYMBOL_FLAGS_REEXPORT, then following the flags is // a uleb128 encoded library ordinal, then a zero terminated // UTF8 string. If the string is zero length, then the symbol // is re-export from the specified dylib with the same name. // If the flags is EXPORT_SYMBOL_FLAGS_STUB_AND_RESOLVER, then following // the flags is two uleb128s: the stub offset and the resolver offset. // The stub is used by non-lazy pointers. The resolver is used // by lazy pointers and must be called to get the actual address to use. // // After the optional exported symbol information is a byte of // how many edges (0-255) that this node has leaving it, // followed by each edge. // Each edge is a zero terminated UTF8 of the addition chars // in the symbol, followed by a uleb128 offset for the node that // edge points to. /// file offset to lazy binding info export_off: u32, /// size of lazy binding info export_size: u32, }; /// A program that uses a dynamic linker contains a dylinker_command to identify /// the name of the dynamic linker (LC_LOAD_DYLINKER). And a dynamic linker /// contains a dylinker_command to identify the dynamic linker (LC_ID_DYLINKER). /// A file can have at most one of these. /// This struct is also used for the LC_DYLD_ENVIRONMENT load command and contains /// string for dyld to treat like an environment variable. pub const dylinker_command = extern struct { /// LC_ID_DYLINKER, LC_LOAD_DYLINKER, or LC_DYLD_ENVIRONMENT cmd: u32, /// includes pathname string cmdsize: u32, /// A variable length string in a load command is represented by an lc_str /// union. The strings are stored just after the load command structure and /// the offset is from the start of the load command structure. The size /// of the string is reflected in the cmdsize field of the load command. /// Once again any padded bytes to bring the cmdsize field to a multiple /// of 4 bytes must be zero. name: u32, }; /// A dynamically linked shared library (filetype == MH_DYLIB in the mach header) /// contains a dylib_command (cmd == LC_ID_DYLIB) to identify the library. /// An object that uses a dynamically linked shared library also contains a /// dylib_command (cmd == LC_LOAD_DYLIB, LC_LOAD_WEAK_DYLIB, or /// LC_REEXPORT_DYLIB) for each library it uses. pub const dylib_command = extern struct { /// LC_ID_DYLIB, LC_LOAD_WEAK_DYLIB, LC_LOAD_DYLIB, LC_REEXPORT_DYLIB cmd: u32, /// includes pathname string cmdsize: u32, /// the library identification dylib: dylib, }; /// Dynamicaly linked shared libraries are identified by two things. The /// pathname (the name of the library as found for execution), and the /// compatibility version number. The pathname must match and the compatibility /// number in the user of the library must be greater than or equal to the /// library being used. The time stamp is used to record the time a library was /// built and copied into user so it can be use to determined if the library used /// at runtime is exactly the same as used to built the program. pub const dylib = extern struct { /// library's pathname (offset pointing at the end of dylib_command) name: u32, /// library's build timestamp timestamp: u32, /// library's current version number current_version: u32, /// library's compatibility version number compatibility_version: u32, }; /// The segment load command indicates that a part of this file is to be /// mapped into the task's address space. The size of this segment in memory, /// vmsize, maybe equal to or larger than the amount to map from this file, /// filesize. The file is mapped starting at fileoff to the beginning of /// the segment in memory, vmaddr. The rest of the memory of the segment, /// if any, is allocated zero fill on demand. The segment's maximum virtual /// memory protection and initial virtual memory protection are specified /// by the maxprot and initprot fields. If the segment has sections then the /// section structures directly follow the segment command and their size is /// reflected in cmdsize. pub const segment_command = extern struct { /// LC_SEGMENT cmd: u32, /// includes sizeof section structs cmdsize: u32, /// segment name segname: [16]u8, /// memory address of this segment vmaddr: u32, /// memory size of this segment vmsize: u32, /// file offset of this segment fileoff: u32, /// amount to map from the file filesize: u32, /// maximum VM protection maxprot: vm_prot_t, /// initial VM protection initprot: vm_prot_t, /// number of sections in segment nsects: u32, flags: u32, }; /// The 64-bit segment load command indicates that a part of this file is to be /// mapped into a 64-bit task's address space. If the 64-bit segment has /// sections then section_64 structures directly follow the 64-bit segment /// command and their size is reflected in cmdsize. pub const segment_command_64 = extern struct { /// LC_SEGMENT_64 cmd: u32, /// includes sizeof section_64 structs cmdsize: u32, /// segment name segname: [16]u8, /// memory address of this segment vmaddr: u64, /// memory size of this segment vmsize: u64, /// file offset of this segment fileoff: u64, /// amount to map from the file filesize: u64, /// maximum VM protection maxprot: vm_prot_t, /// initial VM protection initprot: vm_prot_t, /// number of sections in segment nsects: u32, flags: u32, }; /// A segment is made up of zero or more sections. Non-MH_OBJECT files have /// all of their segments with the proper sections in each, and padded to the /// specified segment alignment when produced by the link editor. The first /// segment of a MH_EXECUTE and MH_FVMLIB format file contains the mach_header /// and load commands of the object file before its first section. The zero /// fill sections are always last in their segment (in all formats). This /// allows the zeroed segment padding to be mapped into memory where zero fill /// sections might be. The gigabyte zero fill sections, those with the section /// type S_GB_ZEROFILL, can only be in a segment with sections of this type. /// These segments are then placed after all other segments. /// /// The MH_OBJECT format has all of its sections in one segment for /// compactness. There is no padding to a specified segment boundary and the /// mach_header and load commands are not part of the segment. /// /// Sections with the same section name, sectname, going into the same segment, /// segname, are combined by the link editor. The resulting section is aligned /// to the maximum alignment of the combined sections and is the new section's /// alignment. The combined sections are aligned to their original alignment in /// the combined section. Any padded bytes to get the specified alignment are /// zeroed. /// /// The format of the relocation entries referenced by the reloff and nreloc /// fields of the section structure for mach object files is described in the /// header file <reloc.h>. pub const @"section" = extern struct { /// name of this section sectname: [16]u8, /// segment this section goes in segname: [16]u8, /// memory address of this section addr: u32, /// size in bytes of this section size: u32, /// file offset of this section offset: u32, /// section alignment (power of 2) @"align": u32, /// file offset of relocation entries reloff: u32, /// number of relocation entries nreloc: u32, /// flags (section type and attributes flags: u32, /// reserved (for offset or index) reserved1: u32, /// reserved (for count or sizeof) reserved2: u32, }; pub const section_64 = extern struct { /// name of this section sectname: [16]u8, /// segment this section goes in segname: [16]u8, /// memory address of this section addr: u64, /// size in bytes of this section size: u64, /// file offset of this section offset: u32, /// section alignment (power of 2) @"align": u32, /// file offset of relocation entries reloff: u32, /// number of relocation entries nreloc: u32, /// flags (section type and attributes flags: u32, /// reserved (for offset or index) reserved1: u32, /// reserved (for count or sizeof) reserved2: u32, /// reserved reserved3: u32, }; pub const nlist = extern struct { n_strx: u32, n_type: u8, n_sect: u8, n_desc: i16, n_value: u32, }; pub const nlist_64 = extern struct { n_strx: u32, n_type: u8, n_sect: u8, n_desc: u16, n_value: u64, }; /// Format of a relocation entry of a Mach-O file. Modified from the 4.3BSD /// format. The modifications from the original format were changing the value /// of the r_symbolnum field for "local" (r_extern == 0) relocation entries. /// This modification is required to support symbols in an arbitrary number of /// sections not just the three sections (text, data and bss) in a 4.3BSD file. /// Also the last 4 bits have had the r_type tag added to them. pub const relocation_info = packed struct { /// offset in the section to what is being relocated r_address: i32, /// symbol index if r_extern == 1 or section ordinal if r_extern == 0 r_symbolnum: u24, /// was relocated pc relative already r_pcrel: u1, /// 0=byte, 1=word, 2=long, 3=quad r_length: u2, /// does not include value of sym referenced r_extern: u1, /// if not 0, machine specific relocation type r_type: u4, }; /// After MacOS X 10.1 when a new load command is added that is required to be /// understood by the dynamic linker for the image to execute properly the /// LC_REQ_DYLD bit will be or'ed into the load command constant. If the dynamic /// linker sees such a load command it it does not understand will issue a /// "unknown load command required for execution" error and refuse to use the /// image. Other load commands without this bit that are not understood will /// simply be ignored. pub const LC_REQ_DYLD = 0x80000000; /// segment of this file to be mapped pub const LC_SEGMENT = 0x1; /// link-edit stab symbol table info pub const LC_SYMTAB = 0x2; /// link-edit gdb symbol table info (obsolete) pub const LC_SYMSEG = 0x3; /// thread pub const LC_THREAD = 0x4; /// unix thread (includes a stack) pub const LC_UNIXTHREAD = 0x5; /// load a specified fixed VM shared library pub const LC_LOADFVMLIB = 0x6; /// fixed VM shared library identification pub const LC_IDFVMLIB = 0x7; /// object identification info (obsolete) pub const LC_IDENT = 0x8; /// fixed VM file inclusion (internal use) pub const LC_FVMFILE = 0x9; /// prepage command (internal use) pub const LC_PREPAGE = 0xa; /// dynamic link-edit symbol table info pub const LC_DYSYMTAB = 0xb; /// load a dynamically linked shared library pub const LC_LOAD_DYLIB = 0xc; /// dynamically linked shared lib ident pub const LC_ID_DYLIB = 0xd; /// load a dynamic linker pub const LC_LOAD_DYLINKER = 0xe; /// dynamic linker identification pub const LC_ID_DYLINKER = 0xf; /// modules prebound for a dynamically pub const LC_PREBOUND_DYLIB = 0x10; /// image routines pub const LC_ROUTINES = 0x11; /// sub framework pub const LC_SUB_FRAMEWORK = 0x12; /// sub umbrella pub const LC_SUB_UMBRELLA = 0x13; /// sub client pub const LC_SUB_CLIENT = 0x14; /// sub library pub const LC_SUB_LIBRARY = 0x15; /// two-level namespace lookup hints pub const LC_TWOLEVEL_HINTS = 0x16; /// prebind checksum pub const LC_PREBIND_CKSUM = 0x17; /// load a dynamically linked shared library that is allowed to be missing /// (all symbols are weak imported). pub const LC_LOAD_WEAK_DYLIB = (0x18 | LC_REQ_DYLD); /// 64-bit segment of this file to be mapped pub const LC_SEGMENT_64 = 0x19; /// 64-bit image routines pub const LC_ROUTINES_64 = 0x1a; /// the uuid pub const LC_UUID = 0x1b; /// runpath additions pub const LC_RPATH = (0x1c | LC_REQ_DYLD); /// local of code signature pub const LC_CODE_SIGNATURE = 0x1d; /// local of info to split segments pub const LC_SEGMENT_SPLIT_INFO = 0x1e; /// load and re-export dylib pub const LC_REEXPORT_DYLIB = (0x1f | LC_REQ_DYLD); /// delay load of dylib until first use pub const LC_LAZY_LOAD_DYLIB = 0x20; /// encrypted segment information pub const LC_ENCRYPTION_INFO = 0x21; /// compressed dyld information pub const LC_DYLD_INFO = 0x22; /// compressed dyld information only pub const LC_DYLD_INFO_ONLY = (0x22 | LC_REQ_DYLD); /// load upward dylib pub const LC_LOAD_UPWARD_DYLIB = (0x23 | LC_REQ_DYLD); /// build for MacOSX min OS version pub const LC_VERSION_MIN_MACOSX = 0x24; /// build for iPhoneOS min OS version pub const LC_VERSION_MIN_IPHONEOS = 0x25; /// compressed table of function start addresses pub const LC_FUNCTION_STARTS = 0x26; /// string for dyld to treat like environment variable pub const LC_DYLD_ENVIRONMENT = 0x27; /// replacement for LC_UNIXTHREAD pub const LC_MAIN = (0x28 | LC_REQ_DYLD); /// table of non-instructions in __text pub const LC_DATA_IN_CODE = 0x29; /// source version used to build binary pub const LC_SOURCE_VERSION = 0x2A; /// Code signing DRs copied from linked dylibs pub const LC_DYLIB_CODE_SIGN_DRS = 0x2B; /// 64-bit encrypted segment information pub const LC_ENCRYPTION_INFO_64 = 0x2C; /// linker options in MH_OBJECT files pub const LC_LINKER_OPTION = 0x2D; /// optimization hints in MH_OBJECT files pub const LC_LINKER_OPTIMIZATION_HINT = 0x2E; /// build for AppleTV min OS version pub const LC_VERSION_MIN_TVOS = 0x2F; /// build for Watch min OS version pub const LC_VERSION_MIN_WATCHOS = 0x30; /// arbitrary data included within a Mach-O file pub const LC_NOTE = 0x31; /// build for platform min OS version pub const LC_BUILD_VERSION = 0x32; /// the mach magic number pub const MH_MAGIC = 0xfeedface; /// NXSwapInt(MH_MAGIC) pub const MH_CIGAM = 0xcefaedfe; /// the 64-bit mach magic number pub const MH_MAGIC_64 = 0xfeedfacf; /// NXSwapInt(MH_MAGIC_64) pub const MH_CIGAM_64 = 0xcffaedfe; /// relocatable object file pub const MH_OBJECT = 0x1; /// demand paged executable file pub const MH_EXECUTE = 0x2; /// fixed VM shared library file pub const MH_FVMLIB = 0x3; /// core file pub const MH_CORE = 0x4; /// preloaded executable file pub const MH_PRELOAD = 0x5; /// dynamically bound shared library pub const MH_DYLIB = 0x6; /// dynamic link editor pub const MH_DYLINKER = 0x7; /// dynamically bound bundle file pub const MH_BUNDLE = 0x8; /// shared library stub for static linking only, no section contents pub const MH_DYLIB_STUB = 0x9; /// companion file with only debug sections pub const MH_DSYM = 0xa; /// x86_64 kexts pub const MH_KEXT_BUNDLE = 0xb; // Constants for the flags field of the mach_header /// the object file has no undefined references pub const MH_NOUNDEFS = 0x1; /// the object file is the output of an incremental link against a base file and can't be link edited again pub const MH_INCRLINK = 0x2; /// the object file is input for the dynamic linker and can't be staticly link edited again pub const MH_DYLDLINK = 0x4; /// the object file's undefined references are bound by the dynamic linker when loaded. pub const MH_BINDATLOAD = 0x8; /// the file has its dynamic undefined references prebound. pub const MH_PREBOUND = 0x10; /// the file has its read-only and read-write segments split pub const MH_SPLIT_SEGS = 0x20; /// the shared library init routine is to be run lazily via catching memory faults to its writeable segments (obsolete) pub const MH_LAZY_INIT = 0x40; /// the image is using two-level name space bindings pub const MH_TWOLEVEL = 0x80; /// the executable is forcing all images to use flat name space bindings pub const MH_FORCE_FLAT = 0x100; /// this umbrella guarantees no multiple defintions of symbols in its sub-images so the two-level namespace hints can always be used. pub const MH_NOMULTIDEFS = 0x200; /// do not have dyld notify the prebinding agent about this executable pub const MH_NOFIXPREBINDING = 0x400; /// the binary is not prebound but can have its prebinding redone. only used when MH_PREBOUND is not set. pub const MH_PREBINDABLE = 0x800; /// indicates that this binary binds to all two-level namespace modules of its dependent libraries. only used when MH_PREBINDABLE and MH_TWOLEVEL are both set. pub const MH_ALLMODSBOUND = 0x1000; /// safe to divide up the sections into sub-sections via symbols for dead code stripping pub const MH_SUBSECTIONS_VIA_SYMBOLS = 0x2000; /// the binary has been canonicalized via the unprebind operation pub const MH_CANONICAL = 0x4000; /// the final linked image contains external weak symbols pub const MH_WEAK_DEFINES = 0x8000; /// the final linked image uses weak symbols pub const MH_BINDS_TO_WEAK = 0x10000; /// When this bit is set, all stacks in the task will be given stack execution privilege. Only used in MH_EXECUTE filetypes. pub const MH_ALLOW_STACK_EXECUTION = 0x20000; /// When this bit is set, the binary declares it is safe for use in processes with uid zero pub const MH_ROOT_SAFE = 0x40000; /// When this bit is set, the binary declares it is safe for use in processes when issetugid() is true pub const MH_SETUID_SAFE = 0x80000; /// When this bit is set on a dylib, the static linker does not need to examine dependent dylibs to see if any are re-exported pub const MH_NO_REEXPORTED_DYLIBS = 0x100000; /// When this bit is set, the OS will load the main executable at a random address. Only used in MH_EXECUTE filetypes. pub const MH_PIE = 0x200000; /// Only for use on dylibs. When linking against a dylib that has this bit set, the static linker will automatically not create a LC_LOAD_DYLIB load command to the dylib if no symbols are being referenced from the dylib. pub const MH_DEAD_STRIPPABLE_DYLIB = 0x400000; /// Contains a section of type S_THREAD_LOCAL_VARIABLES pub const MH_HAS_TLV_DESCRIPTORS = 0x800000; /// When this bit is set, the OS will run the main executable with a non-executable heap even on platforms (e.g. i386) that don't require it. Only used in MH_EXECUTE filetypes. pub const MH_NO_HEAP_EXECUTION = 0x1000000; /// The code was linked for use in an application extension. pub const MH_APP_EXTENSION_SAFE = 0x02000000; /// The external symbols listed in the nlist symbol table do not include all the symbols listed in the dyld info. pub const MH_NLIST_OUTOFSYNC_WITH_DYLDINFO = 0x04000000; /// The flags field of a section structure is separated into two parts a section /// type and section attributes. The section types are mutually exclusive (it /// can only have one type) but the section attributes are not (it may have more /// than one attribute). /// 256 section types pub const SECTION_TYPE = 0x000000ff; /// 24 section attributes pub const SECTION_ATTRIBUTES = 0xffffff00; /// regular section pub const S_REGULAR = 0x0; /// zero fill on demand section pub const S_ZEROFILL = 0x1; /// section with only literal C string pub const S_CSTRING_LITERALS = 0x2; /// section with only 4 byte literals pub const S_4BYTE_LITERALS = 0x3; /// section with only 8 byte literals pub const S_8BYTE_LITERALS = 0x4; /// section with only pointers to pub const S_LITERAL_POINTERS = 0x5; /// if any of these bits set, a symbolic debugging entry pub const N_STAB = 0xe0; /// private external symbol bit pub const N_PEXT = 0x10; /// mask for the type bits pub const N_TYPE = 0x0e; /// external symbol bit, set for external symbols pub const N_EXT = 0x01; /// symbol is undefined pub const N_UNDF = 0x0; /// symbol is absolute pub const N_ABS = 0x2; /// symbol is defined in the section number given in n_sect pub const N_SECT = 0xe; /// symbol is undefined and the image is using a prebound /// value for the symbol pub const N_PBUD = 0xc; /// symbol is defined to be the same as another symbol; the n_value /// field is an index into the string table specifying the name of the /// other symbol pub const N_INDR = 0xa; /// global symbol: name,,NO_SECT,type,0 pub const N_GSYM = 0x20; /// procedure name (f77 kludge): name,,NO_SECT,0,0 pub const N_FNAME = 0x22; /// procedure: name,,n_sect,linenumber,address pub const N_FUN = 0x24; /// static symbol: name,,n_sect,type,address pub const N_STSYM = 0x26; /// .lcomm symbol: name,,n_sect,type,address pub const N_LCSYM = 0x28; /// begin nsect sym: 0,,n_sect,0,address pub const N_BNSYM = 0x2e; /// AST file path: name,,NO_SECT,0,0 pub const N_AST = 0x32; /// emitted with gcc2_compiled and in gcc source pub const N_OPT = 0x3c; /// register sym: name,,NO_SECT,type,register pub const N_RSYM = 0x40; /// src line: 0,,n_sect,linenumber,address pub const N_SLINE = 0x44; /// end nsect sym: 0,,n_sect,0,address pub const N_ENSYM = 0x4e; /// structure elt: name,,NO_SECT,type,struct_offset pub const N_SSYM = 0x60; /// source file name: name,,n_sect,0,address pub const N_SO = 0x64; /// object file name: name,,0,0,st_mtime pub const N_OSO = 0x66; /// local sym: name,,NO_SECT,type,offset pub const N_LSYM = 0x80; /// include file beginning: name,,NO_SECT,0,sum pub const N_BINCL = 0x82; /// #included file name: name,,n_sect,0,address pub const N_SOL = 0x84; /// compiler parameters: name,,NO_SECT,0,0 pub const N_PARAMS = 0x86; /// compiler version: name,,NO_SECT,0,0 pub const N_VERSION = 0x88; /// compiler -O level: name,,NO_SECT,0,0 pub const N_OLEVEL = 0x8A; /// parameter: name,,NO_SECT,type,offset pub const N_PSYM = 0xa0; /// include file end: name,,NO_SECT,0,0 pub const N_EINCL = 0xa2; /// alternate entry: name,,n_sect,linenumber,address pub const N_ENTRY = 0xa4; /// left bracket: 0,,NO_SECT,nesting level,address pub const N_LBRAC = 0xc0; /// deleted include file: name,,NO_SECT,0,sum pub const N_EXCL = 0xc2; /// right bracket: 0,,NO_SECT,nesting level,address pub const N_RBRAC = 0xe0; /// begin common: name,,NO_SECT,0,0 pub const N_BCOMM = 0xe2; /// end common: name,,n_sect,0,0 pub const N_ECOMM = 0xe4; /// end common (local name): 0,,n_sect,0,address pub const N_ECOML = 0xe8; /// second stab entry with length information pub const N_LENG = 0xfe; // For the two types of symbol pointers sections and the symbol stubs section // they have indirect symbol table entries. For each of the entries in the // section the indirect symbol table entries, in corresponding order in the // indirect symbol table, start at the index stored in the reserved1 field // of the section structure. Since the indirect symbol table entries // correspond to the entries in the section the number of indirect symbol table // entries is inferred from the size of the section divided by the size of the // entries in the section. For symbol pointers sections the size of the entries // in the section is 4 bytes and for symbol stubs sections the byte size of the // stubs is stored in the reserved2 field of the section structure. /// section with only non-lazy symbol pointers pub const S_NON_LAZY_SYMBOL_POINTERS = 0x6; /// section with only lazy symbol pointers pub const S_LAZY_SYMBOL_POINTERS = 0x7; /// section with only symbol stubs, byte size of stub in the reserved2 field pub const S_SYMBOL_STUBS = 0x8; /// section with only function pointers for initialization pub const S_MOD_INIT_FUNC_POINTERS = 0x9; /// section with only function pointers for termination pub const S_MOD_TERM_FUNC_POINTERS = 0xa; /// section contains symbols that are to be coalesced pub const S_COALESCED = 0xb; /// zero fill on demand section (that can be larger than 4 gigabytes) pub const S_GB_ZEROFILL = 0xc; /// section with only pairs of function pointers for interposing pub const S_INTERPOSING = 0xd; /// section with only 16 byte literals pub const S_16BYTE_LITERALS = 0xe; /// section contains DTrace Object Format pub const S_DTRACE_DOF = 0xf; /// section with only lazy symbol pointers to lazy loaded dylibs pub const S_LAZY_DYLIB_SYMBOL_POINTERS = 0x10; // If a segment contains any sections marked with S_ATTR_DEBUG then all // sections in that segment must have this attribute. No section other than // a section marked with this attribute may reference the contents of this // section. A section with this attribute may contain no symbols and must have // a section type S_REGULAR. The static linker will not copy section contents // from sections with this attribute into its output file. These sections // generally contain DWARF debugging info. /// a debug section pub const S_ATTR_DEBUG = 0x02000000; /// section contains only true machine instructions pub const S_ATTR_PURE_INSTRUCTIONS = 0x80000000; /// section contains coalesced symbols that are not to be in a ranlib /// table of contents pub const S_ATTR_NO_TOC = 0x40000000; /// ok to strip static symbols in this section in files with the /// MH_DYLDLINK flag pub const S_ATTR_STRIP_STATIC_SYMS = 0x20000000; /// no dead stripping pub const S_ATTR_NO_DEAD_STRIP = 0x10000000; /// blocks are live if they reference live blocks pub const S_ATTR_LIVE_SUPPORT = 0x8000000; /// used with i386 code stubs written on by dyld pub const S_ATTR_SELF_MODIFYING_CODE = 0x4000000; /// section contains some machine instructions pub const S_ATTR_SOME_INSTRUCTIONS = 0x400; /// section has external relocation entries pub const S_ATTR_EXT_RELOC = 0x200; /// section has local relocation entries pub const S_ATTR_LOC_RELOC = 0x100; pub const cpu_type_t = integer_t; pub const cpu_subtype_t = integer_t; pub const integer_t = c_int; pub const vm_prot_t = c_int; /// CPU type targeting 64-bit Intel-based Macs pub const CPU_TYPE_X86_64: cpu_type_t = 0x01000007; /// CPU type targeting 64-bit ARM-based Macs pub const CPU_TYPE_ARM64: cpu_type_t = 0x0100000C; /// All Intel-based Macs pub const CPU_SUBTYPE_X86_64_ALL: cpu_subtype_t = 0x3; /// All ARM-based Macs pub const CPU_SUBTYPE_ARM_ALL: cpu_subtype_t = 0x0; // Protection values defined as bits within the vm_prot_t type /// No VM protection pub const VM_PROT_NONE: vm_prot_t = 0x0; /// VM read permission pub const VM_PROT_READ: vm_prot_t = 0x1; /// VM write permission pub const VM_PROT_WRITE: vm_prot_t = 0x2; /// VM execute permission pub const VM_PROT_EXECUTE: vm_prot_t = 0x4; pub const reloc_type_x86_64 = packed enum(u4) { /// for absolute addresses X86_64_RELOC_UNSIGNED = 0, /// for signed 32-bit displacement X86_64_RELOC_SIGNED, /// a CALL/JMP instruction with 32-bit displacement X86_64_RELOC_BRANCH, /// a MOVQ load of a GOT entry X86_64_RELOC_GOT_LOAD, /// other GOT references X86_64_RELOC_GOT, /// must be followed by a X86_64_RELOC_UNSIGNED X86_64_RELOC_SUBTRACTOR, /// for signed 32-bit displacement with a -1 addend X86_64_RELOC_SIGNED_1, /// for signed 32-bit displacement with a -2 addend X86_64_RELOC_SIGNED_2, /// for signed 32-bit displacement with a -4 addend X86_64_RELOC_SIGNED_4, /// for thread local variables X86_64_RELOC_TLV, }; /// This symbol is a reference to an external non-lazy (data) symbol. pub const REFERENCE_FLAG_UNDEFINED_NON_LAZY: u16 = 0x0; /// This symbol is a reference to an external lazy symbol—that is, to a function call. pub const REFERENCE_FLAG_UNDEFINED_LAZY: u16 = 0x1; /// This symbol is defined in this module. pub const REFERENCE_FLAG_DEFINED: u16 = 0x2; /// This symbol is defined in this module and is visible only to modules within this shared library. pub const REFERENCE_FLAG_PRIVATE_DEFINED: u16 = 3; /// This symbol is defined in another module in this file, is a non-lazy (data) symbol, and is visible /// only to modules within this shared library. pub const REFERENCE_FLAG_PRIVATE_UNDEFINED_NON_LAZY: u16 = 4; /// This symbol is defined in another module in this file, is a lazy (function) symbol, and is visible /// only to modules within this shared library. pub const REFERENCE_FLAG_PRIVATE_UNDEFINED_LAZY: u16 = 5; /// Must be set for any defined symbol that is referenced by dynamic-loader APIs (such as dlsym and /// NSLookupSymbolInImage) and not ordinary undefined symbol references. The strip tool uses this bit /// to avoid removing symbols that must exist: If the symbol has this bit set, strip does not strip it. pub const REFERENCED_DYNAMICALLY: u16 = 0x10; /// Used by the dynamic linker at runtime. Do not set this bit. pub const N_DESC_DISCARDED: u16 = 0x20; /// Indicates that this symbol is a weak reference. If the dynamic linker cannot find a definition /// for this symbol, it sets the address of this symbol to 0. The static linker sets this symbol given /// the appropriate weak-linking flags. pub const N_WEAK_REF: u16 = 0x40; /// Indicates that this symbol is a weak definition. If the static linker or the dynamic linker finds /// another (non-weak) definition for this symbol, the weak definition is ignored. Only symbols in a /// coalesced section (page 23) can be marked as a weak definition. pub const N_WEAK_DEF: u16 = 0x80; /// The N_SYMBOL_RESOLVER bit of the n_desc field indicates that the /// that the function is actually a resolver function and should /// be called to get the address of the real function to use. /// This bit is only available in .o files (MH_OBJECT filetype) pub const N_SYMBOL_RESOLVER: u16 = 0x100; // Codesign consts and structs taken from: // https://opensource.apple.com/source/xnu/xnu-6153.81.5/osfmk/kern/cs_blobs.h.auto.html /// Single Requirement blob pub const CSMAGIC_REQUIREMENT: u32 = 0xfade0c00; /// Requirements vector (internal requirements) pub const CSMAGIC_REQUIREMENTS: u32 = 0xfade0c01; /// CodeDirectory blob pub const CSMAGIC_CODEDIRECTORY: u32 = 0xfade0c02; /// embedded form of signature data pub const CSMAGIC_EMBEDDED_SIGNATURE: u32 = 0xfade0cc0; /// XXX pub const CSMAGIC_EMBEDDED_SIGNATURE_OLD: u32 = 0xfade0b02; /// Embedded entitlements pub const CSMAGIC_EMBEDDED_ENTITLEMENTS: u32 = 0xfade7171; /// Multi-arch collection of embedded signatures pub const CSMAGIC_DETACHED_SIGNATURE: u32 = 0xfade0cc1; /// CMS Signature, among other things pub const CSMAGIC_BLOBWRAPPER: u32 = 0xfade0b01; pub const CS_SUPPORTSSCATTER: u32 = 0x20100; pub const CS_SUPPORTSTEAMID: u32 = 0x20200; pub const CS_SUPPORTSCODELIMIT64: u32 = 0x20300; pub const CS_SUPPORTSEXECSEG: u32 = 0x20400; /// Slot index for CodeDirectory pub const CSSLOT_CODEDIRECTORY: u32 = 0; pub const CSSLOT_INFOSLOT: u32 = 1; pub const CSSLOT_REQUIREMENTS: u32 = 2; pub const CSSLOT_RESOURCEDIR: u32 = 3; pub const CSSLOT_APPLICATION: u32 = 4; pub const CSSLOT_ENTITLEMENTS: u32 = 5; /// first alternate CodeDirectory, if any pub const CSSLOT_ALTERNATE_CODEDIRECTORIES: u32 = 0x1000; /// Max number of alternate CD slots pub const CSSLOT_ALTERNATE_CODEDIRECTORY_MAX: u32 = 5; /// One past the last pub const CSSLOT_ALTERNATE_CODEDIRECTORY_LIMIT: u32 = CSSLOT_ALTERNATE_CODEDIRECTORIES + CSSLOT_ALTERNATE_CODEDIRECTORY_MAX; /// CMS Signature pub const CSSLOT_SIGNATURESLOT: u32 = 0x10000; pub const CSSLOT_IDENTIFICATIONSLOT: u32 = 0x10001; pub const CSSLOT_TICKETSLOT: u32 = 0x10002; /// Compat with amfi pub const CSTYPE_INDEX_REQUIREMENTS: u32 = 0x00000002; /// Compat with amfi pub const CSTYPE_INDEX_ENTITLEMENTS: u32 = 0x00000005; pub const CS_HASHTYPE_SHA1: u8 = 1; pub const CS_HASHTYPE_SHA256: u8 = 2; pub const CS_HASHTYPE_SHA256_TRUNCATED: u8 = 3; pub const CS_HASHTYPE_SHA384: u8 = 4; pub const CS_SHA1_LEN: u32 = 20; pub const CS_SHA256_LEN: u32 = 32; pub const CS_SHA256_TRUNCATED_LEN: u32 = 20; /// Always - larger hashes are truncated pub const CS_CDHASH_LEN: u32 = 20; /// Max size of the hash we'll support pub const CS_HASH_MAX_SIZE: u32 = 48; pub const CS_SIGNER_TYPE_UNKNOWN: u32 = 0; pub const CS_SIGNER_TYPE_LEGACYVPN: u32 = 5; pub const CS_SIGNER_TYPE_MAC_APP_STORE: u32 = 6; pub const CS_ADHOC: u32 = 0x2; pub const CS_EXECSEG_MAIN_BINARY: u32 = 0x1; /// This CodeDirectory is tailored specfically at version 0x20400. pub const CodeDirectory = extern struct { /// Magic number (CSMAGIC_CODEDIRECTORY) magic: u32, /// Total length of CodeDirectory blob length: u32, /// Compatibility version version: u32, /// Setup and mode flags flags: u32, /// Offset of hash slot element at index zero hashOffset: u32, /// Offset of identifier string identOffset: u32, /// Number of special hash slots nSpecialSlots: u32, /// Number of ordinary (code) hash slots nCodeSlots: u32, /// Limit to main image signature range codeLimit: u32, /// Size of each hash in bytes hashSize: u8, /// Type of hash (cdHashType* constants) hashType: u8, /// Platform identifier; zero if not platform binary platform: u8, /// log2(page size in bytes); 0 => infinite pageSize: u8, /// Unused (must be zero) spare2: u32, /// scatterOffset: u32, /// teamOffset: u32, /// spare3: u32, /// codeLimit64: u64, /// Offset of executable segment execSegBase: u64, /// Limit of executable segment execSegLimit: u64, /// Executable segment flags execSegFlags: u64, }; /// Structure of an embedded-signature SuperBlob pub const BlobIndex = extern struct { /// Type of entry @"type": u32, /// Offset of entry offset: u32, }; /// This structure is followed by GenericBlobs in no particular /// order as indicated by offsets in index pub const SuperBlob = extern struct { /// Magic number magic: u32, /// Total length of SuperBlob length: u32, /// Number of index BlobIndex entries following this struct count: u32, }; pub const GenericBlob = extern struct { /// Magic number magic: u32, /// Total length of blob length: u32, };
lib/std/macho.zig
const std = @import("../index.zig"); const c = std.c; const assert = std.debug.assert; pub use @import("darwin_errno.zig"); pub const PATH_MAX = 1024; pub const STDIN_FILENO = 0; pub const STDOUT_FILENO = 1; pub const STDERR_FILENO = 2; /// [MC2] no permissions pub const PROT_NONE = 0x00; /// [MC2] pages can be read pub const PROT_READ = 0x01; /// [MC2] pages can be written pub const PROT_WRITE = 0x02; /// [MC2] pages can be executed pub const PROT_EXEC = 0x04; /// allocated from memory, swap space pub const MAP_ANONYMOUS = 0x1000; /// map from file (default) pub const MAP_FILE = 0x0000; /// interpret addr exactly pub const MAP_FIXED = 0x0010; /// region may contain semaphores pub const MAP_HASSEMAPHORE = 0x0200; /// changes are private pub const MAP_PRIVATE = 0x0002; /// share changes pub const MAP_SHARED = 0x0001; /// don't cache pages for this mapping pub const MAP_NOCACHE = 0x0400; /// don't reserve needed swap area pub const MAP_NORESERVE = 0x0040; pub const MAP_FAILED = @maxValue(usize); /// [XSI] no hang in wait/no child to reap pub const WNOHANG = 0x00000001; /// [XSI] notify on stop, untraced child pub const WUNTRACED = 0x00000002; /// take signal on signal stack pub const SA_ONSTACK = 0x0001; /// restart system on signal return pub const SA_RESTART = 0x0002; /// reset to SIG_DFL when taking signal pub const SA_RESETHAND = 0x0004; /// do not generate SIGCHLD on child stop pub const SA_NOCLDSTOP = 0x0008; /// don't mask the signal we're delivering pub const SA_NODEFER = 0x0010; /// don't keep zombies around pub const SA_NOCLDWAIT = 0x0020; /// signal handler with SA_SIGINFO args pub const SA_SIGINFO = 0x0040; /// do not bounce off kernel's sigtramp pub const SA_USERTRAMP = 0x0100; /// signal handler with SA_SIGINFO args with 64bit regs information pub const SA_64REGSET = 0x0200; pub const O_LARGEFILE = 0x0000; pub const O_PATH = 0x0000; pub const F_OK = 0; pub const X_OK = 1; pub const W_OK = 2; pub const R_OK = 4; /// open for reading only pub const O_RDONLY = 0x0000; /// open for writing only pub const O_WRONLY = 0x0001; /// open for reading and writing pub const O_RDWR = 0x0002; /// do not block on open or for data to become available pub const O_NONBLOCK = 0x0004; /// append on each write pub const O_APPEND = 0x0008; /// create file if it does not exist pub const O_CREAT = 0x0200; /// truncate size to 0 pub const O_TRUNC = 0x0400; /// error if O_CREAT and the file exists pub const O_EXCL = 0x0800; /// atomically obtain a shared lock pub const O_SHLOCK = 0x0010; /// atomically obtain an exclusive lock pub const O_EXLOCK = 0x0020; /// do not follow symlinks pub const O_NOFOLLOW = 0x0100; /// allow open of symlinks pub const O_SYMLINK = 0x200000; /// descriptor requested for event notifications only pub const O_EVTONLY = 0x8000; /// mark as close-on-exec pub const O_CLOEXEC = 0x1000000; pub const O_ACCMODE = 3; pub const O_ALERT = 536870912; pub const O_ASYNC = 64; pub const O_DIRECTORY = 1048576; pub const O_DP_GETRAWENCRYPTED = 1; pub const O_DP_GETRAWUNENCRYPTED = 2; pub const O_DSYNC = 4194304; pub const O_FSYNC = O_SYNC; pub const O_NOCTTY = 131072; pub const O_POPUP = 2147483648; pub const O_SYNC = 128; pub const SEEK_SET = 0x0; pub const SEEK_CUR = 0x1; pub const SEEK_END = 0x2; pub const DT_UNKNOWN = 0; pub const DT_FIFO = 1; pub const DT_CHR = 2; pub const DT_DIR = 4; pub const DT_BLK = 6; pub const DT_REG = 8; pub const DT_LNK = 10; pub const DT_SOCK = 12; pub const DT_WHT = 14; /// block specified signal set pub const SIG_BLOCK = 1; /// unblock specified signal set pub const SIG_UNBLOCK = 2; /// set specified signal set pub const SIG_SETMASK = 3; /// hangup pub const SIGHUP = 1; /// interrupt pub const SIGINT = 2; /// quit pub const SIGQUIT = 3; /// illegal instruction (not reset when caught) pub const SIGILL = 4; /// trace trap (not reset when caught) pub const SIGTRAP = 5; /// abort() pub const SIGABRT = 6; /// pollable event ([XSR] generated, not supported) pub const SIGPOLL = 7; /// compatibility pub const SIGIOT = SIGABRT; /// EMT instruction pub const SIGEMT = 7; /// floating point exception pub const SIGFPE = 8; /// kill (cannot be caught or ignored) pub const SIGKILL = 9; /// bus error pub const SIGBUS = 10; /// segmentation violation pub const SIGSEGV = 11; /// bad argument to system call pub const SIGSYS = 12; /// write on a pipe with no one to read it pub const SIGPIPE = 13; /// alarm clock pub const SIGALRM = 14; /// software termination signal from kill pub const SIGTERM = 15; /// urgent condition on IO channel pub const SIGURG = 16; /// sendable stop signal not from tty pub const SIGSTOP = 17; /// stop signal from tty pub const SIGTSTP = 18; /// continue a stopped process pub const SIGCONT = 19; /// to parent on child stop or exit pub const SIGCHLD = 20; /// to readers pgrp upon background tty read pub const SIGTTIN = 21; /// like TTIN for output if (tp->t_local&LTOSTOP) pub const SIGTTOU = 22; /// input/output possible signal pub const SIGIO = 23; /// exceeded CPU time limit pub const SIGXCPU = 24; /// exceeded file size limit pub const SIGXFSZ = 25; /// virtual time alarm pub const SIGVTALRM = 26; /// profiling time alarm pub const SIGPROF = 27; /// window size changes pub const SIGWINCH = 28; /// information request pub const SIGINFO = 29; /// user defined signal 1 pub const SIGUSR1 = 30; /// user defined signal 2 pub const SIGUSR2 = 31; fn wstatus(x: i32) i32 { return x & 0o177; } const wstopped = 0o177; pub fn WEXITSTATUS(x: i32) i32 { return x >> 8; } pub fn WTERMSIG(x: i32) i32 { return wstatus(x); } pub fn WSTOPSIG(x: i32) i32 { return x >> 8; } pub fn WIFEXITED(x: i32) bool { return wstatus(x) == 0; } pub fn WIFSTOPPED(x: i32) bool { return wstatus(x) == wstopped and WSTOPSIG(x) != 0x13; } pub fn WIFSIGNALED(x: i32) bool { return wstatus(x) != wstopped and wstatus(x) != 0; } /// Get the errno from a syscall return value, or 0 for no error. pub fn getErrno(r: usize) usize { const signed_r = @bitCast(isize, r); return if (signed_r > -4096 and signed_r < 0) @intCast(usize, -signed_r) else 0; } pub fn close(fd: i32) usize { return errnoWrap(c.close(fd)); } pub fn abort() noreturn { c.abort(); } pub fn exit(code: i32) noreturn { c.exit(code); } pub fn isatty(fd: i32) bool { return c.isatty(fd) != 0; } pub fn fstat(fd: i32, buf: *c.Stat) usize { return errnoWrap(c.@"fstat$INODE64"(fd, buf)); } pub fn lseek(fd: i32, offset: isize, whence: c_int) usize { return errnoWrap(c.lseek(fd, offset, whence)); } // TODO https://github.com/ziglang/zig/issues/265 on the whole file pub fn open(path: [*]const u8, flags: u32, mode: usize) usize { return errnoWrap(c.open(path, @bitCast(c_int, flags), mode)); } pub fn raise(sig: i32) usize { return errnoWrap(c.raise(sig)); } pub fn read(fd: i32, buf: [*]u8, nbyte: usize) usize { return errnoWrap(c.read(fd, @ptrCast(*c_void, buf), nbyte)); } pub fn stat(noalias path: [*]const u8, noalias buf: *stat) usize { return errnoWrap(c.stat(path, buf)); } pub fn write(fd: i32, buf: [*]const u8, nbyte: usize) usize { return errnoWrap(c.write(fd, @ptrCast(*const c_void, buf), nbyte)); } pub fn mmap(address: ?[*]u8, length: usize, prot: usize, flags: u32, fd: i32, offset: isize) usize { const ptr_result = c.mmap( @ptrCast(*c_void, address), length, @bitCast(c_int, @intCast(c_uint, prot)), @bitCast(c_int, c_uint(flags)), fd, offset, ); const isize_result = @bitCast(isize, @ptrToInt(ptr_result)); return errnoWrap(isize_result); } pub fn munmap(address: usize, length: usize) usize { return errnoWrap(c.munmap(@intToPtr(*c_void, address), length)); } pub fn unlink(path: [*]const u8) usize { return errnoWrap(c.unlink(path)); } pub fn getcwd(buf: [*]u8, size: usize) usize { return if (c.getcwd(buf, size) == null) @bitCast(usize, -isize(c._errno().*)) else 0; } pub fn waitpid(pid: i32, status: *i32, options: u32) usize { comptime assert(i32.bit_count == c_int.bit_count); return errnoWrap(c.waitpid(pid, @ptrCast(*c_int, status), @bitCast(c_int, options))); } pub fn fork() usize { return errnoWrap(c.fork()); } pub fn access(path: [*]const u8, mode: u32) usize { return errnoWrap(c.access(path, mode)); } pub fn pipe(fds: *[2]i32) usize { comptime assert(i32.bit_count == c_int.bit_count); return errnoWrap(c.pipe(@ptrCast(*[2]c_int, fds))); } pub fn getdirentries64(fd: i32, buf_ptr: [*]u8, buf_len: usize, basep: *i64) usize { return errnoWrap(@bitCast(isize, c.__getdirentries64(fd, buf_ptr, buf_len, basep))); } pub fn mkdir(path: [*]const u8, mode: u32) usize { return errnoWrap(c.mkdir(path, mode)); } pub fn symlink(existing: [*]const u8, new: [*]const u8) usize { return errnoWrap(c.symlink(existing, new)); } pub fn rename(old: [*]const u8, new: [*]const u8) usize { return errnoWrap(c.rename(old, new)); } pub fn rmdir(path: [*]const u8) usize { return errnoWrap(c.rmdir(path)); } pub fn chdir(path: [*]const u8) usize { return errnoWrap(c.chdir(path)); } pub fn execve(path: [*]const u8, argv: [*]const ?[*]const u8, envp: [*]const ?[*]const u8) usize { return errnoWrap(c.execve(path, argv, envp)); } pub fn dup2(old: i32, new: i32) usize { return errnoWrap(c.dup2(old, new)); } pub fn readlink(noalias path: [*]const u8, noalias buf_ptr: [*]u8, buf_len: usize) usize { return errnoWrap(c.readlink(path, buf_ptr, buf_len)); } pub fn gettimeofday(tv: ?*timeval, tz: ?*timezone) usize { return errnoWrap(c.gettimeofday(tv, tz)); } pub fn nanosleep(req: *const timespec, rem: ?*timespec) usize { return errnoWrap(c.nanosleep(req, rem)); } pub fn realpath(noalias filename: [*]const u8, noalias resolved_name: [*]u8) usize { return if (c.realpath(filename, resolved_name) == null) @bitCast(usize, -isize(c._errno().*)) else 0; } pub fn setreuid(ruid: u32, euid: u32) usize { return errnoWrap(c.setreuid(ruid, euid)); } pub fn setregid(rgid: u32, egid: u32) usize { return errnoWrap(c.setregid(rgid, egid)); } pub fn sigprocmask(flags: u32, noalias set: *const sigset_t, noalias oldset: ?*sigset_t) usize { return errnoWrap(c.sigprocmask(@bitCast(c_int, flags), set, oldset)); } pub fn sigaction(sig: u5, noalias act: *const Sigaction, noalias oact: ?*Sigaction) usize { assert(sig != SIGKILL); assert(sig != SIGSTOP); var cact = c.Sigaction{ .handler = @ptrCast(extern fn (c_int) void, act.handler), .sa_flags = @bitCast(c_int, act.flags), .sa_mask = act.mask, }; var coact: c.Sigaction = undefined; const result = errnoWrap(c.sigaction(sig, *cact, *coact)); if (result != 0) { return result; } if (oact) |old| { old.* = Sigaction{ .handler = @ptrCast(extern fn (i32) void, coact.handler), .flags = @bitCast(u32, coact.sa_flags), .mask = coact.sa_mask, }; } return result; } pub const sigset_t = c.sigset_t; pub const empty_sigset = sigset_t(0); pub const timespec = c.timespec; pub const Stat = c.Stat; pub const dirent = c.dirent; pub const sa_family_t = c.sa_family_t; pub const sockaddr = c.sockaddr; /// Renamed from `sigaction` to `Sigaction` to avoid conflict with the syscall. pub const Sigaction = struct { handler: extern fn (i32) void, mask: sigset_t, flags: u32, }; pub fn sigaddset(set: *sigset_t, signo: u5) void { set.* |= u32(1) << (signo - 1); } /// Takes the return value from a syscall and formats it back in the way /// that the kernel represents it to libc. Errno was a mistake, let's make /// it go away forever. fn errnoWrap(value: isize) usize { return @bitCast(usize, if (value == -1) -isize(c._errno().*) else value); } pub const timezone = c.timezone; pub const timeval = c.timeval; pub const mach_timebase_info_data = c.mach_timebase_info_data; pub const mach_absolute_time = c.mach_absolute_time; pub const mach_timebase_info = c.mach_timebase_info;
std/os/darwin.zig
const std = @import("std"); const os = std.os; const mem = std.mem; const Allocator = mem.Allocator; usingnamespace std.os.wasi; /// Type-tag of WASI preopen. /// /// WASI currently offers only `Dir` as a valid preopen resource. pub const PreopenTypeTag = enum { Dir, }; /// Type of WASI preopen. /// /// WASI currently offers only `Dir` as a valid preopen resource. pub const PreopenType = union(PreopenTypeTag) { /// Preopened directory type. Dir: []const u8, const Self = @This(); pub fn eql(self: Self, other: PreopenType) bool { if (!mem.eql(u8, @tagName(self), @tagName(other))) return false; switch (self) { PreopenTypeTag.Dir => |this_path| return mem.eql(u8, this_path, other.Dir), } } pub fn format(self: Self, comptime fmt: []const u8, options: std.fmt.FormatOptions, out_stream: var) !void { try out_stream.print("PreopenType{{ ", .{}); switch (self) { PreopenType.Dir => |path| try out_stream.print(".Dir = '{}'", .{path}), } return out_stream.print(" }}", .{}); } }; /// WASI preopen struct. This struct consists of a WASI file descriptor /// and type of WASI preopen. It can be obtained directly from the WASI /// runtime using `PreopenList.populate()` method. pub const Preopen = struct { /// WASI file descriptor. fd: fd_t, /// Type of the preopen. @"type": PreopenType, /// Construct new `Preopen` instance. pub fn new(fd: fd_t, preopen_type: PreopenType) Preopen { return Preopen{ .fd = fd, .@"type" = preopen_type, }; } }; /// Dynamically-sized array list of WASI preopens. This struct is a /// convenience wrapper for issuing `std.os.wasi.fd_prestat_get` and /// `std.os.wasi.fd_prestat_dir_name` syscalls to the WASI runtime, and /// collecting the returned preopens. /// /// This struct is intended to be used in any WASI program which intends /// to use the capabilities as passed on by the user of the runtime. pub const PreopenList = struct { const InnerList = std.ArrayList(Preopen); /// Internal dynamically-sized buffer for storing the gathered preopens. buffer: InnerList, const Self = @This(); pub const Error = os.UnexpectedError || Allocator.Error; /// Deinitialize with `deinit`. pub fn init(allocator: *Allocator) Self { return Self{ .buffer = InnerList.init(allocator) }; } /// Release all allocated memory. pub fn deinit(pm: Self) void { for (pm.buffer.items) |preopen| { switch (preopen.@"type") { PreopenType.Dir => |path| pm.buffer.allocator.free(path), } } pm.buffer.deinit(); } /// Populate the list with the preopens by issuing `std.os.wasi.fd_prestat_get` /// and `std.os.wasi.fd_prestat_dir_name` syscalls to the runtime. /// /// If called more than once, it will clear its contents every time before /// issuing the syscalls. pub fn populate(self: *Self) Error!void { // Clear contents if we're being called again for (self.toOwnedSlice()) |preopen| { switch (preopen.@"type") { PreopenType.Dir => |path| self.buffer.allocator.free(path), } } errdefer self.deinit(); var fd: fd_t = 3; // start fd has to be beyond stdio fds while (true) { var buf: prestat_t = undefined; switch (fd_prestat_get(fd, &buf)) { ESUCCESS => {}, ENOTSUP => { // not a preopen, so keep going continue; }, EBADF => { // OK, no more fds available break; }, else => |err| return os.unexpectedErrno(err), } const preopen_len = buf.u.dir.pr_name_len; const path_buf = try self.buffer.allocator.alloc(u8, preopen_len); mem.set(u8, path_buf, 0); switch (fd_prestat_dir_name(fd, path_buf.ptr, preopen_len)) { ESUCCESS => {}, else => |err| return os.unexpectedErrno(err), } const preopen = Preopen.new(fd, PreopenType{ .Dir = path_buf }); try self.buffer.append(preopen); fd += 1; } } /// Find preopen by type. If the preopen exists, return it. /// Otherwise, return `null`. pub fn find(self: Self, preopen_type: PreopenType) ?*const Preopen { for (self.buffer.items) |*preopen| { if (preopen.@"type".eql(preopen_type)) { return preopen; } } return null; } /// Return the inner buffer as read-only slice. pub fn asSlice(self: Self) []const Preopen { return self.buffer.items; } /// The caller owns the returned memory. ArrayList becomes empty. pub fn toOwnedSlice(self: *Self) []Preopen { return self.buffer.toOwnedSlice(); } }; test "extracting WASI preopens" { if (@import("builtin").os.tag != .wasi) return error.SkipZigTest; var preopens = PreopenList.init(std.testing.allocator); defer preopens.deinit(); try preopens.populate(); std.testing.expectEqual(@as(usize, 1), preopens.asSlice().len); const preopen = preopens.find(PreopenType{ .Dir = "." }) orelse unreachable; std.testing.expect(preopen.@"type".eql(PreopenType{ .Dir = "." })); std.testing.expectEqual(@as(usize, 3), preopen.fd); }
lib/std/fs/wasi.zig
const Emit = @This(); const std = @import("std"); const math = std.math; const Mir = @import("Mir.zig"); const bits = @import("bits.zig"); const link = @import("../../link.zig"); const Module = @import("../../Module.zig"); const ErrorMsg = Module.ErrorMsg; const assert = std.debug.assert; const DW = std.dwarf; const leb128 = std.leb; const Instruction = bits.Instruction; const Register = bits.Register; const DebugInfoOutput = @import("../../codegen.zig").DebugInfoOutput; mir: Mir, bin_file: *link.File, debug_output: DebugInfoOutput, target: *const std.Target, err_msg: ?*ErrorMsg = null, src_loc: Module.SrcLoc, code: *std.ArrayList(u8), prev_di_line: u32, prev_di_column: u32, /// Relative to the beginning of `code`. prev_di_pc: usize, const InnerError = error{ OutOfMemory, EmitFail, }; pub fn emitMir( emit: *Emit, ) InnerError!void { const mir_tags = emit.mir.instructions.items(.tag); // Emit machine code for (mir_tags) |tag, index| { const inst = @intCast(u32, index); switch (tag) { .add => try emit.mirRType(inst), .sub => try emit.mirRType(inst), .addi => try emit.mirIType(inst), .jalr => try emit.mirIType(inst), .ld => try emit.mirIType(inst), .sd => try emit.mirIType(inst), .ebreak => try emit.mirSystem(inst), .ecall => try emit.mirSystem(inst), .dbg_line => try emit.mirDbgLine(inst), .dbg_prologue_end => try emit.mirDebugPrologueEnd(), .dbg_epilogue_begin => try emit.mirDebugEpilogueBegin(), .mv => try emit.mirRR(inst), .nop => try emit.mirNop(inst), .ret => try emit.mirNop(inst), .lui => try emit.mirUType(inst), } } } pub fn deinit(emit: *Emit) void { emit.* = undefined; } fn writeInstruction(emit: *Emit, instruction: Instruction) !void { const endian = emit.target.cpu.arch.endian(); std.mem.writeInt(u32, try emit.code.addManyAsArray(4), instruction.toU32(), endian); } fn fail(emit: *Emit, comptime format: []const u8, args: anytype) InnerError { @setCold(true); assert(emit.err_msg == null); emit.err_msg = try ErrorMsg.create(emit.bin_file.allocator, emit.src_loc, format, args); return error.EmitFail; } fn dbgAdvancePCAndLine(self: *Emit, line: u32, column: u32) !void { const delta_line = @intCast(i32, line) - @intCast(i32, self.prev_di_line); const delta_pc: usize = self.code.items.len - self.prev_di_pc; switch (self.debug_output) { .dwarf => |dbg_out| { // TODO Look into using the DWARF special opcodes to compress this data. // It lets you emit single-byte opcodes that add different numbers to // both the PC and the line number at the same time. try dbg_out.dbg_line.ensureUnusedCapacity(11); dbg_out.dbg_line.appendAssumeCapacity(DW.LNS.advance_pc); leb128.writeULEB128(dbg_out.dbg_line.writer(), delta_pc) catch unreachable; if (delta_line != 0) { dbg_out.dbg_line.appendAssumeCapacity(DW.LNS.advance_line); leb128.writeILEB128(dbg_out.dbg_line.writer(), delta_line) catch unreachable; } dbg_out.dbg_line.appendAssumeCapacity(DW.LNS.copy); self.prev_di_pc = self.code.items.len; self.prev_di_line = line; self.prev_di_column = column; self.prev_di_pc = self.code.items.len; }, .plan9 => |dbg_out| { if (delta_pc <= 0) return; // only do this when the pc changes // we have already checked the target in the linker to make sure it is compatable const quant = @import("../../link/Plan9/aout.zig").getPCQuant(self.target.cpu.arch) catch unreachable; // increasing the line number try @import("../../link/Plan9.zig").changeLine(dbg_out.dbg_line, delta_line); // increasing the pc const d_pc_p9 = @intCast(i64, delta_pc) - quant; if (d_pc_p9 > 0) { // minus one because if its the last one, we want to leave space to change the line which is one quanta try dbg_out.dbg_line.append(@intCast(u8, @divExact(d_pc_p9, quant) + 128) - quant); if (dbg_out.pcop_change_index.*) |pci| dbg_out.dbg_line.items[pci] += 1; dbg_out.pcop_change_index.* = @intCast(u32, dbg_out.dbg_line.items.len - 1); } else if (d_pc_p9 == 0) { // we don't need to do anything, because adding the quant does it for us } else unreachable; if (dbg_out.start_line.* == null) dbg_out.start_line.* = self.prev_di_line; dbg_out.end_line.* = line; // only do this if the pc changed self.prev_di_line = line; self.prev_di_column = column; self.prev_di_pc = self.code.items.len; }, .none => {}, } } fn mirRType(emit: *Emit, inst: Mir.Inst.Index) !void { const tag = emit.mir.instructions.items(.tag)[inst]; const r_type = emit.mir.instructions.items(.data)[inst].r_type; switch (tag) { .add => try emit.writeInstruction(Instruction.add(r_type.rd, r_type.rs1, r_type.rs2)), .sub => try emit.writeInstruction(Instruction.sub(r_type.rd, r_type.rs1, r_type.rs2)), else => unreachable, } } fn mirIType(emit: *Emit, inst: Mir.Inst.Index) !void { const tag = emit.mir.instructions.items(.tag)[inst]; const i_type = emit.mir.instructions.items(.data)[inst].i_type; switch (tag) { .addi => try emit.writeInstruction(Instruction.addi(i_type.rd, i_type.rs1, i_type.imm12)), .jalr => try emit.writeInstruction(Instruction.jalr(i_type.rd, i_type.imm12, i_type.rs1)), .ld => try emit.writeInstruction(Instruction.ld(i_type.rd, i_type.imm12, i_type.rs1)), .sd => try emit.writeInstruction(Instruction.sd(i_type.rd, i_type.imm12, i_type.rs1)), else => unreachable, } } fn mirSystem(emit: *Emit, inst: Mir.Inst.Index) !void { const tag = emit.mir.instructions.items(.tag)[inst]; switch (tag) { .ebreak => try emit.writeInstruction(Instruction.ebreak), .ecall => try emit.writeInstruction(Instruction.ecall), else => unreachable, } } fn mirDbgLine(emit: *Emit, inst: Mir.Inst.Index) !void { const tag = emit.mir.instructions.items(.tag)[inst]; const dbg_line_column = emit.mir.instructions.items(.data)[inst].dbg_line_column; switch (tag) { .dbg_line => try emit.dbgAdvancePCAndLine(dbg_line_column.line, dbg_line_column.column), else => unreachable, } } fn mirDebugPrologueEnd(self: *Emit) !void { switch (self.debug_output) { .dwarf => |dbg_out| { try dbg_out.dbg_line.append(DW.LNS.set_prologue_end); try self.dbgAdvancePCAndLine(self.prev_di_line, self.prev_di_column); }, .plan9 => {}, .none => {}, } } fn mirDebugEpilogueBegin(self: *Emit) !void { switch (self.debug_output) { .dwarf => |dbg_out| { try dbg_out.dbg_line.append(DW.LNS.set_epilogue_begin); try self.dbgAdvancePCAndLine(self.prev_di_line, self.prev_di_column); }, .plan9 => {}, .none => {}, } } fn mirRR(emit: *Emit, inst: Mir.Inst.Index) !void { const tag = emit.mir.instructions.items(.tag)[inst]; const rr = emit.mir.instructions.items(.data)[inst].rr; switch (tag) { .mv => try emit.writeInstruction(Instruction.addi(rr.rd, rr.rs, 0)), else => unreachable, } } fn mirUType(emit: *Emit, inst: Mir.Inst.Index) !void { const tag = emit.mir.instructions.items(.tag)[inst]; const u_type = emit.mir.instructions.items(.data)[inst].u_type; switch (tag) { .lui => try emit.writeInstruction(Instruction.lui(u_type.rd, u_type.imm20)), else => unreachable, } } fn mirNop(emit: *Emit, inst: Mir.Inst.Index) !void { const tag = emit.mir.instructions.items(.tag)[inst]; switch (tag) { .nop => try emit.writeInstruction(Instruction.addi(.zero, .zero, 0)), .ret => try emit.writeInstruction(Instruction.jalr(.zero, 0, .ra)), else => unreachable, } }
src/arch/riscv64/Emit.zig
const std = @import("std"); const input = @import("input.zig"); pub fn run(stdout: anytype) anyerror!void { { var input_ = try input.readFile("inputs/day9"); defer input_.deinit(); const result = try part1(&input_); try stdout.print("9a: {}\n", .{ result }); std.debug.assert(result == 570); } { var input_ = try input.readFile("inputs/day9"); defer input_.deinit(); const result = try part2(&input_); try stdout.print("9b: {}\n", .{ result }); std.debug.assert(result == 899392); } } const num_input_rows = 100; const num_input_cols = 100; const Part1Result = std.math.IntFittingRange(0, num_input_rows * num_input_cols * (1 + 9)); fn part1(input_: anytype) !Part1Result { var map_view: [3][1 + num_input_cols + 1]u8 = [_][1 + num_input_cols + 1]u8 { [_]u8 { '9' } ** (1 + num_input_cols + 1), } ** 3; var first_row: usize = 0; var result: Part1Result = 0; while (true) { if (try input_.next()) |line| { std.mem.copy(u8, map_view[(first_row + 2) % 3][1..(1 + num_input_cols)], line); part1_inner(map_view, first_row, &result); } else { std.mem.set(u8, map_view[(first_row + 2) % 3][1..(1 + num_input_cols)], '9'); part1_inner(map_view, first_row, &result); break; } first_row = (first_row + 1) % 3; } return result; } fn part1_inner( map_view: [3][1 + num_input_cols + 1]u8, first_row: usize, result: *Part1Result, ) void { const prev_row = &map_view[first_row]; const curr_row = &map_view[(first_row + 1) % 3]; const next_row = &map_view[(first_row + 2) % 3]; for (curr_row[1..(1 + num_input_cols)]) |height, col_i| { if (height < curr_row[col_i] and height < curr_row[col_i + 2] and height < prev_row[col_i + 1] and height < next_row[col_i + 1]) { result.* += 1 + (height - '0'); } } } const Part2Result = std.math.IntFittingRange(0, (num_input_rows * num_input_cols / 3) * (num_input_rows * num_input_cols / 3) * (num_input_rows * num_input_cols / 3)); fn part2(input_: anytype) !Part2Result { const BasinSize = std.math.IntFittingRange(0, num_input_rows * num_input_cols); const Spot = enum { wall, basin_unmarked, basin_marked, }; var map: [1 + num_input_rows + 1][1 + num_input_cols + 1]Spot = [_][1 + num_input_cols + 1]Spot { [_]Spot { .wall } ** (1 + num_input_cols + 1) } ** (1 + num_input_rows + 1); { var row_i: usize = 1; while (try input_.next()) |line| { for (line) |c, col_i| { if (c != '9') { map[row_i][col_i + 1] = .basin_unmarked; } } row_i += 1; } } var basins = [_]BasinSize { 1 } ** 4; var smallest_basin_i: usize = 0; var find_new_basin_row_i: usize = 1; var find_new_basin_col_i: usize = 1; while (find_new_basin_row_i < (1 + num_input_rows)) : (find_new_basin_row_i += 1) { const find_new_basin_row = &map[find_new_basin_row_i]; while (find_new_basin_col_i < (1 + num_input_cols)) : (find_new_basin_col_i += 1) { const find_new_basin_spot = &find_new_basin_row[find_new_basin_col_i]; if (find_new_basin_spot.* != .basin_unmarked) { continue; } // Found an unmarked basin spot. This is the first spot in a new basin. find_new_basin_spot.* = .basin_marked; basins[smallest_basin_i] = 1; // Find all other spots in this basin while (true) { var found_another_spot = false; var row_i = find_new_basin_row_i; var col_i = find_new_basin_col_i; while (row_i < (1 + num_input_rows)) : (row_i += 1) { const row = &map[row_i]; while (col_i < (1 + num_input_cols)) : (col_i += 1) { const spot = &row[col_i]; if (spot.* != .basin_unmarked) { continue; } if ( map[row_i][col_i - 1] == .basin_marked or map[row_i][col_i + 1] == .basin_marked or map[row_i - 1][col_i] == .basin_marked or map[row_i + 1][col_i] == .basin_marked ) { spot.* = .basin_marked; basins[smallest_basin_i] += 1; found_another_spot = true; } } col_i = 1; } if (!found_another_spot) { // No more spots in this basin break; } } smallest_basin_i = std.sort.argMin(BasinSize, basins[0..], {}, comptime std.sort.asc(BasinSize)).?; } find_new_basin_col_i = 1; } var result: Part2Result = 1; for (basins) |basin, basin_i| { if (basin_i != smallest_basin_i) { result *= basin; } } return result; } test "day 9 example 1" { const input_ = \\2199943210 \\3987894921 \\9856789892 \\8767896789 \\9899965678 ; try std.testing.expectEqual(@as(Part1Result, 2 + 1 + 6 + 6), try part1(&input.readString(input_))); try std.testing.expectEqual(@as(Part2Result, 9 * 14 * 9), try part2(&input.readString(input_))); }
src/day9.zig
const ImageInStream = zigimg.ImageInStream; const ImageSeekStream = zigimg.ImageSeekStream; const PixelFormat = zigimg.PixelFormat; const assert = std.debug.assert; const bmp = zigimg.bmp; const color = zigimg.color; const errors = zigimg.errors; const std = @import("std"); const testing = std.testing; const zigimg = @import("zigimg"); usingnamespace @import("helpers.zig"); const MemoryRGBABitmap = @embedFile("fixtures/bmp/windows_rgba_v5.bmp"); fn verifyBitmapRGBAV5(theBitmap: bmp.Bitmap, pixels: color.ColorStorage) void { expectEq(theBitmap.fileHeader.size, 153738); expectEq(theBitmap.fileHeader.reserved, 0); expectEq(theBitmap.fileHeader.pixelOffset, 138); expectEq(theBitmap.width(), 240); expectEq(theBitmap.height(), 160); expectEqSlice(u8, @tagName(theBitmap.infoHeader), "V5"); _ = switch (theBitmap.infoHeader) { .V5 => |v5Header| { expectEq(v5Header.headerSize, bmp.BitmapInfoHeaderV5.HeaderSize); expectEq(v5Header.width, 240); expectEq(v5Header.height, 160); expectEq(v5Header.colorPlane, 1); expectEq(v5Header.bitCount, 32); expectEq(v5Header.compressionMethod, bmp.CompressionMethod.Bitfields); expectEq(v5Header.imageRawSize, 240 * 160 * 4); expectEq(v5Header.horizontalResolution, 2835); expectEq(v5Header.verticalResolution, 2835); expectEq(v5Header.paletteSize, 0); expectEq(v5Header.importantColors, 0); expectEq(v5Header.redMask, 0x00ff0000); expectEq(v5Header.greenMask, 0x0000ff00); expectEq(v5Header.blueMask, 0x000000ff); expectEq(v5Header.alphaMask, 0xff000000); expectEq(v5Header.colorSpace, bmp.BitmapColorSpace.sRgb); expectEq(v5Header.cieEndPoints.red.x, 0); expectEq(v5Header.cieEndPoints.red.y, 0); expectEq(v5Header.cieEndPoints.red.z, 0); expectEq(v5Header.cieEndPoints.green.x, 0); expectEq(v5Header.cieEndPoints.green.y, 0); expectEq(v5Header.cieEndPoints.green.z, 0); expectEq(v5Header.cieEndPoints.blue.x, 0); expectEq(v5Header.cieEndPoints.blue.y, 0); expectEq(v5Header.cieEndPoints.blue.z, 0); expectEq(v5Header.gammaRed, 0); expectEq(v5Header.gammaGreen, 0); expectEq(v5Header.gammaBlue, 0); expectEq(v5Header.intent, bmp.BitmapIntent.Graphics); expectEq(v5Header.profileData, 0); expectEq(v5Header.profileSize, 0); expectEq(v5Header.reserved, 0); }, else => unreachable, }; testing.expect(pixels == .Argb32); expectEq(pixels.len(), 240 * 160); const firstPixel = pixels.Argb32[0]; expectEq(firstPixel.R, 0xFF); expectEq(firstPixel.G, 0xFF); expectEq(firstPixel.B, 0xFF); expectEq(firstPixel.A, 0xFF); const secondPixel = pixels.Argb32[1]; expectEq(secondPixel.R, 0xFF); expectEq(secondPixel.G, 0x00); expectEq(secondPixel.B, 0x00); expectEq(secondPixel.A, 0xFF); const thirdPixel = pixels.Argb32[2]; expectEq(thirdPixel.R, 0x00); expectEq(thirdPixel.G, 0xFF); expectEq(thirdPixel.B, 0x00); expectEq(thirdPixel.A, 0xFF); const fourthPixel = pixels.Argb32[3]; expectEq(fourthPixel.R, 0x00); expectEq(fourthPixel.G, 0x00); expectEq(fourthPixel.B, 0xFF); expectEq(fourthPixel.A, 0xFF); const coloredPixel = pixels.Argb32[(22 * 240) + 16]; expectEq(coloredPixel.R, 195); expectEq(coloredPixel.G, 195); expectEq(coloredPixel.B, 255); expectEq(coloredPixel.A, 255); } test "Read simple version 4 24-bit RGB bitmap" { const file = try testOpenFile(testing.allocator, "tests/fixtures/bmp/simple_v4.bmp"); defer file.close(); var fileInStream = file.inStream(); var fileSeekStream = file.seekableStream(); var theBitmap = bmp.Bitmap{}; const pixels = try theBitmap.read(testing.allocator, @ptrCast(*ImageInStream, &fileInStream.stream), @ptrCast(*ImageSeekStream, &fileSeekStream.stream)); defer pixels.deinit(testing.allocator); expectEq(theBitmap.width(), 8); expectEq(theBitmap.height(), 1); testing.expect(pixels == .Rgb24); const red = pixels.Rgb24[0]; expectEq(red.R, 0xFF); expectEq(red.G, 0x00); expectEq(red.B, 0x00); const green = pixels.Rgb24[1]; expectEq(green.R, 0x00); expectEq(green.G, 0xFF); expectEq(green.B, 0x00); const blue = pixels.Rgb24[2]; expectEq(blue.R, 0x00); expectEq(blue.G, 0x00); expectEq(blue.B, 0xFF); const cyan = pixels.Rgb24[3]; expectEq(cyan.R, 0x00); expectEq(cyan.G, 0xFF); expectEq(cyan.B, 0xFF); const magenta = pixels.Rgb24[4]; expectEq(magenta.R, 0xFF); expectEq(magenta.G, 0x00); expectEq(magenta.B, 0xFF); const yellow = pixels.Rgb24[5]; expectEq(yellow.R, 0xFF); expectEq(yellow.G, 0xFF); expectEq(yellow.B, 0x00); const black = pixels.Rgb24[6]; expectEq(black.R, 0x00); expectEq(black.G, 0x00); expectEq(black.B, 0x00); const white = pixels.Rgb24[7]; expectEq(white.R, 0xFF); expectEq(white.G, 0xFF); expectEq(white.B, 0xFF); } test "Read a valid version 5 RGBA bitmap from file" { // var theBitmap = try bmp.Bitmap.fromFile(testing.allocator, "tests/fixtures/bmp/windows_rgba_v5.bmp"); // verifyBitmapRGBAV5(&theBitmap); const file = try testOpenFile(testing.allocator, "tests/fixtures/bmp/windows_rgba_v5.bmp"); defer file.close(); var fileInStream = file.inStream(); var fileSeekStream = file.seekableStream(); var theBitmap = bmp.Bitmap{}; const pixels = try theBitmap.read(testing.allocator, @ptrCast(*ImageInStream, &fileInStream.stream), @ptrCast(*ImageSeekStream, &fileSeekStream.stream)); defer pixels.deinit(testing.allocator); verifyBitmapRGBAV5(theBitmap, pixels); } test "Read a valid version 5 RGBA bitmap from memory" { var memoryInStream = std.io.SliceSeekableInStream.init(MemoryRGBABitmap); var theBitmap = bmp.Bitmap{}; // TODO: Replace with something better when available const pixels = try theBitmap.read(testing.allocator, @ptrCast(*ImageInStream, &memoryInStream.stream), @ptrCast(*ImageSeekStream, &memoryInStream.seekable_stream)); defer pixels.deinit(testing.allocator); verifyBitmapRGBAV5(theBitmap, pixels); } test "Should error when reading an invalid file" { const file = try testOpenFile(testing.allocator, "tests/fixtures/png/notbmp.png"); defer file.close(); var fileInStream = file.inStream(); var fileSeekStream = file.seekableStream(); var theBitmap = bmp.Bitmap{}; const invalidFile = theBitmap.read(testing.allocator, @ptrCast(*ImageInStream, &fileInStream.stream), @ptrCast(*ImageSeekStream, &fileSeekStream.stream)); expectError(invalidFile, errors.ImageError.InvalidMagicHeader); }
tests/bmp_test.zig
const std = @import("std"); const util = @import("util"); const Cell = struct { height: u8, basin: bool, }; const Map = struct { data: std.ArrayList(std.ArrayList(Cell)), const Self = @This(); fn init(alloc: *std.mem.Allocator) Self { return .{ .data = std.ArrayList(std.ArrayList(Cell)).init(alloc), }; } fn addRow(self: *Self) !*std.ArrayList(Cell) { return self.data.addOne(); } fn get(self: *const Self, y: isize, x: isize) Cell { if (x < 0 or y < 0 or x >= self.data.items[0].items.len or y >= self.data.items.len) { return .{ .height = std.math.maxInt(u8), .basin = false }; } else { return self.data.items[@intCast(usize, y)].items[@intCast(usize, x)]; } } fn get_basin_size(self: *Self, y: isize, x: isize) u64 { var size: u64 = 1; const here = self.get(y, x).height; self.data.items[@intCast(usize, y)].items[@intCast(usize, x)].basin = true; const above = self.get(y - 1, x); if (above.height < 9 and above.height > here and !above.basin) { size += self.get_basin_size(y - 1, x); } const below = self.get(y + 1, x); if (below.height < 9 and below.height > here and !below.basin) { size += self.get_basin_size(y + 1, x); } const left = self.get(y, x - 1); if (left.height < 9 and left.height > here and !left.basin) { size += self.get_basin_size(y, x - 1); } const right = self.get(y, x + 1); if (right.height < 9 and right.height > here and !right.basin) { size += self.get_basin_size(y, x + 1); } return size; } }; fn parse_input(input: []const u8, alloc: *std.mem.Allocator) !Map { var map = Map.init(alloc); var lines = std.mem.tokenize(u8, input, "\n"); while (lines.next()) |line| { var row = try map.addRow(); row.* = std.ArrayList(Cell).init(alloc); for (line) |height| { try row.append(.{ .height = height - '0', .basin = false }); } } return map; } pub fn part1(input: []const u8) !u64 { var arena = std.heap.ArenaAllocator.init(std.heap.page_allocator); const alloc = &arena.allocator; defer arena.deinit(); var map = try parse_input(input, alloc); var total_risk: u64 = 0; for (map.data.items) |row, y| { for (row.items) |cell, x| { const here = cell.height; const above = map.get(@intCast(isize, y) - 1, @intCast(isize, x)).height; const below = map.get(@intCast(isize, y) + 1, @intCast(isize, x)).height; const left = map.get(@intCast(isize, y), @intCast(isize, x) - 1).height; const right = map.get(@intCast(isize, y), @intCast(isize, x) + 1).height; if (here < above and here < below and here < left and here < right) { total_risk += here + 1; } } } return total_risk; } pub fn part2(input: []const u8) !u64 { var arena = std.heap.ArenaAllocator.init(std.heap.page_allocator); const alloc = &arena.allocator; defer arena.deinit(); var map = try parse_input(input, alloc); var basins = std.ArrayList(u64).init(alloc); for (map.data.items) |row, y| { for (row.items) |cell, x| { const here = cell.height; const above = map.get(@intCast(isize, y) - 1, @intCast(isize, x)).height; const below = map.get(@intCast(isize, y) + 1, @intCast(isize, x)).height; const left = map.get(@intCast(isize, y), @intCast(isize, x) - 1).height; const right = map.get(@intCast(isize, y), @intCast(isize, x) + 1).height; if (here < above and here < below and here < left and here < right) { try basins.append(map.get_basin_size(@intCast(isize, y), @intCast(isize, x))); } } } std.sort.sort(u64, basins.items, {}, comptime std.sort.desc(u64)); return basins.items[0] * basins.items[1] * basins.items[2]; } test "day 9 part 1" { const test_input = \\2199943210 \\3987894921 \\9856789892 \\8767896789 \\9899965678 ; try std.testing.expectEqual(part1(test_input), 15); } test "day 9 part 2" { const test_input = \\2199943210 \\3987894921 \\9856789892 \\8767896789 \\9899965678 ; try std.testing.expectEqual(part2(test_input), 1134); }
zig/src/day9.zig
const std = @import("std"); const Allocator = std.mem.Allocator; const List = std.ArrayList; const Map = std.AutoHashMap; const StrMap = std.StringHashMap; const BitSet = std.DynamicBitSet; const Str = []const u8; const util = @import("util.zig"); const gpa = util.gpa; const data = @embedFile("../data/day14.txt"); // const data = @embedFile("../data/day14-tst.txt"); pub fn main() !void { var ping = List(u8).init(gpa); var pong = List(u8).init(gpa); var dict = StrMap(u8).init(gpa); var part2_ping = StrMap(usize).init(gpa); var part2_pong = StrMap(usize).init(gpa); var it = tokenize(u8, data, "\r\n"); var str = it.next().?; while (it.next()) |line| { var rule = tokenize(u8, line, " ->"); var s = rule.next().?; var c = rule.next().?; try dict.put(s, c[0]); try part2_ping.put(s, 0); try part2_pong.put(s, 0); } // Part1 try ping.resize(str.len); std.mem.copy(u8, ping.items, str); for ([_]u0{0} ** 10) |_| { try pong.resize(ping.items.len * 2 - 1); polymerize(ping.items, pong.items, dict); std.mem.swap(List(u8), &ping, &pong); } var counts = [_]usize{0} ** 26; for (ping.items) |c| { counts[c - 'A'] += 1; } var minv: usize = std.math.maxInt(usize); var maxv: usize = 0; for (counts) |i| { if (i == 0) continue; maxv = max(maxv, i); minv = min(minv, i); } print("{}\n", .{maxv - minv}); var i: usize = 0; while (i < str.len - 1) : (i += 1) { var v = part2_ping.getPtr(str[i .. i + 2]).?; v.* += 1; } // Part2 for ([_]u0{0} ** 40) |_| { var value_it = part2_pong.valueIterator(); while (value_it.next()) |v| { v.* = 0; } var map_it = part2_ping.iterator(); while (map_it.next()) |entry| { if (entry.value_ptr.* == 0) continue; var in0 = entry.key_ptr.*[0]; var in1 = entry.key_ptr.*[1]; var c = dict.get(entry.key_ptr.*).?; var key1 = [2]u8{ in0, c }; var key2 = [2]u8{ c, in1 }; var v1 = part2_pong.getPtr(key1[0..]).?; var v2 = part2_pong.getPtr(key2[0..]).?; v1.* += entry.value_ptr.*; v2.* += entry.value_ptr.*; } std.mem.swap(StrMap(usize), &part2_ping, &part2_pong); } minv = std.math.maxInt(usize); maxv = 0; std.mem.set(usize, counts[0..], 0); var map_it = part2_ping.iterator(); while (map_it.next()) |entry| { if (entry.value_ptr.* == 0) continue; counts[entry.key_ptr.*[0] - 'A'] += entry.value_ptr.*; counts[entry.key_ptr.*[1] - 'A'] += entry.value_ptr.*; } counts[str[0] - 'A'] += 1; counts[str[str.len - 1] - 'A'] += 1; for (counts) |n| { if (n == 0) continue; maxv = max(maxv, n / 2); minv = min(minv, n / 2); } print("{}\n", .{maxv - minv}); } fn polymerize(ping: []u8, pong: []u8, dict: StrMap(u8)) void { var i: usize = 0; while (i < ping.len - 1) : (i += 1) { pong[i * 2] = ping[i]; pong[i * 2 + 1] = dict.get(ping[i .. i + 2]).?; } pong[i * 2] = ping[i]; } // Useful stdlib functions const tokenize = std.mem.tokenize; const split = std.mem.split; const indexOf = std.mem.indexOfScalar; const indexOfAny = std.mem.indexOfAny; const indexOfStr = std.mem.indexOfPosLinear; const lastIndexOf = std.mem.lastIndexOfScalar; const lastIndexOfAny = std.mem.lastIndexOfAny; const lastIndexOfStr = std.mem.lastIndexOfLinear; const trim = std.mem.trim; const sliceMin = std.mem.min; const sliceMax = std.mem.max; const parseInt = std.fmt.parseInt; const parseFloat = std.fmt.parseFloat; const min = std.math.min; const min3 = std.math.min3; const max = std.math.max; const max3 = std.math.max3; const print = std.debug.print; const assert = std.debug.assert; const sort = std.sort.sort; const asc = std.sort.asc; const desc = std.sort.desc;
src/day14.zig
pub const IOCTL_STORAGE_BASE = @as(u32, 45); pub const IOCTL_SCMBUS_BASE = @as(u32, 89); pub const IOCTL_DISK_BASE = @as(u32, 7); pub const IOCTL_CHANGER_BASE = @as(u32, 48); pub const FILE_SPECIAL_ACCESS = @as(u32, 0); pub const FILE_DEVICE_UNKNOWN = @as(u32, 34); pub const GUID_DEVINTERFACE_DISK = Guid.initString("53f56307-b6bf-11d0-94f2-00a0c91efb8b"); pub const GUID_DEVINTERFACE_CDROM = Guid.initString("53f56308-b6bf-11d0-94f2-00a0c91efb8b"); pub const GUID_DEVINTERFACE_PARTITION = Guid.initString("53f5630a-b6bf-11d0-94f2-00a0c91efb8b"); pub const GUID_DEVINTERFACE_TAPE = Guid.initString("53f5630b-b6bf-11d0-94f2-00a0c91efb8b"); pub const GUID_DEVINTERFACE_WRITEONCEDISK = Guid.initString("53f5630c-b6bf-11d0-94f2-00a0c91efb8b"); pub const GUID_DEVINTERFACE_VOLUME = Guid.initString("53f5630d-b6bf-11d0-94f2-00a0c91efb8b"); pub const GUID_DEVINTERFACE_MEDIUMCHANGER = Guid.initString("53f56310-b6bf-11d0-94f2-00a0c91efb8b"); pub const GUID_DEVINTERFACE_FLOPPY = Guid.initString("53f56311-b6bf-11d0-94f2-00a0c91efb8b"); pub const GUID_DEVINTERFACE_CDCHANGER = Guid.initString("53f56312-b6bf-11d0-94f2-00a0c91efb8b"); pub const GUID_DEVINTERFACE_STORAGEPORT = Guid.initString("2accfe60-c130-11d2-b082-00a0c91efb8b"); pub const GUID_DEVINTERFACE_VMLUN = Guid.initString("6f416619-9f29-42a5-b20b-37e219ca02b0"); pub const GUID_DEVINTERFACE_SES = Guid.initString("1790c9ec-47d5-4df3-b5af-9adf3cf23e48"); pub const GUID_DEVINTERFACE_ZNSDISK = Guid.initString("b87941c5-ffdb-43c7-b6b1-20b632f0b109"); pub const GUID_DEVINTERFACE_SERVICE_VOLUME = Guid.initString("6ead3d82-25ec-46bc-b7fd-c1f0df8f5037"); pub const GUID_DEVINTERFACE_HIDDEN_VOLUME = Guid.initString("7f108a28-9833-4b3b-b780-2c6b5fa5c062"); pub const GUID_DEVINTERFACE_UNIFIED_ACCESS_RPMB = Guid.initString("27447c21-bcc3-4d07-a05b-a3395bb4eee7"); pub const GUID_DEVICEDUMP_STORAGE_DEVICE = Guid.initString("d8e2592f-1aab-4d56-a746-1f7585df40f4"); pub const GUID_DEVICEDUMP_DRIVER_STORAGE_PORT = Guid.initString("da82441d-7142-4bc1-b844-0807c5a4b67f"); pub const DEVPKEY_Storage_Portable = PROPERTYKEY { .fmtid = Guid.initString("4d1ebee8-0803-4774-9842-b77db50265e9"), .pid = 2 }; pub const DEVPKEY_Storage_Removable_Media = PROPERTYKEY { .fmtid = Guid.initString("4d1ebee8-0803-4774-9842-b77db50265e9"), .pid = 3 }; pub const DEVPKEY_Storage_System_Critical = PROPERTYKEY { .fmtid = Guid.initString("4d1ebee8-0803-4774-9842-b77db50265e9"), .pid = 4 }; pub const DEVPKEY_Storage_Disk_Number = PROPERTYKEY { .fmtid = Guid.initString("4d1ebee8-0803-4774-9842-b77db50265e9"), .pid = 5 }; pub const DEVPKEY_Storage_Partition_Number = PROPERTYKEY { .fmtid = Guid.initString("4d1ebee8-0803-4774-9842-b77db50265e9"), .pid = 6 }; pub const DEVPKEY_Storage_Mbr_Type = PROPERTYKEY { .fmtid = Guid.initString("4d1ebee8-0803-4774-9842-b77db50265e9"), .pid = 7 }; pub const DEVPKEY_Storage_Gpt_Type = PROPERTYKEY { .fmtid = Guid.initString("4d1ebee8-0803-4774-9842-b77db50265e9"), .pid = 8 }; pub const DEVPKEY_Storage_Gpt_Name = PROPERTYKEY { .fmtid = Guid.initString("4d1ebee8-0803-4774-9842-b77db50265e9"), .pid = 9 }; pub const IOCTL_STORAGE_CHECK_VERIFY = @as(u32, 2967552); pub const IOCTL_STORAGE_CHECK_VERIFY2 = @as(u32, 2951168); pub const IOCTL_STORAGE_MEDIA_REMOVAL = @as(u32, 2967556); pub const IOCTL_STORAGE_EJECT_MEDIA = @as(u32, 2967560); pub const IOCTL_STORAGE_LOAD_MEDIA = @as(u32, 2967564); pub const IOCTL_STORAGE_LOAD_MEDIA2 = @as(u32, 2951180); pub const IOCTL_STORAGE_RESERVE = @as(u32, 2967568); pub const IOCTL_STORAGE_RELEASE = @as(u32, 2967572); pub const IOCTL_STORAGE_FIND_NEW_DEVICES = @as(u32, 2967576); pub const IOCTL_STORAGE_MANAGE_BYPASS_IO = @as(u32, 2951360); pub const IOCTL_STORAGE_EJECTION_CONTROL = @as(u32, 2951488); pub const IOCTL_STORAGE_MCN_CONTROL = @as(u32, 2951492); pub const IOCTL_STORAGE_GET_MEDIA_TYPES = @as(u32, 2952192); pub const IOCTL_STORAGE_GET_MEDIA_TYPES_EX = @as(u32, 2952196); pub const IOCTL_STORAGE_GET_MEDIA_SERIAL_NUMBER = @as(u32, 2952208); pub const IOCTL_STORAGE_GET_HOTPLUG_INFO = @as(u32, 2952212); pub const IOCTL_STORAGE_SET_HOTPLUG_INFO = @as(u32, 3001368); pub const IOCTL_STORAGE_RESET_BUS = @as(u32, 2969600); pub const IOCTL_STORAGE_RESET_DEVICE = @as(u32, 2969604); pub const IOCTL_STORAGE_BREAK_RESERVATION = @as(u32, 2969620); pub const IOCTL_STORAGE_PERSISTENT_RESERVE_IN = @as(u32, 2969624); pub const IOCTL_STORAGE_PERSISTENT_RESERVE_OUT = @as(u32, 3002396); pub const IOCTL_STORAGE_GET_DEVICE_NUMBER = @as(u32, 2953344); pub const IOCTL_STORAGE_GET_DEVICE_NUMBER_EX = @as(u32, 2953348); pub const IOCTL_STORAGE_PREDICT_FAILURE = @as(u32, 2953472); pub const IOCTL_STORAGE_FAILURE_PREDICTION_CONFIG = @as(u32, 2953476); pub const IOCTL_STORAGE_GET_COUNTERS = @as(u32, 2953480); pub const IOCTL_STORAGE_READ_CAPACITY = @as(u32, 2969920); pub const IOCTL_STORAGE_GET_DEVICE_TELEMETRY = @as(u32, 3002816); pub const IOCTL_STORAGE_DEVICE_TELEMETRY_NOTIFY = @as(u32, 3002820); pub const IOCTL_STORAGE_DEVICE_TELEMETRY_QUERY_CAPS = @as(u32, 3002824); pub const IOCTL_STORAGE_GET_DEVICE_TELEMETRY_RAW = @as(u32, 3002828); pub const IOCTL_STORAGE_SET_TEMPERATURE_THRESHOLD = @as(u32, 3002880); pub const IOCTL_STORAGE_PROTOCOL_COMMAND = @as(u32, 3003328); pub const IOCTL_STORAGE_SET_PROPERTY = @as(u32, 2987004); pub const IOCTL_STORAGE_QUERY_PROPERTY = @as(u32, 2954240); pub const IOCTL_STORAGE_MANAGE_DATA_SET_ATTRIBUTES = @as(u32, 2987012); pub const IOCTL_STORAGE_GET_LB_PROVISIONING_MAP_RESOURCES = @as(u32, 2970632); pub const IOCTL_STORAGE_REINITIALIZE_MEDIA = @as(u32, 2987584); pub const IOCTL_STORAGE_GET_BC_PROPERTIES = @as(u32, 2971648); pub const IOCTL_STORAGE_ALLOCATE_BC_STREAM = @as(u32, 3004420); pub const IOCTL_STORAGE_FREE_BC_STREAM = @as(u32, 3004424); pub const IOCTL_STORAGE_CHECK_PRIORITY_HINT_SUPPORT = @as(u32, 2955392); pub const IOCTL_STORAGE_START_DATA_INTEGRITY_CHECK = @as(u32, 3004548); pub const IOCTL_STORAGE_STOP_DATA_INTEGRITY_CHECK = @as(u32, 3004552); pub const OBSOLETE_IOCTL_STORAGE_RESET_BUS = @as(u32, 3002368); pub const OBSOLETE_IOCTL_STORAGE_RESET_DEVICE = @as(u32, 3002372); pub const IOCTL_STORAGE_FIRMWARE_GET_INFO = @as(u32, 2956288); pub const IOCTL_STORAGE_FIRMWARE_DOWNLOAD = @as(u32, 3005444); pub const IOCTL_STORAGE_FIRMWARE_ACTIVATE = @as(u32, 3005448); pub const IOCTL_STORAGE_ENABLE_IDLE_POWER = @as(u32, 2956416); pub const IOCTL_STORAGE_GET_IDLE_POWERUP_REASON = @as(u32, 2956420); pub const IOCTL_STORAGE_POWER_ACTIVE = @as(u32, 2956424); pub const IOCTL_STORAGE_POWER_IDLE = @as(u32, 2956428); pub const IOCTL_STORAGE_EVENT_NOTIFICATION = @as(u32, 2956432); pub const IOCTL_STORAGE_DEVICE_POWER_CAP = @as(u32, 2956436); pub const IOCTL_STORAGE_RPMB_COMMAND = @as(u32, 2956440); pub const IOCTL_STORAGE_ATTRIBUTE_MANAGEMENT = @as(u32, 3005596); pub const IOCTL_STORAGE_DIAGNOSTIC = @as(u32, 2956448); pub const IOCTL_STORAGE_GET_PHYSICAL_ELEMENT_STATUS = @as(u32, 2956452); pub const IOCTL_STORAGE_REMOVE_ELEMENT_AND_TRUNCATE = @as(u32, 2956480); pub const IOCTL_STORAGE_GET_DEVICE_INTERNAL_LOG = @as(u32, 2956484); pub const STORAGE_DEVICE_FLAGS_RANDOM_DEVICEGUID_REASON_CONFLICT = @as(u32, 1); pub const STORAGE_DEVICE_FLAGS_RANDOM_DEVICEGUID_REASON_NOHWID = @as(u32, 2); pub const STORAGE_DEVICE_FLAGS_PAGE_83_DEVICEGUID = @as(u32, 4); pub const RECOVERED_WRITES_VALID = @as(u32, 1); pub const UNRECOVERED_WRITES_VALID = @as(u32, 2); pub const RECOVERED_READS_VALID = @as(u32, 4); pub const UNRECOVERED_READS_VALID = @as(u32, 8); pub const WRITE_COMPRESSION_INFO_VALID = @as(u32, 16); pub const READ_COMPRESSION_INFO_VALID = @as(u32, 32); pub const TAPE_RETURN_STATISTICS = @as(i32, 0); pub const TAPE_RETURN_ENV_INFO = @as(i32, 1); pub const TAPE_RESET_STATISTICS = @as(i32, 2); pub const MEDIA_ERASEABLE = @as(u32, 1); pub const MEDIA_WRITE_ONCE = @as(u32, 2); pub const MEDIA_READ_ONLY = @as(u32, 4); pub const MEDIA_READ_WRITE = @as(u32, 8); pub const MEDIA_WRITE_PROTECTED = @as(u32, 256); pub const MEDIA_CURRENTLY_MOUNTED = @as(u32, 2147483648); pub const STORAGE_FAILURE_PREDICTION_CONFIG_V1 = @as(u32, 1); pub const SRB_TYPE_SCSI_REQUEST_BLOCK = @as(u32, 0); pub const SRB_TYPE_STORAGE_REQUEST_BLOCK = @as(u32, 1); pub const STORAGE_ADDRESS_TYPE_BTL8 = @as(u32, 0); pub const STORAGE_RPMB_DESCRIPTOR_VERSION_1 = @as(u32, 1); pub const STORAGE_RPMB_MINIMUM_RELIABLE_WRITE_SIZE = @as(u32, 512); pub const STORAGE_CRYPTO_CAPABILITY_VERSION_1 = @as(u32, 1); pub const STORAGE_CRYPTO_DESCRIPTOR_VERSION_1 = @as(u32, 1); pub const STORAGE_TIER_NAME_LENGTH = @as(u32, 256); pub const STORAGE_TIER_DESCRIPTION_LENGTH = @as(u32, 512); pub const STORAGE_TIER_FLAG_NO_SEEK_PENALTY = @as(u32, 131072); pub const STORAGE_TIER_FLAG_WRITE_BACK_CACHE = @as(u32, 2097152); pub const STORAGE_TIER_FLAG_READ_CACHE = @as(u32, 4194304); pub const STORAGE_TIER_FLAG_PARITY = @as(u32, 8388608); pub const STORAGE_TIER_FLAG_SMR = @as(u32, 16777216); pub const STORAGE_TEMPERATURE_VALUE_NOT_REPORTED = @as(u32, 32768); pub const STORAGE_TEMPERATURE_THRESHOLD_FLAG_ADAPTER_REQUEST = @as(u32, 1); pub const STORAGE_COMPONENT_ROLE_CACHE = @as(u32, 1); pub const STORAGE_COMPONENT_ROLE_TIERING = @as(u32, 2); pub const STORAGE_COMPONENT_ROLE_DATA = @as(u32, 4); pub const STORAGE_ATTRIBUTE_BYTE_ADDRESSABLE_IO = @as(u32, 1); pub const STORAGE_ATTRIBUTE_BLOCK_IO = @as(u32, 2); pub const STORAGE_ATTRIBUTE_DYNAMIC_PERSISTENCE = @as(u32, 4); pub const STORAGE_ATTRIBUTE_VOLATILE = @as(u32, 8); pub const STORAGE_ATTRIBUTE_ASYNC_EVENT_NOTIFICATION = @as(u32, 16); pub const STORAGE_ATTRIBUTE_PERF_SIZE_INDEPENDENT = @as(u32, 32); pub const STORAGE_DEVICE_MAX_OPERATIONAL_STATUS = @as(u32, 16); pub const STORAGE_ADAPTER_SERIAL_NUMBER_V1_MAX_LENGTH = @as(u32, 128); pub const DeviceDsmActionFlag_NonDestructive = @as(u32, 2147483648); pub const DEVICE_DSM_FLAG_ENTIRE_DATA_SET_RANGE = @as(u32, 1); pub const DEVICE_DSM_FLAG_TRIM_NOT_FS_ALLOCATED = @as(u32, 2147483648); pub const DEVICE_DSM_FLAG_TRIM_BYPASS_RZAT = @as(u32, 1073741824); pub const DEVICE_DSM_NOTIFY_FLAG_BEGIN = @as(u32, 1); pub const DEVICE_DSM_NOTIFY_FLAG_END = @as(u32, 2); pub const STORAGE_OFFLOAD_MAX_TOKEN_LENGTH = @as(u32, 512); pub const STORAGE_OFFLOAD_TOKEN_ID_LENGTH = @as(u32, 504); pub const STORAGE_OFFLOAD_TOKEN_TYPE_ZERO_DATA = @as(u32, 4294901761); pub const STORAGE_OFFLOAD_READ_RANGE_TRUNCATED = @as(u32, 1); pub const STORAGE_OFFLOAD_WRITE_RANGE_TRUNCATED = @as(u32, 1); pub const STORAGE_OFFLOAD_TOKEN_INVALID = @as(u32, 2); pub const DEVICE_DSM_FLAG_ALLOCATION_CONSOLIDATEABLE_ONLY = @as(u32, 1073741824); pub const DEVICE_DSM_PARAMETERS_V1 = @as(u32, 1); pub const DEVICE_DATA_SET_LBP_STATE_PARAMETERS_VERSION_V1 = @as(u32, 1); pub const DEVICE_DSM_FLAG_REPAIR_INPUT_TOPOLOGY_ID_PRESENT = @as(u32, 1073741824); pub const DEVICE_DSM_FLAG_REPAIR_OUTPUT_PARITY_EXTENT = @as(u32, 536870912); pub const DEVICE_DSM_FLAG_SCRUB_SKIP_IN_SYNC = @as(u32, 268435456); pub const DEVICE_DSM_FLAG_SCRUB_OUTPUT_PARITY_EXTENT = @as(u32, 536870912); pub const DEVICE_DSM_FLAG_PHYSICAL_ADDRESSES_OMIT_TOTAL_RANGES = @as(u32, 268435456); pub const DEVICE_DSM_PHYSICAL_ADDRESSES_OUTPUT_V1 = @as(u32, 1); pub const DEVICE_DSM_PHYSICAL_ADDRESSES_OUTPUT_VERSION_V1 = @as(u32, 1); pub const DEVICE_STORAGE_NO_ERRORS = @as(u32, 1); pub const DEVICE_DSM_RANGE_ERROR_OUTPUT_V1 = @as(u32, 1); pub const DEVICE_DSM_RANGE_ERROR_INFO_VERSION_V1 = @as(u32, 1); pub const IOCTL_STORAGE_BC_VERSION = @as(u32, 1); pub const STORAGE_PRIORITY_HINT_SUPPORTED = @as(u32, 1); pub const STORAGE_DIAGNOSTIC_FLAG_ADAPTER_REQUEST = @as(u32, 1); pub const ERROR_HISTORY_DIRECTORY_ENTRY_DEFAULT_COUNT = @as(u32, 8); pub const DEVICEDUMP_STRUCTURE_VERSION_V1 = @as(u32, 1); pub const DEVICEDUMP_MAX_IDSTRING = @as(u32, 32); pub const MAX_FW_BUCKET_ID_LENGTH = @as(u32, 132); pub const DDUMP_FLAG_DATA_READ_FROM_DEVICE = @as(u32, 1); pub const FW_ISSUEID_NO_ISSUE = @as(u32, 0); pub const FW_ISSUEID_UNKNOWN = @as(u32, 4294967295); pub const TC_PUBLIC_DEVICEDUMP_CONTENT_SMART = @as(u32, 1); pub const TC_PUBLIC_DEVICEDUMP_CONTENT_GPLOG = @as(u32, 2); pub const TC_PUBLIC_DEVICEDUMP_CONTENT_GPLOG_MAX = @as(u32, 16); pub const TC_DEVICEDUMP_SUBSECTION_DESC_LENGTH = @as(u32, 16); pub const CDB_SIZE = @as(u32, 16); pub const TELEMETRY_COMMAND_SIZE = @as(u32, 16); pub const DEVICEDUMP_CAP_PRIVATE_SECTION = @as(u32, 1); pub const DEVICEDUMP_CAP_RESTRICTED_SECTION = @as(u32, 2); pub const STORAGE_IDLE_POWERUP_REASON_VERSION_V1 = @as(u32, 1); pub const STORAGE_DEVICE_POWER_CAP_VERSION_V1 = @as(u32, 1); pub const STORAGE_EVENT_NOTIFICATION_VERSION_V1 = @as(u32, 1); pub const STORAGE_EVENT_MEDIA_STATUS = @as(u64, 1); pub const STORAGE_EVENT_DEVICE_STATUS = @as(u64, 2); pub const STORAGE_EVENT_DEVICE_OPERATION = @as(u64, 4); pub const READ_COPY_NUMBER_KEY = @as(u32, 1380142592); pub const READ_COPY_NUMBER_BYPASS_CACHE_FLAG = @as(u32, 256); pub const STORAGE_HW_FIRMWARE_REQUEST_FLAG_CONTROLLER = @as(u32, 1); pub const STORAGE_HW_FIRMWARE_REQUEST_FLAG_LAST_SEGMENT = @as(u32, 2); pub const STORAGE_HW_FIRMWARE_REQUEST_FLAG_FIRST_SEGMENT = @as(u32, 4); pub const STORAGE_HW_FIRMWARE_REQUEST_FLAG_SWITCH_TO_EXISTING_FIRMWARE = @as(u32, 2147483648); pub const STORAGE_HW_FIRMWARE_INVALID_SLOT = @as(u32, 255); pub const STORAGE_HW_FIRMWARE_REVISION_LENGTH = @as(u32, 16); pub const STORAGE_PROTOCOL_STRUCTURE_VERSION = @as(u32, 1); pub const STORAGE_PROTOCOL_COMMAND_FLAG_ADAPTER_REQUEST = @as(u32, 2147483648); pub const STORAGE_PROTOCOL_STATUS_PENDING = @as(u32, 0); pub const STORAGE_PROTOCOL_STATUS_SUCCESS = @as(u32, 1); pub const STORAGE_PROTOCOL_STATUS_ERROR = @as(u32, 2); pub const STORAGE_PROTOCOL_STATUS_INVALID_REQUEST = @as(u32, 3); pub const STORAGE_PROTOCOL_STATUS_NO_DEVICE = @as(u32, 4); pub const STORAGE_PROTOCOL_STATUS_BUSY = @as(u32, 5); pub const STORAGE_PROTOCOL_STATUS_DATA_OVERRUN = @as(u32, 6); pub const STORAGE_PROTOCOL_STATUS_INSUFFICIENT_RESOURCES = @as(u32, 7); pub const STORAGE_PROTOCOL_STATUS_THROTTLED_REQUEST = @as(u32, 8); pub const STORAGE_PROTOCOL_STATUS_NOT_SUPPORTED = @as(u32, 255); pub const STORAGE_PROTOCOL_COMMAND_LENGTH_NVME = @as(u32, 64); pub const STORAGE_PROTOCOL_SPECIFIC_NVME_ADMIN_COMMAND = @as(u32, 1); pub const STORAGE_PROTOCOL_SPECIFIC_NVME_NVM_COMMAND = @as(u32, 2); pub const STORATTRIBUTE_NONE = @as(u32, 0); pub const STORATTRIBUTE_MANAGEMENT_STATE = @as(u32, 1); pub const STORAGE_SUPPORTED_FEATURES_BYPASS_IO = @as(u32, 1); pub const STORAGE_SUPPORTED_FEATURES_MASK = @as(u32, 1); pub const GUID_DEVINTERFACE_SCM_PHYSICAL_DEVICE = Guid.initString("4283609d-4dc2-43be-bbb4-4f15dfce2c61"); pub const GUID_SCM_PD_HEALTH_NOTIFICATION = Guid.initString("9da2d386-72f5-4ee3-8155-eca0678e3b06"); pub const GUID_SCM_PD_PASSTHROUGH_INVDIMM = Guid.initString("4309ac30-0d11-11e4-9191-0800200c9a66"); pub const GUID_DEVINTERFACE_COMPORT = Guid.initString("86e0d1e0-8089-11d0-9ce4-08003e301f73"); pub const GUID_DEVINTERFACE_SERENUM_BUS_ENUMERATOR = Guid.initString("4d36e978-e325-11ce-bfc1-08002be10318"); pub const FILE_DEVICE_BEEP = @as(u32, 1); pub const FILE_DEVICE_CD_ROM_FILE_SYSTEM = @as(u32, 3); pub const FILE_DEVICE_CONTROLLER = @as(u32, 4); pub const FILE_DEVICE_DATALINK = @as(u32, 5); pub const FILE_DEVICE_DFS = @as(u32, 6); pub const FILE_DEVICE_DISK_FILE_SYSTEM = @as(u32, 8); pub const FILE_DEVICE_FILE_SYSTEM = @as(u32, 9); pub const FILE_DEVICE_INPORT_PORT = @as(u32, 10); pub const FILE_DEVICE_KEYBOARD = @as(u32, 11); pub const FILE_DEVICE_MAILSLOT = @as(u32, 12); pub const FILE_DEVICE_MIDI_IN = @as(u32, 13); pub const FILE_DEVICE_MIDI_OUT = @as(u32, 14); pub const FILE_DEVICE_MOUSE = @as(u32, 15); pub const FILE_DEVICE_MULTI_UNC_PROVIDER = @as(u32, 16); pub const FILE_DEVICE_NAMED_PIPE = @as(u32, 17); pub const FILE_DEVICE_NETWORK = @as(u32, 18); pub const FILE_DEVICE_NETWORK_BROWSER = @as(u32, 19); pub const FILE_DEVICE_NETWORK_FILE_SYSTEM = @as(u32, 20); pub const FILE_DEVICE_NULL = @as(u32, 21); pub const FILE_DEVICE_PARALLEL_PORT = @as(u32, 22); pub const FILE_DEVICE_PHYSICAL_NETCARD = @as(u32, 23); pub const FILE_DEVICE_PRINTER = @as(u32, 24); pub const FILE_DEVICE_SCANNER = @as(u32, 25); pub const FILE_DEVICE_SERIAL_MOUSE_PORT = @as(u32, 26); pub const FILE_DEVICE_SERIAL_PORT = @as(u32, 27); pub const FILE_DEVICE_SCREEN = @as(u32, 28); pub const FILE_DEVICE_SOUND = @as(u32, 29); pub const FILE_DEVICE_STREAMS = @as(u32, 30); pub const FILE_DEVICE_TAPE_FILE_SYSTEM = @as(u32, 32); pub const FILE_DEVICE_TRANSPORT = @as(u32, 33); pub const FILE_DEVICE_VIDEO = @as(u32, 35); pub const FILE_DEVICE_VIRTUAL_DISK = @as(u32, 36); pub const FILE_DEVICE_WAVE_IN = @as(u32, 37); pub const FILE_DEVICE_WAVE_OUT = @as(u32, 38); pub const FILE_DEVICE_8042_PORT = @as(u32, 39); pub const FILE_DEVICE_NETWORK_REDIRECTOR = @as(u32, 40); pub const FILE_DEVICE_BATTERY = @as(u32, 41); pub const FILE_DEVICE_BUS_EXTENDER = @as(u32, 42); pub const FILE_DEVICE_MODEM = @as(u32, 43); pub const FILE_DEVICE_VDM = @as(u32, 44); pub const FILE_DEVICE_MASS_STORAGE = @as(u32, 45); pub const FILE_DEVICE_SMB = @as(u32, 46); pub const FILE_DEVICE_KS = @as(u32, 47); pub const FILE_DEVICE_CHANGER = @as(u32, 48); pub const FILE_DEVICE_ACPI = @as(u32, 50); pub const FILE_DEVICE_FULLSCREEN_VIDEO = @as(u32, 52); pub const FILE_DEVICE_DFS_FILE_SYSTEM = @as(u32, 53); pub const FILE_DEVICE_DFS_VOLUME = @as(u32, 54); pub const FILE_DEVICE_SERENUM = @as(u32, 55); pub const FILE_DEVICE_TERMSRV = @as(u32, 56); pub const FILE_DEVICE_KSEC = @as(u32, 57); pub const FILE_DEVICE_FIPS = @as(u32, 58); pub const FILE_DEVICE_INFINIBAND = @as(u32, 59); pub const FILE_DEVICE_VMBUS = @as(u32, 62); pub const FILE_DEVICE_CRYPT_PROVIDER = @as(u32, 63); pub const FILE_DEVICE_WPD = @as(u32, 64); pub const FILE_DEVICE_BLUETOOTH = @as(u32, 65); pub const FILE_DEVICE_MT_COMPOSITE = @as(u32, 66); pub const FILE_DEVICE_MT_TRANSPORT = @as(u32, 67); pub const FILE_DEVICE_BIOMETRIC = @as(u32, 68); pub const FILE_DEVICE_PMI = @as(u32, 69); pub const FILE_DEVICE_EHSTOR = @as(u32, 70); pub const FILE_DEVICE_DEVAPI = @as(u32, 71); pub const FILE_DEVICE_GPIO = @as(u32, 72); pub const FILE_DEVICE_USBEX = @as(u32, 73); pub const FILE_DEVICE_CONSOLE = @as(u32, 80); pub const FILE_DEVICE_NFP = @as(u32, 81); pub const FILE_DEVICE_SYSENV = @as(u32, 82); pub const FILE_DEVICE_VIRTUAL_BLOCK = @as(u32, 83); pub const FILE_DEVICE_POINT_OF_SERVICE = @as(u32, 84); pub const FILE_DEVICE_STORAGE_REPLICATION = @as(u32, 85); pub const FILE_DEVICE_TRUST_ENV = @as(u32, 86); pub const FILE_DEVICE_UCM = @as(u32, 87); pub const FILE_DEVICE_UCMTCPCI = @as(u32, 88); pub const FILE_DEVICE_PERSISTENT_MEMORY = @as(u32, 89); pub const FILE_DEVICE_NVDIMM = @as(u32, 90); pub const FILE_DEVICE_HOLOGRAPHIC = @as(u32, 91); pub const FILE_DEVICE_SDFXHCI = @as(u32, 92); pub const FILE_DEVICE_UCMUCSI = @as(u32, 93); pub const FILE_DEVICE_PRM = @as(u32, 94); pub const FILE_DEVICE_EVENT_COLLECTOR = @as(u32, 95); pub const FILE_DEVICE_USB4 = @as(u32, 96); pub const FILE_DEVICE_SOUNDWIRE = @as(u32, 97); pub const METHOD_BUFFERED = @as(u32, 0); pub const METHOD_IN_DIRECT = @as(u32, 1); pub const METHOD_OUT_DIRECT = @as(u32, 2); pub const METHOD_NEITHER = @as(u32, 3); pub const METHOD_DIRECT_TO_HARDWARE = @as(u32, 1); pub const METHOD_DIRECT_FROM_HARDWARE = @as(u32, 2); pub const FILE_ANY_ACCESS = @as(u32, 0); pub const FILE_READ_ACCESS = @as(u32, 1); pub const FILE_WRITE_ACCESS = @as(u32, 2); pub const STORAGE_DEVICE_NUMA_NODE_UNKNOWN = @as(u32, 4294967295); pub const IOCTL_SCMBUS_DEVICE_FUNCTION_BASE = @as(u32, 0); pub const IOCTL_SCM_LOGICAL_DEVICE_FUNCTION_BASE = @as(u32, 768); pub const IOCTL_SCM_PHYSICAL_DEVICE_FUNCTION_BASE = @as(u32, 1536); pub const IOCTL_SCM_BUS_GET_LOGICAL_DEVICES = @as(u32, 5832704); pub const IOCTL_SCM_BUS_GET_PHYSICAL_DEVICES = @as(u32, 5832708); pub const IOCTL_SCM_BUS_GET_REGIONS = @as(u32, 5832712); pub const IOCTL_SCM_BUS_QUERY_PROPERTY = @as(u32, 5832716); pub const IOCTL_SCM_BUS_SET_PROPERTY = @as(u32, 5865492); pub const IOCTL_SCM_BUS_RUNTIME_FW_ACTIVATE = @as(u32, 5865488); pub const IOCTL_SCM_LD_GET_INTERLEAVE_SET = @as(u32, 5835776); pub const IOCTL_SCM_PD_QUERY_PROPERTY = @as(u32, 5838848); pub const IOCTL_SCM_PD_FIRMWARE_DOWNLOAD = @as(u32, 5871620); pub const IOCTL_SCM_PD_FIRMWARE_ACTIVATE = @as(u32, 5871624); pub const IOCTL_SCM_PD_PASSTHROUGH = @as(u32, 5888012); pub const IOCTL_SCM_PD_UPDATE_MANAGEMENT_STATUS = @as(u32, 5838864); pub const IOCTL_SCM_PD_REINITIALIZE_MEDIA = @as(u32, 5871636); pub const IOCTL_SCM_PD_SET_PROPERTY = @as(u32, 5871640); pub const SCM_MAX_SYMLINK_LEN_IN_CHARS = @as(u32, 256); pub const MAX_INTERFACE_CODES = @as(u32, 8); pub const SCM_PD_FIRMWARE_REVISION_LENGTH_BYTES = @as(u32, 32); pub const SCM_PD_PROPERTY_NAME_LENGTH_IN_CHARS = @as(u32, 128); pub const SCM_PD_MAX_OPERATIONAL_STATUS = @as(u32, 16); pub const SCM_PD_FIRMWARE_LAST_DOWNLOAD = @as(u32, 1); pub const IOCTL_DISK_GET_DRIVE_GEOMETRY = @as(u32, 458752); pub const IOCTL_DISK_GET_PARTITION_INFO = @as(u32, 475140); pub const IOCTL_DISK_SET_PARTITION_INFO = @as(u32, 507912); pub const IOCTL_DISK_GET_DRIVE_LAYOUT = @as(u32, 475148); pub const IOCTL_DISK_SET_DRIVE_LAYOUT = @as(u32, 507920); pub const IOCTL_DISK_VERIFY = @as(u32, 458772); pub const IOCTL_DISK_FORMAT_TRACKS = @as(u32, 507928); pub const IOCTL_DISK_REASSIGN_BLOCKS = @as(u32, 507932); pub const IOCTL_DISK_PERFORMANCE = @as(u32, 458784); pub const IOCTL_DISK_IS_WRITABLE = @as(u32, 458788); pub const IOCTL_DISK_LOGGING = @as(u32, 458792); pub const IOCTL_DISK_FORMAT_TRACKS_EX = @as(u32, 507948); pub const IOCTL_DISK_HISTOGRAM_STRUCTURE = @as(u32, 458800); pub const IOCTL_DISK_HISTOGRAM_DATA = @as(u32, 458804); pub const IOCTL_DISK_HISTOGRAM_RESET = @as(u32, 458808); pub const IOCTL_DISK_REQUEST_STRUCTURE = @as(u32, 458812); pub const IOCTL_DISK_REQUEST_DATA = @as(u32, 458816); pub const IOCTL_DISK_PERFORMANCE_OFF = @as(u32, 458848); pub const IOCTL_DISK_CONTROLLER_NUMBER = @as(u32, 458820); pub const SMART_GET_VERSION = @as(u32, 475264); pub const SMART_SEND_DRIVE_COMMAND = @as(u32, 508036); pub const SMART_RCV_DRIVE_DATA = @as(u32, 508040); pub const SMART_RCV_DRIVE_DATA_EX = @as(u32, 458892); pub const IOCTL_DISK_GET_PARTITION_INFO_EX = @as(u32, 458824); pub const IOCTL_DISK_SET_PARTITION_INFO_EX = @as(u32, 507980); pub const IOCTL_DISK_GET_DRIVE_LAYOUT_EX = @as(u32, 458832); pub const IOCTL_DISK_SET_DRIVE_LAYOUT_EX = @as(u32, 507988); pub const IOCTL_DISK_CREATE_DISK = @as(u32, 507992); pub const IOCTL_DISK_GET_LENGTH_INFO = @as(u32, 475228); pub const IOCTL_DISK_GET_DRIVE_GEOMETRY_EX = @as(u32, 458912); pub const IOCTL_DISK_REASSIGN_BLOCKS_EX = @as(u32, 508068); pub const IOCTL_DISK_UPDATE_DRIVE_SIZE = @as(u32, 508104); pub const IOCTL_DISK_GROW_PARTITION = @as(u32, 508112); pub const IOCTL_DISK_GET_CACHE_INFORMATION = @as(u32, 475348); pub const IOCTL_DISK_SET_CACHE_INFORMATION = @as(u32, 508120); pub const IOCTL_DISK_GET_WRITE_CACHE_STATE = @as(u32, 475356); pub const OBSOLETE_DISK_GET_WRITE_CACHE_STATE = @as(u32, 475356); pub const IOCTL_DISK_DELETE_DRIVE_LAYOUT = @as(u32, 508160); pub const IOCTL_DISK_UPDATE_PROPERTIES = @as(u32, 459072); pub const IOCTL_DISK_FORMAT_DRIVE = @as(u32, 508876); pub const IOCTL_DISK_SENSE_DEVICE = @as(u32, 459744); pub const IOCTL_DISK_CHECK_VERIFY = @as(u32, 477184); pub const IOCTL_DISK_MEDIA_REMOVAL = @as(u32, 477188); pub const IOCTL_DISK_EJECT_MEDIA = @as(u32, 477192); pub const IOCTL_DISK_LOAD_MEDIA = @as(u32, 477196); pub const IOCTL_DISK_RESERVE = @as(u32, 477200); pub const IOCTL_DISK_RELEASE = @as(u32, 477204); pub const IOCTL_DISK_FIND_NEW_DEVICES = @as(u32, 477208); pub const IOCTL_DISK_GET_MEDIA_TYPES = @as(u32, 461824); pub const PARTITION_ENTRY_UNUSED = @as(u32, 0); pub const PARTITION_FAT_12 = @as(u32, 1); pub const PARTITION_XENIX_1 = @as(u32, 2); pub const PARTITION_XENIX_2 = @as(u32, 3); pub const PARTITION_FAT_16 = @as(u32, 4); pub const PARTITION_EXTENDED = @as(u32, 5); pub const PARTITION_HUGE = @as(u32, 6); pub const PARTITION_IFS = @as(u32, 7); pub const PARTITION_OS2BOOTMGR = @as(u32, 10); pub const PARTITION_FAT32 = @as(u32, 11); pub const PARTITION_FAT32_XINT13 = @as(u32, 12); pub const PARTITION_XINT13 = @as(u32, 14); pub const PARTITION_XINT13_EXTENDED = @as(u32, 15); pub const PARTITION_MSFT_RECOVERY = @as(u32, 39); pub const PARTITION_MAIN_OS = @as(u32, 40); pub const PARTIITON_OS_DATA = @as(u32, 41); pub const PARTITION_PRE_INSTALLED = @as(u32, 42); pub const PARTITION_BSP = @as(u32, 43); pub const PARTITION_DPP = @as(u32, 44); pub const PARTITION_WINDOWS_SYSTEM = @as(u32, 45); pub const PARTITION_PREP = @as(u32, 65); pub const PARTITION_LDM = @as(u32, 66); pub const PARTITION_DM = @as(u32, 84); pub const PARTITION_EZDRIVE = @as(u32, 85); pub const PARTITION_UNIX = @as(u32, 99); pub const PARTITION_SPACES_DATA = @as(u32, 215); pub const PARTITION_SPACES = @as(u32, 231); pub const PARTITION_GPT = @as(u32, 238); pub const PARTITION_SYSTEM = @as(u32, 239); pub const VALID_NTFT = @as(u32, 192); pub const PARTITION_NTFT = @as(u32, 128); pub const GPT_ATTRIBUTE_NO_BLOCK_IO_PROTOCOL = @as(u64, 2); pub const GPT_ATTRIBUTE_LEGACY_BIOS_BOOTABLE = @as(u64, 4); pub const GPT_BASIC_DATA_ATTRIBUTE_OFFLINE = @as(u64, 576460752303423488); pub const GPT_BASIC_DATA_ATTRIBUTE_DAX = @as(u64, 288230376151711744); pub const GPT_BASIC_DATA_ATTRIBUTE_SERVICE = @as(u64, 144115188075855872); pub const GPT_SPACES_ATTRIBUTE_NO_METADATA = @as(u64, 9223372036854775808); pub const HIST_NO_OF_BUCKETS = @as(u32, 24); pub const DISK_LOGGING_START = @as(u32, 0); pub const DISK_LOGGING_STOP = @as(u32, 1); pub const DISK_LOGGING_DUMP = @as(u32, 2); pub const DISK_BINNING = @as(u32, 3); pub const CAP_ATA_ID_CMD = @as(u32, 1); pub const CAP_ATAPI_ID_CMD = @as(u32, 2); pub const CAP_SMART_CMD = @as(u32, 4); pub const ATAPI_ID_CMD = @as(u32, 161); pub const ID_CMD = @as(u32, 236); pub const SMART_CMD = @as(u32, 176); pub const SMART_CYL_LOW = @as(u32, 79); pub const SMART_CYL_HI = @as(u32, 194); pub const SMART_NO_ERROR = @as(u32, 0); pub const SMART_IDE_ERROR = @as(u32, 1); pub const SMART_INVALID_FLAG = @as(u32, 2); pub const SMART_INVALID_COMMAND = @as(u32, 3); pub const SMART_INVALID_BUFFER = @as(u32, 4); pub const SMART_INVALID_DRIVE = @as(u32, 5); pub const SMART_INVALID_IOCTL = @as(u32, 6); pub const SMART_ERROR_NO_MEM = @as(u32, 7); pub const SMART_INVALID_REGISTER = @as(u32, 8); pub const SMART_NOT_SUPPORTED = @as(u32, 9); pub const SMART_NO_IDE_DEVICE = @as(u32, 10); pub const SMART_OFFLINE_ROUTINE_OFFLINE = @as(u32, 0); pub const SMART_SHORT_SELFTEST_OFFLINE = @as(u32, 1); pub const SMART_EXTENDED_SELFTEST_OFFLINE = @as(u32, 2); pub const SMART_ABORT_OFFLINE_SELFTEST = @as(u32, 127); pub const SMART_SHORT_SELFTEST_CAPTIVE = @as(u32, 129); pub const SMART_EXTENDED_SELFTEST_CAPTIVE = @as(u32, 130); pub const READ_ATTRIBUTE_BUFFER_SIZE = @as(u32, 512); pub const IDENTIFY_BUFFER_SIZE = @as(u32, 512); pub const READ_THRESHOLD_BUFFER_SIZE = @as(u32, 512); pub const SMART_LOG_SECTOR_SIZE = @as(u32, 512); pub const READ_ATTRIBUTES = @as(u32, 208); pub const READ_THRESHOLDS = @as(u32, 209); pub const ENABLE_DISABLE_AUTOSAVE = @as(u32, 210); pub const SAVE_ATTRIBUTE_VALUES = @as(u32, 211); pub const EXECUTE_OFFLINE_DIAGS = @as(u32, 212); pub const SMART_READ_LOG = @as(u32, 213); pub const SMART_WRITE_LOG = @as(u32, 214); pub const ENABLE_SMART = @as(u32, 216); pub const DISABLE_SMART = @as(u32, 217); pub const RETURN_SMART_STATUS = @as(u32, 218); pub const ENABLE_DISABLE_AUTO_OFFLINE = @as(u32, 219); pub const IOCTL_DISK_GET_DISK_ATTRIBUTES = @as(u32, 458992); pub const IOCTL_DISK_SET_DISK_ATTRIBUTES = @as(u32, 508148); pub const DISK_ATTRIBUTE_OFFLINE = @as(u64, 1); pub const DISK_ATTRIBUTE_READ_ONLY = @as(u64, 2); pub const IOCTL_DISK_RESET_SNAPSHOT_INFO = @as(u32, 508432); pub const IOCTL_CHANGER_GET_PARAMETERS = @as(u32, 3162112); pub const IOCTL_CHANGER_GET_STATUS = @as(u32, 3162116); pub const IOCTL_CHANGER_GET_PRODUCT_DATA = @as(u32, 3162120); pub const IOCTL_CHANGER_SET_ACCESS = @as(u32, 3194896); pub const IOCTL_CHANGER_GET_ELEMENT_STATUS = @as(u32, 3194900); pub const IOCTL_CHANGER_INITIALIZE_ELEMENT_STATUS = @as(u32, 3162136); pub const IOCTL_CHANGER_SET_POSITION = @as(u32, 3162140); pub const IOCTL_CHANGER_EXCHANGE_MEDIUM = @as(u32, 3162144); pub const IOCTL_CHANGER_MOVE_MEDIUM = @as(u32, 3162148); pub const IOCTL_CHANGER_REINITIALIZE_TRANSPORT = @as(u32, 3162152); pub const IOCTL_CHANGER_QUERY_VOLUME_TAGS = @as(u32, 3194924); pub const MAX_VOLUME_ID_SIZE = @as(u32, 36); pub const MAX_VOLUME_TEMPLATE_SIZE = @as(u32, 40); pub const VENDOR_ID_LENGTH = @as(u32, 8); pub const PRODUCT_ID_LENGTH = @as(u32, 16); pub const REVISION_LENGTH = @as(u32, 4); pub const SERIAL_NUMBER_LENGTH = @as(u32, 32); pub const CHANGER_RESERVED_BIT = @as(u32, 2147483648); pub const CHANGER_TO_TRANSPORT = @as(u32, 1); pub const CHANGER_TO_SLOT = @as(u32, 2); pub const CHANGER_TO_IEPORT = @as(u32, 4); pub const CHANGER_TO_DRIVE = @as(u32, 8); pub const LOCK_UNLOCK_IEPORT = @as(u32, 1); pub const LOCK_UNLOCK_DOOR = @as(u32, 2); pub const LOCK_UNLOCK_KEYPAD = @as(u32, 4); pub const LOCK_ELEMENT = @as(u32, 0); pub const UNLOCK_ELEMENT = @as(u32, 1); pub const EXTEND_IEPORT = @as(u32, 2); pub const RETRACT_IEPORT = @as(u32, 3); pub const ERROR_LABEL_UNREADABLE = @as(u32, 1); pub const ERROR_LABEL_QUESTIONABLE = @as(u32, 2); pub const ERROR_SLOT_NOT_PRESENT = @as(u32, 4); pub const ERROR_DRIVE_NOT_INSTALLED = @as(u32, 8); pub const ERROR_TRAY_MALFUNCTION = @as(u32, 16); pub const ERROR_INIT_STATUS_NEEDED = @as(u32, 17); pub const ERROR_UNHANDLED_ERROR = @as(u32, 4294967295); pub const SEARCH_ALL = @as(u32, 0); pub const SEARCH_PRIMARY = @as(u32, 1); pub const SEARCH_ALTERNATE = @as(u32, 2); pub const SEARCH_ALL_NO_SEQ = @as(u32, 4); pub const SEARCH_PRI_NO_SEQ = @as(u32, 5); pub const SEARCH_ALT_NO_SEQ = @as(u32, 6); pub const ASSERT_PRIMARY = @as(u32, 8); pub const ASSERT_ALTERNATE = @as(u32, 9); pub const REPLACE_PRIMARY = @as(u32, 10); pub const REPLACE_ALTERNATE = @as(u32, 11); pub const UNDEFINE_PRIMARY = @as(u32, 12); pub const UNDEFINE_ALTERNATE = @as(u32, 13); pub const IOCTL_SERIAL_LSRMST_INSERT = @as(u32, 1769596); pub const IOCTL_SERENUM_EXPOSE_HARDWARE = @as(u32, 3604992); pub const IOCTL_SERENUM_REMOVE_HARDWARE = @as(u32, 3604996); pub const IOCTL_SERENUM_PORT_DESC = @as(u32, 3605000); pub const IOCTL_SERENUM_GET_PORT_NAME = @as(u32, 3605004); pub const FSCTL_REQUEST_OPLOCK_LEVEL_1 = @as(u32, 589824); pub const FSCTL_REQUEST_OPLOCK_LEVEL_2 = @as(u32, 589828); pub const FSCTL_REQUEST_BATCH_OPLOCK = @as(u32, 589832); pub const FSCTL_OPLOCK_BREAK_ACKNOWLEDGE = @as(u32, 589836); pub const FSCTL_OPBATCH_ACK_CLOSE_PENDING = @as(u32, 589840); pub const FSCTL_OPLOCK_BREAK_NOTIFY = @as(u32, 589844); pub const FSCTL_LOCK_VOLUME = @as(u32, 589848); pub const FSCTL_UNLOCK_VOLUME = @as(u32, 589852); pub const FSCTL_DISMOUNT_VOLUME = @as(u32, 589856); pub const FSCTL_IS_VOLUME_MOUNTED = @as(u32, 589864); pub const FSCTL_IS_PATHNAME_VALID = @as(u32, 589868); pub const FSCTL_MARK_VOLUME_DIRTY = @as(u32, 589872); pub const FSCTL_QUERY_RETRIEVAL_POINTERS = @as(u32, 589883); pub const FSCTL_GET_COMPRESSION = @as(u32, 589884); pub const FSCTL_SET_COMPRESSION = @as(u32, 639040); pub const FSCTL_SET_BOOTLOADER_ACCESSED = @as(u32, 589903); pub const FSCTL_MARK_AS_SYSTEM_HIVE = @as(u32, 589903); pub const FSCTL_OPLOCK_BREAK_ACK_NO_2 = @as(u32, 589904); pub const FSCTL_INVALIDATE_VOLUMES = @as(u32, 589908); pub const FSCTL_QUERY_FAT_BPB = @as(u32, 589912); pub const FSCTL_REQUEST_FILTER_OPLOCK = @as(u32, 589916); pub const FSCTL_FILESYSTEM_GET_STATISTICS = @as(u32, 589920); pub const FSCTL_GET_NTFS_VOLUME_DATA = @as(u32, 589924); pub const FSCTL_GET_NTFS_FILE_RECORD = @as(u32, 589928); pub const FSCTL_GET_VOLUME_BITMAP = @as(u32, 589935); pub const FSCTL_GET_RETRIEVAL_POINTERS = @as(u32, 589939); pub const FSCTL_MOVE_FILE = @as(u32, 589940); pub const FSCTL_IS_VOLUME_DIRTY = @as(u32, 589944); pub const FSCTL_ALLOW_EXTENDED_DASD_IO = @as(u32, 589955); pub const FSCTL_FIND_FILES_BY_SID = @as(u32, 589967); pub const FSCTL_SET_OBJECT_ID = @as(u32, 589976); pub const FSCTL_GET_OBJECT_ID = @as(u32, 589980); pub const FSCTL_DELETE_OBJECT_ID = @as(u32, 589984); pub const FSCTL_SET_REPARSE_POINT = @as(u32, 589988); pub const FSCTL_GET_REPARSE_POINT = @as(u32, 589992); pub const FSCTL_DELETE_REPARSE_POINT = @as(u32, 589996); pub const FSCTL_ENUM_USN_DATA = @as(u32, 590003); pub const FSCTL_SECURITY_ID_CHECK = @as(u32, 606391); pub const FSCTL_READ_USN_JOURNAL = @as(u32, 590011); pub const FSCTL_SET_OBJECT_ID_EXTENDED = @as(u32, 590012); pub const FSCTL_CREATE_OR_GET_OBJECT_ID = @as(u32, 590016); pub const FSCTL_SET_SPARSE = @as(u32, 590020); pub const FSCTL_SET_ZERO_DATA = @as(u32, 622792); pub const FSCTL_QUERY_ALLOCATED_RANGES = @as(u32, 606415); pub const FSCTL_ENABLE_UPGRADE = @as(u32, 622800); pub const FSCTL_SET_ENCRYPTION = @as(u32, 590039); pub const FSCTL_ENCRYPTION_FSCTL_IO = @as(u32, 590043); pub const FSCTL_WRITE_RAW_ENCRYPTED = @as(u32, 590047); pub const FSCTL_READ_RAW_ENCRYPTED = @as(u32, 590051); pub const FSCTL_CREATE_USN_JOURNAL = @as(u32, 590055); pub const FSCTL_READ_FILE_USN_DATA = @as(u32, 590059); pub const FSCTL_WRITE_USN_CLOSE_RECORD = @as(u32, 590063); pub const FSCTL_EXTEND_VOLUME = @as(u32, 590064); pub const FSCTL_QUERY_USN_JOURNAL = @as(u32, 590068); pub const FSCTL_DELETE_USN_JOURNAL = @as(u32, 590072); pub const FSCTL_MARK_HANDLE = @as(u32, 590076); pub const FSCTL_SIS_COPYFILE = @as(u32, 590080); pub const FSCTL_SIS_LINK_FILES = @as(u32, 639236); pub const FSCTL_RECALL_FILE = @as(u32, 590103); pub const FSCTL_READ_FROM_PLEX = @as(u32, 606494); pub const FSCTL_FILE_PREFETCH = @as(u32, 590112); pub const FSCTL_MAKE_MEDIA_COMPATIBLE = @as(u32, 622896); pub const FSCTL_SET_DEFECT_MANAGEMENT = @as(u32, 622900); pub const FSCTL_QUERY_SPARING_INFO = @as(u32, 590136); pub const FSCTL_QUERY_ON_DISK_VOLUME_INFO = @as(u32, 590140); pub const FSCTL_SET_VOLUME_COMPRESSION_STATE = @as(u32, 590144); pub const FSCTL_TXFS_MODIFY_RM = @as(u32, 622916); pub const FSCTL_TXFS_QUERY_RM_INFORMATION = @as(u32, 606536); pub const FSCTL_TXFS_ROLLFORWARD_REDO = @as(u32, 622928); pub const FSCTL_TXFS_ROLLFORWARD_UNDO = @as(u32, 622932); pub const FSCTL_TXFS_START_RM = @as(u32, 622936); pub const FSCTL_TXFS_SHUTDOWN_RM = @as(u32, 622940); pub const FSCTL_TXFS_READ_BACKUP_INFORMATION = @as(u32, 606560); pub const FSCTL_TXFS_WRITE_BACKUP_INFORMATION = @as(u32, 622948); pub const FSCTL_TXFS_CREATE_SECONDARY_RM = @as(u32, 622952); pub const FSCTL_TXFS_GET_METADATA_INFO = @as(u32, 606572); pub const FSCTL_TXFS_GET_TRANSACTED_VERSION = @as(u32, 606576); pub const FSCTL_TXFS_SAVEPOINT_INFORMATION = @as(u32, 622968); pub const FSCTL_TXFS_CREATE_MINIVERSION = @as(u32, 622972); pub const FSCTL_TXFS_TRANSACTION_ACTIVE = @as(u32, 606604); pub const FSCTL_SET_ZERO_ON_DEALLOCATION = @as(u32, 590228); pub const FSCTL_SET_REPAIR = @as(u32, 590232); pub const FSCTL_GET_REPAIR = @as(u32, 590236); pub const FSCTL_WAIT_FOR_REPAIR = @as(u32, 590240); pub const FSCTL_INITIATE_REPAIR = @as(u32, 590248); pub const FSCTL_CSC_INTERNAL = @as(u32, 590255); pub const FSCTL_SHRINK_VOLUME = @as(u32, 590256); pub const FSCTL_SET_SHORT_NAME_BEHAVIOR = @as(u32, 590260); pub const FSCTL_DFSR_SET_GHOST_HANDLE_STATE = @as(u32, 590264); pub const FSCTL_TXFS_LIST_TRANSACTION_LOCKED_FILES = @as(u32, 606688); pub const FSCTL_TXFS_LIST_TRANSACTIONS = @as(u32, 606692); pub const FSCTL_QUERY_PAGEFILE_ENCRYPTION = @as(u32, 590312); pub const FSCTL_RESET_VOLUME_ALLOCATION_HINTS = @as(u32, 590316); pub const FSCTL_QUERY_DEPENDENT_VOLUME = @as(u32, 590320); pub const FSCTL_SD_GLOBAL_CHANGE = @as(u32, 590324); pub const FSCTL_TXFS_READ_BACKUP_INFORMATION2 = @as(u32, 590328); pub const FSCTL_LOOKUP_STREAM_FROM_CLUSTER = @as(u32, 590332); pub const FSCTL_TXFS_WRITE_BACKUP_INFORMATION2 = @as(u32, 590336); pub const FSCTL_FILE_TYPE_NOTIFICATION = @as(u32, 590340); pub const FSCTL_FILE_LEVEL_TRIM = @as(u32, 623112); pub const FSCTL_GET_BOOT_AREA_INFO = @as(u32, 590384); pub const FSCTL_GET_RETRIEVAL_POINTER_BASE = @as(u32, 590388); pub const FSCTL_SET_PERSISTENT_VOLUME_STATE = @as(u32, 590392); pub const FSCTL_QUERY_PERSISTENT_VOLUME_STATE = @as(u32, 590396); pub const FSCTL_REQUEST_OPLOCK = @as(u32, 590400); pub const FSCTL_CSV_TUNNEL_REQUEST = @as(u32, 590404); pub const FSCTL_IS_CSV_FILE = @as(u32, 590408); pub const FSCTL_QUERY_FILE_SYSTEM_RECOGNITION = @as(u32, 590412); pub const FSCTL_CSV_GET_VOLUME_PATH_NAME = @as(u32, 590416); pub const FSCTL_CSV_GET_VOLUME_NAME_FOR_VOLUME_MOUNT_POINT = @as(u32, 590420); pub const FSCTL_CSV_GET_VOLUME_PATH_NAMES_FOR_VOLUME_NAME = @as(u32, 590424); pub const FSCTL_IS_FILE_ON_CSV_VOLUME = @as(u32, 590428); pub const FSCTL_CORRUPTION_HANDLING = @as(u32, 590432); pub const FSCTL_OFFLOAD_READ = @as(u32, 606820); pub const FSCTL_OFFLOAD_WRITE = @as(u32, 623208); pub const FSCTL_CSV_INTERNAL = @as(u32, 590444); pub const FSCTL_SET_PURGE_FAILURE_MODE = @as(u32, 590448); pub const FSCTL_QUERY_FILE_LAYOUT = @as(u32, 590455); pub const FSCTL_IS_VOLUME_OWNED_BYCSVFS = @as(u32, 590456); pub const FSCTL_GET_INTEGRITY_INFORMATION = @as(u32, 590460); pub const FSCTL_SET_INTEGRITY_INFORMATION = @as(u32, 639616); pub const FSCTL_QUERY_FILE_REGIONS = @as(u32, 590468); pub const FSCTL_RKF_INTERNAL = @as(u32, 590511); pub const FSCTL_SCRUB_DATA = @as(u32, 590512); pub const FSCTL_REPAIR_COPIES = @as(u32, 639668); pub const FSCTL_DISABLE_LOCAL_BUFFERING = @as(u32, 590520); pub const FSCTL_CSV_MGMT_LOCK = @as(u32, 590524); pub const FSCTL_CSV_QUERY_DOWN_LEVEL_FILE_SYSTEM_CHARACTERISTICS = @as(u32, 590528); pub const FSCTL_ADVANCE_FILE_ID = @as(u32, 590532); pub const FSCTL_CSV_SYNC_TUNNEL_REQUEST = @as(u32, 590536); pub const FSCTL_CSV_QUERY_VETO_FILE_DIRECT_IO = @as(u32, 590540); pub const FSCTL_WRITE_USN_REASON = @as(u32, 590544); pub const FSCTL_CSV_CONTROL = @as(u32, 590548); pub const FSCTL_GET_REFS_VOLUME_DATA = @as(u32, 590552); pub const FSCTL_CSV_H_BREAKING_SYNC_TUNNEL_REQUEST = @as(u32, 590564); pub const FSCTL_QUERY_STORAGE_CLASSES = @as(u32, 590572); pub const FSCTL_QUERY_REGION_INFO = @as(u32, 590576); pub const FSCTL_USN_TRACK_MODIFIED_RANGES = @as(u32, 590580); pub const FSCTL_QUERY_SHARED_VIRTUAL_DISK_SUPPORT = @as(u32, 590592); pub const FSCTL_SVHDX_SYNC_TUNNEL_REQUEST = @as(u32, 590596); pub const FSCTL_SVHDX_SET_INITIATOR_INFORMATION = @as(u32, 590600); pub const FSCTL_SET_EXTERNAL_BACKING = @as(u32, 590604); pub const FSCTL_GET_EXTERNAL_BACKING = @as(u32, 590608); pub const FSCTL_DELETE_EXTERNAL_BACKING = @as(u32, 590612); pub const FSCTL_ENUM_EXTERNAL_BACKING = @as(u32, 590616); pub const FSCTL_ENUM_OVERLAY = @as(u32, 590623); pub const FSCTL_ADD_OVERLAY = @as(u32, 623408); pub const FSCTL_REMOVE_OVERLAY = @as(u32, 623412); pub const FSCTL_UPDATE_OVERLAY = @as(u32, 623416); pub const FSCTL_SHUFFLE_FILE = @as(u32, 639808); pub const FSCTL_DUPLICATE_EXTENTS_TO_FILE = @as(u32, 623428); pub const FSCTL_SPARSE_OVERALLOCATE = @as(u32, 590668); pub const FSCTL_STORAGE_QOS_CONTROL = @as(u32, 590672); pub const FSCTL_INITIATE_FILE_METADATA_OPTIMIZATION = @as(u32, 590684); pub const FSCTL_QUERY_FILE_METADATA_OPTIMIZATION = @as(u32, 590688); pub const FSCTL_SVHDX_ASYNC_TUNNEL_REQUEST = @as(u32, 590692); pub const FSCTL_GET_WOF_VERSION = @as(u32, 590696); pub const FSCTL_HCS_SYNC_TUNNEL_REQUEST = @as(u32, 590700); pub const FSCTL_HCS_ASYNC_TUNNEL_REQUEST = @as(u32, 590704); pub const FSCTL_QUERY_EXTENT_READ_CACHE_INFO = @as(u32, 590711); pub const FSCTL_QUERY_REFS_VOLUME_COUNTER_INFO = @as(u32, 590715); pub const FSCTL_CLEAN_VOLUME_METADATA = @as(u32, 590716); pub const FSCTL_SET_INTEGRITY_INFORMATION_EX = @as(u32, 590720); pub const FSCTL_SUSPEND_OVERLAY = @as(u32, 590724); pub const FSCTL_VIRTUAL_STORAGE_QUERY_PROPERTY = @as(u32, 590728); pub const FSCTL_FILESYSTEM_GET_STATISTICS_EX = @as(u32, 590732); pub const FSCTL_QUERY_VOLUME_CONTAINER_STATE = @as(u32, 590736); pub const FSCTL_SET_LAYER_ROOT = @as(u32, 590740); pub const FSCTL_QUERY_DIRECT_ACCESS_EXTENTS = @as(u32, 590747); pub const FSCTL_NOTIFY_STORAGE_SPACE_ALLOCATION = @as(u32, 590748); pub const FSCTL_SSDI_STORAGE_REQUEST = @as(u32, 590752); pub const FSCTL_QUERY_DIRECT_IMAGE_ORIGINAL_BASE = @as(u32, 590756); pub const FSCTL_READ_UNPRIVILEGED_USN_JOURNAL = @as(u32, 590763); pub const FSCTL_GHOST_FILE_EXTENTS = @as(u32, 623532); pub const FSCTL_QUERY_GHOSTED_FILE_EXTENTS = @as(u32, 590768); pub const FSCTL_UNMAP_SPACE = @as(u32, 590772); pub const FSCTL_HCS_SYNC_NO_WRITE_TUNNEL_REQUEST = @as(u32, 590776); pub const FSCTL_START_VIRTUALIZATION_INSTANCE = @as(u32, 590784); pub const FSCTL_GET_FILTER_FILE_IDENTIFIER = @as(u32, 590788); pub const FSCTL_STREAMS_QUERY_PARAMETERS = @as(u32, 590788); pub const FSCTL_STREAMS_ASSOCIATE_ID = @as(u32, 590792); pub const FSCTL_STREAMS_QUERY_ID = @as(u32, 590796); pub const FSCTL_GET_RETRIEVAL_POINTERS_AND_REFCOUNT = @as(u32, 590803); pub const FSCTL_QUERY_VOLUME_NUMA_INFO = @as(u32, 590804); pub const FSCTL_REFS_DEALLOCATE_RANGES = @as(u32, 590808); pub const FSCTL_QUERY_REFS_SMR_VOLUME_INFO = @as(u32, 590812); pub const FSCTL_SET_REFS_SMR_VOLUME_GC_PARAMETERS = @as(u32, 590816); pub const FSCTL_SET_REFS_FILE_STRICTLY_SEQUENTIAL = @as(u32, 590820); pub const FSCTL_DUPLICATE_EXTENTS_TO_FILE_EX = @as(u32, 623592); pub const FSCTL_QUERY_BAD_RANGES = @as(u32, 590828); pub const FSCTL_SET_DAX_ALLOC_ALIGNMENT_HINT = @as(u32, 590832); pub const FSCTL_DELETE_CORRUPTED_REFS_CONTAINER = @as(u32, 590836); pub const FSCTL_SCRUB_UNDISCOVERABLE_ID = @as(u32, 590840); pub const FSCTL_NOTIFY_DATA_CHANGE = @as(u32, 590844); pub const FSCTL_START_VIRTUALIZATION_INSTANCE_EX = @as(u32, 590848); pub const FSCTL_ENCRYPTION_KEY_CONTROL = @as(u32, 590852); pub const FSCTL_VIRTUAL_STORAGE_SET_BEHAVIOR = @as(u32, 590856); pub const FSCTL_SET_REPARSE_POINT_EX = @as(u32, 590860); pub const FSCTL_REARRANGE_FILE = @as(u32, 640032); pub const FSCTL_VIRTUAL_STORAGE_PASSTHROUGH = @as(u32, 590884); pub const FSCTL_GET_RETRIEVAL_POINTER_COUNT = @as(u32, 590891); pub const FSCTL_ENABLE_PER_IO_FLAGS = @as(u32, 590892); pub const FSCTL_QUERY_ASYNC_DUPLICATE_EXTENTS_STATUS = @as(u32, 590896); pub const FSCTL_SMB_SHARE_FLUSH_AND_PURGE = @as(u32, 590908); pub const FSCTL_REFS_STREAM_SNAPSHOT_MANAGEMENT = @as(u32, 590912); pub const FSCTL_MANAGE_BYPASS_IO = @as(u32, 590920); pub const GET_VOLUME_BITMAP_FLAG_MASK_METADATA = @as(u32, 1); pub const FLAG_USN_TRACK_MODIFIED_RANGES_ENABLE = @as(u32, 1); pub const USN_PAGE_SIZE = @as(u32, 4096); pub const USN_REASON_DATA_OVERWRITE = @as(u32, 1); pub const USN_REASON_DATA_EXTEND = @as(u32, 2); pub const USN_REASON_DATA_TRUNCATION = @as(u32, 4); pub const USN_REASON_NAMED_DATA_OVERWRITE = @as(u32, 16); pub const USN_REASON_NAMED_DATA_EXTEND = @as(u32, 32); pub const USN_REASON_NAMED_DATA_TRUNCATION = @as(u32, 64); pub const USN_REASON_FILE_CREATE = @as(u32, 256); pub const USN_REASON_FILE_DELETE = @as(u32, 512); pub const USN_REASON_EA_CHANGE = @as(u32, 1024); pub const USN_REASON_SECURITY_CHANGE = @as(u32, 2048); pub const USN_REASON_RENAME_OLD_NAME = @as(u32, 4096); pub const USN_REASON_RENAME_NEW_NAME = @as(u32, 8192); pub const USN_REASON_INDEXABLE_CHANGE = @as(u32, 16384); pub const USN_REASON_BASIC_INFO_CHANGE = @as(u32, 32768); pub const USN_REASON_HARD_LINK_CHANGE = @as(u32, 65536); pub const USN_REASON_COMPRESSION_CHANGE = @as(u32, 131072); pub const USN_REASON_ENCRYPTION_CHANGE = @as(u32, 262144); pub const USN_REASON_OBJECT_ID_CHANGE = @as(u32, 524288); pub const USN_REASON_REPARSE_POINT_CHANGE = @as(u32, 1048576); pub const USN_REASON_STREAM_CHANGE = @as(u32, 2097152); pub const USN_REASON_TRANSACTED_CHANGE = @as(u32, 4194304); pub const USN_REASON_INTEGRITY_CHANGE = @as(u32, 8388608); pub const USN_REASON_DESIRED_STORAGE_CLASS_CHANGE = @as(u32, 16777216); pub const USN_REASON_CLOSE = @as(u32, 2147483648); pub const USN_DELETE_VALID_FLAGS = @as(u32, 3); pub const MARK_HANDLE_PROTECT_CLUSTERS = @as(u32, 1); pub const MARK_HANDLE_TXF_SYSTEM_LOG = @as(u32, 4); pub const MARK_HANDLE_NOT_TXF_SYSTEM_LOG = @as(u32, 8); pub const MARK_HANDLE_REALTIME = @as(u32, 32); pub const MARK_HANDLE_NOT_REALTIME = @as(u32, 64); pub const MARK_HANDLE_CLOUD_SYNC = @as(u32, 2048); pub const MARK_HANDLE_READ_COPY = @as(u32, 128); pub const MARK_HANDLE_NOT_READ_COPY = @as(u32, 256); pub const MARK_HANDLE_FILTER_METADATA = @as(u32, 512); pub const MARK_HANDLE_RETURN_PURGE_FAILURE = @as(u32, 1024); pub const MARK_HANDLE_DISABLE_FILE_METADATA_OPTIMIZATION = @as(u32, 4096); pub const MARK_HANDLE_ENABLE_USN_SOURCE_ON_PAGING_IO = @as(u32, 8192); pub const MARK_HANDLE_SKIP_COHERENCY_SYNC_DISALLOW_WRITES = @as(u32, 16384); pub const MARK_HANDLE_SUPPRESS_VOLUME_OPEN_FLUSH = @as(u32, 32768); pub const MARK_HANDLE_ENABLE_CPU_CACHE = @as(u32, 268435456); pub const VOLUME_IS_DIRTY = @as(u32, 1); pub const VOLUME_UPGRADE_SCHEDULED = @as(u32, 2); pub const VOLUME_SESSION_OPEN = @as(u32, 4); pub const FILE_PREFETCH_TYPE_FOR_CREATE = @as(u32, 1); pub const FILE_PREFETCH_TYPE_FOR_DIRENUM = @as(u32, 2); pub const FILE_PREFETCH_TYPE_FOR_CREATE_EX = @as(u32, 3); pub const FILE_PREFETCH_TYPE_FOR_DIRENUM_EX = @as(u32, 4); pub const FILE_PREFETCH_TYPE_MAX = @as(u32, 4); pub const FILESYSTEM_STATISTICS_TYPE_REFS = @as(u32, 4); pub const FILE_ZERO_DATA_INFORMATION_FLAG_PRESERVE_CACHED_DATA = @as(u32, 1); pub const FILE_SET_ENCRYPTION = @as(u32, 1); pub const FILE_CLEAR_ENCRYPTION = @as(u32, 2); pub const STREAM_SET_ENCRYPTION = @as(u32, 3); pub const STREAM_CLEAR_ENCRYPTION = @as(u32, 4); pub const MAXIMUM_ENCRYPTION_VALUE = @as(u32, 4); pub const ENCRYPTION_FORMAT_DEFAULT = @as(u32, 1); pub const ENCRYPTED_DATA_INFO_SPARSE_FILE = @as(u32, 1); pub const COPYFILE_SIS_LINK = @as(u32, 1); pub const COPYFILE_SIS_REPLACE = @as(u32, 2); pub const COPYFILE_SIS_FLAGS = @as(u32, 3); pub const SET_REPAIR_ENABLED = @as(u32, 1); pub const SET_REPAIR_WARN_ABOUT_DATA_LOSS = @as(u32, 8); pub const SET_REPAIR_DISABLED_AND_BUGCHECK_ON_CORRUPT = @as(u32, 16); pub const SET_REPAIR_VALID_MASK = @as(u32, 25); pub const FILE_INITIATE_REPAIR_HINT1_FILE_RECORD_NOT_IN_USE = @as(u64, 1); pub const FILE_INITIATE_REPAIR_HINT1_FILE_RECORD_REUSED = @as(u64, 2); pub const FILE_INITIATE_REPAIR_HINT1_FILE_RECORD_NOT_EXIST = @as(u64, 4); pub const FILE_INITIATE_REPAIR_HINT1_FILE_RECORD_NOT_BASE_RECORD = @as(u64, 8); pub const FILE_INITIATE_REPAIR_HINT1_SYSTEM_FILE = @as(u64, 16); pub const FILE_INITIATE_REPAIR_HINT1_NOT_IMPLEMENTED = @as(u64, 32); pub const FILE_INITIATE_REPAIR_HINT1_UNABLE_TO_REPAIR = @as(u64, 64); pub const FILE_INITIATE_REPAIR_HINT1_REPAIR_DISABLED = @as(u64, 128); pub const FILE_INITIATE_REPAIR_HINT1_RECURSIVELY_CORRUPTED = @as(u64, 256); pub const FILE_INITIATE_REPAIR_HINT1_ORPHAN_GENERATED = @as(u64, 512); pub const FILE_INITIATE_REPAIR_HINT1_REPAIRED = @as(u64, 1024); pub const FILE_INITIATE_REPAIR_HINT1_NOTHING_WRONG = @as(u64, 2048); pub const FILE_INITIATE_REPAIR_HINT1_ATTRIBUTE_NOT_FOUND = @as(u64, 4096); pub const FILE_INITIATE_REPAIR_HINT1_POTENTIAL_CROSSLINK = @as(u64, 8192); pub const FILE_INITIATE_REPAIR_HINT1_STALE_INFORMATION = @as(u64, 16384); pub const FILE_INITIATE_REPAIR_HINT1_CLUSTERS_ALREADY_IN_USE = @as(u64, 32768); pub const FILE_INITIATE_REPAIR_HINT1_LCN_NOT_EXIST = @as(u64, 65536); pub const FILE_INITIATE_REPAIR_HINT1_INVALID_RUN_LENGTH = @as(u64, 131072); pub const FILE_INITIATE_REPAIR_HINT1_FILE_RECORD_NOT_ORPHAN = @as(u64, 262144); pub const FILE_INITIATE_REPAIR_HINT1_FILE_RECORD_IS_BASE_RECORD = @as(u64, 524288); pub const FILE_INITIATE_REPAIR_HINT1_INVALID_ARRAY_LENGTH_COUNT = @as(u64, 1048576); pub const FILE_INITIATE_REPAIR_HINT1_SID_VALID = @as(u64, 2097152); pub const FILE_INITIATE_REPAIR_HINT1_SID_MISMATCH = @as(u64, 4194304); pub const FILE_INITIATE_REPAIR_HINT1_INVALID_PARENT = @as(u64, 8388608); pub const FILE_INITIATE_REPAIR_HINT1_PARENT_FILE_RECORD_NOT_IN_USE = @as(u64, 16777216); pub const FILE_INITIATE_REPAIR_HINT1_PARENT_FILE_RECORD_REUSED = @as(u64, 33554432); pub const FILE_INITIATE_REPAIR_HINT1_PARENT_FILE_RECORD_NOT_EXIST = @as(u64, 67108864); pub const FILE_INITIATE_REPAIR_HINT1_PARENT_FILE_RECORD_NOT_BASE_RECORD = @as(u64, 134217728); pub const FILE_INITIATE_REPAIR_HINT1_PARENT_FILE_RECORD_NOT_INDEX = @as(u64, 268435456); pub const FILE_INITIATE_REPAIR_HINT1_VALID_INDEX_ENTRY = @as(u64, 536870912); pub const FILE_INITIATE_REPAIR_HINT1_OUT_OF_GENERIC_NAMES = @as(u64, 1073741824); pub const FILE_INITIATE_REPAIR_HINT1_OUT_OF_RESOURCE = @as(u64, 2147483648); pub const FILE_INITIATE_REPAIR_HINT1_INVALID_LCN = @as(u64, 4294967296); pub const FILE_INITIATE_REPAIR_HINT1_INVALID_VCN = @as(u64, 8589934592); pub const FILE_INITIATE_REPAIR_HINT1_NAME_CONFLICT = @as(u64, 17179869184); pub const FILE_INITIATE_REPAIR_HINT1_ORPHAN = @as(u64, 34359738368); pub const FILE_INITIATE_REPAIR_HINT1_ATTRIBUTE_TOO_SMALL = @as(u64, 68719476736); pub const FILE_INITIATE_REPAIR_HINT1_ATTRIBUTE_NON_RESIDENT = @as(u64, 137438953472); pub const FILE_INITIATE_REPAIR_HINT1_DENY_DEFRAG = @as(u64, 274877906944); pub const FILE_INITIATE_REPAIR_HINT1_PREVIOUS_PARENT_STILL_VALID = @as(u64, 549755813888); pub const FILE_INITIATE_REPAIR_HINT1_INDEX_ENTRY_MISMATCH = @as(u64, 1099511627776); pub const FILE_INITIATE_REPAIR_HINT1_INVALID_ORPHAN_RECOVERY_NAME = @as(u64, 2199023255552); pub const FILE_INITIATE_REPAIR_HINT1_MULTIPLE_FILE_NAME_ATTRIBUTES = @as(u64, 4398046511104); pub const TXFS_LOGGING_MODE_SIMPLE = @as(u32, 1); pub const TXFS_LOGGING_MODE_FULL = @as(u32, 2); pub const TXFS_TRANSACTION_STATE_NONE = @as(u32, 0); pub const TXFS_TRANSACTION_STATE_ACTIVE = @as(u32, 1); pub const TXFS_TRANSACTION_STATE_PREPARED = @as(u32, 2); pub const TXFS_TRANSACTION_STATE_NOTACTIVE = @as(u32, 3); pub const TXFS_RM_STATE_NOT_STARTED = @as(u32, 0); pub const TXFS_RM_STATE_STARTING = @as(u32, 1); pub const TXFS_RM_STATE_ACTIVE = @as(u32, 2); pub const TXFS_RM_STATE_SHUTTING_DOWN = @as(u32, 3); pub const TXFS_ROLLFORWARD_REDO_FLAG_USE_LAST_REDO_LSN = @as(u32, 1); pub const TXFS_ROLLFORWARD_REDO_FLAG_USE_LAST_VIRTUAL_CLOCK = @as(u32, 2); pub const TXFS_START_RM_FLAG_LOG_CONTAINER_COUNT_MAX = @as(u32, 1); pub const TXFS_START_RM_FLAG_LOG_CONTAINER_COUNT_MIN = @as(u32, 2); pub const TXFS_START_RM_FLAG_LOG_CONTAINER_SIZE = @as(u32, 4); pub const TXFS_START_RM_FLAG_LOG_GROWTH_INCREMENT_NUM_CONTAINERS = @as(u32, 8); pub const TXFS_START_RM_FLAG_LOG_GROWTH_INCREMENT_PERCENT = @as(u32, 16); pub const TXFS_START_RM_FLAG_LOG_AUTO_SHRINK_PERCENTAGE = @as(u32, 32); pub const TXFS_START_RM_FLAG_LOG_NO_CONTAINER_COUNT_MAX = @as(u32, 64); pub const TXFS_START_RM_FLAG_LOG_NO_CONTAINER_COUNT_MIN = @as(u32, 128); pub const TXFS_START_RM_FLAG_RECOVER_BEST_EFFORT = @as(u32, 512); pub const TXFS_START_RM_FLAG_LOGGING_MODE = @as(u32, 1024); pub const TXFS_START_RM_FLAG_PRESERVE_CHANGES = @as(u32, 2048); pub const TXFS_START_RM_FLAG_PREFER_CONSISTENCY = @as(u32, 4096); pub const TXFS_START_RM_FLAG_PREFER_AVAILABILITY = @as(u32, 8192); pub const TXFS_LIST_TRANSACTION_LOCKED_FILES_ENTRY_FLAG_CREATED = @as(u32, 1); pub const TXFS_LIST_TRANSACTION_LOCKED_FILES_ENTRY_FLAG_DELETED = @as(u32, 2); pub const TXFS_TRANSACTED_VERSION_NONTRANSACTED = @as(u32, 4294967294); pub const TXFS_TRANSACTED_VERSION_UNCOMMITTED = @as(u32, 4294967295); pub const TXFS_SAVEPOINT_SET = @as(u32, 1); pub const TXFS_SAVEPOINT_ROLLBACK = @as(u32, 2); pub const TXFS_SAVEPOINT_CLEAR = @as(u32, 4); pub const TXFS_SAVEPOINT_CLEAR_ALL = @as(u32, 16); pub const PERSISTENT_VOLUME_STATE_SHORT_NAME_CREATION_DISABLED = @as(u32, 1); pub const PERSISTENT_VOLUME_STATE_VOLUME_SCRUB_DISABLED = @as(u32, 2); pub const PERSISTENT_VOLUME_STATE_GLOBAL_METADATA_NO_SEEK_PENALTY = @as(u32, 4); pub const PERSISTENT_VOLUME_STATE_LOCAL_METADATA_NO_SEEK_PENALTY = @as(u32, 8); pub const PERSISTENT_VOLUME_STATE_NO_HEAT_GATHERING = @as(u32, 16); pub const PERSISTENT_VOLUME_STATE_CONTAINS_BACKING_WIM = @as(u32, 32); pub const PERSISTENT_VOLUME_STATE_BACKED_BY_WIM = @as(u32, 64); pub const PERSISTENT_VOLUME_STATE_NO_WRITE_AUTO_TIERING = @as(u32, 128); pub const PERSISTENT_VOLUME_STATE_TXF_DISABLED = @as(u32, 256); pub const PERSISTENT_VOLUME_STATE_REALLOCATE_ALL_DATA_WRITES = @as(u32, 512); pub const PERSISTENT_VOLUME_STATE_CHKDSK_RAN_ONCE = @as(u32, 1024); pub const PERSISTENT_VOLUME_STATE_MODIFIED_BY_CHKDSK = @as(u32, 2048); pub const PERSISTENT_VOLUME_STATE_DAX_FORMATTED = @as(u32, 4096); pub const OPLOCK_LEVEL_CACHE_READ = @as(u32, 1); pub const OPLOCK_LEVEL_CACHE_HANDLE = @as(u32, 2); pub const OPLOCK_LEVEL_CACHE_WRITE = @as(u32, 4); pub const REQUEST_OPLOCK_INPUT_FLAG_REQUEST = @as(u32, 1); pub const REQUEST_OPLOCK_INPUT_FLAG_ACK = @as(u32, 2); pub const REQUEST_OPLOCK_INPUT_FLAG_COMPLETE_ACK_ON_CLOSE = @as(u32, 4); pub const REQUEST_OPLOCK_CURRENT_VERSION = @as(u32, 1); pub const REQUEST_OPLOCK_OUTPUT_FLAG_ACK_REQUIRED = @as(u32, 1); pub const REQUEST_OPLOCK_OUTPUT_FLAG_MODES_PROVIDED = @as(u32, 2); pub const QUERY_DEPENDENT_VOLUME_REQUEST_FLAG_HOST_VOLUMES = @as(u32, 1); pub const QUERY_DEPENDENT_VOLUME_REQUEST_FLAG_GUEST_VOLUMES = @as(u32, 2); pub const SD_GLOBAL_CHANGE_TYPE_MACHINE_SID = @as(u32, 1); pub const SD_GLOBAL_CHANGE_TYPE_QUERY_STATS = @as(u32, 65536); pub const SD_GLOBAL_CHANGE_TYPE_ENUM_SDS = @as(u32, 131072); pub const LOOKUP_STREAM_FROM_CLUSTER_ENTRY_FLAG_PAGE_FILE = @as(u32, 1); pub const LOOKUP_STREAM_FROM_CLUSTER_ENTRY_FLAG_DENY_DEFRAG_SET = @as(u32, 2); pub const LOOKUP_STREAM_FROM_CLUSTER_ENTRY_FLAG_FS_SYSTEM_FILE = @as(u32, 4); pub const LOOKUP_STREAM_FROM_CLUSTER_ENTRY_FLAG_TXF_SYSTEM_FILE = @as(u32, 8); pub const LOOKUP_STREAM_FROM_CLUSTER_ENTRY_ATTRIBUTE_MASK = @as(u32, 4278190080); pub const LOOKUP_STREAM_FROM_CLUSTER_ENTRY_ATTRIBUTE_DATA = @as(u32, 16777216); pub const LOOKUP_STREAM_FROM_CLUSTER_ENTRY_ATTRIBUTE_INDEX = @as(u32, 33554432); pub const LOOKUP_STREAM_FROM_CLUSTER_ENTRY_ATTRIBUTE_SYSTEM = @as(u32, 50331648); pub const FILE_TYPE_NOTIFICATION_FLAG_USAGE_BEGIN = @as(u32, 1); pub const FILE_TYPE_NOTIFICATION_FLAG_USAGE_END = @as(u32, 2); pub const FILE_TYPE_NOTIFICATION_GUID_PAGE_FILE = Guid.initString("0d0a64a1-38fc-4db8-9fe7-3f4352cd7c5c"); pub const FILE_TYPE_NOTIFICATION_GUID_HIBERNATION_FILE = Guid.initString("b7624d64-b9a3-4cf8-8011-5b86c940e7b7"); pub const FILE_TYPE_NOTIFICATION_GUID_CRASHDUMP_FILE = Guid.initString("9d453eb7-d2a6-4dbd-a2e3-fbd0ed9109a9"); pub const CSV_MGMTLOCK_CHECK_VOLUME_REDIRECTED = @as(u32, 1); pub const CSV_INVALID_DEVICE_NUMBER = @as(u32, 4294967295); pub const CSV_QUERY_MDS_PATH_V2_VERSION_1 = @as(u32, 1); pub const CSV_QUERY_MDS_PATH_FLAG_STORAGE_ON_THIS_NODE_IS_CONNECTED = @as(u32, 1); pub const CSV_QUERY_MDS_PATH_FLAG_CSV_DIRECT_IO_ENABLED = @as(u32, 2); pub const CSV_QUERY_MDS_PATH_FLAG_SMB_BYPASS_CSV_ENABLED = @as(u32, 4); pub const QUERY_FILE_LAYOUT_RESTART = @as(u32, 1); pub const QUERY_FILE_LAYOUT_INCLUDE_NAMES = @as(u32, 2); pub const QUERY_FILE_LAYOUT_INCLUDE_STREAMS = @as(u32, 4); pub const QUERY_FILE_LAYOUT_INCLUDE_EXTENTS = @as(u32, 8); pub const QUERY_FILE_LAYOUT_INCLUDE_EXTRA_INFO = @as(u32, 16); pub const QUERY_FILE_LAYOUT_INCLUDE_STREAMS_WITH_NO_CLUSTERS_ALLOCATED = @as(u32, 32); pub const QUERY_FILE_LAYOUT_INCLUDE_FULL_PATH_IN_NAMES = @as(u32, 64); pub const QUERY_FILE_LAYOUT_INCLUDE_STREAM_INFORMATION = @as(u32, 128); pub const QUERY_FILE_LAYOUT_INCLUDE_STREAM_INFORMATION_FOR_DSC_ATTRIBUTE = @as(u32, 256); pub const QUERY_FILE_LAYOUT_INCLUDE_STREAM_INFORMATION_FOR_TXF_ATTRIBUTE = @as(u32, 512); pub const QUERY_FILE_LAYOUT_INCLUDE_STREAM_INFORMATION_FOR_EFS_ATTRIBUTE = @as(u32, 1024); pub const QUERY_FILE_LAYOUT_INCLUDE_ONLY_FILES_WITH_SPECIFIC_ATTRIBUTES = @as(u32, 2048); pub const QUERY_FILE_LAYOUT_INCLUDE_FILES_WITH_DSC_ATTRIBUTE = @as(u32, 4096); pub const QUERY_FILE_LAYOUT_INCLUDE_STREAM_INFORMATION_FOR_DATA_ATTRIBUTE = @as(u32, 8192); pub const QUERY_FILE_LAYOUT_INCLUDE_STREAM_INFORMATION_FOR_REPARSE_ATTRIBUTE = @as(u32, 16384); pub const QUERY_FILE_LAYOUT_INCLUDE_STREAM_INFORMATION_FOR_EA_ATTRIBUTE = @as(u32, 32768); pub const QUERY_FILE_LAYOUT_SINGLE_INSTANCED = @as(u32, 1); pub const FILE_LAYOUT_NAME_ENTRY_PRIMARY = @as(u32, 1); pub const FILE_LAYOUT_NAME_ENTRY_DOS = @as(u32, 2); pub const STREAM_LAYOUT_ENTRY_IMMOVABLE = @as(u32, 1); pub const STREAM_LAYOUT_ENTRY_PINNED = @as(u32, 2); pub const STREAM_LAYOUT_ENTRY_RESIDENT = @as(u32, 4); pub const STREAM_LAYOUT_ENTRY_NO_CLUSTERS_ALLOCATED = @as(u32, 8); pub const STREAM_LAYOUT_ENTRY_HAS_INFORMATION = @as(u32, 16); pub const STREAM_EXTENT_ENTRY_AS_RETRIEVAL_POINTERS = @as(u32, 1); pub const STREAM_EXTENT_ENTRY_ALL_EXTENTS = @as(u32, 2); pub const CHECKSUM_TYPE_UNCHANGED = @as(i32, -1); pub const CHECKSUM_TYPE_NONE = @as(u32, 0); pub const CHECKSUM_TYPE_CRC32 = @as(u32, 1); pub const CHECKSUM_TYPE_CRC64 = @as(u32, 2); pub const CHECKSUM_TYPE_ECC = @as(u32, 3); pub const CHECKSUM_TYPE_FIRST_UNUSED_TYPE = @as(u32, 4); pub const FSCTL_INTEGRITY_FLAG_CHECKSUM_ENFORCEMENT_OFF = @as(u32, 1); pub const OFFLOAD_READ_FLAG_ALL_ZERO_BEYOND_CURRENT_RANGE = @as(u32, 1); pub const SET_PURGE_FAILURE_MODE_ENABLED = @as(u32, 1); pub const SET_PURGE_FAILURE_MODE_DISABLED = @as(u32, 2); pub const FILE_REGION_USAGE_VALID_CACHED_DATA = @as(u32, 1); pub const FILE_REGION_USAGE_VALID_NONCACHED_DATA = @as(u32, 2); pub const FILE_REGION_USAGE_OTHER_PAGE_ALIGNMENT = @as(u32, 4); pub const FILE_REGION_USAGE_LARGE_PAGE_ALIGNMENT = @as(u32, 8); pub const FILE_REGION_USAGE_HUGE_PAGE_ALIGNMENT = @as(u32, 16); pub const FILE_REGION_USAGE_QUERY_ALIGNMENT = @as(u32, 8); pub const FILE_STORAGE_TIER_NAME_LENGTH = @as(u32, 256); pub const FILE_STORAGE_TIER_DESCRIPTION_LENGTH = @as(u32, 512); pub const FILE_STORAGE_TIER_FLAG_WRITE_BACK_CACHE = @as(u32, 2097152); pub const FILE_STORAGE_TIER_FLAG_READ_CACHE = @as(u32, 4194304); pub const FILE_STORAGE_TIER_FLAG_PARITY = @as(u32, 8388608); pub const FILE_STORAGE_TIER_FLAG_SMR = @as(u32, 16777216); pub const QUERY_STORAGE_CLASSES_FLAGS_MEASURE_WRITE = @as(u32, 2147483648); pub const QUERY_STORAGE_CLASSES_FLAGS_MEASURE_READ = @as(u32, 1073741824); pub const QUERY_STORAGE_CLASSES_FLAGS_NO_DEFRAG_VOLUME = @as(u32, 536870912); pub const QUERY_FILE_LAYOUT_REPARSE_DATA_INVALID = @as(u32, 1); pub const QUERY_FILE_LAYOUT_REPARSE_TAG_INVALID = @as(u32, 2); pub const DUPLICATE_EXTENTS_DATA_EX_SOURCE_ATOMIC = @as(u32, 1); pub const DUPLICATE_EXTENTS_DATA_EX_ASYNC = @as(u32, 2); pub const REFS_SMR_VOLUME_INFO_OUTPUT_VERSION_V0 = @as(u32, 0); pub const REFS_SMR_VOLUME_INFO_OUTPUT_VERSION_V1 = @as(u32, 1); pub const REFS_SMR_VOLUME_GC_PARAMETERS_VERSION_V1 = @as(u32, 1); pub const STREAMS_INVALID_ID = @as(u32, 0); pub const STREAMS_MAX_ID = @as(u32, 65535); pub const STREAMS_ASSOCIATE_ID_CLEAR = @as(u32, 1); pub const STREAMS_ASSOCIATE_ID_SET = @as(u32, 2); pub const DAX_ALLOC_ALIGNMENT_FLAG_MANDATORY = @as(u32, 1); pub const DAX_ALLOC_ALIGNMENT_FLAG_FALLBACK_SPECIFIED = @as(u32, 2); pub const WOF_CURRENT_VERSION = @as(u32, 1); pub const WOF_PROVIDER_CLOUD = @as(u32, 3); pub const WIM_PROVIDER_CURRENT_VERSION = @as(u32, 1); pub const WIM_PROVIDER_EXTERNAL_FLAG_NOT_ACTIVE = @as(u32, 1); pub const WIM_PROVIDER_EXTERNAL_FLAG_SUSPENDED = @as(u32, 2); pub const FILE_PROVIDER_CURRENT_VERSION = @as(u32, 1); pub const FILE_PROVIDER_SINGLE_FILE = @as(u32, 1); pub const FILE_PROVIDER_COMPRESSION_MAXIMUM = @as(u32, 4); pub const FILE_PROVIDER_FLAG_COMPRESS_ON_WRITE = @as(u32, 1); pub const CONTAINER_VOLUME_STATE_HOSTING_CONTAINER = @as(u32, 1); pub const CONTAINER_ROOT_INFO_FLAG_SCRATCH_ROOT = @as(u32, 1); pub const CONTAINER_ROOT_INFO_FLAG_LAYER_ROOT = @as(u32, 2); pub const CONTAINER_ROOT_INFO_FLAG_VIRTUALIZATION_ROOT = @as(u32, 4); pub const CONTAINER_ROOT_INFO_FLAG_VIRTUALIZATION_TARGET_ROOT = @as(u32, 8); pub const CONTAINER_ROOT_INFO_FLAG_VIRTUALIZATION_EXCEPTION_ROOT = @as(u32, 16); pub const CONTAINER_ROOT_INFO_FLAG_BIND_ROOT = @as(u32, 32); pub const CONTAINER_ROOT_INFO_FLAG_BIND_TARGET_ROOT = @as(u32, 64); pub const CONTAINER_ROOT_INFO_FLAG_BIND_EXCEPTION_ROOT = @as(u32, 128); pub const CONTAINER_ROOT_INFO_FLAG_BIND_DO_NOT_MAP_NAME = @as(u32, 256); pub const CONTAINER_ROOT_INFO_FLAG_UNION_LAYER_ROOT = @as(u32, 512); pub const CONTAINER_ROOT_INFO_VALID_FLAGS = @as(u32, 1023); pub const PROJFS_PROTOCOL_VERSION = @as(u32, 3); pub const EFS_TRACKED_OFFSET_HEADER_FLAG = @as(u32, 1); pub const SPACES_TRACKED_OFFSET_HEADER_FLAG = @as(u32, 2); //-------------------------------------------------------------------------------- // Section: Types (521) //-------------------------------------------------------------------------------- pub const GPT_ATTRIBUTES = enum(u64) { ATTRIBUTE_PLATFORM_REQUIRED = 1, BASIC_DATA_ATTRIBUTE_NO_DRIVE_LETTER = 9223372036854775808, BASIC_DATA_ATTRIBUTE_HIDDEN = 4611686018427387904, BASIC_DATA_ATTRIBUTE_SHADOW_COPY = 2305843009213693952, BASIC_DATA_ATTRIBUTE_READ_ONLY = 1152921504606846976, _, pub fn initFlags(o: struct { ATTRIBUTE_PLATFORM_REQUIRED: u1 = 0, BASIC_DATA_ATTRIBUTE_NO_DRIVE_LETTER: u1 = 0, BASIC_DATA_ATTRIBUTE_HIDDEN: u1 = 0, BASIC_DATA_ATTRIBUTE_SHADOW_COPY: u1 = 0, BASIC_DATA_ATTRIBUTE_READ_ONLY: u1 = 0, }) GPT_ATTRIBUTES { return @intToEnum(GPT_ATTRIBUTES, (if (o.ATTRIBUTE_PLATFORM_REQUIRED == 1) @enumToInt(GPT_ATTRIBUTES.ATTRIBUTE_PLATFORM_REQUIRED) else 0) | (if (o.BASIC_DATA_ATTRIBUTE_NO_DRIVE_LETTER == 1) @enumToInt(GPT_ATTRIBUTES.BASIC_DATA_ATTRIBUTE_NO_DRIVE_LETTER) else 0) | (if (o.BASIC_DATA_ATTRIBUTE_HIDDEN == 1) @enumToInt(GPT_ATTRIBUTES.BASIC_DATA_ATTRIBUTE_HIDDEN) else 0) | (if (o.BASIC_DATA_ATTRIBUTE_SHADOW_COPY == 1) @enumToInt(GPT_ATTRIBUTES.BASIC_DATA_ATTRIBUTE_SHADOW_COPY) else 0) | (if (o.BASIC_DATA_ATTRIBUTE_READ_ONLY == 1) @enumToInt(GPT_ATTRIBUTES.BASIC_DATA_ATTRIBUTE_READ_ONLY) else 0) ); } }; pub const GPT_ATTRIBUTE_PLATFORM_REQUIRED = GPT_ATTRIBUTES.ATTRIBUTE_PLATFORM_REQUIRED; pub const GPT_BASIC_DATA_ATTRIBUTE_NO_DRIVE_LETTER = GPT_ATTRIBUTES.BASIC_DATA_ATTRIBUTE_NO_DRIVE_LETTER; pub const GPT_BASIC_DATA_ATTRIBUTE_HIDDEN = GPT_ATTRIBUTES.BASIC_DATA_ATTRIBUTE_HIDDEN; pub const GPT_BASIC_DATA_ATTRIBUTE_SHADOW_COPY = GPT_ATTRIBUTES.BASIC_DATA_ATTRIBUTE_SHADOW_COPY; pub const GPT_BASIC_DATA_ATTRIBUTE_READ_ONLY = GPT_ATTRIBUTES.BASIC_DATA_ATTRIBUTE_READ_ONLY; pub const USN_DELETE_FLAGS = enum(u32) { DELETE = 1, NOTIFY = 2, _, pub fn initFlags(o: struct { DELETE: u1 = 0, NOTIFY: u1 = 0, }) USN_DELETE_FLAGS { return @intToEnum(USN_DELETE_FLAGS, (if (o.DELETE == 1) @enumToInt(USN_DELETE_FLAGS.DELETE) else 0) | (if (o.NOTIFY == 1) @enumToInt(USN_DELETE_FLAGS.NOTIFY) else 0) ); } }; pub const USN_DELETE_FLAG_DELETE = USN_DELETE_FLAGS.DELETE; pub const USN_DELETE_FLAG_NOTIFY = USN_DELETE_FLAGS.NOTIFY; pub const CHANGER_FEATURES = enum(u32) { BAR_CODE_SCANNER_INSTALLED = 1, CARTRIDGE_MAGAZINE = 256, CLEANER_ACCESS_NOT_VALID = 262144, CLEANER_SLOT = 64, CLOSE_IEPORT = 4, DEVICE_REINITIALIZE_CAPABLE = 134217728, DRIVE_CLEANING_REQUIRED = 65536, DRIVE_EMPTY_ON_DOOR_ACCESS = 536870912, EXCHANGE_MEDIA = 32, INIT_ELEM_STAT_WITH_RANGE = 2, KEYPAD_ENABLE_DISABLE = 268435456, LOCK_UNLOCK = 128, MEDIUM_FLIP = 512, OPEN_IEPORT = 8, POSITION_TO_ELEMENT = 1024, PREDISMOUNT_EJECT_REQUIRED = 131072, PREMOUNT_EJECT_REQUIRED = 524288, REPORT_IEPORT_STATE = 2048, SERIAL_NUMBER_VALID = 67108864, STATUS_NON_VOLATILE = 16, STORAGE_DRIVE = 4096, STORAGE_IEPORT = 8192, STORAGE_SLOT = 16384, STORAGE_TRANSPORT = 32768, VOLUME_ASSERT = 4194304, VOLUME_IDENTIFICATION = 1048576, VOLUME_REPLACE = 8388608, VOLUME_SEARCH = 2097152, VOLUME_UNDEFINE = 16777216, _, pub fn initFlags(o: struct { BAR_CODE_SCANNER_INSTALLED: u1 = 0, CARTRIDGE_MAGAZINE: u1 = 0, CLEANER_ACCESS_NOT_VALID: u1 = 0, CLEANER_SLOT: u1 = 0, CLOSE_IEPORT: u1 = 0, DEVICE_REINITIALIZE_CAPABLE: u1 = 0, DRIVE_CLEANING_REQUIRED: u1 = 0, DRIVE_EMPTY_ON_DOOR_ACCESS: u1 = 0, EXCHANGE_MEDIA: u1 = 0, INIT_ELEM_STAT_WITH_RANGE: u1 = 0, KEYPAD_ENABLE_DISABLE: u1 = 0, LOCK_UNLOCK: u1 = 0, MEDIUM_FLIP: u1 = 0, OPEN_IEPORT: u1 = 0, POSITION_TO_ELEMENT: u1 = 0, PREDISMOUNT_EJECT_REQUIRED: u1 = 0, PREMOUNT_EJECT_REQUIRED: u1 = 0, REPORT_IEPORT_STATE: u1 = 0, SERIAL_NUMBER_VALID: u1 = 0, STATUS_NON_VOLATILE: u1 = 0, STORAGE_DRIVE: u1 = 0, STORAGE_IEPORT: u1 = 0, STORAGE_SLOT: u1 = 0, STORAGE_TRANSPORT: u1 = 0, VOLUME_ASSERT: u1 = 0, VOLUME_IDENTIFICATION: u1 = 0, VOLUME_REPLACE: u1 = 0, VOLUME_SEARCH: u1 = 0, VOLUME_UNDEFINE: u1 = 0, }) CHANGER_FEATURES { return @intToEnum(CHANGER_FEATURES, (if (o.BAR_CODE_SCANNER_INSTALLED == 1) @enumToInt(CHANGER_FEATURES.BAR_CODE_SCANNER_INSTALLED) else 0) | (if (o.CARTRIDGE_MAGAZINE == 1) @enumToInt(CHANGER_FEATURES.CARTRIDGE_MAGAZINE) else 0) | (if (o.CLEANER_ACCESS_NOT_VALID == 1) @enumToInt(CHANGER_FEATURES.CLEANER_ACCESS_NOT_VALID) else 0) | (if (o.CLEANER_SLOT == 1) @enumToInt(CHANGER_FEATURES.CLEANER_SLOT) else 0) | (if (o.CLOSE_IEPORT == 1) @enumToInt(CHANGER_FEATURES.CLOSE_IEPORT) else 0) | (if (o.DEVICE_REINITIALIZE_CAPABLE == 1) @enumToInt(CHANGER_FEATURES.DEVICE_REINITIALIZE_CAPABLE) else 0) | (if (o.DRIVE_CLEANING_REQUIRED == 1) @enumToInt(CHANGER_FEATURES.DRIVE_CLEANING_REQUIRED) else 0) | (if (o.DRIVE_EMPTY_ON_DOOR_ACCESS == 1) @enumToInt(CHANGER_FEATURES.DRIVE_EMPTY_ON_DOOR_ACCESS) else 0) | (if (o.EXCHANGE_MEDIA == 1) @enumToInt(CHANGER_FEATURES.EXCHANGE_MEDIA) else 0) | (if (o.INIT_ELEM_STAT_WITH_RANGE == 1) @enumToInt(CHANGER_FEATURES.INIT_ELEM_STAT_WITH_RANGE) else 0) | (if (o.KEYPAD_ENABLE_DISABLE == 1) @enumToInt(CHANGER_FEATURES.KEYPAD_ENABLE_DISABLE) else 0) | (if (o.LOCK_UNLOCK == 1) @enumToInt(CHANGER_FEATURES.LOCK_UNLOCK) else 0) | (if (o.MEDIUM_FLIP == 1) @enumToInt(CHANGER_FEATURES.MEDIUM_FLIP) else 0) | (if (o.OPEN_IEPORT == 1) @enumToInt(CHANGER_FEATURES.OPEN_IEPORT) else 0) | (if (o.POSITION_TO_ELEMENT == 1) @enumToInt(CHANGER_FEATURES.POSITION_TO_ELEMENT) else 0) | (if (o.PREDISMOUNT_EJECT_REQUIRED == 1) @enumToInt(CHANGER_FEATURES.PREDISMOUNT_EJECT_REQUIRED) else 0) | (if (o.PREMOUNT_EJECT_REQUIRED == 1) @enumToInt(CHANGER_FEATURES.PREMOUNT_EJECT_REQUIRED) else 0) | (if (o.REPORT_IEPORT_STATE == 1) @enumToInt(CHANGER_FEATURES.REPORT_IEPORT_STATE) else 0) | (if (o.SERIAL_NUMBER_VALID == 1) @enumToInt(CHANGER_FEATURES.SERIAL_NUMBER_VALID) else 0) | (if (o.STATUS_NON_VOLATILE == 1) @enumToInt(CHANGER_FEATURES.STATUS_NON_VOLATILE) else 0) | (if (o.STORAGE_DRIVE == 1) @enumToInt(CHANGER_FEATURES.STORAGE_DRIVE) else 0) | (if (o.STORAGE_IEPORT == 1) @enumToInt(CHANGER_FEATURES.STORAGE_IEPORT) else 0) | (if (o.STORAGE_SLOT == 1) @enumToInt(CHANGER_FEATURES.STORAGE_SLOT) else 0) | (if (o.STORAGE_TRANSPORT == 1) @enumToInt(CHANGER_FEATURES.STORAGE_TRANSPORT) else 0) | (if (o.VOLUME_ASSERT == 1) @enumToInt(CHANGER_FEATURES.VOLUME_ASSERT) else 0) | (if (o.VOLUME_IDENTIFICATION == 1) @enumToInt(CHANGER_FEATURES.VOLUME_IDENTIFICATION) else 0) | (if (o.VOLUME_REPLACE == 1) @enumToInt(CHANGER_FEATURES.VOLUME_REPLACE) else 0) | (if (o.VOLUME_SEARCH == 1) @enumToInt(CHANGER_FEATURES.VOLUME_SEARCH) else 0) | (if (o.VOLUME_UNDEFINE == 1) @enumToInt(CHANGER_FEATURES.VOLUME_UNDEFINE) else 0) ); } }; pub const CHANGER_BAR_CODE_SCANNER_INSTALLED = CHANGER_FEATURES.BAR_CODE_SCANNER_INSTALLED; pub const CHANGER_CARTRIDGE_MAGAZINE = CHANGER_FEATURES.CARTRIDGE_MAGAZINE; pub const CHANGER_CLEANER_ACCESS_NOT_VALID = CHANGER_FEATURES.CLEANER_ACCESS_NOT_VALID; pub const CHANGER_CLEANER_SLOT = CHANGER_FEATURES.CLEANER_SLOT; pub const CHANGER_CLOSE_IEPORT = CHANGER_FEATURES.CLOSE_IEPORT; pub const CHANGER_DEVICE_REINITIALIZE_CAPABLE = CHANGER_FEATURES.DEVICE_REINITIALIZE_CAPABLE; pub const CHANGER_DRIVE_CLEANING_REQUIRED = CHANGER_FEATURES.DRIVE_CLEANING_REQUIRED; pub const CHANGER_DRIVE_EMPTY_ON_DOOR_ACCESS = CHANGER_FEATURES.DRIVE_EMPTY_ON_DOOR_ACCESS; pub const CHANGER_EXCHANGE_MEDIA = CHANGER_FEATURES.EXCHANGE_MEDIA; pub const CHANGER_INIT_ELEM_STAT_WITH_RANGE = CHANGER_FEATURES.INIT_ELEM_STAT_WITH_RANGE; pub const CHANGER_KEYPAD_ENABLE_DISABLE = CHANGER_FEATURES.KEYPAD_ENABLE_DISABLE; pub const CHANGER_LOCK_UNLOCK = CHANGER_FEATURES.LOCK_UNLOCK; pub const CHANGER_MEDIUM_FLIP = CHANGER_FEATURES.MEDIUM_FLIP; pub const CHANGER_OPEN_IEPORT = CHANGER_FEATURES.OPEN_IEPORT; pub const CHANGER_POSITION_TO_ELEMENT = CHANGER_FEATURES.POSITION_TO_ELEMENT; pub const CHANGER_PREDISMOUNT_EJECT_REQUIRED = CHANGER_FEATURES.PREDISMOUNT_EJECT_REQUIRED; pub const CHANGER_PREMOUNT_EJECT_REQUIRED = CHANGER_FEATURES.PREMOUNT_EJECT_REQUIRED; pub const CHANGER_REPORT_IEPORT_STATE = CHANGER_FEATURES.REPORT_IEPORT_STATE; pub const CHANGER_SERIAL_NUMBER_VALID = CHANGER_FEATURES.SERIAL_NUMBER_VALID; pub const CHANGER_STATUS_NON_VOLATILE = CHANGER_FEATURES.STATUS_NON_VOLATILE; pub const CHANGER_STORAGE_DRIVE = CHANGER_FEATURES.STORAGE_DRIVE; pub const CHANGER_STORAGE_IEPORT = CHANGER_FEATURES.STORAGE_IEPORT; pub const CHANGER_STORAGE_SLOT = CHANGER_FEATURES.STORAGE_SLOT; pub const CHANGER_STORAGE_TRANSPORT = CHANGER_FEATURES.STORAGE_TRANSPORT; pub const CHANGER_VOLUME_ASSERT = CHANGER_FEATURES.VOLUME_ASSERT; pub const CHANGER_VOLUME_IDENTIFICATION = CHANGER_FEATURES.VOLUME_IDENTIFICATION; pub const CHANGER_VOLUME_REPLACE = CHANGER_FEATURES.VOLUME_REPLACE; pub const CHANGER_VOLUME_SEARCH = CHANGER_FEATURES.VOLUME_SEARCH; pub const CHANGER_VOLUME_UNDEFINE = CHANGER_FEATURES.VOLUME_UNDEFINE; pub const TXFS_RMF_LAGS = enum(u32) { LOGGING_MODE = 1, RENAME_RM = 2, LOG_CONTAINER_COUNT_MAX = 4, LOG_CONTAINER_COUNT_MIN = 8, LOG_GROWTH_INCREMENT_NUM_CONTAINERS = 16, LOG_GROWTH_INCREMENT_PERCENT = 32, LOG_AUTO_SHRINK_PERCENTAGE = 64, LOG_NO_CONTAINER_COUNT_MAX = 128, LOG_NO_CONTAINER_COUNT_MIN = 256, GROW_LOG = 1024, SHRINK_LOG = 2048, ENFORCE_MINIMUM_SIZE = 4096, PRESERVE_CHANGES = 8192, RESET_RM_AT_NEXT_START = 16384, DO_NOT_RESET_RM_AT_NEXT_START = 32768, PREFER_CONSISTENCY = 65536, PREFER_AVAILABILITY = 131072, _, pub fn initFlags(o: struct { LOGGING_MODE: u1 = 0, RENAME_RM: u1 = 0, LOG_CONTAINER_COUNT_MAX: u1 = 0, LOG_CONTAINER_COUNT_MIN: u1 = 0, LOG_GROWTH_INCREMENT_NUM_CONTAINERS: u1 = 0, LOG_GROWTH_INCREMENT_PERCENT: u1 = 0, LOG_AUTO_SHRINK_PERCENTAGE: u1 = 0, LOG_NO_CONTAINER_COUNT_MAX: u1 = 0, LOG_NO_CONTAINER_COUNT_MIN: u1 = 0, GROW_LOG: u1 = 0, SHRINK_LOG: u1 = 0, ENFORCE_MINIMUM_SIZE: u1 = 0, PRESERVE_CHANGES: u1 = 0, RESET_RM_AT_NEXT_START: u1 = 0, DO_NOT_RESET_RM_AT_NEXT_START: u1 = 0, PREFER_CONSISTENCY: u1 = 0, PREFER_AVAILABILITY: u1 = 0, }) TXFS_RMF_LAGS { return @intToEnum(TXFS_RMF_LAGS, (if (o.LOGGING_MODE == 1) @enumToInt(TXFS_RMF_LAGS.LOGGING_MODE) else 0) | (if (o.RENAME_RM == 1) @enumToInt(TXFS_RMF_LAGS.RENAME_RM) else 0) | (if (o.LOG_CONTAINER_COUNT_MAX == 1) @enumToInt(TXFS_RMF_LAGS.LOG_CONTAINER_COUNT_MAX) else 0) | (if (o.LOG_CONTAINER_COUNT_MIN == 1) @enumToInt(TXFS_RMF_LAGS.LOG_CONTAINER_COUNT_MIN) else 0) | (if (o.LOG_GROWTH_INCREMENT_NUM_CONTAINERS == 1) @enumToInt(TXFS_RMF_LAGS.LOG_GROWTH_INCREMENT_NUM_CONTAINERS) else 0) | (if (o.LOG_GROWTH_INCREMENT_PERCENT == 1) @enumToInt(TXFS_RMF_LAGS.LOG_GROWTH_INCREMENT_PERCENT) else 0) | (if (o.LOG_AUTO_SHRINK_PERCENTAGE == 1) @enumToInt(TXFS_RMF_LAGS.LOG_AUTO_SHRINK_PERCENTAGE) else 0) | (if (o.LOG_NO_CONTAINER_COUNT_MAX == 1) @enumToInt(TXFS_RMF_LAGS.LOG_NO_CONTAINER_COUNT_MAX) else 0) | (if (o.LOG_NO_CONTAINER_COUNT_MIN == 1) @enumToInt(TXFS_RMF_LAGS.LOG_NO_CONTAINER_COUNT_MIN) else 0) | (if (o.GROW_LOG == 1) @enumToInt(TXFS_RMF_LAGS.GROW_LOG) else 0) | (if (o.SHRINK_LOG == 1) @enumToInt(TXFS_RMF_LAGS.SHRINK_LOG) else 0) | (if (o.ENFORCE_MINIMUM_SIZE == 1) @enumToInt(TXFS_RMF_LAGS.ENFORCE_MINIMUM_SIZE) else 0) | (if (o.PRESERVE_CHANGES == 1) @enumToInt(TXFS_RMF_LAGS.PRESERVE_CHANGES) else 0) | (if (o.RESET_RM_AT_NEXT_START == 1) @enumToInt(TXFS_RMF_LAGS.RESET_RM_AT_NEXT_START) else 0) | (if (o.DO_NOT_RESET_RM_AT_NEXT_START == 1) @enumToInt(TXFS_RMF_LAGS.DO_NOT_RESET_RM_AT_NEXT_START) else 0) | (if (o.PREFER_CONSISTENCY == 1) @enumToInt(TXFS_RMF_LAGS.PREFER_CONSISTENCY) else 0) | (if (o.PREFER_AVAILABILITY == 1) @enumToInt(TXFS_RMF_LAGS.PREFER_AVAILABILITY) else 0) ); } }; pub const TXFS_RM_FLAG_LOGGING_MODE = TXFS_RMF_LAGS.LOGGING_MODE; pub const TXFS_RM_FLAG_RENAME_RM = TXFS_RMF_LAGS.RENAME_RM; pub const TXFS_RM_FLAG_LOG_CONTAINER_COUNT_MAX = TXFS_RMF_LAGS.LOG_CONTAINER_COUNT_MAX; pub const TXFS_RM_FLAG_LOG_CONTAINER_COUNT_MIN = TXFS_RMF_LAGS.LOG_CONTAINER_COUNT_MIN; pub const TXFS_RM_FLAG_LOG_GROWTH_INCREMENT_NUM_CONTAINERS = TXFS_RMF_LAGS.LOG_GROWTH_INCREMENT_NUM_CONTAINERS; pub const TXFS_RM_FLAG_LOG_GROWTH_INCREMENT_PERCENT = TXFS_RMF_LAGS.LOG_GROWTH_INCREMENT_PERCENT; pub const TXFS_RM_FLAG_LOG_AUTO_SHRINK_PERCENTAGE = TXFS_RMF_LAGS.LOG_AUTO_SHRINK_PERCENTAGE; pub const TXFS_RM_FLAG_LOG_NO_CONTAINER_COUNT_MAX = TXFS_RMF_LAGS.LOG_NO_CONTAINER_COUNT_MAX; pub const TXFS_RM_FLAG_LOG_NO_CONTAINER_COUNT_MIN = TXFS_RMF_LAGS.LOG_NO_CONTAINER_COUNT_MIN; pub const TXFS_RM_FLAG_GROW_LOG = TXFS_RMF_LAGS.GROW_LOG; pub const TXFS_RM_FLAG_SHRINK_LOG = TXFS_RMF_LAGS.SHRINK_LOG; pub const TXFS_RM_FLAG_ENFORCE_MINIMUM_SIZE = TXFS_RMF_LAGS.ENFORCE_MINIMUM_SIZE; pub const TXFS_RM_FLAG_PRESERVE_CHANGES = TXFS_RMF_LAGS.PRESERVE_CHANGES; pub const TXFS_RM_FLAG_RESET_RM_AT_NEXT_START = TXFS_RMF_LAGS.RESET_RM_AT_NEXT_START; pub const TXFS_RM_FLAG_DO_NOT_RESET_RM_AT_NEXT_START = TXFS_RMF_LAGS.DO_NOT_RESET_RM_AT_NEXT_START; pub const TXFS_RM_FLAG_PREFER_CONSISTENCY = TXFS_RMF_LAGS.PREFER_CONSISTENCY; pub const TXFS_RM_FLAG_PREFER_AVAILABILITY = TXFS_RMF_LAGS.PREFER_AVAILABILITY; pub const FILESYSTEM_STATISTICS_TYPE = enum(u16) { EXFAT = 3, FAT = 2, NTFS = 1, }; pub const FILESYSTEM_STATISTICS_TYPE_EXFAT = FILESYSTEM_STATISTICS_TYPE.EXFAT; pub const FILESYSTEM_STATISTICS_TYPE_FAT = FILESYSTEM_STATISTICS_TYPE.FAT; pub const FILESYSTEM_STATISTICS_TYPE_NTFS = FILESYSTEM_STATISTICS_TYPE.NTFS; pub const USN_SOURCE_INFO_ID = enum(u32) { AUXILIARY_DATA = 2, DATA_MANAGEMENT = 1, REPLICATION_MANAGEMENT = 4, CLIENT_REPLICATION_MANAGEMENT = 8, }; pub const USN_SOURCE_AUXILIARY_DATA = USN_SOURCE_INFO_ID.AUXILIARY_DATA; pub const USN_SOURCE_DATA_MANAGEMENT = USN_SOURCE_INFO_ID.DATA_MANAGEMENT; pub const USN_SOURCE_REPLICATION_MANAGEMENT = USN_SOURCE_INFO_ID.REPLICATION_MANAGEMENT; pub const USN_SOURCE_CLIENT_REPLICATION_MANAGEMENT = USN_SOURCE_INFO_ID.CLIENT_REPLICATION_MANAGEMENT; pub const FILE_STORAGE_TIER_FLAGS = enum(u32) { Y = 131072, _, pub fn initFlags(o: struct { Y: u1 = 0, }) FILE_STORAGE_TIER_FLAGS { return @intToEnum(FILE_STORAGE_TIER_FLAGS, (if (o.Y == 1) @enumToInt(FILE_STORAGE_TIER_FLAGS.Y) else 0) ); } }; pub const FILE_STORAGE_TIER_FLAG_NO_SEEK_PENALTY = FILE_STORAGE_TIER_FLAGS.Y; pub const CHANGER_ELEMENT_STATUS_FLAGS = enum(u32) { ACCESS = 8, AVOLTAG = 536870912, EXCEPT = 4, EXENAB = 16, FULL = 1, ID_VALID = 8192, IMPEXP = 2, INENAB = 32, INVERT = 4194304, LUN_VALID = 4096, NOT_BUS = 32768, PVOLTAG = 268435456, SVALID = 8388608, PRODUCT_DATA = 64, _, pub fn initFlags(o: struct { ACCESS: u1 = 0, AVOLTAG: u1 = 0, EXCEPT: u1 = 0, EXENAB: u1 = 0, FULL: u1 = 0, ID_VALID: u1 = 0, IMPEXP: u1 = 0, INENAB: u1 = 0, INVERT: u1 = 0, LUN_VALID: u1 = 0, NOT_BUS: u1 = 0, PVOLTAG: u1 = 0, SVALID: u1 = 0, PRODUCT_DATA: u1 = 0, }) CHANGER_ELEMENT_STATUS_FLAGS { return @intToEnum(CHANGER_ELEMENT_STATUS_FLAGS, (if (o.ACCESS == 1) @enumToInt(CHANGER_ELEMENT_STATUS_FLAGS.ACCESS) else 0) | (if (o.AVOLTAG == 1) @enumToInt(CHANGER_ELEMENT_STATUS_FLAGS.AVOLTAG) else 0) | (if (o.EXCEPT == 1) @enumToInt(CHANGER_ELEMENT_STATUS_FLAGS.EXCEPT) else 0) | (if (o.EXENAB == 1) @enumToInt(CHANGER_ELEMENT_STATUS_FLAGS.EXENAB) else 0) | (if (o.FULL == 1) @enumToInt(CHANGER_ELEMENT_STATUS_FLAGS.FULL) else 0) | (if (o.ID_VALID == 1) @enumToInt(CHANGER_ELEMENT_STATUS_FLAGS.ID_VALID) else 0) | (if (o.IMPEXP == 1) @enumToInt(CHANGER_ELEMENT_STATUS_FLAGS.IMPEXP) else 0) | (if (o.INENAB == 1) @enumToInt(CHANGER_ELEMENT_STATUS_FLAGS.INENAB) else 0) | (if (o.INVERT == 1) @enumToInt(CHANGER_ELEMENT_STATUS_FLAGS.INVERT) else 0) | (if (o.LUN_VALID == 1) @enumToInt(CHANGER_ELEMENT_STATUS_FLAGS.LUN_VALID) else 0) | (if (o.NOT_BUS == 1) @enumToInt(CHANGER_ELEMENT_STATUS_FLAGS.NOT_BUS) else 0) | (if (o.PVOLTAG == 1) @enumToInt(CHANGER_ELEMENT_STATUS_FLAGS.PVOLTAG) else 0) | (if (o.SVALID == 1) @enumToInt(CHANGER_ELEMENT_STATUS_FLAGS.SVALID) else 0) | (if (o.PRODUCT_DATA == 1) @enumToInt(CHANGER_ELEMENT_STATUS_FLAGS.PRODUCT_DATA) else 0) ); } }; pub const ELEMENT_STATUS_ACCESS = CHANGER_ELEMENT_STATUS_FLAGS.ACCESS; pub const ELEMENT_STATUS_AVOLTAG = CHANGER_ELEMENT_STATUS_FLAGS.AVOLTAG; pub const ELEMENT_STATUS_EXCEPT = CHANGER_ELEMENT_STATUS_FLAGS.EXCEPT; pub const ELEMENT_STATUS_EXENAB = CHANGER_ELEMENT_STATUS_FLAGS.EXENAB; pub const ELEMENT_STATUS_FULL = CHANGER_ELEMENT_STATUS_FLAGS.FULL; pub const ELEMENT_STATUS_ID_VALID = CHANGER_ELEMENT_STATUS_FLAGS.ID_VALID; pub const ELEMENT_STATUS_IMPEXP = CHANGER_ELEMENT_STATUS_FLAGS.IMPEXP; pub const ELEMENT_STATUS_INENAB = CHANGER_ELEMENT_STATUS_FLAGS.INENAB; pub const ELEMENT_STATUS_INVERT = CHANGER_ELEMENT_STATUS_FLAGS.INVERT; pub const ELEMENT_STATUS_LUN_VALID = CHANGER_ELEMENT_STATUS_FLAGS.LUN_VALID; pub const ELEMENT_STATUS_NOT_BUS = CHANGER_ELEMENT_STATUS_FLAGS.NOT_BUS; pub const ELEMENT_STATUS_PVOLTAG = CHANGER_ELEMENT_STATUS_FLAGS.PVOLTAG; pub const ELEMENT_STATUS_SVALID = CHANGER_ELEMENT_STATUS_FLAGS.SVALID; pub const ELEMENT_STATUS_PRODUCT_DATA = CHANGER_ELEMENT_STATUS_FLAGS.PRODUCT_DATA; pub const GET_CHANGER_PARAMETERS_FEATURES1 = enum(u32) { CLEANER_AUTODISMOUNT = 2147483652, CLEANER_OPS_NOT_SUPPORTED = 2147483712, IEPORT_USER_CONTROL_CLOSE = 2147483904, IEPORT_USER_CONTROL_OPEN = 2147483776, MOVE_EXTENDS_IEPORT = 2147484160, MOVE_RETRACTS_IEPORT = 2147484672, PREDISMOUNT_ALIGN_TO_DRIVE = 2147483650, PREDISMOUNT_ALIGN_TO_SLOT = 2147483649, RTN_MEDIA_TO_ORIGINAL_ADDR = 2147483680, SLOTS_USE_TRAYS = 2147483664, TRUE_EXCHANGE_CAPABLE = 2147483656, _, pub fn initFlags(o: struct { CLEANER_AUTODISMOUNT: u1 = 0, CLEANER_OPS_NOT_SUPPORTED: u1 = 0, IEPORT_USER_CONTROL_CLOSE: u1 = 0, IEPORT_USER_CONTROL_OPEN: u1 = 0, MOVE_EXTENDS_IEPORT: u1 = 0, MOVE_RETRACTS_IEPORT: u1 = 0, PREDISMOUNT_ALIGN_TO_DRIVE: u1 = 0, PREDISMOUNT_ALIGN_TO_SLOT: u1 = 0, RTN_MEDIA_TO_ORIGINAL_ADDR: u1 = 0, SLOTS_USE_TRAYS: u1 = 0, TRUE_EXCHANGE_CAPABLE: u1 = 0, }) GET_CHANGER_PARAMETERS_FEATURES1 { return @intToEnum(GET_CHANGER_PARAMETERS_FEATURES1, (if (o.CLEANER_AUTODISMOUNT == 1) @enumToInt(GET_CHANGER_PARAMETERS_FEATURES1.CLEANER_AUTODISMOUNT) else 0) | (if (o.CLEANER_OPS_NOT_SUPPORTED == 1) @enumToInt(GET_CHANGER_PARAMETERS_FEATURES1.CLEANER_OPS_NOT_SUPPORTED) else 0) | (if (o.IEPORT_USER_CONTROL_CLOSE == 1) @enumToInt(GET_CHANGER_PARAMETERS_FEATURES1.IEPORT_USER_CONTROL_CLOSE) else 0) | (if (o.IEPORT_USER_CONTROL_OPEN == 1) @enumToInt(GET_CHANGER_PARAMETERS_FEATURES1.IEPORT_USER_CONTROL_OPEN) else 0) | (if (o.MOVE_EXTENDS_IEPORT == 1) @enumToInt(GET_CHANGER_PARAMETERS_FEATURES1.MOVE_EXTENDS_IEPORT) else 0) | (if (o.MOVE_RETRACTS_IEPORT == 1) @enumToInt(GET_CHANGER_PARAMETERS_FEATURES1.MOVE_RETRACTS_IEPORT) else 0) | (if (o.PREDISMOUNT_ALIGN_TO_DRIVE == 1) @enumToInt(GET_CHANGER_PARAMETERS_FEATURES1.PREDISMOUNT_ALIGN_TO_DRIVE) else 0) | (if (o.PREDISMOUNT_ALIGN_TO_SLOT == 1) @enumToInt(GET_CHANGER_PARAMETERS_FEATURES1.PREDISMOUNT_ALIGN_TO_SLOT) else 0) | (if (o.RTN_MEDIA_TO_ORIGINAL_ADDR == 1) @enumToInt(GET_CHANGER_PARAMETERS_FEATURES1.RTN_MEDIA_TO_ORIGINAL_ADDR) else 0) | (if (o.SLOTS_USE_TRAYS == 1) @enumToInt(GET_CHANGER_PARAMETERS_FEATURES1.SLOTS_USE_TRAYS) else 0) | (if (o.TRUE_EXCHANGE_CAPABLE == 1) @enumToInt(GET_CHANGER_PARAMETERS_FEATURES1.TRUE_EXCHANGE_CAPABLE) else 0) ); } }; pub const CHANGER_CLEANER_AUTODISMOUNT = GET_CHANGER_PARAMETERS_FEATURES1.CLEANER_AUTODISMOUNT; pub const CHANGER_CLEANER_OPS_NOT_SUPPORTED = GET_CHANGER_PARAMETERS_FEATURES1.CLEANER_OPS_NOT_SUPPORTED; pub const CHANGER_IEPORT_USER_CONTROL_CLOSE = GET_CHANGER_PARAMETERS_FEATURES1.IEPORT_USER_CONTROL_CLOSE; pub const CHANGER_IEPORT_USER_CONTROL_OPEN = GET_CHANGER_PARAMETERS_FEATURES1.IEPORT_USER_CONTROL_OPEN; pub const CHANGER_MOVE_EXTENDS_IEPORT = GET_CHANGER_PARAMETERS_FEATURES1.MOVE_EXTENDS_IEPORT; pub const CHANGER_MOVE_RETRACTS_IEPORT = GET_CHANGER_PARAMETERS_FEATURES1.MOVE_RETRACTS_IEPORT; pub const CHANGER_PREDISMOUNT_ALIGN_TO_DRIVE = GET_CHANGER_PARAMETERS_FEATURES1.PREDISMOUNT_ALIGN_TO_DRIVE; pub const CHANGER_PREDISMOUNT_ALIGN_TO_SLOT = GET_CHANGER_PARAMETERS_FEATURES1.PREDISMOUNT_ALIGN_TO_SLOT; pub const CHANGER_RTN_MEDIA_TO_ORIGINAL_ADDR = GET_CHANGER_PARAMETERS_FEATURES1.RTN_MEDIA_TO_ORIGINAL_ADDR; pub const CHANGER_SLOTS_USE_TRAYS = GET_CHANGER_PARAMETERS_FEATURES1.SLOTS_USE_TRAYS; pub const CHANGER_TRUE_EXCHANGE_CAPABLE = GET_CHANGER_PARAMETERS_FEATURES1.TRUE_EXCHANGE_CAPABLE; pub const STORAGE_HOTPLUG_INFO = extern struct { Size: u32, MediaRemovable: BOOLEAN, MediaHotplug: BOOLEAN, DeviceHotplug: BOOLEAN, WriteCacheEnableOverride: BOOLEAN, }; pub const STORAGE_DEVICE_NUMBER = extern struct { DeviceType: u32, DeviceNumber: u32, PartitionNumber: u32, }; pub const STORAGE_DEVICE_NUMBERS = extern struct { Version: u32, Size: u32, NumberOfDevices: u32, Devices: [1]STORAGE_DEVICE_NUMBER, }; pub const STORAGE_DEVICE_NUMBER_EX = extern struct { Version: u32, Size: u32, Flags: u32, DeviceType: u32, DeviceNumber: u32, DeviceGuid: Guid, PartitionNumber: u32, }; pub const STORAGE_BUS_RESET_REQUEST = extern struct { PathId: u8, }; pub const STORAGE_BREAK_RESERVATION_REQUEST = extern struct { Length: u32, _unused: u8, PathId: u8, TargetId: u8, Lun: u8, }; pub const PREVENT_MEDIA_REMOVAL = extern struct { PreventMediaRemoval: BOOLEAN, }; pub const CLASS_MEDIA_CHANGE_CONTEXT = extern struct { MediaChangeCount: u32, NewState: u32, }; pub const TAPE_STATISTICS = extern struct { Version: u32, Flags: u32, RecoveredWrites: LARGE_INTEGER, UnrecoveredWrites: LARGE_INTEGER, RecoveredReads: LARGE_INTEGER, UnrecoveredReads: LARGE_INTEGER, CompressionRatioReads: u8, CompressionRatioWrites: u8, }; pub const TAPE_GET_STATISTICS = extern struct { Operation: u32, }; pub const STORAGE_MEDIA_TYPE = enum(i32) { DDS_4mm = 32, MiniQic = 33, Travan = 34, QIC = 35, MP_8mm = 36, AME_8mm = 37, AIT1_8mm = 38, DLT = 39, NCTP = 40, IBM_3480 = 41, IBM_3490E = 42, IBM_Magstar_3590 = 43, IBM_Magstar_MP = 44, STK_DATA_D3 = 45, SONY_DTF = 46, DV_6mm = 47, DMI = 48, SONY_D2 = 49, CLEANER_CARTRIDGE = 50, CD_ROM = 51, CD_R = 52, CD_RW = 53, DVD_ROM = 54, DVD_R = 55, DVD_RW = 56, MO_3_RW = 57, MO_5_WO = 58, MO_5_RW = 59, MO_5_LIMDOW = 60, PC_5_WO = 61, PC_5_RW = 62, PD_5_RW = 63, ABL_5_WO = 64, PINNACLE_APEX_5_RW = 65, SONY_12_WO = 66, PHILIPS_12_WO = 67, HITACHI_12_WO = 68, CYGNET_12_WO = 69, KODAK_14_WO = 70, MO_NFR_525 = 71, NIKON_12_RW = 72, IOMEGA_ZIP = 73, IOMEGA_JAZ = 74, SYQUEST_EZ135 = 75, SYQUEST_EZFLYER = 76, SYQUEST_SYJET = 77, AVATAR_F2 = 78, MP2_8mm = 79, DST_S = 80, DST_M = 81, DST_L = 82, VXATape_1 = 83, VXATape_2 = 84, STK_9840 = 85, LTO_Ultrium = 86, LTO_Accelis = 87, DVD_RAM = 88, AIT_8mm = 89, ADR_1 = 90, ADR_2 = 91, STK_9940 = 92, SAIT = 93, VXATape = 94, }; pub const DDS_4mm = STORAGE_MEDIA_TYPE.DDS_4mm; pub const MiniQic = STORAGE_MEDIA_TYPE.MiniQic; pub const Travan = STORAGE_MEDIA_TYPE.Travan; pub const QIC = STORAGE_MEDIA_TYPE.QIC; pub const MP_8mm = STORAGE_MEDIA_TYPE.MP_8mm; pub const AME_8mm = STORAGE_MEDIA_TYPE.AME_8mm; pub const AIT1_8mm = STORAGE_MEDIA_TYPE.AIT1_8mm; pub const DLT = STORAGE_MEDIA_TYPE.DLT; pub const NCTP = STORAGE_MEDIA_TYPE.NCTP; pub const IBM_3480 = STORAGE_MEDIA_TYPE.IBM_3480; pub const IBM_3490E = STORAGE_MEDIA_TYPE.IBM_3490E; pub const IBM_Magstar_3590 = STORAGE_MEDIA_TYPE.IBM_Magstar_3590; pub const IBM_Magstar_MP = STORAGE_MEDIA_TYPE.IBM_Magstar_MP; pub const STK_DATA_D3 = STORAGE_MEDIA_TYPE.STK_DATA_D3; pub const SONY_DTF = STORAGE_MEDIA_TYPE.SONY_DTF; pub const DV_6mm = STORAGE_MEDIA_TYPE.DV_6mm; pub const DMI = STORAGE_MEDIA_TYPE.DMI; pub const SONY_D2 = STORAGE_MEDIA_TYPE.SONY_D2; pub const CLEANER_CARTRIDGE = STORAGE_MEDIA_TYPE.CLEANER_CARTRIDGE; pub const CD_ROM = STORAGE_MEDIA_TYPE.CD_ROM; pub const CD_R = STORAGE_MEDIA_TYPE.CD_R; pub const CD_RW = STORAGE_MEDIA_TYPE.CD_RW; pub const DVD_ROM = STORAGE_MEDIA_TYPE.DVD_ROM; pub const DVD_R = STORAGE_MEDIA_TYPE.DVD_R; pub const DVD_RW = STORAGE_MEDIA_TYPE.DVD_RW; pub const MO_3_RW = STORAGE_MEDIA_TYPE.MO_3_RW; pub const MO_5_WO = STORAGE_MEDIA_TYPE.MO_5_WO; pub const MO_5_RW = STORAGE_MEDIA_TYPE.MO_5_RW; pub const MO_5_LIMDOW = STORAGE_MEDIA_TYPE.MO_5_LIMDOW; pub const PC_5_WO = STORAGE_MEDIA_TYPE.PC_5_WO; pub const PC_5_RW = STORAGE_MEDIA_TYPE.PC_5_RW; pub const PD_5_RW = STORAGE_MEDIA_TYPE.PD_5_RW; pub const ABL_5_WO = STORAGE_MEDIA_TYPE.ABL_5_WO; pub const PINNACLE_APEX_5_RW = STORAGE_MEDIA_TYPE.PINNACLE_APEX_5_RW; pub const SONY_12_WO = STORAGE_MEDIA_TYPE.SONY_12_WO; pub const PHILIPS_12_WO = STORAGE_MEDIA_TYPE.PHILIPS_12_WO; pub const HITACHI_12_WO = STORAGE_MEDIA_TYPE.HITACHI_12_WO; pub const CYGNET_12_WO = STORAGE_MEDIA_TYPE.CYGNET_12_WO; pub const KODAK_14_WO = STORAGE_MEDIA_TYPE.KODAK_14_WO; pub const MO_NFR_525 = STORAGE_MEDIA_TYPE.MO_NFR_525; pub const NIKON_12_RW = STORAGE_MEDIA_TYPE.NIKON_12_RW; pub const IOMEGA_ZIP = STORAGE_MEDIA_TYPE.IOMEGA_ZIP; pub const IOMEGA_JAZ = STORAGE_MEDIA_TYPE.IOMEGA_JAZ; pub const SYQUEST_EZ135 = STORAGE_MEDIA_TYPE.SYQUEST_EZ135; pub const SYQUEST_EZFLYER = STORAGE_MEDIA_TYPE.SYQUEST_EZFLYER; pub const SYQUEST_SYJET = STORAGE_MEDIA_TYPE.SYQUEST_SYJET; pub const AVATAR_F2 = STORAGE_MEDIA_TYPE.AVATAR_F2; pub const MP2_8mm = STORAGE_MEDIA_TYPE.MP2_8mm; pub const DST_S = STORAGE_MEDIA_TYPE.DST_S; pub const DST_M = STORAGE_MEDIA_TYPE.DST_M; pub const DST_L = STORAGE_MEDIA_TYPE.DST_L; pub const VXATape_1 = STORAGE_MEDIA_TYPE.VXATape_1; pub const VXATape_2 = STORAGE_MEDIA_TYPE.VXATape_2; pub const STK_9840 = STORAGE_MEDIA_TYPE.STK_9840; pub const LTO_Ultrium = STORAGE_MEDIA_TYPE.LTO_Ultrium; pub const LTO_Accelis = STORAGE_MEDIA_TYPE.LTO_Accelis; pub const DVD_RAM = STORAGE_MEDIA_TYPE.DVD_RAM; pub const AIT_8mm = STORAGE_MEDIA_TYPE.AIT_8mm; pub const ADR_1 = STORAGE_MEDIA_TYPE.ADR_1; pub const ADR_2 = STORAGE_MEDIA_TYPE.ADR_2; pub const STK_9940 = STORAGE_MEDIA_TYPE.STK_9940; pub const SAIT = STORAGE_MEDIA_TYPE.SAIT; pub const VXATape = STORAGE_MEDIA_TYPE.VXATape; pub const DEVICE_MEDIA_INFO = extern struct { DeviceSpecific: extern union { DiskInfo: extern struct { Cylinders: LARGE_INTEGER, MediaType: STORAGE_MEDIA_TYPE, TracksPerCylinder: u32, SectorsPerTrack: u32, BytesPerSector: u32, NumberMediaSides: u32, MediaCharacteristics: u32, }, RemovableDiskInfo: extern struct { Cylinders: LARGE_INTEGER, MediaType: STORAGE_MEDIA_TYPE, TracksPerCylinder: u32, SectorsPerTrack: u32, BytesPerSector: u32, NumberMediaSides: u32, MediaCharacteristics: u32, }, TapeInfo: extern struct { MediaType: STORAGE_MEDIA_TYPE, MediaCharacteristics: u32, CurrentBlockSize: u32, BusType: STORAGE_BUS_TYPE, BusSpecificData: extern union { ScsiInformation: extern struct { MediumType: u8, DensityCode: u8, }, }, }, }, }; pub const GET_MEDIA_TYPES = extern struct { DeviceType: u32, MediaInfoCount: u32, MediaInfo: [1]DEVICE_MEDIA_INFO, }; pub const STORAGE_PREDICT_FAILURE = extern struct { PredictFailure: u32, VendorSpecific: [512]u8, }; pub const STORAGE_FAILURE_PREDICTION_CONFIG = extern struct { Version: u32, Size: u32, Set: BOOLEAN, Enabled: BOOLEAN, Reserved: u16, }; pub const STORAGE_QUERY_TYPE = enum(i32) { StandardQuery = 0, ExistsQuery = 1, MaskQuery = 2, QueryMaxDefined = 3, }; pub const PropertyStandardQuery = STORAGE_QUERY_TYPE.StandardQuery; pub const PropertyExistsQuery = STORAGE_QUERY_TYPE.ExistsQuery; pub const PropertyMaskQuery = STORAGE_QUERY_TYPE.MaskQuery; pub const PropertyQueryMaxDefined = STORAGE_QUERY_TYPE.QueryMaxDefined; pub const STORAGE_SET_TYPE = enum(i32) { StandardSet = 0, ExistsSet = 1, SetMaxDefined = 2, }; pub const PropertyStandardSet = STORAGE_SET_TYPE.StandardSet; pub const PropertyExistsSet = STORAGE_SET_TYPE.ExistsSet; pub const PropertySetMaxDefined = STORAGE_SET_TYPE.SetMaxDefined; pub const STORAGE_PROPERTY_ID = enum(i32) { DeviceProperty = 0, AdapterProperty = 1, DeviceIdProperty = 2, DeviceUniqueIdProperty = 3, DeviceWriteCacheProperty = 4, MiniportProperty = 5, AccessAlignmentProperty = 6, DeviceSeekPenaltyProperty = 7, DeviceTrimProperty = 8, DeviceWriteAggregationProperty = 9, DeviceDeviceTelemetryProperty = 10, DeviceLBProvisioningProperty = 11, DevicePowerProperty = 12, DeviceCopyOffloadProperty = 13, DeviceResiliencyProperty = 14, DeviceMediumProductType = 15, AdapterRpmbProperty = 16, AdapterCryptoProperty = 17, DeviceIoCapabilityProperty = 48, AdapterProtocolSpecificProperty = 49, DeviceProtocolSpecificProperty = 50, AdapterTemperatureProperty = 51, DeviceTemperatureProperty = 52, AdapterPhysicalTopologyProperty = 53, DevicePhysicalTopologyProperty = 54, DeviceAttributesProperty = 55, DeviceManagementStatus = 56, AdapterSerialNumberProperty = 57, DeviceLocationProperty = 58, DeviceNumaProperty = 59, DeviceZonedDeviceProperty = 60, DeviceUnsafeShutdownCount = 61, DeviceEnduranceProperty = 62, DeviceLedStateProperty = 63, DeviceSelfEncryptionProperty = 64, FruIdProperty = 65, }; pub const StorageDeviceProperty = STORAGE_PROPERTY_ID.DeviceProperty; pub const StorageAdapterProperty = STORAGE_PROPERTY_ID.AdapterProperty; pub const StorageDeviceIdProperty = STORAGE_PROPERTY_ID.DeviceIdProperty; pub const StorageDeviceUniqueIdProperty = STORAGE_PROPERTY_ID.DeviceUniqueIdProperty; pub const StorageDeviceWriteCacheProperty = STORAGE_PROPERTY_ID.DeviceWriteCacheProperty; pub const StorageMiniportProperty = STORAGE_PROPERTY_ID.MiniportProperty; pub const StorageAccessAlignmentProperty = STORAGE_PROPERTY_ID.AccessAlignmentProperty; pub const StorageDeviceSeekPenaltyProperty = STORAGE_PROPERTY_ID.DeviceSeekPenaltyProperty; pub const StorageDeviceTrimProperty = STORAGE_PROPERTY_ID.DeviceTrimProperty; pub const StorageDeviceWriteAggregationProperty = STORAGE_PROPERTY_ID.DeviceWriteAggregationProperty; pub const StorageDeviceDeviceTelemetryProperty = STORAGE_PROPERTY_ID.DeviceDeviceTelemetryProperty; pub const StorageDeviceLBProvisioningProperty = STORAGE_PROPERTY_ID.DeviceLBProvisioningProperty; pub const StorageDevicePowerProperty = STORAGE_PROPERTY_ID.DevicePowerProperty; pub const StorageDeviceCopyOffloadProperty = STORAGE_PROPERTY_ID.DeviceCopyOffloadProperty; pub const StorageDeviceResiliencyProperty = STORAGE_PROPERTY_ID.DeviceResiliencyProperty; pub const StorageDeviceMediumProductType = STORAGE_PROPERTY_ID.DeviceMediumProductType; pub const StorageAdapterRpmbProperty = STORAGE_PROPERTY_ID.AdapterRpmbProperty; pub const StorageAdapterCryptoProperty = STORAGE_PROPERTY_ID.AdapterCryptoProperty; pub const StorageDeviceIoCapabilityProperty = STORAGE_PROPERTY_ID.DeviceIoCapabilityProperty; pub const StorageAdapterProtocolSpecificProperty = STORAGE_PROPERTY_ID.AdapterProtocolSpecificProperty; pub const StorageDeviceProtocolSpecificProperty = STORAGE_PROPERTY_ID.DeviceProtocolSpecificProperty; pub const StorageAdapterTemperatureProperty = STORAGE_PROPERTY_ID.AdapterTemperatureProperty; pub const StorageDeviceTemperatureProperty = STORAGE_PROPERTY_ID.DeviceTemperatureProperty; pub const StorageAdapterPhysicalTopologyProperty = STORAGE_PROPERTY_ID.AdapterPhysicalTopologyProperty; pub const StorageDevicePhysicalTopologyProperty = STORAGE_PROPERTY_ID.DevicePhysicalTopologyProperty; pub const StorageDeviceAttributesProperty = STORAGE_PROPERTY_ID.DeviceAttributesProperty; pub const StorageDeviceManagementStatus = STORAGE_PROPERTY_ID.DeviceManagementStatus; pub const StorageAdapterSerialNumberProperty = STORAGE_PROPERTY_ID.AdapterSerialNumberProperty; pub const StorageDeviceLocationProperty = STORAGE_PROPERTY_ID.DeviceLocationProperty; pub const StorageDeviceNumaProperty = STORAGE_PROPERTY_ID.DeviceNumaProperty; pub const StorageDeviceZonedDeviceProperty = STORAGE_PROPERTY_ID.DeviceZonedDeviceProperty; pub const StorageDeviceUnsafeShutdownCount = STORAGE_PROPERTY_ID.DeviceUnsafeShutdownCount; pub const StorageDeviceEnduranceProperty = STORAGE_PROPERTY_ID.DeviceEnduranceProperty; pub const StorageDeviceLedStateProperty = STORAGE_PROPERTY_ID.DeviceLedStateProperty; pub const StorageDeviceSelfEncryptionProperty = STORAGE_PROPERTY_ID.DeviceSelfEncryptionProperty; pub const StorageFruIdProperty = STORAGE_PROPERTY_ID.FruIdProperty; pub const STORAGE_PROPERTY_QUERY = extern struct { PropertyId: STORAGE_PROPERTY_ID, QueryType: STORAGE_QUERY_TYPE, AdditionalParameters: [1]u8, }; pub const STORAGE_PROPERTY_SET = extern struct { PropertyId: STORAGE_PROPERTY_ID, SetType: STORAGE_SET_TYPE, AdditionalParameters: [1]u8, }; pub const STORAGE_DESCRIPTOR_HEADER = extern struct { Version: u32, Size: u32, }; pub const STORAGE_DEVICE_DESCRIPTOR = extern struct { Version: u32, Size: u32, DeviceType: u8, DeviceTypeModifier: u8, RemovableMedia: BOOLEAN, CommandQueueing: BOOLEAN, VendorIdOffset: u32, ProductIdOffset: u32, ProductRevisionOffset: u32, SerialNumberOffset: u32, BusType: STORAGE_BUS_TYPE, RawPropertiesLength: u32, RawDeviceProperties: [1]u8, }; pub const STORAGE_ADAPTER_DESCRIPTOR = extern struct { Version: u32, Size: u32, MaximumTransferLength: u32, MaximumPhysicalPages: u32, AlignmentMask: u32, AdapterUsesPio: BOOLEAN, AdapterScansDown: BOOLEAN, CommandQueueing: BOOLEAN, AcceleratedTransfer: BOOLEAN, BusType: u8, BusMajorVersion: u16, BusMinorVersion: u16, SrbType: u8, AddressType: u8, }; pub const STORAGE_ACCESS_ALIGNMENT_DESCRIPTOR = extern struct { Version: u32, Size: u32, BytesPerCacheLine: u32, BytesOffsetForCacheAlignment: u32, BytesPerLogicalSector: u32, BytesPerPhysicalSector: u32, BytesOffsetForSectorAlignment: u32, }; pub const STORAGE_MEDIUM_PRODUCT_TYPE_DESCRIPTOR = extern struct { Version: u32, Size: u32, MediumProductType: u32, }; pub const STORAGE_PORT_CODE_SET = enum(i32) { Reserved = 0, Storport = 1, SCSIport = 2, Spaceport = 3, ATAport = 4, USBport = 5, SBP2port = 6, SDport = 7, }; pub const StoragePortCodeSetReserved = STORAGE_PORT_CODE_SET.Reserved; pub const StoragePortCodeSetStorport = STORAGE_PORT_CODE_SET.Storport; pub const StoragePortCodeSetSCSIport = STORAGE_PORT_CODE_SET.SCSIport; pub const StoragePortCodeSetSpaceport = STORAGE_PORT_CODE_SET.Spaceport; pub const StoragePortCodeSetATAport = STORAGE_PORT_CODE_SET.ATAport; pub const StoragePortCodeSetUSBport = STORAGE_PORT_CODE_SET.USBport; pub const StoragePortCodeSetSBP2port = STORAGE_PORT_CODE_SET.SBP2port; pub const StoragePortCodeSetSDport = STORAGE_PORT_CODE_SET.SDport; pub const STORAGE_MINIPORT_DESCRIPTOR = extern struct { Version: u32, Size: u32, Portdriver: STORAGE_PORT_CODE_SET, LUNResetSupported: BOOLEAN, TargetResetSupported: BOOLEAN, IoTimeoutValue: u16, ExtraIoInfoSupported: BOOLEAN, Flags: extern union { Anonymous: extern struct { _bitfield: u8, }, AsBYTE: u8, }, Reserved0: [2]u8, Reserved1: u32, }; pub const STORAGE_IDENTIFIER_CODE_SET = enum(i32) { Reserved = 0, Binary = 1, Ascii = 2, Utf8 = 3, }; pub const StorageIdCodeSetReserved = STORAGE_IDENTIFIER_CODE_SET.Reserved; pub const StorageIdCodeSetBinary = STORAGE_IDENTIFIER_CODE_SET.Binary; pub const StorageIdCodeSetAscii = STORAGE_IDENTIFIER_CODE_SET.Ascii; pub const StorageIdCodeSetUtf8 = STORAGE_IDENTIFIER_CODE_SET.Utf8; pub const STORAGE_IDENTIFIER_TYPE = enum(i32) { VendorSpecific = 0, VendorId = 1, EUI64 = 2, FCPHName = 3, PortRelative = 4, TargetPortGroup = 5, LogicalUnitGroup = 6, MD5LogicalUnitIdentifier = 7, ScsiNameString = 8, }; pub const StorageIdTypeVendorSpecific = STORAGE_IDENTIFIER_TYPE.VendorSpecific; pub const StorageIdTypeVendorId = STORAGE_IDENTIFIER_TYPE.VendorId; pub const StorageIdTypeEUI64 = STORAGE_IDENTIFIER_TYPE.EUI64; pub const StorageIdTypeFCPHName = STORAGE_IDENTIFIER_TYPE.FCPHName; pub const StorageIdTypePortRelative = STORAGE_IDENTIFIER_TYPE.PortRelative; pub const StorageIdTypeTargetPortGroup = STORAGE_IDENTIFIER_TYPE.TargetPortGroup; pub const StorageIdTypeLogicalUnitGroup = STORAGE_IDENTIFIER_TYPE.LogicalUnitGroup; pub const StorageIdTypeMD5LogicalUnitIdentifier = STORAGE_IDENTIFIER_TYPE.MD5LogicalUnitIdentifier; pub const StorageIdTypeScsiNameString = STORAGE_IDENTIFIER_TYPE.ScsiNameString; pub const STORAGE_ID_NAA_FORMAT = enum(i32) { Extended = 2, Registered = 3, ERegisteredExtended = 5, }; pub const StorageIdNAAFormatIEEEExtended = STORAGE_ID_NAA_FORMAT.Extended; pub const StorageIdNAAFormatIEEERegistered = STORAGE_ID_NAA_FORMAT.Registered; pub const StorageIdNAAFormatIEEEERegisteredExtended = STORAGE_ID_NAA_FORMAT.ERegisteredExtended; pub const STORAGE_ASSOCIATION_TYPE = enum(i32) { Device = 0, Port = 1, Target = 2, }; pub const StorageIdAssocDevice = STORAGE_ASSOCIATION_TYPE.Device; pub const StorageIdAssocPort = STORAGE_ASSOCIATION_TYPE.Port; pub const StorageIdAssocTarget = STORAGE_ASSOCIATION_TYPE.Target; pub const STORAGE_IDENTIFIER = extern struct { CodeSet: STORAGE_IDENTIFIER_CODE_SET, Type: STORAGE_IDENTIFIER_TYPE, IdentifierSize: u16, NextOffset: u16, Association: STORAGE_ASSOCIATION_TYPE, Identifier: [1]u8, }; pub const STORAGE_DEVICE_ID_DESCRIPTOR = extern struct { Version: u32, Size: u32, NumberOfIdentifiers: u32, Identifiers: [1]u8, }; pub const DEVICE_SEEK_PENALTY_DESCRIPTOR = extern struct { Version: u32, Size: u32, IncursSeekPenalty: BOOLEAN, }; pub const DEVICE_WRITE_AGGREGATION_DESCRIPTOR = extern struct { Version: u32, Size: u32, BenefitsFromWriteAggregation: BOOLEAN, }; pub const DEVICE_TRIM_DESCRIPTOR = extern struct { Version: u32, Size: u32, TrimEnabled: BOOLEAN, }; pub const DEVICE_LB_PROVISIONING_DESCRIPTOR = extern struct { Version: u32, Size: u32, _bitfield: u8, Reserved1: [7]u8, OptimalUnmapGranularity: u64, UnmapGranularityAlignment: u64, MaxUnmapLbaCount: u32, MaxUnmapBlockDescriptorCount: u32, }; pub const STORAGE_LB_PROVISIONING_MAP_RESOURCES = extern struct { Size: u32, Version: u32, _bitfield1: u8, Reserved1: [3]u8, _bitfield2: u8, Reserved3: [3]u8, AvailableMappingResources: u64, UsedMappingResources: u64, }; pub const DEVICE_POWER_DESCRIPTOR = extern struct { Version: u32, Size: u32, DeviceAttentionSupported: BOOLEAN, AsynchronousNotificationSupported: BOOLEAN, IdlePowerManagementEnabled: BOOLEAN, D3ColdEnabled: BOOLEAN, D3ColdSupported: BOOLEAN, NoVerifyDuringIdlePower: BOOLEAN, Reserved: [2]u8, IdleTimeoutInMS: u32, }; pub const DEVICE_COPY_OFFLOAD_DESCRIPTOR = extern struct { Version: u32, Size: u32, MaximumTokenLifetime: u32, DefaultTokenLifetime: u32, MaximumTransferSize: u64, OptimalTransferCount: u64, MaximumDataDescriptors: u32, MaximumTransferLengthPerDescriptor: u32, OptimalTransferLengthPerDescriptor: u32, OptimalTransferLengthGranularity: u16, Reserved: [2]u8, }; pub const STORAGE_DEVICE_RESILIENCY_DESCRIPTOR = extern struct { Version: u32, Size: u32, NameOffset: u32, NumberOfLogicalCopies: u32, NumberOfPhysicalCopies: u32, PhysicalDiskRedundancy: u32, NumberOfColumns: u32, Interleave: u32, }; pub const STORAGE_RPMB_FRAME_TYPE = enum(i32) { Unknown = 0, Standard = 1, Max = 2, }; pub const StorageRpmbFrameTypeUnknown = STORAGE_RPMB_FRAME_TYPE.Unknown; pub const StorageRpmbFrameTypeStandard = STORAGE_RPMB_FRAME_TYPE.Standard; pub const StorageRpmbFrameTypeMax = STORAGE_RPMB_FRAME_TYPE.Max; pub const STORAGE_RPMB_DESCRIPTOR = extern struct { Version: u32, Size: u32, SizeInBytes: u32, MaxReliableWriteSizeInBytes: u32, FrameFormat: STORAGE_RPMB_FRAME_TYPE, }; pub const STORAGE_CRYPTO_ALGORITHM_ID = enum(i32) { Unknown = 0, XTSAES = 1, BitlockerAESCBC = 2, AESECB = 3, ESSIVAESCBC = 4, Max = 5, }; pub const StorageCryptoAlgorithmUnknown = STORAGE_CRYPTO_ALGORITHM_ID.Unknown; pub const StorageCryptoAlgorithmXTSAES = STORAGE_CRYPTO_ALGORITHM_ID.XTSAES; pub const StorageCryptoAlgorithmBitlockerAESCBC = STORAGE_CRYPTO_ALGORITHM_ID.BitlockerAESCBC; pub const StorageCryptoAlgorithmAESECB = STORAGE_CRYPTO_ALGORITHM_ID.AESECB; pub const StorageCryptoAlgorithmESSIVAESCBC = STORAGE_CRYPTO_ALGORITHM_ID.ESSIVAESCBC; pub const StorageCryptoAlgorithmMax = STORAGE_CRYPTO_ALGORITHM_ID.Max; pub const STORAGE_CRYPTO_KEY_SIZE = enum(i32) { Unknown = 0, @"128Bits" = 1, @"192Bits" = 2, @"256Bits" = 3, @"512Bits" = 4, }; pub const StorageCryptoKeySizeUnknown = STORAGE_CRYPTO_KEY_SIZE.Unknown; pub const StorageCryptoKeySize128Bits = STORAGE_CRYPTO_KEY_SIZE.@"128Bits"; pub const StorageCryptoKeySize192Bits = STORAGE_CRYPTO_KEY_SIZE.@"192Bits"; pub const StorageCryptoKeySize256Bits = STORAGE_CRYPTO_KEY_SIZE.@"256Bits"; pub const StorageCryptoKeySize512Bits = STORAGE_CRYPTO_KEY_SIZE.@"512Bits"; pub const STORAGE_CRYPTO_CAPABILITY = extern struct { Version: u32, Size: u32, CryptoCapabilityIndex: u32, AlgorithmId: STORAGE_CRYPTO_ALGORITHM_ID, KeySize: STORAGE_CRYPTO_KEY_SIZE, DataUnitSizeBitmask: u32, }; pub const STORAGE_CRYPTO_DESCRIPTOR = extern struct { Version: u32, Size: u32, NumKeysSupported: u32, NumCryptoCapabilities: u32, CryptoCapabilities: [1]STORAGE_CRYPTO_CAPABILITY, }; pub const STORAGE_TIER_MEDIA_TYPE = enum(i32) { Unspecified = 0, Disk = 1, Ssd = 2, Scm = 4, Max = 5, }; pub const StorageTierMediaTypeUnspecified = STORAGE_TIER_MEDIA_TYPE.Unspecified; pub const StorageTierMediaTypeDisk = STORAGE_TIER_MEDIA_TYPE.Disk; pub const StorageTierMediaTypeSsd = STORAGE_TIER_MEDIA_TYPE.Ssd; pub const StorageTierMediaTypeScm = STORAGE_TIER_MEDIA_TYPE.Scm; pub const StorageTierMediaTypeMax = STORAGE_TIER_MEDIA_TYPE.Max; pub const STORAGE_TIER_CLASS = enum(i32) { Unspecified = 0, Capacity = 1, Performance = 2, Max = 3, }; pub const StorageTierClassUnspecified = STORAGE_TIER_CLASS.Unspecified; pub const StorageTierClassCapacity = STORAGE_TIER_CLASS.Capacity; pub const StorageTierClassPerformance = STORAGE_TIER_CLASS.Performance; pub const StorageTierClassMax = STORAGE_TIER_CLASS.Max; pub const STORAGE_TIER = extern struct { Id: Guid, Name: [256]u16, Description: [256]u16, Flags: u64, ProvisionedCapacity: u64, MediaType: STORAGE_TIER_MEDIA_TYPE, Class: STORAGE_TIER_CLASS, }; pub const STORAGE_DEVICE_TIERING_DESCRIPTOR = extern struct { Version: u32, Size: u32, Flags: u32, TotalNumberOfTiers: u32, NumberOfTiersReturned: u32, Tiers: [1]STORAGE_TIER, }; pub const STORAGE_DEVICE_FAULT_DOMAIN_DESCRIPTOR = extern struct { Version: u32, Size: u32, NumberOfFaultDomains: u32, FaultDomainIds: [1]Guid, }; pub const STORAGE_PROTOCOL_TYPE = enum(i32) { Unknown = 0, Scsi = 1, Ata = 2, Nvme = 3, Sd = 4, Ufs = 5, Proprietary = 126, MaxReserved = 127, }; pub const ProtocolTypeUnknown = STORAGE_PROTOCOL_TYPE.Unknown; pub const ProtocolTypeScsi = STORAGE_PROTOCOL_TYPE.Scsi; pub const ProtocolTypeAta = STORAGE_PROTOCOL_TYPE.Ata; pub const ProtocolTypeNvme = STORAGE_PROTOCOL_TYPE.Nvme; pub const ProtocolTypeSd = STORAGE_PROTOCOL_TYPE.Sd; pub const ProtocolTypeUfs = STORAGE_PROTOCOL_TYPE.Ufs; pub const ProtocolTypeProprietary = STORAGE_PROTOCOL_TYPE.Proprietary; pub const ProtocolTypeMaxReserved = STORAGE_PROTOCOL_TYPE.MaxReserved; pub const STORAGE_PROTOCOL_NVME_DATA_TYPE = enum(i32) { Unknown = 0, Identify = 1, LogPage = 2, Feature = 3, }; pub const NVMeDataTypeUnknown = STORAGE_PROTOCOL_NVME_DATA_TYPE.Unknown; pub const NVMeDataTypeIdentify = STORAGE_PROTOCOL_NVME_DATA_TYPE.Identify; pub const NVMeDataTypeLogPage = STORAGE_PROTOCOL_NVME_DATA_TYPE.LogPage; pub const NVMeDataTypeFeature = STORAGE_PROTOCOL_NVME_DATA_TYPE.Feature; pub const STORAGE_PROTOCOL_ATA_DATA_TYPE = enum(i32) { Unknown = 0, Identify = 1, LogPage = 2, }; pub const AtaDataTypeUnknown = STORAGE_PROTOCOL_ATA_DATA_TYPE.Unknown; pub const AtaDataTypeIdentify = STORAGE_PROTOCOL_ATA_DATA_TYPE.Identify; pub const AtaDataTypeLogPage = STORAGE_PROTOCOL_ATA_DATA_TYPE.LogPage; pub const STORAGE_PROTOCOL_UFS_DATA_TYPE = enum(i32) { Unknown = 0, QueryDescriptor = 1, QueryAttribute = 2, QueryFlag = 3, QueryDmeAttribute = 4, QueryDmePeerAttribute = 5, Max = 6, }; pub const UfsDataTypeUnknown = STORAGE_PROTOCOL_UFS_DATA_TYPE.Unknown; pub const UfsDataTypeQueryDescriptor = STORAGE_PROTOCOL_UFS_DATA_TYPE.QueryDescriptor; pub const UfsDataTypeQueryAttribute = STORAGE_PROTOCOL_UFS_DATA_TYPE.QueryAttribute; pub const UfsDataTypeQueryFlag = STORAGE_PROTOCOL_UFS_DATA_TYPE.QueryFlag; pub const UfsDataTypeQueryDmeAttribute = STORAGE_PROTOCOL_UFS_DATA_TYPE.QueryDmeAttribute; pub const UfsDataTypeQueryDmePeerAttribute = STORAGE_PROTOCOL_UFS_DATA_TYPE.QueryDmePeerAttribute; pub const UfsDataTypeMax = STORAGE_PROTOCOL_UFS_DATA_TYPE.Max; pub const STORAGE_PROTOCOL_DATA_SUBVALUE_GET_LOG_PAGE = extern union { Anonymous: extern struct { _bitfield: u32, }, AsUlong: u32, }; pub const STORAGE_PROTOCOL_SPECIFIC_DATA = extern struct { ProtocolType: STORAGE_PROTOCOL_TYPE, DataType: u32, ProtocolDataRequestValue: u32, ProtocolDataRequestSubValue: u32, ProtocolDataOffset: u32, ProtocolDataLength: u32, FixedProtocolReturnData: u32, ProtocolDataRequestSubValue2: u32, ProtocolDataRequestSubValue3: u32, ProtocolDataRequestSubValue4: u32, }; pub const STORAGE_PROTOCOL_SPECIFIC_DATA_EXT = extern struct { ProtocolType: STORAGE_PROTOCOL_TYPE, DataType: u32, ProtocolDataValue: u32, ProtocolDataSubValue: u32, ProtocolDataOffset: u32, ProtocolDataLength: u32, FixedProtocolReturnData: u32, ProtocolDataSubValue2: u32, ProtocolDataSubValue3: u32, ProtocolDataSubValue4: u32, ProtocolDataSubValue5: u32, Reserved: [5]u32, }; pub const STORAGE_PROTOCOL_DATA_DESCRIPTOR = extern struct { Version: u32, Size: u32, ProtocolSpecificData: STORAGE_PROTOCOL_SPECIFIC_DATA, }; pub const STORAGE_PROTOCOL_DATA_DESCRIPTOR_EXT = extern struct { Version: u32, Size: u32, ProtocolSpecificData: STORAGE_PROTOCOL_SPECIFIC_DATA_EXT, }; pub const STORAGE_TEMPERATURE_INFO = extern struct { Index: u16, Temperature: i16, OverThreshold: i16, UnderThreshold: i16, OverThresholdChangable: BOOLEAN, UnderThresholdChangable: BOOLEAN, EventGenerated: BOOLEAN, Reserved0: u8, Reserved1: u32, }; pub const STORAGE_TEMPERATURE_DATA_DESCRIPTOR = extern struct { Version: u32, Size: u32, CriticalTemperature: i16, WarningTemperature: i16, InfoCount: u16, Reserved0: [2]u8, Reserved1: [2]u32, TemperatureInfo: [1]STORAGE_TEMPERATURE_INFO, }; pub const STORAGE_TEMPERATURE_THRESHOLD = extern struct { Version: u32, Size: u32, Flags: u16, Index: u16, Threshold: i16, OverThreshold: BOOLEAN, Reserved: u8, }; pub const STORAGE_DEVICE_FORM_FACTOR = enum(i32) { Unknown = 0, @"3_5" = 1, @"2_5" = 2, @"1_8" = 3, @"1_8Less" = 4, Embedded = 5, MemoryCard = 6, mSata = 7, M_2 = 8, PCIeBoard = 9, Dimm = 10, }; pub const FormFactorUnknown = STORAGE_DEVICE_FORM_FACTOR.Unknown; pub const FormFactor3_5 = STORAGE_DEVICE_FORM_FACTOR.@"3_5"; pub const FormFactor2_5 = STORAGE_DEVICE_FORM_FACTOR.@"2_5"; pub const FormFactor1_8 = STORAGE_DEVICE_FORM_FACTOR.@"1_8"; pub const FormFactor1_8Less = STORAGE_DEVICE_FORM_FACTOR.@"1_8Less"; pub const FormFactorEmbedded = STORAGE_DEVICE_FORM_FACTOR.Embedded; pub const FormFactorMemoryCard = STORAGE_DEVICE_FORM_FACTOR.MemoryCard; pub const FormFactormSata = STORAGE_DEVICE_FORM_FACTOR.mSata; pub const FormFactorM_2 = STORAGE_DEVICE_FORM_FACTOR.M_2; pub const FormFactorPCIeBoard = STORAGE_DEVICE_FORM_FACTOR.PCIeBoard; pub const FormFactorDimm = STORAGE_DEVICE_FORM_FACTOR.Dimm; pub const STORAGE_COMPONENT_HEALTH_STATUS = enum(i32) { Unknown = 0, Normal = 1, Throttled = 2, Warning = 3, Disabled = 4, Failed = 5, }; pub const HealthStatusUnknown = STORAGE_COMPONENT_HEALTH_STATUS.Unknown; pub const HealthStatusNormal = STORAGE_COMPONENT_HEALTH_STATUS.Normal; pub const HealthStatusThrottled = STORAGE_COMPONENT_HEALTH_STATUS.Throttled; pub const HealthStatusWarning = STORAGE_COMPONENT_HEALTH_STATUS.Warning; pub const HealthStatusDisabled = STORAGE_COMPONENT_HEALTH_STATUS.Disabled; pub const HealthStatusFailed = STORAGE_COMPONENT_HEALTH_STATUS.Failed; pub const STORAGE_SPEC_VERSION = extern union { Anonymous: extern struct { MinorVersion: extern union { Anonymous: extern struct { SubMinor: u8, Minor: u8, }, AsUshort: u16, }, MajorVersion: u16, }, AsUlong: u32, }; pub const STORAGE_PHYSICAL_DEVICE_DATA = extern struct { DeviceId: u32, Role: u32, HealthStatus: STORAGE_COMPONENT_HEALTH_STATUS, CommandProtocol: STORAGE_PROTOCOL_TYPE, SpecVersion: STORAGE_SPEC_VERSION, FormFactor: STORAGE_DEVICE_FORM_FACTOR, Vendor: [8]u8, Model: [40]u8, FirmwareRevision: [16]u8, Capacity: u64, PhysicalLocation: [32]u8, Reserved: [2]u32, }; pub const STORAGE_PHYSICAL_ADAPTER_DATA = extern struct { AdapterId: u32, HealthStatus: STORAGE_COMPONENT_HEALTH_STATUS, CommandProtocol: STORAGE_PROTOCOL_TYPE, SpecVersion: STORAGE_SPEC_VERSION, Vendor: [8]u8, Model: [40]u8, FirmwareRevision: [16]u8, PhysicalLocation: [32]u8, ExpanderConnected: BOOLEAN, Reserved0: [3]u8, Reserved1: [3]u32, }; pub const STORAGE_PHYSICAL_NODE_DATA = extern struct { NodeId: u32, AdapterCount: u32, AdapterDataLength: u32, AdapterDataOffset: u32, DeviceCount: u32, DeviceDataLength: u32, DeviceDataOffset: u32, Reserved: [3]u32, }; pub const STORAGE_PHYSICAL_TOPOLOGY_DESCRIPTOR = extern struct { Version: u32, Size: u32, NodeCount: u32, Reserved: u32, Node: [1]STORAGE_PHYSICAL_NODE_DATA, }; pub const STORAGE_DEVICE_IO_CAPABILITY_DESCRIPTOR = extern struct { Version: u32, Size: u32, LunMaxIoCount: u32, AdapterMaxIoCount: u32, }; pub const STORAGE_DEVICE_ATTRIBUTES_DESCRIPTOR = extern struct { Version: u32, Size: u32, Attributes: u64, }; pub const STORAGE_DISK_HEALTH_STATUS = enum(i32) { Unknown = 0, Unhealthy = 1, Warning = 2, Healthy = 3, Max = 4, }; pub const DiskHealthUnknown = STORAGE_DISK_HEALTH_STATUS.Unknown; pub const DiskHealthUnhealthy = STORAGE_DISK_HEALTH_STATUS.Unhealthy; pub const DiskHealthWarning = STORAGE_DISK_HEALTH_STATUS.Warning; pub const DiskHealthHealthy = STORAGE_DISK_HEALTH_STATUS.Healthy; pub const DiskHealthMax = STORAGE_DISK_HEALTH_STATUS.Max; pub const STORAGE_DISK_OPERATIONAL_STATUS = enum(i32) { None = 0, Unknown = 1, Ok = 2, PredictingFailure = 3, InService = 4, HardwareError = 5, NotUsable = 6, TransientError = 7, Missing = 8, }; pub const DiskOpStatusNone = STORAGE_DISK_OPERATIONAL_STATUS.None; pub const DiskOpStatusUnknown = STORAGE_DISK_OPERATIONAL_STATUS.Unknown; pub const DiskOpStatusOk = STORAGE_DISK_OPERATIONAL_STATUS.Ok; pub const DiskOpStatusPredictingFailure = STORAGE_DISK_OPERATIONAL_STATUS.PredictingFailure; pub const DiskOpStatusInService = STORAGE_DISK_OPERATIONAL_STATUS.InService; pub const DiskOpStatusHardwareError = STORAGE_DISK_OPERATIONAL_STATUS.HardwareError; pub const DiskOpStatusNotUsable = STORAGE_DISK_OPERATIONAL_STATUS.NotUsable; pub const DiskOpStatusTransientError = STORAGE_DISK_OPERATIONAL_STATUS.TransientError; pub const DiskOpStatusMissing = STORAGE_DISK_OPERATIONAL_STATUS.Missing; pub const STORAGE_OPERATIONAL_STATUS_REASON = enum(i32) { Unknown = 0, ScsiSenseCode = 1, Media = 2, Io = 3, ThresholdExceeded = 4, LostData = 5, EnergySource = 6, Configuration = 7, DeviceController = 8, MediaController = 9, Component = 10, NVDIMM_N = 11, BackgroundOperation = 12, InvalidFirmware = 13, HealthCheck = 14, LostDataPersistence = 15, DisabledByPlatform = 16, LostWritePersistence = 17, DataPersistenceLossImminent = 18, WritePersistenceLossImminent = 19, Max = 20, }; pub const DiskOpReasonUnknown = STORAGE_OPERATIONAL_STATUS_REASON.Unknown; pub const DiskOpReasonScsiSenseCode = STORAGE_OPERATIONAL_STATUS_REASON.ScsiSenseCode; pub const DiskOpReasonMedia = STORAGE_OPERATIONAL_STATUS_REASON.Media; pub const DiskOpReasonIo = STORAGE_OPERATIONAL_STATUS_REASON.Io; pub const DiskOpReasonThresholdExceeded = STORAGE_OPERATIONAL_STATUS_REASON.ThresholdExceeded; pub const DiskOpReasonLostData = STORAGE_OPERATIONAL_STATUS_REASON.LostData; pub const DiskOpReasonEnergySource = STORAGE_OPERATIONAL_STATUS_REASON.EnergySource; pub const DiskOpReasonConfiguration = STORAGE_OPERATIONAL_STATUS_REASON.Configuration; pub const DiskOpReasonDeviceController = STORAGE_OPERATIONAL_STATUS_REASON.DeviceController; pub const DiskOpReasonMediaController = STORAGE_OPERATIONAL_STATUS_REASON.MediaController; pub const DiskOpReasonComponent = STORAGE_OPERATIONAL_STATUS_REASON.Component; pub const DiskOpReasonNVDIMM_N = STORAGE_OPERATIONAL_STATUS_REASON.NVDIMM_N; pub const DiskOpReasonBackgroundOperation = STORAGE_OPERATIONAL_STATUS_REASON.BackgroundOperation; pub const DiskOpReasonInvalidFirmware = STORAGE_OPERATIONAL_STATUS_REASON.InvalidFirmware; pub const DiskOpReasonHealthCheck = STORAGE_OPERATIONAL_STATUS_REASON.HealthCheck; pub const DiskOpReasonLostDataPersistence = STORAGE_OPERATIONAL_STATUS_REASON.LostDataPersistence; pub const DiskOpReasonDisabledByPlatform = STORAGE_OPERATIONAL_STATUS_REASON.DisabledByPlatform; pub const DiskOpReasonLostWritePersistence = STORAGE_OPERATIONAL_STATUS_REASON.LostWritePersistence; pub const DiskOpReasonDataPersistenceLossImminent = STORAGE_OPERATIONAL_STATUS_REASON.DataPersistenceLossImminent; pub const DiskOpReasonWritePersistenceLossImminent = STORAGE_OPERATIONAL_STATUS_REASON.WritePersistenceLossImminent; pub const DiskOpReasonMax = STORAGE_OPERATIONAL_STATUS_REASON.Max; pub const STORAGE_OPERATIONAL_REASON = extern struct { Version: u32, Size: u32, Reason: STORAGE_OPERATIONAL_STATUS_REASON, RawBytes: extern union { ScsiSenseKey: extern struct { SenseKey: u8, ASC: u8, ASCQ: u8, Reserved: u8, }, NVDIMM_N: extern struct { CriticalHealth: u8, ModuleHealth: [2]u8, ErrorThresholdStatus: u8, }, AsUlong: u32, }, }; pub const STORAGE_DEVICE_MANAGEMENT_STATUS = extern struct { Version: u32, Size: u32, Health: STORAGE_DISK_HEALTH_STATUS, NumberOfOperationalStatus: u32, NumberOfAdditionalReasons: u32, OperationalStatus: [16]STORAGE_DISK_OPERATIONAL_STATUS, AdditionalReasons: [1]STORAGE_OPERATIONAL_REASON, }; pub const STORAGE_ADAPTER_SERIAL_NUMBER = extern struct { Version: u32, Size: u32, SerialNumber: [128]u16, }; pub const STORAGE_ZONED_DEVICE_TYPES = enum(i32) { Unknown = 0, HostManaged = 1, HostAware = 2, DeviceManaged = 3, }; pub const ZonedDeviceTypeUnknown = STORAGE_ZONED_DEVICE_TYPES.Unknown; pub const ZonedDeviceTypeHostManaged = STORAGE_ZONED_DEVICE_TYPES.HostManaged; pub const ZonedDeviceTypeHostAware = STORAGE_ZONED_DEVICE_TYPES.HostAware; pub const ZonedDeviceTypeDeviceManaged = STORAGE_ZONED_DEVICE_TYPES.DeviceManaged; pub const STORAGE_ZONE_TYPES = enum(i32) { Unknown = 0, Conventional = 1, SequentialWriteRequired = 2, SequentialWritePreferred = 3, Max = 4, }; pub const ZoneTypeUnknown = STORAGE_ZONE_TYPES.Unknown; pub const ZoneTypeConventional = STORAGE_ZONE_TYPES.Conventional; pub const ZoneTypeSequentialWriteRequired = STORAGE_ZONE_TYPES.SequentialWriteRequired; pub const ZoneTypeSequentialWritePreferred = STORAGE_ZONE_TYPES.SequentialWritePreferred; pub const ZoneTypeMax = STORAGE_ZONE_TYPES.Max; pub const STORAGE_ZONE_GROUP = extern struct { ZoneCount: u32, ZoneType: STORAGE_ZONE_TYPES, ZoneSize: u64, }; pub const STORAGE_ZONED_DEVICE_DESCRIPTOR = extern struct { Version: u32, Size: u32, DeviceType: STORAGE_ZONED_DEVICE_TYPES, ZoneCount: u32, ZoneAttributes: extern union { SequentialRequiredZone: extern struct { MaxOpenZoneCount: u32, UnrestrictedRead: BOOLEAN, Reserved: [3]u8, }, SequentialPreferredZone: extern struct { OptimalOpenZoneCount: u32, Reserved: u32, }, }, ZoneGroupCount: u32, ZoneGroup: [1]STORAGE_ZONE_GROUP, }; pub const DEVICE_LOCATION = extern struct { Socket: u32, Slot: u32, Adapter: u32, Port: u32, Anonymous: extern union { Anonymous1: extern struct { Channel: u32, Device: u32, }, Anonymous2: extern struct { Target: u32, Lun: u32, }, }, }; pub const STORAGE_DEVICE_LOCATION_DESCRIPTOR = extern struct { Version: u32, Size: u32, Location: DEVICE_LOCATION, StringOffset: u32, }; pub const STORAGE_DEVICE_NUMA_PROPERTY = extern struct { Version: u32, Size: u32, NumaNode: u32, }; pub const STORAGE_DEVICE_UNSAFE_SHUTDOWN_COUNT = extern struct { Version: u32, Size: u32, UnsafeShutdownCount: u32, }; pub const STORAGE_HW_ENDURANCE_INFO = extern struct { ValidFields: u32, GroupId: u32, Flags: extern struct { _bitfield: u32, }, LifePercentage: u32, BytesReadCount: [16]u8, ByteWriteCount: [16]u8, }; pub const STORAGE_HW_ENDURANCE_DATA_DESCRIPTOR = extern struct { Version: u32, Size: u32, EnduranceInfo: STORAGE_HW_ENDURANCE_INFO, }; pub const STORAGE_DEVICE_LED_STATE_DESCRIPTOR = extern struct { Version: u32, Size: u32, State: u64, }; pub const STORAGE_DEVICE_SELF_ENCRYPTION_PROPERTY = extern struct { Version: u32, Size: u32, SupportsSelfEncryption: BOOLEAN, }; pub const STORAGE_FRU_ID_DESCRIPTOR = extern struct { Version: u32, Size: u32, IdentifierSize: u32, Identifier: [1]u8, }; pub const DEVICE_DATA_SET_RANGE = extern struct { StartingOffset: i64, LengthInBytes: u64, }; pub const DEVICE_MANAGE_DATA_SET_ATTRIBUTES = extern struct { Size: u32, Action: u32, Flags: u32, ParameterBlockOffset: u32, ParameterBlockLength: u32, DataSetRangesOffset: u32, DataSetRangesLength: u32, }; pub const DEVICE_MANAGE_DATA_SET_ATTRIBUTES_OUTPUT = extern struct { Size: u32, Action: u32, Flags: u32, OperationStatus: u32, ExtendedError: u32, TargetDetailedError: u32, ReservedStatus: u32, OutputBlockOffset: u32, OutputBlockLength: u32, }; pub const DEVICE_DSM_DEFINITION = extern struct { Action: u32, SingleRange: BOOLEAN, ParameterBlockAlignment: u32, ParameterBlockLength: u32, HasOutput: BOOLEAN, OutputBlockAlignment: u32, OutputBlockLength: u32, }; pub const DEVICE_DSM_NOTIFICATION_PARAMETERS = extern struct { Size: u32, Flags: u32, NumFileTypeIDs: u32, FileTypeID: [1]Guid, }; pub const STORAGE_OFFLOAD_TOKEN = extern struct { TokenType: [4]u8, Reserved: [2]u8, TokenIdLength: [2]u8, Anonymous: extern union { StorageOffloadZeroDataToken: extern struct { Reserved2: [504]u8, }, Token: [504]u8, }, }; pub const DEVICE_DSM_OFFLOAD_READ_PARAMETERS = extern struct { Flags: u32, TimeToLive: u32, Reserved: [2]u32, }; pub const STORAGE_OFFLOAD_READ_OUTPUT = extern struct { OffloadReadFlags: u32, Reserved: u32, LengthProtected: u64, TokenLength: u32, Token: STORAGE_OFFLOAD_TOKEN, }; pub const DEVICE_DSM_OFFLOAD_WRITE_PARAMETERS = extern struct { Flags: u32, Reserved: u32, TokenOffset: u64, Token: STORAGE_OFFLOAD_TOKEN, }; pub const STORAGE_OFFLOAD_WRITE_OUTPUT = extern struct { OffloadWriteFlags: u32, Reserved: u32, LengthCopied: u64, }; pub const DEVICE_DATA_SET_LBP_STATE_PARAMETERS = extern struct { Version: u32, Size: u32, Flags: u32, OutputVersion: u32, }; pub const DEVICE_DATA_SET_LB_PROVISIONING_STATE = extern struct { Size: u32, Version: u32, SlabSizeInBytes: u64, SlabOffsetDeltaInBytes: u32, SlabAllocationBitMapBitCount: u32, SlabAllocationBitMapLength: u32, SlabAllocationBitMap: [1]u32, }; pub const DEVICE_DATA_SET_LB_PROVISIONING_STATE_V2 = extern struct { Size: u32, Version: u32, SlabSizeInBytes: u64, SlabOffsetDeltaInBytes: u64, SlabAllocationBitMapBitCount: u32, SlabAllocationBitMapLength: u32, SlabAllocationBitMap: [1]u32, }; pub const DEVICE_DATA_SET_REPAIR_PARAMETERS = extern struct { NumberOfRepairCopies: u32, SourceCopy: u32, RepairCopies: [1]u32, }; pub const DEVICE_DATA_SET_REPAIR_OUTPUT = extern struct { ParityExtent: DEVICE_DATA_SET_RANGE, }; pub const DEVICE_DATA_SET_SCRUB_OUTPUT = extern struct { BytesProcessed: u64, BytesRepaired: u64, BytesFailed: u64, }; pub const DEVICE_DATA_SET_SCRUB_EX_OUTPUT = extern struct { BytesProcessed: u64, BytesRepaired: u64, BytesFailed: u64, ParityExtent: DEVICE_DATA_SET_RANGE, BytesScrubbed: u64, }; pub const DEVICE_DSM_TIERING_QUERY_INPUT = extern struct { Version: u32, Size: u32, Flags: u32, NumberOfTierIds: u32, TierIds: [1]Guid, }; pub const STORAGE_TIER_REGION = extern struct { TierId: Guid, Offset: u64, Length: u64, }; pub const DEVICE_DSM_TIERING_QUERY_OUTPUT = extern struct { Version: u32, Size: u32, Flags: u32, Reserved: u32, Alignment: u64, TotalNumberOfRegions: u32, NumberOfRegionsReturned: u32, Regions: [1]STORAGE_TIER_REGION, }; pub const DEVICE_DSM_NVCACHE_CHANGE_PRIORITY_PARAMETERS = extern struct { Size: u32, TargetPriority: u8, Reserved: [3]u8, }; pub const DEVICE_DATA_SET_TOPOLOGY_ID_QUERY_OUTPUT = extern struct { TopologyRangeBytes: u64, TopologyId: [16]u8, }; pub const DEVICE_STORAGE_ADDRESS_RANGE = extern struct { StartAddress: i64, LengthInBytes: u64, }; pub const DEVICE_DSM_PHYSICAL_ADDRESSES_OUTPUT = extern struct { Version: u32, Flags: u32, TotalNumberOfRanges: u32, NumberOfRangesReturned: u32, Ranges: [1]DEVICE_STORAGE_ADDRESS_RANGE, }; pub const DEVICE_DSM_REPORT_ZONES_PARAMETERS = extern struct { Size: u32, ReportOption: u8, Partial: u8, Reserved: [2]u8, }; pub const STORAGE_ZONES_ATTRIBUTES = enum(i32) { AndLengthMayDifferent = 0, SameLengthSame = 1, SameLastZoneLengthDifferent = 2, MayDifferentLengthSame = 3, }; pub const ZonesAttributeTypeAndLengthMayDifferent = STORAGE_ZONES_ATTRIBUTES.AndLengthMayDifferent; pub const ZonesAttributeTypeSameLengthSame = STORAGE_ZONES_ATTRIBUTES.SameLengthSame; pub const ZonesAttributeTypeSameLastZoneLengthDifferent = STORAGE_ZONES_ATTRIBUTES.SameLastZoneLengthDifferent; pub const ZonesAttributeTypeMayDifferentLengthSame = STORAGE_ZONES_ATTRIBUTES.MayDifferentLengthSame; pub const STORAGE_ZONE_CONDITION = enum(i32) { Conventional = 0, Empty = 1, ImplicitlyOpened = 2, ExplicitlyOpened = 3, Closed = 4, ReadOnly = 13, Full = 14, Offline = 15, }; pub const ZoneConditionConventional = STORAGE_ZONE_CONDITION.Conventional; pub const ZoneConditionEmpty = STORAGE_ZONE_CONDITION.Empty; pub const ZoneConditionImplicitlyOpened = STORAGE_ZONE_CONDITION.ImplicitlyOpened; pub const ZoneConditionExplicitlyOpened = STORAGE_ZONE_CONDITION.ExplicitlyOpened; pub const ZoneConditionClosed = STORAGE_ZONE_CONDITION.Closed; pub const ZoneConditionReadOnly = STORAGE_ZONE_CONDITION.ReadOnly; pub const ZoneConditionFull = STORAGE_ZONE_CONDITION.Full; pub const ZoneConditionOffline = STORAGE_ZONE_CONDITION.Offline; pub const STORAGE_ZONE_DESCRIPTOR = extern struct { Size: u32, ZoneType: STORAGE_ZONE_TYPES, ZoneCondition: STORAGE_ZONE_CONDITION, ResetWritePointerRecommend: BOOLEAN, Reserved0: [3]u8, ZoneSize: u64, WritePointerOffset: u64, }; pub const DEVICE_DSM_REPORT_ZONES_DATA = extern struct { Size: u32, ZoneCount: u32, Attributes: STORAGE_ZONES_ATTRIBUTES, Reserved0: u32, ZoneDescriptors: [1]STORAGE_ZONE_DESCRIPTOR, }; pub const DEVICE_STORAGE_RANGE_ATTRIBUTES = extern struct { LengthInBytes: u64, Anonymous: extern union { AllFlags: u32, Anonymous: extern struct { _bitfield: u32, }, }, Reserved: u32, }; pub const DEVICE_DSM_RANGE_ERROR_INFO = extern struct { Version: u32, Flags: u32, TotalNumberOfRanges: u32, NumberOfRangesReturned: u32, Ranges: [1]DEVICE_STORAGE_RANGE_ATTRIBUTES, }; pub const DEVICE_DSM_LOST_QUERY_PARAMETERS = extern struct { Version: u32, Granularity: u64, }; pub const DEVICE_DSM_LOST_QUERY_OUTPUT = extern struct { Version: u32, Size: u32, Alignment: u64, NumberOfBits: u32, BitMap: [1]u32, }; pub const DEVICE_DSM_FREE_SPACE_OUTPUT = extern struct { Version: u32, FreeSpace: u64, }; pub const DEVICE_DSM_CONVERSION_OUTPUT = extern struct { Version: u32, Source: Guid, }; pub const STORAGE_GET_BC_PROPERTIES_OUTPUT = extern struct { MaximumRequestsPerPeriod: u32, MinimumPeriod: u32, MaximumRequestSize: u64, EstimatedTimePerRequest: u32, NumOutStandingRequests: u32, RequestSize: u64, }; pub const STORAGE_ALLOCATE_BC_STREAM_INPUT = extern struct { Version: u32, RequestsPerPeriod: u32, Period: u32, RetryFailures: BOOLEAN, Discardable: BOOLEAN, Reserved1: [2]BOOLEAN, AccessType: u32, AccessMode: u32, }; pub const STORAGE_ALLOCATE_BC_STREAM_OUTPUT = extern struct { RequestSize: u64, NumOutStandingRequests: u32, }; pub const STORAGE_PRIORITY_HINT_SUPPORT = extern struct { SupportFlags: u32, }; pub const STORAGE_DIAGNOSTIC_LEVEL = enum(i32) { Default = 0, Max = 1, }; pub const StorageDiagnosticLevelDefault = STORAGE_DIAGNOSTIC_LEVEL.Default; pub const StorageDiagnosticLevelMax = STORAGE_DIAGNOSTIC_LEVEL.Max; pub const STORAGE_DIAGNOSTIC_TARGET_TYPE = enum(i32) { Undefined = 0, Port = 1, Miniport = 2, HbaFirmware = 3, Max = 4, }; pub const StorageDiagnosticTargetTypeUndefined = STORAGE_DIAGNOSTIC_TARGET_TYPE.Undefined; pub const StorageDiagnosticTargetTypePort = STORAGE_DIAGNOSTIC_TARGET_TYPE.Port; pub const StorageDiagnosticTargetTypeMiniport = STORAGE_DIAGNOSTIC_TARGET_TYPE.Miniport; pub const StorageDiagnosticTargetTypeHbaFirmware = STORAGE_DIAGNOSTIC_TARGET_TYPE.HbaFirmware; pub const StorageDiagnosticTargetTypeMax = STORAGE_DIAGNOSTIC_TARGET_TYPE.Max; pub const STORAGE_DIAGNOSTIC_REQUEST = extern struct { Version: u32, Size: u32, Flags: u32, TargetType: STORAGE_DIAGNOSTIC_TARGET_TYPE, Level: STORAGE_DIAGNOSTIC_LEVEL, }; pub const STORAGE_DIAGNOSTIC_DATA = extern struct { Version: u32, Size: u32, ProviderId: Guid, BufferSize: u32, Reserved: u32, DiagnosticDataBuffer: [1]u8, }; pub const PHYSICAL_ELEMENT_STATUS_REQUEST = extern struct { Version: u32, Size: u32, StartingElement: u32, Filter: u8, ReportType: u8, Reserved: [2]u8, }; pub const PHYSICAL_ELEMENT_STATUS_DESCRIPTOR = extern struct { Version: u32, Size: u32, ElementIdentifier: u32, PhysicalElementType: u8, PhysicalElementHealth: u8, Reserved1: [2]u8, AssociatedCapacity: u64, Reserved2: [4]u32, }; pub const PHYSICAL_ELEMENT_STATUS = extern struct { Version: u32, Size: u32, DescriptorCount: u32, ReturnedDescriptorCount: u32, ElementIdentifierBeingDepoped: u32, Reserved: u32, Descriptors: [1]PHYSICAL_ELEMENT_STATUS_DESCRIPTOR, }; pub const REMOVE_ELEMENT_AND_TRUNCATE_REQUEST = extern struct { Version: u32, Size: u32, RequestCapacity: u64, ElementIdentifier: u32, Reserved: u32, }; pub const DEVICE_INTERNAL_STATUS_DATA_REQUEST_TYPE = enum(i32) { InternalStatusDataRequestTypeUndefined = 0, CurrentInternalStatusDataHeader = 1, CurrentInternalStatusData = 2, SavedInternalStatusDataHeader = 3, SavedInternalStatusData = 4, }; pub const DeviceInternalStatusDataRequestTypeUndefined = DEVICE_INTERNAL_STATUS_DATA_REQUEST_TYPE.InternalStatusDataRequestTypeUndefined; pub const DeviceCurrentInternalStatusDataHeader = DEVICE_INTERNAL_STATUS_DATA_REQUEST_TYPE.CurrentInternalStatusDataHeader; pub const DeviceCurrentInternalStatusData = DEVICE_INTERNAL_STATUS_DATA_REQUEST_TYPE.CurrentInternalStatusData; pub const DeviceSavedInternalStatusDataHeader = DEVICE_INTERNAL_STATUS_DATA_REQUEST_TYPE.SavedInternalStatusDataHeader; pub const DeviceSavedInternalStatusData = DEVICE_INTERNAL_STATUS_DATA_REQUEST_TYPE.SavedInternalStatusData; pub const DEVICE_INTERNAL_STATUS_DATA_SET = enum(i32) { Undefined = 0, @"1" = 1, @"2" = 2, @"3" = 3, @"4" = 4, Max = 5, }; pub const DeviceStatusDataSetUndefined = DEVICE_INTERNAL_STATUS_DATA_SET.Undefined; pub const DeviceStatusDataSet1 = DEVICE_INTERNAL_STATUS_DATA_SET.@"1"; pub const DeviceStatusDataSet2 = DEVICE_INTERNAL_STATUS_DATA_SET.@"2"; pub const DeviceStatusDataSet3 = DEVICE_INTERNAL_STATUS_DATA_SET.@"3"; pub const DeviceStatusDataSet4 = DEVICE_INTERNAL_STATUS_DATA_SET.@"4"; pub const DeviceStatusDataSetMax = DEVICE_INTERNAL_STATUS_DATA_SET.Max; pub const GET_DEVICE_INTERNAL_STATUS_DATA_REQUEST = extern struct { Version: u32, Size: u32, RequestDataType: DEVICE_INTERNAL_STATUS_DATA_REQUEST_TYPE, RequestDataSet: DEVICE_INTERNAL_STATUS_DATA_SET, }; pub const DEVICE_INTERNAL_STATUS_DATA = extern struct { Version: u32, Size: u32, T10VendorId: u64, DataSet1Length: u32, DataSet2Length: u32, DataSet3Length: u32, DataSet4Length: u32, StatusDataVersion: u8, Reserved: [3]u8, ReasonIdentifier: [128]u8, StatusDataLength: u32, StatusData: [1]u8, }; pub const STORAGE_SANITIZE_METHOD = enum(i32) { Default = 0, BlockErase = 1, CryptoErase = 2, }; pub const StorageSanitizeMethodDefault = STORAGE_SANITIZE_METHOD.Default; pub const StorageSanitizeMethodBlockErase = STORAGE_SANITIZE_METHOD.BlockErase; pub const StorageSanitizeMethodCryptoErase = STORAGE_SANITIZE_METHOD.CryptoErase; pub const STORAGE_REINITIALIZE_MEDIA = extern struct { Version: u32, Size: u32, TimeoutInSeconds: u32, SanitizeOption: extern struct { _bitfield: u32, }, }; pub const STORAGE_MEDIA_SERIAL_NUMBER_DATA = extern struct { Reserved: u16, SerialNumberLength: u16, SerialNumber: [1]u8, }; pub const STORAGE_READ_CAPACITY = extern struct { Version: u32, Size: u32, BlockLength: u32, NumberOfBlocks: LARGE_INTEGER, DiskLength: LARGE_INTEGER, }; pub const WRITE_CACHE_TYPE = enum(i32) { Unknown = 0, None = 1, WriteBack = 2, WriteThrough = 3, }; pub const WriteCacheTypeUnknown = WRITE_CACHE_TYPE.Unknown; pub const WriteCacheTypeNone = WRITE_CACHE_TYPE.None; pub const WriteCacheTypeWriteBack = WRITE_CACHE_TYPE.WriteBack; pub const WriteCacheTypeWriteThrough = WRITE_CACHE_TYPE.WriteThrough; pub const WRITE_CACHE_ENABLE = enum(i32) { EnableUnknown = 0, Disabled = 1, Enabled = 2, }; pub const WriteCacheEnableUnknown = WRITE_CACHE_ENABLE.EnableUnknown; pub const WriteCacheDisabled = WRITE_CACHE_ENABLE.Disabled; pub const WriteCacheEnabled = WRITE_CACHE_ENABLE.Enabled; pub const WRITE_CACHE_CHANGE = enum(i32) { ChangeUnknown = 0, NotChangeable = 1, Changeable = 2, }; pub const WriteCacheChangeUnknown = WRITE_CACHE_CHANGE.ChangeUnknown; pub const WriteCacheNotChangeable = WRITE_CACHE_CHANGE.NotChangeable; pub const WriteCacheChangeable = WRITE_CACHE_CHANGE.Changeable; pub const WRITE_THROUGH = enum(i32) { Unknown = 0, NotSupported = 1, Supported = 2, }; pub const WriteThroughUnknown = WRITE_THROUGH.Unknown; pub const WriteThroughNotSupported = WRITE_THROUGH.NotSupported; pub const WriteThroughSupported = WRITE_THROUGH.Supported; pub const STORAGE_WRITE_CACHE_PROPERTY = extern struct { Version: u32, Size: u32, WriteCacheType: WRITE_CACHE_TYPE, WriteCacheEnabled: WRITE_CACHE_ENABLE, WriteCacheChangeable: WRITE_CACHE_CHANGE, WriteThroughSupported: WRITE_THROUGH, FlushCacheSupported: BOOLEAN, UserDefinedPowerProtection: BOOLEAN, NVCacheEnabled: BOOLEAN, }; pub const PERSISTENT_RESERVE_COMMAND = extern struct { Version: u32, Size: u32, Anonymous: extern union { PR_IN: extern struct { _bitfield: u8, AllocationLength: u16, }, PR_OUT: extern struct { _bitfield1: u8, _bitfield2: u8, ParameterList: [1]u8, }, }, }; pub const _DEVICEDUMP_COLLECTION_TYPE = enum(i32) { BugCheck = 1, ApplicationRequested = 2, DeviceRequested = 3, }; pub const TCCollectionBugCheck = _DEVICEDUMP_COLLECTION_TYPE.BugCheck; pub const TCCollectionApplicationRequested = _DEVICEDUMP_COLLECTION_TYPE.ApplicationRequested; pub const TCCollectionDeviceRequested = _DEVICEDUMP_COLLECTION_TYPE.DeviceRequested; pub const DEVICEDUMP_SUBSECTION_POINTER = packed struct { dwSize: u32, dwFlags: u32, dwOffset: u32, }; pub const DEVICEDUMP_STRUCTURE_VERSION = packed struct { dwSignature: u32, dwVersion: u32, dwSize: u32, }; pub const DEVICEDUMP_SECTION_HEADER = packed struct { guidDeviceDataId: Guid, sOrganizationID: [16]u8, dwFirmwareRevision: u32, sModelNumber: [32]u8, szDeviceManufacturingID: [32]u8, dwFlags: u32, bRestrictedPrivateDataVersion: u32, dwFirmwareIssueId: u32, szIssueDescriptionString: [132]u8, }; pub const GP_LOG_PAGE_DESCRIPTOR = packed struct { LogAddress: u16, LogSectors: u16, }; pub const DEVICEDUMP_PUBLIC_SUBSECTION = packed struct { dwFlags: u32, GPLogTable: [16]GP_LOG_PAGE_DESCRIPTOR, szDescription: [16]CHAR, bData: [1]u8, }; pub const DEVICEDUMP_RESTRICTED_SUBSECTION = extern struct { bData: [1]u8, }; pub const DEVICEDUMP_PRIVATE_SUBSECTION = packed struct { dwFlags: u32, GPLogId: GP_LOG_PAGE_DESCRIPTOR, bData: [1]u8, }; pub const DEVICEDUMP_STORAGEDEVICE_DATA = packed struct { Descriptor: DEVICEDUMP_STRUCTURE_VERSION, SectionHeader: DEVICEDUMP_SECTION_HEADER, dwBufferSize: u32, dwReasonForCollection: u32, PublicData: DEVICEDUMP_SUBSECTION_POINTER, RestrictedData: DEVICEDUMP_SUBSECTION_POINTER, PrivateData: DEVICEDUMP_SUBSECTION_POINTER, }; pub const DEVICEDUMP_STORAGESTACK_PUBLIC_STATE_RECORD = packed struct { Cdb: [16]u8, Command: [16]u8, StartTime: u64, EndTime: u64, OperationStatus: u32, OperationError: u32, StackSpecific: extern union { ExternalStack: packed struct { dwReserved: u32, }, AtaPort: packed struct { dwAtaPortSpecific: u32, }, StorPort: packed struct { SrbTag: u32, }, }, }; pub const DEVICEDUMP_STORAGESTACK_PUBLIC_DUMP = packed struct { Descriptor: DEVICEDUMP_STRUCTURE_VERSION, dwReasonForCollection: u32, cDriverName: [16]u8, uiNumRecords: u32, RecordArray: [1]DEVICEDUMP_STORAGESTACK_PUBLIC_STATE_RECORD, }; pub const STORAGE_IDLE_POWER = extern struct { Version: u32, Size: u32, _bitfield: u32, D3IdleTimeout: u32, }; pub const STORAGE_POWERUP_REASON_TYPE = enum(i32) { Unknown = 0, IO = 1, DeviceAttention = 2, }; pub const StoragePowerupUnknown = STORAGE_POWERUP_REASON_TYPE.Unknown; pub const StoragePowerupIO = STORAGE_POWERUP_REASON_TYPE.IO; pub const StoragePowerupDeviceAttention = STORAGE_POWERUP_REASON_TYPE.DeviceAttention; pub const STORAGE_IDLE_POWERUP_REASON = extern struct { Version: u32, Size: u32, PowerupReason: STORAGE_POWERUP_REASON_TYPE, }; pub const STORAGE_DEVICE_POWER_CAP_UNITS = enum(i32) { Percent = 0, Milliwatts = 1, }; pub const StorageDevicePowerCapUnitsPercent = STORAGE_DEVICE_POWER_CAP_UNITS.Percent; pub const StorageDevicePowerCapUnitsMilliwatts = STORAGE_DEVICE_POWER_CAP_UNITS.Milliwatts; pub const STORAGE_DEVICE_POWER_CAP = extern struct { Version: u32, Size: u32, Units: STORAGE_DEVICE_POWER_CAP_UNITS, MaxPower: u64, }; pub const STORAGE_RPMB_DATA_FRAME = extern struct { Stuff: [196]u8, KeyOrMAC: [32]u8, Data: [256]u8, Nonce: [16]u8, WriteCounter: [4]u8, Address: [2]u8, BlockCount: [2]u8, OperationResult: [2]u8, RequestOrResponseType: [2]u8, }; pub const STORAGE_RPMB_COMMAND_TYPE = enum(i32) { ProgramAuthKey = 1, QueryWriteCounter = 2, AuthenticatedWrite = 3, AuthenticatedRead = 4, ReadResultRequest = 5, AuthenticatedDeviceConfigWrite = 6, AuthenticatedDeviceConfigRead = 7, }; pub const StorRpmbProgramAuthKey = STORAGE_RPMB_COMMAND_TYPE.ProgramAuthKey; pub const StorRpmbQueryWriteCounter = STORAGE_RPMB_COMMAND_TYPE.QueryWriteCounter; pub const StorRpmbAuthenticatedWrite = STORAGE_RPMB_COMMAND_TYPE.AuthenticatedWrite; pub const StorRpmbAuthenticatedRead = STORAGE_RPMB_COMMAND_TYPE.AuthenticatedRead; pub const StorRpmbReadResultRequest = STORAGE_RPMB_COMMAND_TYPE.ReadResultRequest; pub const StorRpmbAuthenticatedDeviceConfigWrite = STORAGE_RPMB_COMMAND_TYPE.AuthenticatedDeviceConfigWrite; pub const StorRpmbAuthenticatedDeviceConfigRead = STORAGE_RPMB_COMMAND_TYPE.AuthenticatedDeviceConfigRead; pub const STORAGE_EVENT_NOTIFICATION = extern struct { Version: u32, Size: u32, Events: u64, }; pub const STORAGE_COUNTER_TYPE = enum(i32) { Unknown = 0, TemperatureCelsius = 1, TemperatureCelsiusMax = 2, ReadErrorsTotal = 3, ReadErrorsCorrected = 4, ReadErrorsUncorrected = 5, WriteErrorsTotal = 6, WriteErrorsCorrected = 7, WriteErrorsUncorrected = 8, ManufactureDate = 9, StartStopCycleCount = 10, StartStopCycleCountMax = 11, LoadUnloadCycleCount = 12, LoadUnloadCycleCountMax = 13, WearPercentage = 14, WearPercentageWarning = 15, WearPercentageMax = 16, PowerOnHours = 17, ReadLatency100NSMax = 18, WriteLatency100NSMax = 19, FlushLatency100NSMax = 20, Max = 21, }; pub const StorageCounterTypeUnknown = STORAGE_COUNTER_TYPE.Unknown; pub const StorageCounterTypeTemperatureCelsius = STORAGE_COUNTER_TYPE.TemperatureCelsius; pub const StorageCounterTypeTemperatureCelsiusMax = STORAGE_COUNTER_TYPE.TemperatureCelsiusMax; pub const StorageCounterTypeReadErrorsTotal = STORAGE_COUNTER_TYPE.ReadErrorsTotal; pub const StorageCounterTypeReadErrorsCorrected = STORAGE_COUNTER_TYPE.ReadErrorsCorrected; pub const StorageCounterTypeReadErrorsUncorrected = STORAGE_COUNTER_TYPE.ReadErrorsUncorrected; pub const StorageCounterTypeWriteErrorsTotal = STORAGE_COUNTER_TYPE.WriteErrorsTotal; pub const StorageCounterTypeWriteErrorsCorrected = STORAGE_COUNTER_TYPE.WriteErrorsCorrected; pub const StorageCounterTypeWriteErrorsUncorrected = STORAGE_COUNTER_TYPE.WriteErrorsUncorrected; pub const StorageCounterTypeManufactureDate = STORAGE_COUNTER_TYPE.ManufactureDate; pub const StorageCounterTypeStartStopCycleCount = STORAGE_COUNTER_TYPE.StartStopCycleCount; pub const StorageCounterTypeStartStopCycleCountMax = STORAGE_COUNTER_TYPE.StartStopCycleCountMax; pub const StorageCounterTypeLoadUnloadCycleCount = STORAGE_COUNTER_TYPE.LoadUnloadCycleCount; pub const StorageCounterTypeLoadUnloadCycleCountMax = STORAGE_COUNTER_TYPE.LoadUnloadCycleCountMax; pub const StorageCounterTypeWearPercentage = STORAGE_COUNTER_TYPE.WearPercentage; pub const StorageCounterTypeWearPercentageWarning = STORAGE_COUNTER_TYPE.WearPercentageWarning; pub const StorageCounterTypeWearPercentageMax = STORAGE_COUNTER_TYPE.WearPercentageMax; pub const StorageCounterTypePowerOnHours = STORAGE_COUNTER_TYPE.PowerOnHours; pub const StorageCounterTypeReadLatency100NSMax = STORAGE_COUNTER_TYPE.ReadLatency100NSMax; pub const StorageCounterTypeWriteLatency100NSMax = STORAGE_COUNTER_TYPE.WriteLatency100NSMax; pub const StorageCounterTypeFlushLatency100NSMax = STORAGE_COUNTER_TYPE.FlushLatency100NSMax; pub const StorageCounterTypeMax = STORAGE_COUNTER_TYPE.Max; pub const STORAGE_COUNTER = extern struct { Type: STORAGE_COUNTER_TYPE, Value: extern union { ManufactureDate: extern struct { Week: u32, Year: u32, }, AsUlonglong: u64, }, }; pub const STORAGE_COUNTERS = extern struct { Version: u32, Size: u32, NumberOfCounters: u32, Counters: [1]STORAGE_COUNTER, }; pub const STORAGE_HW_FIRMWARE_INFO_QUERY = extern struct { Version: u32, Size: u32, Flags: u32, Reserved: u32, }; pub const STORAGE_HW_FIRMWARE_SLOT_INFO = extern struct { Version: u32, Size: u32, SlotNumber: u8, _bitfield: u8, Reserved1: [6]u8, Revision: [16]u8, }; pub const STORAGE_HW_FIRMWARE_INFO = extern struct { Version: u32, Size: u32, _bitfield: u8, SlotCount: u8, ActiveSlot: u8, PendingActivateSlot: u8, FirmwareShared: BOOLEAN, Reserved: [3]u8, ImagePayloadAlignment: u32, ImagePayloadMaxSize: u32, Slot: [1]STORAGE_HW_FIRMWARE_SLOT_INFO, }; pub const STORAGE_HW_FIRMWARE_DOWNLOAD = extern struct { Version: u32, Size: u32, Flags: u32, Slot: u8, Reserved: [3]u8, Offset: u64, BufferSize: u64, ImageBuffer: [1]u8, }; pub const STORAGE_HW_FIRMWARE_DOWNLOAD_V2 = extern struct { Version: u32, Size: u32, Flags: u32, Slot: u8, Reserved: [3]u8, Offset: u64, BufferSize: u64, ImageSize: u32, Reserved2: u32, ImageBuffer: [1]u8, }; pub const STORAGE_HW_FIRMWARE_ACTIVATE = extern struct { Version: u32, Size: u32, Flags: u32, Slot: u8, Reserved0: [3]u8, }; pub const STORAGE_PROTOCOL_COMMAND = extern struct { Version: u32, Length: u32, ProtocolType: STORAGE_PROTOCOL_TYPE, Flags: u32, ReturnStatus: u32, ErrorCode: u32, CommandLength: u32, ErrorInfoLength: u32, DataToDeviceTransferLength: u32, DataFromDeviceTransferLength: u32, TimeOutValue: u32, ErrorInfoOffset: u32, DataToDeviceBufferOffset: u32, DataFromDeviceBufferOffset: u32, CommandSpecific: u32, Reserved0: u32, FixedProtocolReturnData: u32, Reserved1: [3]u32, Command: [1]u8, }; pub const STORAGE_ATTRIBUTE_MGMT_ACTION = enum(i32) { ClearAttribute = 0, SetAttribute = 1, ResetAttribute = 2, }; pub const StorAttributeMgmt_ClearAttribute = STORAGE_ATTRIBUTE_MGMT_ACTION.ClearAttribute; pub const StorAttributeMgmt_SetAttribute = STORAGE_ATTRIBUTE_MGMT_ACTION.SetAttribute; pub const StorAttributeMgmt_ResetAttribute = STORAGE_ATTRIBUTE_MGMT_ACTION.ResetAttribute; pub const STORAGE_ATTRIBUTE_MGMT = extern struct { Version: u32, Size: u32, Action: STORAGE_ATTRIBUTE_MGMT_ACTION, Attribute: u32, }; pub const SCM_PD_HEALTH_NOTIFICATION_DATA = extern struct { DeviceGuid: Guid, }; pub const SCM_LOGICAL_DEVICE_INSTANCE = extern struct { Version: u32, Size: u32, DeviceGuid: Guid, SymbolicLink: [256]u16, }; pub const SCM_LOGICAL_DEVICES = extern struct { Version: u32, Size: u32, DeviceCount: u32, Devices: [1]SCM_LOGICAL_DEVICE_INSTANCE, }; pub const SCM_PHYSICAL_DEVICE_INSTANCE = extern struct { Version: u32, Size: u32, NfitHandle: u32, SymbolicLink: [256]u16, }; pub const SCM_PHYSICAL_DEVICES = extern struct { Version: u32, Size: u32, DeviceCount: u32, Devices: [1]SCM_PHYSICAL_DEVICE_INSTANCE, }; pub const SCM_REGION_FLAG = enum(i32) { None = 0, Label = 1, }; pub const ScmRegionFlagNone = SCM_REGION_FLAG.None; pub const ScmRegionFlagLabel = SCM_REGION_FLAG.Label; pub const SCM_REGION = extern struct { Version: u32, Size: u32, Flags: u32, NfitHandle: u32, LogicalDeviceGuid: Guid, AddressRangeType: Guid, AssociatedId: u32, Length: u64, StartingDPA: u64, BaseSPA: u64, SPAOffset: u64, RegionOffset: u64, }; pub const SCM_REGIONS = extern struct { Version: u32, Size: u32, RegionCount: u32, Regions: [1]SCM_REGION, }; pub const SCM_BUS_QUERY_TYPE = enum(i32) { Descriptor = 0, IsSupported = 1, Max = 2, }; pub const ScmBusQuery_Descriptor = SCM_BUS_QUERY_TYPE.Descriptor; pub const ScmBusQuery_IsSupported = SCM_BUS_QUERY_TYPE.IsSupported; pub const ScmBusQuery_Max = SCM_BUS_QUERY_TYPE.Max; pub const SCM_BUS_SET_TYPE = enum(i32) { Descriptor = 0, IsSupported = 1, Max = 2, }; pub const ScmBusSet_Descriptor = SCM_BUS_SET_TYPE.Descriptor; pub const ScmBusSet_IsSupported = SCM_BUS_SET_TYPE.IsSupported; pub const ScmBusSet_Max = SCM_BUS_SET_TYPE.Max; pub const SCM_BUS_PROPERTY_ID = enum(i32) { RuntimeFwActivationInfo = 0, DedicatedMemoryInfo = 1, DedicatedMemoryState = 2, Max = 3, }; pub const ScmBusProperty_RuntimeFwActivationInfo = SCM_BUS_PROPERTY_ID.RuntimeFwActivationInfo; pub const ScmBusProperty_DedicatedMemoryInfo = SCM_BUS_PROPERTY_ID.DedicatedMemoryInfo; pub const ScmBusProperty_DedicatedMemoryState = SCM_BUS_PROPERTY_ID.DedicatedMemoryState; pub const ScmBusProperty_Max = SCM_BUS_PROPERTY_ID.Max; pub const SCM_BUS_PROPERTY_QUERY = extern struct { Version: u32, Size: u32, PropertyId: SCM_BUS_PROPERTY_ID, QueryType: SCM_BUS_QUERY_TYPE, AdditionalParameters: [1]u8, }; pub const SCM_BUS_FIRMWARE_ACTIVATION_STATE = enum(i32) { Idle = 0, Armed = 1, Busy = 2, }; pub const ScmBusFirmwareActivationState_Idle = SCM_BUS_FIRMWARE_ACTIVATION_STATE.Idle; pub const ScmBusFirmwareActivationState_Armed = SCM_BUS_FIRMWARE_ACTIVATION_STATE.Armed; pub const ScmBusFirmwareActivationState_Busy = SCM_BUS_FIRMWARE_ACTIVATION_STATE.Busy; pub const SCM_BUS_RUNTIME_FW_ACTIVATION_INFO = extern struct { Version: u32, Size: u32, RuntimeFwActivationSupported: BOOLEAN, FirmwareActivationState: SCM_BUS_FIRMWARE_ACTIVATION_STATE, FirmwareActivationCapability: extern struct { _bitfield: u32, }, EstimatedFirmwareActivationTimeInUSecs: u64, EstimatedProcessorAccessQuiesceTimeInUSecs: u64, EstimatedIOAccessQuiesceTimeInUSecs: u64, PlatformSupportedMaxIOAccessQuiesceTimeInUSecs: u64, }; pub const SCM_BUS_DEDICATED_MEMORY_DEVICE_INFO = extern struct { DeviceGuid: Guid, DeviceNumber: u32, Flags: extern struct { _bitfield: u32, }, DeviceSize: u64, }; pub const SCM_BUS_DEDICATED_MEMORY_DEVICES_INFO = extern struct { Version: u32, Size: u32, DeviceCount: u32, Devices: [1]SCM_BUS_DEDICATED_MEMORY_DEVICE_INFO, }; pub const SCM_BUS_PROPERTY_SET = extern struct { Version: u32, Size: u32, PropertyId: SCM_BUS_PROPERTY_ID, SetType: SCM_BUS_SET_TYPE, AdditionalParameters: [1]u8, }; pub const SCM_BUS_DEDICATED_MEMORY_STATE = extern struct { ActivateState: BOOLEAN, }; pub const SCM_INTERLEAVED_PD_INFO = extern struct { DeviceHandle: u32, DeviceGuid: Guid, }; pub const SCM_LD_INTERLEAVE_SET_INFO = extern struct { Version: u32, Size: u32, InterleaveSetSize: u32, InterleaveSet: [1]SCM_INTERLEAVED_PD_INFO, }; pub const SCM_PD_QUERY_TYPE = enum(i32) { Descriptor = 0, IsSupported = 1, Max = 2, }; pub const ScmPhysicalDeviceQuery_Descriptor = SCM_PD_QUERY_TYPE.Descriptor; pub const ScmPhysicalDeviceQuery_IsSupported = SCM_PD_QUERY_TYPE.IsSupported; pub const ScmPhysicalDeviceQuery_Max = SCM_PD_QUERY_TYPE.Max; pub const SCM_PD_SET_TYPE = enum(i32) { Descriptor = 0, IsSupported = 1, Max = 2, }; pub const ScmPhysicalDeviceSet_Descriptor = SCM_PD_SET_TYPE.Descriptor; pub const ScmPhysicalDeviceSet_IsSupported = SCM_PD_SET_TYPE.IsSupported; pub const ScmPhysicalDeviceSet_Max = SCM_PD_SET_TYPE.Max; pub const SCM_PD_PROPERTY_ID = enum(i32) { DeviceInfo = 0, ManagementStatus = 1, FirmwareInfo = 2, LocationString = 3, DeviceSpecificInfo = 4, DeviceHandle = 5, FruIdString = 6, RuntimeFwActivationInfo = 7, RuntimeFwActivationArmState = 8, Max = 9, }; pub const ScmPhysicalDeviceProperty_DeviceInfo = SCM_PD_PROPERTY_ID.DeviceInfo; pub const ScmPhysicalDeviceProperty_ManagementStatus = SCM_PD_PROPERTY_ID.ManagementStatus; pub const ScmPhysicalDeviceProperty_FirmwareInfo = SCM_PD_PROPERTY_ID.FirmwareInfo; pub const ScmPhysicalDeviceProperty_LocationString = SCM_PD_PROPERTY_ID.LocationString; pub const ScmPhysicalDeviceProperty_DeviceSpecificInfo = SCM_PD_PROPERTY_ID.DeviceSpecificInfo; pub const ScmPhysicalDeviceProperty_DeviceHandle = SCM_PD_PROPERTY_ID.DeviceHandle; pub const ScmPhysicalDeviceProperty_FruIdString = SCM_PD_PROPERTY_ID.FruIdString; pub const ScmPhysicalDeviceProperty_RuntimeFwActivationInfo = SCM_PD_PROPERTY_ID.RuntimeFwActivationInfo; pub const ScmPhysicalDeviceProperty_RuntimeFwActivationArmState = SCM_PD_PROPERTY_ID.RuntimeFwActivationArmState; pub const ScmPhysicalDeviceProperty_Max = SCM_PD_PROPERTY_ID.Max; pub const SCM_PD_PROPERTY_QUERY = extern struct { Version: u32, Size: u32, PropertyId: SCM_PD_PROPERTY_ID, QueryType: SCM_PD_QUERY_TYPE, AdditionalParameters: [1]u8, }; pub const SCM_PD_PROPERTY_SET = extern struct { Version: u32, Size: u32, PropertyId: SCM_PD_PROPERTY_ID, SetType: SCM_PD_SET_TYPE, AdditionalParameters: [1]u8, }; pub const SCM_PD_RUNTIME_FW_ACTIVATION_ARM_STATE = extern struct { ArmState: BOOLEAN, }; pub const SCM_PD_DESCRIPTOR_HEADER = extern struct { Version: u32, Size: u32, }; pub const SCM_PD_DEVICE_HANDLE = extern struct { Version: u32, Size: u32, DeviceGuid: Guid, DeviceHandle: u32, }; pub const SCM_PD_DEVICE_INFO = extern struct { Version: u32, Size: u32, DeviceGuid: Guid, UnsafeShutdownCount: u32, PersistentMemorySizeInBytes: u64, VolatileMemorySizeInBytes: u64, TotalMemorySizeInBytes: u64, SlotNumber: u32, DeviceHandle: u32, PhysicalId: u16, NumberOfFormatInterfaceCodes: u8, FormatInterfaceCodes: [8]u16, VendorId: u32, ProductId: u32, SubsystemDeviceId: u32, SubsystemVendorId: u32, ManufacturingLocation: u8, ManufacturingWeek: u8, ManufacturingYear: u8, SerialNumber4Byte: u32, SerialNumberLengthInChars: u32, SerialNumber: [1]CHAR, }; pub const SCM_PD_DEVICE_SPECIFIC_PROPERTY = extern struct { Name: [128]u16, Value: i64, }; pub const SCM_PD_DEVICE_SPECIFIC_INFO = extern struct { Version: u32, Size: u32, NumberOfProperties: u32, DeviceSpecificProperties: [1]SCM_PD_DEVICE_SPECIFIC_PROPERTY, }; pub const SCM_PD_FIRMWARE_SLOT_INFO = extern struct { Version: u32, Size: u32, SlotNumber: u8, _bitfield: u8, Reserved1: [6]u8, Revision: [32]u8, }; pub const SCM_PD_FIRMWARE_INFO = extern struct { Version: u32, Size: u32, ActiveSlot: u8, NextActiveSlot: u8, SlotCount: u8, Slots: [1]SCM_PD_FIRMWARE_SLOT_INFO, }; pub const SCM_PD_HEALTH_STATUS = enum(i32) { Unknown = 0, Unhealthy = 1, Warning = 2, Healthy = 3, Max = 4, }; pub const ScmPhysicalDeviceHealth_Unknown = SCM_PD_HEALTH_STATUS.Unknown; pub const ScmPhysicalDeviceHealth_Unhealthy = SCM_PD_HEALTH_STATUS.Unhealthy; pub const ScmPhysicalDeviceHealth_Warning = SCM_PD_HEALTH_STATUS.Warning; pub const ScmPhysicalDeviceHealth_Healthy = SCM_PD_HEALTH_STATUS.Healthy; pub const ScmPhysicalDeviceHealth_Max = SCM_PD_HEALTH_STATUS.Max; pub const SCM_PD_OPERATIONAL_STATUS = enum(i32) { Unknown = 0, Ok = 1, PredictingFailure = 2, InService = 3, HardwareError = 4, NotUsable = 5, TransientError = 6, Missing = 7, Max = 8, }; pub const ScmPhysicalDeviceOpStatus_Unknown = SCM_PD_OPERATIONAL_STATUS.Unknown; pub const ScmPhysicalDeviceOpStatus_Ok = SCM_PD_OPERATIONAL_STATUS.Ok; pub const ScmPhysicalDeviceOpStatus_PredictingFailure = SCM_PD_OPERATIONAL_STATUS.PredictingFailure; pub const ScmPhysicalDeviceOpStatus_InService = SCM_PD_OPERATIONAL_STATUS.InService; pub const ScmPhysicalDeviceOpStatus_HardwareError = SCM_PD_OPERATIONAL_STATUS.HardwareError; pub const ScmPhysicalDeviceOpStatus_NotUsable = SCM_PD_OPERATIONAL_STATUS.NotUsable; pub const ScmPhysicalDeviceOpStatus_TransientError = SCM_PD_OPERATIONAL_STATUS.TransientError; pub const ScmPhysicalDeviceOpStatus_Missing = SCM_PD_OPERATIONAL_STATUS.Missing; pub const ScmPhysicalDeviceOpStatus_Max = SCM_PD_OPERATIONAL_STATUS.Max; pub const SCM_PD_OPERATIONAL_STATUS_REASON = enum(i32) { Unknown = 0, Media = 1, ThresholdExceeded = 2, LostData = 3, EnergySource = 4, Configuration = 5, DeviceController = 6, MediaController = 7, Component = 8, BackgroundOperation = 9, InvalidFirmware = 10, HealthCheck = 11, LostDataPersistence = 12, DisabledByPlatform = 13, PermanentError = 14, LostWritePersistence = 15, FatalError = 16, DataPersistenceLossImminent = 17, WritePersistenceLossImminent = 18, MediaRemainingSpareBlock = 19, PerformanceDegradation = 20, ExcessiveTemperature = 21, InternalFailure = 22, Max = 23, }; pub const ScmPhysicalDeviceOpReason_Unknown = SCM_PD_OPERATIONAL_STATUS_REASON.Unknown; pub const ScmPhysicalDeviceOpReason_Media = SCM_PD_OPERATIONAL_STATUS_REASON.Media; pub const ScmPhysicalDeviceOpReason_ThresholdExceeded = SCM_PD_OPERATIONAL_STATUS_REASON.ThresholdExceeded; pub const ScmPhysicalDeviceOpReason_LostData = SCM_PD_OPERATIONAL_STATUS_REASON.LostData; pub const ScmPhysicalDeviceOpReason_EnergySource = SCM_PD_OPERATIONAL_STATUS_REASON.EnergySource; pub const ScmPhysicalDeviceOpReason_Configuration = SCM_PD_OPERATIONAL_STATUS_REASON.Configuration; pub const ScmPhysicalDeviceOpReason_DeviceController = SCM_PD_OPERATIONAL_STATUS_REASON.DeviceController; pub const ScmPhysicalDeviceOpReason_MediaController = SCM_PD_OPERATIONAL_STATUS_REASON.MediaController; pub const ScmPhysicalDeviceOpReason_Component = SCM_PD_OPERATIONAL_STATUS_REASON.Component; pub const ScmPhysicalDeviceOpReason_BackgroundOperation = SCM_PD_OPERATIONAL_STATUS_REASON.BackgroundOperation; pub const ScmPhysicalDeviceOpReason_InvalidFirmware = SCM_PD_OPERATIONAL_STATUS_REASON.InvalidFirmware; pub const ScmPhysicalDeviceOpReason_HealthCheck = SCM_PD_OPERATIONAL_STATUS_REASON.HealthCheck; pub const ScmPhysicalDeviceOpReason_LostDataPersistence = SCM_PD_OPERATIONAL_STATUS_REASON.LostDataPersistence; pub const ScmPhysicalDeviceOpReason_DisabledByPlatform = SCM_PD_OPERATIONAL_STATUS_REASON.DisabledByPlatform; pub const ScmPhysicalDeviceOpReason_PermanentError = SCM_PD_OPERATIONAL_STATUS_REASON.PermanentError; pub const ScmPhysicalDeviceOpReason_LostWritePersistence = SCM_PD_OPERATIONAL_STATUS_REASON.LostWritePersistence; pub const ScmPhysicalDeviceOpReason_FatalError = SCM_PD_OPERATIONAL_STATUS_REASON.FatalError; pub const ScmPhysicalDeviceOpReason_DataPersistenceLossImminent = SCM_PD_OPERATIONAL_STATUS_REASON.DataPersistenceLossImminent; pub const ScmPhysicalDeviceOpReason_WritePersistenceLossImminent = SCM_PD_OPERATIONAL_STATUS_REASON.WritePersistenceLossImminent; pub const ScmPhysicalDeviceOpReason_MediaRemainingSpareBlock = SCM_PD_OPERATIONAL_STATUS_REASON.MediaRemainingSpareBlock; pub const ScmPhysicalDeviceOpReason_PerformanceDegradation = SCM_PD_OPERATIONAL_STATUS_REASON.PerformanceDegradation; pub const ScmPhysicalDeviceOpReason_ExcessiveTemperature = SCM_PD_OPERATIONAL_STATUS_REASON.ExcessiveTemperature; pub const ScmPhysicalDeviceOpReason_InternalFailure = SCM_PD_OPERATIONAL_STATUS_REASON.InternalFailure; pub const ScmPhysicalDeviceOpReason_Max = SCM_PD_OPERATIONAL_STATUS_REASON.Max; pub const SCM_PD_MANAGEMENT_STATUS = extern struct { Version: u32, Size: u32, Health: SCM_PD_HEALTH_STATUS, NumberOfOperationalStatus: u32, NumberOfAdditionalReasons: u32, OperationalStatus: [16]SCM_PD_OPERATIONAL_STATUS, AdditionalReasons: [1]SCM_PD_OPERATIONAL_STATUS_REASON, }; pub const SCM_PD_LOCATION_STRING = extern struct { Version: u32, Size: u32, Location: [1]u16, }; pub const SCM_PD_FRU_ID_STRING = extern struct { Version: u32, Size: u32, IdentifierSize: u32, Identifier: [1]u8, }; pub const SCM_PD_FIRMWARE_DOWNLOAD = extern struct { Version: u32, Size: u32, Flags: u32, Slot: u8, Reserved: [3]u8, Offset: u64, FirmwareImageSizeInBytes: u32, FirmwareImage: [1]u8, }; pub const SCM_PD_FIRMWARE_ACTIVATE = extern struct { Version: u32, Size: u32, Flags: u32, Slot: u8, }; pub const SCM_PD_LAST_FW_ACTIVATION_STATUS = enum(i32) { tionStatus_None = 0, tionStatus_Success = 1, tionStatus_FwNotFound = 2, tionStatus_ColdRebootRequired = 3, itonStatus_ActivationInProgress = 4, itonStatus_Retry = 5, itonStatus_FwUnsupported = 6, itonStatus_UnknownError = 7, }; pub const ScmPdLastFwActivationStatus_None = SCM_PD_LAST_FW_ACTIVATION_STATUS.tionStatus_None; pub const ScmPdLastFwActivationStatus_Success = SCM_PD_LAST_FW_ACTIVATION_STATUS.tionStatus_Success; pub const ScmPdLastFwActivationStatus_FwNotFound = SCM_PD_LAST_FW_ACTIVATION_STATUS.tionStatus_FwNotFound; pub const ScmPdLastFwActivationStatus_ColdRebootRequired = SCM_PD_LAST_FW_ACTIVATION_STATUS.tionStatus_ColdRebootRequired; pub const ScmPdLastFwActivaitonStatus_ActivationInProgress = SCM_PD_LAST_FW_ACTIVATION_STATUS.itonStatus_ActivationInProgress; pub const ScmPdLastFwActivaitonStatus_Retry = SCM_PD_LAST_FW_ACTIVATION_STATUS.itonStatus_Retry; pub const ScmPdLastFwActivaitonStatus_FwUnsupported = SCM_PD_LAST_FW_ACTIVATION_STATUS.itonStatus_FwUnsupported; pub const ScmPdLastFwActivaitonStatus_UnknownError = SCM_PD_LAST_FW_ACTIVATION_STATUS.itonStatus_UnknownError; pub const SCM_PD_FIRMWARE_ACTIVATION_STATE = enum(i32) { Idle = 0, Armed = 1, Busy = 2, }; pub const ScmPdFirmwareActivationState_Idle = SCM_PD_FIRMWARE_ACTIVATION_STATE.Idle; pub const ScmPdFirmwareActivationState_Armed = SCM_PD_FIRMWARE_ACTIVATION_STATE.Armed; pub const ScmPdFirmwareActivationState_Busy = SCM_PD_FIRMWARE_ACTIVATION_STATE.Busy; pub const SCM_PD_RUNTIME_FW_ACTIVATION_INFO = extern struct { Version: u32, Size: u32, LastFirmwareActivationStatus: SCM_PD_LAST_FW_ACTIVATION_STATUS, FirmwareActivationState: SCM_PD_FIRMWARE_ACTIVATION_STATE, }; pub const SCM_PD_PASSTHROUGH_INPUT = extern struct { Version: u32, Size: u32, ProtocolGuid: Guid, DataSize: u32, Data: [1]u8, }; pub const SCM_PD_PASSTHROUGH_OUTPUT = extern struct { Version: u32, Size: u32, ProtocolGuid: Guid, DataSize: u32, Data: [1]u8, }; pub const SCM_PD_PASSTHROUGH_INVDIMM_INPUT = extern struct { Opcode: u32, OpcodeParametersLength: u32, OpcodeParameters: [1]u8, }; pub const SCM_PD_PASSTHROUGH_INVDIMM_OUTPUT = extern struct { GeneralStatus: u16, ExtendedStatus: u16, OutputDataLength: u32, OutputData: [1]u8, }; pub const SCM_PD_REINITIALIZE_MEDIA_INPUT = extern struct { Version: u32, Size: u32, Options: extern struct { _bitfield: u32, }, }; pub const SCM_PD_MEDIA_REINITIALIZATION_STATUS = enum(i32) { Success = 0, RebootNeeded = 1, ColdBootNeeded = 2, Max = 3, }; pub const ScmPhysicalDeviceReinit_Success = SCM_PD_MEDIA_REINITIALIZATION_STATUS.Success; pub const ScmPhysicalDeviceReinit_RebootNeeded = SCM_PD_MEDIA_REINITIALIZATION_STATUS.RebootNeeded; pub const ScmPhysicalDeviceReinit_ColdBootNeeded = SCM_PD_MEDIA_REINITIALIZATION_STATUS.ColdBootNeeded; pub const ScmPhysicalDeviceReinit_Max = SCM_PD_MEDIA_REINITIALIZATION_STATUS.Max; pub const SCM_PD_REINITIALIZE_MEDIA_OUTPUT = extern struct { Version: u32, Size: u32, Status: SCM_PD_MEDIA_REINITIALIZATION_STATUS, }; pub const MEDIA_TYPE = enum(i32) { Unknown = 0, F5_1Pt2_512 = 1, F3_1Pt44_512 = 2, F3_2Pt88_512 = 3, F3_20Pt8_512 = 4, F3_720_512 = 5, F5_360_512 = 6, F5_320_512 = 7, F5_320_1024 = 8, F5_180_512 = 9, F5_160_512 = 10, RemovableMedia = 11, FixedMedia = 12, F3_120M_512 = 13, F3_640_512 = 14, F5_640_512 = 15, F5_720_512 = 16, F3_1Pt2_512 = 17, F3_1Pt23_1024 = 18, F5_1Pt23_1024 = 19, F3_128Mb_512 = 20, F3_230Mb_512 = 21, F8_256_128 = 22, F3_200Mb_512 = 23, F3_240M_512 = 24, F3_32M_512 = 25, }; pub const Unknown = MEDIA_TYPE.Unknown; pub const F5_1Pt2_512 = MEDIA_TYPE.F5_1Pt2_512; pub const F3_1Pt44_512 = MEDIA_TYPE.F3_1Pt44_512; pub const F3_2Pt88_512 = MEDIA_TYPE.F3_2Pt88_512; pub const F3_20Pt8_512 = MEDIA_TYPE.F3_20Pt8_512; pub const F3_720_512 = MEDIA_TYPE.F3_720_512; pub const F5_360_512 = MEDIA_TYPE.F5_360_512; pub const F5_320_512 = MEDIA_TYPE.F5_320_512; pub const F5_320_1024 = MEDIA_TYPE.F5_320_1024; pub const F5_180_512 = MEDIA_TYPE.F5_180_512; pub const F5_160_512 = MEDIA_TYPE.F5_160_512; pub const RemovableMedia = MEDIA_TYPE.RemovableMedia; pub const FixedMedia = MEDIA_TYPE.FixedMedia; pub const F3_120M_512 = MEDIA_TYPE.F3_120M_512; pub const F3_640_512 = MEDIA_TYPE.F3_640_512; pub const F5_640_512 = MEDIA_TYPE.F5_640_512; pub const F5_720_512 = MEDIA_TYPE.F5_720_512; pub const F3_1Pt2_512 = MEDIA_TYPE.F3_1Pt2_512; pub const F3_1Pt23_1024 = MEDIA_TYPE.F3_1Pt23_1024; pub const F5_1Pt23_1024 = MEDIA_TYPE.F5_1Pt23_1024; pub const F3_128Mb_512 = MEDIA_TYPE.F3_128Mb_512; pub const F3_230Mb_512 = MEDIA_TYPE.F3_230Mb_512; pub const F8_256_128 = MEDIA_TYPE.F8_256_128; pub const F3_200Mb_512 = MEDIA_TYPE.F3_200Mb_512; pub const F3_240M_512 = MEDIA_TYPE.F3_240M_512; pub const F3_32M_512 = MEDIA_TYPE.F3_32M_512; pub const FORMAT_PARAMETERS = extern struct { MediaType: MEDIA_TYPE, StartCylinderNumber: u32, EndCylinderNumber: u32, StartHeadNumber: u32, EndHeadNumber: u32, }; pub const FORMAT_EX_PARAMETERS = extern struct { MediaType: MEDIA_TYPE, StartCylinderNumber: u32, EndCylinderNumber: u32, StartHeadNumber: u32, EndHeadNumber: u32, FormatGapLength: u16, SectorsPerTrack: u16, SectorNumber: [1]u16, }; pub const DISK_GEOMETRY = extern struct { Cylinders: LARGE_INTEGER, MediaType: MEDIA_TYPE, TracksPerCylinder: u32, SectorsPerTrack: u32, BytesPerSector: u32, }; pub const PARTITION_INFORMATION = extern struct { StartingOffset: LARGE_INTEGER, PartitionLength: LARGE_INTEGER, HiddenSectors: u32, PartitionNumber: u32, PartitionType: u8, BootIndicator: BOOLEAN, RecognizedPartition: BOOLEAN, RewritePartition: BOOLEAN, }; pub const SET_PARTITION_INFORMATION = extern struct { PartitionType: u8, }; pub const DRIVE_LAYOUT_INFORMATION = extern struct { PartitionCount: u32, Signature: u32, PartitionEntry: [1]PARTITION_INFORMATION, }; pub const VERIFY_INFORMATION = extern struct { StartingOffset: LARGE_INTEGER, Length: u32, }; pub const REASSIGN_BLOCKS = extern struct { Reserved: u16, Count: u16, BlockNumber: [1]u32, }; pub const REASSIGN_BLOCKS_EX = packed struct { Reserved: u16, Count: u16, BlockNumber: [1]LARGE_INTEGER, }; pub const PARTITION_STYLE = enum(i32) { MBR = 0, GPT = 1, RAW = 2, }; pub const PARTITION_STYLE_MBR = PARTITION_STYLE.MBR; pub const PARTITION_STYLE_GPT = PARTITION_STYLE.GPT; pub const PARTITION_STYLE_RAW = PARTITION_STYLE.RAW; pub const PARTITION_INFORMATION_GPT = extern struct { PartitionType: Guid, PartitionId: Guid, Attributes: GPT_ATTRIBUTES, Name: [36]u16, }; pub const PARTITION_INFORMATION_MBR = extern struct { PartitionType: u8, BootIndicator: BOOLEAN, RecognizedPartition: BOOLEAN, HiddenSectors: u32, PartitionId: Guid, }; pub const SET_PARTITION_INFORMATION_EX = extern struct { PartitionStyle: PARTITION_STYLE, Anonymous: extern union { Mbr: SET_PARTITION_INFORMATION, Gpt: PARTITION_INFORMATION_GPT, }, }; pub const CREATE_DISK_GPT = extern struct { DiskId: Guid, MaxPartitionCount: u32, }; pub const CREATE_DISK_MBR = extern struct { Signature: u32, }; pub const CREATE_DISK = extern struct { PartitionStyle: PARTITION_STYLE, Anonymous: extern union { Mbr: CREATE_DISK_MBR, Gpt: CREATE_DISK_GPT, }, }; pub const GET_LENGTH_INFORMATION = extern struct { Length: LARGE_INTEGER, }; pub const PARTITION_INFORMATION_EX = extern struct { PartitionStyle: PARTITION_STYLE, StartingOffset: LARGE_INTEGER, PartitionLength: LARGE_INTEGER, PartitionNumber: u32, RewritePartition: BOOLEAN, IsServicePartition: BOOLEAN, Anonymous: extern union { Mbr: PARTITION_INFORMATION_MBR, Gpt: PARTITION_INFORMATION_GPT, }, }; pub const DRIVE_LAYOUT_INFORMATION_GPT = extern struct { DiskId: Guid, StartingUsableOffset: LARGE_INTEGER, UsableLength: LARGE_INTEGER, MaxPartitionCount: u32, }; pub const DRIVE_LAYOUT_INFORMATION_MBR = extern struct { Signature: u32, CheckSum: u32, }; pub const DRIVE_LAYOUT_INFORMATION_EX = extern struct { PartitionStyle: u32, PartitionCount: u32, Anonymous: extern union { Mbr: DRIVE_LAYOUT_INFORMATION_MBR, Gpt: DRIVE_LAYOUT_INFORMATION_GPT, }, PartitionEntry: [1]PARTITION_INFORMATION_EX, }; pub const DETECTION_TYPE = enum(i32) { None = 0, Int13 = 1, ExInt13 = 2, }; pub const DetectNone = DETECTION_TYPE.None; pub const DetectInt13 = DETECTION_TYPE.Int13; pub const DetectExInt13 = DETECTION_TYPE.ExInt13; pub const DISK_INT13_INFO = extern struct { DriveSelect: u16, MaxCylinders: u32, SectorsPerTrack: u16, MaxHeads: u16, NumberDrives: u16, }; pub const DISK_EX_INT13_INFO = extern struct { ExBufferSize: u16, ExFlags: u16, ExCylinders: u32, ExHeads: u32, ExSectorsPerTrack: u32, ExSectorsPerDrive: u64, ExSectorSize: u16, ExReserved: u16, }; pub const DISK_DETECTION_INFO = extern struct { SizeOfDetectInfo: u32, DetectionType: DETECTION_TYPE, Anonymous: extern union { Anonymous: extern struct { Int13: DISK_INT13_INFO, ExInt13: DISK_EX_INT13_INFO, }, }, }; pub const DISK_PARTITION_INFO = extern struct { SizeOfPartitionInfo: u32, PartitionStyle: PARTITION_STYLE, Anonymous: extern union { Mbr: extern struct { Signature: u32, CheckSum: u32, }, Gpt: extern struct { DiskId: Guid, }, }, }; pub const DISK_GEOMETRY_EX = extern struct { Geometry: DISK_GEOMETRY, DiskSize: LARGE_INTEGER, Data: [1]u8, }; pub const DISK_CONTROLLER_NUMBER = extern struct { ControllerNumber: u32, DiskNumber: u32, }; pub const DISK_CACHE_RETENTION_PRIORITY = enum(i32) { EqualPriority = 0, KeepPrefetchedData = 1, KeepReadData = 2, }; pub const EqualPriority = DISK_CACHE_RETENTION_PRIORITY.EqualPriority; pub const KeepPrefetchedData = DISK_CACHE_RETENTION_PRIORITY.KeepPrefetchedData; pub const KeepReadData = DISK_CACHE_RETENTION_PRIORITY.KeepReadData; pub const DISK_CACHE_INFORMATION = extern struct { ParametersSavable: BOOLEAN, ReadCacheEnabled: BOOLEAN, WriteCacheEnabled: BOOLEAN, ReadRetentionPriority: DISK_CACHE_RETENTION_PRIORITY, WriteRetentionPriority: DISK_CACHE_RETENTION_PRIORITY, DisablePrefetchTransferLength: u16, PrefetchScalar: BOOLEAN, Anonymous: extern union { ScalarPrefetch: extern struct { Minimum: u16, Maximum: u16, MaximumBlocks: u16, }, BlockPrefetch: extern struct { Minimum: u16, Maximum: u16, }, }, }; pub const DISK_GROW_PARTITION = extern struct { PartitionNumber: u32, BytesToGrow: LARGE_INTEGER, }; pub const HISTOGRAM_BUCKET = extern struct { Reads: u32, Writes: u32, }; pub const DISK_HISTOGRAM = extern struct { DiskSize: LARGE_INTEGER, Start: LARGE_INTEGER, End: LARGE_INTEGER, Average: LARGE_INTEGER, AverageRead: LARGE_INTEGER, AverageWrite: LARGE_INTEGER, Granularity: u32, Size: u32, ReadCount: u32, WriteCount: u32, Histogram: ?*HISTOGRAM_BUCKET, }; pub const DISK_PERFORMANCE = extern struct { BytesRead: LARGE_INTEGER, BytesWritten: LARGE_INTEGER, ReadTime: LARGE_INTEGER, WriteTime: LARGE_INTEGER, IdleTime: LARGE_INTEGER, ReadCount: u32, WriteCount: u32, QueueDepth: u32, SplitCount: u32, QueryTime: LARGE_INTEGER, StorageDeviceNumber: u32, StorageManagerName: [8]u16, }; pub const DISK_RECORD = extern struct { ByteOffset: LARGE_INTEGER, StartTime: LARGE_INTEGER, EndTime: LARGE_INTEGER, VirtualAddress: ?*anyopaque, NumberOfBytes: u32, DeviceNumber: u8, ReadRequest: BOOLEAN, }; pub const DISK_LOGGING = extern struct { Function: u8, BufferAddress: ?*anyopaque, BufferSize: u32, }; pub const BIN_TYPES = enum(i32) { Size = 0, Location = 1, }; pub const RequestSize = BIN_TYPES.Size; pub const RequestLocation = BIN_TYPES.Location; pub const BIN_RANGE = extern struct { StartValue: LARGE_INTEGER, Length: LARGE_INTEGER, }; pub const PERF_BIN = extern struct { NumberOfBins: u32, TypeOfBin: u32, BinsRanges: [1]BIN_RANGE, }; pub const BIN_COUNT = extern struct { BinRange: BIN_RANGE, BinCount: u32, }; pub const BIN_RESULTS = extern struct { NumberOfBins: u32, BinCounts: [1]BIN_COUNT, }; pub const GETVERSIONINPARAMS = packed struct { bVersion: u8, bRevision: u8, bReserved: u8, bIDEDeviceMap: u8, fCapabilities: u32, dwReserved: [4]u32, }; pub const IDEREGS = extern struct { bFeaturesReg: u8, bSectorCountReg: u8, bSectorNumberReg: u8, bCylLowReg: u8, bCylHighReg: u8, bDriveHeadReg: u8, bCommandReg: u8, bReserved: u8, }; pub const SENDCMDINPARAMS = packed struct { cBufferSize: u32, irDriveRegs: IDEREGS, bDriveNumber: u8, bReserved: [3]u8, dwReserved: [4]u32, bBuffer: [1]u8, }; pub const DRIVERSTATUS = packed struct { bDriverError: u8, bIDEError: u8, bReserved: [2]u8, dwReserved: [2]u32, }; pub const SENDCMDOUTPARAMS = packed struct { cBufferSize: u32, DriverStatus: DRIVERSTATUS, bBuffer: [1]u8, }; pub const GET_DISK_ATTRIBUTES = extern struct { Version: u32, Reserved1: u32, Attributes: u64, }; pub const SET_DISK_ATTRIBUTES = extern struct { Version: u32, Persist: BOOLEAN, Reserved1: [3]u8, Attributes: u64, AttributesMask: u64, Reserved2: [4]u32, }; pub const ELEMENT_TYPE = enum(i32) { AllElements = 0, ChangerTransport = 1, ChangerSlot = 2, ChangerIEPort = 3, ChangerDrive = 4, ChangerDoor = 5, ChangerKeypad = 6, ChangerMaxElement = 7, }; pub const AllElements = ELEMENT_TYPE.AllElements; pub const ChangerTransport = ELEMENT_TYPE.ChangerTransport; pub const ChangerSlot = ELEMENT_TYPE.ChangerSlot; pub const ChangerIEPort = ELEMENT_TYPE.ChangerIEPort; pub const ChangerDrive = ELEMENT_TYPE.ChangerDrive; pub const ChangerDoor = ELEMENT_TYPE.ChangerDoor; pub const ChangerKeypad = ELEMENT_TYPE.ChangerKeypad; pub const ChangerMaxElement = ELEMENT_TYPE.ChangerMaxElement; pub const CHANGER_ELEMENT = extern struct { ElementType: ELEMENT_TYPE, ElementAddress: u32, }; pub const CHANGER_ELEMENT_LIST = extern struct { Element: CHANGER_ELEMENT, NumberOfElements: u32, }; pub const GET_CHANGER_PARAMETERS = extern struct { Size: u32, NumberTransportElements: u16, NumberStorageElements: u16, NumberCleanerSlots: u16, NumberIEElements: u16, NumberDataTransferElements: u16, NumberOfDoors: u16, FirstSlotNumber: u16, FirstDriveNumber: u16, FirstTransportNumber: u16, FirstIEPortNumber: u16, FirstCleanerSlotAddress: u16, MagazineSize: u16, DriveCleanTimeout: u32, Features0: CHANGER_FEATURES, Features1: GET_CHANGER_PARAMETERS_FEATURES1, MoveFromTransport: u8, MoveFromSlot: u8, MoveFromIePort: u8, MoveFromDrive: u8, ExchangeFromTransport: u8, ExchangeFromSlot: u8, ExchangeFromIePort: u8, ExchangeFromDrive: u8, LockUnlockCapabilities: u8, PositionCapabilities: u8, Reserved1: [2]u8, Reserved2: [2]u32, }; pub const CHANGER_PRODUCT_DATA = extern struct { VendorId: [8]u8, ProductId: [16]u8, Revision: [4]u8, SerialNumber: [32]u8, DeviceType: u8, }; pub const CHANGER_SET_ACCESS = extern struct { Element: CHANGER_ELEMENT, Control: u32, }; pub const CHANGER_READ_ELEMENT_STATUS = extern struct { ElementList: CHANGER_ELEMENT_LIST, VolumeTagInfo: BOOLEAN, }; pub const CHANGER_ELEMENT_STATUS = extern struct { Element: CHANGER_ELEMENT, SrcElementAddress: CHANGER_ELEMENT, Flags: CHANGER_ELEMENT_STATUS_FLAGS, ExceptionCode: u32, TargetId: u8, Lun: u8, Reserved: u16, PrimaryVolumeID: [36]u8, AlternateVolumeID: [36]u8, }; pub const CHANGER_ELEMENT_STATUS_EX = extern struct { Element: CHANGER_ELEMENT, SrcElementAddress: CHANGER_ELEMENT, Flags: CHANGER_ELEMENT_STATUS_FLAGS, ExceptionCode: u32, TargetId: u8, Lun: u8, Reserved: u16, PrimaryVolumeID: [36]u8, AlternateVolumeID: [36]u8, VendorIdentification: [8]u8, ProductIdentification: [16]u8, SerialNumber: [32]u8, }; pub const CHANGER_INITIALIZE_ELEMENT_STATUS = extern struct { ElementList: CHANGER_ELEMENT_LIST, BarCodeScan: BOOLEAN, }; pub const CHANGER_SET_POSITION = extern struct { Transport: CHANGER_ELEMENT, Destination: CHANGER_ELEMENT, Flip: BOOLEAN, }; pub const CHANGER_EXCHANGE_MEDIUM = extern struct { Transport: CHANGER_ELEMENT, Source: CHANGER_ELEMENT, Destination1: CHANGER_ELEMENT, Destination2: CHANGER_ELEMENT, Flip1: BOOLEAN, Flip2: BOOLEAN, }; pub const CHANGER_MOVE_MEDIUM = extern struct { Transport: CHANGER_ELEMENT, Source: CHANGER_ELEMENT, Destination: CHANGER_ELEMENT, Flip: BOOLEAN, }; pub const CHANGER_SEND_VOLUME_TAG_INFORMATION = extern struct { StartingElement: CHANGER_ELEMENT, ActionCode: u32, VolumeIDTemplate: [40]u8, }; pub const READ_ELEMENT_ADDRESS_INFO = extern struct { NumberOfElements: u32, ElementStatus: [1]CHANGER_ELEMENT_STATUS, }; pub const CHANGER_DEVICE_PROBLEM_TYPE = enum(i32) { None = 0, Hardware = 1, CHMError = 2, DoorOpen = 3, CalibrationError = 4, TargetFailure = 5, CHMMoveError = 6, CHMZeroError = 7, CartridgeInsertError = 8, PositionError = 9, SensorError = 10, CartridgeEjectError = 11, GripperError = 12, DriveError = 13, }; pub const DeviceProblemNone = CHANGER_DEVICE_PROBLEM_TYPE.None; pub const DeviceProblemHardware = CHANGER_DEVICE_PROBLEM_TYPE.Hardware; pub const DeviceProblemCHMError = CHANGER_DEVICE_PROBLEM_TYPE.CHMError; pub const DeviceProblemDoorOpen = CHANGER_DEVICE_PROBLEM_TYPE.DoorOpen; pub const DeviceProblemCalibrationError = CHANGER_DEVICE_PROBLEM_TYPE.CalibrationError; pub const DeviceProblemTargetFailure = CHANGER_DEVICE_PROBLEM_TYPE.TargetFailure; pub const DeviceProblemCHMMoveError = CHANGER_DEVICE_PROBLEM_TYPE.CHMMoveError; pub const DeviceProblemCHMZeroError = CHANGER_DEVICE_PROBLEM_TYPE.CHMZeroError; pub const DeviceProblemCartridgeInsertError = CHANGER_DEVICE_PROBLEM_TYPE.CartridgeInsertError; pub const DeviceProblemPositionError = CHANGER_DEVICE_PROBLEM_TYPE.PositionError; pub const DeviceProblemSensorError = CHANGER_DEVICE_PROBLEM_TYPE.SensorError; pub const DeviceProblemCartridgeEjectError = CHANGER_DEVICE_PROBLEM_TYPE.CartridgeEjectError; pub const DeviceProblemGripperError = CHANGER_DEVICE_PROBLEM_TYPE.GripperError; pub const DeviceProblemDriveError = CHANGER_DEVICE_PROBLEM_TYPE.DriveError; pub const PATHNAME_BUFFER = extern struct { PathNameLength: u32, Name: [1]u16, }; pub const FSCTL_QUERY_FAT_BPB_BUFFER = extern struct { First0x24BytesOfBootSector: [36]u8, }; pub const NTFS_VOLUME_DATA_BUFFER = extern struct { VolumeSerialNumber: LARGE_INTEGER, NumberSectors: LARGE_INTEGER, TotalClusters: LARGE_INTEGER, FreeClusters: LARGE_INTEGER, TotalReserved: LARGE_INTEGER, BytesPerSector: u32, BytesPerCluster: u32, BytesPerFileRecordSegment: u32, ClustersPerFileRecordSegment: u32, MftValidDataLength: LARGE_INTEGER, MftStartLcn: LARGE_INTEGER, Mft2StartLcn: LARGE_INTEGER, MftZoneStart: LARGE_INTEGER, MftZoneEnd: LARGE_INTEGER, }; pub const NTFS_EXTENDED_VOLUME_DATA = extern struct { ByteCount: u32, MajorVersion: u16, MinorVersion: u16, BytesPerPhysicalSector: u32, LfsMajorVersion: u16, LfsMinorVersion: u16, MaxDeviceTrimExtentCount: u32, MaxDeviceTrimByteCount: u32, MaxVolumeTrimExtentCount: u32, MaxVolumeTrimByteCount: u32, }; pub const REFS_VOLUME_DATA_BUFFER = extern struct { ByteCount: u32, MajorVersion: u32, MinorVersion: u32, BytesPerPhysicalSector: u32, VolumeSerialNumber: LARGE_INTEGER, NumberSectors: LARGE_INTEGER, TotalClusters: LARGE_INTEGER, FreeClusters: LARGE_INTEGER, TotalReserved: LARGE_INTEGER, BytesPerSector: u32, BytesPerCluster: u32, MaximumSizeOfResidentFile: LARGE_INTEGER, FastTierDataFillRatio: u16, SlowTierDataFillRatio: u16, DestagesFastTierToSlowTierRate: u32, Reserved: [9]LARGE_INTEGER, }; pub const STARTING_LCN_INPUT_BUFFER = extern struct { StartingLcn: LARGE_INTEGER, }; pub const STARTING_LCN_INPUT_BUFFER_EX = extern struct { StartingLcn: LARGE_INTEGER, Flags: u32, }; pub const VOLUME_BITMAP_BUFFER = extern struct { StartingLcn: LARGE_INTEGER, BitmapSize: LARGE_INTEGER, Buffer: [1]u8, }; pub const STARTING_VCN_INPUT_BUFFER = extern struct { StartingVcn: LARGE_INTEGER, }; pub const RETRIEVAL_POINTERS_BUFFER = extern struct { ExtentCount: u32, StartingVcn: LARGE_INTEGER, Extents: [1]extern struct { NextVcn: LARGE_INTEGER, Lcn: LARGE_INTEGER, }, }; pub const RETRIEVAL_POINTERS_AND_REFCOUNT_BUFFER = extern struct { ExtentCount: u32, StartingVcn: LARGE_INTEGER, Extents: [1]extern struct { NextVcn: LARGE_INTEGER, Lcn: LARGE_INTEGER, ReferenceCount: u32, }, }; pub const RETRIEVAL_POINTER_COUNT = extern struct { ExtentCount: u32, }; pub const NTFS_FILE_RECORD_INPUT_BUFFER = extern struct { FileReferenceNumber: LARGE_INTEGER, }; pub const NTFS_FILE_RECORD_OUTPUT_BUFFER = extern struct { FileReferenceNumber: LARGE_INTEGER, FileRecordLength: u32, FileRecordBuffer: [1]u8, }; pub const MOVE_FILE_DATA = extern struct { FileHandle: ?HANDLE, StartingVcn: LARGE_INTEGER, StartingLcn: LARGE_INTEGER, ClusterCount: u32, }; pub const MOVE_FILE_RECORD_DATA = extern struct { FileHandle: ?HANDLE, SourceFileRecord: LARGE_INTEGER, TargetFileRecord: LARGE_INTEGER, }; pub const FIND_BY_SID_DATA = extern struct { Restart: u32, Sid: SID, }; pub const FIND_BY_SID_OUTPUT = extern struct { NextEntryOffset: u32, FileIndex: u32, FileNameLength: u32, FileName: [1]u16, }; pub const MFT_ENUM_DATA_V0 = extern struct { StartFileReferenceNumber: u64, LowUsn: i64, HighUsn: i64, }; pub const MFT_ENUM_DATA_V1 = extern struct { StartFileReferenceNumber: u64, LowUsn: i64, HighUsn: i64, MinMajorVersion: u16, MaxMajorVersion: u16, }; pub const CREATE_USN_JOURNAL_DATA = extern struct { MaximumSize: u64, AllocationDelta: u64, }; pub const READ_FILE_USN_DATA = extern struct { MinMajorVersion: u16, MaxMajorVersion: u16, }; pub const READ_USN_JOURNAL_DATA_V0 = extern struct { StartUsn: i64, ReasonMask: u32, ReturnOnlyOnClose: u32, Timeout: u64, BytesToWaitFor: u64, UsnJournalID: u64, }; pub const READ_USN_JOURNAL_DATA_V1 = extern struct { StartUsn: i64, ReasonMask: u32, ReturnOnlyOnClose: u32, Timeout: u64, BytesToWaitFor: u64, UsnJournalID: u64, MinMajorVersion: u16, MaxMajorVersion: u16, }; pub const USN_TRACK_MODIFIED_RANGES = extern struct { Flags: u32, Unused: u32, ChunkSize: u64, FileSizeThreshold: i64, }; pub const USN_RANGE_TRACK_OUTPUT = extern struct { Usn: i64, }; pub const USN_RECORD_V2 = extern struct { RecordLength: u32, MajorVersion: u16, MinorVersion: u16, FileReferenceNumber: u64, ParentFileReferenceNumber: u64, Usn: i64, TimeStamp: LARGE_INTEGER, Reason: u32, SourceInfo: u32, SecurityId: u32, FileAttributes: u32, FileNameLength: u16, FileNameOffset: u16, FileName: [1]u16, }; pub const USN_RECORD_V3 = extern struct { RecordLength: u32, MajorVersion: u16, MinorVersion: u16, FileReferenceNumber: FILE_ID_128, ParentFileReferenceNumber: FILE_ID_128, Usn: i64, TimeStamp: LARGE_INTEGER, Reason: u32, SourceInfo: u32, SecurityId: u32, FileAttributes: u32, FileNameLength: u16, FileNameOffset: u16, FileName: [1]u16, }; pub const USN_RECORD_COMMON_HEADER = extern struct { RecordLength: u32, MajorVersion: u16, MinorVersion: u16, }; pub const USN_RECORD_EXTENT = extern struct { Offset: i64, Length: i64, }; pub const USN_RECORD_V4 = extern struct { Header: USN_RECORD_COMMON_HEADER, FileReferenceNumber: FILE_ID_128, ParentFileReferenceNumber: FILE_ID_128, Usn: i64, Reason: u32, SourceInfo: USN_SOURCE_INFO_ID, RemainingExtents: u32, NumberOfExtents: u16, ExtentSize: u16, Extents: [1]USN_RECORD_EXTENT, }; pub const USN_RECORD_UNION = extern union { Header: USN_RECORD_COMMON_HEADER, V2: USN_RECORD_V2, V3: USN_RECORD_V3, V4: USN_RECORD_V4, }; pub const USN_JOURNAL_DATA_V0 = extern struct { UsnJournalID: u64, FirstUsn: i64, NextUsn: i64, LowestValidUsn: i64, MaxUsn: i64, MaximumSize: u64, AllocationDelta: u64, }; pub const USN_JOURNAL_DATA_V1 = extern struct { UsnJournalID: u64, FirstUsn: i64, NextUsn: i64, LowestValidUsn: i64, MaxUsn: i64, MaximumSize: u64, AllocationDelta: u64, MinSupportedMajorVersion: u16, MaxSupportedMajorVersion: u16, }; pub const USN_JOURNAL_DATA_V2 = extern struct { UsnJournalID: u64, FirstUsn: i64, NextUsn: i64, LowestValidUsn: i64, MaxUsn: i64, MaximumSize: u64, AllocationDelta: u64, MinSupportedMajorVersion: u16, MaxSupportedMajorVersion: u16, Flags: u32, RangeTrackChunkSize: u64, RangeTrackFileSizeThreshold: i64, }; pub const DELETE_USN_JOURNAL_DATA = extern struct { UsnJournalID: u64, DeleteFlags: USN_DELETE_FLAGS, }; pub const MARK_HANDLE_INFO = extern struct { Anonymous: extern union { UsnSourceInfo: u32, CopyNumber: u32, }, VolumeHandle: ?HANDLE, HandleInfo: u32, }; pub const BULK_SECURITY_TEST_DATA = extern struct { DesiredAccess: u32, SecurityIds: [1]u32, }; pub const FILE_PREFETCH = extern struct { Type: u32, Count: u32, Prefetch: [1]u64, }; pub const FILE_PREFETCH_EX = extern struct { Type: u32, Count: u32, Context: ?*anyopaque, Prefetch: [1]u64, }; pub const FILESYSTEM_STATISTICS = extern struct { FileSystemType: FILESYSTEM_STATISTICS_TYPE, Version: u16, SizeOfCompleteStructure: u32, UserFileReads: u32, UserFileReadBytes: u32, UserDiskReads: u32, UserFileWrites: u32, UserFileWriteBytes: u32, UserDiskWrites: u32, MetaDataReads: u32, MetaDataReadBytes: u32, MetaDataDiskReads: u32, MetaDataWrites: u32, MetaDataWriteBytes: u32, MetaDataDiskWrites: u32, }; pub const FAT_STATISTICS = extern struct { CreateHits: u32, SuccessfulCreates: u32, FailedCreates: u32, NonCachedReads: u32, NonCachedReadBytes: u32, NonCachedWrites: u32, NonCachedWriteBytes: u32, NonCachedDiskReads: u32, NonCachedDiskWrites: u32, }; pub const EXFAT_STATISTICS = extern struct { CreateHits: u32, SuccessfulCreates: u32, FailedCreates: u32, NonCachedReads: u32, NonCachedReadBytes: u32, NonCachedWrites: u32, NonCachedWriteBytes: u32, NonCachedDiskReads: u32, NonCachedDiskWrites: u32, }; pub const NTFS_STATISTICS = extern struct { LogFileFullExceptions: u32, OtherExceptions: u32, MftReads: u32, MftReadBytes: u32, MftWrites: u32, MftWriteBytes: u32, MftWritesUserLevel: extern struct { Write: u16, Create: u16, SetInfo: u16, Flush: u16, }, MftWritesFlushForLogFileFull: u16, MftWritesLazyWriter: u16, MftWritesUserRequest: u16, Mft2Writes: u32, Mft2WriteBytes: u32, Mft2WritesUserLevel: extern struct { Write: u16, Create: u16, SetInfo: u16, Flush: u16, }, Mft2WritesFlushForLogFileFull: u16, Mft2WritesLazyWriter: u16, Mft2WritesUserRequest: u16, RootIndexReads: u32, RootIndexReadBytes: u32, RootIndexWrites: u32, RootIndexWriteBytes: u32, BitmapReads: u32, BitmapReadBytes: u32, BitmapWrites: u32, BitmapWriteBytes: u32, BitmapWritesFlushForLogFileFull: u16, BitmapWritesLazyWriter: u16, BitmapWritesUserRequest: u16, BitmapWritesUserLevel: extern struct { Write: u16, Create: u16, SetInfo: u16, }, MftBitmapReads: u32, MftBitmapReadBytes: u32, MftBitmapWrites: u32, MftBitmapWriteBytes: u32, MftBitmapWritesFlushForLogFileFull: u16, MftBitmapWritesLazyWriter: u16, MftBitmapWritesUserRequest: u16, MftBitmapWritesUserLevel: extern struct { Write: u16, Create: u16, SetInfo: u16, Flush: u16, }, UserIndexReads: u32, UserIndexReadBytes: u32, UserIndexWrites: u32, UserIndexWriteBytes: u32, LogFileReads: u32, LogFileReadBytes: u32, LogFileWrites: u32, LogFileWriteBytes: u32, Allocate: extern struct { Calls: u32, Clusters: u32, Hints: u32, RunsReturned: u32, HintsHonored: u32, HintsClusters: u32, Cache: u32, CacheClusters: u32, CacheMiss: u32, CacheMissClusters: u32, }, DiskResourcesExhausted: u32, }; pub const FILESYSTEM_STATISTICS_EX = extern struct { FileSystemType: FILESYSTEM_STATISTICS_TYPE, Version: u16, SizeOfCompleteStructure: u32, UserFileReads: u64, UserFileReadBytes: u64, UserDiskReads: u64, UserFileWrites: u64, UserFileWriteBytes: u64, UserDiskWrites: u64, MetaDataReads: u64, MetaDataReadBytes: u64, MetaDataDiskReads: u64, MetaDataWrites: u64, MetaDataWriteBytes: u64, MetaDataDiskWrites: u64, }; pub const NTFS_STATISTICS_EX = extern struct { LogFileFullExceptions: u32, OtherExceptions: u32, MftReads: u64, MftReadBytes: u64, MftWrites: u64, MftWriteBytes: u64, MftWritesUserLevel: extern struct { Write: u32, Create: u32, SetInfo: u32, Flush: u32, }, MftWritesFlushForLogFileFull: u32, MftWritesLazyWriter: u32, MftWritesUserRequest: u32, Mft2Writes: u64, Mft2WriteBytes: u64, Mft2WritesUserLevel: extern struct { Write: u32, Create: u32, SetInfo: u32, Flush: u32, }, Mft2WritesFlushForLogFileFull: u32, Mft2WritesLazyWriter: u32, Mft2WritesUserRequest: u32, RootIndexReads: u64, RootIndexReadBytes: u64, RootIndexWrites: u64, RootIndexWriteBytes: u64, BitmapReads: u64, BitmapReadBytes: u64, BitmapWrites: u64, BitmapWriteBytes: u64, BitmapWritesFlushForLogFileFull: u32, BitmapWritesLazyWriter: u32, BitmapWritesUserRequest: u32, BitmapWritesUserLevel: extern struct { Write: u32, Create: u32, SetInfo: u32, Flush: u32, }, MftBitmapReads: u64, MftBitmapReadBytes: u64, MftBitmapWrites: u64, MftBitmapWriteBytes: u64, MftBitmapWritesFlushForLogFileFull: u32, MftBitmapWritesLazyWriter: u32, MftBitmapWritesUserRequest: u32, MftBitmapWritesUserLevel: extern struct { Write: u32, Create: u32, SetInfo: u32, Flush: u32, }, UserIndexReads: u64, UserIndexReadBytes: u64, UserIndexWrites: u64, UserIndexWriteBytes: u64, LogFileReads: u64, LogFileReadBytes: u64, LogFileWrites: u64, LogFileWriteBytes: u64, Allocate: extern struct { Calls: u32, RunsReturned: u32, Hints: u32, HintsHonored: u32, Cache: u32, CacheMiss: u32, Clusters: u64, HintsClusters: u64, CacheClusters: u64, CacheMissClusters: u64, }, DiskResourcesExhausted: u32, VolumeTrimCount: u64, VolumeTrimTime: u64, VolumeTrimByteCount: u64, FileLevelTrimCount: u64, FileLevelTrimTime: u64, FileLevelTrimByteCount: u64, VolumeTrimSkippedCount: u64, VolumeTrimSkippedByteCount: u64, NtfsFillStatInfoFromMftRecordCalledCount: u64, NtfsFillStatInfoFromMftRecordBailedBecauseOfAttributeListCount: u64, NtfsFillStatInfoFromMftRecordBailedBecauseOfNonResReparsePointCount: u64, }; pub const FILE_OBJECTID_BUFFER = extern struct { ObjectId: [16]u8, Anonymous: extern union { Anonymous: extern struct { BirthVolumeId: [16]u8, BirthObjectId: [16]u8, DomainId: [16]u8, }, ExtendedInfo: [48]u8, }, }; pub const FILE_SET_SPARSE_BUFFER = extern struct { SetSparse: BOOLEAN, }; pub const FILE_ZERO_DATA_INFORMATION = extern struct { FileOffset: LARGE_INTEGER, BeyondFinalZero: LARGE_INTEGER, }; pub const FILE_ZERO_DATA_INFORMATION_EX = extern struct { FileOffset: LARGE_INTEGER, BeyondFinalZero: LARGE_INTEGER, Flags: u32, }; pub const FILE_ALLOCATED_RANGE_BUFFER = extern struct { FileOffset: LARGE_INTEGER, Length: LARGE_INTEGER, }; pub const ENCRYPTION_BUFFER = extern struct { EncryptionOperation: u32, Private: [1]u8, }; pub const DECRYPTION_STATUS_BUFFER = extern struct { NoEncryptedStreams: BOOLEAN, }; pub const REQUEST_RAW_ENCRYPTED_DATA = extern struct { FileOffset: i64, Length: u32, }; pub const ENCRYPTED_DATA_INFO = extern struct { StartingFileOffset: u64, OutputBufferOffset: u32, BytesWithinFileSize: u32, BytesWithinValidDataLength: u32, CompressionFormat: u16, DataUnitShift: u8, ChunkShift: u8, ClusterShift: u8, EncryptionFormat: u8, NumberOfDataBlocks: u16, DataBlockSize: [1]u32, }; pub const EXTENDED_ENCRYPTED_DATA_INFO = extern struct { ExtendedCode: u32, Length: u32, Flags: u32, Reserved: u32, }; pub const PLEX_READ_DATA_REQUEST = extern struct { ByteOffset: LARGE_INTEGER, ByteLength: u32, PlexNumber: u32, }; pub const SI_COPYFILE = extern struct { SourceFileNameLength: u32, DestinationFileNameLength: u32, Flags: u32, FileNameBuffer: [1]u16, }; pub const FILE_MAKE_COMPATIBLE_BUFFER = extern struct { CloseDisc: BOOLEAN, }; pub const FILE_SET_DEFECT_MGMT_BUFFER = extern struct { Disable: BOOLEAN, }; pub const FILE_QUERY_SPARING_BUFFER = extern struct { SparingUnitBytes: u32, SoftwareSparing: BOOLEAN, TotalSpareBlocks: u32, FreeSpareBlocks: u32, }; pub const FILE_QUERY_ON_DISK_VOL_INFO_BUFFER = extern struct { DirectoryCount: LARGE_INTEGER, FileCount: LARGE_INTEGER, FsFormatMajVersion: u16, FsFormatMinVersion: u16, FsFormatName: [12]u16, FormatTime: LARGE_INTEGER, LastUpdateTime: LARGE_INTEGER, CopyrightInfo: [34]u16, AbstractInfo: [34]u16, FormattingImplementationInfo: [34]u16, LastModifyingImplementationInfo: [34]u16, }; pub const FILE_INITIATE_REPAIR_OUTPUT_BUFFER = extern struct { Hint1: u64, Hint2: u64, Clsn: u64, Status: u32, }; pub const SHRINK_VOLUME_REQUEST_TYPES = enum(i32) { Prepare = 1, Commit = 2, Abort = 3, }; pub const ShrinkPrepare = SHRINK_VOLUME_REQUEST_TYPES.Prepare; pub const ShrinkCommit = SHRINK_VOLUME_REQUEST_TYPES.Commit; pub const ShrinkAbort = SHRINK_VOLUME_REQUEST_TYPES.Abort; pub const SHRINK_VOLUME_INFORMATION = extern struct { ShrinkRequestType: SHRINK_VOLUME_REQUEST_TYPES, Flags: u64, NewNumberOfSectors: i64, }; pub const TXFS_MODIFY_RM = extern struct { Flags: TXFS_RMF_LAGS, LogContainerCountMax: u32, LogContainerCountMin: u32, LogContainerCount: u32, LogGrowthIncrement: u32, LogAutoShrinkPercentage: u32, Reserved: u64, LoggingMode: u16, }; pub const TXFS_QUERY_RM_INFORMATION = extern struct { BytesRequired: u32, TailLsn: u64, CurrentLsn: u64, ArchiveTailLsn: u64, LogContainerSize: u64, HighestVirtualClock: LARGE_INTEGER, LogContainerCount: u32, LogContainerCountMax: u32, LogContainerCountMin: u32, LogGrowthIncrement: u32, LogAutoShrinkPercentage: u32, Flags: TXFS_RMF_LAGS, LoggingMode: u16, Reserved: u16, RmState: u32, LogCapacity: u64, LogFree: u64, TopsSize: u64, TopsUsed: u64, TransactionCount: u64, OnePCCount: u64, TwoPCCount: u64, NumberLogFileFull: u64, OldestTransactionAge: u64, RMName: Guid, TmLogPathOffset: u32, }; pub const TXFS_ROLLFORWARD_REDO_INFORMATION = extern struct { LastVirtualClock: LARGE_INTEGER, LastRedoLsn: u64, HighestRecoveryLsn: u64, Flags: u32, }; pub const TXFS_START_RM_INFORMATION = extern struct { Flags: u32, LogContainerSize: u64, LogContainerCountMin: u32, LogContainerCountMax: u32, LogGrowthIncrement: u32, LogAutoShrinkPercentage: u32, TmLogPathOffset: u32, TmLogPathLength: u16, LoggingMode: u16, LogPathLength: u16, Reserved: u16, LogPath: [1]u16, }; pub const TXFS_GET_METADATA_INFO_OUT = extern struct { TxfFileId: extern struct { LowPart: i64, HighPart: i64, }, LockingTransaction: Guid, LastLsn: u64, TransactionState: u32, }; pub const TXFS_LIST_TRANSACTION_LOCKED_FILES_ENTRY = extern struct { Offset: u64, NameFlags: u32, FileId: i64, Reserved1: u32, Reserved2: u32, Reserved3: i64, FileName: [1]u16, }; pub const TXFS_LIST_TRANSACTION_LOCKED_FILES = extern struct { KtmTransaction: Guid, NumberOfFiles: u64, BufferSizeRequired: u64, Offset: u64, }; pub const TXFS_LIST_TRANSACTIONS_ENTRY = extern struct { TransactionId: Guid, TransactionState: u32, Reserved1: u32, Reserved2: u32, Reserved3: i64, }; pub const TXFS_LIST_TRANSACTIONS = extern struct { NumberOfTransactions: u64, BufferSizeRequired: u64, }; pub const TXFS_READ_BACKUP_INFORMATION_OUT = extern struct { Anonymous: extern union { BufferLength: u32, Buffer: [1]u8, }, }; pub const TXFS_WRITE_BACKUP_INFORMATION = extern struct { Buffer: [1]u8, }; pub const TXFS_GET_TRANSACTED_VERSION = extern struct { ThisBaseVersion: u32, LatestVersion: u32, ThisMiniVersion: u16, FirstMiniVersion: u16, LatestMiniVersion: u16, }; pub const TXFS_SAVEPOINT_INFORMATION = extern struct { KtmTransaction: ?HANDLE, ActionCode: u32, SavepointId: u32, }; pub const TXFS_CREATE_MINIVERSION_INFO = extern struct { StructureVersion: u16, StructureLength: u16, BaseVersion: u32, MiniVersion: u16, }; pub const TXFS_TRANSACTION_ACTIVE_INFO = extern struct { TransactionsActiveAtSnapshot: BOOLEAN, }; pub const BOOT_AREA_INFO = extern struct { BootSectorCount: u32, BootSectors: [2]extern struct { Offset: LARGE_INTEGER, }, }; pub const RETRIEVAL_POINTER_BASE = extern struct { FileAreaOffset: LARGE_INTEGER, }; pub const FILE_FS_PERSISTENT_VOLUME_INFORMATION = extern struct { VolumeFlags: u32, FlagMask: u32, Version: u32, Reserved: u32, }; pub const FILE_SYSTEM_RECOGNITION_INFORMATION = extern struct { FileSystem: [9]CHAR, }; pub const REQUEST_OPLOCK_INPUT_BUFFER = extern struct { StructureVersion: u16, StructureLength: u16, RequestedOplockLevel: u32, Flags: u32, }; pub const REQUEST_OPLOCK_OUTPUT_BUFFER = extern struct { StructureVersion: u16, StructureLength: u16, OriginalOplockLevel: u32, NewOplockLevel: u32, Flags: u32, AccessMode: u32, ShareMode: u16, }; pub const STORAGE_QUERY_DEPENDENT_VOLUME_REQUEST = extern struct { RequestLevel: u32, RequestFlags: u32, }; pub const STORAGE_QUERY_DEPENDENT_VOLUME_LEV1_ENTRY = extern struct { EntryLength: u32, DependencyTypeFlags: u32, ProviderSpecificFlags: u32, VirtualStorageType: VIRTUAL_STORAGE_TYPE, }; pub const STORAGE_QUERY_DEPENDENT_VOLUME_LEV2_ENTRY = extern struct { EntryLength: u32, DependencyTypeFlags: u32, ProviderSpecificFlags: u32, VirtualStorageType: VIRTUAL_STORAGE_TYPE, AncestorLevel: u32, HostVolumeNameOffset: u32, HostVolumeNameSize: u32, DependentVolumeNameOffset: u32, DependentVolumeNameSize: u32, RelativePathOffset: u32, RelativePathSize: u32, DependentDeviceNameOffset: u32, DependentDeviceNameSize: u32, }; pub const STORAGE_QUERY_DEPENDENT_VOLUME_RESPONSE = extern struct { ResponseLevel: u32, NumberEntries: u32, Anonymous: extern union { Lev1Depends: [1]STORAGE_QUERY_DEPENDENT_VOLUME_LEV1_ENTRY, Lev2Depends: [1]STORAGE_QUERY_DEPENDENT_VOLUME_LEV2_ENTRY, }, }; pub const SD_CHANGE_MACHINE_SID_INPUT = extern struct { CurrentMachineSIDOffset: u16, CurrentMachineSIDLength: u16, NewMachineSIDOffset: u16, NewMachineSIDLength: u16, }; pub const SD_CHANGE_MACHINE_SID_OUTPUT = extern struct { NumSDChangedSuccess: u64, NumSDChangedFail: u64, NumSDUnused: u64, NumSDTotal: u64, NumMftSDChangedSuccess: u64, NumMftSDChangedFail: u64, NumMftSDTotal: u64, }; pub const SD_QUERY_STATS_INPUT = extern struct { Reserved: u32, }; pub const SD_QUERY_STATS_OUTPUT = extern struct { SdsStreamSize: u64, SdsAllocationSize: u64, SiiStreamSize: u64, SiiAllocationSize: u64, SdhStreamSize: u64, SdhAllocationSize: u64, NumSDTotal: u64, NumSDUnused: u64, }; pub const SD_ENUM_SDS_INPUT = extern struct { StartingOffset: u64, MaxSDEntriesToReturn: u64, }; pub const SD_ENUM_SDS_ENTRY = extern struct { Hash: u32, SecurityId: u32, Offset: u64, Length: u32, Descriptor: [1]u8, }; pub const SD_ENUM_SDS_OUTPUT = extern struct { NextOffset: u64, NumSDEntriesReturned: u64, NumSDBytesReturned: u64, SDEntry: [1]SD_ENUM_SDS_ENTRY, }; pub const SD_GLOBAL_CHANGE_INPUT = extern struct { Flags: u32, ChangeType: u32, Anonymous: extern union { SdChange: SD_CHANGE_MACHINE_SID_INPUT, SdQueryStats: SD_QUERY_STATS_INPUT, SdEnumSds: SD_ENUM_SDS_INPUT, }, }; pub const SD_GLOBAL_CHANGE_OUTPUT = extern struct { Flags: u32, ChangeType: u32, Anonymous: extern union { SdChange: SD_CHANGE_MACHINE_SID_OUTPUT, SdQueryStats: SD_QUERY_STATS_OUTPUT, SdEnumSds: SD_ENUM_SDS_OUTPUT, }, }; pub const LOOKUP_STREAM_FROM_CLUSTER_INPUT = extern struct { Flags: u32, NumberOfClusters: u32, Cluster: [1]LARGE_INTEGER, }; pub const LOOKUP_STREAM_FROM_CLUSTER_OUTPUT = extern struct { Offset: u32, NumberOfMatches: u32, BufferSizeRequired: u32, }; pub const LOOKUP_STREAM_FROM_CLUSTER_ENTRY = extern struct { OffsetToNext: u32, Flags: u32, Reserved: LARGE_INTEGER, Cluster: LARGE_INTEGER, FileName: [1]u16, }; pub const FILE_TYPE_NOTIFICATION_INPUT = extern struct { Flags: u32, NumFileTypeIDs: u32, FileTypeID: [1]Guid, }; pub const CSV_MGMT_LOCK = extern struct { Flags: u32, }; pub const CSV_NAMESPACE_INFO = extern struct { Version: u32, DeviceNumber: u32, StartingOffset: LARGE_INTEGER, SectorSize: u32, }; pub const CSV_CONTROL_OP = enum(i32) { StartRedirectFile = 2, StopRedirectFile = 3, QueryRedirectState = 4, QueryFileRevision = 6, QueryMdsPath = 8, QueryFileRevisionFileId128 = 9, QueryVolumeRedirectState = 10, EnableUSNRangeModificationTracking = 13, MarkHandleLocalVolumeMount = 14, UnmarkHandleLocalVolumeMount = 15, GetCsvFsMdsPathV2 = 18, DisableCaching = 19, EnableCaching = 20, StartForceDFO = 21, StopForceDFO = 22, QueryMdsPathNoPause = 23, SetVolumeId = 24, QueryVolumeId = 25, }; pub const CsvControlStartRedirectFile = CSV_CONTROL_OP.StartRedirectFile; pub const CsvControlStopRedirectFile = CSV_CONTROL_OP.StopRedirectFile; pub const CsvControlQueryRedirectState = CSV_CONTROL_OP.QueryRedirectState; pub const CsvControlQueryFileRevision = CSV_CONTROL_OP.QueryFileRevision; pub const CsvControlQueryMdsPath = CSV_CONTROL_OP.QueryMdsPath; pub const CsvControlQueryFileRevisionFileId128 = CSV_CONTROL_OP.QueryFileRevisionFileId128; pub const CsvControlQueryVolumeRedirectState = CSV_CONTROL_OP.QueryVolumeRedirectState; pub const CsvControlEnableUSNRangeModificationTracking = CSV_CONTROL_OP.EnableUSNRangeModificationTracking; pub const CsvControlMarkHandleLocalVolumeMount = CSV_CONTROL_OP.MarkHandleLocalVolumeMount; pub const CsvControlUnmarkHandleLocalVolumeMount = CSV_CONTROL_OP.UnmarkHandleLocalVolumeMount; pub const CsvControlGetCsvFsMdsPathV2 = CSV_CONTROL_OP.GetCsvFsMdsPathV2; pub const CsvControlDisableCaching = CSV_CONTROL_OP.DisableCaching; pub const CsvControlEnableCaching = CSV_CONTROL_OP.EnableCaching; pub const CsvControlStartForceDFO = CSV_CONTROL_OP.StartForceDFO; pub const CsvControlStopForceDFO = CSV_CONTROL_OP.StopForceDFO; pub const CsvControlQueryMdsPathNoPause = CSV_CONTROL_OP.QueryMdsPathNoPause; pub const CsvControlSetVolumeId = CSV_CONTROL_OP.SetVolumeId; pub const CsvControlQueryVolumeId = CSV_CONTROL_OP.QueryVolumeId; pub const CSV_CONTROL_PARAM = extern struct { Operation: CSV_CONTROL_OP, Unused: i64, }; pub const CSV_QUERY_REDIRECT_STATE = extern struct { MdsNodeId: u32, DsNodeId: u32, FileRedirected: BOOLEAN, }; pub const CSV_QUERY_FILE_REVISION = extern struct { FileId: i64, FileRevision: [3]i64, }; pub const CSV_QUERY_FILE_REVISION_FILE_ID_128 = extern struct { FileId: FILE_ID_128, FileRevision: [3]i64, }; pub const CSV_QUERY_MDS_PATH = extern struct { MdsNodeId: u32, DsNodeId: u32, PathLength: u32, Path: [1]u16, }; pub const CSVFS_DISK_CONNECTIVITY = enum(i32) { None = 0, MdsNodeOnly = 1, SubsetOfNodes = 2, AllNodes = 3, }; pub const CsvFsDiskConnectivityNone = CSVFS_DISK_CONNECTIVITY.None; pub const CsvFsDiskConnectivityMdsNodeOnly = CSVFS_DISK_CONNECTIVITY.MdsNodeOnly; pub const CsvFsDiskConnectivitySubsetOfNodes = CSVFS_DISK_CONNECTIVITY.SubsetOfNodes; pub const CsvFsDiskConnectivityAllNodes = CSVFS_DISK_CONNECTIVITY.AllNodes; pub const CSV_QUERY_VOLUME_REDIRECT_STATE = extern struct { MdsNodeId: u32, DsNodeId: u32, IsDiskConnected: BOOLEAN, ClusterEnableDirectIo: BOOLEAN, DiskConnectivity: CSVFS_DISK_CONNECTIVITY, }; pub const CSV_QUERY_MDS_PATH_V2 = extern struct { Version: i64, RequiredSize: u32, MdsNodeId: u32, DsNodeId: u32, Flags: u32, DiskConnectivity: CSVFS_DISK_CONNECTIVITY, VolumeId: Guid, IpAddressOffset: u32, IpAddressLength: u32, PathOffset: u32, PathLength: u32, }; pub const CSV_SET_VOLUME_ID = extern struct { VolumeId: Guid, }; pub const CSV_QUERY_VOLUME_ID = extern struct { VolumeId: Guid, }; pub const CSV_QUERY_VETO_FILE_DIRECT_IO_OUTPUT = extern struct { VetoedFromAltitudeIntegral: u64, VetoedFromAltitudeDecimal: u64, Reason: [256]u16, }; pub const STORAGE_RESERVE_ID = enum(i32) { None = 0, Hard = 1, Soft = 2, UpdateScratch = 3, Max = 4, }; pub const StorageReserveIdNone = STORAGE_RESERVE_ID.None; pub const StorageReserveIdHard = STORAGE_RESERVE_ID.Hard; pub const StorageReserveIdSoft = STORAGE_RESERVE_ID.Soft; pub const StorageReserveIdUpdateScratch = STORAGE_RESERVE_ID.UpdateScratch; pub const StorageReserveIdMax = STORAGE_RESERVE_ID.Max; pub const CSV_IS_OWNED_BY_CSVFS = extern struct { OwnedByCSVFS: BOOLEAN, }; pub const FILE_LEVEL_TRIM_RANGE = extern struct { Offset: u64, Length: u64, }; pub const FILE_LEVEL_TRIM = extern struct { Key: u32, NumRanges: u32, Ranges: [1]FILE_LEVEL_TRIM_RANGE, }; pub const FILE_LEVEL_TRIM_OUTPUT = extern struct { NumRangesProcessed: u32, }; pub const QUERY_FILE_LAYOUT_FILTER_TYPE = enum(i32) { FILTER_TYPE_NONE = 0, FILTER_TYPE_CLUSTERS = 1, FILTER_TYPE_FILEID = 2, FILTER_TYPE_STORAGE_RESERVE_ID = 3, NUM_FILTER_TYPES = 4, }; pub const QUERY_FILE_LAYOUT_FILTER_TYPE_NONE = QUERY_FILE_LAYOUT_FILTER_TYPE.FILTER_TYPE_NONE; pub const QUERY_FILE_LAYOUT_FILTER_TYPE_CLUSTERS = QUERY_FILE_LAYOUT_FILTER_TYPE.FILTER_TYPE_CLUSTERS; pub const QUERY_FILE_LAYOUT_FILTER_TYPE_FILEID = QUERY_FILE_LAYOUT_FILTER_TYPE.FILTER_TYPE_FILEID; pub const QUERY_FILE_LAYOUT_FILTER_TYPE_STORAGE_RESERVE_ID = QUERY_FILE_LAYOUT_FILTER_TYPE.FILTER_TYPE_STORAGE_RESERVE_ID; pub const QUERY_FILE_LAYOUT_NUM_FILTER_TYPES = QUERY_FILE_LAYOUT_FILTER_TYPE.NUM_FILTER_TYPES; pub const CLUSTER_RANGE = extern struct { StartingCluster: LARGE_INTEGER, ClusterCount: LARGE_INTEGER, }; pub const FILE_REFERENCE_RANGE = extern struct { StartingFileReferenceNumber: u64, EndingFileReferenceNumber: u64, }; pub const QUERY_FILE_LAYOUT_INPUT = extern struct { Anonymous: extern union { FilterEntryCount: u32, NumberOfPairs: u32, }, Flags: u32, FilterType: QUERY_FILE_LAYOUT_FILTER_TYPE, Reserved: u32, Filter: extern union { ClusterRanges: [1]CLUSTER_RANGE, FileReferenceRanges: [1]FILE_REFERENCE_RANGE, StorageReserveIds: [1]STORAGE_RESERVE_ID, }, }; pub const QUERY_FILE_LAYOUT_OUTPUT = extern struct { FileEntryCount: u32, FirstFileOffset: u32, Flags: u32, Reserved: u32, }; pub const FILE_LAYOUT_ENTRY = extern struct { Version: u32, NextFileOffset: u32, Flags: u32, FileAttributes: u32, FileReferenceNumber: u64, FirstNameOffset: u32, FirstStreamOffset: u32, ExtraInfoOffset: u32, ExtraInfoLength: u32, }; pub const FILE_LAYOUT_NAME_ENTRY = extern struct { NextNameOffset: u32, Flags: u32, ParentFileReferenceNumber: u64, FileNameLength: u32, Reserved: u32, FileName: [1]u16, }; pub const FILE_LAYOUT_INFO_ENTRY = extern struct { BasicInformation: extern struct { CreationTime: LARGE_INTEGER, LastAccessTime: LARGE_INTEGER, LastWriteTime: LARGE_INTEGER, ChangeTime: LARGE_INTEGER, FileAttributes: u32, }, OwnerId: u32, SecurityId: u32, Usn: i64, StorageReserveId: STORAGE_RESERVE_ID, }; pub const STREAM_LAYOUT_ENTRY = extern struct { Version: u32, NextStreamOffset: u32, Flags: u32, ExtentInformationOffset: u32, AllocationSize: LARGE_INTEGER, EndOfFile: LARGE_INTEGER, StreamInformationOffset: u32, AttributeTypeCode: u32, AttributeFlags: u32, StreamIdentifierLength: u32, StreamIdentifier: [1]u16, }; pub const STREAM_EXTENT_ENTRY = extern struct { Flags: u32, ExtentInformation: extern union { RetrievalPointers: RETRIEVAL_POINTERS_BUFFER, }, }; pub const FSCTL_GET_INTEGRITY_INFORMATION_BUFFER = extern struct { ChecksumAlgorithm: u16, Reserved: u16, Flags: u32, ChecksumChunkSizeInBytes: u32, ClusterSizeInBytes: u32, }; pub const FSCTL_SET_INTEGRITY_INFORMATION_BUFFER = extern struct { ChecksumAlgorithm: u16, Reserved: u16, Flags: u32, }; pub const FSCTL_SET_INTEGRITY_INFORMATION_BUFFER_EX = extern struct { EnableIntegrity: u8, KeepIntegrityStateUnchanged: u8, Reserved: u16, Flags: u32, Version: u8, Reserved2: [7]u8, }; pub const FSCTL_OFFLOAD_READ_INPUT = extern struct { Size: u32, Flags: u32, TokenTimeToLive: u32, Reserved: u32, FileOffset: u64, CopyLength: u64, }; pub const FSCTL_OFFLOAD_READ_OUTPUT = extern struct { Size: u32, Flags: u32, TransferLength: u64, Token: [512]u8, }; pub const FSCTL_OFFLOAD_WRITE_INPUT = extern struct { Size: u32, Flags: u32, FileOffset: u64, CopyLength: u64, TransferOffset: u64, Token: [512]u8, }; pub const FSCTL_OFFLOAD_WRITE_OUTPUT = extern struct { Size: u32, Flags: u32, LengthWritten: u64, }; pub const SET_PURGE_FAILURE_MODE_INPUT = extern struct { Flags: u32, }; pub const REPAIR_COPIES_INPUT = extern struct { Size: u32, Flags: u32, FileOffset: LARGE_INTEGER, Length: u32, SourceCopy: u32, NumberOfRepairCopies: u32, RepairCopies: [1]u32, }; pub const REPAIR_COPIES_OUTPUT = extern struct { Size: u32, Status: u32, ResumeFileOffset: LARGE_INTEGER, }; pub const FILE_REGION_INFO = extern struct { FileOffset: i64, Length: i64, Usage: u32, Reserved: u32, }; pub const FILE_REGION_OUTPUT = extern struct { Flags: u32, TotalRegionEntryCount: u32, RegionEntryCount: u32, Reserved: u32, Region: [1]FILE_REGION_INFO, }; pub const FILE_REGION_INPUT = extern struct { FileOffset: i64, Length: i64, DesiredUsage: u32, }; pub const WRITE_USN_REASON_INPUT = extern struct { Flags: u32, UsnReasonToWrite: u32, }; pub const FILE_STORAGE_TIER_MEDIA_TYPE = enum(i32) { Unspecified = 0, Disk = 1, Ssd = 2, Scm = 4, Max = 5, }; pub const FileStorageTierMediaTypeUnspecified = FILE_STORAGE_TIER_MEDIA_TYPE.Unspecified; pub const FileStorageTierMediaTypeDisk = FILE_STORAGE_TIER_MEDIA_TYPE.Disk; pub const FileStorageTierMediaTypeSsd = FILE_STORAGE_TIER_MEDIA_TYPE.Ssd; pub const FileStorageTierMediaTypeScm = FILE_STORAGE_TIER_MEDIA_TYPE.Scm; pub const FileStorageTierMediaTypeMax = FILE_STORAGE_TIER_MEDIA_TYPE.Max; pub const FILE_STORAGE_TIER_CLASS = enum(i32) { Unspecified = 0, Capacity = 1, Performance = 2, Max = 3, }; pub const FileStorageTierClassUnspecified = FILE_STORAGE_TIER_CLASS.Unspecified; pub const FileStorageTierClassCapacity = FILE_STORAGE_TIER_CLASS.Capacity; pub const FileStorageTierClassPerformance = FILE_STORAGE_TIER_CLASS.Performance; pub const FileStorageTierClassMax = FILE_STORAGE_TIER_CLASS.Max; pub const FILE_STORAGE_TIER = extern struct { Id: Guid, Name: [256]u16, Description: [256]u16, Flags: FILE_STORAGE_TIER_FLAGS, ProvisionedCapacity: u64, MediaType: FILE_STORAGE_TIER_MEDIA_TYPE, Class: FILE_STORAGE_TIER_CLASS, }; pub const FSCTL_QUERY_STORAGE_CLASSES_OUTPUT = extern struct { Version: u32, Size: u32, Flags: FILE_STORAGE_TIER_FLAGS, TotalNumberOfTiers: u32, NumberOfTiersReturned: u32, Tiers: [1]FILE_STORAGE_TIER, }; pub const STREAM_INFORMATION_ENTRY = extern struct { pub const _StreamInformation = extern union { pub const _Reparse = extern struct { Length: u16, Flags: u16, ReparseDataSize: u32, ReparseDataOffset: u32, }; pub const _DesiredStorageClass = extern struct { Class: FILE_STORAGE_TIER_CLASS, Flags: u32, }; pub const _DataStream = extern struct { Length: u16, Flags: u16, Reserved: u32, Vdl: u64, }; pub const _Ea = extern struct { Length: u16, Flags: u16, EaSize: u32, EaInformationOffset: u32, }; DesiredStorageClass: _DesiredStorageClass, DataStream: _DataStream, Reparse: _Reparse, Ea: _Ea, }; Version: u32, Flags: u32, StreamInformation: _StreamInformation, }; pub const FSCTL_QUERY_REGION_INFO_INPUT = extern struct { Version: u32, Size: u32, Flags: u32, NumberOfTierIds: u32, TierIds: [1]Guid, }; pub const FILE_STORAGE_TIER_REGION = extern struct { TierId: Guid, Offset: u64, Length: u64, }; pub const FSCTL_QUERY_REGION_INFO_OUTPUT = extern struct { Version: u32, Size: u32, Flags: u32, Reserved: u32, Alignment: u64, TotalNumberOfRegions: u32, NumberOfRegionsReturned: u32, Regions: [1]FILE_STORAGE_TIER_REGION, }; pub const FILE_DESIRED_STORAGE_CLASS_INFORMATION = extern struct { Class: FILE_STORAGE_TIER_CLASS, Flags: u32, }; pub const DUPLICATE_EXTENTS_DATA = extern struct { FileHandle: ?HANDLE, SourceFileOffset: LARGE_INTEGER, TargetFileOffset: LARGE_INTEGER, ByteCount: LARGE_INTEGER, }; pub const DUPLICATE_EXTENTS_DATA_EX = extern struct { Size: usize, FileHandle: ?HANDLE, SourceFileOffset: LARGE_INTEGER, TargetFileOffset: LARGE_INTEGER, ByteCount: LARGE_INTEGER, Flags: u32, }; pub const DUPLICATE_EXTENTS_STATE = enum(i32) { Inactive = 0, Source = 1, Target = 2, }; pub const FileSnapStateInactive = DUPLICATE_EXTENTS_STATE.Inactive; pub const FileSnapStateSource = DUPLICATE_EXTENTS_STATE.Source; pub const FileSnapStateTarget = DUPLICATE_EXTENTS_STATE.Target; pub const ASYNC_DUPLICATE_EXTENTS_STATUS = extern struct { Version: u32, State: DUPLICATE_EXTENTS_STATE, SourceFileOffset: u64, TargetFileOffset: u64, ByteCount: u64, BytesDuplicated: u64, }; pub const REFS_SMR_VOLUME_GC_STATE = enum(i32) { Inactive = 0, Paused = 1, Active = 2, ActiveFullSpeed = 3, }; pub const SmrGcStateInactive = REFS_SMR_VOLUME_GC_STATE.Inactive; pub const SmrGcStatePaused = REFS_SMR_VOLUME_GC_STATE.Paused; pub const SmrGcStateActive = REFS_SMR_VOLUME_GC_STATE.Active; pub const SmrGcStateActiveFullSpeed = REFS_SMR_VOLUME_GC_STATE.ActiveFullSpeed; pub const REFS_SMR_VOLUME_INFO_OUTPUT = extern struct { Version: u32, Flags: u32, SizeOfRandomlyWritableTier: LARGE_INTEGER, FreeSpaceInRandomlyWritableTier: LARGE_INTEGER, SizeofSMRTier: LARGE_INTEGER, FreeSpaceInSMRTier: LARGE_INTEGER, UsableFreeSpaceInSMRTier: LARGE_INTEGER, VolumeGcState: REFS_SMR_VOLUME_GC_STATE, VolumeGcLastStatus: u32, CurrentGcBandFillPercentage: u32, Unused: [6]u64, }; pub const REFS_SMR_VOLUME_GC_ACTION = enum(i32) { Start = 1, StartFullSpeed = 2, Pause = 3, Stop = 4, }; pub const SmrGcActionStart = REFS_SMR_VOLUME_GC_ACTION.Start; pub const SmrGcActionStartFullSpeed = REFS_SMR_VOLUME_GC_ACTION.StartFullSpeed; pub const SmrGcActionPause = REFS_SMR_VOLUME_GC_ACTION.Pause; pub const SmrGcActionStop = REFS_SMR_VOLUME_GC_ACTION.Stop; pub const REFS_SMR_VOLUME_GC_METHOD = enum(i32) { Compaction = 1, Compression = 2, Rotation = 3, }; pub const SmrGcMethodCompaction = REFS_SMR_VOLUME_GC_METHOD.Compaction; pub const SmrGcMethodCompression = REFS_SMR_VOLUME_GC_METHOD.Compression; pub const SmrGcMethodRotation = REFS_SMR_VOLUME_GC_METHOD.Rotation; pub const REFS_SMR_VOLUME_GC_PARAMETERS = extern struct { Version: u32, Flags: u32, Action: REFS_SMR_VOLUME_GC_ACTION, Method: REFS_SMR_VOLUME_GC_METHOD, IoGranularity: u32, CompressionFormat: u32, Unused: [8]u64, }; pub const STREAMS_QUERY_PARAMETERS_OUTPUT_BUFFER = extern struct { OptimalWriteSize: u32, StreamGranularitySize: u32, StreamIdMin: u32, StreamIdMax: u32, }; pub const STREAMS_ASSOCIATE_ID_INPUT_BUFFER = extern struct { Flags: u32, StreamId: u32, }; pub const STREAMS_QUERY_ID_OUTPUT_BUFFER = extern struct { StreamId: u32, }; pub const QUERY_BAD_RANGES_INPUT_RANGE = extern struct { StartOffset: u64, LengthInBytes: u64, }; pub const QUERY_BAD_RANGES_INPUT = extern struct { Flags: u32, NumRanges: u32, Ranges: [1]QUERY_BAD_RANGES_INPUT_RANGE, }; pub const QUERY_BAD_RANGES_OUTPUT_RANGE = extern struct { Flags: u32, Reserved: u32, StartOffset: u64, LengthInBytes: u64, }; pub const QUERY_BAD_RANGES_OUTPUT = extern struct { Flags: u32, NumBadRanges: u32, NextOffsetToLookUp: u64, BadRanges: [1]QUERY_BAD_RANGES_OUTPUT_RANGE, }; pub const SET_DAX_ALLOC_ALIGNMENT_HINT_INPUT = extern struct { Flags: u32, AlignmentShift: u32, FileOffsetToAlign: u64, FallbackAlignmentShift: u32, }; pub const VIRTUAL_STORAGE_BEHAVIOR_CODE = enum(i32) { Undefined = 0, CacheWriteThrough = 1, CacheWriteBack = 2, StopIoProcessing = 3, RestartIoProcessing = 4, }; pub const VirtualStorageBehaviorUndefined = VIRTUAL_STORAGE_BEHAVIOR_CODE.Undefined; pub const VirtualStorageBehaviorCacheWriteThrough = VIRTUAL_STORAGE_BEHAVIOR_CODE.CacheWriteThrough; pub const VirtualStorageBehaviorCacheWriteBack = VIRTUAL_STORAGE_BEHAVIOR_CODE.CacheWriteBack; pub const VirtualStorageBehaviorStopIoProcessing = VIRTUAL_STORAGE_BEHAVIOR_CODE.StopIoProcessing; pub const VirtualStorageBehaviorRestartIoProcessing = VIRTUAL_STORAGE_BEHAVIOR_CODE.RestartIoProcessing; pub const VIRTUAL_STORAGE_SET_BEHAVIOR_INPUT = extern struct { Size: u32, BehaviorCode: VIRTUAL_STORAGE_BEHAVIOR_CODE, }; pub const ENCRYPTION_KEY_CTRL_INPUT = extern struct { HeaderSize: u32, StructureSize: u32, KeyOffset: u16, KeySize: u16, DplLock: u32, DplUserId: u64, DplCredentialId: u64, }; pub const WOF_EXTERNAL_INFO = extern struct { Version: u32, Provider: u32, }; pub const WOF_EXTERNAL_FILE_ID = extern struct { FileId: FILE_ID_128, }; pub const WOF_VERSION_INFO = extern struct { WofVersion: u32, }; pub const WIM_PROVIDER_EXTERNAL_INFO = extern struct { Version: u32, Flags: u32, DataSourceId: LARGE_INTEGER, ResourceHash: [20]u8, }; pub const WIM_PROVIDER_ADD_OVERLAY_INPUT = extern struct { WimType: u32, WimIndex: u32, WimFileNameOffset: u32, WimFileNameLength: u32, }; pub const WIM_PROVIDER_UPDATE_OVERLAY_INPUT = extern struct { DataSourceId: LARGE_INTEGER, WimFileNameOffset: u32, WimFileNameLength: u32, }; pub const WIM_PROVIDER_REMOVE_OVERLAY_INPUT = extern struct { DataSourceId: LARGE_INTEGER, }; pub const WIM_PROVIDER_SUSPEND_OVERLAY_INPUT = extern struct { DataSourceId: LARGE_INTEGER, }; pub const WIM_PROVIDER_OVERLAY_ENTRY = extern struct { NextEntryOffset: u32, DataSourceId: LARGE_INTEGER, WimGuid: Guid, WimFileNameOffset: u32, WimType: u32, WimIndex: u32, Flags: u32, }; pub const FILE_PROVIDER_EXTERNAL_INFO_V0 = extern struct { Version: u32, Algorithm: u32, }; pub const FILE_PROVIDER_EXTERNAL_INFO_V1 = extern struct { Version: u32, Algorithm: u32, Flags: u32, }; pub const CONTAINER_VOLUME_STATE = extern struct { Flags: u32, }; pub const CONTAINER_ROOT_INFO_INPUT = extern struct { Flags: u32, }; pub const CONTAINER_ROOT_INFO_OUTPUT = extern struct { ContainerRootIdLength: u16, ContainerRootId: [1]u8, }; pub const VIRTUALIZATION_INSTANCE_INFO_INPUT = extern struct { NumberOfWorkerThreads: u32, Flags: u32, }; pub const VIRTUALIZATION_INSTANCE_INFO_INPUT_EX = extern struct { HeaderSize: u16, Flags: u32, NotificationInfoSize: u32, NotificationInfoOffset: u16, ProviderMajorVersion: u16, }; pub const VIRTUALIZATION_INSTANCE_INFO_OUTPUT = extern struct { VirtualizationInstanceID: Guid, }; pub const GET_FILTER_FILE_IDENTIFIER_INPUT = extern struct { AltitudeLength: u16, Altitude: [1]u16, }; pub const GET_FILTER_FILE_IDENTIFIER_OUTPUT = extern struct { FilterFileIdentifierLength: u16, FilterFileIdentifier: [1]u8, }; pub const FS_BPIO_OPERATIONS = enum(i32) { ENABLE = 1, DISABLE = 2, QUERY = 3, VOLUME_STACK_PAUSE = 4, VOLUME_STACK_RESUME = 5, STREAM_PAUSE = 6, STREAM_RESUME = 7, GET_INFO = 8, MAX_OPERATION = 9, }; pub const FS_BPIO_OP_ENABLE = FS_BPIO_OPERATIONS.ENABLE; pub const FS_BPIO_OP_DISABLE = FS_BPIO_OPERATIONS.DISABLE; pub const FS_BPIO_OP_QUERY = FS_BPIO_OPERATIONS.QUERY; pub const FS_BPIO_OP_VOLUME_STACK_PAUSE = FS_BPIO_OPERATIONS.VOLUME_STACK_PAUSE; pub const FS_BPIO_OP_VOLUME_STACK_RESUME = FS_BPIO_OPERATIONS.VOLUME_STACK_RESUME; pub const FS_BPIO_OP_STREAM_PAUSE = FS_BPIO_OPERATIONS.STREAM_PAUSE; pub const FS_BPIO_OP_STREAM_RESUME = FS_BPIO_OPERATIONS.STREAM_RESUME; pub const FS_BPIO_OP_GET_INFO = FS_BPIO_OPERATIONS.GET_INFO; pub const FS_BPIO_OP_MAX_OPERATION = FS_BPIO_OPERATIONS.MAX_OPERATION; pub const FS_BPIO_INFLAGS = enum(i32) { None = 0, SKIP_STORAGE_STACK_QUERY = 1, }; pub const FSBPIO_INFL_None = FS_BPIO_INFLAGS.None; pub const FSBPIO_INFL_SKIP_STORAGE_STACK_QUERY = FS_BPIO_INFLAGS.SKIP_STORAGE_STACK_QUERY; pub const FS_BPIO_INPUT = extern struct { Operation: FS_BPIO_OPERATIONS, InFlags: FS_BPIO_INFLAGS, Reserved1: u64, Reserved2: u64, }; pub const FS_BPIO_OUTFLAGS = enum(i32) { None = 0, VOLUME_STACK_BYPASS_PAUSED = 1, STREAM_BYPASS_PAUSED = 2, FILTER_ATTACH_BLOCKED = 4, COMPATIBLE_STORAGE_DRIVER = 8, }; pub const FSBPIO_OUTFL_None = FS_BPIO_OUTFLAGS.None; pub const FSBPIO_OUTFL_VOLUME_STACK_BYPASS_PAUSED = FS_BPIO_OUTFLAGS.VOLUME_STACK_BYPASS_PAUSED; pub const FSBPIO_OUTFL_STREAM_BYPASS_PAUSED = FS_BPIO_OUTFLAGS.STREAM_BYPASS_PAUSED; pub const FSBPIO_OUTFL_FILTER_ATTACH_BLOCKED = FS_BPIO_OUTFLAGS.FILTER_ATTACH_BLOCKED; pub const FSBPIO_OUTFL_COMPATIBLE_STORAGE_DRIVER = FS_BPIO_OUTFLAGS.COMPATIBLE_STORAGE_DRIVER; pub const FS_BPIO_RESULTS = extern struct { OpStatus: u32, FailingDriverNameLen: u16, FailingDriverName: [32]u16, FailureReasonLen: u16, FailureReason: [128]u16, }; pub const FS_BPIO_INFO = extern struct { ActiveBypassIoCount: u32, StorageDriverNameLen: u16, StorageDriverName: [32]u16, }; pub const FS_BPIO_OUTPUT = extern struct { Operation: FS_BPIO_OPERATIONS, OutFlags: FS_BPIO_OUTFLAGS, Reserved1: u64, Reserved2: u64, Anonymous: extern union { Enable: FS_BPIO_RESULTS, Query: FS_BPIO_RESULTS, VolumeStackResume: FS_BPIO_RESULTS, StreamResume: FS_BPIO_RESULTS, GetInfo: FS_BPIO_INFO, }, }; pub const SMB_SHARE_FLUSH_AND_PURGE_INPUT = extern struct { Version: u16, }; pub const SMB_SHARE_FLUSH_AND_PURGE_OUTPUT = extern struct { cEntriesPurged: u32, }; pub const DISK_EXTENT = extern struct { DiskNumber: u32, StartingOffset: LARGE_INTEGER, ExtentLength: LARGE_INTEGER, }; pub const VOLUME_DISK_EXTENTS = extern struct { NumberOfDiskExtents: u32, Extents: [1]DISK_EXTENT, }; pub const VOLUME_GET_GPT_ATTRIBUTES_INFORMATION = extern struct { GptAttributes: u64, }; pub const PIO_IRP_EXT_PROCESS_TRACKED_OFFSET_CALLBACK = fn( SourceContext: ?*IO_IRP_EXT_TRACK_OFFSET_HEADER, TargetContext: ?*IO_IRP_EXT_TRACK_OFFSET_HEADER, RelativeOffset: i64, ) callconv(@import("std").os.windows.WINAPI) void; pub const IO_IRP_EXT_TRACK_OFFSET_HEADER = extern struct { Validation: u16, Flags: u16, TrackedOffsetCallback: ?PIO_IRP_EXT_PROCESS_TRACKED_OFFSET_CALLBACK, }; pub const MOVE_FILE_DATA32 = switch(@import("../zig.zig").arch) { .X64, .Arm64 => extern struct { FileHandle: u32, StartingVcn: LARGE_INTEGER, StartingLcn: LARGE_INTEGER, ClusterCount: u32, }, else => usize, // NOTE: this should be a @compileError but can't because of https://github.com/ziglang/zig/issues/9682 }; pub const MARK_HANDLE_INFO32 = switch(@import("../zig.zig").arch) { .X64, .Arm64 => extern struct { Anonymous: extern union { UsnSourceInfo: u32, CopyNumber: u32, }, VolumeHandle: u32, HandleInfo: u32, }, else => usize, // NOTE: this should be a @compileError but can't because of https://github.com/ziglang/zig/issues/9682 }; pub const DUPLICATE_EXTENTS_DATA32 = switch(@import("../zig.zig").arch) { .X64, .Arm64 => extern struct { FileHandle: u32, SourceFileOffset: LARGE_INTEGER, TargetFileOffset: LARGE_INTEGER, ByteCount: LARGE_INTEGER, }, else => usize, // NOTE: this should be a @compileError but can't because of https://github.com/ziglang/zig/issues/9682 }; pub const DUPLICATE_EXTENTS_DATA_EX32 = switch(@import("../zig.zig").arch) { .X64, .Arm64 => extern struct { Size: u32, FileHandle: u32, SourceFileOffset: LARGE_INTEGER, TargetFileOffset: LARGE_INTEGER, ByteCount: LARGE_INTEGER, Flags: u32, }, else => usize, // NOTE: this should be a @compileError but can't because of https://github.com/ziglang/zig/issues/9682 }; //-------------------------------------------------------------------------------- // Section: Functions (0) //-------------------------------------------------------------------------------- //-------------------------------------------------------------------------------- // Section: Unicode Aliases (0) //-------------------------------------------------------------------------------- const thismodule = @This(); pub usingnamespace switch (@import("../zig.zig").unicode_mode) { .ansi => struct { }, .wide => struct { }, .unspecified => if (@import("builtin").is_test) struct { } else struct { }, }; //-------------------------------------------------------------------------------- // Section: Imports (10) //-------------------------------------------------------------------------------- const Guid = @import("../zig.zig").Guid; const BOOLEAN = @import("../foundation.zig").BOOLEAN; const CHAR = @import("../foundation.zig").CHAR; const FILE_ID_128 = @import("../storage/file_system.zig").FILE_ID_128; const HANDLE = @import("../foundation.zig").HANDLE; const LARGE_INTEGER = @import("../foundation.zig").LARGE_INTEGER; const PROPERTYKEY = @import("../ui/shell/properties_system.zig").PROPERTYKEY; const SID = @import("../security.zig").SID; const STORAGE_BUS_TYPE = @import("../storage/file_system.zig").STORAGE_BUS_TYPE; const VIRTUAL_STORAGE_TYPE = @import("../storage/vhd.zig").VIRTUAL_STORAGE_TYPE; test { // The following '_ = <FuncPtrType>' lines are a workaround for https://github.com/ziglang/zig/issues/4476 if (@hasDecl(@This(), "PIO_IRP_EXT_PROCESS_TRACKED_OFFSET_CALLBACK")) { _ = PIO_IRP_EXT_PROCESS_TRACKED_OFFSET_CALLBACK; } @setEvalBranchQuota( @import("std").meta.declarations(@This()).len * 3 ); // reference all the pub declarations if (!@import("builtin").is_test) return; inline for (@import("std").meta.declarations(@This())) |decl| { if (decl.is_pub) { _ = decl; } } }
win32/system/ioctl.zig
pub const DSSI_READ_ONLY = @as(u32, 1); pub const DSSI_NO_ACCESS_CHECK = @as(u32, 2); pub const DSSI_NO_EDIT_SACL = @as(u32, 4); pub const DSSI_NO_EDIT_OWNER = @as(u32, 8); pub const DSSI_IS_ROOT = @as(u32, 16); pub const DSSI_NO_FILTER = @as(u32, 32); pub const DSSI_NO_READONLY_MESSAGE = @as(u32, 64); //-------------------------------------------------------------------------------- // Section: Types (6) //-------------------------------------------------------------------------------- pub const PFNREADOBJECTSECURITY = fn( param0: ?[*:0]const u16, param1: u32, param2: ?*?*SECURITY_DESCRIPTOR, param3: LPARAM, ) callconv(@import("std").os.windows.WINAPI) HRESULT; pub const PFNWRITEOBJECTSECURITY = fn( param0: ?[*:0]const u16, param1: u32, param2: ?*SECURITY_DESCRIPTOR, param3: LPARAM, ) callconv(@import("std").os.windows.WINAPI) HRESULT; pub const PFNDSCREATEISECINFO = fn( param0: ?[*:0]const u16, param1: ?[*:0]const u16, param2: u32, param3: ?*?*ISecurityInformation, param4: ?PFNREADOBJECTSECURITY, param5: ?PFNWRITEOBJECTSECURITY, param6: LPARAM, ) callconv(@import("std").os.windows.WINAPI) HRESULT; pub const PFNDSCREATEISECINFOEX = fn( param0: ?[*:0]const u16, param1: ?[*:0]const u16, param2: ?[*:0]const u16, param3: ?[*:0]const u16, param4: ?[*:0]const u16, param5: u32, param6: ?*?*ISecurityInformation, param7: ?PFNREADOBJECTSECURITY, param8: ?PFNWRITEOBJECTSECURITY, param9: LPARAM, ) callconv(@import("std").os.windows.WINAPI) HRESULT; pub const PFNDSCREATESECPAGE = fn( param0: ?[*:0]const u16, param1: ?[*:0]const u16, param2: u32, param3: ?*?HPROPSHEETPAGE, param4: ?PFNREADOBJECTSECURITY, param5: ?PFNWRITEOBJECTSECURITY, param6: LPARAM, ) callconv(@import("std").os.windows.WINAPI) HRESULT; pub const PFNDSEDITSECURITY = fn( param0: ?HWND, param1: ?[*:0]const u16, param2: ?[*:0]const u16, param3: u32, param4: ?[*:0]const u16, param5: ?PFNREADOBJECTSECURITY, param6: ?PFNWRITEOBJECTSECURITY, param7: LPARAM, ) callconv(@import("std").os.windows.WINAPI) HRESULT; //-------------------------------------------------------------------------------- // Section: Functions (4) //-------------------------------------------------------------------------------- // TODO: this type is limited to platform 'windowsServer2008' pub extern "DSSEC" fn DSCreateISecurityInfoObject( pwszObjectPath: ?[*:0]const u16, pwszObjectClass: ?[*:0]const u16, dwFlags: u32, ppSI: ?*?*ISecurityInformation, pfnReadSD: ?PFNREADOBJECTSECURITY, pfnWriteSD: ?PFNWRITEOBJECTSECURITY, lpContext: LPARAM, ) callconv(@import("std").os.windows.WINAPI) HRESULT; // TODO: this type is limited to platform 'windowsServer2008' pub extern "DSSEC" fn DSCreateISecurityInfoObjectEx( pwszObjectPath: ?[*:0]const u16, pwszObjectClass: ?[*:0]const u16, pwszServer: ?[*:0]const u16, pwszUserName: ?[*:0]const u16, pwszPassword: ?[*:0]const u16, dwFlags: u32, ppSI: ?*?*ISecurityInformation, pfnReadSD: ?PFNREADOBJECTSECURITY, pfnWriteSD: ?PFNWRITEOBJECTSECURITY, lpContext: LPARAM, ) callconv(@import("std").os.windows.WINAPI) HRESULT; // TODO: this type is limited to platform 'windowsServer2003' pub extern "DSSEC" fn DSCreateSecurityPage( pwszObjectPath: ?[*:0]const u16, pwszObjectClass: ?[*:0]const u16, dwFlags: u32, phPage: ?*?HPROPSHEETPAGE, pfnReadSD: ?PFNREADOBJECTSECURITY, pfnWriteSD: ?PFNWRITEOBJECTSECURITY, lpContext: LPARAM, ) callconv(@import("std").os.windows.WINAPI) HRESULT; // TODO: this type is limited to platform 'windowsServer2008' pub extern "DSSEC" fn DSEditSecurity( hwndOwner: ?HWND, pwszObjectPath: ?[*:0]const u16, pwszObjectClass: ?[*:0]const u16, dwFlags: u32, pwszCaption: ?[*:0]const u16, pfnReadSD: ?PFNREADOBJECTSECURITY, pfnWriteSD: ?PFNWRITEOBJECTSECURITY, lpContext: LPARAM, ) callconv(@import("std").os.windows.WINAPI) HRESULT; //-------------------------------------------------------------------------------- // Section: Unicode Aliases (0) //-------------------------------------------------------------------------------- const thismodule = @This(); pub usingnamespace switch (@import("../zig.zig").unicode_mode) { .ansi => struct { }, .wide => struct { }, .unspecified => if (@import("builtin").is_test) struct { } else struct { }, }; //-------------------------------------------------------------------------------- // Section: Imports (7) //-------------------------------------------------------------------------------- const HPROPSHEETPAGE = @import("../ui/controls.zig").HPROPSHEETPAGE; const HRESULT = @import("../foundation.zig").HRESULT; const HWND = @import("../foundation.zig").HWND; const ISecurityInformation = @import("../security/authorization/ui.zig").ISecurityInformation; const LPARAM = @import("../foundation.zig").LPARAM; const PWSTR = @import("../foundation.zig").PWSTR; const SECURITY_DESCRIPTOR = @import("../security.zig").SECURITY_DESCRIPTOR; test { // The following '_ = <FuncPtrType>' lines are a workaround for https://github.com/ziglang/zig/issues/4476 if (@hasDecl(@This(), "PFNREADOBJECTSECURITY")) { _ = PFNREADOBJECTSECURITY; } if (@hasDecl(@This(), "PFNWRITEOBJECTSECURITY")) { _ = PFNWRITEOBJECTSECURITY; } if (@hasDecl(@This(), "PFNDSCREATEISECINFO")) { _ = PFNDSCREATEISECINFO; } if (@hasDecl(@This(), "PFNDSCREATEISECINFOEX")) { _ = PFNDSCREATEISECINFOEX; } if (@hasDecl(@This(), "PFNDSCREATESECPAGE")) { _ = PFNDSCREATESECPAGE; } if (@hasDecl(@This(), "PFNDSEDITSECURITY")) { _ = PFNDSEDITSECURITY; } @setEvalBranchQuota( @import("std").meta.declarations(@This()).len * 3 ); // reference all the pub declarations if (!@import("builtin").is_test) return; inline for (@import("std").meta.declarations(@This())) |decl| { if (decl.is_pub) { _ = decl; } } }
win32/security/directory_services.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 leroycep1 properly" { const file = try helpers.testOpenFile(helpers.zigimg_test_allocator, "tests/fixtures/png/leroycep1.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 helpers.expectEq(pngFile.header.width, 17); try helpers.expectEq(pngFile.header.height, 12); try helpers.expectEq(pngFile.header.color_type, png.ColorType.Truecolor); try testing.expect(pixelsOpt != null); if (pixelsOpt) |pixels| { try testing.expect(pixels == PixelFormat.Rgb24); const test_inputs = [_]helpers.TestInput{ .{ .x = 7, .hex = 0x062fc2, }, .{ .x = 8, .hex = 0x4c68cf, }, .{ .x = 7, .y = 1, .hex = 0x8798d9, }, .{ .x = 9, .y = 2, .hex = 0xebebeb, }, }; for (test_inputs) |input| { const expected_color = color.IntegerColor8.fromHtmlHex(input.hex); const index = pngFile.header.width * input.y + input.x; try helpers.expectEq(pixels.Rgb24[index].toColor().toIntegerColor8(), expected_color); } } } test "Read leroycep2 properly" { const file = try helpers.testOpenFile(helpers.zigimg_test_allocator, "tests/fixtures/png/leroycep2.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 helpers.expectEq(pngFile.header.width, 37); try helpers.expectEq(pngFile.header.height, 39); try helpers.expectEq(pngFile.header.color_type, png.ColorType.TruecolorAlpha); try testing.expect(pixelsOpt != null); if (pixelsOpt) |pixels| { try testing.expect(pixels == PixelFormat.Rgba32); const test_inputs = [_]helpers.TestInput{ .{ .x = 8, .y = 9, .hex = 0xb37e6d, }, .{ .x = 10, .y = 24, .hex = 0x914f28, }, .{ .x = 16, .y = 15, .hex = 0x914f28, }, .{ .x = 22, .y = 33, .hex = 0x412b0f, }, }; for (test_inputs) |input| { const expected_color = color.IntegerColor8.fromHtmlHex(input.hex); const index = pngFile.header.width * input.y + input.x; try helpers.expectEq(pixels.Rgba32[index].toColor().toIntegerColor8(), expected_color); } } } test "Read leroycep3 properly" { const file = try helpers.testOpenFile(helpers.zigimg_test_allocator, "tests/fixtures/png/leroycep3.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 helpers.expectEq(pngFile.header.width, 10); try helpers.expectEq(pngFile.header.height, 10); try helpers.expectEq(pngFile.header.color_type, png.ColorType.Truecolor); try testing.expect(pixelsOpt != null); if (pixelsOpt) |pixels| { try testing.expect(pixels == PixelFormat.Rgb24); const test_inputs = [_]helpers.TestInput{ .{ .x = 3, .hex = 0xc3600b, }, .{ .x = 4, .hex = 0xd6a275, }, .{ .x = 5, .hex = 0xd9ab85, }, .{ .x = 5, .y = 2, .hex = 0xebebeb, }, }; for (test_inputs) |input| { const expected_color = color.IntegerColor8.fromHtmlHex(input.hex); const index = pngFile.header.width * input.y + input.x; try helpers.expectEq(pixels.Rgb24[index].toColor().toIntegerColor8(), expected_color); } } } test "Read leroycep4 properly" { const file = try helpers.testOpenFile(helpers.zigimg_test_allocator, "tests/fixtures/png/leroycep4.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 helpers.expectEq(pngFile.header.width, 10); try helpers.expectEq(pngFile.header.height, 10); try helpers.expectEq(pngFile.header.color_type, png.ColorType.Truecolor); try testing.expect(pixelsOpt != null); if (pixelsOpt) |pixels| { try testing.expect(pixels == PixelFormat.Rgb24); const test_inputs = [_]helpers.TestInput{ .{ .x = 3, .hex = 0x88fb86, }, .{ .x = 4, .hex = 0xbbf3ba, }, .{ .x = 4, .y = 4, .hex = 0x2d452c, }, .{ .x = 5, .y = 4, .hex = 0x3d6d3c, }, .{ .x = 4, .y = 3, .hex = 0xebebeb, }, }; for (test_inputs) |input| { const expected_color = color.IntegerColor8.fromHtmlHex(input.hex); const index = pngFile.header.width * input.y + input.x; try helpers.expectEq(pixels.Rgb24[index].toColor().toIntegerColor8(), expected_color); } } }
tests/formats/png_misc_test.zig
const std = @import("std"); const pq = @cImport({ @cInclude("libpq-fe.h"); }); pub const version = "0.0.1"; pub const string = []const u8; pub const c_string = [*:0]const u8; pub const ConnectionParams = struct { hostname: string = "localhost", username: string = "postgres", dbname: string = "", pub fn dsn(self: *ConnectionParams) !c_string { const value = try std.fmt.allocPrint0( std.heap.page_allocator, "host={} dbname={} user={} connect_timeout=10", .{ self.hostname, self.dbname, self.username }, ); return value; } }; pub const ExecStatusType = enum(u8) { PGRES_EMPTY_QUERY = pq.PGRES_EMPTY_QUERY, PGRES_COMMAND_OK = pq.PGRES_COMMAND_OK, PGRES_TUPLES_OK = pq.PGRES_TUPLES_OK, PGRES_COPY_OUT = pq.PGRES_COPY_OUT, PGRES_COPY_IN = pq.PGRES_COPY_IN, PGRES_BAD_RESPONSE = pq.PGRES_BAD_RESPONSE, PGRES_NONFATAL_ERROR = pq.PGRES_NONFATAL_ERROR, PGRES_FATAL_ERROR = pq.PGRES_FATAL_ERROR, PGRES_COPY_BOTH = pq.PGRES_COPY_BOTH, PGRES_SINGLE_TUPLE = pq.PGRES_SINGLE_TUPLE, }; pub const result = opaque { extern fn PQresultStatus(PGresult: *result) u8; pub fn status(res: *result) ExecStatusType { return @intToEnum(ExecStatusType, PQresultStatus(res)); } extern fn PQcmdStatus(PGresult: *result) c_string; pub fn cmdStatus(res: *result) c_string { return PQcmdStatus(res); } extern fn PQcmdTuples(PGresult: *result) c_string; pub fn cmdTuples(res: *result) c_string { return PQcmdTuples(res); } extern fn PQclear(PGresult: *result) void; pub fn clear(res: *result) void { PQclear(res); } extern fn PQntuples(PGresult: *result) u8; pub fn numTuples(res: *result) u8 { return PQntuples(res); } extern fn PQnfields(PGresult: *result) u8; pub fn numFields(res: *result) u8 { return PQnfields(res); } extern fn PQfname(PGresult: *result, fld: u8) c_string; pub fn fieldName(res: *result, fld: u8) c_string { return PQfname(res, fld); } extern fn PQfnumber(PGresult: *result, fld: c_string) u8; pub fn fieldNumber(res: *result, fld: c_string) u8 { return PQfnumber(res, fld); } extern fn PQgetvalue(PGresult: *result, row: u8, col: u8) c_string; pub fn get(res: *result, row: u8, col: u8) c_string { return PQgetvalue(res, row, col); } //int PQgetisnull(const PGresult *res, //int row_number, //int column_number); }; pub const DB = opaque { extern fn PQexec(PGconn: *DB, command: c_string) *result; pub fn exec(conn: *DB, command: c_string) *result { return PQexec(conn, @ptrCast(c_string, command)); } extern fn PQdb(PGconn: *DB) c_string; pub fn name(conn: *DB) c_string { return PQdb(conn); } }; extern fn PQconnectdb(dsn: c_string) *DB; pub fn connect(dsn: c_string) ?*DB { var conn = PQconnectdb(dsn); return conn; }
postgres.zig
const std = @import("std"); const c = @import("internal/c.zig"); const internal = @import("internal/internal.zig"); const log = std.log.scoped(.git); const git = @import("git.zig"); /// Filters are applied in one of two directions: smudging - which is exporting a file from the Git object database to the working /// directory, and cleaning - which is importing a file from the working directory to the Git object database. These values /// control which direction of change is being applied. pub const FilterMode = enum(c_uint) { TO_WORKTREE = 0, TO_ODB = 1, pub const SMUDGE = FilterMode.TO_WORKTREE; pub const CLEAN = FilterMode.TO_ODB; }; pub const FilterFlags = packed struct { /// Don't error for `safecrlf` violations, allow them to continue. ALLOW_UNSAFE: bool = false, /// Don't load `/etc/gitattributes` (or the system equivalent) NO_SYSTEM_ATTRIBUTES: bool = false, /// Load attributes from `.gitattributes` in the root of HEAD ATTRIBUTES_FROM_HEAD: bool = false, /// Load attributes from `.gitattributes` in a given commit. This can only be specified in a `FilterOptions` ATTRIBUTES_FROM_COMMIT: bool = false, z_padding: u28 = 0, pub fn format( value: FilterFlags, comptime fmt: []const u8, options: std.fmt.FormatOptions, writer: anytype, ) !void { _ = fmt; return internal.formatWithoutFields( value, options, writer, &.{"z_padding"}, ); } test { try std.testing.expectEqual(@sizeOf(c.git_filter_flag_t), @sizeOf(FilterFlags)); try std.testing.expectEqual(@bitSizeOf(c.git_filter_flag_t), @bitSizeOf(FilterFlags)); } comptime { std.testing.refAllDecls(@This()); } }; pub const FilterOptions = struct { flags: FilterFlags = .{}, commit_id: ?*git.Oid = null, /// The commit to load attributes from, when `FilterFlags.ATTRIBUTES_FROM_COMMIT` is specified. attr_commit_id: git.Oid = .{.id = [_]u8{0}**20}, pub fn makeCOptionObject(self: FilterOptions) c.git_filter_options { return .{ .version = c.GIT_FILTER_OPTIONS_VERSION, .flags = @bitCast(u32, self.flags), .commit_id = @ptrCast(?*c.git_oid, self.commit_id), .attr_commit_id = @bitCast(c.git_oid, self.attr_commit_id), }; } }; /// A filter that can transform file data /// /// This represents a filter that can be used to transform or even replace file data. /// Libgit2 includes one built in filter and it is possible to write your own (see git2/sys/filter.h for information on that). /// /// The two builtin filters are: /// /// - "crlf" which uses the complex rules with the "text", "eol", and "crlf" file attributes to decide how to convert between LF /// and CRLF line endings /// - "ident" which replaces "$Id$" in a blob with "$Id: <blob OID>$" upon checkout and replaced "$Id: <anything>$" with "$Id$" on /// checkin. pub const Filter = opaque { comptime { std.testing.refAllDecls(@This()); } }; /// List of filters to be applied /// /// This represents a list of filters to be applied to a file / blob. You can build the list with one call, apply it with another, /// and dispose it with a third. In typical usage, there are not many occasions where a `FilterList` is needed directly since the /// library will generally handle conversions for you, but it can be convenient to be able to build and apply the list sometimes. pub const FilterList = opaque { /// Query the filter list to see if a given filter (by name) will run. /// The built-in filters "crlf" and "ident" can be queried, otherwise this is the name of the filter specified by the filter /// attribute. /// /// ## Parameters /// * `name` - The name of the filter to query pub fn contains(self: *FilterList, name: [:0]const u8) bool { log.debug("FilterList.contains called, name={s}", .{name}); const ret = c.git_filter_list_contains(@ptrCast(*c.git_filter_list, self), name.ptr) != 0; log.debug("filter list contains filter: {}", .{ret}); return ret; } /// Apply a filter list to the contents of a file on disk /// /// ## Parameters /// * `repo` - the repository in which to perform the filtering /// * `path` - the path of the file to filter, a relative path will be taken as relative to the workdir pub fn applyToFile(self: *FilterList, repo: *git.Repository, path: [:0]const u8) !git.Buf { log.debug("FilterList.applyToFile called, repo={*}, path={s}", .{ repo, path }); var ret: git.Buf = .{}; try internal.wrapCall("git_filter_list_apply_to_file", .{ @ptrCast(*c.git_buf, &ret), @ptrCast(*c.git_filter_list, self), @ptrCast(*c.git_repository, repo), path.ptr, }); log.debug("result: {s}", .{ret.toSlice()}); return ret; } /// Apply a filter list to the contents of a blob /// /// ## Parameters /// * `blob` - the blob to filter pub fn applyToBlob(self: *FilterList, blob: *git.Blob) !git.Buf { log.debug("FilterList.applyToBlob called, blob={*}", .{blob}); var ret: git.Buf = .{}; try internal.wrapCall("git_filter_list_apply_to_blob", .{ @ptrCast(*c.git_buf, &ret), @ptrCast(*c.git_filter_list, self), @ptrCast(*c.git_blob, blob), }); log.debug("result: {s}", .{ret.toSlice()}); return ret; } /// Apply a filter list to a file as a stream /// /// ## Parameters /// * `repo` - the repository in which to perform the filtering /// * `path` - the path of the file to filter, a relative path will be taken as relative to the workdir /// * `target` - the stream into which the data will be written pub fn applyToFileToStream( self: *FilterList, repo: *git.Repository, path: [:0]const u8, target: *git.WriteStream, ) !void { log.debug("FilterList.applyToFileToStream called, repo={*}, path={s}, target={*}", .{ repo, path, target }); try internal.wrapCall("git_filter_list_stream_file", .{ @ptrCast(*c.git_filter_list, self), @ptrCast(*c.git_repository, repo), path.ptr, @ptrCast(*c.git_writestream, target), }); log.debug("successfully filtered file to stream", .{}); } /// Apply a filter list to a blob as a stream /// /// ## Parameters /// * `blob` - the blob to filter /// * `target` - the stream into which the data will be written pub fn applyToBlobToStream(self: *FilterList, blob: *git.Blob, target: *git.WriteStream) !void { log.debug("FilterList.applyToBlobToStream called, blob={*}, target={*}", .{ blob, target }); try internal.wrapCall("git_filter_list_stream_blob", .{ @ptrCast(*c.git_filter_list, self), @ptrCast(*c.git_blob, blob), @ptrCast(*c.git_writestream, target), }); log.debug("successfully filtered blob to stream", .{}); } pub fn deinit(self: *FilterList) void { log.debug("FilterList.deinit called", .{}); c.git_filter_list_free(@ptrCast(*c.git_filter_list, self)); log.debug("filter list freed successfully", .{}); } /// Apply filter list to a data buffer. /// /// ## Parameters /// * `name` - Buffer containing the data to filter pub fn applyToBuffer(self: *FilterList, in: [:0]const u8) !git.Buf { log.debug("FilterList.applyToBuffer called, in={s}", .{in}); var ret: git.Buf = .{}; try internal.wrapCall("git_filter_list_apply_to_buffer", .{ @ptrCast(*c.git_buf, &ret), @ptrCast(*c.git_filter_list, self), in.ptr, in.len, }); log.debug("result: {s}", .{ret.toSlice()}); return ret; } /// Apply a filter list to an arbitrary buffer as a stream /// /// ## Parameters /// * `buffer` - the buffer to filter /// * `target` - the stream into which the data will be written pub fn applyToBufferToStream(self: *FilterList, buffer: [:0]const u8, target: *git.WriteStream) !void { log.debug("FilterList.applyToBufferToStream called, buffer={s}, target={*}", .{ buffer, target }); try internal.wrapCall("git_filter_list_stream_buffer", .{ @ptrCast(*c.git_filter_list, self), buffer.ptr, buffer.len, @ptrCast(*c.git_writestream, target), }); log.debug("successfully filtered buffer to stream", .{}); } comptime { std.testing.refAllDecls(@This()); } }; comptime { std.testing.refAllDecls(@This()); }
src/filter.zig
const std = @import("std"); const expect = std.testing.expect; const print = std.debug.print; const fmt = std.fmt; const Allocator = std.mem.Allocator; const ArrayList = std.ArrayList; const GeneralPurposeAllocator = std.heap.GeneralPurposeAllocator; const Input = @import("input.zig"); pub fn main() !void { var gpa = GeneralPurposeAllocator(.{}){}; defer { const leaked = gpa.deinit(); if (leaked) expect(false) catch @panic("TEST FAIL"); } const allocator = &gpa.allocator; // TODO: read input from _inputs/*.txt //std.log.info("Day 3 (Part 1): {}", .{try day3A(allocator, &Input.input)}); //std.log.info("Day 3 (Part 2): {}", .{try day3B(allocator, &Input.input, 12)}); } const Day3Mode = enum { min, max, pub fn isMin(self: Day3Mode) bool { return self == Day3Mode.min; } pub fn isMax(self: Day3Mode) bool { return self == Day3Mode.max; } }; fn day3A(allocator: *Allocator, input: []const []const u8) !u32 { var numbers = ArrayList([]const u8).init(allocator); defer numbers.deinit(); try numbers.appendSlice(input); const max_len = input[0].len; var gamma_list = ArrayList(u8).init(allocator); defer gamma_list.deinit(); var epsilon_list = ArrayList(u8).init(allocator); defer epsilon_list.deinit(); var zero_list = ArrayList([]const u8).init(allocator); defer zero_list.deinit(); var one_list = ArrayList([]const u8).init(allocator); defer one_list.deinit(); var index: u32 = 0; while (index < max_len) : (index += 1) { defer zero_list.clearAndFree(); defer one_list.clearAndFree(); for (numbers.items) |str, _| { const number = str[index]; if (number == '0') try zero_list.append(str); if (number == '1') try one_list.append(str); } try gamma_list.append(if (zero_list.items.len > one_list.items.len) '0' else '1'); } for (gamma_list.items) |num, _| { if (num == '0') try epsilon_list.append('1'); if (num == '1') try epsilon_list.append('0'); } var gamma = try fmt.parseInt(u32, gamma_list.items, 2); var epsilon = try fmt.parseInt(u32, epsilon_list.items, 2); return gamma * epsilon; } test "Day 3a" { const results = try day3A(std.testing.allocator, &Input.test_input); try expect(results == 198); } fn day3Helper1(allocator: *Allocator, list_ptr: *ArrayList([]const u8), index: u32, mode: Day3Mode) !void { var zero_list = ArrayList([]const u8).init(allocator); defer zero_list.deinit(); var one_list = ArrayList([]const u8).init(allocator); defer one_list.deinit(); var list = list_ptr.*; print("list:", .{}); for (list.items) |str, _| { const number = str[index]; if (number == '0') try zero_list.append(str); if (number == '1') try one_list.append(str); print("{s},", .{str}); } print("\n", .{}); print("index:{}->\n", .{index}); for (zero_list.items) |item, _| { print("{s},", .{item}); } print("\n\n", .{}); for (one_list.items) |item, _| { print("{s},", .{item}); } print("\n\n\n", .{}); if (mode.isMax()) { if (zero_list.items.len > one_list.items.len) { var x = zero_list.toOwnedSlice(); list.clearAndFree(); try list.appendSlice(x); //try list.replaceRange(0, list.items.len, zero_list.items); //try list.resize(zero_list.items.len); } else { //try list.replaceRange(0, list.items.len, one_list.items); //try list.resize(one_list.items.len); var x = one_list.toOwnedSlice(); list.clearAndFree(); try list.appendSlice(x); } } if (mode.isMin()) { if (one_list.items.len < zero_list.items.len) { //try list.replaceRange(0, list.items.len, one_list.items); //try list.resize(one_list.items.len); var x = one_list.toOwnedSlice(); list.clearAndFree(); try list.appendSlice(x); } else { //try list.replaceRange(0, list.items.len, zero_list.items); //try list.resize(zero_list.items.len); var x = zero_list.toOwnedSlice(); list.clearAndFree(); try list.appendSlice(x); } } } fn day3B(allocator: *Allocator, input: []const []const u8) !u32 { const max_len = input[0].len; var oxygen_gen = ArrayList([]const u8).init(allocator); var co2_scrubber = ArrayList([]const u8).init(allocator); defer oxygen_gen.deinit(); defer co2_scrubber.deinit(); try oxygen_gen.appendSlice(input); try co2_scrubber.appendSlice(input); var index: u32 = 0; // TODO try day3Helper1(allocator, &oxygen_gen, index, .max); index += 1; try day3Helper1(allocator, &oxygen_gen, index, .max); // calculate oxygen generator rating //while (index < max_len) : (index += 1) { //if (oxygen_gen.items.len == 1) break; //try day3Helper1(allocator, &oxygen_gen, index, .max); //for (oxygen_gen.items) |item, _| { //print("{s},", .{item}); //} //print("\n", .{}); //} //index = 0; // calculate co2 scrubber rating //while (index < max_len) : (index += 1) { //if (co2_scrubber.len == 1) break; //co2_scrubber = try day3Helper1(allocator, co2_scrubber, index, .min); //} var x = try fmt.parseInt(u32, oxygen_gen.items[0], 2); //var y = try fmt.parseInt(u32, co2_scrubber[0], 2); return x; //return x * y; } // TODO: tests are crashing, but not sure why... test "Day 3b" { const results = try day3B(std.testing.allocator, &Input.test_input); print("\n\n{}\n", .{results}); try expect(results == 23); //try expect(results == 230); }
2021/zig/src/day3/main.zig
const std = @import("std"); const math = std.math; const fmt = std.fmt; const HashMap = std.hash_map.HashMap; const mem = std.mem; const hashes = @import("./hashes.zig"); const assertOrPanic = std.debug.assertOrPanic; const debugAllocator = std.debug.global_allocator; pub const Resp3Type = packed enum(u8) { pub Array = '*', pub BlobString = '$', pub SimpleString = '+', pub SimpleError = '-', pub Number = ':', pub Null = '_', // pub Double = ',', pub Boolean = '#', pub BlobError = '!', pub VerbatimString = '=', pub Map = '%', pub Set = '~', // pub Attribute = '|', // pub Push = '>', // pub Hello = 'H', // pub BigNumber = '(' }; pub const Error = struct { pub Code: []u8, pub Message: []u8, pub fn equals(a: Error, b: Error) bool { return mem.eql(u8, a.Code, b.Code) and mem.eql(u8, a.Message, b.Message); } pub fn hash(self: Error) u32 { const mixed = hashes.mix(hashes.hashString(self.Code), hashes.hashString(self.Message)); return hashes.finalize(mixed); } }; test "Error::equals for two of the same errors" { const err_1 = Error { .Code = &"ERR", .Message = &"this is the error description", }; const err_2 = Error { .Code = &"ERR", .Message = &"this is the error description", }; assertOrPanic(err_1.equals(err_2)); } test "Error::equals for two different errors" { const err_1 = Error { .Code = &"ERR", .Message = &"this is the error description", }; const err_2 = Error { .Code = &"ERR", .Message = &"this is not the error description", }; assertOrPanic(!err_1.equals(err_2)); } pub const VerbatimStringType = packed enum(u1) { pub Text, pub Markdown, pub fn to_string(self: VerbatimStringType) [3]u8 { return switch (self) { VerbatimStringType.Text => "txt", VerbatimStringType.Markdown => "mkd", }; } }; pub const VerbatimString = struct { pub Type: VerbatimStringType, pub Value: []u8, pub fn equals(a: VerbatimString, b: VerbatimString) bool { return (a.Type == b.Type) and mem.eql(u8, a.Value, b.Value); } pub fn hash(self: VerbatimString) u32 { const mixed = hashes.mix(@enumToInt(self.Type), hashes.hashString(self.Value)); return hashes.finalize(mixed); } }; test "VerbatimString::equals for two of the same verbatim strings" { const verbatim_string_1 = VerbatimString { .Type = VerbatimStringType.Text, .Value = &"Some string", }; const verbatim_string_2 = VerbatimString { .Type = VerbatimStringType.Text, .Value = &"Some string", }; assertOrPanic(verbatim_string_1.equals(verbatim_string_2)); } test "VerbatimString::equals for two different verbatim strings" { const verbatim_string_1 = VerbatimString { .Type = VerbatimStringType.Text, .Value = &"Some string", }; const verbatim_string_2 = VerbatimString { .Type = VerbatimStringType.Text, .Value = &"Some string 2", }; assertOrPanic(!verbatim_string_1.equals(verbatim_string_2)); } const Resp3ValueHashMap = HashMap(Resp3Value, Resp3Value, Resp3Value.hash, Resp3Value.equals); pub const Resp3Value = union(Resp3Type) { pub Array: []Resp3Value, pub BlobString: []u8, pub SimpleString: []u8, pub SimpleError: Error, pub Number: i64, pub Null: void, // TODO: Double pub Boolean: bool, pub BlobError: Error, pub VerbatimString: VerbatimString, pub Map: Resp3ValueHashMap, pub Set: []Resp3Value, // TODO: proper set type // TODO: init/deinit to deinit Resp3ValueHashMap? pub fn encodedLength(self: Resp3Value) usize { return switch (self) { Resp3Value.Array => |arr| blk: { // * (1) + array_len_len + \r (1) + \n (1) + elements_len break :blk lenOfSliceOfValues(arr); }, Resp3Value.BlobString => |str| blk: { const str_len = str.len; const length_len = get_string_length_for_int(str_len); // $ (1) + \r (1) + \n (1) + str_len + \r (1) + \n (1) break :blk @intCast(usize, 5 + str_len + length_len); }, Resp3Value.SimpleString => |str| blk: { const str_len = str.len; // + (1) + str_len + \r (1) + \n (1) break :blk @intCast(usize, 3 + str.len); }, Resp3Value.SimpleError => |err| blk: { const err_code_len = err.Code.len; const err_msg_len = err.Message.len; // - (1) + err_code_len + ' ' (1) + \r (1) + \n (1) break :blk @intCast(usize, 4 + err_code_len + err_msg_len); }, Resp3Value.Number => |num| blk: { const num_len = get_string_length_for_int(num); // : (1) + num_len + \r (1) + \n (1) break :blk @intCast(usize, 3 + num_len); }, Resp3Value.Null => @intCast(usize, 3), Resp3Value.Boolean => @intCast(usize, 4), Resp3Value.BlobError => |err| blk: { const err_code_len = err.Code.len; const err_msg_len = err.Message.len; const length_len = get_string_length_for_int(err_code_len + err_msg_len); // ! (1) + length_len + \r (1) + \n (1) + err_code_len + ' ' (1) + err_msg_len + \r (1) + \n (1) break :blk @intCast(usize, 6 + length_len + err_code_len + err_msg_len); }, Resp3Value.VerbatimString => |str| blk: { const str_len = str.Value.len; // type (3) + : (1) + str_len const total_str_len = str_len + 4; const length_len = get_string_length_for_int(total_str_len); // = (1) + length_len + \r (1) + \n (1) + total_str_len + \r (1) + \n (1) break :blk @intCast(usize, 5 + length_len + total_str_len); }, Resp3Value.Map => |map| blk: { break :blk lenOfMapOfValues(map); }, Resp3Value.Set => |set| blk: { // * (1) + array_len_len + \r (1) + \n (1) + elements_len break :blk lenOfSliceOfValues(set); }, }; } fn get_string_length_for_int(val: var) usize { return if (val == 0) 1 else (@intCast(usize, math.log10(val) + 1)); } fn lenOfSliceOfValues(values: []Resp3Value) usize { const array_len_len = get_string_length_for_int(values.len); var elements_len: usize = 0; for (values) |entry| { elements_len += entry.encodedLength(); } // start_char (1) + array_len_len + \r (1) + \n (1) + elements_len return 3 + array_len_len + elements_len; } fn lenOfMapOfValues(values: Resp3ValueHashMap) usize { const map_len_len = get_string_length_for_int(values.count()); var elements_len: usize = 0; var it = values.iterator(); while (it.next()) |entry| { elements_len += entry.key.encodedLength(); elements_len += entry.value.encodedLength(); } // start_char(1) + map_len_len + \r (1) + \n (1) + elements_len return 3 + map_len_len + elements_len; } pub fn equals(a: Resp3Value, b: Resp3Value) bool { if (Resp3Type(a) != Resp3Type(b)) { return false; } return switch (a) { Resp3Value.Array => |a_arr| blk: { const b_arr = b.Array; if (a_arr.len != b_arr.len) { break :blk false; } var i: usize = 0; while (i < a_arr.len) { const a_entry = a_arr[i]; const b_entry = b_arr[i]; if (!(a_entry.equals(b_entry))) { break :blk false; } i += 1; } break :blk true; }, Resp3Value.BlobString => |a_str| blk: { const b_str = b.BlobString; break :blk mem.eql(u8, a_str, b_str); }, Resp3Value.SimpleString => |a_str| blk: { const b_str = b.SimpleString; break :blk mem.eql(u8, a_str, b_str); }, Resp3Type.SimpleError => |a_err| blk: { const b_err = b.SimpleError; break :blk a_err.equals(b_err); }, Resp3Value.Number => |a_num| blk: { const b_num = b.Number; break :blk (a_num == b_num); }, Resp3Value.Null => true, Resp3Value.Boolean => |a_bool| blk: { const b_bool = b.Boolean; break :blk (a_bool == b_bool); }, Resp3Value.BlobError => |a_err| blk: { const b_err = b.BlobError; break :blk a_err.equals(b_err); }, Resp3Value.VerbatimString => |a_str| blk: { const b_str = b.VerbatimString; break :blk a_str.equals(b_str); }, Resp3Value.Map => |a_map| blk: { const b_map = b.Map; if (a_map.count() != b_map.count()) { break :blk false; } var it = a_map.iterator(); while (it.next()) |entry| { if (b_map.get(entry.key)) |b_entry| { if (!entry.value.equals(b_entry.value)) { break :blk false; } } else { break :blk false; } } break :blk true; }, Resp3Value.Set => |a_set| blk: { const b_set = b.Set; if (a_set.len != b_set.len) { break :blk false; } var i: usize = 0; while (i < a_set.len) { const a_entry = a_set[i]; const b_entry = b_set[i]; if (!(a_entry.equals(b_entry))) { break :blk false; } i += 1; } break :blk true; }, }; } pub fn hash(self: Resp3Value) u32 { var result: u32 = 0; const typeOfValue = Resp3Type(self); const typeOfValueInt = @enumToInt(typeOfValue); result = hashes.mix(result, typeOfValueInt); const child = switch (self) { Resp3Value.Array => |arr| blk: { var sum: u32 = 0; for (arr) |item| { sum = hashes.mix(sum, item.hash()); } break :blk hashes.finalize(sum); }, Resp3Value.BlobString => |str| blk: { break :blk hashes.hashString(str); }, Resp3Value.SimpleString => |str| blk: { break :blk hashes.hashString(str); }, Resp3Type.SimpleError => |err| blk: { break :blk err.hash(); }, Resp3Value.Number => |num| blk: { break :blk hashes.hashInteger64(num); }, Resp3Value.Null => 0, Resp3Value.Boolean => |bool_val| blk: { break :blk @boolToInt(bool_val); }, Resp3Value.BlobError => |err| blk: { break :blk err.hash(); }, Resp3Value.VerbatimString => |str| blk: { break :blk str.hash(); }, Resp3Value.Map => |values| blk: { var sum: u32 = 0; var it = values.iterator(); while (it.next()) |entry| { sum = hashes.mix(sum, entry.key.hash()); sum = hashes.mix(sum, entry.value.hash()); } break :blk hashes.finalize(sum); }, Resp3Value.Set => |set| blk: { var sum: u32 = 0; for (set) |item| { sum = hashes.mix(sum, item.hash()); } break :blk hashes.finalize(sum); }, }; result = hashes.mix(result, child); return hashes.finalize(result); } }; test "Resp3Value::encodedLength for BlobString" { const val = Resp3Value { .BlobString = &"helloworld" }; const expected = "$11\r\nhelloworld\r\n"; assertOrPanic(val.encodedLength() == expected.len); } test "Resp3Value::encodedLength for SimpleString" { const val = Resp3Value { .SimpleString = &"hello world" }; const expected = "+hello world\r\n"; assertOrPanic(val.encodedLength() == expected.len); } test "Resp3Value::encodedLength for SimpleError" { const err = Error { .Code = &"ERR", .Message = &"this is the error description", }; const val = Resp3Value { .SimpleError = err }; const expected = "-ERR this is the error description\r\n"; assertOrPanic(val.encodedLength() == expected.len); } test "Resp3Value::encodedLength for Number" { const val = Resp3Value { .Number = 1234 }; const expected = ":1234\r\n"; assertOrPanic(val.encodedLength() == expected.len); } test "Resp3Value::encodedLength for Null" { const val = Resp3Value { .Null = undefined }; const expected = "_\r\n"; assertOrPanic(val.encodedLength() == expected.len); } test "Resp3Value::encodedLength for Boolean" { const val = Resp3Value { .Boolean = true }; const expected = "#t\r\n"; assertOrPanic(val.encodedLength() == expected.len); } test "Resp3Value::encodedLength for BlobError" { const err = Error { .Code = &"SYNTAX", .Message = &"invalid syntax", }; const val = Resp3Value { .BlobError = err }; const expected = "!21\r\nSYNTAX invalid syntax\r\n"; assertOrPanic(val.encodedLength() == expected.len); } test "Resp3Value::encodedLength for VerbatimString" { const verbatim_string = VerbatimString { .Type = VerbatimStringType.Text, .Value = &"Some string", }; const val = Resp3Value { .VerbatimString = verbatim_string }; const expected = "=15\r\ntxt:Some string\r\n"; assertOrPanic(val.encodedLength() == expected.len); } test "Resp3Value::encodedLength for Array of Number" { const num_1 = Resp3Value { .Number = 1 }; const num_2 = Resp3Value { .Number = 2 }; const num_3 = Resp3Value { .Number = 3 }; var arr = []Resp3Value{ num_1, num_2, num_3, }; const val = Resp3Value { .Array = &arr }; const expected = "*3\r\n:1\r\n:2\r\n:3\r\n"; assertOrPanic(val.encodedLength() == expected.len); } test "Resp3Value::encodedLength for Map of [sring, num]" { var map = Resp3ValueHashMap.init(debugAllocator); defer map.deinit(); const key1 = Resp3Value { .SimpleString = &"first" }; const value1 = Resp3Value { .Number = 1 }; assertOrPanic((try map.put(key1, value1)) == null); const key2 = Resp3Value { .SimpleString = &"second" }; const value2 = Resp3Value { .Number = 2 }; assertOrPanic((try map.put(key2, value2)) == null); const val = Resp3Value { .Map = map }; const expected = "%2\r\n+first\r\n:1\r\n+second\r\n:2\r\n"; assertOrPanic(val.encodedLength() == expected.len); } test "Resp3Value::encodedLength for Set of mixed types" { const orange = Resp3Value { .SimpleString = &"orange" }; const apple = Resp3Value { .SimpleString = &"apple" }; const true_val = Resp3Value { .Boolean = true }; const number_100 = Resp3Value { .Number = 100 }; const number_999 = Resp3Value { .Number = 999 }; var set = []Resp3Value{ orange, apple, true_val, number_100, number_999, }; const val = Resp3Value { .Set = &set }; const expected = "~5\r\n+orange\r\n+apple\r\n#t\r\n:100\r\n:999\r\n"; assertOrPanic(val.encodedLength() == expected.len); } test "Resp3Value::equals for two different types" { const val_1 = Resp3Value { .Boolean = true }; const val_2 = Resp3Value { .Number = 1 }; assertOrPanic(val_1.equals(val_2) == false); } test "Resp3Value::equals for two of the same types and values" { const val_1 = Resp3Value { .Boolean = true }; const val_2 = Resp3Value { .Boolean = true }; assertOrPanic(val_1.equals(val_2) == true); } test "Resp3Value::equals for two of the same types but different values" { const val_1 = Resp3Value { .Boolean = true }; const val_2 = Resp3Value { .Boolean = false }; assertOrPanic(val_1.equals(val_2) == false); } test "Resp3Value::equals for two maps that are equal" { var map = Resp3ValueHashMap.init(debugAllocator); defer map.deinit(); const key1 = Resp3Value { .SimpleString = &"first" }; const value1 = Resp3Value { .Number = 1 }; assertOrPanic((try map.put(key1, value1)) == null); const key2 = Resp3Value { .SimpleString = &"second" }; const value2 = Resp3Value { .Number = 2 }; assertOrPanic((try map.put(key2, value2)) == null); const val = Resp3Value { .Map = map }; const val2 = Resp3Value { .Map = map }; assertOrPanic(val.equals(val2)); }
src/main.zig
const std = @import("std"); usingnamespace @import("coro.zig"); pub fn StackfullCoroutine(comptime T: type) type { return struct { const Self = @This(); pub const UserFunctionType = fn () void; // members coro: *mco_coro, // functions pub fn init(func: UserFunctionType, user_data: *T, allocator: *std.mem.Allocator) !Self { var desc = mco_desc_init(Self.wrapper, 1024 * 1024 * 10); desc.malloc_cb = customAlloc; desc.free_cb = customFree; desc.allocator_data = @ptrCast(*c_void, allocator); desc.user_data = user_data; var coro: *mco_coro = undefined; const result = mco_create(&coro, &desc); if (result != .Success) { return error.FailedToCreateCoroutine; } var fiber = Self{ .coro = coro, }; errdefer fiber.deinit(); try fiber.push(UserFunctionType, func); return fiber; } pub fn deinit(self: *Self) void { _ = mco_destroy(self.coro); } pub fn call(self: *Self) !mco_state { if (mco_resume(self.coro) != .Success) { return error.FailedToResumeCoroutine; } const state = mco_status(self.coro); if (state == .Dead and mco_get_bytes_stored(self.coro) > 0) blk: { const err = self.pop(anyerror) catch |err| { if (err != error.FailedToPopFromCoroutine) { return err; } break :blk; }; return err; } return state; } pub fn yield() !void { if (mco_yield(mco_running()) != .Success) { return error.FailedToYieldCoroutine; } } pub fn getUserData(self: *Self) ?*T { if (mco_get_user_data(mco_running())) |user_data| { return @ptrCast(*T, @alignCast(@alignOf(T), user_data)); } else { return null; } } pub fn current() Self { return Self{ .coro = mco_running() }; } pub fn push(self: Self, comptime V: type, value: V) !void { if (mco_push(self.coro, @ptrCast(*const c_void, &value), @sizeOf(V)) != .Success) { return error.FailedToPushToCoroutine; } } pub fn pop(self: Self, comptime V: type) !V { var result: V = undefined; if (mco_pop(self.coro, &result, @sizeOf(V)) != .Success) { return error.FailedToPopFromCoroutine; } return result; } fn wrapper(coro: *mco_coro) callconv(.C) void { var fiber = Self{ .coro = coro }; var func = fiber.pop(UserFunctionType) catch |err| { std.log.err("Failed to get user function from coroutine data: {any}", .{err}); return; }; func(); } fn customAlloc(size: usize, allocator_data: ?*c_void) callconv(.C) ?*c_void { var allocator = @ptrCast(*std.mem.Allocator, @alignCast(@alignOf(std.mem.Allocator), allocator_data.?)); var mem = allocator.allocAdvanced(u8, @alignOf(usize), size + @sizeOf(usize), .exact) catch { std.log.err("myMalloc failed", .{}); return null; }; var sizePtr = @ptrCast(*usize, mem.ptr); sizePtr.* = size; return mem.ptr + @sizeOf(usize); } fn customFree(ptr: ?*c_void, allocator_data: ?*c_void) callconv(.C) void { if (ptr == null) { return; } var allocator = @ptrCast(*std.mem.Allocator, @alignCast(@alignOf(std.mem.Allocator), allocator_data.?)); const sizePtr = @intToPtr(*usize, @ptrToInt(ptr.?) - @sizeOf(usize)); const size = sizePtr.* + @sizeOf(usize); allocator.free(@ptrCast([*]const u8, sizePtr)[0..size]); } }; }
src/stackfull_coroutine.zig
const __fixdfti = @import("fixdfti.zig").__fixdfti; const std = @import("std"); const math = std.math; const testing = std.testing; const warn = std.debug.warn; fn test__fixdfti(a: f64, expected: i128) void { const x = __fixdfti(a); //warn("a={}:{x} x={}:{x} expected={}:{x}:u64({x})\n", a, @bitCast(u64, a), x, x, expected, expected, @bitCast(u128, expected)); testing.expect(x == expected); } test "fixdfti" { //warn("\n"); test__fixdfti(-math.f64_max, math.minInt(i128)); test__fixdfti(-0x1.FFFFFFFFFFFFFp+1023, math.minInt(i128)); test__fixdfti(-0x1.FFFFFFFFFFFFFp+1023, -0x80000000000000000000000000000000); test__fixdfti(-0x1.0000000000000p+127, -0x80000000000000000000000000000000); test__fixdfti(-0x1.FFFFFFFFFFFFFp+126, -0x7FFFFFFFFFFFFC000000000000000000); test__fixdfti(-0x1.FFFFFFFFFFFFEp+126, -0x7FFFFFFFFFFFF8000000000000000000); test__fixdfti(-0x1.0000000000001p+63, -0x8000000000000800); test__fixdfti(-0x1.0000000000000p+63, -0x8000000000000000); test__fixdfti(-0x1.FFFFFFFFFFFFFp+62, -0x7FFFFFFFFFFFFC00); test__fixdfti(-0x1.FFFFFFFFFFFFEp+62, -0x7FFFFFFFFFFFF800); test__fixdfti(-0x1.FFFFFEp+62, -0x7fffff8000000000); test__fixdfti(-0x1.FFFFFCp+62, -0x7fffff0000000000); test__fixdfti(-2.01, -2); test__fixdfti(-2.0, -2); test__fixdfti(-1.99, -1); test__fixdfti(-1.0, -1); test__fixdfti(-0.99, 0); test__fixdfti(-0.5, 0); test__fixdfti(-math.f64_min, 0); test__fixdfti(0.0, 0); test__fixdfti(math.f64_min, 0); test__fixdfti(0.5, 0); test__fixdfti(0.99, 0); test__fixdfti(1.0, 1); test__fixdfti(1.5, 1); test__fixdfti(1.99, 1); test__fixdfti(2.0, 2); test__fixdfti(2.01, 2); test__fixdfti(0x1.FFFFFCp+62, 0x7FFFFF0000000000); test__fixdfti(0x1.FFFFFEp+62, 0x7FFFFF8000000000); test__fixdfti(0x1.FFFFFFFFFFFFEp+62, 0x7FFFFFFFFFFFF800); test__fixdfti(0x1.FFFFFFFFFFFFFp+62, 0x7FFFFFFFFFFFFC00); test__fixdfti(0x1.0000000000000p+63, 0x8000000000000000); test__fixdfti(0x1.0000000000001p+63, 0x8000000000000800); test__fixdfti(0x1.FFFFFFFFFFFFEp+126, 0x7FFFFFFFFFFFF8000000000000000000); test__fixdfti(0x1.FFFFFFFFFFFFFp+126, 0x7FFFFFFFFFFFFC000000000000000000); test__fixdfti(0x1.0000000000000p+127, 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF); test__fixdfti(0x1.FFFFFFFFFFFFFp+1023, 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF); test__fixdfti(0x1.FFFFFFFFFFFFFp+1023, math.maxInt(i128)); test__fixdfti(math.f64_max, math.maxInt(i128)); }
lib/std/special/compiler_rt/fixdfti_test.zig
const page_allocator = std.heap.page_allocator; const test_allocator = std.testing.allocator; const std = @import("std"); const CFO = @import("./CFO.zig"); const parse = @import("./parse.zig"); const FLIR = @import("./Old_FLIR.zig"); const builtin = @import("builtin"); const s2 = builtin.zig_backend != .stage1; pub fn main2() !void { // wasteful but (doesn't) works :D // const allocator = page_allocator; // var cfo = CFO.init(allocator) catch unreachable; // const size = 1024 * 16; var arr1 = try page_allocator.alloc(f64, size); var arr2 = try page_allocator.alloc(f64, size); const IPReg = CFO.IPReg; const idx: IPReg = .rcx; const arg1: IPReg = .rdi; const arg2: IPReg = .rsi; const arg3: IPReg = .rdx; const v0: u4 = 0; arr1[5] = 7.0; arr2[5] = 8.5; var cfo = try CFO.init(page_allocator); var pos = cfo.get_target(); if (false) { try cfo.enter(); try cfo.arit(.xor, idx, idx); const loop = cfo.get_target(); try cfo.vmovurm(.sd, v0, CFO.qi(arg1, idx)); try cfo.vmathfrm(.add, .sd, v0, v0, CFO.qi(arg2, idx)); try cfo.vmovumr(.sd, CFO.qi(arg1, idx), v0); try cfo.aritri(.add, idx, 1); try cfo.arit(.cmp, idx, arg3); try cfo.jbck(.l, loop); try cfo.mov(.rax, idx); try cfo.leave(); try cfo.ret(); } else { var flir = try FLIR.init_stage2(0, page_allocator); try flir.loop_start(); //_ = try parse.parse(&flir, "xi = xi + yi;"); const Inst = FLIR.Inst; const l1 = try flir.put(Inst{ .tag = .load, .opspec = 0x10, .op1 = 0 }); const l2 = try flir.put(Inst{ .tag = .load, .opspec = 0x11, .op1 = 0 }); const addi: FLIR.Inst = Inst{ .tag = .vmath, .opspec = CFO.VMathOp.add.off(), .op1 = l1, .op2 = l2 }; const add = try flir.put(addi); var inst2: FLIR.Inst = .{ .tag = .store, .opspec = 0x10, .op1 = add, .op2 = 0 }; _ = try flir.put(inst2); try flir.loop_end(); flir.live(true); _ = try flir.scanreg(true); // defer flir.deinit(); flir.debug_print(false); try cfo.enter(); _ = try flir.codegen(&cfo, false); try cfo.leave(); try cfo.ret(); } try cfo.finalize(); const runcount: usize = 137; // <NAME> const ptrtype = if (s2) *const fn ([*]f64, [*]f64, usize) callconv(.C) usize else fn ([*]f64, [*]f64, usize) callconv(.C) usize; var fun = cfo.get_ptr(pos, ptrtype); var ret = fun(arr1.ptr, arr2.ptr, runcount); std.os.exit(@floatToInt(u8, 2.0 * arr1[5])); std.os.exit(@truncate(u8, ret)); } pub fn main() void { main2() catch unreachable; }
src/stage2_main.zig
const std = @import("std"); const Location = @This(); const VirtualFile = @import("virtual_file.zig"); line_number: i32, column_number: i32, filename: ?Filename, pub const Filename = union(enum) { string: []const u8, virtual_file: *VirtualFile, pub fn format(self: Filename, comptime _: []const u8, _: std.fmt.FormatOptions, writer: anytype) !void { switch (self) { .string => |string| { try writer.print("{s}", .{string}); }, .virtual_file => |virtual_file| { try writer.print("{}", .{virtual_file}); }, } } }; pub fn init(filename: ?Filename, line_number: i32, column_number: i32) Location { return .{ .filename = filename, .line_number = line_number, .column_number = column_number, }; } /// Returns the directory name of this location's filename. If /// the filename is a VirtualFile, this is invoked on its expanded /// location. pub fn dirname(self: Location) ?[]const u8 { if (self.original_filename()) |filename| { return std.fs.path.dirname(filename); } else { return null; } } /// Returns the Location whose filename is a string, not a VirtualFile, /// traversing virtual file expanded locations. pub fn expanded_location(self: Location) ?Location { if (self.filename) |filename| { switch (filename) { .string => { return self; }, .virtual_file => |virtual_file| { if (virtual_file.expanded_location) |location| { return location.expanded_location(); } }, } } return null; } /// Returns the Location whose filename is a string, not a VirtualFile, /// traversing virtual file expanded locations leading to the original user source code pub fn macro_location(self: Location) ?Location { if (self.filename) |filename| { switch (filename) { .string => { return self; }, .virtual_file => |virtual_file| { if (virtual_file.macro_location) |location| { return location.macro_location(); } }, } } return null; } /// Returns the filename of the `expanded_location` pub fn original_filename(self: Location) ?[]const u8 { if (self.expanded_location()) |location| { if (location.filename) |filename| { switch (filename) { .string => |string| return string, .virtual_file => {}, } } } return null; } pub fn isBetween(self: Location, min: ?Location, max: ?Location) bool { if (min) |minimum| { if (max) |maximum| { return minimum.order(self).compare(.lte) and self.order(maximum).compare(.lte); } } return false; } pub fn format(self: Location, comptime _: []const u8, _: std.fmt.FormatOptions, writer: anytype) !void { try writer.print("{}:{}:{}", .{self.filename, self.line_number, self.column_number}); } pub fn order(a: Location, b: Location) std.math.Order { // TODO: check if filename is the same? if (a.line_number == b.line_number) { return std.math.order(a.column_number, b.column_number); } else { return std.math.order(a.line_number, b.line_number); } } const print = std.debug.print; const c_allocator = std.heap.c_allocator; const ast = @import("ast.zig"); const utils = @import("utils.zig"); const inspect = utils.inspect; const pp = utils.pp; const p = utils.p; const xprint = utils.xprint; pub fn main() !void { const macro1 = try ast.Macro.create(c_allocator, "foo", try c_allocator.alloc(*ast.Arg, 0), null); p(try VirtualFile.create(c_allocator, macro1, null, "bar", null)); p(Location.init(null, 0, 0)); p(Location.init(Filename { .string = "foo" }, 0, 0)); p(Location.init(Filename { .string = "foo/bar" }, 0, 0)); p(Location.init(Filename { .virtual_file = try VirtualFile.create(c_allocator, macro1, null, "bar", Location.init(Filename { .string = "fizz" }, 0, 0)) }, 0, 0)); p(Location.init(Filename { .virtual_file = try VirtualFile.create(c_allocator, macro1, null, "bar", Location.init(Filename { .string = "fizz/buzz" }, 0, 0)) }, 0, 0)); p(Location.init(null, 0, 0).dirname()); p(Location.init(Filename { .string = "foo" }, 0, 0).dirname()); p(Location.init(Filename { .string = "foo/bar" }, 0, 0).dirname()); p(Location.init(Filename { .virtual_file = try VirtualFile.create(c_allocator, macro1, null, "bar", Location.init(Filename { .string = "fizz" }, 0, 0)) }, 0, 0).dirname()); p(Location.init(Filename { .virtual_file = try VirtualFile.create(c_allocator, macro1, null, "bar", Location.init(Filename { .string = "fizz/buzz" }, 0, 0)) }, 0, 0).dirname()); p(Location.init(null, 1, 1).order(Location.init(null, 1, 0))); p(Location.init(null, 1, 1).order(Location.init(null, 1, 1))); p(Location.init(null, 1, 1).order(Location.init(null, 1, 2))); p(Location.init(null, 1, 1).order(Location.init(null, 0, 1))); p(Location.init(null, 1, 1).order(Location.init(null, 1, 1))); p(Location.init(null, 1, 1).order(Location.init(null, 2, 1))); p(Location.init(null, 1, 1).isBetween(Location.init(null, 1, 0), Location.init(null, 1, 2))); p(Location.init(null, 1, 1).isBetween(Location.init(null, 0, 1), Location.init(null, 2, 1))); p(Location.init(null, 1, 1).isBetween(Location.init(null, 1, 1), Location.init(null, 1, 2))); p(Location.init(null, 1, 1).isBetween(Location.init(null, 1, 2), Location.init(null, 1, 2))); p(Location.init(null, 1, 1).isBetween(Location.init(null, 1, 1), Location.init(null, 2, 1))); p(Location.init(null, 1, 1).isBetween(Location.init(null, 2, 1), Location.init(null, 2, 1))); }
location.zig
const std = @import("std"); const c = @import("c.zig"); pub const Atlas = struct { const Self = @This(); alloc: *std.mem.Allocator, // Font atlas texture tex: []u32, tex_size: u32, // Position within the atlas texture x: u32, y: u32, max_row_height: u32, glyph_index: u32, has_advance: bool, // is the glyph advance stored in u.glyph_advance? // Conversion from codepoint to position in u.glyphs table: std.hash_map.AutoHashMapUnmanaged(u32, u32), // Freetype state ft: c.FT_Library, face: c.FT_Face, // Uniforms (synchronized with the GPU) u: c.fpAtlasUniforms, pub fn deinit(self: *Self) void { status_to_err(c.FT_Done_FreeType(self.ft)) catch |err| { std.debug.panic("Could not destroy library: {}", .{err}); }; self.alloc.free(self.tex); self.table.deinit(self.alloc); } pub fn get_glyph(self: *Self, codepoint: u32) ?u32 { if (codepoint < 127) { return codepoint; } return self.table.get(codepoint); } pub fn add_glyph(self: *Self, codepoint: u32) !u32 { // New glyphs go at the back of the glyphs table const g = self.glyph_index; try self.table.put(self.alloc, codepoint, g); self.glyph_index += 1; const char_index = c.FT_Get_Char_Index(self.face, codepoint); if (char_index == 0) { std.debug.warn("Could not get char for codepoint {x}\n", .{codepoint}); } try status_to_err(c.FT_Load_Glyph( self.face, char_index, 0, )); try status_to_err(c.FT_Render_Glyph( self.face.*.glyph, c.FT_Render_Mode.FT_RENDER_MODE_LCD, )); const glyph = self.face.*.glyph; const bmp = &(glyph.*.bitmap); { // Store the glyph advance const advance = @intCast(u32, glyph.*.advance.x >> 6); if (!self.has_advance) { self.has_advance = true; self.u.glyph_advance = advance; } else if (advance != self.u.glyph_advance) { std.debug.panic("Inconsistent glyph advance; is font not fixed-width?", .{}); } } // Calculate true width (ignoring RGB, which triples width) const bmp_width = bmp.*.width / 3; // Reset to the beginning of the line if (self.x + bmp_width >= self.tex_size) { self.y += self.max_row_height; self.x = 1; self.max_row_height = 0; } if (self.y + bmp.*.rows >= self.tex_size) { std.debug.panic("Ran out of atlas space", .{}); } else if (bmp.*.rows > self.max_row_height) { self.max_row_height = bmp.*.rows; } var row: usize = 0; const pitch: usize = @intCast(usize, bmp.*.pitch); while (row < bmp.*.rows) : (row += 1) { var col: usize = 0; while (col < bmp_width) : (col += 1) { const p: u32 = 0 | @intCast(u32, bmp.*.buffer[row * pitch + col * 3]) | (@intCast(u32, bmp.*.buffer[row * pitch + col * 3 + 1]) << 8) | (@intCast(u32, bmp.*.buffer[row * pitch + col * 3 + 2]) << 16); self.tex[self.x + col + self.tex_size * (row + self.y)] = p; } } const offset = @intCast(i32, self.face.*.size.*.metrics.descender >> 6); self.u.glyphs[g] = c.fpGlyph{ .x0 = self.x, .y0 = self.y, .width = bmp_width, .height = bmp.*.rows, .x_offset = glyph.*.bitmap_left, .y_offset = glyph.*.bitmap_top - @intCast(i32, bmp.*.rows) - offset, }; self.x += bmp_width; return g; } }; pub fn build_atlas( alloc: *std.mem.Allocator, comptime font_name: []const u8, font_size: u32, tex_size: u32, ) !Atlas { const tex = try alloc.alloc(u32, tex_size * tex_size); std.mem.set(u32, tex, 128); var out = Atlas{ .alloc = alloc, .tex = tex, .tex_size = tex_size, .x = 1, .y = 1, .glyph_index = 32, .max_row_height = 0, .has_advance = false, // Freetype handles .ft = undefined, .face = undefined, .table = std.hash_map.AutoHashMapUnmanaged(u32, u32).init(alloc), // GPU uniforms .u = undefined, }; out.u.glyph_height = font_size; try status_to_err(c.FT_Init_FreeType(&out.ft)); try status_to_err(c.FT_New_Face(out.ft, font_name.ptr, 0, &out.face)); try status_to_err(c.FT_Set_Pixel_Sizes( out.face, @intCast(c_uint, font_size), @intCast(c_uint, font_size), )); var i = out.glyph_index; while (i < 127) : (i += 1) { _ = try out.add_glyph(i); } return out; } //////////////////////////////////////////////////////////////////////////////// // TODO: generate all of this at comptime const Error = error{ // Ok = 0 CannotOpenResource, UnknownFileFormat, InvalidFileFormat, InvalidVersion, LowerModuleVersion, InvalidArgument, UnimplementedFeature, InvalidTable, InvalidOffset, ArrayTooLarge, MissingModule, MissingProperty, // glyph/character errors InvalidGlyphIndex, InvalidCharacterCode, InvalidGlyphFormat, CannotRenderGlyph, InvalidOutline, InvalidComposite, TooManyHints, InvalidPixelSize, // handle errors InvalidHandle, InvalidLibraryHandle, InvalidDriverHandle, InvalidFaceHandle, InvalidSizeHandle, InvalidSlotHandle, InvalidCharMapHandle, InvalidCacheHandle, InvalidStreamHandle, // driver errors TooManyDrivers, TooManyExtensions, // memory errors OutOfMemory, UnlistedObject, // stream errors CannotOpenStream, InvalidStreamSeek, InvalidStreamSkip, InvalidStreamRead, InvalidStreamOperation, InvalidFrameOperation, NestedFrameAccess, InvalidFrameRead, // raster errors RasterUninitialized, RasterCorrupted, RasterOverflow, RasterNegativeHeight, // cache errors TooManyCaches, // TrueType and SFNT errors InvalidOpcode, TooFewArguments, StackOverflow, CodeOverflow, BadArgument, DivideByZero, InvalidReference, DebugOpCode, ENDFInExecStream, NestedDEFS, InvalidCodeRange, ExecutionTooLong, TooManyFunctionDefs, TooManyInstructionDefs, TableMissing, HorizHeaderMissing, LocationsMissing, NameTableMissing, CMapTableMissing, HmtxTableMissing, PostTableMissing, InvalidHorizMetrics, InvalidCharMapFormat, InvalidPPem, InvalidVertMetrics, CouldNotFindContext, InvalidPostTableFormat, InvalidPostTable, DEFInGlyfBytecode, MissingBitmap, // CFF, CID, and Type 1 errors SyntaxError, StackUnderflow, Ignore, NoUnicodeGlyphName, GlyphTooBig, // BDF errors MissingStartfontField, MissingFontField, MissingSizeField, MissingFontboundingboxField, MissingCharsField, MissingStartcharField, MissingEncodingField, MissingBbxField, BbxTooBig, CorruptedFontHeader, CorruptedFontGlyphs, // This is an extra error (not from FreeType), if the int isn't known UnknownError, }; fn status_to_err(i: c_int) Error!void { switch (i) { c.FT_Err_Ok => return, c.FT_Err_Cannot_Open_Resource => return error.CannotOpenResource, c.FT_Err_Unknown_File_Format => return error.UnknownFileFormat, c.FT_Err_Invalid_File_Format => return error.InvalidFileFormat, c.FT_Err_Invalid_Version => return error.InvalidVersion, c.FT_Err_Lower_Module_Version => return error.LowerModuleVersion, c.FT_Err_Invalid_Argument => return error.InvalidArgument, c.FT_Err_Unimplemented_Feature => return error.UnimplementedFeature, c.FT_Err_Invalid_Table => return error.InvalidTable, c.FT_Err_Invalid_Offset => return error.InvalidOffset, c.FT_Err_Array_Too_Large => return error.ArrayTooLarge, c.FT_Err_Missing_Module => return error.MissingModule, c.FT_Err_Missing_Property => return error.MissingProperty, // glyph/character errors c.FT_Err_Invalid_Glyph_Index => return error.InvalidGlyphIndex, c.FT_Err_Invalid_Character_Code => return error.InvalidCharacterCode, c.FT_Err_Invalid_Glyph_Format => return error.InvalidGlyphFormat, c.FT_Err_Cannot_Render_Glyph => return error.CannotRenderGlyph, c.FT_Err_Invalid_Outline => return error.InvalidOutline, c.FT_Err_Invalid_Composite => return error.InvalidComposite, c.FT_Err_Too_Many_Hints => return error.TooManyHints, c.FT_Err_Invalid_Pixel_Size => return error.InvalidPixelSize, // handle errors c.FT_Err_Invalid_Handle => return error.InvalidHandle, c.FT_Err_Invalid_Library_Handle => return error.InvalidLibraryHandle, c.FT_Err_Invalid_Driver_Handle => return error.InvalidDriverHandle, c.FT_Err_Invalid_Face_Handle => return error.InvalidFaceHandle, c.FT_Err_Invalid_Size_Handle => return error.InvalidSizeHandle, c.FT_Err_Invalid_Slot_Handle => return error.InvalidSlotHandle, c.FT_Err_Invalid_CharMap_Handle => return error.InvalidCharMapHandle, c.FT_Err_Invalid_Cache_Handle => return error.InvalidCacheHandle, c.FT_Err_Invalid_Stream_Handle => return error.InvalidStreamHandle, // driver errors c.FT_Err_Too_Many_Drivers => return error.TooManyDrivers, c.FT_Err_Too_Many_Extensions => return error.TooManyExtensions, // memory errors c.FT_Err_Out_Of_Memory => return error.OutOfMemory, c.FT_Err_Unlisted_Object => return error.UnlistedObject, // stream errors c.FT_Err_Cannot_Open_Stream => return error.CannotOpenStream, c.FT_Err_Invalid_Stream_Seek => return error.InvalidStreamSeek, c.FT_Err_Invalid_Stream_Skip => return error.InvalidStreamSkip, c.FT_Err_Invalid_Stream_Read => return error.InvalidStreamRead, c.FT_Err_Invalid_Stream_Operation => return error.InvalidStreamOperation, c.FT_Err_Invalid_Frame_Operation => return error.InvalidFrameOperation, c.FT_Err_Nested_Frame_Access => return error.NestedFrameAccess, c.FT_Err_Invalid_Frame_Read => return error.InvalidFrameRead, // raster errors c.FT_Err_Raster_Uninitialized => return error.RasterUninitialized, c.FT_Err_Raster_Corrupted => return error.RasterCorrupted, c.FT_Err_Raster_Overflow => return error.RasterOverflow, c.FT_Err_Raster_Negative_Height => return error.RasterNegativeHeight, // cache errors c.FT_Err_Too_Many_Caches => return error.TooManyCaches, // TrueType and SFNT errors c.FT_Err_Invalid_Opcode => return error.InvalidOpcode, c.FT_Err_Too_Few_Arguments => return error.TooFewArguments, c.FT_Err_Stack_Overflow => return error.StackOverflow, c.FT_Err_Code_Overflow => return error.CodeOverflow, c.FT_Err_Bad_Argument => return error.BadArgument, c.FT_Err_Divide_By_Zero => return error.DivideByZero, c.FT_Err_Invalid_Reference => return error.InvalidReference, c.FT_Err_Debug_OpCode => return error.DebugOpCode, c.FT_Err_ENDF_In_Exec_Stream => return error.ENDFInExecStream, c.FT_Err_Nested_DEFS => return error.NestedDEFS, c.FT_Err_Invalid_CodeRange => return error.InvalidCodeRange, c.FT_Err_Execution_Too_Long => return error.ExecutionTooLong, c.FT_Err_Too_Many_Function_Defs => return error.TooManyFunctionDefs, c.FT_Err_Too_Many_Instruction_Defs => return error.TooManyInstructionDefs, c.FT_Err_Table_Missing => return error.TableMissing, c.FT_Err_Horiz_Header_Missing => return error.HorizHeaderMissing, c.FT_Err_Locations_Missing => return error.LocationsMissing, c.FT_Err_Name_Table_Missing => return error.NameTableMissing, c.FT_Err_CMap_Table_Missing => return error.CMapTableMissing, c.FT_Err_Hmtx_Table_Missing => return error.HmtxTableMissing, c.FT_Err_Post_Table_Missing => return error.PostTableMissing, c.FT_Err_Invalid_Horiz_Metrics => return error.InvalidHorizMetrics, c.FT_Err_Invalid_CharMap_Format => return error.InvalidCharMapFormat, c.FT_Err_Invalid_PPem => return error.InvalidPPem, c.FT_Err_Invalid_Vert_Metrics => return error.InvalidVertMetrics, c.FT_Err_Could_Not_Find_Context => return error.CouldNotFindContext, c.FT_Err_Invalid_Post_Table_Format => return error.InvalidPostTableFormat, c.FT_Err_Invalid_Post_Table => return error.InvalidPostTable, c.FT_Err_DEF_In_Glyf_Bytecode => return error.DEFInGlyfBytecode, c.FT_Err_Missing_Bitmap => return error.MissingBitmap, // CFF, CID, and Type 1 errors c.FT_Err_Syntax_Error => return error.SyntaxError, c.FT_Err_Stack_Underflow => return error.StackUnderflow, c.FT_Err_Ignore => return error.Ignore, c.FT_Err_No_Unicode_Glyph_Name => return error.NoUnicodeGlyphName, c.FT_Err_Glyph_Too_Big => return error.GlyphTooBig, // BDF errors c.FT_Err_Missing_Startfont_Field => return error.MissingStartfontField, c.FT_Err_Missing_Font_Field => return error.MissingFontField, c.FT_Err_Missing_Size_Field => return error.MissingSizeField, c.FT_Err_Missing_Fontboundingbox_Field => return error.MissingFontboundingboxField, c.FT_Err_Missing_Chars_Field => return error.MissingCharsField, c.FT_Err_Missing_Startchar_Field => return error.MissingStartcharField, c.FT_Err_Missing_Encoding_Field => return error.MissingEncodingField, c.FT_Err_Missing_Bbx_Field => return error.MissingBbxField, c.FT_Err_Bbx_Too_Big => return error.BbxTooBig, c.FT_Err_Corrupted_Font_Header => return error.CorruptedFontHeader, c.FT_Err_Corrupted_Font_Glyphs => return error.CorruptedFontGlyphs, else => return error.UnknownError, } }
src/ft.zig
const std = @import("std"); const assert = std.debug.assert; const log = std.log.scoped(.zig_snapshots); const mem = std.mem; const Allocator = mem.Allocator; const Svg = @import("Svg.zig"); var general_purpose_allocator = std.heap.GeneralPurposeAllocator(.{}){}; const gpa = general_purpose_allocator.allocator(); var id: usize = 0; const Snapshot = struct { const Node = struct { const Tag = enum { section_start, section_end, atom_start, atom_end, relocation, }; const Payload = struct { name: []const u8, aliases: [][]const u8, is_global: bool, target: u64, }; address: u64, tag: Tag, payload: Payload, }; timestamp: i128, nodes: []Node, }; const svg_width: usize = 600; const unit_height: usize = 20; const css_styles = @embedFile("styles.css"); const js_helpers = @embedFile("script.js"); fn usageAndExit(arg0: []const u8) noreturn { log.warn("Usage: {s} <input_json_file>", .{arg0}); std.process.exit(1); } pub fn main() !void { var arena_allocator = std.heap.ArenaAllocator.init(gpa); const arena = arena_allocator.allocator(); const args = try std.process.argsAlloc(arena); if (args.len == 1) { log.warn("not enough arguments", .{}); usageAndExit(args[0]); } if (args.len > 2) { log.warn("too many arguments", .{}); usageAndExit(args[0]); } const first_arg = args[1]; const file = try std.fs.cwd().openFile(first_arg, .{}); defer file.close(); const stat = try file.stat(); const contents = try file.readToEndAlloc(arena, stat.size); const opts = std.json.ParseOptions{ .allocator = arena, }; const snapshots = try std.json.parse([]Snapshot, &std.json.TokenStream.init(contents), opts); defer std.json.parseFree([]Snapshot, snapshots, opts); if (snapshots.len == 0) { log.warn("empty snapshots array found", .{}); return; } var svgs = std.ArrayList(Svg).init(arena); var max_height: usize = 0; var onclicks = std.StringHashMap(std.ArrayList(OnClickEvent)).init(arena); for (snapshots) |snapshot, snap_i| { var svg = Svg{ .id = try std.fmt.allocPrint(arena, "svg-{d}", .{snap_i}), .width = 600, .height = 0, }; const defs = try Svg.Element.Raw.new(arena, "defs"); try svg.children.append(arena, &defs.base); const marker = try Svg.Element.Raw.new(arena, "marker"); try marker.attrs.append(arena, "id='arrowhead'"); try marker.attrs.append(arena, "markerWidth='10'"); try marker.attrs.append(arena, "markerHeight='7'"); try marker.attrs.append(arena, "refX='0'"); try marker.attrs.append(arena, "refY='3.5'"); try marker.attrs.append(arena, "orient='auto'"); try defs.children.append(arena, &marker.base); const polygon = try Svg.Element.Raw.new(arena, "polygon"); try polygon.attrs.append(arena, "points='0 0, 10 3.5, 0 7'"); try marker.children.append(arena, &polygon.base); var parser = Parser{ .arena = arena, .nodes = snapshot.nodes }; var x: usize = 10; var y: usize = 10; var lookup = std.AutoHashMap(u64, LookupEntry).init(arena); var relocs = std.ArrayList(RelocPair).init(arena); while (try parser.parse()) |parsed_node| { try parsed_node.toSvg(arena, .{ .nodes = snapshot.nodes, .svg = &svg, .x = &x, .y = &y, .lookup = &lookup, .relocs = &relocs, .onclicks = &onclicks, }); } for (relocs.items) |rel| { const target = lookup.get(rel.target) orelse { // TODO css_classes clearly ought to be a dynamically sized array rel.label.base.css_classes = if (rel.label.base.css_classes) |css| try std.fmt.allocPrint(arena, "{s} italics-font", .{css}) else "italics-font"; rel.label.contents = "dyld bound"; continue; }; const target_el = target.el; // TODO Svg.Element.Text should be able to store and render tspan children rel.label.contents = try std.fmt.allocPrint(arena, "<tspan x='{d}' dy='{d}'>{s}</tspan><tspan x='{d}' dy='{d}'> @ {x}</tspan>", .{ rel.label.x, 0, target.name, rel.label.x, unit_height, rel.target, }); const source_el = rel.box; const x1 = source_el.x + source_el.width; const y1 = source_el.y + @divFloor(source_el.height, 2); const x2 = target_el.x + target_el.width; const y2 = target_el.y + @divFloor(target_el.height, 2); const arrow = try Svg.Element.Path.new(arena, .{ .x1 = x1, .y1 = y1, .x2 = x2, .y2 = y2, }); try rel.group.children.append(arena, &arrow.base); } max_height = std.math.max(max_height, svg.height); try svgs.append(svg); } { var it = onclicks.valueIterator(); while (it.next()) |arr| { var js = std.ArrayList(u8).init(arena); for (arr.items) |evt| { const js_func = try std.fmt.allocPrint(arena, "onClick(\"{s}\", \"{s}\", \"{s}\", {d}, {d});", .{ evt.el.base.id.?, evt.group.base.id.?, evt.svg_id, evt.x, evt.y, }); try js.appendSlice(js_func); } const final = try std.fmt.allocPrint(arena, "(function() {{ {s} }})();", .{js.items}); for (arr.items) |evt| { evt.el.base.onclick = final; } } } const out_file = try std.fs.cwd().createFile("snapshots.html", .{ .truncate = true, .read = true, }); defer out_file.close(); const writer = out_file.writer(); try writer.writeAll("<!DOCTYPE html>"); try writer.writeAll("<html>"); try writer.writeAll("<head>"); try writer.print("<style>{s}</style>", .{css_styles}); try writer.print("<script>{s}</script>", .{js_helpers}); try writer.writeAll("</head>"); try writer.writeAll("<body>"); // TODO why is this even necessary? var next_btn = std.ArrayList(u8).init(arena); if (svgs.items.len <= 2) { try next_btn.appendSlice("disabled"); } try writer.print( \\<div> \\ <span><button id='btn-prev' onclick='onClickPrev()' disabled>Previous</button></span> \\ <span><button id='btn-next' onclick='onClickNext()' {s}>Next</button></span> \\</div> , .{ next_btn.items, }); try writer.writeAll("<div class='snapshot-div'>"); try writer.writeAll("<span id='diff-lhs'>"); svgs.items[0].height = max_height; try svgs.items[0].render(writer); try writer.writeAll("</span>"); if (svgs.items.len > 1) { try writer.writeAll("<span id='diff-rhs'>"); svgs.items[1].height = max_height; try svgs.items[1].render(writer); try writer.writeAll("</span>"); } for (svgs.items) |*svg| { try svg.css_styles.append(arena, "visibility:hidden;"); svg.height = max_height; try svg.render(writer); } try writer.writeAll("</div>"); try writer.writeAll("</body>"); try writer.writeAll("</html>"); } const LookupEntry = struct { el: *Svg.Element.Rect, name: []const u8, }; const OnClickEvent = struct { el: *Svg.Element.Rect, group: *Svg.Element.Group, svg_id: []const u8, x: usize, y: usize, }; const RelocPair = struct { target: u64, label: *Svg.Element.Text, box: *Svg.Element.Rect, group: *Svg.Element.Group, }; const ParsedNode = struct { tag: enum { section, atom, reloc, }, start: usize, end: usize, children: std.ArrayListUnmanaged(*ParsedNode) = .{}, fn deinit(node: *ParsedNode, allocator: Allocator) void { for (node.children.items) |child| { child.deinit(allocator); allocator.destroy(child); } node.children.deinit(allocator); } fn toSvg(node: *ParsedNode, arena: Allocator, ctx: struct { nodes: []Snapshot.Node, svg: *Svg, group: ?*Svg.Element.Group = null, sect_name: ?[]const u8 = null, x: *usize, y: *usize, lookup: *std.AutoHashMap(u64, LookupEntry), relocs: *std.ArrayList(RelocPair), onclicks: *std.StringHashMap(std.ArrayList(OnClickEvent)), }) anyerror!void { var x = ctx.x.*; var y = ctx.y.*; switch (node.tag) { .section => { const group = try Svg.Element.Group.new(arena); try ctx.svg.children.append(arena, &group.base); const inner_group = try Svg.Element.Group.new(arena); try group.children.append(arena, &inner_group.base); const label_text = ctx.nodes[node.start].payload.name; const label = try Svg.Element.Text.new(arena, .{ .x = x, .y = y + 15, .contents = label_text, }); try inner_group.children.append(arena, &label.base); const top = try Svg.Element.Path.new(arena, .{}); try top.moveTo(arena, x, y); try top.lineTo(arena, ctx.svg.width - 100, y); top.base.css_classes = "dotted-line"; try inner_group.children.append(arena, &top.base); const address = try Svg.Element.Text.new(arena, .{ .x = ctx.svg.width - 100, .y = y + 15, .contents = try std.fmt.allocPrint(arena, "{x}", .{ctx.nodes[node.start].address}), }); try inner_group.children.append(arena, &address.base); y += unit_height; for (node.children.items) |child| { try child.toSvg(arena, .{ .nodes = ctx.nodes, .svg = ctx.svg, .group = group, .sect_name = label_text, .x = ctx.x, .y = &y, .lookup = ctx.lookup, .relocs = ctx.relocs, .onclicks = ctx.onclicks, }); } y += unit_height; }, .atom => blk: { if (node.children.items.len > 0 and node.children.items[0].tag == .atom) { // This atom delimits contents of a section from an object file // TODO draw an enclosing box for the contained atoms. for (node.children.items) |child| { try child.toSvg(arena, .{ .nodes = ctx.nodes, .svg = ctx.svg, .group = ctx.group, .sect_name = ctx.sect_name, .x = ctx.x, .y = &y, .lookup = ctx.lookup, .relocs = ctx.relocs, .onclicks = ctx.onclicks, }); } break :blk; } const group = try Svg.Element.Group.new(arena); try ctx.group.?.children.append(arena, &group.base); const label = try Svg.Element.Text.new(arena, .{ .x = x + 210, .y = y + 15, .contents = ctx.nodes[node.start].payload.name, }); try group.children.append(arena, &label.base); const box = try Svg.Element.Rect.new(arena, .{ .x = x + 200, .y = y, .width = 200, .height = unit_height, }); if (ctx.nodes[node.start].payload.is_global) { box.base.css_classes = "symbol global"; } else { box.base.css_classes = "symbol local"; } try group.children.append(arena, &box.base); const name = if (ctx.nodes[node.start].payload.name.len == 0) ctx.sect_name.? else ctx.nodes[node.start].payload.name; try ctx.lookup.putNoClobber(ctx.nodes[node.start].address, .{ .el = box, .name = name, }); y += box.height; const reloc_group = try Svg.Element.Group.new(arena); reloc_group.base.css_classes = "hidden"; reloc_group.base.id = try std.fmt.allocPrint(arena, "reloc-group-{d}", .{id}); id += 1; try group.children.append(arena, &reloc_group.base); const address = try Svg.Element.Text.new(arena, .{ .x = box.x + box.width + 10, .y = box.y + 15, .contents = try std.fmt.allocPrint(arena, "{x}", .{ctx.nodes[node.start].address}), }); address.base.css_classes = "bold-font"; try reloc_group.children.append(arena, &address.base); box.base.id = try std.fmt.allocPrint(arena, "symbol-{d}", .{id}); id += 1; if (ctx.nodes[node.start].payload.name.len == 0) { // Noname means we can't really optimise for diff exploration between snapshots box.base.onclick = try std.fmt.allocPrint(arena, "onClick(\"{s}\", \"{s}\", \"{s}\", 0, {d})", .{ box.base.id.?, reloc_group.base.id.?, ctx.svg.id.?, node.children.items.len * 2 * unit_height, // TODO this should be read from the reloc box rather than hardcoded }); } else { const res = try ctx.onclicks.getOrPut(ctx.nodes[node.start].payload.name); if (!res.found_existing) { res.value_ptr.* = std.ArrayList(OnClickEvent).init(arena); } try res.value_ptr.append(.{ .el = box, .group = reloc_group, .svg_id = ctx.svg.id.?, .x = 0, .y = node.children.items.len * 2 * unit_height, // TODO this should be read from the reloc box rather than hardcoded }); } for (node.children.items) |child| { try child.toSvg(arena, .{ .nodes = ctx.nodes, .svg = ctx.svg, .group = reloc_group, .sect_name = ctx.sect_name, .x = ctx.x, .y = &y, .lookup = ctx.lookup, .relocs = ctx.relocs, .onclicks = ctx.onclicks, }); } y -= node.children.items.len * 2 * unit_height; }, .reloc => { const address = try Svg.Element.Text.new(arena, .{ .x = x + 410, .y = y + 15, .contents = try std.fmt.allocPrint(arena, "{x}", .{ctx.nodes[node.start].address}), }); try ctx.group.?.children.append(arena, &address.base); const box_width = 200; const label = try Svg.Element.Text.new(arena, .{ .x = x + 215, .y = y + 15, .contents = undefined, }); try ctx.group.?.children.append(arena, &label.base); const box = try Svg.Element.Rect.new(arena, .{ .x = x + box_width, .y = y, .width = 200, .height = unit_height * 2, }); try ctx.group.?.children.append(arena, &box.base); try ctx.relocs.append(.{ .target = ctx.nodes[node.start].payload.target, .label = label, .box = box, .group = ctx.group.?, }); y += box.height; }, } ctx.svg.height += y - ctx.y.*; ctx.y.* = y; } }; const Parser = struct { arena: Allocator, nodes: []Snapshot.Node, count: usize = 0, fn parse(parser: *Parser) !?*ParsedNode { const nn = parser.next() orelse return null; return switch (nn.tag) { .section_end, .atom_end, .relocation => unreachable, .section_start => parser.parseSection(), .atom_start => parser.parseAtom(), }; } fn parseSection(parser: *Parser) anyerror!*ParsedNode { const node = try parser.arena.create(ParsedNode); node.* = .{ .tag = .section, .start = parser.count - 1, .end = undefined, }; while (parser.next()) |nn| { switch (nn.tag) { .section_start, .atom_end, .relocation => unreachable, .atom_start => { const child = try parser.parseAtom(); try node.children.append(parser.arena, child); }, .section_end => { node.end = parser.count - 1; break; }, } } return node; } fn parseAtom(parser: *Parser) anyerror!*ParsedNode { const node = try parser.arena.create(ParsedNode); node.* = .{ .tag = .atom, .start = parser.count - 1, .end = undefined, }; while (parser.next()) |nn| { switch (nn.tag) { .section_start, .section_end => unreachable, .atom_start => { const child = try parser.parseAtom(); try node.children.append(parser.arena, child); }, .atom_end => { node.end = parser.count - 1; break; }, .relocation => { const child = try parser.parseReloc(); try node.children.append(parser.arena, child); }, } } return node; } fn parseReloc(parser: *Parser) anyerror!*ParsedNode { const node = try parser.arena.create(ParsedNode); node.* = .{ .tag = .reloc, .start = parser.count - 1, .end = parser.count - 1, }; return node; } fn next(parser: *Parser) ?Snapshot.Node { if (parser.count >= parser.nodes.len) return null; const node = parser.nodes[parser.count]; parser.count += 1; return node; } };
src/main.zig
const std = @import("std"); const math = std.math; const assert = std.debug.assert; const L = std.unicode.utf8ToUtf16LeStringLiteral; const zwin32 = @import("zwin32"); const w32 = zwin32.base; const d3d12 = zwin32.d3d12; const hrPanic = zwin32.hrPanic; const hrPanicOnFail = zwin32.hrPanicOnFail; const zd3d12 = @import("zd3d12"); const common = @import("common"); const GuiRenderer = common.GuiRenderer; const c = common.c; const zm = @import("zmath"); const zmesh = @import("zmesh"); // We need to export below symbols for DirectX 12 Agility SDK. pub export const D3D12SDKVersion: u32 = 4; pub export const D3D12SDKPath: [*:0]const u8 = ".\\d3d12\\"; const content_dir = @import("build_options").content_dir; const window_name = "zig-gamedev: intro 2"; const window_width = 1920; const window_height = 1080; // By convention, we use 'Pso_' prefix for structures that are also defined in HLSL code // (see 'DrawConst' in intro2.hlsl). const Pso_DrawConst = struct { object_to_clip: [16]f32, }; // In this intro application vertex consists of position and normal vector. const Vertex = struct { position: [3]f32, normal: [3]f32, }; const DemoState = struct { gctx: zd3d12.GraphicsContext, guir: GuiRenderer, frame_stats: common.FrameStats, intro2_pso: zd3d12.PipelineHandle, vertex_buffer: zd3d12.ResourceHandle, index_buffer: zd3d12.ResourceHandle, depth_texture: zd3d12.ResourceHandle, depth_texture_dsv: d3d12.CPU_DESCRIPTOR_HANDLE, mesh_num_vertices: u32, mesh_num_indices: u32, }; fn init(allocator: std.mem.Allocator) !DemoState { // Create application window and initialize dear imgui library. const window = try common.initWindow(allocator, window_name, window_width, window_height); // Create temporary memory allocator for use during initialization. We pass this allocator to all // subsystems that need memory and then free everyting with a single deallocation. var arena_allocator_state = std.heap.ArenaAllocator.init(allocator); defer arena_allocator_state.deinit(); const arena_allocator = arena_allocator_state.allocator(); // Create DirectX 12 context. var gctx = zd3d12.GraphicsContext.init(allocator, window); // Enable vsync. // gctx.present_flags = 0; // gctx.present_interval = 1; // Create pipeline state object (pso) which is needed to draw geometry - it contains vertex shader, // pixel shader and draw state data all linked together. const intro2_pso = blk: { const input_layout_desc = [_]d3d12.INPUT_ELEMENT_DESC{ d3d12.INPUT_ELEMENT_DESC.init("POSITION", 0, .R32G32B32_FLOAT, 0, 0, .PER_VERTEX_DATA, 0), d3d12.INPUT_ELEMENT_DESC.init("_Normal", 0, .R32G32B32_FLOAT, 0, 12, .PER_VERTEX_DATA, 0), }; var pso_desc = d3d12.GRAPHICS_PIPELINE_STATE_DESC.initDefault(); pso_desc.InputLayout = .{ .pInputElementDescs = &input_layout_desc, .NumElements = input_layout_desc.len, }; pso_desc.RTVFormats[0] = .R8G8B8A8_UNORM; pso_desc.NumRenderTargets = 1; pso_desc.DSVFormat = .D32_FLOAT; pso_desc.BlendState.RenderTarget[0].RenderTargetWriteMask = 0xf; pso_desc.PrimitiveTopologyType = .TRIANGLE; break :blk gctx.createGraphicsShaderPipeline( arena_allocator, &pso_desc, content_dir ++ "shaders/intro2.vs.cso", content_dir ++ "shaders/intro2.ps.cso", ); }; // Load a mesh from file and store the data in temporary arrays. var mesh_indices = std.ArrayList(u32).init(arena_allocator); var mesh_positions = std.ArrayList([3]f32).init(arena_allocator); var mesh_normals = std.ArrayList([3]f32).init(arena_allocator); { zmesh.init(arena_allocator); defer zmesh.deinit(); const data = try zmesh.io.parseAndLoadFile(content_dir ++ "cube.gltf"); defer zmesh.io.cgltf.free(data); try zmesh.io.appendMeshPrimitive(data, 0, 0, &mesh_indices, &mesh_positions, &mesh_normals, null, null); } const mesh_num_indices = @intCast(u32, mesh_indices.items.len); const mesh_num_vertices = @intCast(u32, mesh_positions.items.len); // Create vertex buffer and return a *handle* to the underlying Direct3D12 resource. const vertex_buffer = gctx.createCommittedResource( .DEFAULT, d3d12.HEAP_FLAG_NONE, &d3d12.RESOURCE_DESC.initBuffer(mesh_num_vertices * @sizeOf(Vertex)), d3d12.RESOURCE_STATE_COPY_DEST, null, ) catch |err| hrPanic(err); // Create index buffer and return a *handle* to the underlying Direct3D12 resource. const index_buffer = gctx.createCommittedResource( .DEFAULT, d3d12.HEAP_FLAG_NONE, &d3d12.RESOURCE_DESC.initBuffer(mesh_num_indices * @sizeOf(u32)), d3d12.RESOURCE_STATE_COPY_DEST, null, ) catch |err| hrPanic(err); // Create depth texture resource. const depth_texture = gctx.createCommittedResource( .DEFAULT, d3d12.HEAP_FLAG_NONE, &blk: { var desc = d3d12.RESOURCE_DESC.initTex2d(.D32_FLOAT, gctx.viewport_width, gctx.viewport_height, 1); desc.Flags = d3d12.RESOURCE_FLAG_ALLOW_DEPTH_STENCIL | d3d12.RESOURCE_FLAG_DENY_SHADER_RESOURCE; break :blk desc; }, d3d12.RESOURCE_STATE_DEPTH_WRITE, &d3d12.CLEAR_VALUE.initDepthStencil(.D32_FLOAT, 1.0, 0), ) catch |err| hrPanic(err); // Create depth texture 'view' - a descriptor which can be send to Direct3D12 API. const depth_texture_dsv = gctx.allocateCpuDescriptors(.DSV, 1); gctx.device.CreateDepthStencilView( gctx.lookupResource(depth_texture).?, // Get the D3D12 resource from a handle. null, depth_texture_dsv, ); // Open D3D12 command list, setup descriptor heap, etc. After this call we can upload resources to the GPU, // draw 3D graphics etc. gctx.beginFrame(); // Create and upload graphics resources for dear imgui renderer. var guir = GuiRenderer.init(arena_allocator, &gctx, 1, content_dir); // Fill vertex buffer with vertex data. { // Allocate memory from upload heap and fill it with vertex data. const verts = gctx.allocateUploadBufferRegion(Vertex, mesh_num_vertices); for (mesh_positions.items) |_, i| { verts.cpu_slice[i].position = mesh_positions.items[i]; verts.cpu_slice[i].normal = mesh_normals.items[i]; } // Copy vertex data from upload heap to vertex buffer resource that resides in high-performance memory // on the GPU. gctx.cmdlist.CopyBufferRegion( gctx.lookupResource(vertex_buffer).?, 0, verts.buffer, verts.buffer_offset, verts.cpu_slice.len * @sizeOf(@TypeOf(verts.cpu_slice[0])), ); } // Fill index buffer with index data. { // Allocate memory from upload heap and fill it with index data. const indices = gctx.allocateUploadBufferRegion(u32, mesh_num_indices); for (mesh_indices.items) |_, i| { indices.cpu_slice[i] = mesh_indices.items[i]; } // Copy index data from upload heap to index buffer resource that resides in high-performance memory // on the GPU. gctx.cmdlist.CopyBufferRegion( gctx.lookupResource(index_buffer).?, 0, indices.buffer, indices.buffer_offset, indices.cpu_slice.len * @sizeOf(@TypeOf(indices.cpu_slice[0])), ); } // Transition vertex and index buffers from 'copy dest' state to the state appropriate for rendering. gctx.addTransitionBarrier(vertex_buffer, d3d12.RESOURCE_STATE_VERTEX_AND_CONSTANT_BUFFER); gctx.addTransitionBarrier(index_buffer, d3d12.RESOURCE_STATE_INDEX_BUFFER); gctx.flushResourceBarriers(); // This will send command list to the GPU, call 'Present' and do some other bookkeeping. gctx.endFrame(); // Wait for the GPU to finish all commands. gctx.finishGpuCommands(); return DemoState{ .gctx = gctx, .guir = guir, .frame_stats = common.FrameStats.init(), .intro2_pso = intro2_pso, .vertex_buffer = vertex_buffer, .index_buffer = index_buffer, .depth_texture = depth_texture, .depth_texture_dsv = depth_texture_dsv, .mesh_num_vertices = mesh_num_vertices, .mesh_num_indices = mesh_num_indices, }; } fn deinit(demo: *DemoState, allocator: std.mem.Allocator) void { demo.gctx.finishGpuCommands(); demo.guir.deinit(&demo.gctx); demo.gctx.deinit(allocator); common.deinitWindow(allocator); demo.* = undefined; } fn update(demo: *DemoState) void { // Update frame counter and fps stats. demo.frame_stats.update(demo.gctx.window, window_name); const dt = demo.frame_stats.delta_time; // Update dear imgui common. After this call we can define our widgets. common.newImGuiFrame(dt); } fn draw(demo: *DemoState) void { var gctx = &demo.gctx; // Begin DirectX 12 rendering. gctx.beginFrame(); // Get current back buffer resource and transition it to 'render target' state. const back_buffer = gctx.getBackBuffer(); gctx.addTransitionBarrier(back_buffer.resource_handle, d3d12.RESOURCE_STATE_RENDER_TARGET); gctx.flushResourceBarriers(); gctx.cmdlist.OMSetRenderTargets( 1, &[_]d3d12.CPU_DESCRIPTOR_HANDLE{back_buffer.descriptor_handle}, w32.TRUE, &demo.depth_texture_dsv, ); gctx.cmdlist.ClearRenderTargetView( back_buffer.descriptor_handle, &[4]f32{ 0.0, 0.0, 0.0, 1.0 }, 0, null, ); gctx.cmdlist.ClearDepthStencilView(demo.depth_texture_dsv, d3d12.CLEAR_FLAG_DEPTH, 1.0, 0, 0, null); // Set graphics state and draw. gctx.setCurrentPipeline(demo.intro2_pso); gctx.cmdlist.IASetPrimitiveTopology(.TRIANGLELIST); gctx.cmdlist.IASetVertexBuffers(0, 1, &[_]d3d12.VERTEX_BUFFER_VIEW{.{ .BufferLocation = gctx.lookupResource(demo.vertex_buffer).?.GetGPUVirtualAddress(), .SizeInBytes = demo.mesh_num_vertices * @sizeOf(Vertex), .StrideInBytes = @sizeOf(Vertex), }}); gctx.cmdlist.IASetIndexBuffer(&.{ .BufferLocation = gctx.lookupResource(demo.index_buffer).?.GetGPUVirtualAddress(), .SizeInBytes = demo.mesh_num_indices * @sizeOf(u32), .Format = .R32_UINT, }); // Upload per-draw constant data. { // Compute transformation matrices. const object_to_world = zm.rotationY(@floatCast(f32, demo.frame_stats.time)); const world_to_view = zm.lookAtLh( zm.f32x4(3.0, 3.0, -3.0, 1.0), // eye position zm.f32x4(0.0, 0.0, 0.0, 1.0), // focus point zm.f32x4(0.0, 1.0, 0.0, 0.0), // up direction ('w' coord is zero because this is a vector not a point) ); const view_to_clip = zm.perspectiveFovLh( 0.25 * math.pi, @intToFloat(f32, gctx.viewport_width) / @intToFloat(f32, gctx.viewport_height), 0.1, 20.0, ); const object_to_view = zm.mul(object_to_world, world_to_view); const object_to_clip = zm.mul(object_to_view, view_to_clip); // Allocate memory for one instance of Pso_DrawConst structure. const mem = gctx.allocateUploadMemory(Pso_DrawConst, 1); // Copy 'object_to_clip' matrix to upload memory. We need to transpose it because // HLSL uses column-major matrices by default (zmath uses row-major matrices). zm.storeMat(mem.cpu_slice[0].object_to_clip[0..], zm.transpose(object_to_clip)); // Set GPU handle of our allocated memory region so that it is visible to the shader. gctx.cmdlist.SetGraphicsRootConstantBufferView( 0, // Slot index 0 in Root Signature (CBV(b0), see intro2.hlsl). mem.gpu_base, ); } gctx.cmdlist.DrawIndexedInstanced(demo.mesh_num_indices, 1, 0, 0, 0); // Draw dear imgui widgets (not used in this demo). demo.guir.draw(gctx); gctx.addTransitionBarrier(back_buffer.resource_handle, d3d12.RESOURCE_STATE_PRESENT); gctx.flushResourceBarriers(); // Call 'Present' and prepare for the next frame. gctx.endFrame(); } pub fn main() !void { // Initialize some low-level Windows stuff (DPI awarness, COM), check Windows version and also check // if DirectX 12 Agility SDK is supported. common.init(); defer common.deinit(); // Create main memory allocator for our application. var gpa = std.heap.GeneralPurposeAllocator(.{}){}; defer _ = gpa.deinit(); const allocator = gpa.allocator(); var demo = try init(allocator); defer deinit(&demo, allocator); while (common.handleWindowEvents()) { update(&demo); draw(&demo); } }
samples/intro/src/intro2.zig
const std = @import("std"); pub fn main() anyerror!void { const stdout = std.io.getStdOut().writer(); try stdout.print("Hello, {}!\n", .{"world"}); } const expect = std.testing.expect; test "comments" { // comments start with "//" until newline // foo bar baz const x = true; // another comment expect(x); } /// a doc comment starts with "///" /// multiple lines are merged together const Timestamp = struct { /// number of seconds since epoch seconds: i64, /// number of nanoseconds past the second nano: u32, const Self = @This(); pub fn unixEpoch() Self { return Self{ .seconds = 0, .nanos = 0, }; } }; const my_val = switch (std.Target.current.os.tag) { .linux => "Linux", else => "not Linux", }; const Book = enum { paperback, hardcover, ebook, pdf, }; const TokenType = union(enum) { int: isize, float: f64, string: []const u8, }; const array_lit: [4]u8 = .{ 11, 22, 33, 44 }; const sentinal_lit = [_:0]u8{ 1, 2, 3, 4 }; test "address of syntax" { // Get the address of a variable: const x: i32 = 1234; const x_ptr = &x; // Dereference a pointer: expect(x_ptr.* == 1234); // When you get the address of a const variable, you get a const pointer to a single item. expect(@TypeOf(x_ptr) == *const i32); // If you want to mutate the value, you'd need an address of a mutable variable: var y: i32 = 5678; const y_ptr = &y; expect(@TypeOf(y_ptr) == *i32); y_ptr.* += 1; expect(y_ptr.* == 5679); } // integer literals const decimal_int = 98222; const hex_int = 0xff; const another_hex_int = 0xFF; const octal_int = 0o755; const binary_int = 0b11110000; // underscores may be placed between two digits as a visual separator const one_billion = 1_000_000_000; const binary_mask = 0b1_1111_1111; const permissions = 0o7_5_5; const big_address = 0xFF80_0000_0000_0000; // float literals const floating_point = 123.0E+77; const another_float = 123.0; const yet_another = 123.0e+77; const hex_floating_point = 0x103.70p-5; const another_hex_float = 0x103.70; const yet_another_hex_float = 0x103.70P-5; // underscores may be placed between two digits as a visual separator const lightspeed = 299_792_458.000_000; const nanosecond = 0.000_000_001; const more_hex = 0x1234_5678.9ABC_CDEFp-10; fn max(comptime T: type, a: T, b: T) T { return if (a > b) a else b; }
tests/syntax-tests/source/Zig/example.zig
const std = @import("std"); const aoc = @import("aoc-lib.zig"); const Signal = struct { patterns: [][]const u8, output: [][]const u8, map: [7]u8, alloc: std.mem.Allocator, pub fn init(alloc: std.mem.Allocator, line: []const u8) !*Signal { var sig = try alloc.create(Signal); sig.alloc = alloc; var patternOutput = std.mem.split(u8, line, " | "); var patterns = patternOutput.next().?; var output = patternOutput.next().?; sig.patterns = try aoc.splitToOwnedSlice(alloc, patterns, " "); sig.output = try aoc.splitToOwnedSlice(alloc, output, " "); sig.initMap(); return sig; } pub fn deinit(self: *Signal) void { self.alloc.free(self.patterns); self.alloc.free(self.output); self.alloc.destroy(self); } pub fn known(self: *Signal) usize { var c: usize = 0; for (self.output) |o| { switch (o.len) { 2, 4, 3, 7 => { c += 1; }, else => {}, } } return c; } pub fn initMap(self: *Signal) void { var occur = [7]u8{ 0, 0, 0, 0, 0, 0, 0 }; var occur6 = [7]u8{ 0, 0, 0, 0, 0, 0, 0 }; for (self.patterns) |p| { for (p) |ch| { occur[@as(usize, ch - 'a')] += 1; if (p.len == 6) { occur6[@as(usize, ch - 'a')] += 1; } } } //aoc.print("{any} {any}\n", .{ occur, occur6 }) catch unreachable; for (occur) |o, i| { switch (o) { 6 => { self.map[i] = @as(u8, 'b'); }, 4 => { self.map[i] = @as(u8, 'e'); }, 9 => { self.map[i] = @as(u8, 'f'); }, 7 => { if (occur6[i] == 2) { self.map[i] = @as(u8, 'd'); } else { self.map[i] = @as(u8, 'g'); } }, 8 => { if (occur6[i] == 2) { self.map[i] = @as(u8, 'c'); } else { self.map[i] = @as(u8, 'a'); } }, else => unreachable, } } //aoc.print("{any}\n", .{self.map}) catch unreachable; } pub fn value(self: *Signal) usize { return 1000 * self.digitValue(0) + 100 * self.digitValue(1) + 10 * self.digitValue(2) + self.digitValue(3); } pub fn digitValue(self: *Signal, i: usize) usize { switch (self.output[i].len) { 2 => { return 1; }, 4 => { return 4; }, 3 => { return 7; }, 7 => { return 8; }, 5 => { if (self.digitContains(i, 'e')) { return 2; } if (self.digitContains(i, 'c')) { return 3; } return 5; }, 6 => { if (!self.digitContains(i, 'c')) { return 6; } if (self.digitContains(i, 'e')) { return 0; } return 9; }, else => unreachable, } } pub fn digitContains(self: *Signal, i: usize, tch: u8) bool { for (self.output[i]) |ch| { if (self.map[ch - 'a'] == tch) { return true; } } return false; } }; test "signal" { var sig = try Signal.init(aoc.talloc, "fgeab ca afcebg bdacfeg cfaedg gcfdb baec bfadeg bafgc acf | gebdcfa ecba ca fadegcb"); defer sig.deinit(); try aoc.assertEq(@as(usize, 4), sig.known()); try aoc.assertEq(@as(usize, 8418), sig.value()); try aoc.assertEq(true, sig.digitContains(0, 'a')); try aoc.assertEq(true, sig.digitContains(0, 'f')); try aoc.assertEq(false, sig.digitContains(2, 'a')); try aoc.assertEq(true, sig.digitContains(2, 'c')); try aoc.assertEq(true, sig.digitContains(2, 'f')); var ex = try Signal.init(aoc.talloc, "acedgfb cdfbe gcdfa fbcad dab cefabd cdfgeb eafb cagedb ab | cdfeb fcadb cdfeb cdbaf"); defer ex.deinit(); try aoc.assertEq(@as(usize, 0), ex.known()); try aoc.assertEq(@as(usize, 5353), ex.value()); } const Signals = struct { signals: []*Signal, map: [7]u8, alloc: std.mem.Allocator, pub fn init(alloc: std.mem.Allocator, inp: []const u8) !*Signals { var self = try alloc.create(Signals); self.alloc = alloc; var sigs = std.ArrayList(*Signal).init(alloc); var lines = try aoc.splitToOwnedSlice(alloc, inp, "\n"); defer alloc.free(lines); for (lines) |l| { var sig = try Signal.init(alloc, l); try sigs.append(sig); } self.signals = sigs.toOwnedSlice(); return self; } pub fn deinit(self: *Signals) void { for (self.signals) |sig| { sig.deinit(); } self.alloc.free(self.signals); self.alloc.destroy(self); } pub fn parts(self: *Signals) ![2]usize { var r = [2]usize{ 0, 0 }; for (self.signals) |sig| { r[0] += sig.known(); r[1] += sig.value(); } return r; } }; test "examples" { var t = try Signals.init(aoc.talloc, aoc.test1file); defer t.deinit(); var p = try t.parts(); try aoc.assertEq(@as(u64, 26), p[0]); try aoc.assertEq(@as(u64, 61229), p[1]); var ti = try Signals.init(aoc.talloc, aoc.inputfile); defer ti.deinit(); var pi = try ti.parts(); try aoc.assertEq(@as(u64, 504), pi[0]); try aoc.assertEq(@as(u64, 1073431), pi[1]); } fn day08(inp: []const u8, bench: bool) anyerror!void { var s = try Signals.init(aoc.halloc, inp); var p = try s.parts(); if (!bench) { try aoc.print("Part 1: {}\nPart 2: {}\n", .{ p[0], p[1] }); } } pub fn main() anyerror!void { try aoc.benchme(aoc.input(), day08); }
2021/08/aoc.zig
const c = @cImport({ @cInclude("coremark.h"); @cInclude("core_portme.h"); }); const warn = @import("../nonsecure-common/debug.zig").warn; const timer = @import("../ports/" ++ @import("build_options").BOARD ++ "/timer.zig").timer0; const port_ns = @import("../ports/" ++ @import("build_options").BOARD ++ "/nonsecure.zig"); const port = @import("../ports/" ++ @import("build_options").BOARD ++ "/common.zig"); const tzmcfi = @cImport(@cInclude("TZmCFI/Gateway.h")); const TIMER_RESET_VALUE: u32 = 0x80000000; /// This function will be called right before starting the timed portion of the benchmark. /// /// Implementation may be capturing a system timer (as implemented in the example code) /// or zeroing some system parameters - e.g. setting the cpu clocks cycles to 0. export fn start_time() void { tzmcfi.TCDebugStartProfiler(); timer.setValue(TIMER_RESET_VALUE); timer.start(); } /// This function will be called right after ending the timed portion of the benchmark. /// /// Implementation may be capturing a system timer (as implemented in the example code) /// or other system parameters - e.g. reading the current value of cpu cycles counter. export fn stop_time() void { timer.stop(); tzmcfi.TCDebugStopProfiler(); tzmcfi.TCDebugDumpProfile(); } /// Return an abstract "ticks" number that signifies time on the system. /// /// Actual value returned may be cpu cycles, milliseconds or any other value, /// as long as it can be converted to seconds by <time_in_secs>. /// This methodology is taken to accomodate any hardware or simulated platform. /// The sample implementation returns millisecs by default, /// and the resolution is controlled by <TIMER_RES_DIVIDER> export fn get_time() c.CORE_TICKS { return TIMER_RESET_VALUE - timer.getValue(); } /// Convert the value returned by get_time to seconds. /// /// The <secs_ret> type is used to accomodate systems with no support for floating point. /// Default implementation implemented by the EE_TICKS_PER_SEC macro above. export fn time_in_secs(ticks: c.CORE_TICKS) c.secs_ret { return @intToFloat(f64, ticks) / port.system_core_clock; } export var default_num_contexts: c.ee_u32 = 1; comptime { if (@sizeOf(c.ee_ptr_int) != @sizeOf([*c]c.ee_u8)) { @compileError("ERROR! Please define ee_ptr_int to a type that holds a pointer!"); } if (@sizeOf(c.ee_u32) != 4) { @compileError("ERROR! Please define ee_u32 to a 32b unsigned type!"); } } /// Target specific initialization code export fn portable_init(p: *c.core_portable, _argc: *c_int, _argv: ?[*]([*]u8)) void { port_ns.init(); p.portable_id = 1; warn("* portable_init\r\n", .{}); } /// Target specific final code export fn portable_fini(p: *c.core_portable) void { p.portable_id = 0; warn("* portable_fini - system halted\r\n", .{}); while (true) {} } export fn uart_send_char(ch: u8) void { if (ch == '\n') { warn("\r\n", .{}); } else { warn("{}", .{&[_]u8{ch}}); } }
examples/nonsecure-bench-coremark/core_portme.zig
pub const std = @import("std"); pub const zzz = @import("zzz"); fn node_functions() !void { var tree = zzz.ZStaticTree(8){}; try zzz.appendText(&tree, null, "foo:bar;biz:baz,boom"); var iter: ?*zzz.ZNode = null; // Iterate nodes in the tree starting from some node. iter = &tree.root; while (iter) |it| : (iter = it.next(null)) { std.debug.print("node_functions():next(): {s}\n", .{it.*.value}); } // Iterate children. iter = null; while (tree.root.nextChild(iter)) |it| : (iter = it) { std.debug.print("node_functions():nextChild(): {s}\n", .{it.*.value}); } // Iterate descendants. iter = null; while (tree.root.nextDescendant(iter, null)) |it| : (iter = it) { std.debug.print("node_functions():nextDescendant(): {s}\n", .{it.*.value}); } // Get nth child. std.debug.print("node_functions():getNthChild(): {s}\n", .{tree.root.getNthChild(0).?.value}); std.debug.print("node_functions():getNthChildValue(): {s}\n", .{tree.root.getNthChildValue(1)}); // Number of children. std.debug.print("node_functions():getChildCount(): {}\n", .{tree.root.getChildCount()}); // Find children/descendants. std.debug.print("node_functions():findChild(): {s}\n", .{tree.root.findChild("biz").?.value}); std.debug.print("node_functions():findDescendant(): {s}\n", .{tree.root.findDescendant("boom").?.value}); std.debug.print("node_functions():findNthChild(): {any}\n", .{tree.root.findNthChild(1, "biz")}); std.debug.print("node_functions():findNthDescendant(): {any}\n", .{tree.root.findNthDescendant(1, "boom")}); // Output. tree.root.show(); } fn static_tree_functions() !void { var tree = zzz.ZStaticTree(8){}; try zzz.appendText(&tree, null, "foo:bar;biz:baz,boom"); // Remaining nodes in the tree. std.debug.print("static_tree_functions():node_count: {}\n", .{tree.node_count}); std.debug.print("static_tree_functions():nodesRemaining(): {}\n", .{tree.nodesRemaining()}); // Check if we can append more text. std.debug.print("static_tree_functions():canAppend(): {}\n", .{tree.canAppend("this:will:not:fit")}); std.debug.print("static_tree_functions():canAppend(): {}\n", .{tree.canAppend("this:will")}); // Appending values. std.debug.print("static_tree_functions():appendValue(): {s}\n", .{(try tree.appendValue(null, "last one")).value}); // Clearing. tree.clear(); } fn dynamic_tree_functions() !void { var tree = zzz.ZDynamicTree.init(std.testing.allocator); defer tree.deinit(); try zzz.appendText(&tree, null, "foo:bar;biz:baz,boom"); // Appending values and types. std.debug.print("dynamic_tree_functions():appendValue(): {s}\n", .{(try tree.appendValue(null, "some string")).value}); std.debug.print("dynamic_tree_functions():appendAnytype(): {s}\n", .{(try tree.appendAnytype(null, 42)).value}); } fn module_functions() !void { var stree = zzz.ZStaticTree(8){}; var dtree = zzz.ZDynamicTree.init(std.testing.allocator); defer dtree.deinit(); // Append text. try zzz.appendText(&stree, null, "foo:bar;biz:baz,boom"); try zzz.appendText(&dtree, null, "foo:bar;biz:baz,boom"); // Copy nodes. _ = try zzz.copyNode(&dtree, null, stree.root.findDescendant("biz").?); dtree.root.show(); // Count text nodes. std.debug.print("module_functions():countTextNodes(): {}\n", .{zzz.countTextNodes("this:has:four:nodes")}); } pub fn main() !void { try node_functions(); try static_tree_functions(); try dynamic_tree_functions(); try module_functions(); }
examples/api.zig
const std = @import("std"); const testing = std.testing; const http = @import("net/http.zig"); const Peer = @import("Peer.zig"); const Allocator = std.mem.Allocator; const Sha1 = std.crypto.hash.Sha1; const bencode = @import("bencode.zig"); const Torrent = @import("Torrent.zig"); /// Our port we will seed from when we implement seeding /// Default based on 'BEP 3': http://bittorrent.org/beps/bep_0003.html const local_port: u16 = 6881; /// sub struct, part of torrent bencode file const Info = struct { /// Total length of the file in case of a single-file torrent. /// Null when the torrent is a multi-file torrent length: ?usize = null, /// In case of multi-file torrents, `files` will be non-null /// and includes a list of directories with each file size files: ?[]const struct { length: usize, path: []const []const u8, } = null, /// Name of the torrentfile name: []const u8, /// The length of each piece piece_length: usize, /// The individual pieces as one slice of bytes /// Totals to an amount multiple of 20. Where each 20 bytes equals to a SHA1 hash. pieces: []const u8, /// Generates a Sha1 hash of the info metadata. fn hash(self: Info, gpa: *Allocator) ![20]u8 { // create arraylist for writer with some initial capacity to reduce allocation count var list = std.ArrayList(u8).init(gpa); defer list.deinit(); const serializer = bencode.serializer(list.writer()); try serializer.serialize(self); // create sha1 hash of bencoded info var result: [20]u8 = undefined; Sha1.hash(list.items, &result, .{}); return result; } /// Retrieves the hashes of each individual piece fn pieceHashes(self: Info, gpa: *Allocator) ![][20]u8 { const hashes = self.pieces.len / 20; // 20 bytes per hash const buffer = try gpa.alloc([20]u8, hashes); errdefer gpa.free(buffer); // copy each hash into an element var i: usize = 0; while (i < hashes) : (i += 1) { // copy pieces payload into each piece hash std.mem.copy(u8, &buffer[i], self.pieces[i * 20 .. (i + 1) * 20]); } return buffer; } }; /// Bencode file for torrent information const TorrentMeta = struct { /// Torrent announce url announce: []const u8, /// Information regarding the pieces and the actual information required /// to correctly request for data from peers info: Info, }; /// Bencode file with tracker information const Tracker = struct { failure_reason: ?[]const u8 = null, /// Defines how often trackers are refreshed by the host interval: ?usize = null, /// Slice of all peers that are seeding peers: ?[]const u8 = null, }; /// struct to hold URL query information const QueryParameter = struct { name: []const u8, value: []const u8, }; /// TorrentFile represents the data structure needed to retreive all torrent data pub const TorrentFile = struct { /// the URL to be called to retreive torrent data from announce: []const u8, /// hashed metadata of the torrent hash: [20]u8, /// hashes of each individual piece to be downloaded, used to check and validate legitimacy piece_hashes: []const [20]u8, /// the length of each piece piece_length: usize, /// total size of the file size: usize, /// name of the torrent file name: []const u8, /// The arena state, used to free all memory allocated at once /// during the TorrentFile generation state: std.heap.ArenaAllocator.State, /// Generates the URL to retreive tracker information pub fn trackerURL(self: TorrentFile, gpa: *Allocator, peer_id: [20]u8, port: u16) ![]const u8 { // build our query paramaters var buf: [4]u8 = undefined; const port_slice = try std.fmt.bufPrint(&buf, "{d}", .{port}); var buf2: [100]u8 = undefined; const size = try std.fmt.bufPrint(&buf2, "{d}", .{self.size}); const queries = [_]QueryParameter{ .{ .name = "info_hash", .value = &self.hash }, .{ .name = "peer_id", .value = &peer_id }, .{ .name = "port", .value = port_slice }, .{ .name = "uploaded", .value = "0" }, .{ .name = "downloaded", .value = "0" }, .{ .name = "compact", .value = "1" }, .{ .name = "left", .value = size }, .{ .name = "key", .value = "test1241" }, }; return try encodeUrl(gpa, self.announce, &queries); } pub fn deinit(self: *TorrentFile, gpa: *Allocator) void { self.state.promote(gpa).deinit(); self.* = undefined; } /// Downloads the actual content and saves it to the given directory if `path` is non-null pub fn download(self: *TorrentFile, gpa: *Allocator, path: ?[]const u8) !void { // build our peers to connect to const peer_id = try generatePeerId(); const peers = try self.getPeers(gpa, peer_id, local_port); defer gpa.free(peers); const torrent = Torrent{ .peers = peers, .peer_id = peer_id, .file = self, }; // create destination file const full_path = try std.fs.path.join(gpa, &[_][]const u8{ path orelse ".", self.name, }); defer gpa.free(full_path); // This is blocking and will actually download the contents of the torrent try torrent.download(gpa, full_path); } /// calls the trackerURL to retrieve a list of peers and our interval /// of when we can obtain a new list of peers. fn getPeers(self: TorrentFile, gpa: *Allocator, peer_id: [20]u8, port: u16) ![]const Peer { // apart from the slice of Peers we only allocate temporary data // therefore it's easier (and faster) to just use an arena here var arena = std.heap.ArenaAllocator.init(gpa); defer arena.deinit(); const ally = &arena.allocator; const url = try self.trackerURL(ally, peer_id, port); const resp = try http.get(ally, url); if (!std.mem.eql(u8, resp.status_code, "200")) return error.CouldNotConnect; var stream = std.io.fixedBufferStream(resp.body); var deserializer = bencode.deserializer(ally, stream.reader()); const tracker = try deserializer.deserialize(Tracker); if (tracker.failure_reason) |reason| { std.log.err("Could not connect with tracker: '{s}'", .{reason}); return error.CouldNotConnect; } // the peers are compacted into binary format, so decode those too. return Peer.listFromCompact(gpa, tracker.peers.?); } /// Opens a torrentfile from the given path /// and decodes the Bencode into a `TorrentFile` pub fn open(gpa: *Allocator, path: []const u8) !TorrentFile { if (!std.mem.endsWith(u8, path, ".torrent")) return error.WrongFormat; // open the file const file = try std.fs.cwd().openFile(path, .{}); defer file.close(); var arena = std.heap.ArenaAllocator.init(gpa); var deserializer = bencode.deserializer(&arena.allocator, file.reader()); const meta = try deserializer.deserialize(TorrentMeta); const hash = try meta.info.hash(&arena.allocator); const piece_hashes = try meta.info.pieceHashes(&arena.allocator); const size = meta.info.length orelse blk: { var i: usize = 0; for (meta.info.files.?) |part| { i += part.length; } break :blk i; }; return TorrentFile{ .announce = meta.announce, .hash = hash, .piece_hashes = piece_hashes, .piece_length = meta.info.piece_length, .size = size, .name = meta.info.name, .state = arena.state, }; } }; /// generates a *new* peer_id, everytime this gets called. fn generatePeerId() ![20]u8 { // full peer_id var peer_id: [20]u8 = undefined; // our app name which will always remain the same const app_name = "-RM0010-"; std.mem.copy(u8, &peer_id, app_name); // generate a random seed var buf: [8]u8 = undefined; std.crypto.random.bytes(&buf); const seed = std.mem.readIntLittle(u64, &buf); const lookup = "0123456789abcdefghijklmnopqrstuvwxyz"; // generate next bytes var bytes: [12]u8 = undefined; var r = std.rand.DefaultPrng.init(seed); for (peer_id[app_name.len..]) |*b| { b.* = lookup[r.random.intRangeAtMost(u8, 0, lookup.len - 1)]; } return peer_id; } /// encodes queries into a query string attached to the provided base /// i.e. results example.com?parm=val where `base` is example.com /// and `queries` is a HashMap with key "parm" and value "val". fn encodeUrl(gpa: *Allocator, base: []const u8, queries: []const QueryParameter) ![]const u8 { if (queries.len == 0) return base; var list = std.ArrayList(u8).init(gpa); defer list.deinit(); const writer = list.writer(); try writer.writeAll(base); try writer.writeByte('?'); for (queries) |query, i| { if (i != 0) { try writer.writeByte('&'); } try writer.writeAll(query.name); try writer.writeByte('='); try escapeSlice(writer, query.value); // try writer.writeAll(query.value); } return list.toOwnedSlice(); } fn escapeSlice(writer: anytype, slice: []const u8) !void { for (slice) |c| try escapeChar(writer, c); } /// Encodes a singular character fn escapeChar(writer: anytype, char: u8) !void { switch (char) { '0'...'9', 'a'...'z', 'A'...'Z', '.', '-', '_', '~', => try writer.writeByte(char), else => try writer.print("%{X:0>2}", .{char}), } } test "encode URL queries" { const queries = [_]QueryParameter{ .{ .name = "key1", .value = "val1" }, .{ .name = "key2", .value = "val2" }, }; const base = "test.com"; const result = try encodeUrl(testing.allocator, base, &queries); defer testing.allocator.free(result); testing.expectEqualStrings("test.com?key1=val1&key2=val2", result); } test "generating tracker URL" { var hash: [20]u8 = undefined; std.mem.copy(u8, &hash, "12345678901234567890"); var piece_hashes: [1][20]u8 = undefined; std.mem.copy(u8, &piece_hashes[0], &hash); const tf = TorrentFile{ .announce = "example.com", .hash = hash, .size = 120, .piece_hashes = &piece_hashes, .piece_length = 1, .name = "test", .state = undefined, }; const url = try tf.trackerURL( testing.allocator, "12345678901234567890".*, 80, ); defer testing.allocator.free(url); testing.expectEqualStrings( "example.com?info_hash=12345678901234567890&peer_id=12345678901234567890&port=80&uploaded=0&downloaded=0&compact=1&left=120&key=test1241", url, ); } test "Escape url" { const test_string = "https://www.google.com/search?q=tracker+info_hash+escape&oq=tracker+" ++ "info_hash+escape&aqs=chrome..69i57j33i160l2.3049j0j7&sourceid=chrome&ie=UTF-8"; const expected = "https%3A%2F%2Fwww.google.com%2Fsearch%3Fq%3Dtracker%2Binfo_hash%2B" ++ "escape%26oq%3Dtracker%2Binfo_hash%2Bescape%26aqs%3Dchrome..69i57j33i160l2.3049j0j7%26sourceid%3Dchrome%26ie%3DUTF-8"; var list = std.ArrayList(u8).init(testing.allocator); defer list.deinit(); try escapeSlice(list.writer(), test_string); testing.expectEqualStrings(expected, list.items); }
src/torrent_file.zig
export fn @"__x86.get_pc_thunk.bx"() void {} export fn _IO_stderr_() void {} export fn _IO_stdin_() void {} export fn _IO_stdout_() void {} export fn _Unwind_Find_FDE() void {} export fn ___brk_addr() void {} export fn __deregister_frame() void {} export fn __deregister_frame_info() void {} export fn __deregister_frame_info_bases() void {} export fn __divdi3() void {} export fn __frame_state_for() void {} export fn __memcpy_by2() void {} export fn __memcpy_by4() void {} export fn __memcpy_c() void {} export fn __memcpy_g() void {} export fn __mempcpy_by2() void {} export fn __mempcpy_by4() void {} export fn __mempcpy_byn() void {} export fn __memset_cc() void {} export fn __memset_ccn_by2() void {} export fn __memset_ccn_by4() void {} export fn __memset_cg() void {} export fn __memset_gcn_by2() void {} export fn __memset_gcn_by4() void {} export fn __memset_gg() void {} export fn __moddi3() void {} export fn __modify_ldt() void {} export fn __register_frame() void {} export fn __register_frame_info() void {} export fn __register_frame_info_bases() void {} export fn __register_frame_info_table() void {} export fn __register_frame_info_table_bases() void {} export fn __register_frame_table() void {} export fn __stpcpy_g() void {} export fn __strcat_c() void {} export fn __strcat_g() void {} export fn __strchr_c() void {} export fn __strchr_g() void {} export fn __strchrnul_c() void {} export fn __strchrnul_g() void {} export fn __strcmp_gg() void {} export fn __strcpy_g() void {} export fn __strcspn_cg() void {} export fn __strcspn_g() void {} export fn __strlen_g() void {} export fn __strncat_g() void {} export fn __strncmp_g() void {} export fn __strncpy_by2() void {} export fn __strncpy_by4() void {} export fn __strncpy_byn() void {} export fn __strncpy_gg() void {} export fn __strpbrk_cg() void {} export fn __strpbrk_g() void {} export fn __strrchr_c() void {} export fn __strrchr_g() void {} export fn __strspn_cg() void {} export fn __strspn_g() void {} export fn __strstr_cg() void {} export fn __strstr_g() void {} export fn __strtoq_internal() void {} export fn __strtouq_internal() void {} export fn __udivdi3() void {} export fn __umoddi3() void {} export fn __uname() void {} export fn atexit() void {} export fn gettid() void {} export fn res_init() void {} export fn scalbln() void {} export fn scalblnf() void {} export fn scalblnl() void {} export fn vm86() void {}
libc/dummy/c/i386.zig
const std = @import("std"); const util = @import("util.zig"); const data = @embedFile("../data/day16.txt"); const Input = struct { bits: std.DynamicBitSet = undefined, pub fn init(input_text: []const u8, allocator: std.mem.Allocator) !@This() { _ = allocator; var input = Input{}; errdefer input.deinit(); var lines = std.mem.tokenize(u8, input_text, "\r\n"); while (lines.next()) |line| { input.bits = try std.DynamicBitSet.initEmpty(allocator, line.len * 4); var i: usize = 0; while (i < line.len) : (i += 1) { const hexit: u4 = try parseInt(u4, line[i .. i + 1], 16); if ((hexit & 0b1000) != 0) input.bits.set(i * 4 + 0); if ((hexit & 0b0100) != 0) input.bits.set(i * 4 + 1); if ((hexit & 0b0010) != 0) input.bits.set(i * 4 + 2); if ((hexit & 0b0001) != 0) input.bits.set(i * 4 + 3); } } return input; } pub fn deinit(self: *@This()) void { self.bits.deinit(); _ = self; } }; const PacketType = enum(u3) { OpSum = 0, OpProduct = 1, OpMin = 2, OpMax = 3, Literal = 4, OpGreaterThan = 5, OpLessThan = 6, OpEqualTo = 7, }; fn readBits(comptime T: type, start_bit: *usize, bits: std.DynamicBitSet) !T { const int_type = switch (@typeInfo(T)) { .Int => T, .Enum => |info| info.tag_type, else => @compileError("expected enum or union type, found '" ++ @typeName(T) ++ "'"), }; const bit_count = @typeInfo(int_type).Int.bits; var i: usize = start_bit.*; const end_bit = i + bit_count; if (end_bit > bits.capacity()) { return error.OutOfRange; } start_bit.* += bit_count; // Special case for reading a single bit if (bit_count == 1) { return @as(int_type, if (bits.isSet(i)) 1 else 0); } var result_as_int: int_type = 0; while (i < end_bit) : (i += 1) { result_as_int = (result_as_int << 1) | @as(int_type, if (bits.isSet(i)) 1 else 0); } var result = switch (@typeInfo(T)) { .Int => result_as_int, .Enum => @intToEnum(T, result_as_int), else => @compileError("expected enum or union type, found '" ++ @typeName(T) ++ "'"), }; return result; } fn initPrefixSum(op: PacketType) i64 { return switch (op) { .OpSum => 0, .OpProduct => 1, .OpMin => std.math.maxInt(i64), .OpMax => std.math.minInt(i64), .OpGreaterThan => -1, .OpLessThan => -1, .OpEqualTo => -1, else => unreachable, }; } fn applyPrefixSum(op: PacketType, sum: *i64, val: i64) void { sum.* = switch (op) { .OpSum => sum.* + val, .OpProduct => sum.* * val, .OpMin => std.math.min(sum.*, val), .OpMax => std.math.max(sum.*, val), .OpGreaterThan => if (sum.* == -1) val else if (sum.* > val) @as(i64, 1) else @as(i64, 0), .OpLessThan => if (sum.* == -1) val else if (sum.* < val) @as(i64, 1) else @as(i64, 0), .OpEqualTo => if (sum.* == -1) val else if (sum.* == val) @as(i64, 1) else @as(i64, 0), else => unreachable, }; } fn processPacket(bits: std.DynamicBitSet, next_bit: *usize, version_sum: *i64) anyerror!i64 { const version = try readBits(u3, next_bit, bits); version_sum.* += version; const type_id = try readBits(PacketType, next_bit, bits); switch (type_id) { .Literal => { var value: i64 = 0; const continue_mask: u5 = 0b10000; while (true) { const literal_block = try readBits(u5, next_bit, bits); value <<= 4; value |= @as(i64, literal_block & ~continue_mask); if ((literal_block & continue_mask) == 0) { //print("{d} ", .{value}); return value; } } }, else => { var sum: i64 = initPrefixSum(type_id); const length_type_id = try readBits(u1, next_bit, bits); //print("{s}(", .{@tagName(type_id)}); if (length_type_id == 0) { const bit_count = try readBits(u15, next_bit, bits); const end_bit = next_bit.* + bit_count; while (next_bit.* < end_bit) { applyPrefixSum(type_id, &sum, try processPacket(bits, next_bit, version_sum)); } } else { const packet_count: usize = try readBits(u11, next_bit, bits); var packet: usize = 0; while (packet < packet_count) : (packet += 1) { applyPrefixSum(type_id, &sum, try processPacket(bits, next_bit, version_sum)); } } //print(")", .{}); return sum; }, } } fn part1(input: Input) i64 { var next_bit: usize = 0; var version_sum: i64 = 0; _ = processPacket(input.bits, &next_bit, &version_sum) catch unreachable; return version_sum; } fn part2(input: Input) i64 { var next_bit: usize = 0; var version_sum: i64 = 0; return processPacket(input.bits, &next_bit, &version_sum) catch unreachable; } const test_data = \\D2FE28 ; const part1_test_solution: ?i64 = 6; const part1_solution: ?i64 = 847; const part2_test_solution: ?i64 = 2021; const part2_solution: ?i64 = 333794664059; // Just boilerplate below here, nothing to see fn testPart1() !void { var test_input = try Input.init(test_data, std.testing.allocator); defer test_input.deinit(); if (part1_test_solution) |solution| { try std.testing.expectEqual(solution, part1(test_input)); } var test_input2 = try Input.init("8A004A801A8002F478", std.testing.allocator); defer test_input2.deinit(); try std.testing.expectEqual(@as(i64, 16), part1(test_input2)); var test_input3 = try Input.init("620080001611562C8802118E34", std.testing.allocator); defer test_input3.deinit(); try std.testing.expectEqual(@as(i64, 12), part1(test_input3)); var test_input4 = try Input.init("C0015000016115A2E0802F182340", std.testing.allocator); defer test_input4.deinit(); try std.testing.expectEqual(@as(i64, 23), part1(test_input4)); var test_input5 = try Input.init("A0016C880162017C3686B18A3D4780", std.testing.allocator); defer test_input5.deinit(); try std.testing.expectEqual(@as(i64, 31), part1(test_input5)); var timer = try std.time.Timer.start(); var input = try Input.init(data, std.testing.allocator); defer input.deinit(); if (part1_solution) |solution| { try std.testing.expectEqual(solution, part1(input)); print("part1 took {d:9.3}ms\n", .{@intToFloat(f64, timer.lap()) / 1000000.0}); } } fn testPart2() !void { var test_input = try Input.init(test_data, std.testing.allocator); defer test_input.deinit(); if (part2_test_solution) |solution| { try std.testing.expectEqual(solution, part2(test_input)); } var test_input2 = try Input.init("C200B40A82", std.testing.allocator); defer test_input2.deinit(); try std.testing.expectEqual(@as(i64, 3), part2(test_input2)); var test_input3 = try Input.init("04005AC33890", std.testing.allocator); defer test_input3.deinit(); try std.testing.expectEqual(@as(i64, 54), part2(test_input3)); var test_input4 = try Input.init("880086C3E88112", std.testing.allocator); defer test_input4.deinit(); try std.testing.expectEqual(@as(i64, 7), part2(test_input4)); var test_input5 = try Input.init("CE00C43D881120", std.testing.allocator); defer test_input5.deinit(); try std.testing.expectEqual(@as(i64, 9), part2(test_input5)); var test_input6 = try Input.init("D8005AC2A8F0", std.testing.allocator); defer test_input6.deinit(); try std.testing.expectEqual(@as(i64, 1), part2(test_input6)); var test_input7 = try Input.init("F600BC2D8F", std.testing.allocator); defer test_input7.deinit(); try std.testing.expectEqual(@as(i64, 0), part2(test_input7)); var test_input8 = try Input.init("9C005AC2F8F0", std.testing.allocator); defer test_input8.deinit(); try std.testing.expectEqual(@as(i64, 0), part2(test_input8)); var test_input9 = try Input.init("9C0141080250320F1802104A08", std.testing.allocator); defer test_input9.deinit(); try std.testing.expectEqual(@as(i64, 1), part2(test_input9)); var timer = try std.time.Timer.start(); var input = try Input.init(data, std.testing.allocator); defer input.deinit(); if (part2_solution) |solution| { try std.testing.expectEqual(solution, part2(input)); print("part2 took {d:9.3}ms\n", .{@intToFloat(f64, timer.lap()) / 1000000.0}); } } pub fn main() !void { try testPart1(); try testPart2(); } test "part1" { try testPart1(); } test "part2" { try testPart2(); } // Useful stdlib functions const tokenize = std.mem.tokenize; const split = std.mem.split; const parseInt = std.fmt.parseInt; const min = std.math.min; const max = std.math.max; const print = std.debug.print; const expect = std.testing.expect; const assert = std.debug.assert;
src/day16.zig
const std = @import("std"); const Builder = @import("std").build.Builder; const Target = @import("std").Target; const CrossTarget = @import("std").zig.CrossTarget; const builtin = @import("builtin"); pub fn build(b: *Builder) void { const wasiTarget = CrossTarget{ .cpu_arch = Target.Cpu.Arch.wasm32, .os_tag = Target.Os.Tag.wasi, }; // Soon we'll support other targets (riscv-uefi, et al.) const kernel_target = CrossTarget{ .cpu_arch = Target.Cpu.Arch.x86_64, .cpu_model = .baseline, .os_tag = Target.Os.Tag.uefi, .abi = Target.Abi.msvc, }; const kernel_binary: []const u8 = "bootx64"; const kernel_output_dir: []const u8 = "output/efi/boot"; const kernel_clang_target: []const u8 = "--target=x86_64-unknown-windows-msvc"; const rootfsOutputDir: []const u8 = "output/rootfs"; const tempOutputDir: []const u8 = "output/temp"; const mode = b.standardReleaseOptions(); const app_names = [_][]const u8{ "init", }; const apps_step = b.step("apps", "Build Userspace Apps"); { inline for (app_names) |app_name| { const app = b.addExecutable(app_name, "apps/" ++ app_name ++ "/main.zig"); app.setTarget(wasiTarget); // Due to a bug, we always have to use either `release-safe` or `debug` mode //app.setBuildMode(mode); app.setBuildMode(std.builtin.Mode.ReleaseSafe); app.setOutputDir(tempOutputDir); apps_step.dependOn(&app.step); } } const rootfs_step = b.step("rootfs", "Build Root Filesystem"); { // hack to always generate fresh rootfs rootfs_step.dependOn(&b.addSystemCommand(&[_][]const u8{"rm", "-rf", rootfsOutputDir}).step); rootfs_step.dependOn(&b.addSystemCommand(&[_][]const u8{"rsync", "-a", "rootfs_skel/", rootfsOutputDir}).step); rootfs_step.dependOn(apps_step); inline for (app_names) |app_name| { rootfs_step.dependOn(&b.addSystemCommand(&[_][]const u8{"cp", tempOutputDir ++ "/" ++ app_name ++ ".wasm", rootfsOutputDir ++ "/bin/" ++ app_name}).step); } } const initrd_step = b.step("initrd", "Build Initial Ramdisk"); { initrd_step.dependOn(rootfs_step); // hack to always generate fresh initrd initrd_step.dependOn(&b.addSystemCommand(&[_][]const u8{"rm", "-f", tempOutputDir ++ "/initrd.zip"}).step); // another hack //initrd_step.dependOn(&b.addSystemCommand(&[_][]const u8{"zip", "-x", "*.keepdir*", "-x", "**/*.keepdir*", "-r", tempOutputDir ++ "/initrd.zip", "."}).step); // invoke 'sh' to use chdir initrd_step.dependOn(&b.addSystemCommand(&[_][]const u8{"sh", "-c", "cd '" ++ rootfsOutputDir ++ "' && zip -x '*.keepdir*' -x '**/*.keepdir*' -9r '../../" ++ tempOutputDir ++ "/initrd.zip' ."}).step); } const kernel_step = b.step("kernel", "Build Kernel"); { const ucontext = b.addStaticLibrary("ucontext", null); const ucontext_arch = "kernel/libucontext/arch/" ++ @tagName(kernel_target.cpu_arch.?); ucontext.addIncludeDir("kernel"); ucontext.addIncludeDir("kernel/klibc"); ucontext.addIncludeDir("kernel/klibc/" ++ @tagName(kernel_target.cpu_arch.?)); ucontext.addIncludeDir("kernel/libucontext/arch/common"); ucontext.addCSourceFile("kernel/klibc/ucontext.c", &[_][]const u8{kernel_clang_target}); ucontext.addCSourceFile(ucontext_arch ++ "/makecontext.c", &[_][]const u8{kernel_clang_target}); ucontext.setTarget(CrossTarget{.cpu_arch = kernel_target.cpu_arch, .cpu_model = .baseline}); ucontext.setBuildMode(std.builtin.Mode.ReleaseSmall); // Needed because of undefined behavior. TODO FIXME. const ucontext_asm = b.addStaticLibrary("ucontext_asm", null); ucontext_asm.addIncludeDir("kernel"); ucontext_asm.addIncludeDir("kernel/klibc"); ucontext_asm.addIncludeDir("kernel/klibc/" ++ @tagName(kernel_target.cpu_arch.?)); ucontext_asm.addIncludeDir("kernel/libucontext/arch/common"); // This looks wrong, but works around a compiler bug. Don't change it. ucontext_asm.addCSourceFile(ucontext_arch ++ "/setcontext.S", &[_][]const u8{kernel_clang_target}); ucontext_asm.addCSourceFile(ucontext_arch ++ "/getcontext.S", &[_][]const u8{kernel_clang_target}); ucontext_asm.addCSourceFile(ucontext_arch ++ "/startcontext.S", &[_][]const u8{kernel_clang_target}); ucontext_asm.addCSourceFile(ucontext_arch ++ "/swapcontext.S", &[_][]const u8{kernel_clang_target}); ucontext_asm.setTarget(CrossTarget{.cpu_arch = kernel_target.cpu_arch, .cpu_model = .baseline}); ucontext_asm.setBuildMode(std.builtin.Mode.ReleaseSmall); // Needed because of undefined behavior. TODO FIXME. const wasm3 = b.addStaticLibrary("wasm3", null); wasm3.addIncludeDir("kernel"); wasm3.addIncludeDir("kernel/klibc"); wasm3.addIncludeDir("kernel/wasm3/source"); wasm3.addCSourceFile("kernel/wasm3_all.c", &[_][]const u8{kernel_clang_target}); wasm3.setTarget(CrossTarget{.cpu_arch = kernel_target.cpu_arch, .cpu_model = .baseline}); wasm3.setBuildMode(std.builtin.Mode.ReleaseSmall); // Needed because of undefined behavior. TODO FIXME. const ckern = b.addStaticLibrary("ckern", null); ckern.addIncludeDir("kernel"); ckern.addIncludeDir("kernel/klibc"); ckern.addCSourceFile("kernel/sanitytests.c", &[_][]const u8{kernel_clang_target}); ckern.setTarget(CrossTarget{.cpu_arch = kernel_target.cpu_arch, .cpu_model = .baseline}); ckern.setBuildMode(mode); const miniz = b.addStaticLibrary("miniz", null); miniz.addIncludeDir("kernel"); miniz.addIncludeDir("kernel/klibc"); miniz.addIncludeDir("kernel/miniz"); miniz.addCSourceFile("kernel/miniz/miniz.c", &[_][]const u8{kernel_clang_target}); miniz.setTarget(CrossTarget{.cpu_arch = kernel_target.cpu_arch, .cpu_model = .baseline}); miniz.setBuildMode(std.builtin.Mode.ReleaseSmall); // Needed because of undefined behavior. TODO FIXME. const exe = b.addExecutable(kernel_binary, "kernel/main.zig"); exe.addIncludeDir("kernel"); exe.addIncludeDir("kernel/klibc"); exe.addIncludeDir("kernel/klibc/" ++ @tagName(kernel_target.cpu_arch.?)); exe.setTarget(kernel_target); exe.setBuildMode(mode); exe.setOutputDir(kernel_output_dir); exe.linkLibrary(ucontext_asm); exe.linkLibrary(ucontext); exe.linkLibrary(wasm3); exe.linkLibrary(ckern); exe.linkLibrary(miniz); kernel_step.dependOn(&b.addSystemCommand(&[_][]const u8{"touch", "kernel/utsname_extra.h"}).step); kernel_step.dependOn(initrd_step); kernel_step.dependOn(&exe.step); } //const run_cmd = exe.run(); //run_cmd.step.dependOn(b.getInstallStep()); //const run_step = b.step("run", "Run the app"); //run_step.dependOn(&run_cmd.step); b.default_step.dependOn(kernel_step); }
build.zig
const std = @import("std"); const ascii = std.ascii; const debug = std.debug; const fmt = std.fmt; const io = std.io; const math = std.math; const mem = std.mem; const os = std.os; const testing = std.testing; pub const default_escapes = blk: { @setEvalBranchQuota(1000000); var res: []const Escape = &[_]Escape{}; var i: u8 = 0; while (i <= math.maxInt(u7)) : (i += 1) { switch (i) { '\\' => res = res ++ [_]Escape{.{ .escaped = "\\\\", .unescaped = "\\" }}, '\n' => res = res ++ [_]Escape{.{ .escaped = "\\n", .unescaped = "\n" }}, '\r' => res = res ++ [_]Escape{.{ .escaped = "\\r", .unescaped = "\r" }}, '\t' => res = res ++ [_]Escape{.{ .escaped = "\\t", .unescaped = "\t" }}, else => { if (ascii.isPrint(i)) continue; const escaped = fmt.comptimePrint("\\x{x:02}", .{i}); res = res ++ [_]Escape{.{ .escaped = escaped, .unescaped = &[_]u8{i} }}; }, } } break :blk res; }; pub const default = generate(default_escapes); pub const Escape = struct { escaped: []const u8, unescaped: []const u8, }; pub fn generate(comptime escapes: []const Escape) type { const find_replace_escaped = blk: { var res: []const Replacement = &[_]Replacement{}; for (escapes) |esc| res = res ++ [_]Replacement{.{ .find = esc.escaped, .replace = esc.unescaped }}; break :blk res; }; const find_replace_unescaped = blk: { var res: []const Replacement = &[_]Replacement{}; for (escapes) |esc| res = res ++ [_]Replacement{.{ .find = esc.unescaped, .replace = esc.escaped }}; break :blk res; }; return struct { pub fn EscapingWriter(comptime ChildWriter: type) type { return ReplacingWriter(find_replace_unescaped, ChildWriter); } pub fn escapingWriter(child_writer: anytype) EscapingWriter(@TypeOf(child_writer)) { return .{ .child_writer = child_writer }; } pub fn UnescapingWriter(comptime ChildWriter: type) type { return ReplacingWriter(find_replace_escaped, ChildWriter); } pub fn unescapingWriter(child_writer: anytype) UnescapingWriter(@TypeOf(child_writer)) { return .{ .child_writer = child_writer }; } pub fn EscapingReader(comptime ChildReader: type) type { return ReplacingReader(find_replace_unescaped, ChildReader); } pub fn escapingReader(child_reader: anytype) EscapingReader(@TypeOf(child_reader)) { return .{ .child_reader = child_reader }; } pub fn UnescapingReader(comptime ChildReader: type) type { return ReplacingReader(find_replace_escaped, ChildReader); } pub fn unescapingReader(child_reader: anytype) UnescapingReader(@TypeOf(child_reader)) { return .{ .child_reader = child_reader }; } pub fn escapeWrite(writer: anytype, str: []const u8) !void { var esc = escapingWriter(writer); try esc.writer().writeAll(str); try esc.finish(); } pub fn escapePrint(writer: anytype, comptime format: []const u8, args: anytype) !void { var esc = escapingWriter(writer); try esc.writer().print(format, args); try esc.finish(); } pub fn escapeAlloc(allocator: mem.Allocator, str: []const u8) ![]u8 { var res = std.ArrayList(u8).init(allocator); try escapeWrite(res.writer(), str); return res.toOwnedSlice(); } pub fn escapeFmt(value: anytype) Format(@TypeOf(value), .escape) { return .{ .value = value }; } pub fn unescapeWrite(writer: anytype, str: []const u8) !void { var esc = unescapingWriter(writer); try esc.writer().writeAll(str); try esc.finish(); } pub fn unescapePrint(writer: anytype, comptime format: []const u8, args: anytype) !void { var esc = unescapingWriter(writer); try esc.writer().print(format, args); try esc.finish(); } pub fn unescapeAlloc(allocator: mem.Allocator, str: []const u8) ![]u8 { var res = std.ArrayList(u8).init(allocator); try unescapeWrite(res.writer(), str); return res.toOwnedSlice(); } pub fn unescapeFmt(value: anytype) Format(@TypeOf(value), .unescape) { return .{ .value = value }; } pub fn Format(comptime T: type, comptime kind: enum { escape, unescape }) type { return struct { value: T, pub fn format( self: @This(), comptime fmt_str: []const u8, options: std.fmt.FormatOptions, writer: anytype, ) @TypeOf(writer).Error!void { var esc = switch (kind) { .escape => escapingWriter(writer), .unescape => unescapingWriter(writer), }; try fmt.formatType( self.value, fmt_str, options, esc.writer(), fmt.default_max_depth, ); try esc.finish(); } }; } }; } pub const Replacement = struct { find: []const u8, replace: []const u8, fn lessThan(_: void, a: Replacement, b: Replacement) bool { return mem.lessThan(u8, a.find, b.find); } }; fn startsWith(comptime replacements: []const Replacement, buf: []const u8) ?usize { inline for (replacements) |rep, i| { if (mem.startsWith(u8, buf, rep.find)) return i; } return null; } const State = struct { index: usize = 0, start: usize = 0, end: usize, }; /// replacements must be sorted. fn transion(replacements: []const Replacement, byte: u8, state: State) ?State { const start = for (replacements[state.start..state.end]) |rep, i| { const rest = rep.find[state.index..]; if (rest.len != 0 and rest[0] == byte) break state.start + i; } else return null; const end = for (replacements[start..state.end]) |rep, i| { const rest = rep.find[state.index..]; if (rest.len == 0 or rest[0] != byte) break start + i; } else state.end; return State{ .start = start, .end = end, .index = state.index + 1, }; } test "transion" { const replacements = [_]Replacement{ .{ .find = "bar", .replace = "baz" }, .{ .find = "baz", .replace = "stuff" }, .{ .find = "foo", .replace = "bar" }, }; try testing.expectEqual(@as(?State, State{ .index = 1, .start = 2, .end = 3 }), transion(&replacements, 'f', .{ .end = 3 })); try testing.expectEqual(@as(?State, State{ .index = 1, .start = 0, .end = 2 }), transion(&replacements, 'b', .{ .end = 3 })); try testing.expectEqual(@as(?State, State{ .index = 2, .start = 0, .end = 2 }), transion(&replacements, 'a', .{ .index = 1, .start = 0, .end = 2 })); try testing.expectEqual(@as(?State, State{ .index = 3, .start = 1, .end = 2 }), transion(&replacements, 'z', .{ .index = 2, .start = 0, .end = 2 })); } pub fn ReplacingWriter(comptime replacements: []const Replacement, comptime ChildWriter: type) type { @setEvalBranchQuota(1000000); comptime var replacements_sorted = replacements[0..replacements.len].*; std.sort.sort(Replacement, &replacements_sorted, {}, Replacement.lessThan); return struct { child_writer: ChildWriter, state: State = .{ .end = replacements.len }, pub const Error = switch (@typeInfo(ChildWriter)) { .Pointer => |info| info.child.Error, else => ChildWriter.Error, }; pub const Writer = io.Writer(*@This(), Error, write); pub fn writer(self: *@This()) Writer { return .{ .context = self }; } pub fn write(self: *@This(), bytes: []const u8) Error!usize { var i: usize = 0; while (i < bytes.len) { if (transion(&replacements_sorted, bytes[i], self.state)) |new| { self.state = new; i += 1; } else if (self.state.index == 0) { try self.child_writer.writeByte(bytes[i]); self.state = .{ .end = replacements_sorted.len }; i += 1; } else { try self.finish(); } } return bytes.len; } pub fn finish(self: *@This()) Error!void { defer self.state = .{ .end = replacements_sorted.len }; if (self.state.index == 0) return; const curr = replacements_sorted[self.state.start]; if (curr.find.len == self.state.index) { try self.child_writer.writeAll(curr.replace); } else { try self.child_writer.writeAll(curr.find[0..self.state.index]); } } }; } pub fn replacingWriter( comptime replacements: []const Replacement, child_writer: anytype, ) ReplacingWriter(replacements, @TypeOf(child_writer)) { return .{ .child_writer = child_writer }; } pub fn ReplacingReader(comptime replacements: []const Replacement, comptime ChildReader: type) type { return struct { const longest_find = blk: { var res: usize = 0; for (replacements) |r| res = math.max(r.find.len, res); break :blk res; }; child_reader: ChildReader, buf: [mem.page_size]u8 = undefined, start: usize = 0, end: usize = 0, leftovers: []const u8 = "", pub const Error = ChildReader.Error; pub const Reader = io.Reader(*@This(), Error, read); pub fn reader(self: *@This()) Reader { return .{ .context = self }; } pub fn read(self: *@This(), dest: []u8) Error!usize { const rest = self.buf[self.start..self.end]; if (rest.len < longest_find) { mem.copy(u8, &self.buf, rest); self.end -= self.start; self.start = 0; self.end += try self.child_reader.read(self.buf[self.start..]); } var fbs = io.fixedBufferStream(dest); // We might have leftovers from a replacement that didn't // quite finish. We need to make sure that gets written now. const l = fbs.write(self.leftovers) catch return 0; self.leftovers = self.leftovers[l..]; if (self.leftovers.len != 0) return l; var i: usize = self.start; while (i < self.end) { if (startsWith(replacements, self.buf[i..self.end])) |rep| { self.start += fbs.write(self.buf[self.start..i]) catch 0; if (self.start != i) break; i += replacements[rep].find.len; self.start = i; const replace = replacements[rep].replace; const res = fbs.write(replace) catch 0; if (replace.len != res) { self.leftovers = replace[res..]; break; } } else { i += 1; } } self.start += fbs.write(self.buf[self.start..i]) catch 0; return fbs.getWritten().len; } }; } pub fn replacingReader( comptime replacements: []const Replacement, child_reader: anytype, ) ReplacingReader(replacements, @TypeOf(child_reader)) { return .{ .child_reader = child_reader }; } fn testReplacingStreams(comptime replacements: []const Replacement, input: []const u8, expect: []const u8) !void { var buf: [mem.page_size]u8 = undefined; var fbs = io.fixedBufferStream(&buf); var replacing_writer = replacingWriter(replacements, fbs.writer()); replacing_writer.writer().writeAll(input) catch unreachable; replacing_writer.finish() catch unreachable; try testing.expectEqualStrings(expect, fbs.getWritten()); var fbs2 = io.fixedBufferStream(input); var replacing_reader = replacingReader(replacements, fbs2.reader()); const res = replacing_reader.reader().readAll(&buf) catch unreachable; try testing.expectEqualStrings(expect, buf[0..res]); } test "replacingWriter" { const replacements = [_]Replacement{ .{ .find = "baz", .replace = "stuff" }, .{ .find = "foo", .replace = "bar" }, .{ .find = "bar", .replace = "baz" }, }; try testReplacingStreams(&replacements, "abcd", "abcd"); try testReplacingStreams(&replacements, "abfoocd", "abbarcd"); try testReplacingStreams(&replacements, "abbarcd", "abbazcd"); try testReplacingStreams(&replacements, "abbazcd", "abstuffcd"); try testReplacingStreams(&replacements, "foobarbaz", "barbazstuff"); try testReplacingStreams(&replacements, "bazbarfoo", "stuffbazbar"); try testReplacingStreams(&replacements, "baz bar foo", "stuff baz bar"); } pub fn splitEscaped(buffer: []const u8, esc: []const u8, delimiter: []const u8) EscapedSplitter { std.debug.assert(delimiter.len != 0); return EscapedSplitter{ .index = 0, .buffer = buffer, .escape = esc, .delimiter = delimiter, }; } pub const EscapedSplitter = struct { buffer: []const u8, index: ?usize, escape: []const u8, delimiter: []const u8, /// Returns a slice of the next field, or null if splitting is complete. pub fn next(self: *EscapedSplitter) ?[]const u8 { const start = self.index orelse return null; var start2 = start; const end = blk: { while (true) { if (mem.indexOfPos(u8, self.buffer, start2, self.delimiter)) |delim_start| { if (delim_start >= self.escape.len and mem.eql(u8, self.buffer[delim_start - self.escape.len .. delim_start], self.escape)) { start2 = delim_start + self.escape.len; continue; } self.index = delim_start + self.delimiter.len; break :blk delim_start; } else { self.index = null; break :blk self.buffer.len; } } unreachable; }; return self.buffer[start..end]; } /// Returns a slice of the remaining bytes. Does not affect iterator state. pub fn rest(self: EscapedSplitter) []const u8 { const end = self.buffer.len; const start = self.index orelse end; return self.buffer[start..end]; } }; test "splitEscaped" { var it = splitEscaped("abc|def||ghi\\|jkl", "\\", "|"); try testing.expectEqualStrings("abc", it.next().?); try testing.expectEqualStrings("def", it.next().?); try testing.expectEqualStrings("", it.next().?); try testing.expectEqualStrings("ghi\\|jkl", it.next().?); try testing.expect(it.next() == null); it = splitEscaped("", "\\", "|"); try testing.expectEqualStrings("", it.next().?); try testing.expect(it.next() == null); it = splitEscaped("|", "\\", "|"); try testing.expectEqualStrings("", it.next().?); try testing.expectEqualStrings("", it.next().?); try testing.expect(it.next() == null); it = splitEscaped("hello", "\\", " "); try testing.expectEqualStrings(it.next().?, "hello"); try testing.expect(it.next() == null); it = splitEscaped("\\,\\,,", "\\", ","); try testing.expectEqualStrings(it.next().?, "\\,\\,"); try testing.expectEqualStrings(it.next().?, ""); try testing.expect(it.next() == null); } test "splitEscaped (multibyte)" { var it = splitEscaped("a, b ,, c, d, e\\\\, f", "\\\\", ", "); try testing.expectEqualStrings(it.next().?, "a"); try testing.expectEqualStrings(it.next().?, "b ,"); try testing.expectEqualStrings(it.next().?, "c"); try testing.expectEqualStrings(it.next().?, "d"); try testing.expectEqualStrings(it.next().?, "e\\\\, f"); try testing.expect(it.next() == null); }
src/common/escape.zig
const std = @import("std"); const print = std.debug.print; const util = @import("util.zig"); const gpa = util.gpa; const data = @embedFile("../data/day24.txt"); const Type = enum { // First the real instructions. inp, add, mul, div, mod, eql, // Then we encode a different instruction for the variants that take an imm. add_imm, mul_imm, div_imm, mod_imm, eql_imm, }; const Instruction = struct { ty : Type, a : i64, b : i64, pub fn init(ty : Type, a : i64, b : i64) @This() { return @This() { .ty = ty, .a = a, .b = b, }; } }; const Program = struct { instructions : std.ArrayList(Instruction), pub fn init(input : []const u8, allocator : *std.mem.Allocator) !@This() { var me = @This() { .instructions = std.ArrayList(Instruction).init(allocator), }; var lines = std.mem.tokenize(input, "\r\n"); while (lines.next()) |line| { var tokens = std.mem.tokenize(line, " "); const instruction = tokens.next().?; var ty : Type = undefined; if (std.mem.eql(u8, instruction, "inp")) { ty = Type.inp; } else if (std.mem.eql(u8, instruction, "add")) { ty = Type.add; } else if (std.mem.eql(u8, instruction, "mul")) { ty = Type.mul; } else if (std.mem.eql(u8, instruction, "div")) { ty = Type.div; } else if (std.mem.eql(u8, instruction, "mod")) { ty = Type.mod; } else if (std.mem.eql(u8, instruction, "eql")) { ty = Type.eql; } else { unreachable; } // The first is always a register. const a = tokens.next().?[0] - 'w'; var b : i64 = undefined; if (ty != Type.inp) { const bStr = tokens.next().?; switch (bStr[0]) { 'w'...'z' => b = bStr[0] - 'w', else => { b = try std.fmt.parseInt(i64, bStr, 10); // Also convert our instruction into the imm form. switch (ty) { Type.add => ty = Type.add_imm, Type.mul => ty = Type.mul_imm, Type.div => ty = Type.div_imm, Type.mod => ty = Type.mod_imm, Type.eql => ty = Type.eql_imm, else => unreachable, } }, } } try me.instructions.append(Instruction.init(ty, a, b)); } return me; } pub fn deinit(me : @This()) void { me.instructions.deinit(); } const State = struct { registers : [4]i64, index : usize, }; pub fn part1(me : *const @This(), input : [14]u8, map : *std.AutoHashMap(i64, State)) bool { var inputIndex : u8 = 0; var registers = [_]i64{0} ** 4; for (me.instructions.items) |instruction| { const a = instruction.a; const b = instruction.b; switch (instruction.ty) { Type.inp => { registers[@intCast(usize, @intCast(usize, a))] = input[inputIndex]; inputIndex += 1; }, Type.add => registers[@intCast(usize, a)] += registers[@intCast(usize, b)], Type.mul => registers[@intCast(usize, a)] *= registers[@intCast(usize, b)], Type.div => registers[@intCast(usize, a)] = @divTrunc(registers[@intCast(usize, a)], registers[@intCast(usize, b)]), Type.mod => registers[@intCast(usize, a)] = @mod(registers[@intCast(usize, a)], registers[@intCast(usize, b)]), Type.eql => registers[@intCast(usize, a)] = if (registers[@intCast(usize, a)] == registers[@intCast(usize, b)]) 1 else 0, Type.add_imm => registers[@intCast(usize, a)] += b, Type.mul_imm => registers[@intCast(usize, a)] *= b, Type.div_imm => registers[@intCast(usize, a)] = @divTrunc(registers[@intCast(usize, a)], b), Type.mod_imm => registers[@intCast(usize, a)] = @mod(registers[@intCast(usize, a)], b), Type.eql_imm => registers[@intCast(usize, a)] = if (registers[@intCast(usize,a)] == b) 1 else 0, } print("{} {} {} [{} {} {} {}]\n", .{instruction.ty, a, b, registers[0], registers[1], registers[2], registers[3]}); } return registers['z' - 'w'] == 0; } }; pub fn main() !void { const program = try Program.init(data, gpa); defer program.deinit(); var input = [_]u8{1} ** 14; var map = std.AutoHashMap(i64, void).init(gpa); var discard = program.part1(input, &map); if (!discard) { unreachable; } // Best guess so far was 99999952878116 while (!program.part1(input, &map)) { var index : u8 = 14; while (index > 0) : (index -= 1) { if (input[index - 1] == 1) { input[index - 1] = 9; continue; } input[index - 1] -= 1; break; } } }
src/day24.zig
const std = @import("std"); const os = std.os; const net = std.net; const testing = std.testing; const assert = std.debug.assert; const known_folders = @import("known-folders"); pub const known_folders_config = .{ .xdg_on_mac = true, }; pub const TransportKind = enum { un_socket, }; pub const max_packet_size: usize = 1024 * 16; pub const max_method_size: usize = 1024; pub const max_message_size: usize = max_packet_size; const max_connect_retries = 50; const connect_retry_delay = std.time.ns_per_ms * 5; const listen_socket_backlog = 10; pub fn bindUnixSocket(address: *net.Address) !os.socket_t { const socket = try os.socket( os.AF_UNIX, os.SOCK_SEQPACKET | os.SOCK_CLOEXEC, os.PF_UNIX, ); errdefer os.closeSocket(socket); try os.bind(socket, &address.any, address.getOsSockLen()); try os.listen(socket, listen_socket_backlog); return socket; } pub fn connectToUnixSocket(address: *net.Address) !os.socket_t { const socket = try os.socket( os.AF_UNIX, os.SOCK_SEQPACKET | os.SOCK_CLOEXEC, os.PF_UNIX, ); errdefer os.closeSocket(socket); var connect_retries: u8 = max_connect_retries; while (true) { os.connect(socket, &address.any, address.getOsSockLen()) catch |err| switch (err) { error.ConnectionRefused, error.FileNotFound => { // If the server is not yet listening, wait a bit. if (connect_retries == 0) return err; std.time.sleep(connect_retry_delay); connect_retries -= 1; continue; }, else => return err, }; break; } return socket; } /// Caller owns the memory. pub fn pathForUnixSocket(ally: *std.mem.Allocator) ![]u8 { const runtime_dir = (try known_folders.getPath( ally, .runtime, )) orelse (try known_folders.getPath( ally, .app_menu, )) orelse return error.NoRuntimeDirectory; defer ally.free(runtime_dir); const subpath = "kisa"; var path_builder = std.ArrayList(u8).init(ally); errdefer path_builder.deinit(); try path_builder.appendSlice(runtime_dir); try path_builder.append(std.fs.path.sep); try path_builder.appendSlice(subpath); std.fs.makeDirAbsolute(path_builder.items) catch |err| switch (err) { error.PathAlreadyExists => {}, else => return err, }; const filename = try std.fmt.allocPrint(ally, "{d}", .{os.linux.getpid()}); defer ally.free(filename); try path_builder.append(std.fs.path.sep); try path_builder.appendSlice(filename); std.fs.deleteFileAbsolute(path_builder.items) catch |err| switch (err) { error.FileNotFound => {}, else => return err, }; return path_builder.toOwnedSlice(); } /// Caller owns the memory. pub fn addressForUnixSocket(ally: *std.mem.Allocator, path: []const u8) !*net.Address { const address = try ally.create(net.Address); errdefer ally.destroy(address); address.* = try net.Address.initUnix(path); return address; } pub const CommunicationResources = union(TransportKind) { un_socket: struct { socket: os.socket_t, }, const Self = @This(); pub fn initWithUnixSocket(socket: os.socket_t) Self { return Self{ .un_socket = .{ .socket = socket } }; } }; /// `CommunicationContainer` must be a container which has `comms` field /// of type `CommunicationResources`. pub fn CommunicationMixin(comptime CommunicationContainer: type) type { return struct { const Self = CommunicationContainer; pub fn initWithUnixSocket(socket: os.socket_t) Self { return Self{ .comms = CommunicationResources.initWithUnixSocket(socket) }; } pub fn deinitComms(self: Self) void { switch (self.comms) { .un_socket => |s| { os.closeSocket(s.socket); }, } } // TODO: allow the caller to pass `packet_buf`. /// Sends a message, `message` must implement `generate` receiving a buffer and putting /// []u8 content into it. pub fn send(self: Self, message: anytype) !void { switch (self.comms) { .un_socket => |s| { var packet_buf: [max_packet_size]u8 = undefined; const packet = try message.generate(&packet_buf); const bytes_sent = try os.send(s.socket, packet, 0); assert(packet.len == bytes_sent); }, } } /// Reads a message of type `Message` with memory stored inside `out_buf`, `Message` must /// implement `parse` taking a buffer and a string, returning `Message` object. pub fn recv(self: Self, comptime Message: type, out_buf: []u8) !?Message { var packet_buf: [max_packet_size]u8 = undefined; if (try self.readPacket(&packet_buf)) |packet| { return try Message.parse(out_buf, packet); } else { return null; } } /// Returns the slice with the length of a received packet. pub fn readPacket(self: Self, buf: []u8) !?[]u8 { switch (self.comms) { .un_socket => |s| { const bytes_read = try os.recv(s.socket, buf, 0); if (bytes_read == 0) return null; if (buf.len == bytes_read) return error.MessageTooBig; return buf[0..bytes_read]; }, } } }; } pub const FdType = enum { /// Listens for incoming client connections to the server. listen_socket, /// Used for communication between client and server. connection_socket, }; pub const WatcherFd = struct { /// Native to the OS structure which is used for polling. pollfd: os.pollfd, /// Metadata for identifying the type of a file descriptor. ty: FdType, /// External identifier which is interpreted by the user of this API. id: u32, }; pub const Watcher = struct { ally: *std.mem.Allocator, /// Array of file descriptor data. Must not be modified directly, only with provided API. fds: std.MultiArrayList(WatcherFd) = std.MultiArrayList(WatcherFd){}, /// `poll` call can return several events at a time, this is their total count per call. pending_events_count: usize = 0, /// When `poll` returns several events, this cursor is used for subsequent searches /// inside `pollfd` array. pending_events_cursor: usize = 0, const Self = @This(); const Result = struct { fd: os.fd_t, id: u32, ty: FdType, fd_index: usize }; const PollResult = union(enum) { success: Result, err: struct { id: u32 }, }; pub fn init(ally: *std.mem.Allocator) Self { return Self{ .ally = ally }; } pub fn deinit(self: *Self) void { for (self.fds.items(.pollfd)) |pollfd| os.close(pollfd.fd); self.fds.deinit(self.ally); } /// Adds listen socket which is used for listening for other sockets' connections. pub fn addListenSocket(self: *Self, fd: os.fd_t, id: u32) !void { try self.addFd(fd, os.POLLIN, .listen_socket, id); } /// Adds connection socket which is used for communication between server and client. pub fn addConnectionSocket(self: *Self, fd: os.fd_t, id: u32) !void { try self.addFd(fd, os.POLLIN, .connection_socket, id); } pub fn findFileDescriptor(self: Self, id: u32) ?Result { for (self.fds.items(.id)) |fds_id, idx| { if (fds_id == id) { const pollfds = self.fds.items(.pollfd); const tys = self.fds.items(.ty); return Result{ .fd = pollfds[idx].fd, .id = id, .ty = tys[idx], .fd_index = idx, }; } } return null; } /// Removes any file descriptor with `id`, `id` must exist in the current /// array of ids. pub fn removeFileDescriptor(self: *Self, id: u32) void { for (self.fds.items(.id)) |fds_id, idx| { if (fds_id == id) { self.removeFd(idx); return; } } } fn addFd(self: *Self, fd: os.fd_t, events: i16, ty: FdType, id: u32) !void { // Only add ready-for-reading notifications with current assumptions of `pollReadable`. assert(events == os.POLLIN); // Ensure the `id` is unique across all elements. for (self.fds.items(.id)) |existing_id| assert(id != existing_id); try self.fds.append(self.ally, .{ .pollfd = os.pollfd{ .fd = fd, .events = events, .revents = 0, }, .ty = ty, .id = id, }); } fn removeFd(self: *Self, index: usize) void { os.close(self.fds.items(.pollfd)[index].fd); self.fds.swapRemove(index); } /// Returns a readable file descriptor or `null` if timeout has expired. If timeout is -1, /// always returns non-null result. Assumes that we don't have any other descriptors /// other than readable and that this will block if no readable file descriptors are /// available. pub fn pollReadable(self: *Self, timeout: i32) !?PollResult { if ((try self.poll(timeout)) == 0) return null; const pollfds = self.fds.items(.pollfd); const ids = self.fds.items(.id); const tys = self.fds.items(.ty); while (self.pending_events_cursor < pollfds.len) : (self.pending_events_cursor += 1) { const revents = pollfds[self.pending_events_cursor].revents; if (revents != 0) { self.pending_events_count -= 1; if (revents & (os.POLLERR | os.POLLHUP | os.POLLNVAL) != 0) { // `pollfd` is removed by swapping current one with the last one, so the cursor // stays the same. const result = PollResult{ .err = .{ .id = ids[self.pending_events_cursor], } }; self.removeFd(self.pending_events_cursor); return result; } else if (revents & os.POLLIN != 0) { const result = PollResult{ .success = .{ .fd = pollfds[self.pending_events_cursor].fd, .id = ids[self.pending_events_cursor], .ty = tys[self.pending_events_cursor], .fd_index = self.pending_events_cursor, } }; self.pending_events_cursor += 1; return result; } } } unreachable; } /// Fills current `fds` array with result events which can be inspected. fn poll(self: *Self, timeout: i32) !usize { if (self.pending_events_count == 0) { self.pending_events_count = try os.poll(self.fds.items(.pollfd), timeout); self.pending_events_cursor = 0; } return self.pending_events_count; } }; const MyContainer = struct { comms: CommunicationResources, usingnamespace CommunicationMixin(@This()); }; const MyMessage = struct { content: []u8, const Self = @This(); fn generate(message: anytype, out_buf: []u8) ![]u8 { _ = message; const str = "generated message"; std.mem.copy(u8, out_buf, str); return out_buf[0..str.len]; } fn parse(out_buf: []u8, string: []const u8) !Self { _ = string; const str = "parsed message"; std.mem.copy(u8, out_buf, str); return Self{ .content = out_buf[0..str.len] }; } }; test "transport/fork1: communication via un_socket" { const path = try pathForUnixSocket(testing.allocator); defer testing.allocator.free(path); const address = try addressForUnixSocket(testing.allocator, path); defer testing.allocator.destroy(address); const pid = try os.fork(); if (pid == 0) { const listen_socket = try bindUnixSocket(address); const accepted_socket = try os.accept(listen_socket, null, null, 0); const server = MyContainer.initWithUnixSocket(accepted_socket); var buf: [256]u8 = undefined; const message = try server.recv(MyMessage, &buf); std.debug.assert(message != null); } else { const client = MyContainer.initWithUnixSocket(try connectToUnixSocket(address)); const message = MyMessage{ .content = undefined }; try client.send(message); } } test "transport/fork2: client and server both poll events with watcher" { const path = try pathForUnixSocket(testing.allocator); defer testing.allocator.free(path); const address = try addressForUnixSocket(testing.allocator, path); defer testing.allocator.destroy(address); const client_message = "hello from client"; const pid = try os.fork(); if (pid == 0) { // Server const listen_socket = try bindUnixSocket(address); var watcher = Watcher.init(testing.allocator); defer watcher.deinit(); try watcher.addListenSocket(listen_socket, 0); var cnt: u8 = 3; while (cnt > 0) : (cnt -= 1) { switch ((try watcher.pollReadable(-1)).?) { .success => |polled_data| { switch (polled_data.ty) { .listen_socket => { const accepted_socket = try os.accept(polled_data.fd, null, null, 0); try watcher.addConnectionSocket(accepted_socket, 1); const bytes_sent = try os.send(accepted_socket, "1", 0); try testing.expectEqual(@as(usize, 1), bytes_sent); }, .connection_socket => { var buf: [256]u8 = undefined; const bytes_read = try os.recv(polled_data.fd, &buf, 0); if (bytes_read != 0) { try testing.expectEqualStrings(client_message, buf[0..bytes_read]); } else { // This should have been handled by POLLHUP event and union is `err`. unreachable; } }, } }, .err => {}, } } } else { // Client const message = try std.fmt.allocPrint(testing.allocator, client_message, .{}); defer testing.allocator.free(message); const socket = try connectToUnixSocket(address); var watcher = Watcher.init(testing.allocator); defer watcher.deinit(); try watcher.addConnectionSocket(socket, 0); switch ((try watcher.pollReadable(-1)).?) { .success => |polled_data| { var buf: [256]u8 = undefined; const bytes_read = try os.recv(polled_data.fd, &buf, 0); try testing.expectEqualStrings("1", buf[0..bytes_read]); }, .err => unreachable, } const bytes_sent = try os.send(socket, message, 0); try testing.expectEqual(message.len, bytes_sent); } }
src/transport.zig
const std = @import("std"); const mem = std.mem; pub const Kind = enum { L, T, V, LV, LVT, }; allocator: *mem.Allocator, map: std.AutoHashMap(u21, Kind), const HangulMap = @This(); pub fn init(allocator: *mem.Allocator) !HangulMap { var instance = HangulMap{ .allocator = allocator, .map = std.AutoHashMap(u21, Kind).init(allocator), }; var index: u21 = 0; index = 0x1100; while (index <= 0x115F) : (index += 1) { try instance.map.put(index, .L); } index = 0xA960; while (index <= 0xA97C) : (index += 1) { try instance.map.put(index, .L); } index = 0x1160; while (index <= 0x11A7) : (index += 1) { try instance.map.put(index, .V); } index = 0xD7B0; while (index <= 0xD7C6) : (index += 1) { try instance.map.put(index, .V); } index = 0x11A8; while (index <= 0x11FF) : (index += 1) { try instance.map.put(index, .T); } index = 0xD7CB; while (index <= 0xD7FB) : (index += 1) { try instance.map.put(index, .T); } try instance.map.put(0xAC00, .LV); try instance.map.put(0xAC1C, .LV); try instance.map.put(0xAC38, .LV); try instance.map.put(0xAC54, .LV); try instance.map.put(0xAC70, .LV); try instance.map.put(0xAC8C, .LV); try instance.map.put(0xACA8, .LV); try instance.map.put(0xACC4, .LV); try instance.map.put(0xACE0, .LV); try instance.map.put(0xACFC, .LV); try instance.map.put(0xAD18, .LV); try instance.map.put(0xAD34, .LV); try instance.map.put(0xAD50, .LV); try instance.map.put(0xAD6C, .LV); try instance.map.put(0xAD88, .LV); try instance.map.put(0xADA4, .LV); try instance.map.put(0xADC0, .LV); try instance.map.put(0xADDC, .LV); try instance.map.put(0xADF8, .LV); try instance.map.put(0xAE14, .LV); try instance.map.put(0xAE30, .LV); try instance.map.put(0xAE4C, .LV); try instance.map.put(0xAE68, .LV); try instance.map.put(0xAE84, .LV); try instance.map.put(0xAEA0, .LV); try instance.map.put(0xAEBC, .LV); try instance.map.put(0xAED8, .LV); try instance.map.put(0xAEF4, .LV); try instance.map.put(0xAF10, .LV); try instance.map.put(0xAF2C, .LV); try instance.map.put(0xAF48, .LV); try instance.map.put(0xAF64, .LV); try instance.map.put(0xAF80, .LV); try instance.map.put(0xAF9C, .LV); try instance.map.put(0xAFB8, .LV); try instance.map.put(0xAFD4, .LV); try instance.map.put(0xAFF0, .LV); try instance.map.put(0xB00C, .LV); try instance.map.put(0xB028, .LV); try instance.map.put(0xB044, .LV); try instance.map.put(0xB060, .LV); try instance.map.put(0xB07C, .LV); try instance.map.put(0xB098, .LV); try instance.map.put(0xB0B4, .LV); try instance.map.put(0xB0D0, .LV); try instance.map.put(0xB0EC, .LV); try instance.map.put(0xB108, .LV); try instance.map.put(0xB124, .LV); try instance.map.put(0xB140, .LV); try instance.map.put(0xB15C, .LV); try instance.map.put(0xB178, .LV); try instance.map.put(0xB194, .LV); try instance.map.put(0xB1B0, .LV); try instance.map.put(0xB1CC, .LV); try instance.map.put(0xB1E8, .LV); try instance.map.put(0xB204, .LV); try instance.map.put(0xB220, .LV); try instance.map.put(0xB23C, .LV); try instance.map.put(0xB258, .LV); try instance.map.put(0xB274, .LV); try instance.map.put(0xB290, .LV); try instance.map.put(0xB2AC, .LV); try instance.map.put(0xB2C8, .LV); try instance.map.put(0xB2E4, .LV); try instance.map.put(0xB300, .LV); try instance.map.put(0xB31C, .LV); try instance.map.put(0xB338, .LV); try instance.map.put(0xB354, .LV); try instance.map.put(0xB370, .LV); try instance.map.put(0xB38C, .LV); try instance.map.put(0xB3A8, .LV); try instance.map.put(0xB3C4, .LV); try instance.map.put(0xB3E0, .LV); try instance.map.put(0xB3FC, .LV); try instance.map.put(0xB418, .LV); try instance.map.put(0xB434, .LV); try instance.map.put(0xB450, .LV); try instance.map.put(0xB46C, .LV); try instance.map.put(0xB488, .LV); try instance.map.put(0xB4A4, .LV); try instance.map.put(0xB4C0, .LV); try instance.map.put(0xB4DC, .LV); try instance.map.put(0xB4F8, .LV); try instance.map.put(0xB514, .LV); try instance.map.put(0xB530, .LV); try instance.map.put(0xB54C, .LV); try instance.map.put(0xB568, .LV); try instance.map.put(0xB584, .LV); try instance.map.put(0xB5A0, .LV); try instance.map.put(0xB5BC, .LV); try instance.map.put(0xB5D8, .LV); try instance.map.put(0xB5F4, .LV); try instance.map.put(0xB610, .LV); try instance.map.put(0xB62C, .LV); try instance.map.put(0xB648, .LV); try instance.map.put(0xB664, .LV); try instance.map.put(0xB680, .LV); try instance.map.put(0xB69C, .LV); try instance.map.put(0xB6B8, .LV); try instance.map.put(0xB6D4, .LV); try instance.map.put(0xB6F0, .LV); try instance.map.put(0xB70C, .LV); try instance.map.put(0xB728, .LV); try instance.map.put(0xB744, .LV); try instance.map.put(0xB760, .LV); try instance.map.put(0xB77C, .LV); try instance.map.put(0xB798, .LV); try instance.map.put(0xB7B4, .LV); try instance.map.put(0xB7D0, .LV); try instance.map.put(0xB7EC, .LV); try instance.map.put(0xB808, .LV); try instance.map.put(0xB824, .LV); try instance.map.put(0xB840, .LV); try instance.map.put(0xB85C, .LV); try instance.map.put(0xB878, .LV); try instance.map.put(0xB894, .LV); try instance.map.put(0xB8B0, .LV); try instance.map.put(0xB8CC, .LV); try instance.map.put(0xB8E8, .LV); try instance.map.put(0xB904, .LV); try instance.map.put(0xB920, .LV); try instance.map.put(0xB93C, .LV); try instance.map.put(0xB958, .LV); try instance.map.put(0xB974, .LV); try instance.map.put(0xB990, .LV); try instance.map.put(0xB9AC, .LV); try instance.map.put(0xB9C8, .LV); try instance.map.put(0xB9E4, .LV); try instance.map.put(0xBA00, .LV); try instance.map.put(0xBA1C, .LV); try instance.map.put(0xBA38, .LV); try instance.map.put(0xBA54, .LV); try instance.map.put(0xBA70, .LV); try instance.map.put(0xBA8C, .LV); try instance.map.put(0xBAA8, .LV); try instance.map.put(0xBAC4, .LV); try instance.map.put(0xBAE0, .LV); try instance.map.put(0xBAFC, .LV); try instance.map.put(0xBB18, .LV); try instance.map.put(0xBB34, .LV); try instance.map.put(0xBB50, .LV); try instance.map.put(0xBB6C, .LV); try instance.map.put(0xBB88, .LV); try instance.map.put(0xBBA4, .LV); try instance.map.put(0xBBC0, .LV); try instance.map.put(0xBBDC, .LV); try instance.map.put(0xBBF8, .LV); try instance.map.put(0xBC14, .LV); try instance.map.put(0xBC30, .LV); try instance.map.put(0xBC4C, .LV); try instance.map.put(0xBC68, .LV); try instance.map.put(0xBC84, .LV); try instance.map.put(0xBCA0, .LV); try instance.map.put(0xBCBC, .LV); try instance.map.put(0xBCD8, .LV); try instance.map.put(0xBCF4, .LV); try instance.map.put(0xBD10, .LV); try instance.map.put(0xBD2C, .LV); try instance.map.put(0xBD48, .LV); try instance.map.put(0xBD64, .LV); try instance.map.put(0xBD80, .LV); try instance.map.put(0xBD9C, .LV); try instance.map.put(0xBDB8, .LV); try instance.map.put(0xBDD4, .LV); try instance.map.put(0xBDF0, .LV); try instance.map.put(0xBE0C, .LV); try instance.map.put(0xBE28, .LV); try instance.map.put(0xBE44, .LV); try instance.map.put(0xBE60, .LV); try instance.map.put(0xBE7C, .LV); try instance.map.put(0xBE98, .LV); try instance.map.put(0xBEB4, .LV); try instance.map.put(0xBED0, .LV); try instance.map.put(0xBEEC, .LV); try instance.map.put(0xBF08, .LV); try instance.map.put(0xBF24, .LV); try instance.map.put(0xBF40, .LV); try instance.map.put(0xBF5C, .LV); try instance.map.put(0xBF78, .LV); try instance.map.put(0xBF94, .LV); try instance.map.put(0xBFB0, .LV); try instance.map.put(0xBFCC, .LV); try instance.map.put(0xBFE8, .LV); try instance.map.put(0xC004, .LV); try instance.map.put(0xC020, .LV); try instance.map.put(0xC03C, .LV); try instance.map.put(0xC058, .LV); try instance.map.put(0xC074, .LV); try instance.map.put(0xC090, .LV); try instance.map.put(0xC0AC, .LV); try instance.map.put(0xC0C8, .LV); try instance.map.put(0xC0E4, .LV); try instance.map.put(0xC100, .LV); try instance.map.put(0xC11C, .LV); try instance.map.put(0xC138, .LV); try instance.map.put(0xC154, .LV); try instance.map.put(0xC170, .LV); try instance.map.put(0xC18C, .LV); try instance.map.put(0xC1A8, .LV); try instance.map.put(0xC1C4, .LV); try instance.map.put(0xC1E0, .LV); try instance.map.put(0xC1FC, .LV); try instance.map.put(0xC218, .LV); try instance.map.put(0xC234, .LV); try instance.map.put(0xC250, .LV); try instance.map.put(0xC26C, .LV); try instance.map.put(0xC288, .LV); try instance.map.put(0xC2A4, .LV); try instance.map.put(0xC2C0, .LV); try instance.map.put(0xC2DC, .LV); try instance.map.put(0xC2F8, .LV); try instance.map.put(0xC314, .LV); try instance.map.put(0xC330, .LV); try instance.map.put(0xC34C, .LV); try instance.map.put(0xC368, .LV); try instance.map.put(0xC384, .LV); try instance.map.put(0xC3A0, .LV); try instance.map.put(0xC3BC, .LV); try instance.map.put(0xC3D8, .LV); try instance.map.put(0xC3F4, .LV); try instance.map.put(0xC410, .LV); try instance.map.put(0xC42C, .LV); try instance.map.put(0xC448, .LV); try instance.map.put(0xC464, .LV); try instance.map.put(0xC480, .LV); try instance.map.put(0xC49C, .LV); try instance.map.put(0xC4B8, .LV); try instance.map.put(0xC4D4, .LV); try instance.map.put(0xC4F0, .LV); try instance.map.put(0xC50C, .LV); try instance.map.put(0xC528, .LV); try instance.map.put(0xC544, .LV); try instance.map.put(0xC560, .LV); try instance.map.put(0xC57C, .LV); try instance.map.put(0xC598, .LV); try instance.map.put(0xC5B4, .LV); try instance.map.put(0xC5D0, .LV); try instance.map.put(0xC5EC, .LV); try instance.map.put(0xC608, .LV); try instance.map.put(0xC624, .LV); try instance.map.put(0xC640, .LV); try instance.map.put(0xC65C, .LV); try instance.map.put(0xC678, .LV); try instance.map.put(0xC694, .LV); try instance.map.put(0xC6B0, .LV); try instance.map.put(0xC6CC, .LV); try instance.map.put(0xC6E8, .LV); try instance.map.put(0xC704, .LV); try instance.map.put(0xC720, .LV); try instance.map.put(0xC73C, .LV); try instance.map.put(0xC758, .LV); try instance.map.put(0xC774, .LV); try instance.map.put(0xC790, .LV); try instance.map.put(0xC7AC, .LV); try instance.map.put(0xC7C8, .LV); try instance.map.put(0xC7E4, .LV); try instance.map.put(0xC800, .LV); try instance.map.put(0xC81C, .LV); try instance.map.put(0xC838, .LV); try instance.map.put(0xC854, .LV); try instance.map.put(0xC870, .LV); try instance.map.put(0xC88C, .LV); try instance.map.put(0xC8A8, .LV); try instance.map.put(0xC8C4, .LV); try instance.map.put(0xC8E0, .LV); try instance.map.put(0xC8FC, .LV); try instance.map.put(0xC918, .LV); try instance.map.put(0xC934, .LV); try instance.map.put(0xC950, .LV); try instance.map.put(0xC96C, .LV); try instance.map.put(0xC988, .LV); try instance.map.put(0xC9A4, .LV); try instance.map.put(0xC9C0, .LV); try instance.map.put(0xC9DC, .LV); try instance.map.put(0xC9F8, .LV); try instance.map.put(0xCA14, .LV); try instance.map.put(0xCA30, .LV); try instance.map.put(0xCA4C, .LV); try instance.map.put(0xCA68, .LV); try instance.map.put(0xCA84, .LV); try instance.map.put(0xCAA0, .LV); try instance.map.put(0xCABC, .LV); try instance.map.put(0xCAD8, .LV); try instance.map.put(0xCAF4, .LV); try instance.map.put(0xCB10, .LV); try instance.map.put(0xCB2C, .LV); try instance.map.put(0xCB48, .LV); try instance.map.put(0xCB64, .LV); try instance.map.put(0xCB80, .LV); try instance.map.put(0xCB9C, .LV); try instance.map.put(0xCBB8, .LV); try instance.map.put(0xCBD4, .LV); try instance.map.put(0xCBF0, .LV); try instance.map.put(0xCC0C, .LV); try instance.map.put(0xCC28, .LV); try instance.map.put(0xCC44, .LV); try instance.map.put(0xCC60, .LV); try instance.map.put(0xCC7C, .LV); try instance.map.put(0xCC98, .LV); try instance.map.put(0xCCB4, .LV); try instance.map.put(0xCCD0, .LV); try instance.map.put(0xCCEC, .LV); try instance.map.put(0xCD08, .LV); try instance.map.put(0xCD24, .LV); try instance.map.put(0xCD40, .LV); try instance.map.put(0xCD5C, .LV); try instance.map.put(0xCD78, .LV); try instance.map.put(0xCD94, .LV); try instance.map.put(0xCDB0, .LV); try instance.map.put(0xCDCC, .LV); try instance.map.put(0xCDE8, .LV); try instance.map.put(0xCE04, .LV); try instance.map.put(0xCE20, .LV); try instance.map.put(0xCE3C, .LV); try instance.map.put(0xCE58, .LV); try instance.map.put(0xCE74, .LV); try instance.map.put(0xCE90, .LV); try instance.map.put(0xCEAC, .LV); try instance.map.put(0xCEC8, .LV); try instance.map.put(0xCEE4, .LV); try instance.map.put(0xCF00, .LV); try instance.map.put(0xCF1C, .LV); try instance.map.put(0xCF38, .LV); try instance.map.put(0xCF54, .LV); try instance.map.put(0xCF70, .LV); try instance.map.put(0xCF8C, .LV); try instance.map.put(0xCFA8, .LV); try instance.map.put(0xCFC4, .LV); try instance.map.put(0xCFE0, .LV); try instance.map.put(0xCFFC, .LV); try instance.map.put(0xD018, .LV); try instance.map.put(0xD034, .LV); try instance.map.put(0xD050, .LV); try instance.map.put(0xD06C, .LV); try instance.map.put(0xD088, .LV); try instance.map.put(0xD0A4, .LV); try instance.map.put(0xD0C0, .LV); try instance.map.put(0xD0DC, .LV); try instance.map.put(0xD0F8, .LV); try instance.map.put(0xD114, .LV); try instance.map.put(0xD130, .LV); try instance.map.put(0xD14C, .LV); try instance.map.put(0xD168, .LV); try instance.map.put(0xD184, .LV); try instance.map.put(0xD1A0, .LV); try instance.map.put(0xD1BC, .LV); try instance.map.put(0xD1D8, .LV); try instance.map.put(0xD1F4, .LV); try instance.map.put(0xD210, .LV); try instance.map.put(0xD22C, .LV); try instance.map.put(0xD248, .LV); try instance.map.put(0xD264, .LV); try instance.map.put(0xD280, .LV); try instance.map.put(0xD29C, .LV); try instance.map.put(0xD2B8, .LV); try instance.map.put(0xD2D4, .LV); try instance.map.put(0xD2F0, .LV); try instance.map.put(0xD30C, .LV); try instance.map.put(0xD328, .LV); try instance.map.put(0xD344, .LV); try instance.map.put(0xD360, .LV); try instance.map.put(0xD37C, .LV); try instance.map.put(0xD398, .LV); try instance.map.put(0xD3B4, .LV); try instance.map.put(0xD3D0, .LV); try instance.map.put(0xD3EC, .LV); try instance.map.put(0xD408, .LV); try instance.map.put(0xD424, .LV); try instance.map.put(0xD440, .LV); try instance.map.put(0xD45C, .LV); try instance.map.put(0xD478, .LV); try instance.map.put(0xD494, .LV); try instance.map.put(0xD4B0, .LV); try instance.map.put(0xD4CC, .LV); try instance.map.put(0xD4E8, .LV); try instance.map.put(0xD504, .LV); try instance.map.put(0xD520, .LV); try instance.map.put(0xD53C, .LV); try instance.map.put(0xD558, .LV); try instance.map.put(0xD574, .LV); try instance.map.put(0xD590, .LV); try instance.map.put(0xD5AC, .LV); try instance.map.put(0xD5C8, .LV); try instance.map.put(0xD5E4, .LV); try instance.map.put(0xD600, .LV); try instance.map.put(0xD61C, .LV); try instance.map.put(0xD638, .LV); try instance.map.put(0xD654, .LV); try instance.map.put(0xD670, .LV); try instance.map.put(0xD68C, .LV); try instance.map.put(0xD6A8, .LV); try instance.map.put(0xD6C4, .LV); try instance.map.put(0xD6E0, .LV); try instance.map.put(0xD6FC, .LV); try instance.map.put(0xD718, .LV); try instance.map.put(0xD734, .LV); try instance.map.put(0xD750, .LV); try instance.map.put(0xD76C, .LV); try instance.map.put(0xD788, .LV); index = 0xAC01; while (index <= 0xAC1B) : (index += 1) { try instance.map.put(index, .LVT); } index = 0xAC1D; while (index <= 0xAC37) : (index += 1) { try instance.map.put(index, .LVT); } index = 0xAC39; while (index <= 0xAC53) : (index += 1) { try instance.map.put(index, .LVT); } index = 0xAC55; while (index <= 0xAC6F) : (index += 1) { try instance.map.put(index, .LVT); } index = 0xAC71; while (index <= 0xAC8B) : (index += 1) { try instance.map.put(index, .LVT); } index = 0xAC8D; while (index <= 0xACA7) : (index += 1) { try instance.map.put(index, .LVT); } index = 0xACA9; while (index <= 0xACC3) : (index += 1) { try instance.map.put(index, .LVT); } index = 0xACC5; while (index <= 0xACDF) : (index += 1) { try instance.map.put(index, .LVT); } index = 0xACE1; while (index <= 0xACFB) : (index += 1) { try instance.map.put(index, .LVT); } index = 0xACFD; while (index <= 0xAD17) : (index += 1) { try instance.map.put(index, .LVT); } index = 0xAD19; while (index <= 0xAD33) : (index += 1) { try instance.map.put(index, .LVT); } index = 0xAD35; while (index <= 0xAD4F) : (index += 1) { try instance.map.put(index, .LVT); } index = 0xAD51; while (index <= 0xAD6B) : (index += 1) { try instance.map.put(index, .LVT); } index = 0xAD6D; while (index <= 0xAD87) : (index += 1) { try instance.map.put(index, .LVT); } index = 0xAD89; while (index <= 0xADA3) : (index += 1) { try instance.map.put(index, .LVT); } index = 0xADA5; while (index <= 0xADBF) : (index += 1) { try instance.map.put(index, .LVT); } index = 0xADC1; while (index <= 0xADDB) : (index += 1) { try instance.map.put(index, .LVT); } index = 0xADDD; while (index <= 0xADF7) : (index += 1) { try instance.map.put(index, .LVT); } index = 0xADF9; while (index <= 0xAE13) : (index += 1) { try instance.map.put(index, .LVT); } index = 0xAE15; while (index <= 0xAE2F) : (index += 1) { try instance.map.put(index, .LVT); } index = 0xAE31; while (index <= 0xAE4B) : (index += 1) { try instance.map.put(index, .LVT); } index = 0xAE4D; while (index <= 0xAE67) : (index += 1) { try instance.map.put(index, .LVT); } index = 0xAE69; while (index <= 0xAE83) : (index += 1) { try instance.map.put(index, .LVT); } index = 0xAE85; while (index <= 0xAE9F) : (index += 1) { try instance.map.put(index, .LVT); } index = 0xAEA1; while (index <= 0xAEBB) : (index += 1) { try instance.map.put(index, .LVT); } index = 0xAEBD; while (index <= 0xAED7) : (index += 1) { try instance.map.put(index, .LVT); } index = 0xAED9; while (index <= 0xAEF3) : (index += 1) { try instance.map.put(index, .LVT); } index = 0xAEF5; while (index <= 0xAF0F) : (index += 1) { try instance.map.put(index, .LVT); } index = 0xAF11; while (index <= 0xAF2B) : (index += 1) { try instance.map.put(index, .LVT); } index = 0xAF2D; while (index <= 0xAF47) : (index += 1) { try instance.map.put(index, .LVT); } index = 0xAF49; while (index <= 0xAF63) : (index += 1) { try instance.map.put(index, .LVT); } index = 0xAF65; while (index <= 0xAF7F) : (index += 1) { try instance.map.put(index, .LVT); } index = 0xAF81; while (index <= 0xAF9B) : (index += 1) { try instance.map.put(index, .LVT); } index = 0xAF9D; while (index <= 0xAFB7) : (index += 1) { try instance.map.put(index, .LVT); } index = 0xAFB9; while (index <= 0xAFD3) : (index += 1) { try instance.map.put(index, .LVT); } index = 0xAFD5; while (index <= 0xAFEF) : (index += 1) { try instance.map.put(index, .LVT); } index = 0xAFF1; while (index <= 0xB00B) : (index += 1) { try instance.map.put(index, .LVT); } index = 0xB00D; while (index <= 0xB027) : (index += 1) { try instance.map.put(index, .LVT); } index = 0xB029; while (index <= 0xB043) : (index += 1) { try instance.map.put(index, .LVT); } index = 0xB045; while (index <= 0xB05F) : (index += 1) { try instance.map.put(index, .LVT); } index = 0xB061; while (index <= 0xB07B) : (index += 1) { try instance.map.put(index, .LVT); } index = 0xB07D; while (index <= 0xB097) : (index += 1) { try instance.map.put(index, .LVT); } index = 0xB099; while (index <= 0xB0B3) : (index += 1) { try instance.map.put(index, .LVT); } index = 0xB0B5; while (index <= 0xB0CF) : (index += 1) { try instance.map.put(index, .LVT); } index = 0xB0D1; while (index <= 0xB0EB) : (index += 1) { try instance.map.put(index, .LVT); } index = 0xB0ED; while (index <= 0xB107) : (index += 1) { try instance.map.put(index, .LVT); } index = 0xB109; while (index <= 0xB123) : (index += 1) { try instance.map.put(index, .LVT); } index = 0xB125; while (index <= 0xB13F) : (index += 1) { try instance.map.put(index, .LVT); } index = 0xB141; while (index <= 0xB15B) : (index += 1) { try instance.map.put(index, .LVT); } index = 0xB15D; while (index <= 0xB177) : (index += 1) { try instance.map.put(index, .LVT); } index = 0xB179; while (index <= 0xB193) : (index += 1) { try instance.map.put(index, .LVT); } index = 0xB195; while (index <= 0xB1AF) : (index += 1) { try instance.map.put(index, .LVT); } index = 0xB1B1; while (index <= 0xB1CB) : (index += 1) { try instance.map.put(index, .LVT); } index = 0xB1CD; while (index <= 0xB1E7) : (index += 1) { try instance.map.put(index, .LVT); } index = 0xB1E9; while (index <= 0xB203) : (index += 1) { try instance.map.put(index, .LVT); } index = 0xB205; while (index <= 0xB21F) : (index += 1) { try instance.map.put(index, .LVT); } index = 0xB221; while (index <= 0xB23B) : (index += 1) { try instance.map.put(index, .LVT); } index = 0xB23D; while (index <= 0xB257) : (index += 1) { try instance.map.put(index, .LVT); } index = 0xB259; while (index <= 0xB273) : (index += 1) { try instance.map.put(index, .LVT); } index = 0xB275; while (index <= 0xB28F) : (index += 1) { try instance.map.put(index, .LVT); } index = 0xB291; while (index <= 0xB2AB) : (index += 1) { try instance.map.put(index, .LVT); } index = 0xB2AD; while (index <= 0xB2C7) : (index += 1) { try instance.map.put(index, .LVT); } index = 0xB2C9; while (index <= 0xB2E3) : (index += 1) { try instance.map.put(index, .LVT); } index = 0xB2E5; while (index <= 0xB2FF) : (index += 1) { try instance.map.put(index, .LVT); } index = 0xB301; while (index <= 0xB31B) : (index += 1) { try instance.map.put(index, .LVT); } index = 0xB31D; while (index <= 0xB337) : (index += 1) { try instance.map.put(index, .LVT); } index = 0xB339; while (index <= 0xB353) : (index += 1) { try instance.map.put(index, .LVT); } index = 0xB355; while (index <= 0xB36F) : (index += 1) { try instance.map.put(index, .LVT); } index = 0xB371; while (index <= 0xB38B) : (index += 1) { try instance.map.put(index, .LVT); } index = 0xB38D; while (index <= 0xB3A7) : (index += 1) { try instance.map.put(index, .LVT); } index = 0xB3A9; while (index <= 0xB3C3) : (index += 1) { try instance.map.put(index, .LVT); } index = 0xB3C5; while (index <= 0xB3DF) : (index += 1) { try instance.map.put(index, .LVT); } index = 0xB3E1; while (index <= 0xB3FB) : (index += 1) { try instance.map.put(index, .LVT); } index = 0xB3FD; while (index <= 0xB417) : (index += 1) { try instance.map.put(index, .LVT); } index = 0xB419; while (index <= 0xB433) : (index += 1) { try instance.map.put(index, .LVT); } index = 0xB435; while (index <= 0xB44F) : (index += 1) { try instance.map.put(index, .LVT); } index = 0xB451; while (index <= 0xB46B) : (index += 1) { try instance.map.put(index, .LVT); } index = 0xB46D; while (index <= 0xB487) : (index += 1) { try instance.map.put(index, .LVT); } index = 0xB489; while (index <= 0xB4A3) : (index += 1) { try instance.map.put(index, .LVT); } index = 0xB4A5; while (index <= 0xB4BF) : (index += 1) { try instance.map.put(index, .LVT); } index = 0xB4C1; while (index <= 0xB4DB) : (index += 1) { try instance.map.put(index, .LVT); } index = 0xB4DD; while (index <= 0xB4F7) : (index += 1) { try instance.map.put(index, .LVT); } index = 0xB4F9; while (index <= 0xB513) : (index += 1) { try instance.map.put(index, .LVT); } index = 0xB515; while (index <= 0xB52F) : (index += 1) { try instance.map.put(index, .LVT); } index = 0xB531; while (index <= 0xB54B) : (index += 1) { try instance.map.put(index, .LVT); } index = 0xB54D; while (index <= 0xB567) : (index += 1) { try instance.map.put(index, .LVT); } index = 0xB569; while (index <= 0xB583) : (index += 1) { try instance.map.put(index, .LVT); } index = 0xB585; while (index <= 0xB59F) : (index += 1) { try instance.map.put(index, .LVT); } index = 0xB5A1; while (index <= 0xB5BB) : (index += 1) { try instance.map.put(index, .LVT); } index = 0xB5BD; while (index <= 0xB5D7) : (index += 1) { try instance.map.put(index, .LVT); } index = 0xB5D9; while (index <= 0xB5F3) : (index += 1) { try instance.map.put(index, .LVT); } index = 0xB5F5; while (index <= 0xB60F) : (index += 1) { try instance.map.put(index, .LVT); } index = 0xB611; while (index <= 0xB62B) : (index += 1) { try instance.map.put(index, .LVT); } index = 0xB62D; while (index <= 0xB647) : (index += 1) { try instance.map.put(index, .LVT); } index = 0xB649; while (index <= 0xB663) : (index += 1) { try instance.map.put(index, .LVT); } index = 0xB665; while (index <= 0xB67F) : (index += 1) { try instance.map.put(index, .LVT); } index = 0xB681; while (index <= 0xB69B) : (index += 1) { try instance.map.put(index, .LVT); } index = 0xB69D; while (index <= 0xB6B7) : (index += 1) { try instance.map.put(index, .LVT); } index = 0xB6B9; while (index <= 0xB6D3) : (index += 1) { try instance.map.put(index, .LVT); } index = 0xB6D5; while (index <= 0xB6EF) : (index += 1) { try instance.map.put(index, .LVT); } index = 0xB6F1; while (index <= 0xB70B) : (index += 1) { try instance.map.put(index, .LVT); } index = 0xB70D; while (index <= 0xB727) : (index += 1) { try instance.map.put(index, .LVT); } index = 0xB729; while (index <= 0xB743) : (index += 1) { try instance.map.put(index, .LVT); } index = 0xB745; while (index <= 0xB75F) : (index += 1) { try instance.map.put(index, .LVT); } index = 0xB761; while (index <= 0xB77B) : (index += 1) { try instance.map.put(index, .LVT); } index = 0xB77D; while (index <= 0xB797) : (index += 1) { try instance.map.put(index, .LVT); } index = 0xB799; while (index <= 0xB7B3) : (index += 1) { try instance.map.put(index, .LVT); } index = 0xB7B5; while (index <= 0xB7CF) : (index += 1) { try instance.map.put(index, .LVT); } index = 0xB7D1; while (index <= 0xB7EB) : (index += 1) { try instance.map.put(index, .LVT); } index = 0xB7ED; while (index <= 0xB807) : (index += 1) { try instance.map.put(index, .LVT); } index = 0xB809; while (index <= 0xB823) : (index += 1) { try instance.map.put(index, .LVT); } index = 0xB825; while (index <= 0xB83F) : (index += 1) { try instance.map.put(index, .LVT); } index = 0xB841; while (index <= 0xB85B) : (index += 1) { try instance.map.put(index, .LVT); } index = 0xB85D; while (index <= 0xB877) : (index += 1) { try instance.map.put(index, .LVT); } index = 0xB879; while (index <= 0xB893) : (index += 1) { try instance.map.put(index, .LVT); } index = 0xB895; while (index <= 0xB8AF) : (index += 1) { try instance.map.put(index, .LVT); } index = 0xB8B1; while (index <= 0xB8CB) : (index += 1) { try instance.map.put(index, .LVT); } index = 0xB8CD; while (index <= 0xB8E7) : (index += 1) { try instance.map.put(index, .LVT); } index = 0xB8E9; while (index <= 0xB903) : (index += 1) { try instance.map.put(index, .LVT); } index = 0xB905; while (index <= 0xB91F) : (index += 1) { try instance.map.put(index, .LVT); } index = 0xB921; while (index <= 0xB93B) : (index += 1) { try instance.map.put(index, .LVT); } index = 0xB93D; while (index <= 0xB957) : (index += 1) { try instance.map.put(index, .LVT); } index = 0xB959; while (index <= 0xB973) : (index += 1) { try instance.map.put(index, .LVT); } index = 0xB975; while (index <= 0xB98F) : (index += 1) { try instance.map.put(index, .LVT); } index = 0xB991; while (index <= 0xB9AB) : (index += 1) { try instance.map.put(index, .LVT); } index = 0xB9AD; while (index <= 0xB9C7) : (index += 1) { try instance.map.put(index, .LVT); } index = 0xB9C9; while (index <= 0xB9E3) : (index += 1) { try instance.map.put(index, .LVT); } index = 0xB9E5; while (index <= 0xB9FF) : (index += 1) { try instance.map.put(index, .LVT); } index = 0xBA01; while (index <= 0xBA1B) : (index += 1) { try instance.map.put(index, .LVT); } index = 0xBA1D; while (index <= 0xBA37) : (index += 1) { try instance.map.put(index, .LVT); } index = 0xBA39; while (index <= 0xBA53) : (index += 1) { try instance.map.put(index, .LVT); } index = 0xBA55; while (index <= 0xBA6F) : (index += 1) { try instance.map.put(index, .LVT); } index = 0xBA71; while (index <= 0xBA8B) : (index += 1) { try instance.map.put(index, .LVT); } index = 0xBA8D; while (index <= 0xBAA7) : (index += 1) { try instance.map.put(index, .LVT); } index = 0xBAA9; while (index <= 0xBAC3) : (index += 1) { try instance.map.put(index, .LVT); } index = 0xBAC5; while (index <= 0xBADF) : (index += 1) { try instance.map.put(index, .LVT); } index = 0xBAE1; while (index <= 0xBAFB) : (index += 1) { try instance.map.put(index, .LVT); } index = 0xBAFD; while (index <= 0xBB17) : (index += 1) { try instance.map.put(index, .LVT); } index = 0xBB19; while (index <= 0xBB33) : (index += 1) { try instance.map.put(index, .LVT); } index = 0xBB35; while (index <= 0xBB4F) : (index += 1) { try instance.map.put(index, .LVT); } index = 0xBB51; while (index <= 0xBB6B) : (index += 1) { try instance.map.put(index, .LVT); } index = 0xBB6D; while (index <= 0xBB87) : (index += 1) { try instance.map.put(index, .LVT); } index = 0xBB89; while (index <= 0xBBA3) : (index += 1) { try instance.map.put(index, .LVT); } index = 0xBBA5; while (index <= 0xBBBF) : (index += 1) { try instance.map.put(index, .LVT); } index = 0xBBC1; while (index <= 0xBBDB) : (index += 1) { try instance.map.put(index, .LVT); } index = 0xBBDD; while (index <= 0xBBF7) : (index += 1) { try instance.map.put(index, .LVT); } index = 0xBBF9; while (index <= 0xBC13) : (index += 1) { try instance.map.put(index, .LVT); } index = 0xBC15; while (index <= 0xBC2F) : (index += 1) { try instance.map.put(index, .LVT); } index = 0xBC31; while (index <= 0xBC4B) : (index += 1) { try instance.map.put(index, .LVT); } index = 0xBC4D; while (index <= 0xBC67) : (index += 1) { try instance.map.put(index, .LVT); } index = 0xBC69; while (index <= 0xBC83) : (index += 1) { try instance.map.put(index, .LVT); } index = 0xBC85; while (index <= 0xBC9F) : (index += 1) { try instance.map.put(index, .LVT); } index = 0xBCA1; while (index <= 0xBCBB) : (index += 1) { try instance.map.put(index, .LVT); } index = 0xBCBD; while (index <= 0xBCD7) : (index += 1) { try instance.map.put(index, .LVT); } index = 0xBCD9; while (index <= 0xBCF3) : (index += 1) { try instance.map.put(index, .LVT); } index = 0xBCF5; while (index <= 0xBD0F) : (index += 1) { try instance.map.put(index, .LVT); } index = 0xBD11; while (index <= 0xBD2B) : (index += 1) { try instance.map.put(index, .LVT); } index = 0xBD2D; while (index <= 0xBD47) : (index += 1) { try instance.map.put(index, .LVT); } index = 0xBD49; while (index <= 0xBD63) : (index += 1) { try instance.map.put(index, .LVT); } index = 0xBD65; while (index <= 0xBD7F) : (index += 1) { try instance.map.put(index, .LVT); } index = 0xBD81; while (index <= 0xBD9B) : (index += 1) { try instance.map.put(index, .LVT); } index = 0xBD9D; while (index <= 0xBDB7) : (index += 1) { try instance.map.put(index, .LVT); } index = 0xBDB9; while (index <= 0xBDD3) : (index += 1) { try instance.map.put(index, .LVT); } index = 0xBDD5; while (index <= 0xBDEF) : (index += 1) { try instance.map.put(index, .LVT); } index = 0xBDF1; while (index <= 0xBE0B) : (index += 1) { try instance.map.put(index, .LVT); } index = 0xBE0D; while (index <= 0xBE27) : (index += 1) { try instance.map.put(index, .LVT); } index = 0xBE29; while (index <= 0xBE43) : (index += 1) { try instance.map.put(index, .LVT); } index = 0xBE45; while (index <= 0xBE5F) : (index += 1) { try instance.map.put(index, .LVT); } index = 0xBE61; while (index <= 0xBE7B) : (index += 1) { try instance.map.put(index, .LVT); } index = 0xBE7D; while (index <= 0xBE97) : (index += 1) { try instance.map.put(index, .LVT); } index = 0xBE99; while (index <= 0xBEB3) : (index += 1) { try instance.map.put(index, .LVT); } index = 0xBEB5; while (index <= 0xBECF) : (index += 1) { try instance.map.put(index, .LVT); } index = 0xBED1; while (index <= 0xBEEB) : (index += 1) { try instance.map.put(index, .LVT); } index = 0xBEED; while (index <= 0xBF07) : (index += 1) { try instance.map.put(index, .LVT); } index = 0xBF09; while (index <= 0xBF23) : (index += 1) { try instance.map.put(index, .LVT); } index = 0xBF25; while (index <= 0xBF3F) : (index += 1) { try instance.map.put(index, .LVT); } index = 0xBF41; while (index <= 0xBF5B) : (index += 1) { try instance.map.put(index, .LVT); } index = 0xBF5D; while (index <= 0xBF77) : (index += 1) { try instance.map.put(index, .LVT); } index = 0xBF79; while (index <= 0xBF93) : (index += 1) { try instance.map.put(index, .LVT); } index = 0xBF95; while (index <= 0xBFAF) : (index += 1) { try instance.map.put(index, .LVT); } index = 0xBFB1; while (index <= 0xBFCB) : (index += 1) { try instance.map.put(index, .LVT); } index = 0xBFCD; while (index <= 0xBFE7) : (index += 1) { try instance.map.put(index, .LVT); } index = 0xBFE9; while (index <= 0xC003) : (index += 1) { try instance.map.put(index, .LVT); } index = 0xC005; while (index <= 0xC01F) : (index += 1) { try instance.map.put(index, .LVT); } index = 0xC021; while (index <= 0xC03B) : (index += 1) { try instance.map.put(index, .LVT); } index = 0xC03D; while (index <= 0xC057) : (index += 1) { try instance.map.put(index, .LVT); } index = 0xC059; while (index <= 0xC073) : (index += 1) { try instance.map.put(index, .LVT); } index = 0xC075; while (index <= 0xC08F) : (index += 1) { try instance.map.put(index, .LVT); } index = 0xC091; while (index <= 0xC0AB) : (index += 1) { try instance.map.put(index, .LVT); } index = 0xC0AD; while (index <= 0xC0C7) : (index += 1) { try instance.map.put(index, .LVT); } index = 0xC0C9; while (index <= 0xC0E3) : (index += 1) { try instance.map.put(index, .LVT); } index = 0xC0E5; while (index <= 0xC0FF) : (index += 1) { try instance.map.put(index, .LVT); } index = 0xC101; while (index <= 0xC11B) : (index += 1) { try instance.map.put(index, .LVT); } index = 0xC11D; while (index <= 0xC137) : (index += 1) { try instance.map.put(index, .LVT); } index = 0xC139; while (index <= 0xC153) : (index += 1) { try instance.map.put(index, .LVT); } index = 0xC155; while (index <= 0xC16F) : (index += 1) { try instance.map.put(index, .LVT); } index = 0xC171; while (index <= 0xC18B) : (index += 1) { try instance.map.put(index, .LVT); } index = 0xC18D; while (index <= 0xC1A7) : (index += 1) { try instance.map.put(index, .LVT); } index = 0xC1A9; while (index <= 0xC1C3) : (index += 1) { try instance.map.put(index, .LVT); } index = 0xC1C5; while (index <= 0xC1DF) : (index += 1) { try instance.map.put(index, .LVT); } index = 0xC1E1; while (index <= 0xC1FB) : (index += 1) { try instance.map.put(index, .LVT); } index = 0xC1FD; while (index <= 0xC217) : (index += 1) { try instance.map.put(index, .LVT); } index = 0xC219; while (index <= 0xC233) : (index += 1) { try instance.map.put(index, .LVT); } index = 0xC235; while (index <= 0xC24F) : (index += 1) { try instance.map.put(index, .LVT); } index = 0xC251; while (index <= 0xC26B) : (index += 1) { try instance.map.put(index, .LVT); } index = 0xC26D; while (index <= 0xC287) : (index += 1) { try instance.map.put(index, .LVT); } index = 0xC289; while (index <= 0xC2A3) : (index += 1) { try instance.map.put(index, .LVT); } index = 0xC2A5; while (index <= 0xC2BF) : (index += 1) { try instance.map.put(index, .LVT); } index = 0xC2C1; while (index <= 0xC2DB) : (index += 1) { try instance.map.put(index, .LVT); } index = 0xC2DD; while (index <= 0xC2F7) : (index += 1) { try instance.map.put(index, .LVT); } index = 0xC2F9; while (index <= 0xC313) : (index += 1) { try instance.map.put(index, .LVT); } index = 0xC315; while (index <= 0xC32F) : (index += 1) { try instance.map.put(index, .LVT); } index = 0xC331; while (index <= 0xC34B) : (index += 1) { try instance.map.put(index, .LVT); } index = 0xC34D; while (index <= 0xC367) : (index += 1) { try instance.map.put(index, .LVT); } index = 0xC369; while (index <= 0xC383) : (index += 1) { try instance.map.put(index, .LVT); } index = 0xC385; while (index <= 0xC39F) : (index += 1) { try instance.map.put(index, .LVT); } index = 0xC3A1; while (index <= 0xC3BB) : (index += 1) { try instance.map.put(index, .LVT); } index = 0xC3BD; while (index <= 0xC3D7) : (index += 1) { try instance.map.put(index, .LVT); } index = 0xC3D9; while (index <= 0xC3F3) : (index += 1) { try instance.map.put(index, .LVT); } index = 0xC3F5; while (index <= 0xC40F) : (index += 1) { try instance.map.put(index, .LVT); } index = 0xC411; while (index <= 0xC42B) : (index += 1) { try instance.map.put(index, .LVT); } index = 0xC42D; while (index <= 0xC447) : (index += 1) { try instance.map.put(index, .LVT); } index = 0xC449; while (index <= 0xC463) : (index += 1) { try instance.map.put(index, .LVT); } index = 0xC465; while (index <= 0xC47F) : (index += 1) { try instance.map.put(index, .LVT); } index = 0xC481; while (index <= 0xC49B) : (index += 1) { try instance.map.put(index, .LVT); } index = 0xC49D; while (index <= 0xC4B7) : (index += 1) { try instance.map.put(index, .LVT); } index = 0xC4B9; while (index <= 0xC4D3) : (index += 1) { try instance.map.put(index, .LVT); } index = 0xC4D5; while (index <= 0xC4EF) : (index += 1) { try instance.map.put(index, .LVT); } index = 0xC4F1; while (index <= 0xC50B) : (index += 1) { try instance.map.put(index, .LVT); } index = 0xC50D; while (index <= 0xC527) : (index += 1) { try instance.map.put(index, .LVT); } index = 0xC529; while (index <= 0xC543) : (index += 1) { try instance.map.put(index, .LVT); } index = 0xC545; while (index <= 0xC55F) : (index += 1) { try instance.map.put(index, .LVT); } index = 0xC561; while (index <= 0xC57B) : (index += 1) { try instance.map.put(index, .LVT); } index = 0xC57D; while (index <= 0xC597) : (index += 1) { try instance.map.put(index, .LVT); } index = 0xC599; while (index <= 0xC5B3) : (index += 1) { try instance.map.put(index, .LVT); } index = 0xC5B5; while (index <= 0xC5CF) : (index += 1) { try instance.map.put(index, .LVT); } index = 0xC5D1; while (index <= 0xC5EB) : (index += 1) { try instance.map.put(index, .LVT); } index = 0xC5ED; while (index <= 0xC607) : (index += 1) { try instance.map.put(index, .LVT); } index = 0xC609; while (index <= 0xC623) : (index += 1) { try instance.map.put(index, .LVT); } index = 0xC625; while (index <= 0xC63F) : (index += 1) { try instance.map.put(index, .LVT); } index = 0xC641; while (index <= 0xC65B) : (index += 1) { try instance.map.put(index, .LVT); } index = 0xC65D; while (index <= 0xC677) : (index += 1) { try instance.map.put(index, .LVT); } index = 0xC679; while (index <= 0xC693) : (index += 1) { try instance.map.put(index, .LVT); } index = 0xC695; while (index <= 0xC6AF) : (index += 1) { try instance.map.put(index, .LVT); } index = 0xC6B1; while (index <= 0xC6CB) : (index += 1) { try instance.map.put(index, .LVT); } index = 0xC6CD; while (index <= 0xC6E7) : (index += 1) { try instance.map.put(index, .LVT); } index = 0xC6E9; while (index <= 0xC703) : (index += 1) { try instance.map.put(index, .LVT); } index = 0xC705; while (index <= 0xC71F) : (index += 1) { try instance.map.put(index, .LVT); } index = 0xC721; while (index <= 0xC73B) : (index += 1) { try instance.map.put(index, .LVT); } index = 0xC73D; while (index <= 0xC757) : (index += 1) { try instance.map.put(index, .LVT); } index = 0xC759; while (index <= 0xC773) : (index += 1) { try instance.map.put(index, .LVT); } index = 0xC775; while (index <= 0xC78F) : (index += 1) { try instance.map.put(index, .LVT); } index = 0xC791; while (index <= 0xC7AB) : (index += 1) { try instance.map.put(index, .LVT); } index = 0xC7AD; while (index <= 0xC7C7) : (index += 1) { try instance.map.put(index, .LVT); } index = 0xC7C9; while (index <= 0xC7E3) : (index += 1) { try instance.map.put(index, .LVT); } index = 0xC7E5; while (index <= 0xC7FF) : (index += 1) { try instance.map.put(index, .LVT); } index = 0xC801; while (index <= 0xC81B) : (index += 1) { try instance.map.put(index, .LVT); } index = 0xC81D; while (index <= 0xC837) : (index += 1) { try instance.map.put(index, .LVT); } index = 0xC839; while (index <= 0xC853) : (index += 1) { try instance.map.put(index, .LVT); } index = 0xC855; while (index <= 0xC86F) : (index += 1) { try instance.map.put(index, .LVT); } index = 0xC871; while (index <= 0xC88B) : (index += 1) { try instance.map.put(index, .LVT); } index = 0xC88D; while (index <= 0xC8A7) : (index += 1) { try instance.map.put(index, .LVT); } index = 0xC8A9; while (index <= 0xC8C3) : (index += 1) { try instance.map.put(index, .LVT); } index = 0xC8C5; while (index <= 0xC8DF) : (index += 1) { try instance.map.put(index, .LVT); } index = 0xC8E1; while (index <= 0xC8FB) : (index += 1) { try instance.map.put(index, .LVT); } index = 0xC8FD; while (index <= 0xC917) : (index += 1) { try instance.map.put(index, .LVT); } index = 0xC919; while (index <= 0xC933) : (index += 1) { try instance.map.put(index, .LVT); } index = 0xC935; while (index <= 0xC94F) : (index += 1) { try instance.map.put(index, .LVT); } index = 0xC951; while (index <= 0xC96B) : (index += 1) { try instance.map.put(index, .LVT); } index = 0xC96D; while (index <= 0xC987) : (index += 1) { try instance.map.put(index, .LVT); } index = 0xC989; while (index <= 0xC9A3) : (index += 1) { try instance.map.put(index, .LVT); } index = 0xC9A5; while (index <= 0xC9BF) : (index += 1) { try instance.map.put(index, .LVT); } index = 0xC9C1; while (index <= 0xC9DB) : (index += 1) { try instance.map.put(index, .LVT); } index = 0xC9DD; while (index <= 0xC9F7) : (index += 1) { try instance.map.put(index, .LVT); } index = 0xC9F9; while (index <= 0xCA13) : (index += 1) { try instance.map.put(index, .LVT); } index = 0xCA15; while (index <= 0xCA2F) : (index += 1) { try instance.map.put(index, .LVT); } index = 0xCA31; while (index <= 0xCA4B) : (index += 1) { try instance.map.put(index, .LVT); } index = 0xCA4D; while (index <= 0xCA67) : (index += 1) { try instance.map.put(index, .LVT); } index = 0xCA69; while (index <= 0xCA83) : (index += 1) { try instance.map.put(index, .LVT); } index = 0xCA85; while (index <= 0xCA9F) : (index += 1) { try instance.map.put(index, .LVT); } index = 0xCAA1; while (index <= 0xCABB) : (index += 1) { try instance.map.put(index, .LVT); } index = 0xCABD; while (index <= 0xCAD7) : (index += 1) { try instance.map.put(index, .LVT); } index = 0xCAD9; while (index <= 0xCAF3) : (index += 1) { try instance.map.put(index, .LVT); } index = 0xCAF5; while (index <= 0xCB0F) : (index += 1) { try instance.map.put(index, .LVT); } index = 0xCB11; while (index <= 0xCB2B) : (index += 1) { try instance.map.put(index, .LVT); } index = 0xCB2D; while (index <= 0xCB47) : (index += 1) { try instance.map.put(index, .LVT); } index = 0xCB49; while (index <= 0xCB63) : (index += 1) { try instance.map.put(index, .LVT); } index = 0xCB65; while (index <= 0xCB7F) : (index += 1) { try instance.map.put(index, .LVT); } index = 0xCB81; while (index <= 0xCB9B) : (index += 1) { try instance.map.put(index, .LVT); } index = 0xCB9D; while (index <= 0xCBB7) : (index += 1) { try instance.map.put(index, .LVT); } index = 0xCBB9; while (index <= 0xCBD3) : (index += 1) { try instance.map.put(index, .LVT); } index = 0xCBD5; while (index <= 0xCBEF) : (index += 1) { try instance.map.put(index, .LVT); } index = 0xCBF1; while (index <= 0xCC0B) : (index += 1) { try instance.map.put(index, .LVT); } index = 0xCC0D; while (index <= 0xCC27) : (index += 1) { try instance.map.put(index, .LVT); } index = 0xCC29; while (index <= 0xCC43) : (index += 1) { try instance.map.put(index, .LVT); } index = 0xCC45; while (index <= 0xCC5F) : (index += 1) { try instance.map.put(index, .LVT); } index = 0xCC61; while (index <= 0xCC7B) : (index += 1) { try instance.map.put(index, .LVT); } index = 0xCC7D; while (index <= 0xCC97) : (index += 1) { try instance.map.put(index, .LVT); } index = 0xCC99; while (index <= 0xCCB3) : (index += 1) { try instance.map.put(index, .LVT); } index = 0xCCB5; while (index <= 0xCCCF) : (index += 1) { try instance.map.put(index, .LVT); } index = 0xCCD1; while (index <= 0xCCEB) : (index += 1) { try instance.map.put(index, .LVT); } index = 0xCCED; while (index <= 0xCD07) : (index += 1) { try instance.map.put(index, .LVT); } index = 0xCD09; while (index <= 0xCD23) : (index += 1) { try instance.map.put(index, .LVT); } index = 0xCD25; while (index <= 0xCD3F) : (index += 1) { try instance.map.put(index, .LVT); } index = 0xCD41; while (index <= 0xCD5B) : (index += 1) { try instance.map.put(index, .LVT); } index = 0xCD5D; while (index <= 0xCD77) : (index += 1) { try instance.map.put(index, .LVT); } index = 0xCD79; while (index <= 0xCD93) : (index += 1) { try instance.map.put(index, .LVT); } index = 0xCD95; while (index <= 0xCDAF) : (index += 1) { try instance.map.put(index, .LVT); } index = 0xCDB1; while (index <= 0xCDCB) : (index += 1) { try instance.map.put(index, .LVT); } index = 0xCDCD; while (index <= 0xCDE7) : (index += 1) { try instance.map.put(index, .LVT); } index = 0xCDE9; while (index <= 0xCE03) : (index += 1) { try instance.map.put(index, .LVT); } index = 0xCE05; while (index <= 0xCE1F) : (index += 1) { try instance.map.put(index, .LVT); } index = 0xCE21; while (index <= 0xCE3B) : (index += 1) { try instance.map.put(index, .LVT); } index = 0xCE3D; while (index <= 0xCE57) : (index += 1) { try instance.map.put(index, .LVT); } index = 0xCE59; while (index <= 0xCE73) : (index += 1) { try instance.map.put(index, .LVT); } index = 0xCE75; while (index <= 0xCE8F) : (index += 1) { try instance.map.put(index, .LVT); } index = 0xCE91; while (index <= 0xCEAB) : (index += 1) { try instance.map.put(index, .LVT); } index = 0xCEAD; while (index <= 0xCEC7) : (index += 1) { try instance.map.put(index, .LVT); } index = 0xCEC9; while (index <= 0xCEE3) : (index += 1) { try instance.map.put(index, .LVT); } index = 0xCEE5; while (index <= 0xCEFF) : (index += 1) { try instance.map.put(index, .LVT); } index = 0xCF01; while (index <= 0xCF1B) : (index += 1) { try instance.map.put(index, .LVT); } index = 0xCF1D; while (index <= 0xCF37) : (index += 1) { try instance.map.put(index, .LVT); } index = 0xCF39; while (index <= 0xCF53) : (index += 1) { try instance.map.put(index, .LVT); } index = 0xCF55; while (index <= 0xCF6F) : (index += 1) { try instance.map.put(index, .LVT); } index = 0xCF71; while (index <= 0xCF8B) : (index += 1) { try instance.map.put(index, .LVT); } index = 0xCF8D; while (index <= 0xCFA7) : (index += 1) { try instance.map.put(index, .LVT); } index = 0xCFA9; while (index <= 0xCFC3) : (index += 1) { try instance.map.put(index, .LVT); } index = 0xCFC5; while (index <= 0xCFDF) : (index += 1) { try instance.map.put(index, .LVT); } index = 0xCFE1; while (index <= 0xCFFB) : (index += 1) { try instance.map.put(index, .LVT); } index = 0xCFFD; while (index <= 0xD017) : (index += 1) { try instance.map.put(index, .LVT); } index = 0xD019; while (index <= 0xD033) : (index += 1) { try instance.map.put(index, .LVT); } index = 0xD035; while (index <= 0xD04F) : (index += 1) { try instance.map.put(index, .LVT); } index = 0xD051; while (index <= 0xD06B) : (index += 1) { try instance.map.put(index, .LVT); } index = 0xD06D; while (index <= 0xD087) : (index += 1) { try instance.map.put(index, .LVT); } index = 0xD089; while (index <= 0xD0A3) : (index += 1) { try instance.map.put(index, .LVT); } index = 0xD0A5; while (index <= 0xD0BF) : (index += 1) { try instance.map.put(index, .LVT); } index = 0xD0C1; while (index <= 0xD0DB) : (index += 1) { try instance.map.put(index, .LVT); } index = 0xD0DD; while (index <= 0xD0F7) : (index += 1) { try instance.map.put(index, .LVT); } index = 0xD0F9; while (index <= 0xD113) : (index += 1) { try instance.map.put(index, .LVT); } index = 0xD115; while (index <= 0xD12F) : (index += 1) { try instance.map.put(index, .LVT); } index = 0xD131; while (index <= 0xD14B) : (index += 1) { try instance.map.put(index, .LVT); } index = 0xD14D; while (index <= 0xD167) : (index += 1) { try instance.map.put(index, .LVT); } index = 0xD169; while (index <= 0xD183) : (index += 1) { try instance.map.put(index, .LVT); } index = 0xD185; while (index <= 0xD19F) : (index += 1) { try instance.map.put(index, .LVT); } index = 0xD1A1; while (index <= 0xD1BB) : (index += 1) { try instance.map.put(index, .LVT); } index = 0xD1BD; while (index <= 0xD1D7) : (index += 1) { try instance.map.put(index, .LVT); } index = 0xD1D9; while (index <= 0xD1F3) : (index += 1) { try instance.map.put(index, .LVT); } index = 0xD1F5; while (index <= 0xD20F) : (index += 1) { try instance.map.put(index, .LVT); } index = 0xD211; while (index <= 0xD22B) : (index += 1) { try instance.map.put(index, .LVT); } index = 0xD22D; while (index <= 0xD247) : (index += 1) { try instance.map.put(index, .LVT); } index = 0xD249; while (index <= 0xD263) : (index += 1) { try instance.map.put(index, .LVT); } index = 0xD265; while (index <= 0xD27F) : (index += 1) { try instance.map.put(index, .LVT); } index = 0xD281; while (index <= 0xD29B) : (index += 1) { try instance.map.put(index, .LVT); } index = 0xD29D; while (index <= 0xD2B7) : (index += 1) { try instance.map.put(index, .LVT); } index = 0xD2B9; while (index <= 0xD2D3) : (index += 1) { try instance.map.put(index, .LVT); } index = 0xD2D5; while (index <= 0xD2EF) : (index += 1) { try instance.map.put(index, .LVT); } index = 0xD2F1; while (index <= 0xD30B) : (index += 1) { try instance.map.put(index, .LVT); } index = 0xD30D; while (index <= 0xD327) : (index += 1) { try instance.map.put(index, .LVT); } index = 0xD329; while (index <= 0xD343) : (index += 1) { try instance.map.put(index, .LVT); } index = 0xD345; while (index <= 0xD35F) : (index += 1) { try instance.map.put(index, .LVT); } index = 0xD361; while (index <= 0xD37B) : (index += 1) { try instance.map.put(index, .LVT); } index = 0xD37D; while (index <= 0xD397) : (index += 1) { try instance.map.put(index, .LVT); } index = 0xD399; while (index <= 0xD3B3) : (index += 1) { try instance.map.put(index, .LVT); } index = 0xD3B5; while (index <= 0xD3CF) : (index += 1) { try instance.map.put(index, .LVT); } index = 0xD3D1; while (index <= 0xD3EB) : (index += 1) { try instance.map.put(index, .LVT); } index = 0xD3ED; while (index <= 0xD407) : (index += 1) { try instance.map.put(index, .LVT); } index = 0xD409; while (index <= 0xD423) : (index += 1) { try instance.map.put(index, .LVT); } index = 0xD425; while (index <= 0xD43F) : (index += 1) { try instance.map.put(index, .LVT); } index = 0xD441; while (index <= 0xD45B) : (index += 1) { try instance.map.put(index, .LVT); } index = 0xD45D; while (index <= 0xD477) : (index += 1) { try instance.map.put(index, .LVT); } index = 0xD479; while (index <= 0xD493) : (index += 1) { try instance.map.put(index, .LVT); } index = 0xD495; while (index <= 0xD4AF) : (index += 1) { try instance.map.put(index, .LVT); } index = 0xD4B1; while (index <= 0xD4CB) : (index += 1) { try instance.map.put(index, .LVT); } index = 0xD4CD; while (index <= 0xD4E7) : (index += 1) { try instance.map.put(index, .LVT); } index = 0xD4E9; while (index <= 0xD503) : (index += 1) { try instance.map.put(index, .LVT); } index = 0xD505; while (index <= 0xD51F) : (index += 1) { try instance.map.put(index, .LVT); } index = 0xD521; while (index <= 0xD53B) : (index += 1) { try instance.map.put(index, .LVT); } index = 0xD53D; while (index <= 0xD557) : (index += 1) { try instance.map.put(index, .LVT); } index = 0xD559; while (index <= 0xD573) : (index += 1) { try instance.map.put(index, .LVT); } index = 0xD575; while (index <= 0xD58F) : (index += 1) { try instance.map.put(index, .LVT); } index = 0xD591; while (index <= 0xD5AB) : (index += 1) { try instance.map.put(index, .LVT); } index = 0xD5AD; while (index <= 0xD5C7) : (index += 1) { try instance.map.put(index, .LVT); } index = 0xD5C9; while (index <= 0xD5E3) : (index += 1) { try instance.map.put(index, .LVT); } index = 0xD5E5; while (index <= 0xD5FF) : (index += 1) { try instance.map.put(index, .LVT); } index = 0xD601; while (index <= 0xD61B) : (index += 1) { try instance.map.put(index, .LVT); } index = 0xD61D; while (index <= 0xD637) : (index += 1) { try instance.map.put(index, .LVT); } index = 0xD639; while (index <= 0xD653) : (index += 1) { try instance.map.put(index, .LVT); } index = 0xD655; while (index <= 0xD66F) : (index += 1) { try instance.map.put(index, .LVT); } index = 0xD671; while (index <= 0xD68B) : (index += 1) { try instance.map.put(index, .LVT); } index = 0xD68D; while (index <= 0xD6A7) : (index += 1) { try instance.map.put(index, .LVT); } index = 0xD6A9; while (index <= 0xD6C3) : (index += 1) { try instance.map.put(index, .LVT); } index = 0xD6C5; while (index <= 0xD6DF) : (index += 1) { try instance.map.put(index, .LVT); } index = 0xD6E1; while (index <= 0xD6FB) : (index += 1) { try instance.map.put(index, .LVT); } index = 0xD6FD; while (index <= 0xD717) : (index += 1) { try instance.map.put(index, .LVT); } index = 0xD719; while (index <= 0xD733) : (index += 1) { try instance.map.put(index, .LVT); } index = 0xD735; while (index <= 0xD74F) : (index += 1) { try instance.map.put(index, .LVT); } index = 0xD751; while (index <= 0xD76B) : (index += 1) { try instance.map.put(index, .LVT); } index = 0xD76D; while (index <= 0xD787) : (index += 1) { try instance.map.put(index, .LVT); } index = 0xD789; while (index <= 0xD7A3) : (index += 1) { try instance.map.put(index, .LVT); } return instance; } const Self = @This(); pub fn deinit(self: *Self) void { self.map.deinit(); } /// syllableType maps the code point to its Hangul Syllable Type. pub fn syllableType(self: Self, cp: u21) ?Kind { return self.map.get(cp); }
src/components/autogen/HangulSyllableType/HangulMap.zig
const std = @import("std"); /// Modes' escape codes. pub const Mode = struct { pub const r = "\x1b[0m"; pub const b = "\x1b[1m"; pub const d = "\x1b[2m"; pub const n = "\x1b[3m"; pub const u = "\x1b[4m"; // Aliases pub const reset = r; pub const underline = u; pub const negate = n; pub const bold = b; pub const bright = b; pub const dim = d; }; /// Palette struct with 16 colors. /// * Foregound colors: 30-37 /// * Background colors: 40-47 /// Example, red foreground: `\x1b[31m` /// Example, red background: `\x1b[41m` pub const Palette16 = struct { pub const Foreground = struct { pub const black = "\x1b[30m"; pub const red = "\x1b[31m"; pub const green = "\x1b[32m"; pub const yellow = "\x1b[33m"; pub const blue = "\x1b[34m"; pub const magenta = "\x1b[35m"; pub const cyan = "\x1b[36m"; pub const white = "\x1b[37m"; }; pub const Background = struct { pub const black = "\x1b[40m"; pub const red = "\x1b[41m"; pub const green = "\x1b[42m"; pub const yellow = "\x1b[43m"; pub const blue = "\x1b[44m"; pub const magenta = "\x1b[45m"; pub const cyan = "\x1b[46m"; pub const white = "\x1b[47m"; }; // Aliases pub const fg = Foreground; pub const bg = Background; }; /// Palette struct with 256 colors. /// * Foreground and background colors: 0-255 /// * Font color is prepended with 38;5; /// * Background color is prepended with 48;5; /// Example, Foreground[196]: `\x1b[38;5;196m` /// Example, Background[123]: `\x1b[48;5;123m` pub const Palette256 = struct { const FG_EC = "\x1b[38;5;"; const BG_EC = "\x1b[48;5;"; pub const Foreground = blk: { var colors: [256][11]u8 = undefined; var i: usize = 0; inline while (i < colors.len) : (i += 1) { _ = std.fmt.bufPrint(colors[i][0..], FG_EC ++ "{d:0>3}m", .{i}) catch unreachable; } break :blk colors; }; pub const Background = blk: { var colors: [256][11]u8 = undefined; var i: usize = 0; inline while (i < colors.len) : (i += 1) { _ = std.fmt.bufPrint(colors[i][0..], BG_EC ++ "{d:0>3}m", .{i}) catch unreachable; } break :blk colors; }; // Aliases pub const fg = Foreground; pub const bg = Background; };
src/palettes.zig
const std = @import("std"); const Wal = @import("wal.zig").Wal; const Record = @import("record.zig").Record; const Op = @import("ops.zig").Op; const File = std.fs.File; const ArrayList = std.ArrayList; const lsmtree = @import("main.zig"); const MakeDirError = std.os.MakeDirError; const OpenFileError = std.is.OpenFileError; /// Tracks the files that belong to the system. pub fn DiskManager(comptime WalType: type) type { return struct { const Self = @This(); file_id: u8 = 1, folder_path: []const u8, id_file: ?File = null, pub fn init(folder_path: []const u8) !Self { std.log.debug("using folder '{s}'\n", .{folder_path}); // Create a folder to store data and continue if the folder already exists so it is opened. std.os.mkdir(folder_path, 600) catch |err| { _ = switch (err) { MakeDirError.PathAlreadyExists => void, //open the content of the folder, else => return err, }; }; //TODO Read contents of folder, return error if unexpected content // Find SST ID File by its extension var dir = try std.fs.openDirAbsolute(folder_path, std.fs.Dir.OpenDirOptions{ .iterate = true }); var iter = dir.iterate(); //TODO URGENT fix this while (true) { var next = try iter.next(); if (next == null) { break; } // std.debug.print("File found in folder '{s}': {s}\n", .{ folder_path, next.?.name }); } return Self{ .folder_path = folder_path, }; } /// No deallocations are needed. /// /// Callers must close the file when they are done with it. Unfortunately /// there's not "WriterCloser" to return a writer than can be closed so the /// concrete File implementation must be returned. /// /// TODO build an wrapper to allow using a File like a WriterCloser interface to allow switching /// implementations (to transparently do compression, for example). pub fn new_sst_file(self: *Self, allocator: *std.mem.Allocator) !File { const file_id: []u8 = try self.get_new_file_id(allocator); defer allocator.free(file_id); var full_path = try std.fmt.allocPrint(allocator.*, "{s}/{s}.sst", .{ self.folder_path, file_id }); defer allocator.free(full_path); var f = try std.fs.createFileAbsolute(full_path, File.CreateFlags{ .exclusive = true }); return f; } /// Writes all the contents of a WAL to disk, requesting a new file to itself pub fn persist_wal(self: *Self, wal: *WalType) !usize { //TODO Use a one time allocator somehow in the following line //Create a new file var alloc = std.testing.allocator; var f = try self.new_sst_file(&alloc); defer f.close(); //Sort the wal in place wal.sort(); //Iterate var iter = wal.iterator(); var written: usize = 0; var total_record_bytes: usize = 0; var buf: [2048]u8 = undefined; while (iter.next()) |record| { total_record_bytes = try lsmtree.serialize.record.toBytes(record, &buf); written += try f.write(buf[0..total_record_bytes]); } return written; } /// No deallocations are needed. pub fn read_file(self: *Self, filename: []const u8, allocator: *std.mem.Allocator) !ArrayList(*Record) { var full_path = try std.fmt.allocPrint(allocator.*, "{s}/{s}.sst", .{ self.folder_path, filename }); defer allocator.free(full_path); var f = try std.fs.openFileAbsolute(full_path, File.OpenFlags{}); var all = try f.readToEndAlloc(allocator.*, 4096); defer allocator.free(all); var list = std.ArrayList(*Record).init(allocator.*); var seek_pos: usize = 0; var alloc = allocator; while (lsmtree.serialize.record.fromBytes(all[seek_pos..], alloc)) |r| { seek_pos += r.record_size_in_bytes; try list.append(r); } return list; } // TODO it must return a unique numeric id for the file being created. fn get_new_file_id(self: *Self, allocator: *std.mem.Allocator) ![]u8 { // var full_path = try std.fmt.allocPrint(allocator, "{s}/{s}.sst", .{ self.folder_path, filename }); // std.fs.openFileAbsolute(); var buf = try std.fmt.allocPrint(allocator.*, "{d}", .{self.file_id}); self.file_id = self.file_id + 1; return buf; } // TODO Return a list of the SST files in the folder. fn get_files(self: *Self) !void { // Read every file from self.folder_path // Discard all unknown files // Return the array of files } }; } test "disk_manager.create or open SST ID file" {} test "disk_manager.read file" { try testWriteWalToDisk("/tmp"); // Remove testing file defer _ = std.fs.deleteFileAbsolute("/tmp/1.sst") catch null; var path = "/tmp".*; var dm = DiskManager(Wal(100)){ .folder_path = path[0..] }; var alloc = std.testing.allocator; var list = try dm.read_file("1", &alloc); while (list.popOrNull()) |r| { r.deinit(); } defer list.deinit(); } fn testWriteWalToDisk(path: []const u8) !void { const WalType = Wal(100); var alloc = std.testing.allocator; var wal = try WalType.init(&alloc); defer wal.deinit_cascade(); try wal.add_record(try Record.init("hell", "world", Op.Create, &alloc)); try wal.add_record(try Record.init("hell1", "world", Op.Create, &alloc)); try wal.add_record(try Record.init("hell2", "world", Op.Create, &alloc)); var dm = DiskManager(WalType){ .folder_path = path[0..] }; const total_bytes = try dm.persist_wal(wal); try std.testing.expectEqual(@as(usize, 62), total_bytes); } test "disk_manager.write wal" { const path = "/tmp"; const WalType = Wal(100); var alloc = std.testing.allocator; var wal = try WalType.init(&alloc); defer wal.deinit_cascade(); try wal.add_record(try Record.init("hell", "world", Op.Create, &alloc)); try wal.add_record(try Record.init("hell1", "world", Op.Create, &alloc)); try wal.add_record(try Record.init("hell2", "world", Op.Create, &alloc)); var dm = DiskManager(WalType){ .folder_path = path[0..] }; const total_bytes = try dm.persist_wal(wal); try std.testing.expectEqual(@as(usize, 62), total_bytes); // Remove testing file _ = std.fs.deleteFileAbsolute("/tmp/1.sst") catch null; } test "disk_manager.get new file id" { const WalType = Wal(100); var dm = DiskManager(WalType){ .folder_path = "/tmp" }; var alloc = std.testing.allocator; var f = try dm.get_new_file_id(&alloc); defer alloc.free(f); } test "disk_manager.create file" { const WalType = Wal(100); var dm = DiskManager(WalType){ .folder_path = "/tmp" }; var alloc = std.testing.allocator; var f = try dm.new_sst_file(&alloc); defer f.close(); // Remove testing file defer _ = std.fs.deleteFileAbsolute("/tmp/1.sst") catch null; } test "disk_manager.size on memory" { try std.testing.expectEqual(32, @sizeOf(DiskManager(Wal(100)))); }
src/disk_manager.zig
const std = @import("std"); const input = @embedFile("day03.txt"); pub fn main() !void { { // Part 1 var lines = std.mem.split(u8, input, "\n"); var bit_counts = [_]u32{0} ** 12; var line_count: usize = 0; while (lines.next()) |bit_pattern| : (line_count += 1) { for (bit_pattern) |bit, idx| { if (bit == '1') bit_counts[idx] += 1; } } var gamma_rate: u12 = 0; for (bit_counts) |bit_count, idx| { if (bit_count > line_count / 2) { gamma_rate |= @as(u12, 1) << (11 - @intCast(u4, idx)); } } const epsilon_rate: u12 = ~gamma_rate; std.debug.print("Part 1: {d}\n", .{@as(u32, epsilon_rate) * gamma_rate}); } { // Part 2 var nums: [1000]u12 = undefined; { var lines = std.mem.split(u8, input, "\n"); var idx: usize = 0; while (lines.next()) |bit_pattern| : (idx += 1) { nums[idx] = try std.fmt.parseUnsigned(u12, bit_pattern, 2); } } var oxygen_generator_rating: u12 = result: { var nums_copy: [1000]u12 = undefined; std.mem.copy(u12, nums_copy[0..], nums[0..]); break :result findOxygenGeneratorRating(11, nums_copy[0..])[0]; }; var co2_scrubber_rating: u12 = findC02ScrubberRating(11, nums[0..])[0]; std.debug.print("Part 2: {d}\n", .{@as(u32, oxygen_generator_rating) * co2_scrubber_rating}); } } fn findOxygenGeneratorRating(bit_idx: usize, nums: []u12) []u12 { const most_common_bit = mostCommonBit(bit_idx, nums); var filtered_nums = filterByBitPrefix(bit_idx, most_common_bit, nums); if (filtered_nums.len == 1) return filtered_nums; return findOxygenGeneratorRating(bit_idx - 1, filtered_nums); } fn findC02ScrubberRating(bit_idx: usize, nums: []u12) []u12 { const least_common_bit = leastCommonBit(bit_idx, nums); var filtered_nums = filterByBitPrefix(bit_idx, least_common_bit, nums); if (filtered_nums.len == 1) return filtered_nums; return findC02ScrubberRating(bit_idx - 1, filtered_nums); } fn mostCommonBit(bit_idx: usize, nums: []u12) u1 { const ones = countOnes(bit_idx, nums); const zeros = nums.len - ones; return if (ones >= zeros) 1 else 0; } fn leastCommonBit(bit_idx: usize, nums: []u12) u1 { const ones = countOnes(bit_idx, nums); const zeros = nums.len - ones; return if (zeros > ones) 1 else 0; } fn countOnes(bit_idx: usize, nums: []u12) usize { var ones: usize = 0; for (nums) |num| { if (num & (@as(u12, 1) << @intCast(u4, bit_idx)) != 0) { ones += 1; } } return ones; } fn filterByBitPrefix(bit_idx: usize, bit: u1, nums: []u12) []u12 { var idx: usize = 0; for (nums) |num| { if (isBitSet(num, bit_idx, bit)) { nums[idx] = num; idx += 1; } } return nums[0..idx]; } fn isBitSet(num: u12, bit_idx: usize, bit: u1) bool { const bit_result: u1 = if (num & @as(u12, 1) << @intCast(u4, bit_idx) == 0) 0 else 1; return bit_result == bit; }
2021/day03.zig
const std = @import("std"); const with_trace = true; const assert = std.debug.assert; fn trace(comptime fmt: []const u8, args: anytype) void { if (with_trace) std.debug.print(fmt, args); } const Attribs = enum { children, cats, samoyeds, pomeranians, akitas, vizslas, goldfish, trees, cars, perfumes, const asString = comptime blk: { var names = [1][]const u8{""} ** @memberCount(Attribs); for (names) |*n, i| { n.* = @memberName(Attribs, i); } break :blk names; }; }; const Aunt = struct { name: []const u8, att: [@memberCount(Attribs)]?u32, }; fn parse_line(line: []const u8) Aunt { // Sue 279: perfumes: 9, cars: 8, vizslas: 2 var aunt = Aunt{ .name = undefined, .att = [1]?u32{null} ** @memberCount(Attribs) }; var slice = line; var sep = std.mem.indexOf(u8, slice, ": "); aunt.name = slice[0..sep.?]; slice = slice[sep.? + 2 ..]; while (slice.len > 0) { sep = std.mem.indexOf(u8, slice, ": "); const atrribute = slice[0..sep.?]; slice = slice[sep.? + 2 ..]; sep = std.mem.indexOf(u8, slice, ", "); const value = if (sep) |s| slice[0..s] else slice; slice = if (sep) |s| slice[s + 2 ..] else slice[0..0]; var found = false; for (aunt.att) |*att, i| { if (std.mem.eql(u8, atrribute, Attribs.asString[i])) { found = true; att.* = std.fmt.parseInt(u32, value, 10) catch unreachable; } } assert(found); } return aunt; } pub fn main() anyerror!void { var arena = std.heap.ArenaAllocator.init(std.heap.page_allocator); defer arena.deinit(); const allocator = arena.allocator(); const limit = 1 * 1024 * 1024 * 1024; const text = try std.fs.cwd().readFileAlloc(allocator, "day16.txt", limit); var clues: [@memberCount(Attribs)]u32 = undefined; clues[@enumToInt(Attribs.children)] = 3; clues[@enumToInt(Attribs.cats)] = 7; clues[@enumToInt(Attribs.samoyeds)] = 2; clues[@enumToInt(Attribs.pomeranians)] = 3; clues[@enumToInt(Attribs.akitas)] = 0; clues[@enumToInt(Attribs.vizslas)] = 0; clues[@enumToInt(Attribs.goldfish)] = 5; clues[@enumToInt(Attribs.trees)] = 3; clues[@enumToInt(Attribs.cars)] = 2; clues[@enumToInt(Attribs.perfumes)] = 1; var it = std.mem.tokenize(u8, text, "\n"); var combi: u32 = 1; while (it.next()) |line| { const aunt = parse_line(line); var ok = true; for (aunt.att) |att, i| { const e = @intToEnum(Attribs, @intCast(u4, i)); if (att) |a| { ok = ok and switch (e) { .cats, .trees => (a > clues[i]), .pomeranians, .goldfish => (a < clues[i]), else => (a == clues[i]), }; } } if (ok) trace("{}\n", aunt); } const out = std.io.getStdOut().writer(); try out.print("pass = {} \n", text.len); // return error.SolutionNotFound; }
2015/day16.zig
const std = @import("std"); const warn = std.debug.warn; const wgi = @import("WindowGraphicsInput/WindowGraphicsInput.zig"); const window = wgi.window; const input = wgi.input; const c = wgi.c; const Constants = wgi.Constants; const vertexarray = wgi.vertexarray; const buffer = wgi.buffer; const render = @import("RTRenderEngine/RTRenderEngine.zig"); const Texture2D = render.Texture2D; const ModelData = render.ModelData; const Animation = render.Animation; const c_allocator = std.heap.c_allocator; const maths = @import("Mathematics/Mathematics.zig"); const Matrix = maths.Matrix; const Vector = maths.Vector; const Files = @import("Files.zig"); const loadFile = Files.loadFile; const compress = @import("Compress/Compress.zig"); const assets = @import("Assets/Assets.zig"); const Asset = assets.Asset; const HSV2RGB = @import("Colour.zig").HSV2RGB; const scenes = @import("Scene/Scene.zig"); var mouse_button_down: bool = false; fn mouseCallback(button: i32, action: i32, mods: i32) void { if (button == 0) { mouse_button_down = action != Constants.RELEASE; } } var fullscreen: bool = false; fn keyCallback(key: i32, scancode: i32, action: i32, mods: i32) void { if (action == Constants.RELEASE and key == Constants.KEY_F11) { if (fullscreen) { window.exitFullScreen(1024, 768); } else { window.goFullScreen(); } fullscreen = !fullscreen; } } fn assetFileLoaded(a: *Asset) void { std.debug.warn("Asset file loaded: {}\n", .{a.*.file_path[0..a.*.file_path_len]}); } fn assetLoaded(a: *Asset) void { std.debug.warn("Asset loaded: {}\n", .{a.*.file_path[0..a.*.file_path_len]}); } pub fn main() !void { errdefer @import("ErrorDialog.zig").showErrorMessageDialog("Fatal Error", "An error has occurred."); assets.setAssetsDirectory("DemoAssets" ++ Files.path_seperator); var assets_list = std.ArrayList(Asset).init(c_allocator); defer assets_list.deinit(); try assets_list.resize(6); var minotaur_model_asset = &assets_list.items[0]; var minotaur_texture_asset = &assets_list.items[1]; var minotaur_normal_map_asset = &assets_list.items[2]; var minotaur_texture2_asset = &assets_list.items[3]; var minotaur_normal_map2_asset = &assets_list.items[4]; var minotaur_animation_asset = &assets_list.items[5]; minotaur_model_asset.* = try Asset.init("minotaur.model.compressed"); minotaur_texture_asset.* = try Asset.init("minotaur.png"); minotaur_texture_asset.texture_channels = 4; minotaur_normal_map_asset.* = try Asset.init("minotaur_normal.png"); minotaur_normal_map_asset.texture_channels = 4; minotaur_texture2_asset.* = try Asset.init("minotaur2.png"); minotaur_texture2_asset.texture_channels = 4; minotaur_normal_map2_asset.* = try Asset.init("minotaur_normal2.png"); minotaur_normal_map2_asset.texture_channels = 4; minotaur_animation_asset.* = try Asset.init("minotaur_idle.anim.compressed"); defer { for (assets_list.items) |*a| { if (a.state != Asset.AssetState.Freed) { std.debug.warn("Asset {} not freed\n", .{a.file_path[0..a.file_path_len]}); if (a.data != null) { std.debug.warn("\t^ Data has not been freed either\n", .{}); } } } } for (assets_list.items) |*a| { a.*.whenFileLoaded = assetFileLoaded; a.*.whenAssetDecoded = assetLoaded; } try assets.startAssetLoader1(assets_list.items, c_allocator); defer assets.assetLoaderCleanup(); try window.createWindow(fullscreen, 1024, 768, "Demo 2", true, 0); defer window.closeWindow(); input.setKeyCallback(keyCallback); window.setResizeable(true); input.setMouseButtonCallback(mouseCallback); try render.init(wgi.getMicroTime(), c_allocator); defer render.deinit(c_allocator); const settings = render.getSettings(); settings.max_fragment_lights = 1; settings.max_vertex_lights = 0; settings.ambient[0] = 0.1; settings.ambient[1] = 0.1; settings.ambient[2] = 0.1; settings.clear_colour[0] = 0.5; settings.clear_colour[1] = 0.5; settings.clear_colour[2] = 0.5; settings.enable_directional_lights = false; settings.enable_spot_lights = false; settings.enable_shadows = false; var root_object: render.Object = render.Object.init("root"); // Deletes all objects and frees all resources defer root_object.delete(true); var camera: render.Object = render.Object.init("camera"); try root_object.addChild(&camera); camera.setTransform(Matrix(f32, 4).translate(Vector(f32, 3).init([3]f32{ 0, 1, 5 }))); render.setActiveCamera(&camera); var light: render.Object = render.Object.init("light"); light.light = render.Light{ .light_type = render.Light.LightType.Point, .colour = [3]f32{ 100.0, 100.0, 100.0 }, .attenuation = 0.8, .cast_realtime_shadows = false, }; light.setTransform(Matrix(f32, 4).translate(Vector(f32, 3).init([3]f32{ 4.0, 4.0, 1.0 }))); try root_object.addChild(&light); // Wait for game assets to finish loading while (!assets.assetsLoaded()) { window.pollEvents(); if (window.windowShouldClose()) { return; } std.time.sleep(100000000); } for (assets_list.items) |*a| { if (a.state != Asset.AssetState.Ready) { return error.AssetLoadError; } } var minotaur_object = render.Object.init("minotaur"); var minotaur_mesh: render.Mesh = try render.Mesh.initFromAsset(minotaur_model_asset, false); var t = try Texture2D.loadFromAsset(minotaur_texture_asset); var t2 = try Texture2D.loadFromAsset(minotaur_normal_map_asset); var t3 = try Texture2D.loadFromAsset(minotaur_texture2_asset); var t4 = try Texture2D.loadFromAsset(minotaur_normal_map2_asset); var minotaur_mesh_renderer = try render.MeshRenderer.init(&minotaur_mesh, c_allocator); minotaur_object.setMeshRenderer(&minotaur_mesh_renderer); // Body minotaur_object.mesh_renderer.?.materials[1].setTexture(&t); minotaur_object.mesh_renderer.?.materials[1].setNormalMap(&t2); minotaur_object.mesh_renderer.?.materials[1].specular_intensity = 10.0; // Clothes minotaur_object.mesh_renderer.?.materials[0].setTexture(&t3); minotaur_object.mesh_renderer.?.materials[0].setNormalMap(&t4); minotaur_object.mesh_renderer.?.materials[0].specular_intensity = 0.0; var animation_object = try Animation.initFromAssets(minotaur_animation_asset, minotaur_model_asset, c_allocator); minotaur_object.mesh_renderer.?.setAnimationObject(&animation_object); try root_object.addChild(&minotaur_object); // Free assets (data has been uploaded the GPU) for (assets_list.items) |*a| { a.freeData(); } // - var mouse_pos_prev: [2]i32 = input.getMousePosition(); var last_frame_time = wgi.getMicroTime(); var last_fps_print_time = last_frame_time; var fps_count: u32 = 0; var brightness: f32 = 1.0; var contrast: f32 = 1.0; var model_rotation: f32 = 0.0; // Game loop while (!window.windowShouldClose()) { if (input.isKeyDown(Constants.KEY_ESCAPE)) { break; } const micro_time = wgi.getMicroTime(); const this_frame_time = micro_time; const deltaTime = @intToFloat(f32, this_frame_time - last_frame_time) * 0.000001; last_frame_time = this_frame_time; if (this_frame_time - last_fps_print_time >= 990000) { warn("{}\n", .{fps_count + 1}); fps_count = 0; last_fps_print_time = this_frame_time; } else { fps_count += 1; } if (input.isKeyDown(Constants.KEY_LEFT_BRACKET)) { brightness -= 0.06; if (brightness < 0.0) { brightness = 0.0; } } else if (input.isKeyDown(Constants.KEY_RIGHT_BRACKET)) { brightness += 0.06; } if (input.isKeyDown(Constants.KEY_COMMA)) { contrast -= 0.01; if (contrast < 0.0) { contrast = 0.0; } } else if (input.isKeyDown(Constants.KEY_PERIOD)) { contrast += 0.01; } if (input.isKeyDown(Constants.KEY_P)) { animation_object.pause(); } else if (input.isKeyDown(Constants.KEY_U)) { animation_object.unpause(); } render.setImageCorrection(brightness, contrast); const mouse_pos = input.getMousePosition(); if (mouse_button_down) { // Rotate minotaur to in direction of mouse cursor model_rotation += @intToFloat(f32, mouse_pos[0] - mouse_pos_prev[0]) * deltaTime; minotaur_object.setTransform(Matrix(f32, 4).rotateY(model_rotation)); } mouse_pos_prev = mouse_pos; try render.render(&root_object, micro_time, c_allocator); window.swapBuffers(); window.pollEvents(); } }
src/Demo2.zig
const std = @import("std"); const testing = std.testing; const c = @import("c/c.zig"); const utils = @import("utils.zig"); pub usingnamespace @import("types.zig"); pub usingnamespace @import("events.zig"); pub const ConsoleApp = struct { const Self = @This(); stdin_handle: c.HANDLE, stdout_handle: c.HANDLE, pub fn init() !Self { return Self{ .stdin_handle = try c.GetStdHandle(c.STD_INPUT_HANDLE), .stdout_handle = try c.GetStdHandle(c.STD_OUTPUT_HANDLE) }; } pub fn getInputMode(self: Self) !InputMode { var mode: c.DWORD = undefined; if (c.GetConsoleMode(self.stdin_handle, &mode) == 0) { switch (c.kernel32.GetLastError()) { else => |err| return c.unexpectedError(err), } } return utils.fromUnsigned(InputMode, mode); } pub fn setInputMode(self: Self, mode: InputMode) !void { if (c.SetConsoleMode(self.stdin_handle, utils.toUnsigned(InputMode, mode)) == 0) { switch (c.kernel32.GetLastError()) { else => |err| return c.unexpectedError(err), } } } pub fn getOutputMode(self: Self) !OutputMode { var mode: c.DWORD = undefined; if (c.GetConsoleMode(self.stdout_handle, &mode) == 0) { switch (c.kernel32.GetLastError()) { else => |err| return c.unexpectedError(err), } } return utils.fromUnsigned(OutputMode, mode); } pub fn setOutputMode(self: Self, mode: OutputMode) !void { if (c.SetConsoleMode(self.stdout_handle, utils.toUnsigned(OutputMode, mode)) == 0) { switch (c.kernel32.GetLastError()) { else => |err| return c.unexpectedError(err), } } } pub fn getEvent(self: Self) !Event { var events: u32 = 0; var input_record = std.mem.zeroes(c.INPUT_RECORD); if (c.ReadConsoleInputW(self.stdin_handle, &input_record, 1, &events) == 0) { switch (c.kernel32.GetLastError()) { else => |err| return c.unexpectedError(err), } } return Event.fromInputRecord(input_record); } pub fn viewportCoords(self: Self, coords: Coords, viewport_rect: ?Rect) !Coords { return Coords{.x = coords.x, .y = coords.y - (viewport_rect orelse (try self.getScreenBufferInfo()).viewport_rect).top}; } pub fn getScreenBufferInfo(self: Self) !ScreenBufferInfo { var bf = std.mem.zeroes(c.CONSOLE_SCREEN_BUFFER_INFO); if (c.kernel32.GetConsoleScreenBufferInfo(self.stdout_handle, &bf) == 0) { switch (c.kernel32.GetLastError()) { else => |err| return c.unexpectedError(err), } } return @bitCast(ScreenBufferInfo, bf); } pub fn getCodepage(self: Self) c_uint { return c.GetConsoleOutputCP(); } pub fn setCodepage(self: Self, codepage: c_uint) !void { if (c.SetConsoleOutputCP(codepage) == 0) { switch (c.kernel32.GetLastError()) { else => |err| return c.unexpectedError(err), } } } pub fn writeW(self: Self, buf: []u16) !void { if (c.WriteConsoleW(self.stdout_handle, buf.ptr, @intCast(u32, buf.len), null, null) == 0) { switch (c.kernel32.GetLastError()) { else => |err| return c.unexpectedError(err), } } } };
src/main.zig
const std = @import("std"); const json = std.json; const Tuple = std.meta.Tuple; pub fn IntBackedEnumStringify(comptime T: type) type { return struct { pub fn jsonStringify(value: T, options: json.StringifyOptions, out_stream: anytype) !void { try json.stringify(@enumToInt(value), options, out_stream); } }; } test "int-backed enum stringify" { const MyEnum = enum(i64) { one = 1, two = 2, usingnamespace IntBackedEnumStringify(@This()); }; var buf: [2]u8 = undefined; var fbs = std.io.fixedBufferStream(&buf); try json.stringify(MyEnum.one, .{}, fbs.writer()); try std.testing.expectEqual(@as(u8, '1'), buf[0]); try json.stringify(MyEnum.two, .{}, fbs.writer()); try std.testing.expectEqual(@as(u8, '2'), buf[1]); } pub fn StringBackedEnumStringify(comptime T: type) type { return struct { pub fn jsonStringify(value: T, options: json.StringifyOptions, out_stream: anytype) !void { inline for (std.meta.fields(T)) |field| { if (@enumToInt(value) == field.value) { try json.stringify(field.name, options, out_stream); return; } } unreachable; } }; } test "string-backed enum stringify" { const MyEnum = enum { one, two, usingnamespace StringBackedEnumStringify(@This()); }; var buf: [10]u8 = undefined; var fbs = std.io.fixedBufferStream(&buf); try json.stringify(MyEnum.one, .{}, fbs.writer()); try std.testing.expectEqualSlices(u8, "\"one\"", buf[0..5]); try json.stringify(MyEnum.two, .{}, fbs.writer()); try std.testing.expectEqualSlices(u8, "\"two\"", buf[5..]); } /// The LSP any type pub const LSPAny = std.json.Value; pub const ManuallyTranslateValue = @compileError("bruh 😭"); pub const RequestId = union(enum) { integer: i64, string: []const u8, }; test { // Test for general correctness of structs std.testing.refAllDecls(@This()); }
src/base.zig
const std = @import("std"); const MoveType = enum { ship, waypoint, }; const Ferry = struct { x: i64, y: i64, waypoint_x: i64, waypoint_y: i64, fn move(self: *Ferry, dx: i64, dy: i64, steps: i64, navigation_type: MoveType) void { var x_ptr = if (navigation_type == .ship) &self.x else &self.waypoint_x; var y_ptr = if (navigation_type == .ship) &self.y else &self.waypoint_y; x_ptr.* += dx * steps; y_ptr.* += dy * steps; } fn rotate(self: *Ferry, rot_y: i64, degrees: i64) void { std.debug.assert(@mod(degrees, 90) == 0); var to_rotate = degrees; while (to_rotate > 0) : (to_rotate -= 90) { const old_waypoint_x = self.waypoint_x; self.waypoint_x = -self.waypoint_y * rot_y; self.waypoint_y = old_waypoint_x * rot_y; } } fn distance_to_start(self: *Ferry) i64 { return (std.math.absInt(self.x) catch unreachable) + (std.math.absInt(self.y) catch unreachable); } }; fn navigate(input: []const u8, navigation_type: MoveType) i64 { var it = std.mem.tokenize(input, "\n"); var ferry = Ferry{ .x = 0, .y = 0, .waypoint_x = if (navigation_type == .ship) 1 else 10, .waypoint_y = if (navigation_type == .ship) 0 else 1, }; while (it.next()) |line| { const cmd = line[0]; const arg = std.fmt.parseInt(i64, line[1..], 10) catch unreachable; switch (cmd) { 'N' => ferry.move(0, 1, arg, navigation_type), 'S' => ferry.move(0, -1, arg, navigation_type), 'E' => ferry.move(1, 0, arg, navigation_type), 'W' => ferry.move(-1, 0, arg, navigation_type), 'L' => ferry.rotate(1, arg), 'R' => ferry.rotate(-1, arg), 'F' => ferry.move(ferry.waypoint_x, ferry.waypoint_y, arg, MoveType.ship), else => unreachable, } } return ferry.distance_to_start(); } pub fn main() !void { var gpa = std.heap.GeneralPurposeAllocator(.{}){}; defer _ = gpa.deinit(); var input = try std.fs.cwd().readFileAlloc(&gpa.allocator, "12.txt", std.math.maxInt(usize)); defer gpa.allocator.free(input); std.debug.print("EASY: {}\n", .{navigate(input, MoveType.ship)}); std.debug.print("HARD: {}\n", .{navigate(input, MoveType.waypoint)}); }
src/day-12/main.zig
const std = @import("std"); const Builder = @import("std").build.Builder; //var gpa = std.heap.GeneralPurposeAllocator(.{}){}; var buffer = [_]u8{0} ** 4194304; var fba = std.heap.FixedBufferAllocator.init(buffer[0..]); const alloc = &fba.allocator; fn build_http_parser(b: *Builder) *std.build.RunStep { const ensure_lib_dir_exists = b.addSystemCommand( &[_][]const u8{ "mkdir", "-p", "./zig-cache/lib", }, ); const ensure_include_dir_exists = b.addSystemCommand( &[_][]const u8{ "mkdir", "-p", "./zig-cache/include/http-parser", }, ); const build_http_parser_c = b.addSystemCommand( &[_][]const u8{ "make", "-C", "./deps/http-parser", "package", }, ); build_http_parser_c.step.dependOn(&ensure_include_dir_exists.step); build_http_parser_c.step.dependOn(&ensure_lib_dir_exists.step); const install_http_parser_lib = b.addSystemCommand( &[_][]const u8{ "cp", "./deps/http-parser/libhttp_parser.a", "./zig-cache/lib/libhttp_parser.a", }, ); install_http_parser_lib.step.dependOn(&build_http_parser_c.step); const install_http_parser_headers = b.addSystemCommand( &[_][]const u8{ "cp", "./deps/http-parser/http_parser.h", "./zig-cache/include/http-parser/http_parser.h", }, ); install_http_parser_headers.step.dependOn(&install_http_parser_lib.step); return install_http_parser_headers; } fn build_libuv(b: *Builder) *std.build.RunStep { const ensure_lib_dir_exists = b.addSystemCommand( &[_][]const u8{ "mkdir", "-p", "./zig-cache/lib", }, ); const ensure_include_dir_exists = b.addSystemCommand( &[_][]const u8{ "mkdir", "-p", "./zig-cache/include/libuv", }, ); const make_build_dir = b.addSystemCommand( &[_][]const u8{ "mkdir", "-p", "./deps/libuv/build", }, ); make_build_dir.step.dependOn(&ensure_include_dir_exists.step); make_build_dir.step.dependOn(&ensure_include_dir_exists.step); const run_cmake = b.addSystemCommand( &[_][]const u8{ "cmake", "-DCMAKE_INSTALL_PREFIX=./zig-cache", "-S", "./deps/libuv/", "-B", "./deps/libuv/build/", }, ); run_cmake.step.dependOn(&make_build_dir.step); const build_libuv_step = b.addSystemCommand( &[_][]const u8{ "cmake", "--build", "./deps/libuv/build", }, ); build_libuv_step.step.dependOn(&run_cmake.step); const install_libuv_step = b.addSystemCommand( &[_][]const u8{ "cmake", "--install", "./deps/libuv/build", }, ); install_libuv_step.step.dependOn(&build_libuv_step.step); return install_libuv_step; } pub fn build(b: *Builder) !void { // Standard target options allows the person running `zig build` to choose // what target to build for. Here we do not override the defaults, which // means any target is allowed, and the default is native. Other options // for restricting supported target set are available. const target = b.standardTargetOptions(.{}); // Standard release options allow the person running `zig build` to select // between Debug, ReleaseSafe, ReleaseFast, and ReleaseSmall. const mode = b.standardReleaseOptions(); const http_parser = build_http_parser(b); const libuv = build_libuv(b); const exe = b.addExecutable("ztor", "src/main.zig"); exe.addPackagePath("zben", "./deps/zben/src/main.zig"); exe.addPackagePath("uri", "./deps/zig-uri/uri.zig"); exe.setTarget(target); exe.setBuildMode(mode); exe.addLibPath("./zig-cache/lib/"); exe.addIncludeDir("./zig-cache/include"); exe.linkSystemLibraryName("http_parser"); exe.linkSystemLibrary("uv"); exe.linkLibC(); exe.install(); exe.step.dependOn(&http_parser.step); exe.step.dependOn(&libuv.step); const uvtee = b.addExecutable("uvtee", "src/uv_examples/uvtee.zig"); uvtee.setTarget(target); uvtee.setBuildMode(mode); uvtee.addIncludeDir("./zig-cache/include"); uvtee.addLibPath("./zig-cache/lib/"); uvtee.linkSystemLibrary("uv"); uvtee.linkLibC(); uvtee.install(); const uvserver = b.addExecutable("uvserver", "src/uv_examples/uvserver.zig"); uvserver.setTarget(target); uvserver.setBuildMode(mode); uvserver.linkSystemLibrary("uv"); uvserver.addIncludeDir("./zig-cache/include"); uvserver.addLibPath("./zig-cache/lib/"); uvserver.linkLibC(); uvserver.install(); const uvclient = b.addExecutable("uvclient", "src/uv_examples/uvclient.zig"); uvclient.setTarget(target); uvclient.setBuildMode(mode); uvclient.linkSystemLibrary("uv"); uvclient.addIncludeDir("./zig-cache/include"); uvclient.addLibPath("./zig-cache/lib/"); uvclient.linkLibC(); uvclient.install(); const run_cmd = exe.run(); run_cmd.step.dependOn(b.getInstallStep()); const uvtee_cmd = uvtee.run(); uvtee_cmd.step.dependOn(b.getInstallStep()); const run_step = b.step("run", "Run the app"); run_step.dependOn(&run_cmd.step); const uvtee_step = b.step("uv_test", "Run uv test"); uvtee_step.dependOn(&uvtee_cmd.step); }
build.zig
const std = @import("std"); const StringList = std.ArrayList([]const u8); pub const ConfigDirectives = struct { strict_links: bool = true, index: ?[]const u8 = null, webroot: []const u8 = "", project_footer: bool = false, }; fn parseBool(string: []const u8) bool { if (std.mem.eql(u8, "yes", string)) return true; if (std.mem.eql(u8, "no", string)) return false; return false; } pub const BuildFile = struct { allocator: std.mem.Allocator, vault_path: []const u8, includes: StringList, config: ConfigDirectives, const Self = @This(); pub fn parse(allocator: std.mem.Allocator, input_data: []const u8) !Self { var includes = StringList.init(allocator); errdefer includes.deinit(); var file_lines_it = std.mem.split(u8, input_data, "\n"); var config = ConfigDirectives{}; var vault_path: ?[]const u8 = null; while (file_lines_it.next()) |line| { if (line.len == 0) continue; if (line[0] == '#') continue; const first_space_index = std.mem.indexOf(u8, line, " ") orelse return error.ParseError; const directive = std.mem.trim(u8, line[0..first_space_index], "\n"); const value = line[first_space_index + 1 ..]; if (std.mem.eql(u8, "vault", directive)) { vault_path = value; } else if (std.mem.eql(u8, "include", directive)) { try includes.append(value); } else if (std.mem.eql(u8, "index", directive)) { config.index = value; } else if (std.mem.eql(u8, "webroot", directive)) { config.webroot = value; } else if (std.mem.eql(u8, "strict_links", directive)) { config.strict_links = parseBool(value); } else if (std.mem.eql(u8, "project_footer", directive)) { config.project_footer = parseBool(value); } else { std.log.err("unknown directive '{s}'", .{directive}); return error.UnknownDirective; } } return Self{ .allocator = allocator, .vault_path = vault_path.?, .includes = includes, .config = config, }; } pub fn deinit(self: *Self) void { self.includes.deinit(); } }; test "build file works" { const test_file = \\vault /home/test/vault \\include Folder1/ \\include ./ \\include Folder2/ \\include TestFile.md \\index Abcdef ; var build_file = try BuildFile.parse(std.testing.allocator, test_file); defer build_file.deinit(); try std.testing.expectEqualStrings("/home/test/vault", build_file.vault_path); try std.testing.expectEqualStrings("Abcdef", build_file.config.index orelse return error.UnexpectedNull); try std.testing.expectEqual(@as(usize, 4), build_file.includes.items.len); }
src/build_file.zig
const std = @import("std"); const testing = std.testing; //! Contains what Luf sees as tokens //! This file solely contains the definitions of all tokens //! the parsing of the tokens can be found in the `Lexer`. /// Type Luf uses to define a token in the language const Token = @This(); token_type: TokenType, start: usize, end: usize, /// Identifiers that are considered a token pub const TokenType = enum { illegal, eof, period, // identifiers + literals identifier, integer, string, comment, // operators assign, plus, minus, percent, bang, asterisk, slash, less_than, greater_than, less_than_equal, greater_than_equal, equal, not_equal, ampersand, caret, pipe, tilde, equal_add, equal_sub, equal_mul, equal_div, equal_ampersand, equal_caret, equal_pipe, shift_left, shift_right, double_period, // delimiters comma, left_parenthesis, right_parenthesis, left_brace, right_brace, left_bracket, right_bracket, colon, query, // keywords function, mutable, constant, while_loop, for_loop, nil, import, // Reserved words in Zig, so we create literals @"and", @"or", @"true", @"false", @"if", @"else", @"return", @"continue", @"break", @"enum", @"switch", @"pub", // types bool_type, int_type, string_type, void_type, }; /// Lookup 'table' to check if an identifier is a keyword pub const Keywords = std.ComptimeStringMap(TokenType, .{ .{ "fn", .function }, .{ "mut", .mutable }, .{ "const", .constant }, .{ "while", .while_loop }, .{ "for", .for_loop }, .{ "nil", .nil }, .{ "import", .import }, .{ "true", .@"true" }, .{ "false", .@"false" }, .{ "if", .@"if" }, .{ "else", .@"else" }, .{ "return", .@"return" }, .{ "and", .@"and" }, .{ "or", .@"or" }, .{ "break", .@"break" }, .{ "continue", .@"continue" }, .{ "enum", .@"enum" }, .{ "switch", .@"switch" }, .{ "bool", .bool_type }, .{ "int", .int_type }, .{ "string", .string_type }, .{ "void", .void_type }, .{ "pub", .@"pub" }, }); /// Returns the string value of the token pub fn fmtString(token_type: comptime Token.TokenType) []const u8 { return switch (token_type) { .illegal => "[illegal]", .eof => "[eof]", // identifiers + literals .identifier => "[identifier]", .integer => "[integer]", .string => "[string]", .comment => "[comment]", .double_period => "..", // operators .assign => "=", .plus => "+", .minus => "-", .bang => "!", .asterisk => "*", .slash => "/", .less_than => "<", .greater_than => ">", .equal => "==", .not_equal => "!=", .less_than_equal => "<=", .greater_than_equal => ">=", .ampersand => "&", .caret => "^", .pipe => "|", .tilde => "~", .percent => "%", .period => ".", .equal_add => "+=", .equal_sub => "-=", .equal_mul => "*=", .equal_div => "/=", .equal_ampersand => "&=", .equal_caret => "^=", .equal_pipe => "|=", .shift_left => "<<", .shift_right => ">>", // delimiters .comma => ",", .left_parenthesis => "(", .right_parenthesis => ")", .left_brace => "{{", //escaped for fmt .right_brace => "}}", //escaped for fmt .left_bracket => "[", .right_bracket => "]", .colon => ":", .query => "?", // keywords .function => "fn", .mutable => "mut", .constant => "const", .while_loop => "while", .nil => "nil", .import => "import", .for_loop => "for", // literals because they are Zig keywords .@"and" => "and", .@"or" => "or", .@"true" => "true", .@"false" => "false", .@"if" => "if", .@"else" => "else", .@"return" => "return", .@"break" => "break", .@"continue" => "continue", .@"enum" => "enum", .@"switch" => "switch", .@"pub" => "pub", // types .bool_type => "bool", .string_type => "string", .int_type => "int", .void_type => "void", }; } /// Returns the correct type of the identifier. /// First checks if it's a keyword and returns the corresponding keyword, /// if no keyword is found, returns `.identifier`. pub fn findType(identifier: []const u8) Token.TokenType { return Token.Keywords.get(identifier) orelse .identifier; } test "Keywords" { const keywords = &[_][]const u8{ "fn", "mut", "const", "true", "false", "if", "else", "return", "while", "nil", "or", "and", "return", "for", "continue", "break", "enum", "switch", "bool", "int", "string", "void", "pub", }; for (keywords) |keyword| { try testing.expect(findType(keyword) != .identifier); } } test "Identifiers" { const identifiers = &[_][]const u8{ "a", "word", "random", }; for (identifiers) |identifier| { try testing.expect(findType(identifier) == .identifier); } }
src/Token.zig
const std = @import("std"); const builtin = @import("builtin"); const trace = @import("tracy.zig").trace; const fs = std.fs; const io = std.io; const mem = std.mem; const logger = std.log.scoped(.archive_main); const process = std.process; const Archive = @import("archive/Archive.zig"); const overview = \\Zig Archiver \\ \\Usage: zar [options] [-]<operation>[modifiers] [relpos] [count] <archive> [files] \\ \\Options: \\ --format=<type> \\ Can be default, gnu, darwin or bsd. This determines the format used to serialise an archive, this is ignored when parsing archives as type there is always inferred. When creating an archive the host machine is used to infer <type> if one is not specified. \\ --version \\ Print program version details and exit. \\ -h, --help \\ Print (this) help text and exit. \\ \\Ignored for compatability: \\ --plugin=<string> \\ \\Operations: \\ r - replace/insert [files] in <archive>, create archive if it does not exist. \\ d - delete [files] from <archive>. \\ m - move [files] in <archive>. \\ p - print contents of files in <archive>. \\ q - quick append [files] to <archive>. \\ s - act as ranlib. \\ t - display filenames in <archive>. \\ x - extract [files] from <archive>. \\ S - show symbols in the <archive>. \\ \\Modifiers: \\ c - Disable archive creation warning if inserting files to new archive. \\ u - Only update archive contents if [files] have more recent timestamps than it. \\ D - Use zero for timestamps, GIDs and UIDs in archived files (enabled by default). \\ U - Use real timestamps, GIDS and UIDs for archived files. \\ v - Print verbose output, depending on opertion: \\ S: show file names that symbols belong to. \\ s - Generate symbol table \\ S - Do not generate symbol table \\ r - Create sorted symbol table \\ R - Do not create sorted symbol table \\ \\Note, in the case of conflicting modifiers, the last one listed always takes precedence. \\ ; const version = "0.0.0"; const version_details = \\zar (https://github.com/moosichu/zar): \\ zar version {s} \\ {s} build \\ default archive type: {s} \\ host: {s}-{s}-{s} \\ ; pub const full_logging = builtin.mode == .Debug; pub const debug_errors = builtin.mode == .Debug; pub const log_level: std.log.Level = if (full_logging) .debug else .warn; // For the release standalone program, we just want to display concise errors // to the end-user, but during development we want them to show up as part of // the regular logging flow. pub fn log( comptime level: std.log.Level, comptime scope: @TypeOf(.EnumLiteral), comptime format: []const u8, args: anytype, ) void { const scope_prefix = "(" ++ @tagName(scope) ++ "): "; const prefix = level.asText() ++ scope_prefix; std.debug.getStderrMutex().lock(); defer std.debug.getStderrMutex().unlock(); const stderr = std.io.getStdErr().writer(); if (full_logging) { nosuspend stderr.print(prefix ++ format ++ "\n", args) catch return; } else { nosuspend stderr.print(format ++ "\n", args) catch return; } } // We want to show program overview if invalid argument combination is passed // through to the program be the user, we do this often enough that it's worth // having a procedure for it. fn printArgumentError(comptime errorString: []const u8, args: anytype) void { logger.err(overview ++ "\nShowing help text above as error occured:\n" ++ errorString, args); } fn checkArgsBounds(args: []const []const u8, index: u32, comptime missing_argument: []const u8) bool { if (index >= args.len) { printArgumentError("An " ++ missing_argument ++ " must be provided.", .{}); return false; } return true; } fn openOrCreateFile(cwd: fs.Dir, archive_path: []const u8, print_creation_warning: bool, created: *bool) !fs.File { created.* = false; const open_file_handle = cwd.openFile(archive_path, .{ .mode = .read_write }) catch |err| switch (err) { error.FileNotFound => { created.* = true; if (print_creation_warning) { logger.warn("Creating new archive as none exists at path provided\n", .{}); } const create_file_handle = try Archive.handleFileIoError(.creating, archive_path, cwd.createFile(archive_path, .{ .read = true })); return create_file_handle; }, else => { Archive.printFileIoError(.opening, archive_path, err); return err; }, }; return open_file_handle; } pub fn main() anyerror!void { const tracy = trace(@src()); defer tracy.end(); var arena = std.heap.ArenaAllocator.init(std.heap.page_allocator); defer arena.deinit(); var allocator = arena.allocator(); const args = process.argsAlloc(allocator) catch |err| if (debug_errors) { return err; } else { logger.err("Unknown error occured.", .{}); return; }; const cwd = fs.cwd(); archiveMain(cwd, allocator, args) catch |err| { handleArchiveError(err) catch |e| if (debug_errors) { return e; } else { logger.err("Unknown error occured.", .{}); }; }; } pub fn archiveMain(cwd: fs.Dir, allocator: anytype, args: []const []const u8) anyerror!void { // const tracy_zone = ztracy.zoneNC(@src(), "ArchiveMain", 0x00_ff_00_00, 1); // defer tracy_zone.end(); // skip the executable name const stdout = io.getStdOut().writer(); const stderr = io.getStdErr().writer(); var arg_index: u32 = 1; var archive_type = Archive.ArchiveType.ambiguous; // Process Options First var keep_processing_current_option = true; while (keep_processing_current_option) { if (!checkArgsBounds(args, arg_index, "operation")) { return; } keep_processing_current_option = false; var current_arg = args[arg_index]; { // TODO: Make sure an arg doesn't show up twice! const format_string_prefix = "--format="; const plugin_string_prefix = "--plugin="; const help_string = "--help"; const help_shortcut = "-h"; const version_string = "--version"; if (mem.startsWith(u8, current_arg, format_string_prefix)) { // TODO: Handle format option! keep_processing_current_option = true; const format_string = current_arg[format_string_prefix.len..]; if (mem.eql(u8, format_string, "default")) { // do nothing } else if (mem.eql(u8, format_string, "bsd")) { archive_type = .bsd; } else if (mem.eql(u8, format_string, "darwin")) { archive_type = .darwin; } else if (mem.eql(u8, format_string, "gnu")) { archive_type = .gnu; } else { // TODO: do an actual error here! return error.TODO; } arg_index = arg_index + 1; continue; } else if (mem.startsWith(u8, current_arg, plugin_string_prefix)) { keep_processing_current_option = true; arg_index = arg_index + 1; continue; } else if (args[arg_index].len == 0) { keep_processing_current_option = true; arg_index = arg_index + 1; continue; } else if (mem.eql(u8, current_arg, help_string) or mem.eql(u8, current_arg, help_shortcut)) { try stdout.print(overview, .{}); return; } else if (mem.eql(u8, current_arg, version_string)) { // TODO: calculate build, archive type & host! const target = builtin.target; const default_archive_type = @tagName(Archive.getDefaultArchiveTypeFromHost()); try stdout.print(version_details, .{ version, @tagName(builtin.mode), default_archive_type, @tagName(target.cpu.arch), @tagName(target.os.tag), @tagName(target.abi) }); return; } } } if (!checkArgsBounds(args, arg_index, "operation")) { return; } const operation_slice = slice: { // the operation may start with a hyphen - so slice it! var arg_slice = args[arg_index][0..args[arg_index].len]; if (arg_slice[0] == '-') { if (arg_slice.len == 1) { printArgumentError("A valid operation must be provided - only hyphen found.", .{}); return; } arg_slice = arg_slice[1..arg_slice.len]; } break :slice arg_slice; }; // Process Operation const operation = operation: { switch (operation_slice[0]) { 'r' => break :operation Archive.Operation.insert, 'd' => break :operation Archive.Operation.delete, 'm' => break :operation Archive.Operation.move, 'p' => break :operation Archive.Operation.print_contents, 'q' => break :operation Archive.Operation.quick_append, 's' => break :operation Archive.Operation.ranlib, 't' => break :operation Archive.Operation.print_names, 'x' => break :operation Archive.Operation.extract, 'S' => break :operation Archive.Operation.print_symbols, else => { printArgumentError("'{c}' is not a valid operation.", .{operation_slice[0]}); return; }, } }; if (operation == .ranlib) { // https://www.freebsd.org/cgi/man.cgi?query=ranlib&sektion=1&apropos=0&manpath=FreeBSD+13.0-RELEASE+and+Ports // logger.err("Operation {} still needs to be implemented!\n", .{operation}); // return error.TODO; // TODO: implement modifiers for this operation! } var modifiers: Archive.Modifiers = .{}; if (operation_slice.len > 1) { const modifier_slice = operation_slice[1..]; for (modifier_slice) |modifier_char| { switch (modifier_char) { 'c' => modifiers.create = true, 'u' => modifiers.update_only = true, 'U' => modifiers.use_real_timestamps_and_ids = true, 'D' => modifiers.use_real_timestamps_and_ids = false, 'v' => modifiers.verbose = true, 's' => modifiers.build_symbol_table = true, 'S' => modifiers.build_symbol_table = false, 'r' => modifiers.sort_symbol_table = .set_true, 'R' => modifiers.sort_symbol_table = .set_false, 'a' => modifiers.move_setting = .before, 'b', 'i' => modifiers.move_setting = .after, // TODO: should we print warning with unknown modifier? // TODO: handle other modifiers! else => {}, } } } arg_index = arg_index + 1; if (!checkArgsBounds(args, arg_index, "archive")) { return; } // TODO: Process [relpos] // TODO: Process [count] const archive_path = args[arg_index]; arg_index = arg_index + 1; const files = file_result: { if (args.len > arg_index) { break :file_result args[arg_index..args.len]; } const empty = [_][:0]u8{}; break :file_result &empty; }; switch (operation) { .insert => { var created = false; const file = try openOrCreateFile(cwd, archive_path, !modifiers.create, &created); defer file.close(); var archive = try Archive.create(cwd, file, archive_path, archive_type, modifiers, created); try archive.parse(allocator); try archive.insertFiles(allocator, files); try archive.finalize(allocator); }, .delete => { var created = false; const file = try openOrCreateFile(cwd, archive_path, !modifiers.create, &created); defer file.close(); var archive = try Archive.create(cwd, file, archive_path, archive_type, modifiers, created); try archive.parse(allocator); try archive.deleteFiles(files); try archive.finalize(allocator); }, .print_names => { const file = try Archive.handleFileIoError(.opening, archive_path, cwd.openFile(archive_path, .{})); defer file.close(); var archive = try Archive.create(cwd, file, archive_path, archive_type, modifiers, false); try archive.parse(allocator); for (archive.files.items) |parsed_file| { try stdout.print("{s}\n", .{parsed_file.name}); } }, .print_contents => { const file = try Archive.handleFileIoError(.opening, archive_path, cwd.openFile(archive_path, .{})); defer file.close(); var archive = try Archive.create(cwd, file, archive_path, archive_type, modifiers, false); try archive.parse(allocator); for (archive.files.items) |parsed_file| { try parsed_file.contents.write(stdout, stderr); } }, .print_symbols => { const file = try Archive.handleFileIoError(.opening, archive_path, cwd.openFile(archive_path, .{})); defer file.close(); var archive = try Archive.create(cwd, file, archive_path, archive_type, modifiers, false); try archive.parse(allocator); for (archive.symbols.items) |symbol| { if (modifiers.verbose) { if (symbol.file_index == Archive.invalid_file_index) { try stdout.print("?: {s}\n", .{symbol.name}); } else { try stdout.print("{s}: {s}\n", .{ archive.files.items[symbol.file_index].name, symbol.name }); } } else { try stdout.print("{s}\n", .{symbol.name}); } } }, .move => { var created = false; const file = try openOrCreateFile(cwd, archive_path, !modifiers.create, &created); defer file.close(); var archive = try Archive.create(cwd, file, archive_path, archive_type, modifiers, created); try archive.parse(allocator); try archive.moveFiles(files); try archive.finalize(allocator); }, .quick_append => { logger.err("quick append still needs to be implemented!\n", .{}); return error.TODO; }, .ranlib => { const file = try Archive.handleFileIoError(.opening, archive_path, cwd.openFile(archive_path, .{ .mode = .read_write })); defer file.close(); var archive = try Archive.create(cwd, file, archive_path, archive_type, modifiers, false); try archive.parse(allocator); try archive.finalize(allocator); }, .extract => { logger.err("extract still needs to be implemented!\n", .{}); return error.TODO; }, } } // TODO: systemically work through all errors, put them in an Archive error // set so that we know they print appropriate error messages, make this NOT // return any error type, and know we have a robust main program alongside // a usable API that returns a well-defined set of errors. fn handleArchiveError(err: anyerror) !void { { // we can ignore these errors because we log context specific // information about them at the time that they are thrown. const fields = comptime std.meta.fields(Archive.HandledError); inline for (fields) |field| { if (@field(Archive.HandledError, field.name) == err) { return; } } } switch (err) { // These are errors which already have appropraite log messages printed error.NotArchive => logger.err("Provided file is not an archive.", .{}), error.MalformedArchive, error.Overflow, error.InvalidCharacter => logger.err("Malformed archive provided.", .{}), error.OutOfMemory => logger.err("Program ran out of memory.", .{}), // TODO: ignore runtime errors as they aren't needed. // we bubble-up other errors as they are currently unhandled // TODO: handle these (either at top-level or in parsing method). // or have a bug reporting system (or make them not possible by explicitly // covering the union of all errors. else => return err, } }
src/main.zig
const std = @import("std"); const builtin = @import("builtin"); const stdx = @import("stdx"); const platform = @import("platform"); const Window = platform.Window; const graphics = @import("graphics"); const Color = graphics.Color; const ui = @import("ui"); const EventDispatcher = platform.EventDispatcher; const log = stdx.log.scoped(.helper); pub const App = struct { ui_mod: ui.Module, gctx: *graphics.Graphics, renderer: graphics.Renderer, cam: graphics.Camera, dispatcher: EventDispatcher, win: Window, fps_limiter: graphics.DefaultFpsLimiter, quit: bool, last_frame_time_ms: f64, alloc: std.mem.Allocator, const Self = @This(); pub fn init(self: *Self, title: []const u8) void { const alloc = stdx.heap.getDefaultAllocator(); self.alloc = alloc; self.dispatcher = EventDispatcher.init(alloc); self.win = Window.init(alloc, .{ .title = title, .width = 1200, .height = 800, .high_dpi = true, .resizable = true, .mode = .Windowed, .anti_alias = false, }) catch unreachable; self.win.addDefaultHandlers(&self.dispatcher); self.renderer.init(alloc, &self.win); self.gctx = self.renderer.getGraphics(); self.gctx.setClearColor(Color.init(20, 20, 20, 255)); self.cam.init2D(self.win.getWidth(), self.win.getHeight()); // Create an fps limiter in case vsync is off or not supported. self.fps_limiter = graphics.DefaultFpsLimiter.init(30); self.quit = false; const S = struct { fn onQuit(ptr: ?*anyopaque) void { const self_ = stdx.mem.ptrCastAlign(*App, ptr.?); self_.quit = true; } }; self.dispatcher.addOnQuit(self, S.onQuit); if (builtin.target.isWasm()) { self.last_frame_time_ms = stdx.time.getMillisTime(); } self.ui_mod.init(self.alloc, self.gctx); self.ui_mod.addInputHandlers(&self.dispatcher); } pub fn runEventLoop(app: *Self, comptime update: fn (delta_ms: f32) void) void { while (!app.quit) { app.dispatcher.processEvents(); app.renderer.beginFrame(app.cam); app.fps_limiter.beginFrame(); const delta_ms = app.fps_limiter.getLastFrameDeltaMs(); update(delta_ms); app.renderer.endFrame(); const delay = app.fps_limiter.endFrame(); if (delay > 0) { platform.delay(delay); } } } pub fn deinit(self: *Self) void { self.ui_mod.deinit(); self.dispatcher.deinit(); self.renderer.deinit(self.alloc); self.win.deinit(); stdx.heap.deinitDefaultAllocator(); } }; pub fn wasmUpdate(cur_time_ms: f64, input_buffer_len: u32, app: *App, comptime update: fn (delta_ms: f32) void) *const u8 { // Update the input buffer view. stdx.wasm.js_buffer.input_buf.items.len = input_buffer_len; const delta_ms = cur_time_ms - app.last_frame_time_ms; app.last_frame_time_ms = cur_time_ms; app.dispatcher.processEvents(); app.renderer.beginFrame(app.cam); update(@floatCast(f32, delta_ms)); app.renderer.endFrame(); return stdx.wasm.js_buffer.writeResult(); } pub fn wasmInit(app: *App, title: []const u8) *const u8 { const alloc = stdx.heap.getDefaultAllocator(); stdx.wasm.init(alloc); app.init(title); return stdx.wasm.js_buffer.writeResult(); }
ui/examples/helper.zig
const std = @import("std"); const builtin = @import("builtin"); const is_test = builtin.is_test; const os_tag = builtin.os.tag; const arch = builtin.cpu.arch; const abi = builtin.abi; const is_gnu = abi.isGnu(); const is_mingw = os_tag == .windows and is_gnu; const is_darwin = std.Target.Os.Tag.isDarwin(os_tag); const linkage = if (is_test) std.builtin.GlobalLinkage.Internal else std.builtin.GlobalLinkage.Weak; const strong_linkage = if (is_test) std.builtin.GlobalLinkage.Internal else std.builtin.GlobalLinkage.Strong; const long_double_is_f80 = builtin.target.longDoubleIs(f80); const long_double_is_f128 = builtin.target.longDoubleIs(f128); comptime { // These files do their own comptime exporting logic. _ = @import("compiler_rt/atomics.zig"); if (builtin.zig_backend != .stage2_llvm) { // TODO _ = @import("compiler_rt/clear_cache.zig").clear_cache; } const __extenddftf2 = @import("compiler_rt/extendXfYf2.zig").__extenddftf2; @export(__extenddftf2, .{ .name = "__extenddftf2", .linkage = linkage }); const __extendsftf2 = @import("compiler_rt/extendXfYf2.zig").__extendsftf2; @export(__extendsftf2, .{ .name = "__extendsftf2", .linkage = linkage }); const __extendhfsf2 = @import("compiler_rt/extendXfYf2.zig").__extendhfsf2; @export(__extendhfsf2, .{ .name = "__extendhfsf2", .linkage = linkage }); const __extendhftf2 = @import("compiler_rt/extendXfYf2.zig").__extendhftf2; @export(__extendhftf2, .{ .name = "__extendhftf2", .linkage = linkage }); const __extendhfxf2 = @import("compiler_rt/extend_f80.zig").__extendhfxf2; @export(__extendhfxf2, .{ .name = "__extendhfxf2", .linkage = linkage }); const __extendsfxf2 = @import("compiler_rt/extend_f80.zig").__extendsfxf2; @export(__extendsfxf2, .{ .name = "__extendsfxf2", .linkage = linkage }); const __extenddfxf2 = @import("compiler_rt/extend_f80.zig").__extenddfxf2; @export(__extenddfxf2, .{ .name = "__extenddfxf2", .linkage = linkage }); const __extendxftf2 = @import("compiler_rt/extend_f80.zig").__extendxftf2; @export(__extendxftf2, .{ .name = "__extendxftf2", .linkage = linkage }); const __lesf2 = @import("compiler_rt/compareXf2.zig").__lesf2; @export(__lesf2, .{ .name = "__lesf2", .linkage = linkage }); const __ledf2 = @import("compiler_rt/compareXf2.zig").__ledf2; @export(__ledf2, .{ .name = "__ledf2", .linkage = linkage }); const __letf2 = @import("compiler_rt/compareXf2.zig").__letf2; @export(__letf2, .{ .name = "__letf2", .linkage = linkage }); const __lexf2 = @import("compiler_rt/compareXf2.zig").__lexf2; @export(__lexf2, .{ .name = "__lexf2", .linkage = linkage }); const __gesf2 = @import("compiler_rt/compareXf2.zig").__gesf2; @export(__gesf2, .{ .name = "__gesf2", .linkage = linkage }); const __gedf2 = @import("compiler_rt/compareXf2.zig").__gedf2; @export(__gedf2, .{ .name = "__gedf2", .linkage = linkage }); const __getf2 = @import("compiler_rt/compareXf2.zig").__getf2; @export(__getf2, .{ .name = "__getf2", .linkage = linkage }); const __gexf2 = @import("compiler_rt/compareXf2.zig").__gexf2; @export(__gexf2, .{ .name = "__gexf2", .linkage = linkage }); const __eqsf2 = @import("compiler_rt/compareXf2.zig").__eqsf2; @export(__eqsf2, .{ .name = "__eqsf2", .linkage = linkage }); const __eqdf2 = @import("compiler_rt/compareXf2.zig").__eqdf2; @export(__eqdf2, .{ .name = "__eqdf2", .linkage = linkage }); const __eqxf2 = @import("compiler_rt/compareXf2.zig").__eqxf2; @export(__eqxf2, .{ .name = "__eqxf2", .linkage = linkage }); const __ltsf2 = @import("compiler_rt/compareXf2.zig").__ltsf2; @export(__ltsf2, .{ .name = "__ltsf2", .linkage = linkage }); const __ltdf2 = @import("compiler_rt/compareXf2.zig").__ltdf2; @export(__ltdf2, .{ .name = "__ltdf2", .linkage = linkage }); const __ltxf2 = @import("compiler_rt/compareXf2.zig").__ltxf2; @export(__ltxf2, .{ .name = "__ltxf2", .linkage = linkage }); const __nesf2 = @import("compiler_rt/compareXf2.zig").__nesf2; @export(__nesf2, .{ .name = "__nesf2", .linkage = linkage }); const __nedf2 = @import("compiler_rt/compareXf2.zig").__nedf2; @export(__nedf2, .{ .name = "__nedf2", .linkage = linkage }); const __nexf2 = @import("compiler_rt/compareXf2.zig").__nexf2; @export(__nexf2, .{ .name = "__nexf2", .linkage = linkage }); const __gtsf2 = @import("compiler_rt/compareXf2.zig").__gtsf2; @export(__gtsf2, .{ .name = "__gtsf2", .linkage = linkage }); const __gtdf2 = @import("compiler_rt/compareXf2.zig").__gtdf2; @export(__gtdf2, .{ .name = "__gtdf2", .linkage = linkage }); const __gtxf2 = @import("compiler_rt/compareXf2.zig").__gtxf2; @export(__gtxf2, .{ .name = "__gtxf2", .linkage = linkage }); if (!is_test) { @export(__lesf2, .{ .name = "__cmpsf2", .linkage = linkage }); @export(__ledf2, .{ .name = "__cmpdf2", .linkage = linkage }); @export(__letf2, .{ .name = "__cmptf2", .linkage = linkage }); @export(__letf2, .{ .name = "__eqtf2", .linkage = linkage }); @export(__letf2, .{ .name = "__lttf2", .linkage = linkage }); @export(__getf2, .{ .name = "__gttf2", .linkage = linkage }); @export(__letf2, .{ .name = "__netf2", .linkage = linkage }); @export(__extendhfsf2, .{ .name = "__gnu_h2f_ieee", .linkage = linkage }); } if (builtin.os.tag == .windows) { // Default stack-probe functions emitted by LLVM if (is_mingw) { const _chkstk = @import("compiler_rt/stack_probe.zig")._chkstk; @export(_chkstk, .{ .name = "_alloca", .linkage = strong_linkage }); const ___chkstk_ms = @import("compiler_rt/stack_probe.zig").___chkstk_ms; @export(___chkstk_ms, .{ .name = "___chkstk_ms", .linkage = strong_linkage }); } else if (!builtin.link_libc) { // This symbols are otherwise exported by MSVCRT.lib const _chkstk = @import("compiler_rt/stack_probe.zig")._chkstk; @export(_chkstk, .{ .name = "_chkstk", .linkage = strong_linkage }); const __chkstk = @import("compiler_rt/stack_probe.zig").__chkstk; @export(__chkstk, .{ .name = "__chkstk", .linkage = strong_linkage }); } switch (arch) { .i386 => { const __divti3 = @import("compiler_rt/divti3.zig").__divti3; @export(__divti3, .{ .name = "__divti3", .linkage = linkage }); const __modti3 = @import("compiler_rt/modti3.zig").__modti3; @export(__modti3, .{ .name = "__modti3", .linkage = linkage }); const __multi3 = @import("compiler_rt/multi3.zig").__multi3; @export(__multi3, .{ .name = "__multi3", .linkage = linkage }); const __udivti3 = @import("compiler_rt/udivti3.zig").__udivti3; @export(__udivti3, .{ .name = "__udivti3", .linkage = linkage }); const __udivmodti4 = @import("compiler_rt/udivmodti4.zig").__udivmodti4; @export(__udivmodti4, .{ .name = "__udivmodti4", .linkage = linkage }); const __umodti3 = @import("compiler_rt/umodti3.zig").__umodti3; @export(__umodti3, .{ .name = "__umodti3", .linkage = linkage }); }, .x86_64 => { // The "ti" functions must use Vector(2, u64) parameter types to adhere to the ABI // that LLVM expects compiler-rt to have. const __divti3_windows_x86_64 = @import("compiler_rt/divti3.zig").__divti3_windows_x86_64; @export(__divti3_windows_x86_64, .{ .name = "__divti3", .linkage = linkage }); const __modti3_windows_x86_64 = @import("compiler_rt/modti3.zig").__modti3_windows_x86_64; @export(__modti3_windows_x86_64, .{ .name = "__modti3", .linkage = linkage }); const __multi3_windows_x86_64 = @import("compiler_rt/multi3.zig").__multi3_windows_x86_64; @export(__multi3_windows_x86_64, .{ .name = "__multi3", .linkage = linkage }); const __udivti3_windows_x86_64 = @import("compiler_rt/udivti3.zig").__udivti3_windows_x86_64; @export(__udivti3_windows_x86_64, .{ .name = "__udivti3", .linkage = linkage }); const __udivmodti4_windows_x86_64 = @import("compiler_rt/udivmodti4.zig").__udivmodti4_windows_x86_64; @export(__udivmodti4_windows_x86_64, .{ .name = "__udivmodti4", .linkage = linkage }); const __umodti3_windows_x86_64 = @import("compiler_rt/umodti3.zig").__umodti3_windows_x86_64; @export(__umodti3_windows_x86_64, .{ .name = "__umodti3", .linkage = linkage }); }, else => {}, } if (arch.isAARCH64()) { const __chkstk = @import("compiler_rt/stack_probe.zig").__chkstk; @export(__chkstk, .{ .name = "__chkstk", .linkage = strong_linkage }); const __divti3_windows = @import("compiler_rt/divti3.zig").__divti3; @export(__divti3_windows, .{ .name = "__divti3", .linkage = linkage }); const __modti3 = @import("compiler_rt/modti3.zig").__modti3; @export(__modti3, .{ .name = "__modti3", .linkage = linkage }); const __udivti3_windows = @import("compiler_rt/udivti3.zig").__udivti3; @export(__udivti3_windows, .{ .name = "__udivti3", .linkage = linkage }); const __umodti3 = @import("compiler_rt/umodti3.zig").__umodti3; @export(__umodti3, .{ .name = "__umodti3", .linkage = linkage }); } } else { const __divti3 = @import("compiler_rt/divti3.zig").__divti3; @export(__divti3, .{ .name = "__divti3", .linkage = linkage }); const __modti3 = @import("compiler_rt/modti3.zig").__modti3; @export(__modti3, .{ .name = "__modti3", .linkage = linkage }); const __multi3 = @import("compiler_rt/multi3.zig").__multi3; @export(__multi3, .{ .name = "__multi3", .linkage = linkage }); const __udivti3 = @import("compiler_rt/udivti3.zig").__udivti3; @export(__udivti3, .{ .name = "__udivti3", .linkage = linkage }); const __udivmodti4 = @import("compiler_rt/udivmodti4.zig").__udivmodti4; @export(__udivmodti4, .{ .name = "__udivmodti4", .linkage = linkage }); const __umodti3 = @import("compiler_rt/umodti3.zig").__umodti3; @export(__umodti3, .{ .name = "__umodti3", .linkage = linkage }); } const __truncdfhf2 = @import("compiler_rt/truncXfYf2.zig").__truncdfhf2; @export(__truncdfhf2, .{ .name = "__truncdfhf2", .linkage = linkage }); const __trunctfhf2 = @import("compiler_rt/truncXfYf2.zig").__trunctfhf2; @export(__trunctfhf2, .{ .name = "__trunctfhf2", .linkage = linkage }); const __trunctfdf2 = @import("compiler_rt/truncXfYf2.zig").__trunctfdf2; @export(__trunctfdf2, .{ .name = "__trunctfdf2", .linkage = linkage }); const __trunctfsf2 = @import("compiler_rt/truncXfYf2.zig").__trunctfsf2; @export(__trunctfsf2, .{ .name = "__trunctfsf2", .linkage = linkage }); const __truncdfsf2 = @import("compiler_rt/truncXfYf2.zig").__truncdfsf2; @export(__truncdfsf2, .{ .name = "__truncdfsf2", .linkage = linkage }); const __truncxfhf2 = @import("compiler_rt/trunc_f80.zig").__truncxfhf2; @export(__truncxfhf2, .{ .name = "__truncxfhf2", .linkage = linkage }); const __truncxfsf2 = @import("compiler_rt/trunc_f80.zig").__truncxfsf2; @export(__truncxfsf2, .{ .name = "__truncxfsf2", .linkage = linkage }); const __truncxfdf2 = @import("compiler_rt/trunc_f80.zig").__truncxfdf2; @export(__truncxfdf2, .{ .name = "__truncxfdf2", .linkage = linkage }); const __trunctfxf2 = @import("compiler_rt/trunc_f80.zig").__trunctfxf2; @export(__trunctfxf2, .{ .name = "__trunctfxf2", .linkage = linkage }); if (builtin.zig_backend == .stage1) { // TODO switch (arch) { .i386, .x86_64, => { const zig_probe_stack = @import("compiler_rt/stack_probe.zig").zig_probe_stack; @export(zig_probe_stack, .{ .name = "__zig_probe_stack", .linkage = linkage, }); }, else => {}, } } const __unordsf2 = @import("compiler_rt/compareXf2.zig").__unordsf2; @export(__unordsf2, .{ .name = "__unordsf2", .linkage = linkage }); const __unorddf2 = @import("compiler_rt/compareXf2.zig").__unorddf2; @export(__unorddf2, .{ .name = "__unorddf2", .linkage = linkage }); const __unordtf2 = @import("compiler_rt/compareXf2.zig").__unordtf2; @export(__unordtf2, .{ .name = "__unordtf2", .linkage = linkage }); const __addsf3 = @import("compiler_rt/addXf3.zig").__addsf3; @export(__addsf3, .{ .name = "__addsf3", .linkage = linkage }); const __adddf3 = @import("compiler_rt/addXf3.zig").__adddf3; @export(__adddf3, .{ .name = "__adddf3", .linkage = linkage }); const __addtf3 = @import("compiler_rt/addXf3.zig").__addtf3; @export(__addtf3, .{ .name = "__addtf3", .linkage = linkage }); const __addxf3 = @import("compiler_rt/addXf3.zig").__addxf3; @export(__addxf3, .{ .name = "__addxf3", .linkage = linkage }); const __subsf3 = @import("compiler_rt/addXf3.zig").__subsf3; @export(__subsf3, .{ .name = "__subsf3", .linkage = linkage }); const __subdf3 = @import("compiler_rt/addXf3.zig").__subdf3; @export(__subdf3, .{ .name = "__subdf3", .linkage = linkage }); const __subtf3 = @import("compiler_rt/addXf3.zig").__subtf3; @export(__subtf3, .{ .name = "__subtf3", .linkage = linkage }); const __subxf3 = @import("compiler_rt/addXf3.zig").__subxf3; @export(__subxf3, .{ .name = "__subxf3", .linkage = linkage }); const __mulsf3 = @import("compiler_rt/mulXf3.zig").__mulsf3; @export(__mulsf3, .{ .name = "__mulsf3", .linkage = linkage }); const __muldf3 = @import("compiler_rt/mulXf3.zig").__muldf3; @export(__muldf3, .{ .name = "__muldf3", .linkage = linkage }); const __multf3 = @import("compiler_rt/mulXf3.zig").__multf3; @export(__multf3, .{ .name = "__multf3", .linkage = linkage }); const __divsf3 = @import("compiler_rt/divsf3.zig").__divsf3; @export(__divsf3, .{ .name = "__divsf3", .linkage = linkage }); const __divdf3 = @import("compiler_rt/divdf3.zig").__divdf3; @export(__divdf3, .{ .name = "__divdf3", .linkage = linkage }); const __divtf3 = @import("compiler_rt/divtf3.zig").__divtf3; @export(__divtf3, .{ .name = "__divtf3", .linkage = linkage }); // Integer Bit operations const __clzsi2 = @import("compiler_rt/count0bits.zig").__clzsi2; @export(__clzsi2, .{ .name = "__clzsi2", .linkage = linkage }); const __clzdi2 = @import("compiler_rt/count0bits.zig").__clzdi2; @export(__clzdi2, .{ .name = "__clzdi2", .linkage = linkage }); const __clzti2 = @import("compiler_rt/count0bits.zig").__clzti2; @export(__clzti2, .{ .name = "__clzti2", .linkage = linkage }); const __ctzsi2 = @import("compiler_rt/count0bits.zig").__ctzsi2; @export(__ctzsi2, .{ .name = "__ctzsi2", .linkage = linkage }); const __ctzdi2 = @import("compiler_rt/count0bits.zig").__ctzdi2; @export(__ctzdi2, .{ .name = "__ctzdi2", .linkage = linkage }); const __ctzti2 = @import("compiler_rt/count0bits.zig").__ctzti2; @export(__ctzti2, .{ .name = "__ctzti2", .linkage = linkage }); const __ffssi2 = @import("compiler_rt/count0bits.zig").__ffssi2; @export(__ffssi2, .{ .name = "__ffssi2", .linkage = linkage }); const __ffsdi2 = @import("compiler_rt/count0bits.zig").__ffsdi2; @export(__ffsdi2, .{ .name = "__ffsdi2", .linkage = linkage }); const __ffsti2 = @import("compiler_rt/count0bits.zig").__ffsti2; @export(__ffsti2, .{ .name = "__ffsti2", .linkage = linkage }); const __paritysi2 = @import("compiler_rt/parity.zig").__paritysi2; @export(__paritysi2, .{ .name = "__paritysi2", .linkage = linkage }); const __paritydi2 = @import("compiler_rt/parity.zig").__paritydi2; @export(__paritydi2, .{ .name = "__paritydi2", .linkage = linkage }); const __parityti2 = @import("compiler_rt/parity.zig").__parityti2; @export(__parityti2, .{ .name = "__parityti2", .linkage = linkage }); const __popcountsi2 = @import("compiler_rt/popcount.zig").__popcountsi2; @export(__popcountsi2, .{ .name = "__popcountsi2", .linkage = linkage }); const __popcountdi2 = @import("compiler_rt/popcount.zig").__popcountdi2; @export(__popcountdi2, .{ .name = "__popcountdi2", .linkage = linkage }); const __popcountti2 = @import("compiler_rt/popcount.zig").__popcountti2; @export(__popcountti2, .{ .name = "__popcountti2", .linkage = linkage }); const __bswapsi2 = @import("compiler_rt/bswap.zig").__bswapsi2; @export(__bswapsi2, .{ .name = "__bswapsi2", .linkage = linkage }); const __bswapdi2 = @import("compiler_rt/bswap.zig").__bswapdi2; @export(__bswapdi2, .{ .name = "__bswapdi2", .linkage = linkage }); const __bswapti2 = @import("compiler_rt/bswap.zig").__bswapti2; @export(__bswapti2, .{ .name = "__bswapti2", .linkage = linkage }); // Integral -> Float Conversion // Conversion to f32 const __floatsisf = @import("compiler_rt/floatXiYf.zig").__floatsisf; @export(__floatsisf, .{ .name = "__floatsisf", .linkage = linkage }); const __floatunsisf = @import("compiler_rt/floatXiYf.zig").__floatunsisf; @export(__floatunsisf, .{ .name = "__floatunsisf", .linkage = linkage }); const __floatundisf = @import("compiler_rt/floatXiYf.zig").__floatundisf; @export(__floatundisf, .{ .name = "__floatundisf", .linkage = linkage }); const __floatdisf = @import("compiler_rt/floatXiYf.zig").__floatdisf; @export(__floatdisf, .{ .name = "__floatdisf", .linkage = linkage }); const __floattisf = @import("compiler_rt/floatXiYf.zig").__floattisf; @export(__floattisf, .{ .name = "__floattisf", .linkage = linkage }); const __floatuntisf = @import("compiler_rt/floatXiYf.zig").__floatuntisf; @export(__floatuntisf, .{ .name = "__floatuntisf", .linkage = linkage }); // Conversion to f64 const __floatsidf = @import("compiler_rt/floatXiYf.zig").__floatsidf; @export(__floatsidf, .{ .name = "__floatsidf", .linkage = linkage }); const __floatunsidf = @import("compiler_rt/floatXiYf.zig").__floatunsidf; @export(__floatunsidf, .{ .name = "__floatunsidf", .linkage = linkage }); const __floatdidf = @import("compiler_rt/floatXiYf.zig").__floatdidf; @export(__floatdidf, .{ .name = "__floatdidf", .linkage = linkage }); const __floatundidf = @import("compiler_rt/floatXiYf.zig").__floatundidf; @export(__floatundidf, .{ .name = "__floatundidf", .linkage = linkage }); const __floattidf = @import("compiler_rt/floatXiYf.zig").__floattidf; @export(__floattidf, .{ .name = "__floattidf", .linkage = linkage }); const __floatuntidf = @import("compiler_rt/floatXiYf.zig").__floatuntidf; @export(__floatuntidf, .{ .name = "__floatuntidf", .linkage = linkage }); // Conversion to f80 const __floatsixf = @import("compiler_rt/floatXiYf.zig").__floatsixf; @export(__floatsixf, .{ .name = "__floatsixf", .linkage = linkage }); const __floatunsixf = @import("compiler_rt/floatXiYf.zig").__floatunsixf; @export(__floatunsixf, .{ .name = "__floatunsixf", .linkage = linkage }); const __floatdixf = @import("compiler_rt/floatXiYf.zig").__floatdixf; @export(__floatdixf, .{ .name = "__floatdixf", .linkage = linkage }); const __floatundixf = @import("compiler_rt/floatXiYf.zig").__floatundixf; @export(__floatundixf, .{ .name = "__floatundixf", .linkage = linkage }); const __floattixf = @import("compiler_rt/floatXiYf.zig").__floattixf; @export(__floattixf, .{ .name = "__floattixf", .linkage = linkage }); const __floatuntixf = @import("compiler_rt/floatXiYf.zig").__floatuntixf; @export(__floatuntixf, .{ .name = "__floatuntixf", .linkage = linkage }); // Conversion to f128 const __floatsitf = @import("compiler_rt/floatXiYf.zig").__floatsitf; @export(__floatsitf, .{ .name = "__floatsitf", .linkage = linkage }); const __floatunsitf = @import("compiler_rt/floatXiYf.zig").__floatunsitf; @export(__floatunsitf, .{ .name = "__floatunsitf", .linkage = linkage }); const __floatditf = @import("compiler_rt/floatXiYf.zig").__floatditf; @export(__floatditf, .{ .name = "__floatditf", .linkage = linkage }); const __floatunditf = @import("compiler_rt/floatXiYf.zig").__floatunditf; @export(__floatunditf, .{ .name = "__floatunditf", .linkage = linkage }); const __floattitf = @import("compiler_rt/floatXiYf.zig").__floattitf; @export(__floattitf, .{ .name = "__floattitf", .linkage = linkage }); const __floatuntitf = @import("compiler_rt/floatXiYf.zig").__floatuntitf; @export(__floatuntitf, .{ .name = "__floatuntitf", .linkage = linkage }); // Float -> Integral Conversion // Conversion from f32 const __fixsfsi = @import("compiler_rt/fixXfYi.zig").__fixsfsi; @export(__fixsfsi, .{ .name = "__fixsfsi", .linkage = linkage }); const __fixunssfsi = @import("compiler_rt/fixXfYi.zig").__fixunssfsi; @export(__fixunssfsi, .{ .name = "__fixunssfsi", .linkage = linkage }); const __fixsfdi = @import("compiler_rt/fixXfYi.zig").__fixsfdi; @export(__fixsfdi, .{ .name = "__fixsfdi", .linkage = linkage }); const __fixunssfdi = @import("compiler_rt/fixXfYi.zig").__fixunssfdi; @export(__fixunssfdi, .{ .name = "__fixunssfdi", .linkage = linkage }); const __fixsfti = @import("compiler_rt/fixXfYi.zig").__fixsfti; @export(__fixsfti, .{ .name = "__fixsfti", .linkage = linkage }); const __fixunssfti = @import("compiler_rt/fixXfYi.zig").__fixunssfti; @export(__fixunssfti, .{ .name = "__fixunssfti", .linkage = linkage }); // Conversion from f64 const __fixdfsi = @import("compiler_rt/fixXfYi.zig").__fixdfsi; @export(__fixdfsi, .{ .name = "__fixdfsi", .linkage = linkage }); const __fixunsdfsi = @import("compiler_rt/fixXfYi.zig").__fixunsdfsi; @export(__fixunsdfsi, .{ .name = "__fixunsdfsi", .linkage = linkage }); const __fixdfdi = @import("compiler_rt/fixXfYi.zig").__fixdfdi; @export(__fixdfdi, .{ .name = "__fixdfdi", .linkage = linkage }); const __fixunsdfdi = @import("compiler_rt/fixXfYi.zig").__fixunsdfdi; @export(__fixunsdfdi, .{ .name = "__fixunsdfdi", .linkage = linkage }); const __fixdfti = @import("compiler_rt/fixXfYi.zig").__fixdfti; @export(__fixdfti, .{ .name = "__fixdfti", .linkage = linkage }); const __fixunsdfti = @import("compiler_rt/fixXfYi.zig").__fixunsdfti; @export(__fixunsdfti, .{ .name = "__fixunsdfti", .linkage = linkage }); // Conversion from f80 const __fixxfsi = @import("compiler_rt/fixXfYi.zig").__fixxfsi; @export(__fixxfsi, .{ .name = "__fixxfsi", .linkage = linkage }); const __fixunsxfsi = @import("compiler_rt/fixXfYi.zig").__fixunsxfsi; @export(__fixunsxfsi, .{ .name = "__fixunsxfsi", .linkage = linkage }); const __fixxfdi = @import("compiler_rt/fixXfYi.zig").__fixxfdi; @export(__fixxfdi, .{ .name = "__fixxfdi", .linkage = linkage }); const __fixunsxfdi = @import("compiler_rt/fixXfYi.zig").__fixunsxfdi; @export(__fixunsxfdi, .{ .name = "__fixunsxfdi", .linkage = linkage }); const __fixxfti = @import("compiler_rt/fixXfYi.zig").__fixxfti; @export(__fixxfti, .{ .name = "__fixxfti", .linkage = linkage }); const __fixunsxfti = @import("compiler_rt/fixXfYi.zig").__fixunsxfti; @export(__fixunsxfti, .{ .name = "__fixunsxfti", .linkage = linkage }); // Conversion from f128 const __fixtfsi = @import("compiler_rt/fixXfYi.zig").__fixtfsi; @export(__fixtfsi, .{ .name = "__fixtfsi", .linkage = linkage }); const __fixunstfsi = @import("compiler_rt/fixXfYi.zig").__fixunstfsi; @export(__fixunstfsi, .{ .name = "__fixunstfsi", .linkage = linkage }); const __fixtfdi = @import("compiler_rt/fixXfYi.zig").__fixtfdi; @export(__fixtfdi, .{ .name = "__fixtfdi", .linkage = linkage }); const __fixunstfdi = @import("compiler_rt/fixXfYi.zig").__fixunstfdi; @export(__fixunstfdi, .{ .name = "__fixunstfdi", .linkage = linkage }); const __fixtfti = @import("compiler_rt/fixXfYi.zig").__fixtfti; @export(__fixtfti, .{ .name = "__fixtfti", .linkage = linkage }); const __fixunstfti = @import("compiler_rt/fixXfYi.zig").__fixunstfti; @export(__fixunstfti, .{ .name = "__fixunstfti", .linkage = linkage }); const __udivmoddi4 = @import("compiler_rt/int.zig").__udivmoddi4; @export(__udivmoddi4, .{ .name = "__udivmoddi4", .linkage = linkage }); const __truncsfhf2 = @import("compiler_rt/truncXfYf2.zig").__truncsfhf2; @export(__truncsfhf2, .{ .name = "__truncsfhf2", .linkage = linkage }); if (!is_test) { @export(__truncsfhf2, .{ .name = "__gnu_f2h_ieee", .linkage = linkage }); } const __extendsfdf2 = @import("compiler_rt/extendXfYf2.zig").__extendsfdf2; @export(__extendsfdf2, .{ .name = "__extendsfdf2", .linkage = linkage }); if (is_darwin) { const __isPlatformVersionAtLeast = @import("compiler_rt/os_version_check.zig").__isPlatformVersionAtLeast; @export(__isPlatformVersionAtLeast, .{ .name = "__isPlatformVersionAtLeast", .linkage = linkage }); } // Integer Arithmetic const __ashldi3 = @import("compiler_rt/shift.zig").__ashldi3; @export(__ashldi3, .{ .name = "__ashldi3", .linkage = linkage }); const __ashlti3 = @import("compiler_rt/shift.zig").__ashlti3; @export(__ashlti3, .{ .name = "__ashlti3", .linkage = linkage }); const __ashrdi3 = @import("compiler_rt/shift.zig").__ashrdi3; @export(__ashrdi3, .{ .name = "__ashrdi3", .linkage = linkage }); const __ashrti3 = @import("compiler_rt/shift.zig").__ashrti3; @export(__ashrti3, .{ .name = "__ashrti3", .linkage = linkage }); const __lshrdi3 = @import("compiler_rt/shift.zig").__lshrdi3; @export(__lshrdi3, .{ .name = "__lshrdi3", .linkage = linkage }); const __lshrti3 = @import("compiler_rt/shift.zig").__lshrti3; @export(__lshrti3, .{ .name = "__lshrti3", .linkage = linkage }); const __negsi2 = @import("compiler_rt/negXi2.zig").__negsi2; @export(__negsi2, .{ .name = "__negsi2", .linkage = linkage }); const __negdi2 = @import("compiler_rt/negXi2.zig").__negdi2; @export(__negdi2, .{ .name = "__negdi2", .linkage = linkage }); const __negti2 = @import("compiler_rt/negXi2.zig").__negti2; @export(__negti2, .{ .name = "__negti2", .linkage = linkage }); const __mulsi3 = @import("compiler_rt/int.zig").__mulsi3; @export(__mulsi3, .{ .name = "__mulsi3", .linkage = linkage }); const __muldi3 = @import("compiler_rt/muldi3.zig").__muldi3; @export(__muldi3, .{ .name = "__muldi3", .linkage = linkage }); const __divmoddi4 = @import("compiler_rt/int.zig").__divmoddi4; @export(__divmoddi4, .{ .name = "__divmoddi4", .linkage = linkage }); const __divsi3 = @import("compiler_rt/int.zig").__divsi3; @export(__divsi3, .{ .name = "__divsi3", .linkage = linkage }); const __divdi3 = @import("compiler_rt/int.zig").__divdi3; @export(__divdi3, .{ .name = "__divdi3", .linkage = linkage }); const __udivsi3 = @import("compiler_rt/int.zig").__udivsi3; @export(__udivsi3, .{ .name = "__udivsi3", .linkage = linkage }); const __udivdi3 = @import("compiler_rt/int.zig").__udivdi3; @export(__udivdi3, .{ .name = "__udivdi3", .linkage = linkage }); const __modsi3 = @import("compiler_rt/int.zig").__modsi3; @export(__modsi3, .{ .name = "__modsi3", .linkage = linkage }); const __moddi3 = @import("compiler_rt/int.zig").__moddi3; @export(__moddi3, .{ .name = "__moddi3", .linkage = linkage }); const __umodsi3 = @import("compiler_rt/int.zig").__umodsi3; @export(__umodsi3, .{ .name = "__umodsi3", .linkage = linkage }); const __umoddi3 = @import("compiler_rt/int.zig").__umoddi3; @export(__umoddi3, .{ .name = "__umoddi3", .linkage = linkage }); const __divmodsi4 = @import("compiler_rt/int.zig").__divmodsi4; @export(__divmodsi4, .{ .name = "__divmodsi4", .linkage = linkage }); const __udivmodsi4 = @import("compiler_rt/int.zig").__udivmodsi4; @export(__udivmodsi4, .{ .name = "__udivmodsi4", .linkage = linkage }); // Integer Arithmetic with trapping overflow const __absvsi2 = @import("compiler_rt/absv.zig").__absvsi2; @export(__absvsi2, .{ .name = "__absvsi2", .linkage = linkage }); const __absvdi2 = @import("compiler_rt/absv.zig").__absvdi2; @export(__absvdi2, .{ .name = "__absvdi2", .linkage = linkage }); const __absvti2 = @import("compiler_rt/absv.zig").__absvti2; @export(__absvti2, .{ .name = "__absvti2", .linkage = linkage }); const __negvsi2 = @import("compiler_rt/negv.zig").__negvsi2; @export(__negvsi2, .{ .name = "__negvsi2", .linkage = linkage }); const __negvdi2 = @import("compiler_rt/negv.zig").__negvdi2; @export(__negvdi2, .{ .name = "__negvdi2", .linkage = linkage }); const __negvti2 = @import("compiler_rt/negv.zig").__negvti2; @export(__negvti2, .{ .name = "__negvti2", .linkage = linkage }); // Integer arithmetic which returns if overflow const __addosi4 = @import("compiler_rt/addo.zig").__addosi4; @export(__addosi4, .{ .name = "__addosi4", .linkage = linkage }); const __addodi4 = @import("compiler_rt/addo.zig").__addodi4; @export(__addodi4, .{ .name = "__addodi4", .linkage = linkage }); const __addoti4 = @import("compiler_rt/addo.zig").__addoti4; @export(__addoti4, .{ .name = "__addoti4", .linkage = linkage }); const __subosi4 = @import("compiler_rt/subo.zig").__subosi4; @export(__subosi4, .{ .name = "__subosi4", .linkage = linkage }); const __subodi4 = @import("compiler_rt/subo.zig").__subodi4; @export(__subodi4, .{ .name = "__subodi4", .linkage = linkage }); const __suboti4 = @import("compiler_rt/subo.zig").__suboti4; @export(__suboti4, .{ .name = "__suboti4", .linkage = linkage }); const __mulosi4 = @import("compiler_rt/mulo.zig").__mulosi4; @export(__mulosi4, .{ .name = "__mulosi4", .linkage = linkage }); const __mulodi4 = @import("compiler_rt/mulo.zig").__mulodi4; @export(__mulodi4, .{ .name = "__mulodi4", .linkage = linkage }); const __muloti4 = @import("compiler_rt/mulo.zig").__muloti4; @export(__muloti4, .{ .name = "__muloti4", .linkage = linkage }); // Integer Comparison // (a < b) => 0 // (a == b) => 1 // (a > b) => 2 const __cmpsi2 = @import("compiler_rt/cmp.zig").__cmpsi2; @export(__cmpsi2, .{ .name = "__cmpsi2", .linkage = linkage }); const __cmpdi2 = @import("compiler_rt/cmp.zig").__cmpdi2; @export(__cmpdi2, .{ .name = "__cmpdi2", .linkage = linkage }); const __cmpti2 = @import("compiler_rt/cmp.zig").__cmpti2; @export(__cmpti2, .{ .name = "__cmpti2", .linkage = linkage }); const __ucmpsi2 = @import("compiler_rt/cmp.zig").__ucmpsi2; @export(__ucmpsi2, .{ .name = "__ucmpsi2", .linkage = linkage }); const __ucmpdi2 = @import("compiler_rt/cmp.zig").__ucmpdi2; @export(__ucmpdi2, .{ .name = "__ucmpdi2", .linkage = linkage }); const __ucmpti2 = @import("compiler_rt/cmp.zig").__ucmpti2; @export(__ucmpti2, .{ .name = "__ucmpti2", .linkage = linkage }); // missing: Floating point raised to integer power // missing: Complex arithmetic // (a + ib) * (c + id) // (a + ib) / (c + id) const __negsf2 = @import("compiler_rt/negXf2.zig").__negsf2; @export(__negsf2, .{ .name = "__negsf2", .linkage = linkage }); const __negdf2 = @import("compiler_rt/negXf2.zig").__negdf2; @export(__negdf2, .{ .name = "__negdf2", .linkage = linkage }); if (builtin.link_libc and os_tag == .openbsd) { const __emutls_get_address = @import("compiler_rt/emutls.zig").__emutls_get_address; @export(__emutls_get_address, .{ .name = "__emutls_get_address", .linkage = linkage }); } if ((arch.isARM() or arch.isThumb()) and !is_test) { const __aeabi_unwind_cpp_pr0 = @import("compiler_rt/arm.zig").__aeabi_unwind_cpp_pr0; @export(__aeabi_unwind_cpp_pr0, .{ .name = "__aeabi_unwind_cpp_pr0", .linkage = linkage }); const __aeabi_unwind_cpp_pr1 = @import("compiler_rt/arm.zig").__aeabi_unwind_cpp_pr1; @export(__aeabi_unwind_cpp_pr1, .{ .name = "__aeabi_unwind_cpp_pr1", .linkage = linkage }); const __aeabi_unwind_cpp_pr2 = @import("compiler_rt/arm.zig").__aeabi_unwind_cpp_pr2; @export(__aeabi_unwind_cpp_pr2, .{ .name = "__aeabi_unwind_cpp_pr2", .linkage = linkage }); @export(__muldi3, .{ .name = "__aeabi_lmul", .linkage = linkage }); const __aeabi_ldivmod = @import("compiler_rt/arm.zig").__aeabi_ldivmod; @export(__aeabi_ldivmod, .{ .name = "__aeabi_ldivmod", .linkage = linkage }); const __aeabi_uldivmod = @import("compiler_rt/arm.zig").__aeabi_uldivmod; @export(__aeabi_uldivmod, .{ .name = "__aeabi_uldivmod", .linkage = linkage }); @export(__divsi3, .{ .name = "__aeabi_idiv", .linkage = linkage }); const __aeabi_idivmod = @import("compiler_rt/arm.zig").__aeabi_idivmod; @export(__aeabi_idivmod, .{ .name = "__aeabi_idivmod", .linkage = linkage }); @export(__udivsi3, .{ .name = "__aeabi_uidiv", .linkage = linkage }); const __aeabi_uidivmod = @import("compiler_rt/arm.zig").__aeabi_uidivmod; @export(__aeabi_uidivmod, .{ .name = "__aeabi_uidivmod", .linkage = linkage }); const __aeabi_memcpy = @import("compiler_rt/arm.zig").__aeabi_memcpy; @export(__aeabi_memcpy, .{ .name = "__aeabi_memcpy", .linkage = linkage }); @export(__aeabi_memcpy, .{ .name = "__aeabi_memcpy4", .linkage = linkage }); @export(__aeabi_memcpy, .{ .name = "__aeabi_memcpy8", .linkage = linkage }); const __aeabi_memmove = @import("compiler_rt/arm.zig").__aeabi_memmove; @export(__aeabi_memmove, .{ .name = "__aeabi_memmove", .linkage = linkage }); @export(__aeabi_memmove, .{ .name = "__aeabi_memmove4", .linkage = linkage }); @export(__aeabi_memmove, .{ .name = "__aeabi_memmove8", .linkage = linkage }); const __aeabi_memset = @import("compiler_rt/arm.zig").__aeabi_memset; @export(__aeabi_memset, .{ .name = "__aeabi_memset", .linkage = linkage }); @export(__aeabi_memset, .{ .name = "__aeabi_memset4", .linkage = linkage }); @export(__aeabi_memset, .{ .name = "__aeabi_memset8", .linkage = linkage }); const __aeabi_memclr = @import("compiler_rt/arm.zig").__aeabi_memclr; @export(__aeabi_memclr, .{ .name = "__aeabi_memclr", .linkage = linkage }); @export(__aeabi_memclr, .{ .name = "__aeabi_memclr4", .linkage = linkage }); @export(__aeabi_memclr, .{ .name = "__aeabi_memclr8", .linkage = linkage }); if (os_tag == .linux) { const __aeabi_read_tp = @import("compiler_rt/arm.zig").__aeabi_read_tp; @export(__aeabi_read_tp, .{ .name = "__aeabi_read_tp", .linkage = linkage }); } const __aeabi_f2d = @import("compiler_rt/extendXfYf2.zig").__aeabi_f2d; @export(__aeabi_f2d, .{ .name = "__aeabi_f2d", .linkage = linkage }); const __aeabi_i2d = @import("compiler_rt/floatXiYf.zig").__aeabi_i2d; @export(__aeabi_i2d, .{ .name = "__aeabi_i2d", .linkage = linkage }); const __aeabi_l2d = @import("compiler_rt/floatXiYf.zig").__aeabi_l2d; @export(__aeabi_l2d, .{ .name = "__aeabi_l2d", .linkage = linkage }); const __aeabi_l2f = @import("compiler_rt/floatXiYf.zig").__aeabi_l2f; @export(__aeabi_l2f, .{ .name = "__aeabi_l2f", .linkage = linkage }); const __aeabi_ui2d = @import("compiler_rt/floatXiYf.zig").__aeabi_ui2d; @export(__aeabi_ui2d, .{ .name = "__aeabi_ui2d", .linkage = linkage }); const __aeabi_ul2d = @import("compiler_rt/floatXiYf.zig").__aeabi_ul2d; @export(__aeabi_ul2d, .{ .name = "__aeabi_ul2d", .linkage = linkage }); const __aeabi_ui2f = @import("compiler_rt/floatXiYf.zig").__aeabi_ui2f; @export(__aeabi_ui2f, .{ .name = "__aeabi_ui2f", .linkage = linkage }); const __aeabi_ul2f = @import("compiler_rt/floatXiYf.zig").__aeabi_ul2f; @export(__aeabi_ul2f, .{ .name = "__aeabi_ul2f", .linkage = linkage }); const __aeabi_fneg = @import("compiler_rt/negXf2.zig").__aeabi_fneg; @export(__aeabi_fneg, .{ .name = "__aeabi_fneg", .linkage = linkage }); const __aeabi_dneg = @import("compiler_rt/negXf2.zig").__aeabi_dneg; @export(__aeabi_dneg, .{ .name = "__aeabi_dneg", .linkage = linkage }); const __aeabi_fmul = @import("compiler_rt/mulXf3.zig").__aeabi_fmul; @export(__aeabi_fmul, .{ .name = "__aeabi_fmul", .linkage = linkage }); const __aeabi_dmul = @import("compiler_rt/mulXf3.zig").__aeabi_dmul; @export(__aeabi_dmul, .{ .name = "__aeabi_dmul", .linkage = linkage }); const __aeabi_d2h = @import("compiler_rt/truncXfYf2.zig").__aeabi_d2h; @export(__aeabi_d2h, .{ .name = "__aeabi_d2h", .linkage = linkage }); const __aeabi_f2ulz = @import("compiler_rt/fixXfYi.zig").__aeabi_f2ulz; @export(__aeabi_f2ulz, .{ .name = "__aeabi_f2ulz", .linkage = linkage }); const __aeabi_d2ulz = @import("compiler_rt/fixXfYi.zig").__aeabi_d2ulz; @export(__aeabi_d2ulz, .{ .name = "__aeabi_d2ulz", .linkage = linkage }); const __aeabi_f2lz = @import("compiler_rt/fixXfYi.zig").__aeabi_f2lz; @export(__aeabi_f2lz, .{ .name = "__aeabi_f2lz", .linkage = linkage }); const __aeabi_d2lz = @import("compiler_rt/fixXfYi.zig").__aeabi_d2lz; @export(__aeabi_d2lz, .{ .name = "__aeabi_d2lz", .linkage = linkage }); const __aeabi_d2uiz = @import("compiler_rt/fixXfYi.zig").__aeabi_d2uiz; @export(__aeabi_d2uiz, .{ .name = "__aeabi_d2uiz", .linkage = linkage }); const __aeabi_h2f = @import("compiler_rt/extendXfYf2.zig").__aeabi_h2f; @export(__aeabi_h2f, .{ .name = "__aeabi_h2f", .linkage = linkage }); const __aeabi_f2h = @import("compiler_rt/truncXfYf2.zig").__aeabi_f2h; @export(__aeabi_f2h, .{ .name = "__aeabi_f2h", .linkage = linkage }); const __aeabi_i2f = @import("compiler_rt/floatXiYf.zig").__aeabi_i2f; @export(__aeabi_i2f, .{ .name = "__aeabi_i2f", .linkage = linkage }); const __aeabi_d2f = @import("compiler_rt/truncXfYf2.zig").__aeabi_d2f; @export(__aeabi_d2f, .{ .name = "__aeabi_d2f", .linkage = linkage }); const __aeabi_fadd = @import("compiler_rt/addXf3.zig").__aeabi_fadd; @export(__aeabi_fadd, .{ .name = "__aeabi_fadd", .linkage = linkage }); const __aeabi_dadd = @import("compiler_rt/addXf3.zig").__aeabi_dadd; @export(__aeabi_dadd, .{ .name = "__aeabi_dadd", .linkage = linkage }); const __aeabi_fsub = @import("compiler_rt/addXf3.zig").__aeabi_fsub; @export(__aeabi_fsub, .{ .name = "__aeabi_fsub", .linkage = linkage }); const __aeabi_dsub = @import("compiler_rt/addXf3.zig").__aeabi_dsub; @export(__aeabi_dsub, .{ .name = "__aeabi_dsub", .linkage = linkage }); const __aeabi_f2uiz = @import("compiler_rt/fixXfYi.zig").__aeabi_f2uiz; @export(__aeabi_f2uiz, .{ .name = "__aeabi_f2uiz", .linkage = linkage }); const __aeabi_f2iz = @import("compiler_rt/fixXfYi.zig").__aeabi_f2iz; @export(__aeabi_f2iz, .{ .name = "__aeabi_f2iz", .linkage = linkage }); const __aeabi_d2iz = @import("compiler_rt/fixXfYi.zig").__aeabi_d2iz; @export(__aeabi_d2iz, .{ .name = "__aeabi_d2iz", .linkage = linkage }); const __aeabi_fdiv = @import("compiler_rt/divsf3.zig").__aeabi_fdiv; @export(__aeabi_fdiv, .{ .name = "__aeabi_fdiv", .linkage = linkage }); const __aeabi_ddiv = @import("compiler_rt/divdf3.zig").__aeabi_ddiv; @export(__aeabi_ddiv, .{ .name = "__aeabi_ddiv", .linkage = linkage }); const __aeabi_llsl = @import("compiler_rt/shift.zig").__aeabi_llsl; @export(__aeabi_llsl, .{ .name = "__aeabi_llsl", .linkage = linkage }); const __aeabi_lasr = @import("compiler_rt/shift.zig").__aeabi_lasr; @export(__aeabi_lasr, .{ .name = "__aeabi_lasr", .linkage = linkage }); const __aeabi_llsr = @import("compiler_rt/shift.zig").__aeabi_llsr; @export(__aeabi_llsr, .{ .name = "__aeabi_llsr", .linkage = linkage }); const __aeabi_fcmpeq = @import("compiler_rt/compareXf2.zig").__aeabi_fcmpeq; @export(__aeabi_fcmpeq, .{ .name = "__aeabi_fcmpeq", .linkage = linkage }); const __aeabi_fcmplt = @import("compiler_rt/compareXf2.zig").__aeabi_fcmplt; @export(__aeabi_fcmplt, .{ .name = "__aeabi_fcmplt", .linkage = linkage }); const __aeabi_fcmple = @import("compiler_rt/compareXf2.zig").__aeabi_fcmple; @export(__aeabi_fcmple, .{ .name = "__aeabi_fcmple", .linkage = linkage }); const __aeabi_fcmpge = @import("compiler_rt/compareXf2.zig").__aeabi_fcmpge; @export(__aeabi_fcmpge, .{ .name = "__aeabi_fcmpge", .linkage = linkage }); const __aeabi_fcmpgt = @import("compiler_rt/compareXf2.zig").__aeabi_fcmpgt; @export(__aeabi_fcmpgt, .{ .name = "__aeabi_fcmpgt", .linkage = linkage }); const __aeabi_fcmpun = @import("compiler_rt/compareXf2.zig").__aeabi_fcmpun; @export(__aeabi_fcmpun, .{ .name = "__aeabi_fcmpun", .linkage = linkage }); const __aeabi_dcmpeq = @import("compiler_rt/compareXf2.zig").__aeabi_dcmpeq; @export(__aeabi_dcmpeq, .{ .name = "__aeabi_dcmpeq", .linkage = linkage }); const __aeabi_dcmplt = @import("compiler_rt/compareXf2.zig").__aeabi_dcmplt; @export(__aeabi_dcmplt, .{ .name = "__aeabi_dcmplt", .linkage = linkage }); const __aeabi_dcmple = @import("compiler_rt/compareXf2.zig").__aeabi_dcmple; @export(__aeabi_dcmple, .{ .name = "__aeabi_dcmple", .linkage = linkage }); const __aeabi_dcmpge = @import("compiler_rt/compareXf2.zig").__aeabi_dcmpge; @export(__aeabi_dcmpge, .{ .name = "__aeabi_dcmpge", .linkage = linkage }); const __aeabi_dcmpgt = @import("compiler_rt/compareXf2.zig").__aeabi_dcmpgt; @export(__aeabi_dcmpgt, .{ .name = "__aeabi_dcmpgt", .linkage = linkage }); const __aeabi_dcmpun = @import("compiler_rt/compareXf2.zig").__aeabi_dcmpun; @export(__aeabi_dcmpun, .{ .name = "__aeabi_dcmpun", .linkage = linkage }); } if (arch == .i386 and abi == .msvc) { // Don't let LLVM apply the stdcall name mangling on those MSVC builtins const _alldiv = @import("compiler_rt/aulldiv.zig")._alldiv; @export(_alldiv, .{ .name = "\x01__alldiv", .linkage = strong_linkage }); const _aulldiv = @import("compiler_rt/aulldiv.zig")._aulldiv; @export(_aulldiv, .{ .name = "\x01__aulldiv", .linkage = strong_linkage }); const _allrem = @import("compiler_rt/aullrem.zig")._allrem; @export(_allrem, .{ .name = "\x01__allrem", .linkage = strong_linkage }); const _aullrem = @import("compiler_rt/aullrem.zig")._aullrem; @export(_aullrem, .{ .name = "\x01__aullrem", .linkage = strong_linkage }); } if (!is_test) { @export(fmodl, .{ .name = "fmodl", .linkage = linkage }); if (long_double_is_f128) { @export(fmodl, .{ .name = "fmodq", .linkage = linkage }); } else { @export(fmodq, .{ .name = "fmodq", .linkage = linkage }); } @export(floorf, .{ .name = "floorf", .linkage = linkage }); @export(floor, .{ .name = "floor", .linkage = linkage }); @export(floorl, .{ .name = "floorl", .linkage = linkage }); @export(ceilf, .{ .name = "ceilf", .linkage = linkage }); @export(ceil, .{ .name = "ceil", .linkage = linkage }); @export(ceill, .{ .name = "ceill", .linkage = linkage }); @export(fma, .{ .name = "fma", .linkage = linkage }); @export(fmaf, .{ .name = "fmaf", .linkage = linkage }); @export(fmal, .{ .name = "fmal", .linkage = linkage }); if (long_double_is_f80) { @export(fmal, .{ .name = "__fmax", .linkage = linkage }); } else { @export(__fmax, .{ .name = "__fmax", .linkage = linkage }); } if (long_double_is_f128) { @export(fmal, .{ .name = "fmaq", .linkage = linkage }); } else { @export(fmaq, .{ .name = "fmaq", .linkage = linkage }); } } if (arch.isSPARC()) { // SPARC systems use a different naming scheme const _Qp_add = @import("compiler_rt/sparc.zig")._Qp_add; @export(_Qp_add, .{ .name = "_Qp_add", .linkage = linkage }); const _Qp_div = @import("compiler_rt/sparc.zig")._Qp_div; @export(_Qp_div, .{ .name = "_Qp_div", .linkage = linkage }); const _Qp_mul = @import("compiler_rt/sparc.zig")._Qp_mul; @export(_Qp_mul, .{ .name = "_Qp_mul", .linkage = linkage }); const _Qp_sub = @import("compiler_rt/sparc.zig")._Qp_sub; @export(_Qp_sub, .{ .name = "_Qp_sub", .linkage = linkage }); const _Qp_cmp = @import("compiler_rt/sparc.zig")._Qp_cmp; @export(_Qp_cmp, .{ .name = "_Qp_cmp", .linkage = linkage }); const _Qp_feq = @import("compiler_rt/sparc.zig")._Qp_feq; @export(_Qp_feq, .{ .name = "_Qp_feq", .linkage = linkage }); const _Qp_fne = @import("compiler_rt/sparc.zig")._Qp_fne; @export(_Qp_fne, .{ .name = "_Qp_fne", .linkage = linkage }); const _Qp_flt = @import("compiler_rt/sparc.zig")._Qp_flt; @export(_Qp_flt, .{ .name = "_Qp_flt", .linkage = linkage }); const _Qp_fle = @import("compiler_rt/sparc.zig")._Qp_fle; @export(_Qp_fle, .{ .name = "_Qp_fle", .linkage = linkage }); const _Qp_fgt = @import("compiler_rt/sparc.zig")._Qp_fgt; @export(_Qp_fgt, .{ .name = "_Qp_fgt", .linkage = linkage }); const _Qp_fge = @import("compiler_rt/sparc.zig")._Qp_fge; @export(_Qp_fge, .{ .name = "_Qp_fge", .linkage = linkage }); const _Qp_itoq = @import("compiler_rt/sparc.zig")._Qp_itoq; @export(_Qp_itoq, .{ .name = "_Qp_itoq", .linkage = linkage }); const _Qp_uitoq = @import("compiler_rt/sparc.zig")._Qp_uitoq; @export(_Qp_uitoq, .{ .name = "_Qp_uitoq", .linkage = linkage }); const _Qp_xtoq = @import("compiler_rt/sparc.zig")._Qp_xtoq; @export(_Qp_xtoq, .{ .name = "_Qp_xtoq", .linkage = linkage }); const _Qp_uxtoq = @import("compiler_rt/sparc.zig")._Qp_uxtoq; @export(_Qp_uxtoq, .{ .name = "_Qp_uxtoq", .linkage = linkage }); const _Qp_stoq = @import("compiler_rt/sparc.zig")._Qp_stoq; @export(_Qp_stoq, .{ .name = "_Qp_stoq", .linkage = linkage }); const _Qp_dtoq = @import("compiler_rt/sparc.zig")._Qp_dtoq; @export(_Qp_dtoq, .{ .name = "_Qp_dtoq", .linkage = linkage }); const _Qp_qtoi = @import("compiler_rt/sparc.zig")._Qp_qtoi; @export(_Qp_qtoi, .{ .name = "_Qp_qtoi", .linkage = linkage }); const _Qp_qtoui = @import("compiler_rt/sparc.zig")._Qp_qtoui; @export(_Qp_qtoui, .{ .name = "_Qp_qtoui", .linkage = linkage }); const _Qp_qtox = @import("compiler_rt/sparc.zig")._Qp_qtox; @export(_Qp_qtox, .{ .name = "_Qp_qtox", .linkage = linkage }); const _Qp_qtoux = @import("compiler_rt/sparc.zig")._Qp_qtoux; @export(_Qp_qtoux, .{ .name = "_Qp_qtoux", .linkage = linkage }); const _Qp_qtos = @import("compiler_rt/sparc.zig")._Qp_qtos; @export(_Qp_qtos, .{ .name = "_Qp_qtos", .linkage = linkage }); const _Qp_qtod = @import("compiler_rt/sparc.zig")._Qp_qtod; @export(_Qp_qtod, .{ .name = "_Qp_qtod", .linkage = linkage }); } if ((arch.isPPC() or arch.isPPC64()) and !is_test) { @export(__addtf3, .{ .name = "__addkf3", .linkage = linkage }); @export(__subtf3, .{ .name = "__subkf3", .linkage = linkage }); @export(__multf3, .{ .name = "__mulkf3", .linkage = linkage }); @export(__divtf3, .{ .name = "__divkf3", .linkage = linkage }); @export(__extendsftf2, .{ .name = "__extendsfkf2", .linkage = linkage }); @export(__extenddftf2, .{ .name = "__extenddfkf2", .linkage = linkage }); @export(__trunctfsf2, .{ .name = "__trunckfsf2", .linkage = linkage }); @export(__trunctfdf2, .{ .name = "__trunckfdf2", .linkage = linkage }); @export(__fixtfdi, .{ .name = "__fixkfdi", .linkage = linkage }); @export(__fixtfsi, .{ .name = "__fixkfsi", .linkage = linkage }); @export(__fixunstfsi, .{ .name = "__fixunskfsi", .linkage = linkage }); @export(__fixunstfdi, .{ .name = "__fixunskfdi", .linkage = linkage }); @export(__floatsitf, .{ .name = "__floatsikf", .linkage = linkage }); @export(__floatditf, .{ .name = "__floatdikf", .linkage = linkage }); @export(__floatunditf, .{ .name = "__floatundikf", .linkage = linkage }); @export(__floatunsitf, .{ .name = "__floatunsikf", .linkage = linkage }); @export(__letf2, .{ .name = "__eqkf2", .linkage = linkage }); @export(__letf2, .{ .name = "__nekf2", .linkage = linkage }); @export(__getf2, .{ .name = "__gekf2", .linkage = linkage }); @export(__letf2, .{ .name = "__ltkf2", .linkage = linkage }); @export(__letf2, .{ .name = "__lekf2", .linkage = linkage }); @export(__getf2, .{ .name = "__gtkf2", .linkage = linkage }); @export(__unordtf2, .{ .name = "__unordkf2", .linkage = linkage }); // LLVM PPC backend lowers f128 fma to `fmaf128`. @export(fmal, .{ .name = "fmaf128", .linkage = linkage }); } } const math = std.math; fn fmaf(a: f32, b: f32, c: f32) callconv(.C) f32 { return math.fma(f32, a, b, c); } fn fma(a: f64, b: f64, c: f64) callconv(.C) f64 { return math.fma(f64, a, b, c); } fn __fmax(a: f80, b: f80, c: f80) callconv(.C) f80 { return math.fma(f80, a, b, c); } fn fmaq(a: f128, b: f128, c: f128) callconv(.C) f128 { return math.fma(f128, a, b, c); } fn fmal(a: c_longdouble, b: c_longdouble, c: c_longdouble) callconv(.C) c_longdouble { return math.fma(c_longdouble, a, b, c); } // TODO add intrinsics for these (and probably the double version too) // and have the math stuff use the intrinsic. same as @mod and @rem fn floorf(x: f32) callconv(.C) f32 { return math.floor(x); } fn floor(x: f64) callconv(.C) f64 { return math.floor(x); } fn floorl(x: c_longdouble) callconv(.C) c_longdouble { if (!long_double_is_f128) { @panic("TODO implement this"); } return math.floor(x); } fn ceilf(x: f32) callconv(.C) f32 { return math.ceil(x); } fn ceil(x: f64) callconv(.C) f64 { return math.ceil(x); } fn ceill(x: c_longdouble) callconv(.C) c_longdouble { if (!long_double_is_f128) { @panic("TODO implement this"); } return math.ceil(x); } const fmodq = @import("compiler_rt/floatfmodq.zig").fmodq; fn fmodl(x: c_longdouble, y: c_longdouble) callconv(.C) c_longdouble { if (!long_double_is_f128) { @panic("TODO implement this"); } return @floatCast(c_longdouble, fmodq(x, y)); } // Avoid dragging in the runtime safety mechanisms into this .o file, // unless we're trying to test this file. pub fn panic(msg: []const u8, error_return_trace: ?*std.builtin.StackTrace) noreturn { _ = error_return_trace; @setCold(true); if (is_test) { std.debug.panic("{s}", .{msg}); } else { unreachable; } }
lib/std/special/compiler_rt.zig
const std = @import("std.zig"); const debug = std.debug; const mem = std.mem; const Allocator = mem.Allocator; const assert = debug.assert; const testing = std.testing; const ArrayList = std.ArrayList; /// A buffer that allocates memory and maintains a null byte at the end. pub const Buffer = struct { list: ArrayList(u8), /// Must deinitialize with deinit. pub fn init(allocator: *Allocator, m: []const u8) !Buffer { var self = try initSize(allocator, m.len); mem.copy(u8, self.list.items, m); return self; } /// Initialize memory to size bytes of undefined values. /// Must deinitialize with deinit. pub fn initSize(allocator: *Allocator, size: usize) !Buffer { var self = initNull(allocator); try self.resize(size); return self; } /// Initialize with capacity to hold at least num bytes. /// Must deinitialize with deinit. pub fn initCapacity(allocator: *Allocator, num: usize) !Buffer { var self = Buffer{ .list = try ArrayList(u8).initCapacity(allocator, num + 1) }; self.list.appendAssumeCapacity(0); return self; } /// Must deinitialize with deinit. /// None of the other operations are valid until you do one of these: /// * ::replaceContents /// * ::resize pub fn initNull(allocator: *Allocator) Buffer { return Buffer{ .list = ArrayList(u8).init(allocator) }; } /// Must deinitialize with deinit. pub fn initFromBuffer(buffer: Buffer) !Buffer { return Buffer.init(buffer.list.allocator, buffer.span()); } /// Buffer takes ownership of the passed in slice. The slice must have been /// allocated with `allocator`. /// Must deinitialize with deinit. pub fn fromOwnedSlice(allocator: *Allocator, slice: []u8) !Buffer { var self = Buffer{ .list = ArrayList(u8).fromOwnedSlice(allocator, slice) }; try self.list.append(0); return self; } /// The caller owns the returned memory. The Buffer becomes null and /// is safe to `deinit`. pub fn toOwnedSlice(self: *Buffer) [:0]u8 { const allocator = self.list.allocator; const result = self.list.toOwnedSlice(); self.* = initNull(allocator); return result[0 .. result.len - 1 :0]; } pub fn allocPrint(allocator: *Allocator, comptime format: []const u8, args: var) !Buffer { const size = std.math.cast(usize, std.fmt.count(format, args)) catch |err| switch (err) { error.Overflow => return error.OutOfMemory, }; var self = try Buffer.initSize(allocator, size); assert((std.fmt.bufPrint(self.list.items, format, args) catch unreachable).len == size); return self; } pub fn deinit(self: *Buffer) void { self.list.deinit(); } pub fn span(self: var) @TypeOf(self.list.items[0 .. self.list.len - 1 :0]) { return self.list.span()[0..self.len() :0]; } pub const toSlice = @compileError("deprecated; use span()"); pub const toSliceConst = @compileError("deprecated; use span()"); pub fn shrink(self: *Buffer, new_len: usize) void { assert(new_len <= self.len()); self.list.shrink(new_len + 1); self.list.items[self.len()] = 0; } pub fn resize(self: *Buffer, new_len: usize) !void { try self.list.resize(new_len + 1); self.list.items[self.len()] = 0; } pub fn isNull(self: Buffer) bool { return self.list.len == 0; } pub fn len(self: Buffer) usize { return self.list.len - 1; } pub fn capacity(self: Buffer) usize { return if (self.list.items.len > 0) self.list.items.len - 1 else 0; } pub fn append(self: *Buffer, m: []const u8) !void { const old_len = self.len(); try self.resize(old_len + m.len); mem.copy(u8, self.list.span()[old_len..], m); } pub fn appendByte(self: *Buffer, byte: u8) !void { const old_len = self.len(); try self.resize(old_len + 1); self.list.span()[old_len] = byte; } pub fn eql(self: Buffer, m: []const u8) bool { return mem.eql(u8, self.span(), m); } pub fn startsWith(self: Buffer, m: []const u8) bool { if (self.len() < m.len) return false; return mem.eql(u8, self.list.items[0..m.len], m); } pub fn endsWith(self: Buffer, m: []const u8) bool { const l = self.len(); if (l < m.len) return false; const start = l - m.len; return mem.eql(u8, self.list.items[start..l], m); } pub fn replaceContents(self: *Buffer, m: []const u8) !void { try self.resize(m.len); mem.copy(u8, self.list.span(), m); } pub fn outStream(self: *Buffer) std.io.OutStream(*Buffer, error{OutOfMemory}, appendWrite) { return .{ .context = self }; } /// Same as `append` except it returns the number of bytes written, which is always the same /// as `m.len`. The purpose of this function existing is to match `std.io.OutStream` API. pub fn appendWrite(self: *Buffer, m: []const u8) !usize { try self.append(m); return m.len; } }; test "simple Buffer" { var buf = try Buffer.init(testing.allocator, ""); defer buf.deinit(); testing.expect(buf.len() == 0); try buf.append("hello"); try buf.append(" "); try buf.append("world"); testing.expect(buf.eql("hello world")); testing.expect(mem.eql(u8, mem.spanZ(buf.span().ptr), buf.span())); var buf2 = try Buffer.initFromBuffer(buf); defer buf2.deinit(); testing.expect(buf.eql(buf2.span())); testing.expect(buf.startsWith("hell")); testing.expect(buf.endsWith("orld")); try buf2.resize(4); testing.expect(buf.startsWith(buf2.span())); } test "Buffer.initSize" { var buf = try Buffer.initSize(testing.allocator, 3); defer buf.deinit(); testing.expect(buf.len() == 3); try buf.append("hello"); testing.expect(mem.eql(u8, buf.span()[3..], "hello")); } test "Buffer.initCapacity" { var buf = try Buffer.initCapacity(testing.allocator, 10); defer buf.deinit(); testing.expect(buf.len() == 0); testing.expect(buf.capacity() >= 10); const old_cap = buf.capacity(); try buf.append("hello"); testing.expect(buf.len() == 5); testing.expect(buf.capacity() == old_cap); testing.expect(mem.eql(u8, buf.span(), "hello")); } test "Buffer.print" { var buf = try Buffer.init(testing.allocator, ""); defer buf.deinit(); try buf.outStream().print("Hello {} the {}", .{ 2, "world" }); testing.expect(buf.eql("Hello 2 the world")); } test "Buffer.outStream" { var buffer = try Buffer.initSize(testing.allocator, 0); defer buffer.deinit(); const buf_stream = buffer.outStream(); const x: i32 = 42; const y: i32 = 1234; try buf_stream.print("x: {}\ny: {}\n", .{ x, y }); testing.expect(mem.eql(u8, buffer.span(), "x: 42\ny: 1234\n")); }
lib/std/buffer.zig
const std = @import("std"); const builtin = @import("builtin"); fn offsetPtr(ptr: [*]const u8, offset: usize) callconv(.Inline) [*]const u8 { // ptr + offset doesn't work at comptime so we need this instead. return @ptrCast([*]const u8, &ptr[offset]); } fn fetch32(ptr: [*]const u8, offset: usize) u32 { return std.mem.readIntLittle(u32, offsetPtr(ptr, offset)[0..4]); } fn fetch64(ptr: [*]const u8, offset: usize) u64 { return std.mem.readIntLittle(u64, offsetPtr(ptr, offset)[0..8]); } pub const CityHash32 = struct { const Self = @This(); // Magic numbers for 32-bit hashing. Copied from Murmur3. const c1: u32 = 0xcc9e2d51; const c2: u32 = 0x1b873593; // A 32-bit to 32-bit integer hash copied from Murmur3. fn fmix(h: u32) u32 { var h1: u32 = h; h1 ^= h1 >> 16; h1 *%= 0x85ebca6b; h1 ^= h1 >> 13; h1 *%= 0xc2b2ae35; h1 ^= h1 >> 16; return h1; } // Rotate right helper fn rotr32(x: u32, comptime r: u32) u32 { return (x >> r) | (x << (32 - r)); } // Helper from Murmur3 for combining two 32-bit values. fn mur(a: u32, h: u32) u32 { var a1: u32 = a; var h1: u32 = h; a1 *%= c1; a1 = rotr32(a1, 17); a1 *%= c2; h1 ^= a1; h1 = rotr32(h1, 19); return h1 *% 5 +% 0xe6546b64; } fn hash32Len0To4(str: []const u8) u32 { const len: u32 = @truncate(u32, str.len); var b: u32 = 0; var c: u32 = 9; for (str) |v| { b = b *% c1 +% @bitCast(u32, @intCast(i32, @bitCast(i8, v))); c ^= b; } return fmix(mur(b, mur(len, c))); } fn hash32Len5To12(str: []const u8) u32 { var a: u32 = @truncate(u32, str.len); var b: u32 = a *% 5; var c: u32 = 9; const d: u32 = b; a +%= fetch32(str.ptr, 0); b +%= fetch32(str.ptr, str.len - 4); c +%= fetch32(str.ptr, (str.len >> 1) & 4); return fmix(mur(c, mur(b, mur(a, d)))); } fn hash32Len13To24(str: []const u8) u32 { const len: u32 = @truncate(u32, str.len); const a: u32 = fetch32(str.ptr, (str.len >> 1) - 4); const b: u32 = fetch32(str.ptr, 4); const c: u32 = fetch32(str.ptr, str.len - 8); const d: u32 = fetch32(str.ptr, str.len >> 1); const e: u32 = fetch32(str.ptr, 0); const f: u32 = fetch32(str.ptr, str.len - 4); return fmix(mur(f, mur(e, mur(d, mur(c, mur(b, mur(a, len))))))); } pub fn hash(str: []const u8) u32 { if (str.len <= 24) { if (str.len <= 4) { return hash32Len0To4(str); } else { if (str.len <= 12) return hash32Len5To12(str); return hash32Len13To24(str); } } const len: u32 = @truncate(u32, str.len); var h: u32 = len; var g: u32 = c1 *% len; var f: u32 = g; const a0: u32 = rotr32(fetch32(str.ptr, str.len - 4) *% c1, 17) *% c2; const a1: u32 = rotr32(fetch32(str.ptr, str.len - 8) *% c1, 17) *% c2; const a2: u32 = rotr32(fetch32(str.ptr, str.len - 16) *% c1, 17) *% c2; const a3: u32 = rotr32(fetch32(str.ptr, str.len - 12) *% c1, 17) *% c2; const a4: u32 = rotr32(fetch32(str.ptr, str.len - 20) *% c1, 17) *% c2; h ^= a0; h = rotr32(h, 19); h = h *% 5 +% 0xe6546b64; h ^= a2; h = rotr32(h, 19); h = h *% 5 +% 0xe6546b64; g ^= a1; g = rotr32(g, 19); g = g *% 5 +% 0xe6546b64; g ^= a3; g = rotr32(g, 19); g = g *% 5 +% 0xe6546b64; f +%= a4; f = rotr32(f, 19); f = f *% 5 +% 0xe6546b64; var iters = (str.len - 1) / 20; var ptr = str.ptr; while (iters != 0) : (iters -= 1) { const b0: u32 = rotr32(fetch32(ptr, 0) *% c1, 17) *% c2; const b1: u32 = fetch32(ptr, 4); const b2: u32 = rotr32(fetch32(ptr, 8) *% c1, 17) *% c2; const b3: u32 = rotr32(fetch32(ptr, 12) *% c1, 17) *% c2; const b4: u32 = fetch32(ptr, 16); h ^= b0; h = rotr32(h, 18); h = h *% 5 +% 0xe6546b64; f +%= b1; f = rotr32(f, 19); f = f *% c1; g +%= b2; g = rotr32(g, 18); g = g *% 5 +% 0xe6546b64; h ^= b3 +% b1; h = rotr32(h, 19); h = h *% 5 +% 0xe6546b64; g ^= b4; g = @byteSwap(u32, g) *% 5; h +%= b4 *% 5; h = @byteSwap(u32, h); f +%= b0; const t: u32 = h; h = f; f = g; g = t; ptr = offsetPtr(ptr, 20); } g = rotr32(g, 11) *% c1; g = rotr32(g, 17) *% c1; f = rotr32(f, 11) *% c1; f = rotr32(f, 17) *% c1; h = rotr32(h +% g, 19); h = h *% 5 +% 0xe6546b64; h = rotr32(h, 17) *% c1; h = rotr32(h +% f, 19); h = h *% 5 +% 0xe6546b64; h = rotr32(h, 17) *% c1; return h; } }; pub const CityHash64 = struct { const Self = @This(); // Some primes between 2^63 and 2^64 for various uses. const k0: u64 = 0xc3a5c85c97cb3127; const k1: u64 = 0xb492b66fbe98f273; const k2: u64 = 0x9ae16a3b2f90404f; // Rotate right helper fn rotr64(x: u64, comptime r: u64) u64 { return (x >> r) | (x << (64 - r)); } fn shiftmix(v: u64) u64 { return v ^ (v >> 47); } fn hashLen16(u: u64, v: u64) u64 { return @call(.{ .modifier = .always_inline }, hash128To64, .{ u, v }); } fn hashLen16Mul(low: u64, high: u64, mul: u64) u64 { var a: u64 = (low ^ high) *% mul; a ^= (a >> 47); var b: u64 = (high ^ a) *% mul; b ^= (b >> 47); b *%= mul; return b; } fn hash128To64(low: u64, high: u64) u64 { return @call(.{ .modifier = .always_inline }, hashLen16Mul, .{ low, high, 0x9ddfea08eb382d69 }); } fn hashLen0To16(str: []const u8) u64 { const len: u64 = @as(u64, str.len); if (len >= 8) { const mul: u64 = k2 +% len *% 2; const a: u64 = fetch64(str.ptr, 0) +% k2; const b: u64 = fetch64(str.ptr, str.len - 8); const c: u64 = rotr64(b, 37) *% mul +% a; const d: u64 = (rotr64(a, 25) +% b) *% mul; return hashLen16Mul(c, d, mul); } if (len >= 4) { const mul: u64 = k2 +% len *% 2; const a: u64 = fetch32(str.ptr, 0); return hashLen16Mul(len +% (a << 3), fetch32(str.ptr, str.len - 4), mul); } if (len > 0) { const a: u8 = str[0]; const b: u8 = str[str.len >> 1]; const c: u8 = str[str.len - 1]; const y: u32 = @intCast(u32, a) +% (@intCast(u32, b) << 8); const z: u32 = @truncate(u32, str.len) +% (@intCast(u32, c) << 2); return shiftmix(@intCast(u64, y) *% k2 ^ @intCast(u64, z) *% k0) *% k2; } return k2; } fn hashLen17To32(str: []const u8) u64 { const len: u64 = @as(u64, str.len); const mul: u64 = k2 +% len *% 2; const a: u64 = fetch64(str.ptr, 0) *% k1; const b: u64 = fetch64(str.ptr, 8); const c: u64 = fetch64(str.ptr, str.len - 8) *% mul; const d: u64 = fetch64(str.ptr, str.len - 16) *% k2; return hashLen16Mul(rotr64(a +% b, 43) +% rotr64(c, 30) +% d, a +% rotr64(b +% k2, 18) +% c, mul); } fn hashLen33To64(str: []const u8) u64 { const len: u64 = @as(u64, str.len); const mul: u64 = k2 +% len *% 2; const a: u64 = fetch64(str.ptr, 0) *% k2; const b: u64 = fetch64(str.ptr, 8); const c: u64 = fetch64(str.ptr, str.len - 24); const d: u64 = fetch64(str.ptr, str.len - 32); const e: u64 = fetch64(str.ptr, 16) *% k2; const f: u64 = fetch64(str.ptr, 24) *% 9; const g: u64 = fetch64(str.ptr, str.len - 8); const h: u64 = fetch64(str.ptr, str.len - 16) *% mul; const u: u64 = rotr64(a +% g, 43) +% (rotr64(b, 30) +% c) *% 9; const v: u64 = ((a +% g) ^ d) +% f +% 1; const w: u64 = @byteSwap(u64, (u +% v) *% mul) +% h; const x: u64 = rotr64(e +% f, 42) +% c; const y: u64 = (@byteSwap(u64, (v +% w) *% mul) +% g) *% mul; const z: u64 = e +% f +% c; const a1: u64 = @byteSwap(u64, (x +% z) *% mul +% y) +% b; const b1: u64 = shiftmix((z +% a1) *% mul +% d +% h) *% mul; return b1 +% x; } const WeakPair = struct { first: u64, second: u64, }; fn weakHashLen32WithSeedsHelper(w: u64, x: u64, y: u64, z: u64, a: u64, b: u64) WeakPair { var a1: u64 = a; var b1: u64 = b; a1 +%= w; b1 = rotr64(b1 +% a1 +% z, 21); var c: u64 = a1; a1 +%= x; a1 +%= y; b1 +%= rotr64(a1, 44); return WeakPair{ .first = a1 +% z, .second = b1 +% c }; } fn weakHashLen32WithSeeds(ptr: [*]const u8, a: u64, b: u64) WeakPair { return @call(.{ .modifier = .always_inline }, weakHashLen32WithSeedsHelper, .{ fetch64(ptr, 0), fetch64(ptr, 8), fetch64(ptr, 16), fetch64(ptr, 24), a, b, }); } pub fn hash(str: []const u8) u64 { if (str.len <= 32) { if (str.len <= 16) { return hashLen0To16(str); } else { return hashLen17To32(str); } } else if (str.len <= 64) { return hashLen33To64(str); } var len: u64 = @as(u64, str.len); var x: u64 = fetch64(str.ptr, str.len - 40); var y: u64 = fetch64(str.ptr, str.len - 16) +% fetch64(str.ptr, str.len - 56); var z: u64 = hashLen16(fetch64(str.ptr, str.len - 48) +% len, fetch64(str.ptr, str.len - 24)); var v: WeakPair = weakHashLen32WithSeeds(offsetPtr(str.ptr, str.len - 64), len, z); var w: WeakPair = weakHashLen32WithSeeds(offsetPtr(str.ptr, str.len - 32), y +% k1, x); x = x *% k1 +% fetch64(str.ptr, 0); len = (len - 1) & ~@intCast(u64, 63); var ptr: [*]const u8 = str.ptr; while (true) { x = rotr64(x +% y +% v.first +% fetch64(ptr, 8), 37) *% k1; y = rotr64(y +% v.second +% fetch64(ptr, 48), 42) *% k1; x ^= w.second; y +%= v.first +% fetch64(ptr, 40); z = rotr64(z +% w.first, 33) *% k1; v = weakHashLen32WithSeeds(ptr, v.second *% k1, x +% w.first); w = weakHashLen32WithSeeds(offsetPtr(ptr, 32), z +% w.second, y +% fetch64(ptr, 16)); const t: u64 = z; z = x; x = t; ptr = offsetPtr(ptr, 64); len -= 64; if (len == 0) break; } return hashLen16(hashLen16(v.first, w.first) +% shiftmix(y) *% k1 +% z, hashLen16(v.second, w.second) +% x); } pub fn hashWithSeed(str: []const u8, seed: u64) u64 { return @call(.{ .modifier = .always_inline }, Self.hashWithSeeds, .{ str, k2, seed }); } pub fn hashWithSeeds(str: []const u8, seed0: u64, seed1: u64) u64 { return hashLen16(hash(str) -% seed0, seed1); } }; fn SMHasherTest(comptime hash_fn: anytype) u32 { const HashResult = @typeInfo(@TypeOf(hash_fn)).Fn.return_type.?; var key: [256]u8 = undefined; var hashes_bytes: [256 * @sizeOf(HashResult)]u8 = undefined; var final: HashResult = 0; std.mem.set(u8, &key, 0); std.mem.set(u8, &hashes_bytes, 0); var i: u32 = 0; while (i < 256) : (i += 1) { key[i] = @intCast(u8, i); var h: HashResult = hash_fn(key[0..i], 256 - i); // comptime can't really do reinterpret casting yet, // so we need to write the bytes manually. for (hashes_bytes[i * @sizeOf(HashResult) ..][0..@sizeOf(HashResult)]) |*byte| { byte.* = @truncate(u8, h); h = h >> 8; } } return @truncate(u32, hash_fn(&hashes_bytes, 0)); } fn CityHash32hashIgnoreSeed(str: []const u8, seed: u32) u32 { return CityHash32.hash(str); } test "cityhash32" { const Test = struct { fn doTest() !void { // Note: SMHasher doesn't provide a 32bit version of the algorithm. // Note: The implementation was verified against the Google Abseil version. try std.testing.expectEqual(SMHasherTest(CityHash32hashIgnoreSeed), 0x68254F81); try std.testing.expectEqual(SMHasherTest(CityHash32hashIgnoreSeed), 0x68254F81); } }; try Test.doTest(); // TODO This is uncommented to prevent OOM on the CI server. Re-enable this test // case once we ship stage2. //@setEvalBranchQuota(50000); //comptime Test.doTest(); } test "cityhash64" { const Test = struct { fn doTest() !void { // Note: This is not compliant with the SMHasher implementation of CityHash64! // Note: The implementation was verified against the Google Abseil version. try std.testing.expectEqual(SMHasherTest(CityHash64.hashWithSeed), 0x5FABC5C5); } }; try Test.doTest(); // TODO This is uncommented to prevent OOM on the CI server. Re-enable this test // case once we ship stage2. //@setEvalBranchQuota(50000); //comptime Test.doTest(); }
lib/std/hash/cityhash.zig
const TestContext = @import("../../src-self-hosted/test.zig").TestContext; pub fn addCases(ctx: *TestContext) void { ctx.addZIRTransform("elemptr, add, cmp, condbr, return, breakpoint", \\@void = primitive(void) \\@usize = primitive(usize) \\@fnty = fntype([], @void, cc=C) \\@0 = int(0) \\@1 = int(1) \\@2 = int(2) \\@3 = int(3) \\ \\@entry = fn(@fnty, { \\ %a = str("\x32\x08\x01\x0a") \\ %eptr0 = elemptr(%a, @0) \\ %eptr1 = elemptr(%a, @1) \\ %eptr2 = elemptr(%a, @2) \\ %eptr3 = elemptr(%a, @3) \\ %v0 = deref(%eptr0) \\ %v1 = deref(%eptr1) \\ %v2 = deref(%eptr2) \\ %v3 = deref(%eptr3) \\ %x0 = add(%v0, %v1) \\ %x1 = add(%v2, %v3) \\ %result = add(%x0, %x1) \\ \\ %expected = int(69) \\ %ok = cmp(%result, eq, %expected) \\ %10 = condbr(%ok, { \\ %11 = return() \\ }, { \\ %12 = breakpoint() \\ }) \\}) \\ \\@9 = str("entry") \\@10 = export(@9, @entry) , \\@0 = primitive(void) \\@1 = fntype([], @0, cc=C) \\@2 = fn(@1, { \\ %0 = return() \\}) \\@3 = str("entry") \\@4 = export(@3, @2) \\ ); if (@import("std").Target.current.os.tag != .linux or @import("std").Target.current.cpu.arch != .x86_64) { // TODO implement self-hosted PE (.exe file) linking // TODO implement more ZIR so we don't depend on x86_64-linux return; } ctx.addZIRCompareOutput("hello world ZIR", \\@0 = str("Hello, world!\n") \\@1 = primitive(noreturn) \\@2 = primitive(usize) \\@3 = fntype([], @1, cc=Naked) \\@4 = int(0) \\@5 = int(1) \\@6 = int(231) \\@7 = str("len") \\ \\@8 = fn(@3, { \\ %0 = as(@2, @5) ; SYS_write \\ %1 = as(@2, @5) ; STDOUT_FILENO \\ %2 = ptrtoint(@0) ; msg ptr \\ %3 = fieldptr(@0, @7) ; msg len ptr \\ %4 = deref(%3) ; msg len \\ %sysoutreg = str("={rax}") \\ %rax = str("{rax}") \\ %rdi = str("{rdi}") \\ %rsi = str("{rsi}") \\ %rdx = str("{rdx}") \\ %rcx = str("rcx") \\ %r11 = str("r11") \\ %memory = str("memory") \\ %syscall = str("syscall") \\ %5 = asm(%syscall, @2, \\ volatile=1, \\ output=%sysoutreg, \\ inputs=[%rax, %rdi, %rsi, %rdx], \\ clobbers=[%rcx, %r11, %memory], \\ args=[%0, %1, %2, %4]) \\ \\ %6 = as(@2, @6) ;SYS_exit_group \\ %7 = as(@2, @4) ;exit code \\ %8 = asm(%syscall, @2, \\ volatile=1, \\ output=%sysoutreg, \\ inputs=[%rax, %rdi], \\ clobbers=[%rcx, %r11, %memory], \\ args=[%6, %7]) \\ \\ %9 = unreachable() \\}) \\ \\@9 = str("_start") \\@10 = export(@9, @8) , \\Hello, world! \\ ); }
test/stage2/zir.zig
const std = @import("std"); const builtin = @import("builtin"); const testing = std.testing; const math = std.math; const root = @import("root"); const io = std.io; const os = std.os; const fs = std.fs; // TODO: check windows support const windows = os.windows; const posix = os.posix; const Mutex = std.Mutex; // TODO: readd windows support // const FOREGROUND_BLUE = 1; // const FOREGROUND_GREEN = 2; // const FOREGROUND_AQUA = 3; // const FOREGROUND_RED = 4; // const FOREGROUND_MAGENTA = 5; // const FOREGROUND_YELLOW = 6; pub const TTY = enum { const Self = @This(); Red, Green, Yellow, Blue, Magenta, Cyan, White, Reset, Bright, Dim, pub fn Code(self: Self) []const u8 { return switch (self) { .Red => "\x1b[31m", .Green => "\x1b[32m", .Yellow => "\x1b[33m", .Blue => "\x1b[34m", .Magenta => "\x1b[35m", .Cyan => "\x1b[36m", .White => "\x1b[37m", .Reset => "\x1b[0m", .Bright => "\x1b[1m", .Dim => "\x1b[2m", }; } }; /// The default log level is based on build mode. pub const default_level: Level = switch (builtin.mode) { .Debug => .Debug, .ReleaseSafe => .Info, .ReleaseFast => .Error, .ReleaseSmall => .Error, }; /// The current log level. This is set to root.log_level if present, otherwise /// log.default_level. pub const level: Level = if (@hasDecl(root, "log_level")) root.log_level else default_level; /// different levels of logging pub const Level = enum { const Self = @This(); Trace, Debug, Info, Warn, Error, Fatal, pub fn toString(self: Self) []const u8 { return switch (self) { Self.Trace => "TRACE", Self.Debug => "DEBUG", Self.Info => "INFO", Self.Warn => "WARN", Self.Error => "ERROR", Self.Fatal => "FATAL", }; } pub fn color(self: Self) TTY { return switch (self) { Self.Trace => TTY.Blue, Self.Debug => TTY.Cyan, Self.Info => TTY.Green, Self.Warn => TTY.Yellow, Self.Error => TTY.Red, Self.Fatal => TTY.Magenta, }; } }; pub const LoggerOptions = struct { color: bool = false, fileName: bool = false, lineNumber: bool = false, timestamp: bool = false, doubleSpacing: bool = false, }; /// Used only for writing a single debug info line in the prefix formatter /// This is a work around until https://github.com/ziglang/zig/issues/7106 /// Uses more stack memory than is probably necessary, but it will hopefully be enough pub fn DebugInfoWriter() type { return struct { const Self = @This(); items: Slice = std.mem.zeroes([400]u8), capacity: usize = 0, lastWriteEnd: usize = 0, pub const Slice = [400]u8; pub const SliceConst = []const u8; pub fn appendSlice(self: *Self, items: SliceConst) !void { // std.debug.warn("last: {}, len: {}, items.len: {}\n", .{ self.lastWriteEnd, self.items.len, items.len }); std.mem.copy(u8, self.items[self.lastWriteEnd..], items); self.lastWriteEnd += items.len; } usingnamespace struct { pub const Writer = std.io.Writer(*Self, error{OutOfMemory}, appendWrite); /// Initializes a Writer which will append to the list. pub fn writer(self: *Self) Writer { return .{ .context = self }; } /// Deprecated: use `writer` pub const outStream = writer; /// Same as `append` except it returns the number of bytes written, which is always the same /// as `m.len`. The purpose of this function existing is to match `std.io.Writer` API. fn appendWrite(self: *Self, m: []const u8) !usize { try self.appendSlice(m); return m.len; } }; }; } // NOT THE WAY TO DO THIS // // This code has multiple workarounds due to pending proposals and compiler bugs // // "ambiguity of forced comptime types" https://github.com/ziglang/zig/issues/5672 // "access to root source file for testing" https://github.com/ziglang/zig/issues/6621 pub fn LogFormatPrefix( // writer: anytype, // config: LoggerOptions, log: *Logger, scopelevel: Level, ) void { // TODO: readd windows support // if (std.Target.current.os.tag == .windows and !os.supportsAnsiEscapeCodes(self.file.handle)) { // self.setTtyColorWindows(color); // } else { // } if (log.options.timestamp) { log.writer.print("{} ", .{std.time.timestamp()}) catch return; } if (log.options.color) { log.writer.print("{}", .{TTY.Code(.Reset)}) catch return; log.writer.writeAll(scopelevel.color().Code()) catch return; log.writer.print("[{}]", .{scopelevel.toString()}) catch return; log.writer.writeAll(TTY.Reset.Code()) catch return; log.writer.print(": ", .{}) catch return; } else { log.writer.print("[{s}]: ", .{scopelevel.toString()}) catch return; } // TODO: use better method to get the filename and line number https://github.com/ziglang/zig/issues/7106 // TODO: allow independent fileName and lineNumber if (!log.options.fileName and !log.options.lineNumber) { return; } var dbconfig: std.debug.TTY.Config = .no_color; var lineBuf: DebugInfoWriter() = .{}; const debug_info = std.debug.getSelfDebugInfo() catch return; var it = std.debug.StackIterator.init(@returnAddress(), null); var count: u8 = 0; var address: usize = 0; while (it.next()) |return_address| { if (count == 2) { address = return_address; break; } count += 1; } std.debug.printSourceAtAddress(debug_info, lineBuf.writer(), address - 1, dbconfig) catch unreachable; const colPos = std.mem.indexOf(u8, lineBuf.items[0..], ": "); if (log.options.color) { log.writer.print("{}[{}]: ", .{ TTY.Code(.Reset), lineBuf.items[0..colPos.?] }) catch unreachable; } else { log.writer.print("[{}]: ", .{lineBuf.items[0..colPos.?]}) catch unreachable; } } // Should be this: // // const PrefixFormatter = fn (writer: anytype, options: LoggerOptions, level: Level) void; // // But throws a weird compiled error: // // ./src/index.zig:430:30: error: unable to evaluate constant expression // var logger = Logger.init(file, LoggerOptions{ // // Seems to be related to https://github.com/ziglang/zig/issues/5672 // const PrefixFormatter = fn (log: *Logger, level: Level) void; /// a simple thread-safe logger pub const Logger = struct { const Self = @This(); file: fs.File, writer: fs.File.Writer, default_attrs: windows.WORD, options: LoggerOptions, mutex: Mutex = Mutex{}, // workaround until https://github.com/ziglang/zig/issues/6621 prefixFormatter: PrefixFormatter, /// create `Logger`. pub fn init(file: fs.File, fmtFn: PrefixFormatter, options: LoggerOptions) Self { var info: windows.CONSOLE_SCREEN_BUFFER_INFO = undefined; if (std.Target.current.os.tag == .windows) { _ = windows.kernel32.GetConsoleScreenBufferInfo(file.handle, &info); } return Self{ .file = file, .writer = file.writer(), .default_attrs = info.wAttributes, .options = options, .prefixFormatter = fmtFn, }; } /// General purpose log function. pub fn log(self: *Self, scopeLevel: Level, comptime fmt: []const u8, args: anytype) !void { if (@enumToInt(scopeLevel) < @enumToInt(level)) { return; } var held = self.mutex.acquire(); defer held.release(); // nosuspend self.prefixFormatter(self.writer, self.options, scopeLevel); nosuspend self.prefixFormatter(self, scopeLevel); nosuspend self.writer.print(fmt, args) catch return; if (self.options.doubleSpacing) { self.writer.writeAll("\n") catch return; } } /// log at level `Level.Trace`. pub fn Trace(self: *Self, comptime fmt: []const u8, args: anytype) void { self.log(Level.Trace, fmt, args) catch return; } /// log at level `Level.Debug`. pub fn Debug(self: *Self, comptime fmt: []const u8, args: anytype) void { self.log(Level.Debug, fmt, args) catch return; } /// log at level `Level.Info`. pub fn Info(self: *Self, comptime fmt: []const u8, args: anytype) void { self.log(Level.Info, fmt, args) catch return; } /// log at level `Level.Warn`. pub fn Warn(self: *Self, comptime fmt: []const u8, args: anytype) void { self.log(Level.Warn, fmt, args) catch return; } /// log at level `Level.Error`. pub fn Error(self: *Self, comptime fmt: []const u8, args: anytype) void { self.log(Level.Error, fmt, args) catch return; } /// log at level `Level.Fatal`. pub fn Fatal(self: *Self, comptime fmt: []const u8, args: anytype) void { self.log(Level.Fatal, fmt, args) catch return; } }; test "Log without style" { var tmpDir = testing.tmpDir(std.fs.Dir.OpenDirOptions{}); defer tmpDir.cleanup(); const file = try tmpDir.dir.createFile("test", .{ .mode = 0o755, .truncate = true, }); defer file.close(); var logger = Logger.init(file, LogFormatPrefix, LoggerOptions{ .color = false, .timestamp = false, .fileName = false, .lineNumber = false, .doubleSpacing = false, }); logger.Trace("hi\n", .{}); logger.Debug("hey\n", .{}); logger.Info("hello\n", .{}); logger.Info("hello {} {}\n", .{ "hello", 25 }); logger.Warn("greetings\n", .{}); logger.Error("salutations\n", .{}); logger.Fatal("goodbye\n", .{}); const expect = "[DEBUG]: hey\n[INFO]: hello\n[INFO]: hello hello 25\n[WARN]: greetings\n[ERROR]: salutations\n[FATAL]: goodbye\n"; const out = try tmpDir.dir.readFileAlloc(testing.allocator, "test", math.maxInt(usize)); defer std.testing.allocator.free(out); if (!std.mem.eql(u8, out, expect)) { std.debug.warn("TEST FAILED!\ngot:\n\n{}\n\nexpect:\n\n{}\n", .{ out, expect }); std.os.exit(1); } } test "Log with color" { var tmpDir = testing.tmpDir(std.fs.Dir.OpenDirOptions{}); defer tmpDir.cleanup(); const file = try tmpDir.dir.createFile("test", .{ .mode = 0o755, .truncate = true, }); defer file.close(); var logger = Logger.init(file, LogFormatPrefix, LoggerOptions{ .color = true, .timestamp = false, .fileName = false, .lineNumber = false, .doubleSpacing = false, }); logger.Trace("hi\n", .{}); logger.Debug("hey\n", .{}); logger.Info("hello\n", .{}); logger.Warn("greetings\n", .{}); logger.Error("salutations\n", .{}); logger.Fatal("goodbye\n", .{}); const expect = "\x1b[0m\x1b[36m[DEBUG]\x1b[0m: hey\n\x1b[0m\x1b[32m[INFO]\x1b[0m: hello\n\x1b[0m\x1b[33m[WARN]\x1b[0m: greetings\n\x1b[0m\x1b[31m[ERROR]\x1b[0m: salutations\n\x1b[0m\x1b[35m[FATAL]\x1b[0m: goodbye\n"; const out = try tmpDir.dir.readFileAlloc(testing.allocator, "test", math.maxInt(usize)); defer std.testing.allocator.free(out); if (!std.mem.eql(u8, out, expect)) { std.debug.warn("TEST FAILED!\ngot:\n\n{}\n\nexpect:\n\n{}\n", .{ out, expect }); std.os.exit(1); } } fn worker(logger: *Logger) void { logger.Trace("hi\n", .{}); std.time.sleep(10000); logger.Debug("hey\n", .{}); std.time.sleep(10); logger.Info("hello\n", .{}); std.time.sleep(100); logger.Warn("greetings\n", .{}); std.time.sleep(1000); logger.Error("salutations\n", .{}); std.time.sleep(10000); logger.Fatal("goodbye\n", .{}); std.time.sleep(1000000000); } test "Log Thread Safe" { var tmpDir = testing.tmpDir(std.fs.Dir.OpenDirOptions{}); defer tmpDir.cleanup(); const file = try tmpDir.dir.createFile("test", .{ .mode = 0o755, .truncate = true, }); defer file.close(); var logger = Logger.init(file, LogFormatPrefix, LoggerOptions{}); const thread_count = 5; var threads: [thread_count]*std.Thread = undefined; for (threads) |*t| { t.* = try std.Thread.spawn(&logger, worker); } for (threads) |t| { t.wait(); } const out = try tmpDir.dir.readFileAlloc(testing.allocator, "test", math.maxInt(usize)); defer std.testing.allocator.free(out); // Broken thread logging will probably contain these if (std.mem.count(u8, out, "[]") > 0 or std.mem.count(u8, out, "[[") > 0) { std.debug.warn("TEST FAILED!\ngot:\n\n{}\nexpect: {}\n\n", .{ out, "output to not contain [[ or []" }); std.os.exit(1); } } test "Log with Timestamp" { // Zig does not have date formatted timestamps in std lib yet var tmpDir = testing.tmpDir(std.fs.Dir.OpenDirOptions{}); defer tmpDir.cleanup(); const file = try tmpDir.dir.createFile("test", .{ .mode = 0o755, .truncate = true, }); defer file.close(); var logger = Logger.init(file, LogFormatPrefix, LoggerOptions{ .color = false, .timestamp = true, .fileName = false, .lineNumber = false, .doubleSpacing = false, }); var tsBuf: [10]u8 = undefined; // If there is slowness between these next two lines, the test will fail var ts = try std.fmt.bufPrint(tsBuf[0..], "{}", .{std.time.timestamp()}); logger.Error("boo!\n", .{}); const expect = try std.mem.concat(testing.allocator, u8, &[_][]const u8{ ts, " ", "[ERROR]: boo!\n" }); defer testing.allocator.free(expect); const out = try tmpDir.dir.readFileAlloc(testing.allocator, "test", math.maxInt(usize)); defer std.testing.allocator.free(out); if (!std.mem.eql(u8, out, expect)) { std.debug.warn("TEST FAILED!\ngot:\n\n{}\n\nexpect:\n\n{}\n", .{ out, expect }); std.os.exit(1); } } test "Log with File Name and Line Number" { // Zig does not have date formatted timestamps in std lib yet var tmpDir = testing.tmpDir(std.fs.Dir.OpenDirOptions{}); defer tmpDir.cleanup(); const file = try tmpDir.dir.createFile("test", .{ .mode = 0o755, .truncate = true, }); defer file.close(); var logger = Logger.init(file, LogFormatPrefix, LoggerOptions{ .color = false, .timestamp = false, .fileName = true, .lineNumber = true, .doubleSpacing = false, }); logger.Error("boo!\n", .{}); // TODO: replace with a regex someday, or use @src() const expect = "/src/index.zig:391:17]: boo!\n"; const out = try tmpDir.dir.readFileAlloc(testing.allocator, "test", math.maxInt(usize)); defer std.testing.allocator.free(out); const inStr = if (std.mem.indexOf(u8, out, expect)) |in| in else 1; if (inStr == 0) { std.debug.warn("TEST FAILED!\ngot:\n\n{}\nexpect:\n\n{}\n", .{ out, expect }); std.os.exit(1); } } test "Log with File Name and Line Number with Double Space" { // Zig does not have date formatted timestamps in std lib yet var tmpDir = testing.tmpDir(std.fs.Dir.OpenDirOptions{}); defer tmpDir.cleanup(); const file = try tmpDir.dir.createFile("test", .{ .mode = 0o755, .truncate = true, }); defer file.close(); var logger = Logger.init(file, LogFormatPrefix, LoggerOptions{ .color = false, .timestamp = false, .fileName = true, .lineNumber = true, .doubleSpacing = true, }); logger.Error("boo!\n", .{}); // TODO: replace with a regex someday, or use @src() const expect = "src/index.zig:420:17]: boo!\n\n"; const out = try tmpDir.dir.readFileAlloc(testing.allocator, "test", math.maxInt(usize)); defer std.testing.allocator.free(out); const inStr = if (std.mem.indexOf(u8, out, expect)) |in| in else 1; if (inStr == 0) { std.debug.warn("TEST FAILED!\ngot:\n\n{}\nexpect:\n\n{}\n", .{ out, expect }); std.os.exit(1); } } test "Log starts with reset" { // Zig does not have date formatted timestamps in std lib yet var tmpDir = testing.tmpDir(std.fs.Dir.OpenDirOptions{}); defer tmpDir.cleanup(); const file = try tmpDir.dir.createFile("test", .{ .mode = 0o755, .truncate = true, }); defer file.close(); var logger = Logger.init(file, LogFormatPrefix, LoggerOptions{ .color = true, .timestamp = false, .fileName = false, .lineNumber = false, .doubleSpacing = false, }); logger.Error("boo!\n", .{}); logger.Error("boo2!\n", .{}); // TODO: replace with a regex someday, or use @src() const expect = "\x1b[0m\x1b[31m[ERROR]\x1b[0m: boo!\n\x1b[0m\x1b[31m[ERROR]\x1b[0m: boo2!\n"; const out = try tmpDir.dir.readFileAlloc(testing.allocator, "test", math.maxInt(usize)); defer std.testing.allocator.free(out); if (!std.mem.eql(u8, out, expect)) { std.debug.warn("TEST FAILED!\ngot:\n\n{}\nexpect:\n\n{}\n", .{ out, expect }); std.os.exit(1); } }
src/index.zig
const std = @import("std"); const assert = std.debug.assert; const tools = @import("tools"); pub const main = tools.defaultMain("2021/day04.txt", run); pub fn run(input: []const u8, gpa: std.mem.Allocator) tools.RunError![2][]const u8 { var arena = std.heap.ArenaAllocator.init(gpa); defer arena.deinit(); const allocator = arena.allocator(); const Grid = [25]u8; var grid_list: []Grid = undefined; var number_list: []u8 = undefined; { var it = std.mem.tokenize(u8, input, "\n\r"); if (it.next()) |line| { // first line var list = std.ArrayList(u8).init(allocator); var it_num = std.mem.split(u8, line, ","); while (it_num.next()) |txt| { const n = try std.fmt.parseInt(u8, txt, 10); assert(std.mem.indexOfScalar(u8, list.items, n) == null); // pas de répétitions! try list.append(n); } number_list = list.items; //std.debug.print("numbers={d}\n", .{number_list}); } var grids = std.ArrayList(Grid).init(allocator); var cur_grid: Grid = undefined; var i: u32 = 0; while (it.next()) |line| { var it_num = std.mem.tokenize(u8, line, " \t\n\r"); while (it_num.next()) |txt| { cur_grid[i] = try std.fmt.parseInt(u8, txt, 10); i += 1; if (i % 25 == 0) { try grids.append(cur_grid); i = 0; } } } grid_list = grids.items; //std.debug.print("numbers={} grids={}\n", .{ number_list.len, grid_list.len }); } const answer = ans: { const State = struct { sum: u32, // somme des nombres cochés lines: [5]u8, // combien de cases cochées sur la ligne columns: [5]u8, // combien de cases cochées sur la colonne }; const states = try allocator.alloc(State, grid_list.len); defer allocator.free(states); std.mem.set(State, states, .{ .sum = 0, .lines = [5]u8{ 0, 0, 0, 0, 0 }, .columns = [5]u8{ 0, 0, 0, 0, 0 } }); var active_grids = try allocator.alloc(u32, grid_list.len); defer allocator.free(active_grids); for (active_grids) |*idx, i| idx.* = @intCast(u32, i); var ans1: ?u32 = null; for (number_list) |n| { var j: i32 = 0; while (j < active_grids.len) : (j += 1) { const i = active_grids[@intCast(usize, j)]; const g = grid_list[i]; if (std.mem.indexOfScalar(u8, &g, n)) |idx| { const s = &states[i]; s.sum += n; s.lines[idx / 5] += 1; s.columns[idx % 5] += 1; if (s.lines[idx / 5] == 5 or s.columns[idx % 5] == 5) { // Quine! var total: u32 = 0; for (g) |sq| total += sq; const v = (total - s.sum) * n; if (ans1 == null) ans1 = v; if (active_grids.len == 1) { const ans2 = v; break :ans .{ ans1.?, ans2 }; } // écarte la grille active_grids[@intCast(usize, j)] = active_grids[active_grids.len - 1]; active_grids.len -= 1; j -= 1; } } } } unreachable; }; return [_][]const u8{ try std.fmt.allocPrint(gpa, "{}", .{answer[0]}), try std.fmt.allocPrint(gpa, "{}", .{answer[1]}), }; } test { const res = try run( \\7,4,9,5,11,17,23,2,0,14,21,24,10,16,13,6,15,25,12,22,18,20,8,19,3,26,1 \\ \\22 13 17 11 0 \\ 8 2 23 4 24 \\21 9 14 16 7 \\ 6 10 3 18 5 \\ 1 12 20 15 19 \\ \\ 3 15 0 2 22 \\ 9 18 13 17 5 \\19 8 7 25 23 \\20 11 10 24 4 \\14 21 16 12 6 \\ \\14 21 17 24 4 \\10 16 15 9 19 \\18 8 23 26 20 \\22 11 13 6 5 \\ 2 0 12 3 7 , std.testing.allocator); defer std.testing.allocator.free(res[0]); defer std.testing.allocator.free(res[1]); try std.testing.expectEqualStrings("4512", res[0]); try std.testing.expectEqualStrings("1924", res[1]); }
2021/day04.zig
const Allocator = @import("std").mem.Allocator; const ArenaAllocator = @import("std").heap.ArenaAllocator; const ArrayList = @import("std").ArrayList; const IntegerColor8 = @import("color.zig").IntegerColor8; const MaxDepth = 8; pub const OctTreeQuantizer = struct { rootNode: OctTreeQuantizerNode, levels: [MaxDepth]NodeArrayList, arenaAllocator: ArenaAllocator, const NodeArrayList = ArrayList(*OctTreeQuantizerNode); const Self = @This(); pub fn init(allocator: *Allocator) Self { var result = Self{ .rootNode = OctTreeQuantizerNode{}, .arenaAllocator = ArenaAllocator.init(allocator), .levels = undefined, }; var i: usize = 0; while (i < result.levels.len) : (i += 1) { result.levels[i] = NodeArrayList.init(allocator); } result.rootNode.init(0, &result) catch unreachable; return result; } pub fn deinit(self: *Self) void { self.arenaAllocator.deinit(); var i: usize = 0; while (i < self.levels.len) : (i += 1) { self.levels[i].deinit(); } } pub fn allocateNode(self: *Self) !*OctTreeQuantizerNode { return try self.arenaAllocator.allocator.create(OctTreeQuantizerNode); } pub fn addLevelNode(self: *Self, level: i32, node: *OctTreeQuantizerNode) !void { try self.levels[@intCast(usize, level)].append(node); } pub fn addColor(self: *Self, color: IntegerColor8) !void { try self.rootNode.addColor(color, 0, self); } pub fn getPaletteIndex(self: Self, color: IntegerColor8) !usize { return try self.rootNode.getPaletteIndex(color, 0); } pub fn makePalette(self: *Self, colorCount: usize, palette: []IntegerColor8) anyerror![]IntegerColor8 { var paletteIndex: usize = 0; var rootLeafNodes = try self.rootNode.getLeafNodes(self.arenaAllocator.child_allocator); defer rootLeafNodes.deinit(); var leafCount = rootLeafNodes.items.len; var level: usize = MaxDepth - 1; while (level >= 0) : (level -= 1) { for (self.levels[level].items) |node| { leafCount -= @intCast(usize, node.removeLeaves()); if (leafCount <= colorCount) { break; } } if (leafCount <= colorCount) { break; } try self.levels[level].resize(0); } var processedRoofLeafNodes = try self.rootNode.getLeafNodes(self.arenaAllocator.child_allocator); defer processedRoofLeafNodes.deinit(); for (processedRoofLeafNodes.items) |node| { if (paletteIndex >= colorCount) { break; } if (node.isLeaf()) { palette[paletteIndex] = node.getColor(); node.paletteIndex = paletteIndex; paletteIndex += 1; } } return palette[0..paletteIndex]; } }; const OctTreeQuantizerNode = struct { red: u32 = 0, green: u32 = 0, blue: u32 = 0, referenceCount: usize = 0, paletteIndex: usize = 0, children: [8]?*Self = undefined, const Self = @This(); const NodeArrayList = ArrayList(*Self); pub fn init(self: *Self, level: i32, parent: *OctTreeQuantizer) !void { self.red = 0; self.green = 0; self.blue = 0; self.referenceCount = 0; self.paletteIndex = 0; var i: usize = 0; while (i < self.children.len) : (i += 1) { self.children[i] = null; } if (level < (MaxDepth - 1)) { try parent.addLevelNode(level, self); } } pub fn isLeaf(self: Self) bool { return self.referenceCount > 0; } pub fn getColor(self: Self) IntegerColor8 { return IntegerColor8.initRGB(@intCast(u8, self.red / self.referenceCount), @intCast(u8, self.green / self.referenceCount), @intCast(u8, self.blue / self.referenceCount)); } pub fn addColor(self: *Self, color: IntegerColor8, level: i32, parent: *OctTreeQuantizer) anyerror!void { if (level >= MaxDepth) { self.red += color.R; self.green += color.G; self.blue += color.B; self.referenceCount += 1; return; } const index = getColorIndex(color, level); if (index >= self.children.len) { return error.InvalidColorIndex; } if (self.children[index]) |child| { try child.addColor(color, level + 1, parent); } else { var newNode = try parent.allocateNode(); try newNode.init(level, parent); try newNode.addColor(color, level + 1, parent); self.children[index] = newNode; } } pub fn getPaletteIndex(self: Self, color: IntegerColor8, level: i32) anyerror!usize { if (self.isLeaf()) { return self.paletteIndex; } const index = getColorIndex(color, level); if (self.children[index]) |child| { return try child.getPaletteIndex(color, level + 1); } else { for (self.children) |childOptional| { if (childOptional) |child| { return try child.getPaletteIndex(color, level + 1); } } } return error.ColorNotFound; } pub fn getLeafNodes(self: Self, allocator: *Allocator) anyerror!NodeArrayList { var leafNodes = NodeArrayList.init(allocator); for (self.children) |childOptional| { if (childOptional) |child| { if (child.isLeaf()) { try leafNodes.append(child); } else { var childNodes = try child.getLeafNodes(allocator); defer childNodes.deinit(); for (childNodes.items) |childNode| { try leafNodes.append(childNode); } } } } return leafNodes; } pub fn removeLeaves(self: *Self) i32 { var result: i32 = 0; for (self.children) |childOptional, i| { if (childOptional) |child| { self.red += child.red; self.green += child.green; self.blue += child.blue; self.referenceCount += child.referenceCount; result += 1; self.children[i] = null; } } return result - 1; } inline fn getColorIndex(color: IntegerColor8, level: i32) usize { var index: usize = 0; var mask = @intCast(u8, 0b10000000) >> @intCast(u3, level); if (color.R & mask != 0) { index |= 0b100; } if (color.G & mask != 0) { index |= 0b010; } if (color.B & mask != 0) { index |= 0b001; } return index; } };
src/octree_quantizer.zig
const std = @import("std"); const Allocator = std.mem.Allocator; const ArrayList = std.ArrayList; const AutoHashMap = std.AutoHashMap; const StrMap = std.StringHashMap; const BitSet = std.DynamicBitSet; const Str = []const u8; const util = @import("util.zig"); const gpa = util.gpa; const data = @embedFile("../data/puzzle/day13.txt"); const Dot = struct { x: i64, y: i64, }; const Axis = enum { x, y, }; fn foldDots(dots: *AutoHashMap(Dot, bool), coord: i64, axis: Axis) void { var to_swap = ArrayList(Dot).init(gpa); defer to_swap.deinit(); var it = dots.keyIterator(); while (it.next()) |key_ptr| { if (key_ptr.x > coord and axis == Axis.x) { to_swap.append(key_ptr.*) catch unreachable; } else if (key_ptr.y > coord and axis == Axis.y) { to_swap.append(key_ptr.*) catch unreachable; } } for (to_swap.items) |dot| { var thing = dots.remove(dot); if (axis == Axis.x) { var aux = dots.getOrPutValue(.{ .x = 2 * coord - dot.x, .y = dot.y }, true) catch unreachable; } else { var aux = dots.getOrPutValue(.{ .x = dot.x, .y = 2 * coord - dot.y }, true) catch unreachable; } } } pub fn main() !void { var dots = AutoHashMap(Dot, bool).init(gpa); defer dots.deinit(); var lines = tokenize(data, "\r\n"); while (lines.next()) |line| { if (line[0] == 'f') { var words = split(line, "="); var axis = strToEnum(Axis, words.next().?[11..12]).?; var val = parseInt(i64, words.next().?, 10) catch unreachable; foldDots(&dots, val, axis); print("Folded {}={}: {}\n", .{ axis, val, dots.count() }); } else { var words = split(line, ","); var x = parseInt(i64, words.next().?, 10) catch unreachable; var y = parseInt(i64, words.next().?, 10) catch unreachable; var aux = dots.getOrPutValue(.{ .x = x, .y = y }, true) catch unreachable; } } var map = std.mem.zeroes([6][60]u8); var it = dots.keyIterator(); while (it.next()) |key_ptr| { map[@intCast(usize, key_ptr.y)][@intCast(usize, key_ptr.x)] = 1; } print("\n", .{}); for (map) |row| { for (row) |cell| { if (cell == 1) print("X", .{}); if (cell == 0) print(" ", .{}); } print("\n", .{}); } } // Useful stdlib functions const tokenize = std.mem.tokenize; const split = std.mem.split; const indexOf = std.mem.indexOfScalar; const indexOfAny = std.mem.indexOfAny; const indexOfStr = std.mem.indexOfPosLinear; const lastIndexOf = std.mem.lastIndexOfScalar; const lastIndexOfAny = std.mem.lastIndexOfAny; const lastIndexOfStr = std.mem.lastIndexOfLinear; const trim = std.mem.trim; const sliceMin = std.mem.min; const sliceMax = std.mem.max; const strToEnum = std.meta.stringToEnum; const parseInt = std.fmt.parseInt; const parseFloat = std.fmt.parseFloat; const min = std.math.min; const min3 = std.math.min3; const max = std.math.max; const max3 = std.math.max3; const print = std.debug.print; const assert = std.debug.assert; const sort = std.sort.sort; const asc = std.sort.asc; const desc = std.sort.desc;
src/day13.zig
const std = @import("std"); const assert = std.debug.assert; pub fn main() !void { var gpa = std.heap.GeneralPurposeAllocator(.{}){}; defer _ = gpa.deinit(); const allocator = gpa.allocator(); var input_file = try std.fs.cwd().openFile("input/13.txt", .{}); defer input_file.close(); var buffered_reader = std.io.bufferedReader(input_file.reader()); const dots = try fold(allocator, buffered_reader.reader()); defer allocator.free(dots); try printDots(allocator, dots); } const Point = packed struct { x: u32, y: u32 }; fn printDots(gpa: std.mem.Allocator, dots: []const u64) !void { var max_x: u32 = 0; var max_y: u32 = 0; for (dots) |x| { const dot = @bitCast(Point, x); max_x = std.math.max(max_x, dot.x); max_y = std.math.max(max_y, dot.y); } const width = max_x + 1; const height = max_y + 1; const dot_screen = try gpa.alloc(bool, width * height); defer gpa.free(dot_screen); std.mem.set(bool, dot_screen, false); for (dots) |x| { const dot = @bitCast(Point, x); dot_screen[dot.x + width * dot.y] = true; } const stdout = std.io.getStdOut(); var buffered_writer = std.io.bufferedWriter(stdout.writer()); const writer = buffered_writer.writer(); var y: u32 = 0; while (y < height) : (y += 1) { var x: u32 = 0; while (x < width) : (x += 1) { try writer.writeAll(if (dot_screen[x + width * y]) "#" else "."); } try writer.writeAll("\n"); } try buffered_writer.flush(); } fn fold(gpa: std.mem.Allocator, reader: anytype) ![]const u64 { var arena = std.heap.ArenaAllocator.init(gpa); defer arena.deinit(); const allocator = arena.allocator(); var buf: [4096]u8 = undefined; var parse_mode: enum { dots, fold_instructions } = .dots; var dots = std.ArrayList(u64).init(allocator); while (try reader.readUntilDelimiterOrEof(&buf, '\n')) |line| { switch (parse_mode) { .dots => { if (line.len == 0) { parse_mode = .fold_instructions; } else { var iter = std.mem.split(u8, line, ","); const x = try std.fmt.parseInt(u32, iter.next() orelse return error.WrongFormat, 10); const y = try std.fmt.parseInt(u32, iter.next() orelse return error.WrongFormat, 10); if (iter.next() != null) return error.WrongFormat; try dots.append(@bitCast(u64, Point{ .x = x, .y = y })); } }, .fold_instructions => { var iter = std.mem.split(u8, line, "="); const axis_x_y = iter.next() orelse return error.WrongFormat; const axis_pos = try std.fmt.parseInt(u32, iter.next() orelse return error.WrongFormat, 10); if (iter.next() != null) return error.WrongFormat; if (std.mem.eql(u8, "fold along x", axis_x_y)) { var i: usize = 0; while (i < dots.items.len) { const p = @bitCast(Point, dots.items[i]); if (p.x > axis_pos) { const new_x = p.x - (2 * (p.x - axis_pos)); const new_p = Point{ .x = new_x, .y = p.y }; const already_exists_before = i > 0 and std.mem.indexOfScalar(u64, dots.items[0 .. i - 1], @bitCast(u64, new_p)) != null; const already_exists_after = std.mem.indexOfScalarPos(u64, dots.items, i + 1, @bitCast(u64, new_p)) != null; const already_exists = already_exists_before or already_exists_after; if (already_exists) { _ = dots.swapRemove(i); continue; } else { dots.items[i] = @bitCast(u64, new_p); } } i += 1; } } else if (std.mem.eql(u8, "fold along y", axis_x_y)) { var i: usize = 0; while (i < dots.items.len) { const p = @bitCast(Point, dots.items[i]); if (p.y > axis_pos) { const new_y = p.y - (2 * (p.y - axis_pos)); const new_p = Point{ .x = p.x, .y = new_y }; const already_exists_before = i > 0 and std.mem.indexOfScalar(u64, dots.items[0 .. i - 1], @bitCast(u64, new_p)) != null; const already_exists_after = std.mem.indexOfScalarPos(u64, dots.items, i + 1, @bitCast(u64, new_p)) != null; const already_exists = already_exists_before or already_exists_after; if (already_exists) { _ = dots.swapRemove(i); continue; } else { dots.items[i] = @bitCast(u64, new_p); } } i += 1; } } else unreachable; }, } } return try gpa.dupe(u64, dots.items); }
src/13_2.zig
const std = @import("std"); const math = std.math; const Allocator = std.mem.Allocator; const PixelFormat = @import("pixel_format.zig").PixelFormat; const TypeInfo = std.builtin.TypeInfo; pub inline fn toColorInt(comptime T: type, value: f32) T { return math.max(math.minInt(T), math.min(math.maxInt(T), @floatToInt(T, @round(value * @intToFloat(f32, math.maxInt(T)))))); } pub inline fn toColorFloat(value: anytype) f32 { return @intToFloat(f32, value) / @intToFloat(f32, math.maxInt(@TypeOf(value))); } pub const Color = struct { R: f32, G: f32, B: f32, A: f32, const Self = @This(); pub fn initRGB(r: f32, g: f32, b: f32) Self { return Self{ .R = r, .G = g, .B = b, .A = 1.0, }; } pub fn initRGBA(r: f32, g: f32, b: f32, a: f32) Self { return Self{ .R = r, .G = g, .B = b, .A = a, }; } pub fn fromHtmlHex(value: u32) Self { return Self{ .R = toColorFloat((value >> 16) & 0xFF), .G = toColorFloat((value >> 8) & 0xFF), .B = toColorFloat(value & 0xFF), .A = 1.0, }; } pub fn premultipliedAlpha(self: Self) Self { return Self{ .R = self.R * self.A, .G = self.G * self.A, .B = self.B * self.A, .A = self.A, }; } pub fn toIntegerColor(self: Self, comptime storage_type: type) IntegerColor(storage_type) { return IntegerColor(storage_type){ .R = toColorInt(storage_type, self.R), .G = toColorInt(storage_type, self.G), .B = toColorInt(storage_type, self.B), .A = toColorInt(storage_type, self.A), }; } pub fn toIntegerColor8(self: Self) IntegerColor8 { return toIntegerColor(self, u8); } pub fn toIntegerColor16(self: Self) IntegerColor16 { return toIntegerColor(self, u16); } }; pub fn IntegerColor(comptime storage_type: type) type { return struct { R: storage_type, G: storage_type, B: storage_type, A: storage_type, const Self = @This(); pub fn initRGB(r: storage_type, g: storage_type, b: storage_type) Self { return Self{ .R = r, .G = g, .B = b, .A = math.maxInt(storage_type), }; } pub fn initRGBA(r: storage_type, g: storage_type, b: storage_type, a: storage_type) Self { return Self{ .R = r, .G = g, .B = b, .A = a, }; } pub fn fromHtmlHex(value: u32) Self { return Self{ .R = @intCast(storage_type, (value >> 16) & 0xFF), .G = @intCast(storage_type, (value >> 8) & 0xFF), .B = @intCast(storage_type, value & 0xFF), .A = math.maxInt(storage_type), }; } pub fn premultipliedAlpha(self: Self) Self { var floatR: f32 = toColorFloat(self.R); var floatG: f32 = toColorFloat(self.G); var floatB: f32 = toColorFloat(self.B); var floatA: f32 = toColorFloat(self.A); return Self{ .R = toColorInt(u8, floatR * floatA), .G = toColorInt(u8, floatG * floatA), .B = toColorInt(u8, floatB * floatA), .A = self.A, }; } pub fn toColor(self: Self) Color { return Color{ .R = toColorFloat(self.R), .G = toColorFloat(self.G), .B = toColorFloat(self.B), .A = toColorFloat(self.A), }; } }; } pub const IntegerColor8 = IntegerColor(u8); pub const IntegerColor16 = IntegerColor(u16); fn RgbColor(comptime red_bits: comptime_int, comptime green_bits: comptime_int, comptime blue_bits: comptime_int) type { return packed struct { R: RedType, G: GreenType, B: BlueType, const RedType = @Type(TypeInfo{ .Int = TypeInfo.Int{ .signedness = .unsigned, .bits = red_bits } }); const GreenType = @Type(TypeInfo{ .Int = TypeInfo.Int{ .signedness = .unsigned, .bits = green_bits } }); const BlueType = @Type(TypeInfo{ .Int = TypeInfo.Int{ .signedness = .unsigned, .bits = blue_bits } }); const Self = @This(); pub fn initRGB(r: RedType, g: GreenType, b: BlueType) Self { return Self{ .R = r, .G = g, .B = b, }; } pub fn toColor(self: Self) Color { return Color{ .R = toColorFloat(self.R), .G = toColorFloat(self.G), .B = toColorFloat(self.B), .A = 1.0, }; } }; } fn RgbaColor(comptime red_bits: comptime_int, comptime green_bits: comptime_int, comptime blue_bits: comptime_int, comptime alpha_bits: comptime_int) type { return packed struct { R: RedType, G: GreenType, B: BlueType, A: AlphaType, const RedType = @Type(TypeInfo{ .Int = TypeInfo.Int{ .signedness = .unsigned, .bits = red_bits } }); const GreenType = @Type(TypeInfo{ .Int = TypeInfo.Int{ .signedness = .unsigned, .bits = green_bits } }); const BlueType = @Type(TypeInfo{ .Int = TypeInfo.Int{ .signedness = .unsigned, .bits = blue_bits } }); const AlphaType = @Type(TypeInfo{ .Int = TypeInfo.Int{ .signedness = .unsigned, .bits = alpha_bits } }); const Self = @This(); pub fn initRGB(r: RedType, g: GreenType, b: BlueType) Self { return Self{ .R = r, .G = g, .B = b, .A = math.maxInt(AlphaType), }; } pub fn initRGBA(r: RedType, g: GreenType, b: BlueType, a: AlphaType) Self { return Self{ .R = r, .G = g, .B = b, .A = a, }; } pub fn toColor(self: Self) Color { return Color{ .R = toColorFloat(self.R), .G = toColorFloat(self.G), .B = toColorFloat(self.B), .A = toColorFloat(self.A), }; } }; } // Rgb24 // OpenGL: GL_RGB // Vulkan: VK_FORMAT_R8G8B8_UNORM // Direct3D/DXGI: n/a pub const Rgb24 = RgbColor(8, 8, 8); // Rgba32 // OpenGL: GL_RGBA // Vulkan: VK_FORMAT_R8G8B8A8_UNORM // Direct3D/DXGI: DXGI_FORMAT_R8G8B8A8_UNORM pub const Rgba32 = RgbaColor(8, 8, 8, 8); // Rgb565 // OpenGL: n/a // Vulkan: n/a // Direct3D/DXGI: n/a pub const Rgb565 = RgbColor(5, 6, 5); // Rgb555 // OpenGL: GL_RGB5 // Vulkan: VK_FORMAT_R5G6B5_UNORM_PACK16 // Direct3D/DXGI: n/a pub const Rgb555 = RgbColor(5, 5, 5); // Rgb48 // OpenGL: GL_RGB16 // Vulkan: VK_FORMAT_R16G16B16_UNORM // Direct3D/DXGI: n/a pub const Rgb48 = RgbColor(16, 16, 16); // Rgba64 // OpenGL: GL_RGBA16 // Vulkan: VK_FORMAT_R16G16B16A16_UNORM // Direct3D/DXGI: DXGI_FORMAT_R16G16B16A16_UNORM pub const Rgba64 = RgbaColor(16, 16, 16, 16); fn BgrColor(comptime red_bits: comptime_int, comptime green_bits: comptime_int, comptime blue_bits: comptime_int) type { return packed struct { B: BlueType, G: GreenType, R: RedType, const RedType = @Type(TypeInfo{ .Int = TypeInfo.Int{ .signedness = .unsigned, .bits = red_bits } }); const GreenType = @Type(TypeInfo{ .Int = TypeInfo.Int{ .signedness = .unsigned, .bits = green_bits } }); const BlueType = @Type(TypeInfo{ .Int = TypeInfo.Int{ .signedness = .unsigned, .bits = blue_bits } }); const Self = @This(); pub fn initRGB(r: RedType, g: GreenType, b: BlueType) Self { return Self{ .R = r, .G = g, .B = b, }; } pub fn toColor(self: Self) Color { return Color{ .R = toColorFloat(self.R), .G = toColorFloat(self.G), .B = toColorFloat(self.B), .A = 1.0, }; } }; } fn BgraColor(comptime red_bits: comptime_int, comptime green_bits: comptime_int, comptime blue_bits: comptime_int, comptime alpha_bits: comptime_int) type { return packed struct { B: BlueType, G: GreenType, R: RedType, A: AlphaType, const RedType = @Type(TypeInfo{ .Int = TypeInfo.Int{ .signedness = .unsigned, .bits = red_bits } }); const GreenType = @Type(TypeInfo{ .Int = TypeInfo.Int{ .signedness = .unsigned, .bits = green_bits } }); const BlueType = @Type(TypeInfo{ .Int = TypeInfo.Int{ .signedness = .unsigned, .bits = blue_bits } }); const AlphaType = @Type(TypeInfo{ .Int = TypeInfo.Int{ .signedness = .unsigned, .bits = alpha_bits } }); const Self = @This(); pub fn initRGB(r: RedType, g: GreenType, b: BlueType) Self { return Self{ .R = r, .G = g, .B = b, .A = math.maxInt(AlphaType), }; } pub fn initRGBA(r: RedType, g: GreenType, b: BlueType, a: AlphaType) Self { return Self{ .R = r, .G = g, .B = b, .A = a, }; } pub fn toColor(self: Self) Color { return Color{ .R = toColorFloat(self.R), .G = toColorFloat(self.G), .B = toColorFloat(self.B), .A = toColorFloat(self.A), }; } }; } // Bgr24 // OpenGL: GL_BGR // Vulkan: VK_FORMAT_B8G8R8_UNORM // Direct3D/DXGI: n/a pub const Bgr24 = BgrColor(8, 8, 8); // Bgra32 // OpenGL: GL_BGRA // Vulkan: VK_FORMAT_B8G8R8A8_UNORM // Direct3D/DXGI: DXGI_FORMAT_B8G8R8A8_UNORM pub const Bgra32 = BgraColor(8, 8, 8, 8); pub fn IndexedStorage(comptime T: type) type { return struct { palette: []Color, indices: []T, pub const PaletteSize = 1 << @bitSizeOf(T); const Self = @This(); pub fn init(allocator: Allocator, pixel_count: usize) !Self { return Self{ .indices = try allocator.alloc(T, pixel_count), .palette = try allocator.alloc(Color, PaletteSize), }; } pub fn deinit(self: Self, allocator: Allocator) void { allocator.free(self.palette); allocator.free(self.indices); } }; } pub const IndexedStorage1 = IndexedStorage(u1); pub const IndexedStorage2 = IndexedStorage(u2); pub const IndexedStorage4 = IndexedStorage(u4); pub const IndexedStorage8 = IndexedStorage(u8); pub const IndexedStorage16 = IndexedStorage(u16); pub fn Grayscale(comptime T: type) type { return struct { value: T, const Self = @This(); pub fn toColor(self: Self) Color { const gray = toColorFloat(self.value); return Color{ .R = gray, .G = gray, .B = gray, .A = 1.0, }; } }; } pub fn GrayscaleAlpha(comptime T: type) type { return struct { value: T, alpha: T, const Self = @This(); pub fn toColor(self: Self) Color { const gray = toColorFloat(self.value); return Color{ .R = gray, .G = gray, .B = gray, .A = toColorFloat(self.alpha), }; } }; } pub const Grayscale1 = Grayscale(u1); pub const Grayscale2 = Grayscale(u2); pub const Grayscale4 = Grayscale(u4); pub const Grayscale8 = Grayscale(u8); pub const Grayscale16 = Grayscale(u16); pub const Grayscale8Alpha = GrayscaleAlpha(u8); pub const Grayscale16Alpha = GrayscaleAlpha(u16); pub const ColorStorage = union(PixelFormat) { Bpp1: IndexedStorage1, Bpp2: IndexedStorage2, Bpp4: IndexedStorage4, Bpp8: IndexedStorage8, Bpp16: IndexedStorage16, Grayscale1: []Grayscale1, Grayscale2: []Grayscale2, Grayscale4: []Grayscale4, Grayscale8: []Grayscale8, Grayscale8Alpha: []Grayscale8Alpha, Grayscale16: []Grayscale16, Grayscale16Alpha: []Grayscale16Alpha, Rgb24: []Rgb24, Rgba32: []Rgba32, Rgb565: []Rgb565, Rgb555: []Rgb555, Bgr24: []Bgr24, Bgra32: []Bgra32, Rgb48: []Rgb48, Rgba64: []Rgba64, Float32: []Color, const Self = @This(); pub fn init(allocator: Allocator, format: PixelFormat, pixel_count: usize) !Self { return switch (format) { .Bpp1 => { return Self{ .Bpp1 = try IndexedStorage(u1).init(allocator, pixel_count), }; }, .Bpp2 => { return Self{ .Bpp2 = try IndexedStorage(u2).init(allocator, pixel_count), }; }, .Bpp4 => { return Self{ .Bpp4 = try IndexedStorage(u4).init(allocator, pixel_count), }; }, .Bpp8 => { return Self{ .Bpp8 = try IndexedStorage(u8).init(allocator, pixel_count), }; }, .Bpp16 => { return Self{ .Bpp16 = try IndexedStorage(u16).init(allocator, pixel_count), }; }, .Grayscale1 => { return Self{ .Grayscale1 = try allocator.alloc(Grayscale1, pixel_count), }; }, .Grayscale2 => { return Self{ .Grayscale2 = try allocator.alloc(Grayscale2, pixel_count), }; }, .Grayscale4 => { return Self{ .Grayscale4 = try allocator.alloc(Grayscale4, pixel_count), }; }, .Grayscale8 => { return Self{ .Grayscale8 = try allocator.alloc(Grayscale8, pixel_count), }; }, .Grayscale8Alpha => { return Self{ .Grayscale8Alpha = try allocator.alloc(Grayscale8Alpha, pixel_count), }; }, .Grayscale16 => { return Self{ .Grayscale16 = try allocator.alloc(Grayscale16, pixel_count), }; }, .Grayscale16Alpha => { return Self{ .Grayscale16Alpha = try allocator.alloc(Grayscale16Alpha, pixel_count), }; }, .Rgb24 => { return Self{ .Rgb24 = try allocator.alloc(Rgb24, pixel_count), }; }, .Rgba32 => { return Self{ .Rgba32 = try allocator.alloc(Rgba32, pixel_count), }; }, .Rgb565 => { return Self{ .Rgb565 = try allocator.alloc(Rgb565, pixel_count), }; }, .Rgb555 => { return Self{ .Rgb555 = try allocator.alloc(Rgb555, pixel_count), }; }, .Bgr24 => { return Self{ .Bgr24 = try allocator.alloc(Bgr24, pixel_count), }; }, .Bgra32 => { return Self{ .Bgra32 = try allocator.alloc(Bgra32, pixel_count), }; }, .Rgb48 => { return Self{ .Rgb48 = try allocator.alloc(Rgb48, pixel_count), }; }, .Rgba64 => { return Self{ .Rgba64 = try allocator.alloc(Rgba64, pixel_count), }; }, .Float32 => { return Self{ .Float32 = try allocator.alloc(Color, pixel_count), }; }, }; } pub fn deinit(self: Self, allocator: Allocator) void { switch (self) { .Bpp1 => |data| data.deinit(allocator), .Bpp2 => |data| data.deinit(allocator), .Bpp4 => |data| data.deinit(allocator), .Bpp8 => |data| data.deinit(allocator), .Bpp16 => |data| data.deinit(allocator), .Grayscale1 => |data| allocator.free(data), .Grayscale2 => |data| allocator.free(data), .Grayscale4 => |data| allocator.free(data), .Grayscale8 => |data| allocator.free(data), .Grayscale8Alpha => |data| allocator.free(data), .Grayscale16 => |data| allocator.free(data), .Grayscale16Alpha => |data| allocator.free(data), .Rgb24 => |data| allocator.free(data), .Rgba32 => |data| allocator.free(data), .Rgb565 => |data| allocator.free(data), .Rgb555 => |data| allocator.free(data), .Bgr24 => |data| allocator.free(data), .Bgra32 => |data| allocator.free(data), .Rgb48 => |data| allocator.free(data), .Rgba64 => |data| allocator.free(data), .Float32 => |data| allocator.free(data), } } pub fn len(self: Self) usize { return switch (self) { .Bpp1 => |data| data.indices.len, .Bpp2 => |data| data.indices.len, .Bpp4 => |data| data.indices.len, .Bpp8 => |data| data.indices.len, .Bpp16 => |data| data.indices.len, .Grayscale1 => |data| data.len, .Grayscale2 => |data| data.len, .Grayscale4 => |data| data.len, .Grayscale8 => |data| data.len, .Grayscale8Alpha => |data| data.len, .Grayscale16 => |data| data.len, .Grayscale16Alpha => |data| data.len, .Rgb24 => |data| data.len, .Rgba32 => |data| data.len, .Rgb565 => |data| data.len, .Rgb555 => |data| data.len, .Bgr24 => |data| data.len, .Bgra32 => |data| data.len, .Rgb48 => |data| data.len, .Rgba64 => |data| data.len, .Float32 => |data| data.len, }; } pub fn isIndexed(self: Self) bool { return switch (self) { .Bpp1 => true, .Bpp2 => true, .Bpp4 => true, .Bpp8 => true, .Bpp16 => true, else => false, }; } }; pub const ColorStorageIterator = struct { pixels: *const ColorStorage = undefined, current_index: usize = 0, end: usize = 0, const Self = @This(); pub fn init(pixels: *const ColorStorage) Self { return Self{ .pixels = pixels, .end = pixels.len(), }; } pub fn initNull() Self { return Self{}; } pub fn next(self: *Self) ?Color { if (self.current_index >= self.end) { return null; } const result: ?Color = switch (self.pixels.*) { .Bpp1 => |data| data.palette[data.indices[self.current_index]], .Bpp2 => |data| data.palette[data.indices[self.current_index]], .Bpp4 => |data| data.palette[data.indices[self.current_index]], .Bpp8 => |data| data.palette[data.indices[self.current_index]], .Bpp16 => |data| data.palette[data.indices[self.current_index]], .Grayscale1 => |data| data[self.current_index].toColor(), .Grayscale2 => |data| data[self.current_index].toColor(), .Grayscale4 => |data| data[self.current_index].toColor(), .Grayscale8 => |data| data[self.current_index].toColor(), .Grayscale8Alpha => |data| data[self.current_index].toColor(), .Grayscale16 => |data| data[self.current_index].toColor(), .Grayscale16Alpha => |data| data[self.current_index].toColor(), .Rgb24 => |data| data[self.current_index].toColor(), .Rgba32 => |data| data[self.current_index].toColor(), .Rgb565 => |data| data[self.current_index].toColor(), .Rgb555 => |data| data[self.current_index].toColor(), .Bgr24 => |data| data[self.current_index].toColor(), .Bgra32 => |data| data[self.current_index].toColor(), .Rgb48 => |data| data[self.current_index].toColor(), .Rgba64 => |data| data[self.current_index].toColor(), .Float32 => |data| data[self.current_index], }; self.current_index += 1; return result; } };
src/color.zig
const std = @import("std"); const assert = std.debug.assert; const img = @import("Image.zig"); const ImageType = img.ImageType; const CubeMap = @import("CubeMap.zig").CubeMap; const FrameBuffer = @import("FrameBuffer.zig").FrameBuffer; const window = @import("Window.zig"); const c = @import("c.zig").c; const ReferenceCounter = @import("../RefCount.zig").ReferenceCounter; // For point shadows pub const CubeFrameBuffer = struct { ref_count: ReferenceCounter = ReferenceCounter{}, pub const Direction = enum(u32) { PositiveX, NegativeX, PositiveY, NegativeY, PositiveZ, NegativeZ, }; ids: [6]u32, depth_texture: CubeMap, depth_type: FrameBuffer.DepthType, pub fn init(width_height: u32, depth_type: FrameBuffer.DepthType) !CubeFrameBuffer { if (depth_type == FrameBuffer.DepthType.None) { return error.NoTexture; } var frameBuffer = CubeFrameBuffer{ .ids = ([1]u32{0}) ** 6, .depth_type = depth_type, .depth_texture = undefined, // set later }; // Create OpenGL framebuffer objects c.glGenFramebuffers(6, @ptrCast([*c]c_uint, &frameBuffer.ids)); errdefer c.glDeleteFramebuffers(6, @ptrCast([*c]c_uint, &frameBuffer.ids)); var i: u32 = 0; while (i < 6) : (i += 1) { if (frameBuffer.ids[i] == 0) { assert(false); return error.OpenGLError; } } // Create depth buffer frameBuffer.depth_texture = try CubeMap.init(false, img.MinFilter.Nearest); errdefer frameBuffer.depth_texture.free(); try frameBuffer.setTextureSize(width_height); const textureTargets = [6]c_uint{ c.GL_TEXTURE_CUBE_MAP_POSITIVE_X, c.GL_TEXTURE_CUBE_MAP_NEGATIVE_X, c.GL_TEXTURE_CUBE_MAP_POSITIVE_Y, c.GL_TEXTURE_CUBE_MAP_NEGATIVE_Y, c.GL_TEXTURE_CUBE_MAP_POSITIVE_Z, c.GL_TEXTURE_CUBE_MAP_NEGATIVE_Z, }; i = 0; while (i < 6) : (i += 1) { c.glBindFramebuffer(c.GL_FRAMEBUFFER, frameBuffer.ids[i]); c.glFramebufferTexture2D(c.GL_FRAMEBUFFER, c.GL_DEPTH_ATTACHMENT, textureTargets[i], frameBuffer.depth_texture.id, 0); // Configure framebuffer (no colour information is written) c.glDrawBuffer(c.GL_NONE); c.glReadBuffer(c.GL_NONE); // Validate framebuffer if (c.glCheckFramebufferStatus(c.GL_FRAMEBUFFER) != c.GL_FRAMEBUFFER_COMPLETE) { assert(false); return error.OpenGLError; } } c.glBindFramebuffer(c.GL_FRAMEBUFFER, 0); return frameBuffer; } // Bind for drawing pub fn bind(self: *CubeFrameBuffer, direction: Direction) !void { if (self.ids[@enumToInt(direction)] == 0) { assert(false); return error.InvalidState; } c.glBindFramebuffer(c.GL_DRAW_FRAMEBUFFER, self.ids[@enumToInt(direction)]); c.glViewport(0, 0, @intCast(c_int, self.depth_texture.size), @intCast(c_int, self.depth_texture.size)); } pub fn bindDepthTexture(self: CubeFrameBuffer) !void { try self.depth_texture.bind(); } pub fn bindDepthTextureToUnit(self: CubeFrameBuffer, unit: u32) !void { try self.depth_texture.bindToUnit(unit); } pub fn free(self: *CubeFrameBuffer) void { self.ref_count.deinit(); var i: u32 = 0; while (i < 6) : (i += 1) { if (self.ids[i] == 0) { assert(false); continue; } self.depth_texture.free(); self.ids[i] = 0; } c.glDeleteFramebuffers(6, @ptrCast([*c]const c_uint, &self.ids[0])); } pub fn bindDefaultFrameBuffer() void { FrameBuffer.bindDefaultFrameBuffer(); } fn setTextureSize(self: *CubeFrameBuffer, new_width_height: u32) !void { if (self.depth_type == FrameBuffer.DepthType.I16) { try self.depth_texture.upload(new_width_height, ImageType.Depth16, null, null, null, null, null, null); } else if (self.depth_type == FrameBuffer.DepthType.I24) { try self.depth_texture.upload(new_width_height, ImageType.Depth24, null, null, null, null, null, null); } else if (self.depth_type == FrameBuffer.DepthType.F32) { try self.depth_texture.upload(new_width_height, ImageType.Depth32F, null, null, null, null, null, null); } else { assert(false); } } // Active framebuffer will be unbound pub fn resize(self: *CubeFrameBuffer, new_width_height: u32) !void { c.glBindFramebuffer(c.GL_FRAMEBUFFER, 0); try self.setTextureSize(new_width_height); } }; test "framebuffer" { try window.createWindow(false, 200, 200, "test", true, 0); var fb: CubeFrameBuffer = try CubeFrameBuffer.init(256, FrameBuffer.DepthType.I16); try fb.bind(CubeFrameBuffer.Direction.PositiveY); fb.free(); window.closeWindow(); }
src/WindowGraphicsInput/CubeFrameBuffer.zig
const std = @import("std.zig"); const mem = std.mem; /// Like ComptimeStringHashMap but optimized for small sets of disparate string keys. /// Works by separating the keys by length at comptime and only checking strings of /// equal length at runtime. /// /// `kvs` expects a list literal containing list literals or an array/slice of structs /// where `.@"0"` is the `[]const u8` key and `.@"1"` is the associated value of type `V`. /// TODO: https://github.com/ziglang/zig/issues/4335 pub fn ComptimeStringMap(comptime V: type, comptime kvs: anytype) type { const precomputed = comptime blk: { @setEvalBranchQuota(2000); const KV = struct { key: []const u8, value: V, }; var sorted_kvs: [kvs.len]KV = undefined; const lenAsc = (struct { fn lenAsc(context: void, a: KV, b: KV) bool { return a.key.len < b.key.len; } }).lenAsc; for (kvs) |kv, i| { if (V != void) { sorted_kvs[i] = .{ .key = kv.@"0", .value = kv.@"1" }; } else { sorted_kvs[i] = .{ .key = kv.@"0", .value = {} }; } } std.sort.sort(KV, &sorted_kvs, {}, lenAsc); const min_len = sorted_kvs[0].key.len; const max_len = sorted_kvs[sorted_kvs.len - 1].key.len; var len_indexes: [max_len + 1]usize = undefined; var len: usize = 0; var i: usize = 0; while (len <= max_len) : (len += 1) { // find the first keyword len == len while (len > sorted_kvs[i].key.len) { i += 1; } len_indexes[len] = i; } break :blk .{ .min_len = min_len, .max_len = max_len, .sorted_kvs = sorted_kvs, .len_indexes = len_indexes, }; }; return struct { pub fn has(str: []const u8) bool { return get(str) != null; } pub fn get(str: []const u8) ?V { if (str.len < precomputed.min_len or str.len > precomputed.max_len) return null; var i = precomputed.len_indexes[str.len]; while (true) { const kv = precomputed.sorted_kvs[i]; if (kv.key.len != str.len) return null; if (mem.eql(u8, kv.key, str)) return kv.value; i += 1; if (i >= precomputed.sorted_kvs.len) return null; } } }; } const TestEnum = enum { A, B, C, D, E, }; test "ComptimeStringMap list literal of list literals" { const map = ComptimeStringMap(TestEnum, .{ .{ "these", .D }, .{ "have", .A }, .{ "nothing", .B }, .{ "incommon", .C }, .{ "samelen", .E }, }); testMap(map); } test "ComptimeStringMap array of structs" { const KV = struct { @"0": []const u8, @"1": TestEnum, }; const map = ComptimeStringMap(TestEnum, [_]KV{ .{ .@"0" = "these", .@"1" = .D }, .{ .@"0" = "have", .@"1" = .A }, .{ .@"0" = "nothing", .@"1" = .B }, .{ .@"0" = "incommon", .@"1" = .C }, .{ .@"0" = "samelen", .@"1" = .E }, }); testMap(map); } test "ComptimeStringMap slice of structs" { const KV = struct { @"0": []const u8, @"1": TestEnum, }; const slice: []const KV = &[_]KV{ .{ .@"0" = "these", .@"1" = .D }, .{ .@"0" = "have", .@"1" = .A }, .{ .@"0" = "nothing", .@"1" = .B }, .{ .@"0" = "incommon", .@"1" = .C }, .{ .@"0" = "samelen", .@"1" = .E }, }; const map = ComptimeStringMap(TestEnum, slice); testMap(map); } fn testMap(comptime map: anytype) void { std.testing.expectEqual(TestEnum.A, map.get("have").?); std.testing.expectEqual(TestEnum.B, map.get("nothing").?); std.testing.expect(null == map.get("missing")); std.testing.expectEqual(TestEnum.D, map.get("these").?); std.testing.expectEqual(TestEnum.E, map.get("samelen").?); std.testing.expect(!map.has("missing")); std.testing.expect(map.has("these")); } test "ComptimeStringMap void value type, slice of structs" { const KV = struct { @"0": []const u8, }; const slice: []const KV = &[_]KV{ .{ .@"0" = "these" }, .{ .@"0" = "have" }, .{ .@"0" = "nothing" }, .{ .@"0" = "incommon" }, .{ .@"0" = "samelen" }, }; const map = ComptimeStringMap(void, slice); testSet(map); } test "ComptimeStringMap void value type, list literal of list literals" { const map = ComptimeStringMap(void, .{ .{"these"}, .{"have"}, .{"nothing"}, .{"incommon"}, .{"samelen"}, }); testSet(map); } fn testSet(comptime map: anytype) void { std.testing.expectEqual({}, map.get("have").?); std.testing.expectEqual({}, map.get("nothing").?); std.testing.expect(null == map.get("missing")); std.testing.expectEqual({}, map.get("these").?); std.testing.expectEqual({}, map.get("samelen").?); std.testing.expect(!map.has("missing")); std.testing.expect(map.has("these")); }
lib/std/comptime_string_map.zig
const std = @import("std"); const ansi = @import("ansi"); const zwc = @import("zwc"); pub fn main() !void { var con = try zwc.ConsoleApp.init(); var stdout = std.io.getStdOut().writer(); var before_cp = con.getCodepage(); var before_input_mode = try con.getInputMode(); var before_output_mode = try con.getOutputMode(); try con.setInputMode(zwc.InputMode{ .enable_extended_flags = true, // Does things... docs aren't very clear but do say they should be used with quickedit = false .enable_processed_input = false, // False disables Windows handling Control + C, we do that ourselves .enable_mouse_input = true, // Allows mouse events to be processed .enable_quick_edit_mode = false // False disables auto drag selection }); try con.setOutputMode(zwc.OutputMode{ .enable_virtual_terminal_processing = true, // Enables ANSI sequences - this demo was originally a paint app but I didn't want unnecessary external deps to plague this simple example }); defer { con.setCodepage(before_cp) catch {}; con.setInputMode(before_input_mode) catch {}; con.setOutputMode(before_output_mode) catch {}; } try con.setCodepage(65001); try stdout.writeAll("Cool thing: I have UTF-8 support thanks to the 65001 codepage!\n"); var sbi = try con.getScreenBufferInfo(); var w: usize = 0; while (w < sbi.viewport_rect.right + 1) : (w += 1) { try stdout.writeAll("─"); } try stdout.writeAll("\n"); std.debug.print("Move your mouse around and type on your keyboard to see what I do!\n", .{}); main: while (true) { var event = try con.getEvent(); // NOTE: Mouse events don't work in Windows Terminal because Microsoft is slacking switch (event) { .key => |key| { if (key.key == .ascii and key.key.ascii == 3) break :main; std.debug.print("Key Event | key: {} | is down: {}\n", .{ key.key, key.is_down }); }, .mouse => |mouse| { std.debug.print("Mouse Event | abs: {} | in viewport: {}", .{mouse.abs_coords, try con.viewportCoords(mouse.abs_coords, null)}); if (mouse.mouse_flags.double_click) std.debug.print(" | double click", .{}); if (mouse.mouse_flags.mouse_moved) std.debug.print(" | mouse moved", .{}); if (mouse.mouse_flags.mouse_wheeled or mouse.mouse_flags.mouse_hwheeled) std.debug.print(" | mouse wheel: {}", .{mouse.mouse_scroll_direction.?}); if (mouse.mouse_buttons.left_mouse_button) std.debug.print(" | left click", .{}); if (mouse.mouse_buttons.middle_mouse_button) std.debug.print(" | middle click", .{}); if (mouse.mouse_buttons.right_mouse_button) std.debug.print(" | right click", .{}); std.debug.print("\n", .{}); }, .window_buffer_size => |wbz| { std.debug.print("Window Buffer Size | {}\n", .{wbz}); }, .menu => |menu| { std.debug.print("Menu Event | {}\n", .{menu}); }, .focus => |focused| { std.debug.print("Focused | {}\n", .{focused}); } } } }
examples/events.zig
const std = @import("std"); const config = @cImport(@cInclude("config.h")); pub const Score = f64; pub const SCORE_MIN = -std.math.f64_max; pub const SCORE_MAX = std.math.f64_max; pub const MAX_LEN = 1024; const BONUS_INDEX = init: { comptime var table: [256]usize = undefined; std.mem.set(usize, &table, 0); comptime var i = 'A'; inline while (i <= 'Z') : (i += 1) { table[i] = 2; } i = 'a'; inline while (i <= 'z') : (i += 1) { table[i] = 1; } i = '0'; inline while (i <= '9') : (i += 1) { table[i] = 1; } break :init table; }; const BONUS_STATES = init: { var table: [3][256]Score = undefined; for (table) |*sub| { std.mem.set(Score, sub, 0); } table[1]['/'] = config.SCORE_MATCH_SLASH; table[1]['-'] = config.SCORE_MATCH_WORD; table[1]['_'] = config.SCORE_MATCH_WORD; table[1][' '] = config.SCORE_MATCH_WORD; table[1]['.'] = config.SCORE_MATCH_DOT; table[2]['/'] = config.SCORE_MATCH_SLASH; table[2]['-'] = config.SCORE_MATCH_WORD; table[2]['_'] = config.SCORE_MATCH_WORD; table[2][' '] = config.SCORE_MATCH_WORD; table[2]['.'] = config.SCORE_MATCH_DOT; var i = 'a'; inline while (i <= 'z') : (i += 1) { table[2][i] = config.SCORE_MATCH_CAPITAL; } break :init table; }; fn computeBonus(last_ch: u8, ch: u8) Score { return BONUS_STATES[BONUS_INDEX[ch]][last_ch]; } // Lower case versions of needle and haystack. Statically allocated per thread threadlocal var match_needle: [MAX_LEN]u8 = undefined; threadlocal var match_haystack: [MAX_LEN]u8 = undefined; threadlocal var match_bonus: [MAX_LEN]Score = [_]Score{0} ** MAX_LEN; pub const Match = struct { needle: []const u8 = undefined, haystack: []const u8 = undefined, fn init(needle: []const u8, haystack: []const u8) Match { var self = Match{}; self.needle = std.ascii.lowerString(&match_needle, needle); self.haystack = std.ascii.lowerString(&match_haystack, haystack); if (haystack.len <= MAX_LEN and needle.len <= haystack.len) { var last_ch: u8 = '/'; for (haystack) |c, i| { match_bonus[i] = computeBonus(last_ch, c); last_ch = c; } } return self; } fn matchRow(self: *Match, row: usize, curr_D: []Score, curr_M: []Score, last_D: []const Score, last_M: []const Score) void { var prev_score: Score = SCORE_MIN; var gap_score: Score = if (row == self.needle.len - 1) config.SCORE_GAP_TRAILING else config.SCORE_GAP_INNER; for (self.haystack) |h, j| { if (self.needle[row] == h) { var score: Score = SCORE_MIN; if (row == 0) { score = (@intToFloat(f64, j) * config.SCORE_GAP_LEADING) + match_bonus[j]; } else if (j > 0) { score = std.math.max(last_M[j - 1] + match_bonus[j], last_D[j - 1] + config.SCORE_MATCH_CONSECUTIVE); } curr_D[j] = score; prev_score = std.math.max(score, prev_score + gap_score); curr_M[j] = prev_score; } else { curr_D[j] = SCORE_MIN; prev_score = prev_score + gap_score; curr_M[j] = prev_score; } } } }; pub fn match(needle: []const u8, haystack: []const u8) Score { if (needle.len == 0) { return SCORE_MIN; } if (haystack.len > MAX_LEN or needle.len > haystack.len) { // Unreasonably large candidate: return no score // If it is a valid match it will still be returned, it will // just be ranked below any reasonably sized candidates return SCORE_MIN; } if (needle.len == haystack.len) { // Since this method can only be called with a haystack which // matches needle, if the lengths of the strings are equal the // strings themselves must also be equal (ignoring case). return SCORE_MAX; } // D stores the best score for this position ending with a match. // M stores the best possible score at this position. var D: [2][MAX_LEN]Score = undefined; var M: [2][MAX_LEN]Score = undefined; var last_D: []Score = &D[0]; var last_M: []Score = &M[0]; var curr_D: []Score = &D[1]; var curr_M: []Score = &M[1]; var this_match = Match.init(needle, haystack); for (needle) |_, i| { this_match.matchRow(i, curr_D, curr_M, last_D, last_M); std.mem.swap([]Score, &curr_D, &last_D); std.mem.swap([]Score, &curr_M, &last_M); } return last_M[haystack.len - 1]; } pub fn matchPositions(allocator: std.mem.Allocator, needle: []const u8, haystack: []const u8, positions: ?[]usize) Score { if (needle.len == 0) { return SCORE_MIN; } if (haystack.len > MAX_LEN or needle.len > haystack.len) { // Unreasonably large candidate: return no score // If it is a valid match it will still be returned, it will // just be ranked below any reasonably sized candidates return SCORE_MIN; } if (needle.len == haystack.len) { // Since this method can only be called with a haystack which // matches needle, if the lengths of the strings are equal the // strings themselves must also be equal (ignoring case). if (positions) |_| { for (needle) |_, i| { positions.?[i] = i; } } return SCORE_MAX; } var D = allocator.alloc([MAX_LEN]Score, needle.len) catch unreachable; defer allocator.free(D); var M = allocator.alloc([MAX_LEN]Score, needle.len) catch unreachable; defer allocator.free(M); var last_D: []Score = undefined; var last_M: []Score = undefined; var curr_D: []Score = undefined; var curr_M: []Score = undefined; var this_match = Match.init(needle, haystack); for (needle) |_, i| { curr_D = &D[i]; curr_M = &M[i]; this_match.matchRow(i, curr_D, curr_M, last_D, last_M); last_D = curr_D; last_M = curr_M; } if (positions) |_| { var match_required = false; var i: usize = needle.len; var j: usize = haystack.len; outer: while (i > 0) { i -= 1; while (j > 0) : (j -= 1) { const jj = j - 1; // There may be multiple paths which result in the optimal // weight. // // For simplicity, we will pick the first one we encounter, // the latest in the candidate string. if (D[i][jj] != SCORE_MIN and (match_required or D[i][jj] == M[i][jj])) { // If this score was determined using // SCORE_MATCH_CONSECUTIVE, the previous character MUST // be a match match_required = (i != 0) and (jj != 0) and M[i][jj] == D[i - 1][jj - 1] + config.SCORE_MATCH_CONSECUTIVE; positions.?[i] = jj; if (jj == 0) break :outer; j -= 1; break; } } } } return M[needle.len - 1][haystack.len - 1]; } // This is the hot loop for matching algorithm. If this can be optimized, everything speeds up. pub fn hasMatch(needle: []const u8, haystack: []const u8) bool { var i: usize = 0; for (needle) |c| { i = if (std.mem.indexOfAnyPos(u8, haystack, i, &[_]u8{ c, std.ascii.toUpper(c) })) |j| j + 1 else return false; } return true; }
src/match.zig
const Self = @This(); const build_options = @import("build_options"); const std = @import("std"); const mem = std.mem; const assert = std.debug.assert; const wlr = @import("wlroots"); const wl = @import("wayland").server.wl; const server = &@import("main.zig").server; const util = @import("util.zig"); const Output = @import("Output.zig"); const View = @import("View.zig"); const ViewStack = @import("view_stack.zig").ViewStack; const XwaylandUnmanaged = @import("XwaylandUnmanaged.zig"); const DragIcon = @import("DragIcon.zig"); // Minimum effective width/height for outputs. // This is needed, to prevent integer overflows caused by the output effective // resolution beeing too small to fit clients that can't get scaled more and // thus will be bigger than the output resolution. // The value is totally arbitrary and low enough, that it should never be // encountered during normal usage. const min_size = 50; new_output: wl.Listener(*wlr.Output) = wl.Listener(*wlr.Output).init(handleNewOutput), output_layout: *wlr.OutputLayout, layout_change: wl.Listener(*wlr.OutputLayout) = wl.Listener(*wlr.OutputLayout).init(handleLayoutChange), output_manager: *wlr.OutputManagerV1, manager_apply: wl.Listener(*wlr.OutputConfigurationV1) = wl.Listener(*wlr.OutputConfigurationV1).init(handleManagerApply), manager_test: wl.Listener(*wlr.OutputConfigurationV1) = wl.Listener(*wlr.OutputConfigurationV1).init(handleManagerTest), power_manager: *wlr.OutputPowerManagerV1, power_manager_set_mode: wl.Listener(*wlr.OutputPowerManagerV1.event.SetMode) = wl.Listener(*wlr.OutputPowerManagerV1.event.SetMode).init(handlePowerManagerSetMode), /// A list of all outputs all_outputs: std.TailQueue(*Output) = .{}, /// A list of all active outputs. See Output.active outputs: std.TailQueue(Output) = .{}, /// This output is used internally when no real outputs are available. /// It is not advertised to clients. noop_output: Output = undefined, drag_icons: std.SinglyLinkedList(DragIcon) = .{}, /// This list stores all unmanaged Xwayland windows. This needs to be in root /// since X is like the wild west and who knows where these things will go. xwayland_unmanaged_views: if (build_options.xwayland) std.TailQueue(XwaylandUnmanaged) else void = if (build_options.xwayland) .{}, /// Number of layout demands pending before the transaction may be started. pending_layout_demands: u32 = 0, /// Number of pending configures sent in the current transaction. /// A value of 0 means there is no current transaction. pending_configures: u32 = 0, /// Handles timeout of transactions transaction_timer: *wl.EventSource, pub fn init(self: *Self) !void { const output_layout = try wlr.OutputLayout.create(); errdefer output_layout.destroy(); _ = try wlr.XdgOutputManagerV1.create(server.wl_server, output_layout); const event_loop = server.wl_server.getEventLoop(); const transaction_timer = try event_loop.addTimer(*Self, handleTransactionTimeout, self); errdefer transaction_timer.remove(); const noop_wlr_output = try server.noop_backend.noopAddOutput(); self.* = .{ .output_layout = output_layout, .output_manager = try wlr.OutputManagerV1.create(server.wl_server), .power_manager = try wlr.OutputPowerManagerV1.create(server.wl_server), .transaction_timer = transaction_timer, .noop_output = .{ .wlr_output = noop_wlr_output, // TODO: find a good way to not create a wlr.OutputDamage for the noop output .damage = try wlr.OutputDamage.create(noop_wlr_output), .usable_box = .{ .x = 0, .y = 0, .width = 0, .height = 0 }, }, }; noop_wlr_output.data = @ptrToInt(&self.noop_output); server.backend.events.new_output.add(&self.new_output); self.output_manager.events.apply.add(&self.manager_apply); self.output_manager.events.@"test".add(&self.manager_test); self.output_layout.events.change.add(&self.layout_change); self.power_manager.events.set_mode.add(&self.power_manager_set_mode); } pub fn deinit(self: *Self) void { self.output_layout.destroy(); self.transaction_timer.remove(); } fn handleNewOutput(listener: *wl.Listener(*wlr.Output), wlr_output: *wlr.Output) void { const self = @fieldParentPtr(Self, "new_output", listener); std.log.scoped(.output_manager).debug("new output {s}", .{mem.sliceTo(&wlr_output.name, 0)}); const node = util.gpa.create(std.TailQueue(Output).Node) catch { wlr_output.destroy(); return; }; node.data.init(wlr_output) catch { wlr_output.destroy(); util.gpa.destroy(node); return; }; const ptr_node = util.gpa.create(std.TailQueue(*Output).Node) catch { wlr_output.destroy(); util.gpa.destroy(node); return; }; ptr_node.data = &node.data; self.all_outputs.append(ptr_node); self.addOutput(&node.data); } /// Remove the output from self.outputs and evacuate views if it is a member of /// the list. The node is not freed pub fn removeOutput(self: *Self, output: *Output) void { const node = @fieldParentPtr(std.TailQueue(Output).Node, "data", output); // If the node has already been removed, do nothing var output_it = self.outputs.first; while (output_it) |n| : (output_it = n.next) { if (n == node) break; } else return; self.outputs.remove(node); // Use the first output in the list as fallback. If the last real output // is being removed, use the noop output. const fallback_output = blk: { if (self.outputs.first) |output_node| { break :blk &output_node.data; } else { // Store the focused output tags if we are hotplugged down to // 0 real outputs so they can be restored on gaining a new output. self.noop_output.current.tags = output.current.tags; break :blk &self.noop_output; } }; // Move all views from the destroyed output to the fallback one while (output.views.last) |view_node| { const view = &view_node.view; view.sendToOutput(fallback_output); } // Close all layer surfaces on the removed output for (output.layers) |*layer| { // Closing the layer surface will cause LayerSurface.handleUnmap() // to be called synchronously, which will remove it from this list. while (layer.first) |layer_node| { const layer_surface = &layer_node.data; layer_surface.wlr_layer_surface.close(); layer_surface.wlr_layer_surface.output = null; layer_surface.output = undefined; } } // If any seat has the removed output focused, focus the fallback one var seat_it = server.input_manager.seats.first; while (seat_it) |seat_node| : (seat_it = seat_node.next) { const seat = &seat_node.data; if (seat.focused_output == output) { seat.focusOutput(fallback_output); seat.focus(null); } } // Destroy all layouts of the output while (output.layouts.first) |layout_node| layout_node.data.destroy(); while (output.status_trackers.first) |status_node| status_node.data.destroy(); // Arrange the root in case evacuated views affect the layout fallback_output.arrangeViews(); self.startTransaction(); } /// Add the output to self.outputs and the output layout if it has not /// already been added. pub fn addOutput(self: *Self, output: *Output) void { const node = @fieldParentPtr(std.TailQueue(Output).Node, "data", output); // If we have already added the output, do nothing and return var output_it = self.outputs.first; while (output_it) |n| : (output_it = n.next) if (n == node) return; self.outputs.append(node); // This aarranges outputs from left-to-right in the order they appear. The // wlr-output-management protocol may be used to modify this arrangement. // This also creates a wl_output global which is advertised to clients. self.output_layout.addAuto(node.data.wlr_output); // If we previously had no real outputs, move focus from the noop output // to the new one. if (self.outputs.len == 1) { // Restore the focused tags of the last output to be removed output.pending.tags = self.noop_output.current.tags; output.current.tags = self.noop_output.current.tags; // Move all views from noop output to the new output while (self.noop_output.views.last) |n| n.view.sendToOutput(output); // Focus the new output with all seats var it = server.input_manager.seats.first; while (it) |seat_node| : (it = seat_node.next) { const seat = &seat_node.data; seat.focusOutput(output); seat.focus(null); } } } /// Arrange all views on all outputs pub fn arrangeAll(self: *Self) void { var it = self.outputs.first; while (it) |node| : (it = node.next) node.data.arrangeViews(); } /// Record the number of currently pending layout demands so that a transaction /// can be started once all are either complete or have timed out. pub fn trackLayoutDemands(self: *Self) void { self.pending_layout_demands = 0; var it = self.outputs.first; while (it) |node| : (it = node.next) { if (node.data.layout_demand != null) self.pending_layout_demands += 1; } assert(self.pending_layout_demands > 0); } /// This function is used to inform the transaction system that a layout demand /// has either been completed or timed out. If it was the last pending layout /// demand in the current sequence, a transaction is started. pub fn notifyLayoutDemandDone(self: *Self) void { self.pending_layout_demands -= 1; if (self.pending_layout_demands == 0) self.startTransaction(); } /// Initiate an atomic change to the layout. This change will not be /// applied until all affected clients ack a configure and commit a buffer. pub fn startTransaction(self: *Self) void { // If one or more layout demands are currently in progress, postpone // transactions until they complete. Every frame must be perfect. if (self.pending_layout_demands > 0) return; // If a new transaction is started while another is in progress, we need // to reset the pending count to 0 and clear serials from the views const preempting = self.pending_configures > 0; self.pending_configures = 0; // Iterate over all views of all outputs var output_it = self.outputs.first; while (output_it) |output_node| : (output_it = output_node.next) { var view_it = output_node.data.views.first; while (view_it) |view_node| : (view_it = view_node.next) { const view = &view_node.view; if (view.surface == null) continue; if (view.shouldTrackConfigure()) { // Clear the serial in case this transaction is interrupting a prior one. view.pending_serial = null; if (view.needsConfigure()) { view.configure(); self.pending_configures += 1; // Send a frame done that the client will commit a new frame // with the dimensions we sent in the configure. Normally this // event would be sent in the render function. view.sendFrameDone(); } // If there are saved buffers present, then this transaction is interrupting // a previous transaction and we should keep the old buffers. if (view.saved_buffers.items.len == 0) view.saveBuffers(); } else { if (view.needsConfigure()) view.configure(); } } } if (self.pending_configures > 0) { std.log.scoped(.transaction).debug("started transaction with {} pending configure(s)", .{ self.pending_configures, }); // Timeout the transaction after 200ms. If we are preempting an // already in progress transaction, don't extend the timeout. if (!preempting) { self.transaction_timer.timerUpdate(200) catch { std.log.scoped(.transaction).err("failed to update timer", .{}); self.commitTransaction(); }; } } else { // No views need configures, clear the current timer in case we are // interrupting another transaction and commit. self.transaction_timer.timerUpdate(0) catch std.log.scoped(.transaction).err("error disarming timer", .{}); self.commitTransaction(); } } fn handleTransactionTimeout(self: *Self) callconv(.C) c_int { std.log.scoped(.transaction).err("timeout occurred, some imperfect frames may be shown", .{}); self.pending_configures = 0; self.commitTransaction(); return 0; } pub fn notifyConfigured(self: *Self) void { self.pending_configures -= 1; if (self.pending_configures == 0) { // Disarm the timer, as we didn't timeout self.transaction_timer.timerUpdate(0) catch std.log.scoped(.transaction).err("error disarming timer", .{}); self.commitTransaction(); } } /// Apply the pending state and drop stashed buffers. This means that /// the next frame drawn will be the post-transaction state of the /// layout. Should only be called after all clients have configured for /// the new layout. If called early imperfect frames may be drawn. fn commitTransaction(self: *Self) void { assert(self.pending_configures == 0); // Iterate over all views of all outputs var output_it = self.outputs.first; while (output_it) |output_node| : (output_it = output_node.next) { const output = &output_node.data; // Apply pending state of the output if (output.pending.tags != output.current.tags) { std.log.scoped(.output).debug( "changing current focus: {b:0>10} to {b:0>10}", .{ output.current.tags, output.pending.tags }, ); var it = output.status_trackers.first; while (it) |node| : (it = node.next) node.data.sendFocusedTags(output.pending.tags); } output.current = output.pending; var view_tags_changed = false; var urgent_tags_dirty = false; var view_it = output.views.first; while (view_it) |view_node| { const view = &view_node.view; view_it = view_node.next; if (view.surface == null) { view.dropSavedBuffers(); view.output.views.remove(view_node); if (view.destroying) view.destroy(); continue; } assert(!view.destroying); if (view.pending_serial != null and !view.shouldTrackConfigure()) continue; // Apply pending state of the view view.pending_serial = null; if (view.pending.tags != view.current.tags) view_tags_changed = true; if (view.pending.urgent != view.current.urgent) urgent_tags_dirty = true; if (view.pending.urgent and view_tags_changed) urgent_tags_dirty = true; view.current = view.pending; view.dropSavedBuffers(); } if (view_tags_changed) output.sendViewTags(); if (urgent_tags_dirty) output.sendUrgentTags(); output.damage.addWhole(); } server.input_manager.updateCursorState(); } /// Send the new output configuration to all wlr-output-manager clients fn handleLayoutChange( listener: *wl.Listener(*wlr.OutputLayout), output_layout: *wlr.OutputLayout, ) void { const self = @fieldParentPtr(Self, "layout_change", listener); const config = self.outputConfigFromCurrent() catch { std.log.scoped(.output_manager).crit("out of memory", .{}); return; }; self.output_manager.setConfiguration(config); } fn handleManagerApply( listener: *wl.Listener(*wlr.OutputConfigurationV1), config: *wlr.OutputConfigurationV1, ) void { const self = @fieldParentPtr(Self, "manager_apply", listener); defer config.destroy(); if (self.applyOutputConfig(config)) { config.sendSucceeded(); } else { config.sendFailed(); } // Send the config that was actually applied const applied_config = self.outputConfigFromCurrent() catch { std.log.scoped(.output_manager).crit("out of memory", .{}); return; }; self.output_manager.setConfiguration(applied_config); } fn handleManagerTest( listener: *wl.Listener(*wlr.OutputConfigurationV1), config: *wlr.OutputConfigurationV1, ) void { const self = @fieldParentPtr(Self, "manager_test", listener); defer config.destroy(); if (testOutputConfig(config, true)) { config.sendSucceeded(); } else { config.sendFailed(); } } /// Apply the given config, return false on faliure fn applyOutputConfig(self: *Self, config: *wlr.OutputConfigurationV1) bool { // Ignore layout change events while applying the config self.layout_change.link.remove(); defer self.output_layout.events.change.add(&self.layout_change); // Test if the config should apply cleanly if (!testOutputConfig(config, false)) return false; var it = config.heads.iterator(.forward); while (it.next()) |head| { const output = @intToPtr(*Output, head.state.output.data); const disable = output.wlr_output.enabled and !head.state.enabled; // Since we have done a successful test commit, this will only fail // due to error in the output's backend implementation. output.wlr_output.commit() catch std.log.scoped(.output_manager).err("output commit failed for {s}", .{mem.sliceTo(&output.wlr_output.name, 0)}); if (output.wlr_output.enabled) { // Moves the output if it is already in the layout self.output_layout.add(output.wlr_output, head.state.x, head.state.y); } if (disable) { self.removeOutput(output); self.output_layout.remove(output.wlr_output); } // Arrange layers to adjust the usable_box // We dont need to call arrangeViews() since arrangeLayers() will call // it for us because the usable_box changed output.arrangeLayers(.mapped); self.startTransaction(); } return true; } /// Tests the output configuration. /// If rollback is false all changes are applied to the pending state of the affected outputs. fn testOutputConfig(config: *wlr.OutputConfigurationV1, rollback: bool) bool { var ok = true; var it = config.heads.iterator(.forward); while (it.next()) |head| { const wlr_output = head.state.output; const width = if (head.state.mode) |m| m.width else head.state.custom_mode.width; const height = if (head.state.mode) |m| m.height else head.state.custom_mode.height; const scale = head.state.scale; const too_small = (@intToFloat(f32, width) / scale < min_size) or (@intToFloat(f32, height) / scale < min_size); if (too_small) { std.log.scoped(.output_manager).info( "The requested output resolution {}x{} scaled with {} for {s} would be too small.", .{ width, height, scale, mem.sliceTo(&wlr_output.name, 0) }, ); } applyHeadToOutput(head, wlr_output); ok = ok and !too_small and wlr_output.testCommit(); } if (rollback or !ok) { // Rollback all changes it = config.heads.iterator(.forward); while (it.next()) |head| head.state.output.rollback(); } return ok; } fn applyHeadToOutput(head: *wlr.OutputConfigurationV1.Head, wlr_output: *wlr.Output) void { wlr_output.enable(head.state.enabled); // The output must be enabled for the following properties to apply if (head.state.enabled) { // TODO(wlroots) Somehow on the drm backend setting the mode causes // the commit in the rendering loop to fail. The commit that // applies the mode works fine. // We can just ignore this because nothing bad happens but it // should be fixed in the future // See https://github.com/swaywm/wlroots/issues/2492 if (head.state.mode) |mode| { wlr_output.setMode(mode); } else { const custom_mode = &head.state.custom_mode; wlr_output.setCustomMode(custom_mode.width, custom_mode.height, custom_mode.refresh); } wlr_output.setScale(head.state.scale); wlr_output.setTransform(head.state.transform); } } /// Create the config describing the current configuration fn outputConfigFromCurrent(self: *Self) !*wlr.OutputConfigurationV1 { const config = try wlr.OutputConfigurationV1.create(); // this destroys all associated config heads as well errdefer config.destroy(); var it = self.all_outputs.first; while (it) |node| : (it = node.next) try self.createHead(node.data, config); return config; } fn createHead(self: *Self, output: *Output, config: *wlr.OutputConfigurationV1) !void { const head = try wlr.OutputConfigurationV1.Head.create(config, output.wlr_output); // If the output is not part of the layout (and thus disabled) we dont care // about the position if (self.output_layout.getBox(output.wlr_output)) |box| { head.state.x = box.x; head.state.y = box.y; } } fn handlePowerManagerSetMode( listener: *wl.Listener(*wlr.OutputPowerManagerV1.event.SetMode), event: *wlr.OutputPowerManagerV1.event.SetMode, ) void { const self = @fieldParentPtr(Self, "power_manager_set_mode", listener); const enable = event.mode == .on; const log_text = if (enable) "Enabling" else "Disabling"; std.log.scoped(.output_manager).debug( "{s} dpms for output {s}", .{ log_text, mem.sliceTo(&event.output.name, 0) }, ); event.output.enable(enable); event.output.commit() catch { std.log.scoped(.server).err("output commit failed for {s}", .{mem.sliceTo(&event.output.name, 0)}); }; }
source/river-0.1.0/river/Root.zig
const std = @import("std"); // utility for checking if a value is a string. follows optionals and pointers. if string then returns the string value pub fn isString(value: var) ?[]const u8 { const Info = @typeInfo(@TypeOf(value)); switch (Info) { .Pointer => |p| { if (p.size == .Slice and p.child == u8) { return value; } else { return isString(value.*); } }, .Array => |arr| { if (arr.child == u8) { return value[0..]; } }, .Optional => |opt| { if (value) |val| { return isString(val); } else { return null; } }, else => { return null; }, } return null; } test "isString" { std.testing.expect(isString("hi") != null); } pub fn isStringType(comptime T: type) bool { const Info = @typeInfo(T); return switch (Info) { .Pointer => |p| p.size == .Slice and p.child == u8, .Array => |arr| arr.child == u8, .Optional => |opt| isStringType(opt.child), else => false, }; } test "isStringType" { std.testing.expect(isStringType([]const u8)); std.testing.expect(isStringType([]u8)); std.testing.expect(isStringType([4]u8)); std.testing.expect(isStringType(?[]const u8)); std.testing.expect(!isStringType(u8)); std.testing.expect(!isStringType([]u32)); } pub fn isInteger(comptime T: type) bool { comptime { const Info = @typeInfo(T); if (Info == .Int or Info == .ComptimeInt) { return true; } return false; } } pub fn isFloat(comptime T: type) bool { return switch (@typeInfo(T)) { .Float, .ComptimeFloat => true, else => false, }; } // converts any string into the Pascal-Kebab-Case that http headers use pub fn toPascalKebabCase(str: []u8) void { var i: usize = 0; var uppercase = true; while (i < str.len) : (i += 1) { if (uppercase) { str[i] = std.ascii.toUpper(str[i]); uppercase = false; } else if (str[i] == '-') { uppercase = true; } else { str[i] = std.ascii.toLower(str[i]); } } } const StrToNumError = error{ CannotBeLessThanZero, OverflowOrUnderflow, InvalidCharacter }; pub fn strToNum(comptime T: type, str: []const u8) StrToNumError!T { var result: T = 0; var negate: usize = 0; if (str.len > 0 and str[0] == '-') { if (std.math.minInt(T) == 0) { return error.CannotBeLessThanZero; } else { negate = 1; } } for (str[negate..]) |c| { if (@mulWithOverflow(T, result, 10, &result)) { return error.OverflowOrUnderflow; } var char: u8 = c - 48; if (char < 0 or char > 9) { return error.InvalidCharacter; } if (char > std.math.maxInt(T)) { return error.OverflowOrUnderflow; } if (@addWithOverflow(T, result, @intCast(T, char), &result)) { return error.OverflowOrUnderflow; } } if (negate > 0) { if (std.math.minInt(T) < 0) { if (@mulWithOverflow(T, result, -1, &result)) { return error.OverflowOrUnderflow; } } } return result; } test "strToNum" { var num = try strToNum(i32, "500"); std.testing.expect(num == 500); overflow: { var overflow = strToNum(i8, "500") catch break :overflow; unreachable; } var neg = try strToNum(i32, "-500"); std.testing.expect(neg == -500); underflow: { var underflow = strToNum(u8, "-42") catch break :underflow; unreachable; } }
src/utility.zig
const fun = @import("fun"); const std = @import("std"); const debug = std.debug; const heap = std.heap; const io = std.io; const math = std.math; const mem = std.mem; const os = std.os; const scan = fun.scan.scan; pub fn main() !void { const stdin = &(try io.getStdIn()).inStream().stream; const stdout = &(try io.getStdOut()).outStream().stream; var direct_allocator = heap.DirectAllocator.init(); const allocator = &direct_allocator.allocator; defer direct_allocator.deinit(); const lines = try readLines(allocator, stdin); defer { for (lines) |line| allocator.free(line); allocator.free(lines); } try stdout.print("{}\n", checksum(lines)); const match = try findMatch(allocator, lines); defer allocator.free(match); try stdout.print("{}\n", match); } fn readLines(allocator: *mem.Allocator, in_stream: var) ![][]u8 { var lines = std.ArrayList([]u8).init(allocator); defer { for (lines.toSlice()) |line| allocator.free(line); lines.deinit(); } while (in_stream.readUntilDelimiterAlloc(allocator, '\n', 10000)) |line| { try lines.append(line); } else |err| switch (err) { error.EndOfStream => {}, else => return err, } return lines.toOwnedSlice(); } fn checksum(lines: []const []const u8) u64 { var counts = []u64{0} ** (math.maxInt(u8) + 1); for (lines) |line| { var add = []u1{0} ** (math.maxInt(u8) + 1); var letters = []u64{0} ** (math.maxInt(u8) + 1); for (line) |c| letters[c] += 1; for (letters) |num| add[num] = 1; for (add) |num, i| counts[i] += num; } return counts[2] * counts[3]; } fn findMatch(allocator: *mem.Allocator, lines: []const []const u8) ![]u8 { var all = std.ArrayList([]const u8).init(allocator); defer all.deinit(); for (lines) |line| { for (all.toSlice()) |str| { if (str.len != line.len) continue; var diff: usize = 0; for (str) |c, i| diff += @boolToInt(c != line[i]); if (diff != 1) continue; var res = try allocator.alloc(u8, line.len - 1); var res_ptr = res.ptr; for (str) |c, i| { if (c != line[i]) continue; res_ptr.* = c; res_ptr += 1; } debug.assert(res.ptr + res.len == res_ptr); return res; } try all.append(try mem.dupe(allocator, u8, line)); } return error.NoMatch; }
src/day2.zig
const std = @import("std"); const Allocator = std.mem.Allocator; const ArenaAllocator = std.heap.ArenaAllocator; const AutoHashMap = std.AutoHashMap; const test_allocator = std.testing.allocator; const expect = std.testing.expect; const expectEqual = std.testing.expectEqual; const ArrayList = std.ArrayList; usingnamespace @import("./drawer.zig"); const math = std.math; const ascii = std.ascii; const fmt = std.fmt; const mem = std.mem; const unicode = std.unicode; const print = std.debug.print; const assert = std.debug.assert; const Wyhash = std.hash.Wyhash; const panic = std.debug.panic; const Key = enum { Bspc, Esc, Cursor, }; const KeyState = struct { /// If the key is held down (regardless of any frame). is_repeat: bool = false, /// Return true during the frame if the key is down. is_down: bool = false, /// Return true during the frame if the key is up. is_up: bool = false, /// Used to keep track of the previous frame state. was_down: bool = false, }; /// Representing color with alpha channel. /// The method `to_array` is used to convert the /// rgba color to an array. pub const Color = struct { rgb: [3]i32, a: f32, const Self = @This(); /// 0-255 color per channel. pub fn new(r: i32, g: i32, b: i32, a: f32) Self { return .{ .rgb = .{ r, g, b }, .a = a, }; } pub fn black() Self { return Self.new(0, 0, 0, 1); } pub fn white() Self { return Self.new(255, 255, 255, 1); } pub fn to_array(self: *const Self) [4]f32 { return [4]f32{ @intToFloat(f32, self.rgb[0]) / 255, @intToFloat(f32, self.rgb[1]) / 255, @intToFloat(f32, self.rgb[2]) / 255, self.a, }; } }; /// All possible status. pub const Status = enum { Normal, Hovered, Pressed, Dragged, Disabled, }; /// TODO: Rename is_clicked/is_pressed... pub const BoundState = struct { is_hover: bool = false, is_clicked: bool = false, is_pressed: bool = false, is_missed: bool = false, status: Status = .Disabled, }; /// Text pub const Text = struct { x: f32, y: f32, color: Color, content: []const u8, }; const WidgetColor = struct { border_color: Color, base_color: Color, text_color: Color, }; pub const Style = struct { background_color: Color = Color.new(0, 34, 43, 1), line_color: Color = Color.new(129, 192, 208, 1), normal: WidgetColor = .{ .border_color = Color.new(47, 116, 134, 1), .base_color = Color.new(2, 70, 88, 1), .text_color = Color.new(81, 191, 211, 1), }, hovered: WidgetColor = .{ .border_color = Color.new(130, 205, 224, 1), .base_color = Color.new(50, 153, 180, 1), .text_color = Color.new(182, 225, 234, 1), }, pressed: WidgetColor = .{ .border_color = Color.new(235, 118, 48, 1), .base_color = Color.new(255, 188, 81, 1), .text_color = Color.new(216, 111, 54, 1), }, disabled: WidgetColor = .{ .border_color = Color.new(19, 75, 90, 1), .base_color = Color.new(2, 49, 61, 1), .text_color = Color.new(23, 80, 95, 1), }, border_size: f32 = 3, widget_margin: f32 = 5, text_padding: f32 = 10, indent: f32 = 15, resizer_size: f32 = 10, closer_size: f32 = 10, /// TODO: Impl Dragged color. pub fn widget_color(self: *const @This(), status: Status) WidgetColor { return switch (status) { .Normal => self.normal, .Hovered => self.hovered, .Pressed => self.pressed, .Disabled => self.disabled, .Dragged => @panic("Not impl yet!\n"), }; } }; /// Config object, used to pass given allocator, given callback for /// compute text sizes. pub fn Config(comptime F: anytype) type { return struct { allocator: *Allocator, font: *F, font_size: f32, calc_text_size: fn (font: *F, size: f32, text: []const u8) f32, }; } pub const TriangleDir = enum { Down, Right, DiagRight }; /// Simple triangle data + color. pub const Triangle = struct { edges: [6]f32, color: Color, direction: TriangleDir = .Down, pub fn new(rect: Rect, color: Color, dir: TriangleDir) Triangle { return switch (dir) { .Down => down(rect, color), .Right => right(rect, color), .DiagRight => diag_right(rect, color), }; } /// Only used for the resizer. fn diag_right(rect: Rect, color: Color) Triangle { const b_x = rect.x + rect.w; const b_y = rect.y; const c_x = rect.x; const c_y = rect.y + rect.h; const d_x = rect.x + rect.w; const d_y = rect.y + rect.h; return .{ .edges = .{ c_x, c_y, b_x, b_y, d_x, d_y, }, .color = color, }; } /// Triangle pointing to the bottom. fn down(rect: Rect, color: Color) Triangle { const a_x = rect.x; const a_y = rect.y; const b_x = rect.x + rect.w; const b_y = rect.y; const c_x = rect.x + rect.w / 2; const c_y = rect.y + rect.h; return .{ .edges = .{ a_x, a_y, b_x, b_y, c_x, c_y, }, .color = color, }; } /// Triangle pointing to the right. fn right(rect: Rect, color: Color) Triangle { const a_x = rect.x; const a_y = rect.y; const b_x = rect.x; const b_y = rect.y + rect.h; const c_x = rect.x + rect.w; const c_y = rect.y + rect.h / 2; return .{ .edges = .{ a_x, a_y, b_x, b_y, c_x, c_y, }, .color = color, }; } }; /// Rectangle mainly used to describe a region lay down /// on the screen. pub const Rect = struct { x: f32, y: f32, w: f32, h: f32, color: Color = Color.new(1, 1, 1, 0.3), pub fn new(x: f32, y: f32, w: f32, h: f32) Rect { return .{ .x = x, .y = y, .w = w, .h = h }; } /// Create new sub region. pub fn add_padding(outer: Rect, padding_hori: f32, padding_vert: f32) Rect { return Rect.new( outer.x + padding_hori, outer.y + padding_vert, outer.w - padding_hori * 2, outer.h - padding_vert * 2, ); } pub fn intersect(lhs: Rect, rhs: Rect) Rect { const x1 = math.max(lhs.x, rhs.x); const y1 = math.max(lhs.y, rhs.y); var x2 = math.min(lhs.x + lhs.w, rhs.x + rhs.w); var y2 = math.min(lhs.y + lhs.h, rhs.y + rhs.h); if (x2 < x1) x2 = x1; if (y2 < y1) y2 = y1; return Rect.new(x1, y1, x2 - x1, y2 - y1); } /// Align element of given width and height inside /// the given rectangle. pub fn xy_center(container: Rect, w: f32, h: f32) Rect { return Rect.new( container.x + ((container.w - w) / 2), container.y + ((container.h - h) / 2), w, h, ); } pub fn y_center(container: Rect, w: f32, h: f32) Rect { return Rect.new( container.x, container.y + ((container.h - h) / 2), w, h, ); } }; pub const TextAlignment = enum { Left, Center, Right }; const Layout = @import("./layout.zig").Layout; const LayoutOptions = @import("./layout.zig").LayoutOptions; pub const OverlayType = enum { Panel, Popup, Select }; pub const OverlayOptions = struct { overlay_type: OverlayType = .Panel, resizable: bool = false, draggable: bool = false, bordered: bool = false, has_header: bool = false, closable: bool = false, // If overlay should be closed when initialized. closed: bool = false, }; /// Main container. pub const Overlay = struct { id: Id, title: []const u8, header: ?Rect = null, body: Rect, resizer: ?Rect = null, closer: ?Rect = null, parent: ?Id = null, is_closed: bool = false, is_resizing: bool = false, is_dragging: bool = false, scroll: ?Rect = null, options: OverlayOptions = .{}, layout: Layout, /// Return overlay's total bounds. pub fn bounds(win: *const Overlay) Rect { if (win.header) |header| { return .{ .x = header.x, .y = header.y, .w = header.w, .h = header.h + win.body.h, }; } else { return win.body; } } }; const Tree = struct { is_expanded: bool }; const Input = struct { val: f128, buf: []u8, slice: [:0]u8, }; const CachedValue = union(enum) { Overlay: Overlay, Tree: Tree, Input: Input, }; pub const Id = u64; /// Immediate graphical interface. /// You must provide your own Font. pub fn Interface(comptime F: anytype) type { return struct { cfg: Config(F), cursor: struct { delta_x: f32 = 0, delta_y: f32 = 0, x: f32 = 0, y: f32 = 0, scroll_offset: f32 = 0, } = .{}, disabled: bool = false, is_hot: bool = false, /// Visual styles is stored here, padding/margin included. style: Style = .{}, // _draw_list: ArrayList(DrawSlice), layer: struct { /// The active item is always at the end of the stack. orders: ArrayList(Id), /// Next element to bring to front. bring_to_front: ?Id = null, }, drawer: Drawer, /// The overlay currently process. current_overlay: Id, /// Last generated id, used for caching some /// values between frames. last_id: i32 = 0, /// If the value is set to `null`, nothing is currently drag, /// otherwise, the `id` of the dragging element is stored. dragging_id: ?i32 = null, focus_item: ?i32 = null, /// Used to keep track of key pressed. /// Reset between frame. key_status: AutoHashMap(Key, KeyState), /// Frame states. states: AutoHashMap(Id, CachedValue), /// Store user's unicode characters. //TODO: Should be a slice. string_buffer: ArrayList(u8), string_storage: ArrayList([]u8), /// Used to free all heap allocated data at once. _arena: *ArenaAllocator, const Self = @This(); /// Initialize a new Interface from the given style and /// custom configuration object. pub fn init(cfg: Config(F), style: Style) !Self { var ui: Self = undefined; const allocator = cfg.allocator; ui._arena = try allocator.create(ArenaAllocator); ui._arena.* = ArenaAllocator.init(allocator); const arena = ui._arena.child_allocator; ui.cfg = cfg; ui.style = style; ui.layer.orders = ArrayList(Id).init(arena); ui.states = AutoHashMap(Id, CachedValue).init(arena); ui.string_buffer = ArrayList(u8).init(arena); ui.string_storage = ArrayList([]u8).init(arena); ui.key_status = AutoHashMap(Key, KeyState).init(arena); ui.drawer = Drawer.init(arena); return ui; } /// Generic method to construct any kind of overlay. /// They are all stored into the state manager. /// `title` will be used to create the id. fn _overlay( self: *Self, title: []const u8, bounds: Rect, layout_options: struct { hori: f32, vert: f32, space: f32 }, options: OverlayOptions, ) !*Overlay { const style = self.style; const header_size = self.cfg.font_size + style.text_padding * 2; const seed = @intCast(u64, self.gen_id()); const overlay_id = Wyhash.hash(seed, title); // Set drawer id. self.drawer.set_cmd_id(overlay_id); var overlay = blk: { const result = try self.states.getOrPut(overlay_id); // If overlay isn't found in frame states, we initialize a new one. if (!result.found_existing) { if (options.overlay_type == .Select) { try self.layer.orders.insert(0, overlay_id); } else { try self.layer.orders.append(overlay_id); } result.value_ptr.* = .{ .Overlay = Overlay{ .id = overlay_id, .title = title, .header = if (!options.has_header) null else Rect.new( bounds.x, bounds.y, bounds.w, header_size, ), .body = if (!options.has_header) bounds else Rect.new( bounds.x, bounds.y + header_size, bounds.w, bounds.h - header_size, ), .closer = if (!options.closable) null else Rect.new( bounds.x + bounds.w - style.closer_size - 5, bounds.y + 5, style.closer_size, style.closer_size, ), .resizer = if (!options.resizable) null else Rect.new( bounds.x + bounds.w - style.resizer_size - 2, bounds.y + bounds.h - style.resizer_size - 2, style.resizer_size, style.resizer_size, ), .options = options, .is_closed = options.closed, .layout = undefined, // .draw_commands = DrawCommands.init(self._arena.child_allocator), }, }; } const entry = self.states.getEntry(overlay_id).?; break :blk &entry.value_ptr.Overlay; }; // Display the scroll bar if the layout content is // larger than the parent dimension. if (overlay.layout.is_bigger_than_parent) { const space = 3; const width: f32 = 8; const height: f32 = 100; overlay.scroll = Rect.new( (overlay.body.x + overlay.body.w) - width - space, overlay.body.y + space, width, height, ); if (self.cursor.scroll_offset != 0) { const max_y = overlay.layout.cursor.y; const with_offset = overlay.body.y + self.cursor.scroll_offset; print("diff: {d}\n", .{(with_offset + overlay.body.h) - max_y}); overlay.body.y += self.cursor.scroll_offset; } } else { overlay.scroll = null; } // Used for parent Id on the select overlay type. const old_overlay = self.current_overlay; self.current_overlay = overlay_id; switch (overlay.options.overlay_type) { .Popup, .Panel => { if (self.find_zindex(overlay_id)) |z_index| { if (self.should_bring_to_front(overlay.bounds(), z_index)) { self.layer.bring_to_front = overlay_id; } if (overlay.closer) |closer| { if (self.bounds_state(closer, true).is_clicked) { _ = self.layer.orders.orderedRemove(z_index); overlay.is_closed = true; } } } }, .Select => { overlay.body = bounds; overlay.parent = old_overlay; if (!self.is_on_front()) overlay.is_closed = true; }, } const dx = self.cursor.delta_x; const dy = self.cursor.delta_y; if (overlay.header) |*header| { const is_draggable = overlay.options.draggable; overlay.is_dragging = false; if (is_draggable and self.dragging(header.*, self.gen_id())) { header.x += dx; header.y += dy; overlay.body.x += dx; overlay.body.y += dy; if (overlay.resizer) |*resizer| { resizer.x += dx; resizer.y += dy; } if (overlay.closer) |*closer| { closer.x += dx; closer.y += dy; } } } if (overlay.resizer) |*resizer| { const is_resizable = overlay.options.resizable; overlay.is_resizing = false; if (is_resizable and self.dragging(resizer.*, self.gen_id())) { overlay.is_resizing = true; overlay.body.w += dx; overlay.body.h += dy; resizer.x += dx; resizer.y += dy; if (overlay.header) |*header| header.w += dx; if (overlay.closer) |*closer| closer.x += dx; } } if (!self.is_hot) { const state = self.bounds_state(overlay.bounds(), false); self.is_hot = state.is_hover; } // Reset layout data after overlay was resized or dragged. overlay.layout = Layout.new( overlay.body.add_padding( layout_options.hori, layout_options.vert, ), self.min_height(), layout_options.space, ); return overlay; } /// New floating overlay. /// /// Created only once, thus data will be cached /// and retrieved every frame. pub fn panel( self: *Self, title: []const u8, x: f32, y: f32, w: f32, h: f32, ) bool { const bounds = Rect.new(x, y, w, h); const overlay = self._overlay(title, bounds, .{ .hori = 10, .vert = 15, .space = 5, }, .{ .has_header = true, .draggable = true, .resizable = true, .bordered = true, .closable = true, }) catch { @panic("Crashing while getting/creating Panel overlay."); }; if (!overlay.is_closed) { self.draw_overlay(overlay.*); return true; } return false; } pub fn option_label(self: *Self, text: []const u8, is_checked: bool) bool { var checked = is_checked; self.checkbox_label(text, &checked); return checked; } pub fn checkbox_label( self: *Self, text: []const u8, is_checked: *bool, ) void { const size = self.cfg.font_size + 3; var rect = self.current_layout().allocate_space(null); const outer = Rect.y_center(rect, size, size); const state = self.bounds_state(outer, true); const color = self.style.widget_color(state.status); if (state.is_clicked) is_checked.* = !is_checked.*; // Draw instructions. { self.drawer.push_borders(outer, 2, color.border_color); if (is_checked.*) { var inner = outer.xy_center(size - 6, size - 6); inner.color = color.base_color; self.drawer.push_rect(inner); } self.push_text( rect.add_padding(outer.w + 5, 0), text, .Left, color.text_color, ); } } pub fn padding_space(self: *Self, padding: f32) void { self.current_layout().cursor.y += padding; } pub fn alloc_incr_value( self: *Self, comptime T: type, value: *T, step: T, min: ?T, max: ?T, ) !void { const layout = self.current_layout(); const width = 70; var v = value.*; const rect = layout.allocate_space(null); var input = Rect.y_center(rect, width, rect.h); const add_btn = Rect.y_center( input.add_padding(width + 2, 0), rect.h, rect.h, ); const min_btn = Rect.y_center( add_btn.add_padding(add_btn.w + 2, 0), rect.h, rect.h, ); const allocator = self.cfg.allocator; const string = try fmt.allocPrint(allocator, "{d:.2}", .{value.*}); try self.string_storage.append(string); // Draw instructions. { const style = self.style; const color = if (self.is_on_front()) style.normal else style.disabled; self.drawer.push_rect(input); self.drawer.push_borders(input, 2, color.border_color); self.push_text(input, string, .Center, color.text_color); } if (self._raw_button("+", true, true, add_btn)) v += step; if (self._raw_button("-", true, true, min_btn)) v -= step; if (min) |m| v = math.max(m, v); if (max) |m| v = math.min(m, v); value.* = v; } pub fn send_scroll_offset(self: *Self, offset: f32) void { self.cursor.scroll_offset = offset; } pub fn send_cursor_position(self: *Self, x: f32, y: f32) void { const old_cursor = self.cursor; self.cursor.x = x; self.cursor.y = y; self.cursor.delta_x = x - old_cursor.x; self.cursor.delta_y = y - old_cursor.y; } pub fn send_input_key(self: *Self, key: Key, is_down: bool) !void { const entry = try self.key_status.getOrPutValue(key, KeyState{}); var key_state = entry.value_ptr; const old_state = key_state.*; key_state.was_down = is_down; key_state.is_down = !(old_state.was_down and is_down); key_state.is_repeat = old_state.was_down and is_down; key_state.is_up = old_state.was_down and !is_down; if (!is_down) { key_state.is_down = false; key_state.is_repeat = false; } } fn get_key(self: *const Self, key: Key) KeyState { const default = KeyState{}; return if (self.key_status.get(key)) |state| state else default; } pub fn send_ascii_string(self: *Self, string: []const u8) void { self.string_buffer.appendSlice(string) catch unreachable; } /// Send unicode character. pub fn send_codepoint(self: *Self, codepoint: u21) !void { var tmp = [_]u8{0} ** 64; var len = try unicode.utf8Encode(codepoint, &tmp); try self.string_buffer.appendSlice(tmp[0..len]); } pub fn graph(self: *Self, data: []const f32, max: f32) void { const layout = self.current_layout(); self.row_flex(100, 1); var row = layout.allocate_space(null); self.drawer.push_rect(row); const bounds = row.add_padding(10, 10); const count = @intToFloat(f32, data.len); const space = 1; const width = (bounds.w - space * count) * (1 / count); const height: f32 = bounds.h; const ref_max = height / max; var x = bounds.x; for (data) |d| { const min = max * 0.1; const value = math.clamp(d * ref_max, min, height); var bar = Rect.new(x, bounds.y, width, bounds.h); bar.h = value; bar.y += height - value; const state = self.bounds_state(bar, true); if (state.is_hover) { bar.color = self.style.hovered.border_color; } else { bar.color = self.style.normal.border_color; } self.drawer.push_rect(bar); x += width + space; } self.row_flex(0, 1); } /// Edit given value (up to f128). /// If the given value changed outside the input, /// we reflect the changement. pub fn edit_value( self: *Self, comptime T: type, value: *T, comptime _fmt: []const u8, ) !void { const info = @typeInfo(T); const input_id = @intCast(u64, self.gen_id()); const focus_id = self.gen_id(); var initialized = false; var is_valid = true; var is_focus = false; const rect = self.current_layout().allocate_space(null); const state = self.bounds_state(rect, true); var input = blk: { if (self.states.get(input_id)) |cached| { break :blk cached.Input; } else { initialized = true; // For now, we're using the arena allocator // because the input lifetime is equal to the UI. const allocator = self._arena.child_allocator; const buf = try allocator.alloc(u8, 128); break :blk Input{ .buf = buf, .val = undefined, .slice = try fmt.bufPrintZ(buf, _fmt, .{value.*}), }; } }; // If value changed outside the input. const has_changed = blk: { if (initialized or input.slice.len == 0) break :blk false; break :blk switch (info) { .Float => @floatCast(f128, value.*) != input.val, .Int => @intToFloat(f128, value.*) != input.val, else => false, }; }; if (has_changed) { input.slice = try fmt.bufPrintZ(input.buf, _fmt, .{value.*}); } const to_append = self.string_buffer.items; // Bring the current input to focus if nothing is focused. if (self.focus_item == null and state.is_clicked) { self.focus_item = focus_id; } switch (info) { .Float => { var has_decimal_point = false; for (input.slice) |c| { if (c == '.') has_decimal_point = true; } for (to_append) |c| { const isPoint = c == '.'; const two_deci_point = has_decimal_point and isPoint; const isNotDigit = !ascii.isDigit(c) and !isPoint; if (two_deci_point or isNotDigit) { is_valid = false; break; } if (c == '.') has_decimal_point = true; } }, .Int => { for (to_append) |c| { if (!ascii.isDigit(c)) { is_valid = false; break; } } }, else => { @panic("Value type not impl.\n"); }, } if (is_valid) { if (self.focus_item) |item_id| { is_focus = item_id == focus_id; const is_delete = self.get_key(.Bspc).is_down; if (is_focus) { if (to_append.len > 0 and !is_delete) { input.slice = try fmt.bufPrintZ(input.buf, "{s}{s}", .{ input.slice, to_append, }); } if (is_delete and input.slice.len > 0) { input.slice[input.slice.len - 1] = '\x00'; input.slice.len = input.slice.len - 1; } } if (is_focus and state.is_missed) { self.focus_item = null; } } if (input.slice.len > 0) { value.* = blk: { switch (info) { .Float => { const val = try fmt.parseFloat(T, input.slice); input.val = @floatCast(f128, val); break :blk val; }, .Int => { const val = try fmt.parseInt(T, input.slice, 0); input.val = @intToFloat(f128, val); break :blk val; }, else => {}, } }; } else { value.* = 0; } } // Draw instructions. { var color = if (self.is_on_front()) self.style.normal else self.style.disabled; var bounds = if (state.is_hover) rect.add_padding(-2, -2) else rect; if (is_focus) { bounds = rect.add_padding(-2, -2); color = self.style.hovered; } self.drawer.push_rect(bounds); self.drawer.push_borders(bounds, 2, color.border_color); self.push_text( bounds.add_padding(5, 0), input.slice, .Left, color.text_color, ); } self.states.put(input_id, .{ .Input = input }) catch unreachable; } pub fn edit_string(self: *Self, starter: []const u8) !?[]const u8 { const input_id = @intCast(u64, self.gen_id()); const id = self.gen_id(); var is_focus = false; const rect = self.current_layout().allocate_space(null); const state = self.bounds_state(rect, true); var input = blk: { if (self.states.get(input_id)) |cached| { break :blk cached.Input; } else { // For now, we're using the arena allocator // because the input lifetime is equal to the UI. const allocator = self._arena.child_allocator; const buf = try allocator.alloc(u8, 512); break :blk Input{ .buf = buf, .val = undefined, .slice = try fmt.bufPrintZ(buf, "{s}", .{starter}), }; } }; // Bring the current input to focus if nothing is focused. if (self.focus_item == null and state.is_clicked) { self.focus_item = id; } var str: ?[]const u8 = null; const to_append = self.string_buffer.items; if (self.focus_item) |item_id| { is_focus = item_id == id; const is_delete = self.get_key(.Bspc).is_down; if (is_focus) { if (to_append.len > 0 and !is_delete) { input.slice = try fmt.bufPrintZ(input.buf, "{s}{s}", .{ input.slice, to_append, }); } if (is_delete and input.slice.len > 0) { input.slice[input.slice.len - 1] = '\x00'; input.slice.len = input.slice.len - 1; } if (to_append.len > 0 or is_delete) str = input.slice; } if (is_focus and state.is_missed) { self.focus_item = null; } } // Draw instructions. { var color = if (self.is_on_front()) self.style.normal else self.style.disabled; var bounds = if (state.is_hover) rect.add_padding(-2, -2) else rect; if (is_focus) { bounds = rect.add_padding(-2, -2); color = self.style.hovered; } self.drawer.push_rect(bounds); self.drawer.push_borders(bounds, 2, color.border_color); self.push_text( bounds.add_padding(5, 0), input.slice, .Left, color.text_color, ); } self.states.put(input_id, .{ .Input = input }) catch unreachable; return str; } pub fn label_alloc( self: *Self, comptime text: []const u8, args: anytype, aligment: TextAlignment, ) !void { const allocator = self.cfg.allocator; const string = try fmt.allocPrint(allocator, text, args); try self.string_storage.append(string); self.label(string, aligment); } pub fn label( self: *Self, text: []const u8, aligment: TextAlignment, ) void { const layout = self.current_layout(); const min_width = self.get_text_size(text); const rect = layout.allocate_space(min_width); const color = if (self.is_on_front()) self.style.normal.text_color else self.style.disabled.text_color; self.push_text(rect, text, aligment, color); } /// Get current overlay. /// TODO: Rename this function... fn get_current(self: *const Self) *Overlay { const entry = self.states.getEntry(self.current_overlay); return &entry.?.value_ptr.Overlay; } fn current_layout(self: *const Self) *Layout { const overlay = self.get_current(); return &overlay.layout; } pub fn popup_begin(self: *Self, title: []const u8) bool { const padding = 10; return self.panel( title, self.cursor.x + padding, self.cursor.y + padding, 300, 500, ); } pub fn select( self: *Self, items: [][]const u8, selected: anytype, ) @TypeOf(selected) { const T = @TypeOf(selected); var currently_selected = selected; var old_current = self.current_overlay; var input_bounds = self.current_layout().allocate_space(null); const state = self.bounds_state(input_bounds, true); // Draw instructions for selected input box. { var color = if (state.status != .Disabled) self.style.normal else self.style.disabled; self.drawer.push_rect(input_bounds); self.drawer.push_borders(input_bounds, 2, color.border_color); self.push_text( input_bounds.add_padding(5, 0), items[selected], .Left, color.text_color, ); } const options_height = @intToFloat(f32, items.len) * input_bounds.h; const overlay = self._overlay( "select_id", Rect.new( input_bounds.x, input_bounds.y + input_bounds.h, input_bounds.w, options_height, ), .{ .hori = 0, .vert = 0, .space = 0 }, .{ .overlay_type = .Select, .closed = true, .bordered = true }, ) catch { @panic("Crash while creating/getting new overlay.\n"); }; if (!overlay.is_closed) { self.draw_overlay(overlay.*); for (items) |item_label, index| { if (self._raw_button(item_label, false, false, null)) { currently_selected = @intCast(T, index); overlay.is_closed = true; self.layer.bring_to_front = old_current; } } self.drawer.push_borders(overlay.bounds(), 2, self.style.normal.border_color); } if (state.is_clicked) { overlay.is_closed = !overlay.is_closed; if (!overlay.is_closed) self.layer.bring_to_front = overlay.id; } self.current_overlay = old_current; self.drawer.set_cmd_id(old_current); return currently_selected; } pub fn tree_begin( self: *Self, title: []const u8, expanded: bool, mode: enum { Collapser, Tree }, ) bool { self.row_flex(20, 1); const layout = self.current_layout(); const current_win = self.get_current(); const tree_id = blk: { var hash = Wyhash.init(@intCast(u64, self.gen_id())); hash.update(current_win.title); hash.update(title); break :blk hash.final(); }; var tree = if (self.states.get(tree_id)) |cached| cached.Tree else Tree{ .is_expanded = expanded }; var rect = layout.allocate_space(null); const state = self.bounds_state(rect, true); const color = self.style.widget_color(state.status); if (state.is_clicked) tree.is_expanded = !tree.is_expanded; if (tree.is_expanded) layout.indent += self.style.indent; // Draw instructions. { rect.color = color.base_color; const size = self.cfg.font_size - 5; const icon_bounds = rect.add_padding(self.style.indent, 0); var icon = icon_bounds.y_center(size, size); switch (mode) { .Collapser => { self.drawer.push_rect(rect); self.drawer.push_borders(rect, 1, color.border_color); self.drawer.push_triangle( icon, size, color.border_color, if (tree.is_expanded) .Down else .Right, ); self.push_text(rect, title, .Center, color.text_color); }, .Tree => { self.drawer.push_triangle( icon, size, color.border_color, if (tree.is_expanded) .Down else .Right, ); const region = rect.add_padding(35, 0); self.push_text(region, title, .Left, color.text_color); }, } } self.states.put(tree_id, .{ .Tree = tree }) catch unreachable; return tree.is_expanded; } pub fn tree_end(self: *Self) void { self.current_layout().indent -= self.style.indent; self.padding_space(10); self.row_flex(0, 1); } /// TODO: Should review... pub fn slider(self: *Self, min: f32, max: f32, value: f32, step: f32) f32 { var bounds = self.current_layout().allocate_space(null); const cursor_h = bounds.h - 5; const cursor_w = cursor_h * 0.5; const range = max - min; var slider_value = math.clamp(value, min, max); const slider_steps = range / step; const offset = (slider_value - min) / step; var logical_cursor: Rect = undefined; var visual_cursor: Rect = undefined; visual_cursor.color = self.style.normal.border_color; logical_cursor.h = bounds.h; logical_cursor.w = bounds.w / slider_steps; logical_cursor.x = bounds.x + (logical_cursor.w * offset); logical_cursor.y = bounds.y; visual_cursor.h = cursor_h; visual_cursor.w = cursor_w; visual_cursor.y = (bounds.y + bounds.h * 0.5) - visual_cursor.h * 0.5; visual_cursor.x = logical_cursor.x - visual_cursor.w * 0.5; const cursor_state = self.bounds_state(visual_cursor, true); const cursor_color = self.style.widget_color(cursor_state.status); var border_color = cursor_color.border_color; bounds.color = cursor_color.base_color; visual_cursor.color = cursor_color.text_color; if (self.dragging(visual_cursor, self.gen_id())) { var ratio: f32 = 0; const d = self.cursor.x - (visual_cursor.x + visual_cursor.w * 0.5); const pxstep = bounds.w / slider_steps; if (math.fabs(d) >= pxstep) { const steps = @divTrunc(math.fabs(d), pxstep); slider_value += if (d > 0) step * steps else -(step * steps); slider_value = math.clamp(slider_value, min, max); ratio = (slider_value - min) / step; logical_cursor.x = bounds.x + (logical_cursor.w * ratio); } bounds.color = self.style.pressed.base_color; visual_cursor.color = self.style.pressed.text_color; border_color = self.style.pressed.border_color; } visual_cursor.x = logical_cursor.x - visual_cursor.w * 0.5; // Draw instructions. { self.drawer.push_rect(bounds); self.drawer.push_borders(bounds, 2, border_color); self.drawer.push_rect(visual_cursor); } return slider_value; } pub fn button(self: *Self, text: []const u8) bool { return self._raw_button(text, true, true, null); } fn _raw_button( self: *Self, text: []const u8, bordered: bool, text_centered: bool, region: ?Rect, ) bool { const layout = self.current_layout(); var rect = if (region) |reg| reg else layout.allocate_space(null); const state = self.bounds_state(rect, true); const color = self.style.widget_color(state.status); // Draw instructions. { rect.color = color.base_color; self.drawer.push_rect(rect); if (bordered) self.drawer.push_borders(rect, 2, color.border_color); self.push_text( rect.add_padding(5, 0), text, if (text_centered) .Center else .Left, color.text_color, ); } return state.is_clicked; } pub fn row_static( self: *Self, width: f32, height: f32, items: i32, ) void { assert(items > 0); const layout = self.current_layout(); layout.reset(); layout.column_threshold = items; layout.row_mode = .{ .RowFixed = width }; layout.height = math.max(self.min_height(), height); } pub fn row_array_static( self: *Self, item_widths: []const f32, height: f32, ) void { assert(item_widths.len > 0); const layout = self.current_layout(); layout.reset(); layout.column_threshold = @intCast(i32, item_widths.len); layout.row_mode = .{ .RowFixedArray = item_widths }; layout.height = math.max(self.min_height(), height); } /// Create new flex row. pub fn row_flex(self: *Self, height: f32, threshold: i32) void { assert(threshold > 0); const layout = self.current_layout(); layout.reset(); layout.column_threshold = threshold; layout.row_mode = .{ .RowFlex = {} }; layout.height = math.max(self.min_height(), height); } // Push Text to the draw list. fn push_text( self: *Self, r: Rect, text: []const u8, alignment: TextAlignment, color: Color, ) void { const half_size = self.cfg.font_size / (2 + 2); var x = r.x; var y = r.y + (r.h / 2) + half_size; if (alignment == .Center) { const text_width = self.get_text_size(text); x = r.x + (r.w / 2) - (text_width / 2); } if (alignment == .Right) { const text_width = self.get_text_size(text); x = math.max(x, r.x + r.w - text_width); } self.drawer.push_text(.{ .x = x, .y = y, .color = color, .content = text, }); } /// Bring to front the registered overlay. fn sort_layers(self: *Self) void { if (self.layer.bring_to_front) |focus_id| { for (self.layer.orders.items) |id, index| { if (id == focus_id) { _ = self.layer.orders.orderedRemove(index); } } self.layer.orders.append(focus_id) catch unreachable; } } pub fn process_ui(self: *Self) DrawerData { self.sort_layers(); return self.drawer.process_ui(self.layer.orders.items); } pub fn draw(self: *Self) []DrawSlice { return self.drawer.draw_list.items; } fn gen_id(self: *Self) i32 { const current_id = self.last_id; self.last_id += 1; return current_id; } fn dragging(self: *Self, region: Rect, id: i32) bool { const cursor = self.get_key(.Cursor); const is_hover = self.cursor_vs_rect(region); if (self.dragging_id) |dragger_id| { if (dragger_id == id) { if (!cursor.is_repeat) { self.dragging_id = null; } return true; } } else { if (cursor.is_repeat and is_hover and self.is_on_front()) { self.dragging_id = id; } } return false; } /// Z index is simply the position in the layer orders stack. /// It should always find it. fn find_zindex(self: *Self, id_to_find: Id) ?usize { for (self.layer.orders.items) |id, zindex| { if (id == id_to_find) return zindex; } return null; } /// Try to bring an overlay to front. fn should_bring_to_front(self: *Self, bounds: Rect, z_index: usize) bool { const state = self.bounds_state(bounds, false); if (!state.is_clicked or self.is_on_front()) { return false; } // At this point, we know two things: // - Current overlay isn't already on top of the orders stack. // - Mouse is pressed and hovered the overlay region. var activate = true; // Now, we iterate over all overlay that are in front // of the current one in order to check if the "clicked" // part was visible. for (self.layer.orders.items[z_index + 1 ..]) |id| { if (self.states.get(id)) |entry| { switch (entry) { .Overlay => |win| { const intersection_region = Rect.intersect(bounds, win.bounds()); if (self.cursor_vs_rect(intersection_region)) { activate = false; break; } }, else => {}, } } } return activate; } /// Return if the given bounds is clicked, hovered, pressed. /// If the current overlay isn't hovered, return the default state. /// TODO: Rename to `get_bounds_state`? fn bounds_state(self: *const Self, rect: Rect, check_focus: bool) BoundState { if ((check_focus and !self.is_on_front()) or self.disabled) { return BoundState{}; } const cursor = self.get_key(.Cursor); const is_hover = self.cursor_vs_rect(rect); const is_clicked = is_hover and cursor.is_down; const is_pressed = is_hover and cursor.is_repeat; const is_missed = cursor.is_down and !is_hover; const status: Status = blk: { if ((is_pressed or is_clicked) and is_hover) { break :blk .Pressed; } else if (is_hover) { break :blk .Hovered; } break :blk .Normal; }; return .{ .is_hover = is_hover, .is_clicked = is_clicked, .is_pressed = is_pressed, .is_missed = is_missed, .status = status, }; } /// Return if the current overlay is the active one. fn is_on_front(self: *const Self) bool { const orders = &self.layer.orders; const len = orders.items.len; if (len == 0) return false; return orders.items[len - 1] == self.current_overlay; } /// Default height equal to the font size + text_padding. fn min_height(self: *const Self) f32 { return self.cfg.font_size + self.style.text_padding; } fn cursor_vs_rect(self: *const Self, rect: Rect) bool { return point_vs_rect(rect, self.cursor.x, self.cursor.y); } fn get_text_size(self: *const Self, text: []const u8) f32 { return self.cfg.calc_text_size( self.cfg.font, self.cfg.font_size, text, ); } fn point_vs_rect(rect: Rect, x: f32, y: f32) bool { return x >= rect.x and x <= (rect.x + rect.w) and y >= rect.y and y <= (rect.y + rect.h); } fn draw_overlay(self: *Self, win: Overlay) void { const color = if (self.is_on_front()) self.style.normal else self.style.disabled; const bounds = win.bounds(); var mut_win = win; mut_win.body.color = self.style.background_color; self.drawer.push_clip(bounds.x, bounds.y, bounds.w, bounds.h); if (mut_win.header) |*header| { header.color = color.base_color; self.drawer.push_rect(header.*); self.push_text(header.*, win.title, .Center, color.text_color); } self.drawer.push_rect(mut_win.body); if (win.options.bordered) { self.drawer.push_borders(bounds, 1, color.border_color); } if (mut_win.closer) |*closer| { closer.color = color.base_color; self.drawer.push_rect(closer.*); self.push_text(closer.*, "-", .Center, color.text_color); } if (mut_win.resizer) |*resizer| { const size = self.cfg.font_size - 5; self.drawer.push_triangle(resizer.*, size, color.text_color, .DiagRight); } if (mut_win.scroll) |*scroll| { scroll.color = color.base_color; self.drawer.push_rect(scroll.*); } } /// Shrink allocated memory used in the last frame. pub fn reset(self: *Self) void { self.last_id = 0; self.is_hot = false; self.layer.bring_to_front = null; self.string_buffer.shrinkAndFree(0); self.drawer.reset(); defer self.string_storage.shrinkAndFree(0); for (self.string_storage.items) |ptr| { self.cfg.allocator.free(ptr); } } pub fn deinit(self: *Self) void { const allocator = self._arena.child_allocator; self._arena.deinit(); allocator.destroy(self._arena); } }; } const TestFont = struct {}; fn calc_text_size(_: *TestFont, _: f32, _: []const u8) f32 { return 150; } test "interface.init" { var test_font = TestFont{}; var ui = try Interface(TestFont).init(.{ .allocator = test_allocator, .font = test_font, .font_size = 16, .calc_text_size = calc_text_size, }, .{}); defer ui.deinit(); }
src/ui.zig
pub const bmp = @import("bmp.zig"); pub const png = @import("png.zig"); const std = @import("std"); const Allocator = std.mem.Allocator; pub const ColorChannel = enum { Red, Green, Blue, Alpha }; //// A pixel format. Note that it only represents the sRGB color space. pub const ImageFormat = struct { /// Bit mask for the red color channel. /// Example: 0xFF000000 for RGBA. redMask: u32, /// Bit mask for the green color channel. /// Example: 0x00FF0000 for RGBA. greenMask: u32, /// Bit mask for the blue color channel. /// Example: 0x0000FF00 for RGBA. blueMask: u32, /// Bit mask for the alpha transparency channel. /// Example: 0x000000FF for RGBA. alphaMask: u32 = 0, /// The size, in bits, of one pixel. bitsSize: u8, /// 8-bit red, green and blue samples in that order. pub const RGB24 = ImageFormat {.redMask=0xFF0000, .greenMask=0x00FF00, .blueMask=0x0000FF, .bitsSize=24}; /// 8-bit blue, green and red samples in that order. pub const BGR24 = ImageFormat {.redMask=0x0000FF, .greenMask=0x00FF00, .blueMask=0xFF0000, .bitsSize=24}; /// 8-bit red, green, blue and alpha samples in that order. pub const RGBA32 = ImageFormat{.redMask=0xFF000000,.greenMask=0x00FF0000,.blueMask=0x0000FF00,.alphaMask=0x000000FF,.bitsSize=32}; /// 8-bit gray sample. pub const GRAY8 = ImageFormat {.redMask=0xFF, .greenMask=0xFF, .blueMask=0xFF, .bitsSize=8}; /// Get the bit size of the image format. pub fn getBitSize(self: *ImageFormat) u8 { return self.bitsSize; } /// Get the bit mask of the specified color channel. pub fn getBitMask(self: *ImageFormat, channel: ColorChannel) u32 { return switch (channel) { .Red => self.redMask, .Green => self.greenMask, .Blue => self.blueMask, .Alpha => self.alphaMask }; } pub const ShiftError = error { /// If the mask of the color channel is 0, /// no shift can be found and this error is returned. NullMask }; /// Returns how many bits must be shifted to the right in order to get the specified color channel value. /// Example: for ColorChannel.Red, this functions returns 24 if the image format is RGBA as you must /// shift a pixel 24 bits to the right to get the red color. pub fn getShift(self: *ImageFormat, channel: ColorChannel) ShiftError!u5 { // Example: // The mask of the red color is 0b111000 // We shift right one time and get 0b011100, last bit is 0 so continue // We shift right another time and get 0b001110, last bit is also 0 so continue // We shift right a 3rd time and get 0b000111, the last bit is 1 and our shift is correct. // So we now know that a color value has to be shifted 3 times to get the red color. const mask = self.getBitMask(channel); var shift: u8 = 0; while (shift < self.bitsSize) : (shift += 1) { const num = mask >> @intCast(u5, shift); if ((num & 1) == 1) { // if we hit the first 1 bit of the mask return @intCast(u5, shift); } } return ShiftError.NullMask; } /// Using this image format, get the value corresponding to the color channel from a pixel. /// Example: Assuming RGBA image format and a pixel with value 0x11223344, if we use this function /// with the Red color channel, it will return 0x11. pub fn getValue(self: *ImageFormat, channel: ColorChannel, value: u32) !u32 { const mask = self.getBitMask(channel); const shift = try self.getShift(channel); return (value & mask) >> shift; } }; pub const Image = struct { allocator: ?*Allocator = null, /// The image data, in linear 8-bit RGB format. data: []u8, /// The width of the image in pixels. width: usize, /// The height of the image in pixels. height: usize, /// The pixel format of the image. format: ImageFormat, pub fn deinit(self: *const Image) void { if (self.allocator) |allocator| { allocator.free(self.data); } } }; comptime { @import("std").testing.refAllDecls(bmp); @import("std").testing.refAllDecls(png); @import("std").testing.refAllDecls(Image); @import("std").testing.refAllDecls(ImageFormat); }
didot-image/image.zig
const std = @import("std"); const Allocator = std.mem.Allocator; const vk = @import("../include/vk.zig"); const glfw = @import("../include/glfw.zig"); const windowing = @import("../windowing.zig"); const BackendError = @import("backend.zig").BackendError; const Context = @import("context.zig").Context; pub const Swapchain = struct { const Image = struct { context: *const Context, image: vk.Image, view: vk.ImageView, fn init(context: *const Context, image: vk.Image, format: vk.Format) !Image { const view = try context.vkd.createImageView(context.device, .{ .image = image, .view_type = .@"2d", .format = format, .components = vk.ComponentMapping{ .r = .identity, .g = .identity, .b = .identity, .a = .identity, }, .subresource_range = vk.ImageSubresourceRange{ .aspect_mask = vk.ImageAspectFlags{ .color_bit = true }, .base_mip_level = 0, .level_count = 1, .base_array_layer = 0, .layer_count = 1, }, .flags = .{}, }, null); errdefer context.vkd.destroyImageView(context.device, view, null); return Image{ .context = context, .image = image, .view = view, }; } fn deinit(self: Image) void { self.context.vkd.destroyImageView(self.context.device, self.view, null); } }; const Self = @This(); allocator: *Allocator, swapchain: vk.SwapchainKHR, context: *const Context, window: *windowing.Window, images: []Image, present_mode: vk.PresentModeKHR, image_format: vk.Format, extent: vk.Extent2D, pub fn new() Self { return Self{ .allocator = undefined, .swapchain = undefined, .context = undefined, .window = undefined, .images = undefined, .present_mode = undefined, .image_format = undefined, .extent = undefined, }; } pub fn init(self: *Self, allocator: *Allocator, context: *const Context, window: *windowing.Window) !void { self.allocator = allocator; self.context = context; self.window = window; try self.createSwapchain(.null_handle); try self.createImages(); } pub fn recreate(self: *Self) !void { self.deinitNoSwapchain(); try self.createSwapchain(self.swapchain); try self.createImages(); } fn deinitNoSwapchain(self: *Self) void { for (self.images) |image| image.deinit(); self.allocator.free(self.images); } pub fn deinit(self: *Self) void { self.deinitNoSwapchain(); self.context.vkd.destroySwapchainKHR(self.context.device, self.swapchain, null); } pub fn acquireNextImage(self: *Self, semaphore: vk.Semaphore, imageIndex: *u32) !bool { if (self.context.vkd.acquireNextImageKHR(self.context.device, self.swapchain, std.math.maxInt(u64), semaphore, .null_handle)) |result| { imageIndex.* = result.image_index; return false; } else |err| switch (err) { error.OutOfDateKHR => return true, else => return BackendError.AcquireImageFailed, } } pub fn present(self: *Self, semaphore: vk.Semaphore, imageIndex: u32) !bool { const presentInfo = vk.PresentInfoKHR{ .wait_semaphore_count = 1, .p_wait_semaphores = @ptrCast([*]const vk.Semaphore, &semaphore), .swapchain_count = 1, .p_swapchains = @ptrCast([*]const vk.SwapchainKHR, &self.swapchain), .p_image_indices = @ptrCast([*]const u32, &imageIndex), .p_results = null, }; if (self.context.vkd.queuePresentKHR(self.context.present_queue, presentInfo)) |result| { switch (result) { .suboptimal_khr => return true, else => return false, } } else |err| switch (err) { error.OutOfDateKHR => return true, else => return BackendError.PresentFailed, } } fn createSwapchain(self: *Self, old: vk.SwapchainKHR) !void { const surfaceFormat = try self.chooseSurfaceFormat(); const presentMode = try self.choosePresentMode(); const extent = try self.findActualExtent(); const capabilities = try self.context.vki.getPhysicalDeviceSurfaceCapabilitiesKHR(self.context.physical_device, self.context.surface); var imageCount: u32 = capabilities.min_image_count + 1; if (capabilities.max_image_count > 0) imageCount = std.math.min(imageCount, capabilities.max_image_count); const indices = self.context.indices; const queueFamilyIndices = [_]u32{ indices.graphics_family.?, indices.present_family.? }; const differentFamilies = indices.graphics_family.? != indices.present_family.?; var createInfo = vk.SwapchainCreateInfoKHR{ .surface = self.context.surface, .min_image_count = imageCount, .image_format = surfaceFormat.format, .image_color_space = surfaceFormat.color_space, .image_extent = extent, .image_array_layers = 1, .image_usage = vk.ImageUsageFlags{ .color_attachment_bit = true }, .image_sharing_mode = if (differentFamilies) .concurrent else .exclusive, .queue_family_index_count = if (differentFamilies) 2 else 0, .p_queue_family_indices = if (differentFamilies) &queueFamilyIndices else undefined, .pre_transform = capabilities.current_transform, .composite_alpha = vk.CompositeAlphaFlagsKHR{ .opaque_bit_khr = true }, .present_mode = presentMode, .clipped = vk.TRUE, .flags = .{}, .old_swapchain = old, }; self.swapchain = try self.context.vkd.createSwapchainKHR(self.context.device, createInfo, null); if (old != .null_handle) self.context.vkd.destroySwapchainKHR(self.context.device, old, null); self.present_mode = presentMode; self.image_format = surfaceFormat.format; self.extent = extent; } fn createImages(self: *Self) !void { var count: u32 = 0; _ = try self.context.vkd.getSwapchainImagesKHR(self.context.device, self.swapchain, &count, null); var vkImages = try self.allocator.alloc(vk.Image, count); defer self.allocator.free(vkImages); _ = try self.context.vkd.getSwapchainImagesKHR(self.context.device, self.swapchain, &count, vkImages.ptr); self.images = try self.allocator.alloc(Image, count); errdefer self.allocator.free(self.images); var i: usize = 0; errdefer for (self.images[0..i]) |image| image.deinit(); for (vkImages) |vkImage| { self.images[i] = try Image.init(self.context, vkImage, self.image_format); i += 1; } } fn chooseSurfaceFormat(self: *Self) !vk.SurfaceFormatKHR { const preferred = [_]vk.SurfaceFormatKHR{.{ .format = .b8g8r8a8_srgb, .color_space = .srgb_nonlinear_khr, }}; var count: u32 = 0; _ = try self.context.vki.getPhysicalDeviceSurfaceFormatsKHR(self.context.physical_device, self.context.surface, &count, null); var availableFormats = try self.allocator.alloc(vk.SurfaceFormatKHR, count); defer self.allocator.free(availableFormats); _ = try self.context.vki.getPhysicalDeviceSurfaceFormatsKHR(self.context.physical_device, self.context.surface, &count, availableFormats.ptr); for (preferred) |format| for (availableFormats) |availableFormat| if (std.meta.eql(format, availableFormat)) return format; return availableFormats[0]; } fn choosePresentMode(self: *Self) !vk.PresentModeKHR { const preferred = [_]vk.PresentModeKHR{ .mailbox_khr, .immediate_khr, }; var count: u32 = 0; _ = try self.context.vki.getPhysicalDeviceSurfacePresentModesKHR(self.context.physical_device, self.context.surface, &count, null); var availablePresentModes = try self.allocator.alloc(vk.PresentModeKHR, count); defer self.allocator.free(availablePresentModes); _ = try self.context.vki.getPhysicalDeviceSurfacePresentModesKHR(self.context.physical_device, self.context.surface, &count, availablePresentModes.ptr); for (preferred) |mode| if (std.mem.indexOfScalar(vk.PresentModeKHR, availablePresentModes, mode) != null) return mode; return .fifo_khr; } fn findActualExtent(self: *Self) !vk.Extent2D { const capabilities = try self.context.vki.getPhysicalDeviceSurfaceCapabilitiesKHR(self.context.physical_device, self.context.surface); if (capabilities.current_extent.width != std.math.maxInt(u32)) { return vk.Extent2D{ .width = capabilities.current_extent.width, .height = capabilities.current_extent.height }; } else { var width: c_int = 0; var height: c_int = 0; glfw.glfwGetFramebufferSize(self.window.window, &width, &height); var actualExtent = vk.Extent2D{ .width = @intCast(u32, width), .height = @intCast(u32, height), }; actualExtent.width = @intCast(u32, std.math.max(capabilities.min_image_extent.width, std.math.min(capabilities.max_image_extent.width, actualExtent.width))); actualExtent.height = @intCast(u32, std.math.max(capabilities.min_image_extent.height, std.math.min(capabilities.max_image_extent.height, actualExtent.height))); return actualExtent; } } };
render/src/backend/swapchain.zig
const std = @import("std"); const builtin = @import("builtin"); const VM = @import("./vm.zig").VM; const _value = @import("./value.zig"); const _obj = @import("./obj.zig"); const dumpStack = @import("./disassembler.zig").dumpStack; const Config = @import("./config.zig").Config; const Value = _value.Value; const valueToString = _value.valueToString; const Obj = _obj.Obj; const ObjString = _obj.ObjString; const ObjTypeDef = _obj.ObjTypeDef; const ObjUpValue = _obj.ObjUpValue; const ObjClosure = _obj.ObjClosure; const ObjFunction = _obj.ObjFunction; const ObjObjectInstance = _obj.ObjObjectInstance; const ObjObject = _obj.ObjObject; const ObjList = _obj.ObjList; const ObjMap = _obj.ObjMap; const ObjEnum = _obj.ObjEnum; const ObjEnumInstance = _obj.ObjEnumInstance; const ObjBoundMethod = _obj.ObjBoundMethod; const ObjNative = _obj.ObjNative; const ObjUserData = _obj.ObjUserData; pub fn allocate(vm: *VM, comptime T: type) !*T { vm.bytes_allocated += @sizeOf(T); if (vm.bytes_allocated > vm.next_gc) { try collectGarbage(vm); } return try vm.allocator.create(T); } pub fn allocateMany(vm: *VM, comptime T: type, count: usize) ![]T { vm.bytes_allocated += @sizeOf(T); if (vm.bytes_allocated > vm.next_gc) { try collectGarbage(vm); } return try vm.allocator.alloc(T, count); } pub fn free(vm: *VM, comptime T: type, pointer: *T) void { vm.bytes_allocated -= @sizeOf(T); vm.allocator.destroy(pointer); if (Config.debug_gc) { std.debug.print("(from {}), freed {}, {} allocated\n", .{ vm.bytes_allocated + @sizeOf(T), @sizeOf(T), vm.bytes_allocated }); } } pub fn freeMany(vm: *VM, comptime T: type, pointer: []const T) void { const n: usize = (@sizeOf(T) * pointer.len); vm.bytes_allocated -= n; vm.allocator.free(pointer); if (Config.debug_gc) { std.debug.print("(from {}), freed {}, {} allocated\n", .{ vm.bytes_allocated + n, n, vm.bytes_allocated }); } } pub fn markObj(vm: *VM, obj: *Obj) !void { if (obj.is_marked) { if (Config.debug_gc) { std.debug.print("{*} already marked\n", .{obj}); } return; } if (Config.debug_gc) { std.debug.print("marking {*}: {s}\n", .{ obj, try valueToString(vm.allocator, Value{ .Obj = obj }) }); } obj.is_marked = true; try vm.gray_stack.append(obj); } fn blackenObject(vm: *VM, obj: *Obj) !void { _ = try switch (obj.obj_type) { .String => ObjString.cast(obj).?.mark(vm), .Type => ObjTypeDef.cast(obj).?.mark(vm), .UpValue => ObjUpValue.cast(obj).?.mark(vm), .Closure => ObjClosure.cast(obj).?.mark(vm), .Function => ObjFunction.cast(obj).?.mark(vm), .ObjectInstance => ObjObjectInstance.cast(obj).?.mark(vm), .Object => ObjObject.cast(obj).?.mark(vm), .List => ObjList.cast(obj).?.mark(vm), .Map => ObjMap.cast(obj).?.mark(vm), .Enum => ObjEnum.cast(obj).?.mark(vm), .EnumInstance => ObjEnumInstance.cast(obj).?.mark(vm), .Bound => ObjBoundMethod.cast(obj).?.mark(vm), .Native => ObjNative.cast(obj).?.mark(vm), .UserData => ObjUserData.cast(obj).?.mark(vm), }; } fn freeObj(vm: *VM, obj: *Obj) void { if (Config.debug_gc) { std.debug.print("freeing {*}: {}\n", .{ obj, obj.obj_type }); } switch (obj.obj_type) { .String => { var obj_string = ObjString.cast(obj).?; freeMany(vm, u8, obj_string.string); free(vm, ObjString, obj_string); }, .Type => { var obj_typedef = ObjTypeDef.cast(obj).?; obj_typedef.deinit(); free(vm, ObjTypeDef, obj_typedef); }, .UpValue => free(vm, ObjUpValue, ObjUpValue.cast(obj).?), .Closure => { var obj_closure = ObjClosure.cast(obj).?; obj_closure.deinit(); free(vm, ObjClosure, obj_closure); }, .Function => { var obj_function = ObjFunction.cast(obj).?; obj_function.deinit(); free(vm, ObjFunction, obj_function); }, .ObjectInstance => { var obj_objectinstance = ObjObjectInstance.cast(obj).?; obj_objectinstance.deinit(); free(vm, ObjObjectInstance, obj_objectinstance); }, .Object => { var obj_object = ObjObject.cast(obj).?; obj_object.deinit(); free(vm, ObjObject, obj_object); }, .List => { var obj_list = ObjList.cast(obj).?; obj_list.deinit(); free(vm, ObjList, obj_list); }, .Map => { var obj_map = ObjMap.cast(obj).?; obj_map.deinit(); free(vm, ObjMap, obj_map); }, .Enum => { var obj_enum = ObjEnum.cast(obj).?; obj_enum.deinit(); free(vm, ObjEnum, obj_enum); }, .EnumInstance => free(vm, ObjEnumInstance, ObjEnumInstance.cast(obj).?), .Bound => free(vm, ObjBoundMethod, ObjBoundMethod.cast(obj).?), .Native => free(vm, ObjNative, ObjNative.cast(obj).?), .UserData => free(vm, ObjUserData, ObjUserData.cast(obj).?), } } pub fn markValue(vm: *VM, value: Value) !void { if (value == .Obj) { try markObj(vm, value.Obj); } } fn markRoots(vm: *VM) !void { // Mark stack values var i = @ptrCast([*]Value, vm.stack); while (@ptrToInt(i) < @ptrToInt(vm.stack_top)) : (i += 1) { try markValue(vm, i[0]); } // Mark closure for (vm.frames.items) |frame| { try markObj(vm, frame.closure.toObj()); } // Mark opened upvalues if (vm.open_upvalues) |open_upvalues| { var upvalue: ?*ObjUpValue = open_upvalues; while (upvalue) |unwrapped| : (upvalue = unwrapped.next) { try markObj(vm, unwrapped.toObj()); } } // Mark globals for (vm.globals.items) |global| { try markValue(vm, global); } } fn traceReference(vm: *VM) !void { while (vm.gray_stack.items.len > 0) { try blackenObject(vm, vm.gray_stack.pop()); } } fn sweep(vm: *VM) void { var swept: usize = vm.bytes_allocated; var previous: ?*Obj = null; var obj: ?*Obj = vm.objects; while (obj) |uobj| { if (uobj.is_marked) { uobj.is_marked = false; previous = uobj; obj = uobj.next; } else { var unreached: *Obj = uobj; obj = uobj.next; if (previous) |uprevious| { uprevious.next = obj; } else { vm.objects = obj; } freeObj(vm, unreached); } } if (Config.debug_gc) { std.debug.print("Swept {} bytes, now {} bytes, remaining are:\n", .{ swept - vm.bytes_allocated, vm.bytes_allocated }); obj = vm.objects; while (obj) |uobj| { std.debug.print("\t{*}: {s}\n", .{ uobj, uobj }); obj = uobj.next; } } } pub fn collectGarbage(vm: *VM) !void { if (Config.debug_gc) { std.debug.print("-- gc starts\n", .{}); try dumpStack(vm); } try markRoots(vm); try traceReference(vm); var it = vm.strings.iterator(); while (it.next()) |kv| { try markObj(vm, kv.value_ptr.*.toObj()); } sweep(vm); vm.next_gc = vm.bytes_allocated * 2; if (Config.debug_gc) { std.debug.print("-- gc end\n", .{}); } }
src/memory.zig
//Zglfw //Mit License // //Copyright (C) 2020 Iridescence Technologies // //Permission Is Hereby Granted, Free Of Charge, To Any Person Obtaining A Copy //Of This Software And Associated Documentation Files (The "Software"), To Deal //In The Software Without Restriction, Including Without Limitation The Rights //To Use, Copy, Modify, Merge, Publish, Distribute, Sublicense, And/Or Sell //Copies Of The Software, And To Permit Persons To Whom The Software Is //Furnished To Do So, Subject To The Following Conditions: // //The Above Copyright Notice And This Permission Notice Shall Be Included In All //Copies Or Substantial Portions Of The Software. // //The Software Is Provided "As Is", Without Warranty Of Any Kind, Express Or //Implied, Including But Not Limited To The Warranties Of Merchantability, //Fitness For A Particular Purpose And Noninfringement. In No Event Shall The //Authors Or Copyright Holders Be Liable For Any Claim, Damages Or Other //Liability, Whether In An Action Of Contract, Tort Or Otherwise, Arising From, //Out Of Or In Connection With The Software Or The Use Or Other Dealings In The //Software. // //Glfw //Copyright (C) 2002-2006 <NAME> // //Copyright (C) 2006-2019 <NAME> // //This Software Is Provided 'As-Is', Without Any Express Or Implied //Warranty. In No Event Will The Authors Be Held Liable For Any Damages //Arising From The Use Of This Software. // //Permission Is Granted To Anyone To Use This Software For Any Purpose, //Including Commercial Applications, And To Alter It And Redistribute It //Freely, Subject To The Following Restrictions: // //1. The Origin Of This Software Must Not Be Misrepresented; You Must Not // Claim That You Wrote The Original Software. If You Use This Software // In A Product, An Acknowledgment In The Product Documentation Would // Be Appreciated But Is Not Required. // //2. Altered Source Versions Must Be Plainly Marked As Such, And Must Not // Be Misrepresented As Being The Original Software. // //3. This Notice May Not Be Removed Or Altered From Any Source // Distribution. pub const VersionMajor = 3; pub const VersionMinor = 3; pub const VersionRevision = 2; pub const KeyState = extern enum(c_int) { Release = 0, Press = 1, Repeat = 2 }; pub const JoystickHat = extern enum(c_int) { Centered = 0, Up = 1, Right = 2, Down = 4, Left = 8, Rightup = (2 | 1), Rightdown = (2 | 4), Leftup = (8 | 1), Leftdown = (8 | 4), }; pub const Key = extern enum(c_int) { Unknown = -1, ///Modified Invalid = 0, Space = 32, Apostrophe = 39, Comma = 44, Minus = 45, Period = 46, Slash = 47, Num0 = 48, Num1 = 49, Num2 = 50, Num3 = 51, Num4 = 52, Num5 = 53, Num6 = 54, Num7 = 55, Num8 = 56, Num9 = 57, Semicolon = 59, Equal = 61, A = 65, B = 66, C = 67, D = 68, E = 69, F = 70, G = 71, H = 72, I = 73, J = 74, K = 75, L = 76, M = 77, N = 78, O = 79, P = 80, Q = 81, R = 82, S = 83, T = 84, U = 85, V = 86, W = 87, X = 88, Y = 89, Z = 90, LeftBracket = 91, Backslash = 92, RightBracket = 93, GraveAccent = 96, World1 = 161, World2 = 162, Escape = 256, Enter = 257, Tab = 258, Backspace = 259, Insert = 260, Delete = 261, Right = 262, Left = 263, Down = 264, Up = 265, PageUp = 266, PageDown = 267, Home = 268, End = 269, CapsLock = 280, ScrollLock = 281, NumLock = 282, PrintScreen = 283, Pause = 284, F1 = 290, F2 = 291, F3 = 292, F4 = 293, F5 = 294, F6 = 295, F7 = 296, F8 = 297, F9 = 298, F10 = 299, F11 = 300, F12 = 301, F13 = 302, F14 = 303, F15 = 304, F16 = 305, F17 = 306, F18 = 307, F19 = 308, F20 = 309, F21 = 310, F22 = 311, F23 = 312, F24 = 313, F25 = 314, Kp0 = 320, Kp1 = 321, Kp2 = 322, Kp3 = 323, Kp4 = 324, Kp5 = 325, Kp6 = 326, Kp7 = 327, Kp8 = 328, Kp9 = 329, KpDecimal = 330, KpDivide = 331, KpMultiply = 332, KpSubtract = 333, KpAdd = 334, KpEnter = 335, KpEqual = 336, LeftShift = 340, LeftControl = 341, LeftAlt = 342, LeftSuper = 343, RightShift = 344, RightControl = 345, RightAlt = 346, RightSuper = 347, Menu = 348, Last = 348, }; pub const Modifiers = extern enum(c_int) { Shift = 0x0001, Control = 0x0002, Alt = 0x0004, Super = 0x0008, CapsLock = 0x0010, NumLock = 0x0020, }; pub const Mouse = extern enum(c_int) { Invalid = -1, Button1 = 0, Button2 = 1, Button3 = 2, Button4 = 3, Button5 = 4, Button6 = 5, Button7 = 6, Button8 = 7, ButtonLast = 7, ButtonLeft = 0, ButtonRight = 1, ButtonMiddle = 2 }; pub const Joystick = extern enum(c_int) { Button1 = 0, Button2 = 1, Button3 = 2, Button4 = 3, Button5 = 4, Button6 = 5, Button7 = 6, Button8 = 7, Button9 = 8, Button10 = 9, Button11 = 10, Button12 = 11, Button13 = 12, Button14 = 13, Button15 = 14, Button16 = 15, ButtonLast = 15, }; pub const GamepadButton = extern enum(c_int) { A = 0, B = 1, X = 2, Y = 3, LeftBumper = 4, RightBumper = 5, Back = 6, Start = 7, Guide = 8, LeftThumb = 9, RightThumb = 10, DpadUp = 11, DpadRight = 12, DpadDown = 13, DpadLeft = 14, Last = 14, Cross = 0, Circle = 1, Square = 2, Triangle = 3, }; pub const GamepadAxis = extern enum(c_int) { LeftX = 0, LeftY = 1, RightX = 2, RightY = 3, LeftTrigger = 4, RightTrigger = 5, Last = 5 }; pub const GLFWError = error{ NotInitialized, NoCurrentContext, InvalidEnum, InvalidValue, OutOfMemory, APIUnavailable, VersionUnavailable, PlatformError, FormatUnavailable, NoWindowContext }; pub const ErrorCode = extern enum(c_int) { NotInitialized = 0x00010001, NoCurrentContext = 0x00010002, InvalidEnum = 0x00010003, InvalidValue = 0x00010004, OutOfMemory = 0x00010005, APIUnavailable = 0x00010006, VersionUnavailable = 0x00010007, PlatformError = 0x00010008, FormatUnavailable = 0x00010009, NoWindowContext = 0x0001000A, NoError = 0, }; pub const WindowHint = extern enum(c_int) { Focused = 0x00020001, Iconified = 0x00020002, Resizable = 0x00020003, Visible = 0x00020004, Decorated = 0x00020005, AutoIconify = 0x00020006, Floating = 0x00020007, Maximized = 0x00020008, CenterCursor = 0x00020009, TransparentFramebuffer = 0x0002000a, Hovered = 0x0002000b, FocusOnShow = 0x0002000c, RedBits = 0x00021001, GreenBits = 0x00021002, BlueBits = 0x00021003, AlphaBits = 0x00021004, DepthBits = 0x00021005, StencilBits = 0x00021006, AccumRedBits = 0x00021007, AccumGreenBits = 0x00021008, AccumBlueBits = 0x00021009, AccumAlphaBits = 0x0002100a, AUXBuffers = 0x0002100b, Stereo = 0x0002100c, Samples = 0x0002100d, SRGBCapable = 0x0002100e, RefreshRate = 0x0002100f, Doublebuffer = 0x00021010, ClientAPI = 0x00022001, ContextVersionMajor = 0x00022002, ContextVersionMinor = 0x00022003, ContextRevision = 0x00022004, ContextRobustness = 0x00022005, OpenGLForwardCompat = 0x00022006, OpenGLDebugContext = 0x00022007, OpenGLProfile = 0x00022008, ContextReleaseBehavior = 0x00022009, ContextNoError = 0x0002200a, ContextCreationAPI = 0x0002200b, ScaleToMonitor = 0x0002200c, CocoaRetinaFramebuffer = 0x00023001, CocoaFrameName = 0x00023002, CocoaGraphicsSwitching = 0x00023003, X11ClassName = 0x00024001, X11InstanceName = 0x00024002, }; pub const APIAttribute = extern enum(c_int) { NoAPI = 0, OpenGLAPI = 0x00030001, OpenGLESAPI = 0x00030002, }; pub const RobustnessAttribute = extern enum(c_int) { NoRobustness = 0, NoResetNotification = 0x00031001, LoseContextOnReset = 0x00031002, }; pub const GLProfileAttribute = extern enum(c_int) { OpenglAnyProfile = 0, OpenglCoreProfile = 0x00032001, OpenglCompatProfile = 0x00032002, }; pub const InputMode = extern enum(c_int) { Cursor = 0x00033001, StickyKeys = 0x00033002, StickyMouseButtons = 0x00033003, LockKeyMods = 0x00033004, RawMouseMotion = 0x00033005, }; pub const CursorVisibilityAttribute = extern enum(c_int) { CursorNormal = 0x00034001, CursorHidden = 0x00034002, CursorDisabled = 0x00034003, }; pub const ReleaseBehaviorAttribute = extern enum(c_int) { AnyReleaseBehavior = 0, ReleaseBehaviorFlush = 0x00035001, ReleaseBehaviorNone = 0x00035002, }; pub const ContextAPIAttribute = extern enum(c_int) { NativeContextAPI = 0x00036001, EGLContextAPI = 0x00036002, OSMesaContextAPI = 0x00036003, }; pub const DontCare: c_int = -1; pub const CursorShape = extern enum(c_int) { Arrow = 0x00036001, IBeam = 0x00036002, Crosshair = 0x00036003, Hand = 0x00036004, HResize = 0x00036005, VResize = 0x00036006, }; pub const Connection = extern enum(c_int) { Connected = 0x00040001, Disconnected = 0x00040002, }; pub const InitHint = extern enum(c_int) { JoystickHatButtons = 0x00050001, CocoaChdirResources = 0x00051001, CocoaMenubar = 0x00051002, }; pub const GLproc = fn (void) void; pub const VKproc = fn (void) void; pub const Monitor = c_long; pub const Window = c_long; pub const Cursor = c_long; pub const ErrorFun = fn (error_code: c_int, description: [*:0]u8) callconv(.C) void; pub const WindowPosFun = fn (window: *Window, xpos: c_int, ypos: c_int) callconv(.C) void; pub const WindowSizeFun = fn (window: *Window, width: c_int, height: c_int) callconv(.C) void; pub const WindowCloseFun = fn (window: *Window) callconv(.C) void; pub const WindowRefreshFun = fn (window: *Window) callconv(.C) void; pub const WindowFocusFun = fn (window: *Window, focused: c_int) callconv(.C) void; pub const WindowIconifyFun = fn (window: *Window, iconified: c_int) callconv(.C) void; pub const WindowMaximizeFun = fn (window: *Window, iconified: c_int) callconv(.C) void; pub const FramebufferSizeFun = fn (window: *Window, width: c_int, height: c_int) callconv(.C) void; pub const WindowContentScaleFun = fn (window: *Window, xscale: f32, yscale: f32) callconv(.C) void; //Mods is bitfield of modifiers, button is enum of mouse buttons, and action is enum of keystates. pub const MouseButtonFun = fn (window: *Window, button: c_int, action: c_int, mods: c_int) callconv(.C) void; pub const CursorPosFun = fn (window: *Window, xpos: f64, ypos: f64) callconv(.C) void; //Entered is true or false pub const CursorEnterFun = fn (window: *Window, entered: c_int) callconv(.C) void; pub const ScrollFun = fn (window: *Window, xoffset: f64, yoffset: f64) callconv(.C) void; //Mods is bitfield of modifiers, keys is enum of keys, and action is enum of keystates. pub const KeyFun = fn (window: *Window, key: c_int, scancode: c_int, action: c_int, mods: c_int) callconv(.C) void; pub const CharFun = fn (window: *Window, codepoint: c_uint) callconv(.C) void; //Mods refers to the bitfield of Modifiers pub const CharmodsFun = fn (window: *Window, codepoint: c_uint, mods: c_int) callconv(.C) void; pub const DropFun = fn (window: *Window, path_count: c_int, paths: [*:0]const u8) callconv(.C) void; //Event is one of two states defined by the enum 'Connection' pub const Monitorfun = fn (monitor: *Monitor, event: c_int) callconv(.C) void; //Event is one of two states defined by the enum 'Connection' pub const JoystickFun = fn (id: c_int, event: c_int) callconv(.C) void; pub const Vidmode = extern struct { width: i32, height: i32, redBits: i32, greenBits: i32, blueBits: i32, refreshRate: i32, }; pub const Gammaramp = extern struct { red: ?[*]u16, green: ?[*]u16, blue: ?[*]u16, size: u32 }; pub const Image = extern struct { width: i32, height: i32, pixels: ?[*]u8 }; pub const GamepadState = extern struct { buttons: [15]u8, axes: [6]f32 }; extern fn glfwInit() c_int; pub fn init() !void { if (glfwInit() != 1) { return GLFWError.PlatformError; } } extern fn glfwTerminate() void; extern fn glfwGetError(description: ?[*:0]const u8) c_int; fn errorCheck() !void { var code: c_int = glfwGetError(null); switch (@intToEnum(ErrorCode, code)) { .NotInitialized => return GLFWError.NotInitialized, .NoCurrentContext => return GLFWError.NoCurrentContext, .InvalidEnum => return GLFWError.InvalidEnum, .InvalidValue => return GLFWError.InvalidValue, .OutOfMemory => return GLFWError.OutOfMemory, .APIUnavailable => return GLFWError.APIUnavailable, .VersionUnavailable => return GLFWError.VersionUnavailable, .PlatformError => return GLFWError.PlatformError, .FormatUnavailable => return GLFWError.FormatUnavailable, .NoWindowContext => return GLFWError.NoWindowContext, else => {}, } } pub fn terminate() !void { glfwTerminate(); try errorCheck(); } extern fn glfwInitHint(hint: c_int, value: c_int) void; pub fn initHint(hint: InitHint, value: bool) !void { glfwInitHint(@enumToInt(hint), @boolToInt(value)); try errorCheck(); } extern fn glfwGetVersion(major: *c_int, minor: *c_int, rev: *c_int) void; extern fn glfwGetVersionString() [*:0]const u8; pub const getVersion = glfwGetVersion; pub const getVersionString = glfwGetVersionString; extern fn glfwSetErrorCallback(callback: ErrorFun) ErrorFun; pub const setErrorCallback = glfwSetErrorCallback; extern fn glfwGetMonitors(count: *c_int) ?[*]*Monitor; pub fn getMonitors(count: *c_int) !?[*]*Monitor { var res = glfwGetMonitors(count); try errorCheck(); return res; } extern fn glfwGetPrimaryMonitor() *Monitor; pub fn getPrimaryMonitor() !*Monitor { var res = glfwGetPrimaryMonitor(); try errorCheck(); return res; } extern fn glfwGetMonitorPos(monitor: ?*Monitor, xpos: ?*c_int, ypos: ?*c_int) void; pub fn getMonitorPos(monitor: ?*Monitor, xpos: ?*c_int, ypos: ?*c_int) !void { glfwGetMonitorPos(monitor, xpos, ypos); try errorCheck(); } extern fn glfwGetMonitorWorkarea(monitor: ?*Monitor, xpos: ?*c_int, ypos: ?*c_int, width: ?*c_int, height: ?*c_int) void; pub fn getMonitorWorkarea(monitor: ?*Monitor, xpos: ?*c_int, ypos: ?*c_int, width: ?*c_int, height: ?*c_int) !void { glfwGetMonitorWorkarea(monitor, xpos, ypos, width, height); try errorCheck(); } extern fn glfwGetMonitorPhysicalSize(monitor: ?*Monitor, widthMM: ?*c_int, heightMM: ?*c_int) void; pub fn getMonitorPhysicalSize(monitor: ?*Monitor, widthMM: ?*c_int, heightMM: ?*c_int) !void { glfwGetMonitorPhysicalSize(monitor, widthMM, heightMM); try errorCheck(); } extern fn glfwGetMonitorContentScale(monitor: ?*Monitor, xscale: ?*f32, yscale: ?*f32) void; pub fn getMonitorContentScale(monitor: ?*Monitor, xscale: ?*f32, yscale: ?*f32) !void { glfwGetMonitorContentScale(monitor, xscale, yscale); try errorCheck(); } extern fn glfwGetMonitorName(monitor: ?*Monitor) ?[*:0]const u8; pub fn getMonitorName(monitor: ?*Monitor) !?[*:0]const u8 { var res = glfwGetMonitorName(monitor); try errorCheck(); return res; } extern fn glfwSetMonitorUserPointer(monitor: ?*Monitor, pointer: ?*c_void) void; pub fn setMonitorUserPointer(monitor: ?*Monitor, pointer: ?*c_void) !void { glfwSetMonitorUserPointer(monitor, pointer); try errorCheck(); } extern fn glfwGetMonitorUserPointer(monitor: ?*Monitor) ?*c_void; pub fn getMonitorUserPointer(monitor: ?*Monitor) !?*c_void { var res = glfwGetMonitorUserPointer(monitor); try errorCheck(); return res; } extern fn glfwSetMonitorCallback(callback: MonitorFun) MonitorFun; pub fn setMonitorCallback(callback: MonitorFun) !MonitorFun { var res = glfwSetMonitorCallback(callback); try errorCheck(); return res; } extern fn glfwGetVideoModes(monitor: ?*Monitor, count: *c_int) ?[*]Vidmode; pub fn getVideoModes(monitor: ?*Monitor, count: *c_int) !?[*]Vidmode { var res = glfwGetVideoModes(monitor, count); try errorCheck(); return res; } extern fn glfwGetVideoMode(monitor: ?*Monitor) *Vidmode; pub fn getVideoMode(monitor: ?*Monitor) !*Vidmode { var res = glfwGetVideoMode(monitor); try errorCheck(); return res; } extern fn glfwSetGamma(monitor: ?*Monitor, gamma: f32) void; pub fn setGamma(monitor: ?*Monitor, gamma: f32) !void { glfwSetGamma(monitor, gamma); try errorCheck(); } extern fn glfwGetGammaRamp(monitor: ?*Monitor) *Gammaramp; pub fn getGammaRamp(monitor: ?*Monitor) !*Gammaramp { var res = glfwGetGammaRamp(monitor); try errorCheck(); return res; } extern fn glfwSetGammaRamp(monitor: ?*Monitor, ramp: ?*Gammaramp) void; pub fn setGammaRamp(monitor: ?*Monitor, ramp: ?*Gammaramp) !void { glfwSetGammaRamp(monitor, ramp); try errorCheck(); } extern fn glfwDefaultWindowHints() void; pub fn defaultWindowHints() !void { glfwDefaultWindowHints(); try errorCheck(); } extern fn glfwWindowHint(hint: c_int, value: c_int) void; pub fn windowHint(hint: WindowHint, value: c_int) !void { glfwWindowHint(@enumToInt(hint), value); try errorCheck(); } extern fn glfwWindowHintString(hint: c_int, value: [*:0]const u8) void; pub fn windowHintString(hint: WindowHint, value: [*:0]const u8) !void { glfwWindowHintString(@enumToInt(hint), value); try errorCheck(); } extern fn glfwCreateWindow(width: c_int, height: c_int, title: [*:0]const u8, monitor: ?*Monitor, share: ?*Window) ?*Window; pub fn createWindow(width: c_int, height: c_int, title: [*:0]const u8, monitor: ?*Monitor, share: ?*Window) !*Window { var res = glfwCreateWindow(width, height, title, monitor, share); try errorCheck(); if (res == null) { return GLFWError.PlatformError; } return res.?; } extern fn glfwDestroyWindow(window: ?*Window) void; pub fn destroyWindow(window: ?*Window) !void { glfwDestroyWindow(window); try errorCheck(); } extern fn glfwWindowShouldClose(window: ?*Window) c_int; pub fn windowShouldClose(window: ?*Window) !bool { var res = glfwWindowShouldClose(window); try errorCheck(); return res != 0; } extern fn glfwSetWindowShouldClose(window: ?*Window, value: c_int) void; pub fn setWindowShouldClose(window: ?*Window, value: bool) !void { glfwSetWindowShouldClose(window, @boolToInt(value)); try errorCheck(); } extern fn glfwSetWindowTitle(window: ?*Window, title: [*:0]const u8) void; pub fn setWindowTitle(window: ?*Window, title: [*:0]const u8) !void { glfwSetWindowTitle(window, title); try errorCheck(); } extern fn glfwSetWindowIcon(window: ?*Window, count: c_int, images: ?[*]const Image) void; pub fn setWindowIcon(window: ?*Window, count: c_int, images: ?[*]const Image) !void { glfwSetWindowIcon(window, count, images); try errorCheck(); } extern fn glfwGetWindowPos(window: ?*Window, xpos: *c_int, ypos: *c_int) void; pub fn getWindowPos(window: ?*Window, xpos: *c_int, ypos: *c_int) !void { glfwGetWindowPos(window, xpos, ypos); try errorCheck(); } extern fn glfwSetWindowPos(window: ?*Window, xpos: c_int, ypos: c_int) void; pub fn setWindowPos(window: ?*Window, xpos: c_int, ypos: c_int) !void { glfwSetWindowPos(window, xpos, ypos); try errorCheck(); } extern fn glfwGetWindowSize(window: ?*Window, width: *c_int, height: *c_int) void; pub fn getWindowSize(window: ?*Window, width: *c_int, height: *c_int) !void { glfwGetWindowSize(window, width, height); try errorCheck(); } extern fn glfwSetWindowSizeLimits(window: ?*Window, minwidth: c_int, minheight: c_int, maxwidth: c_int, maxheight: c_int) void; pub fn setWindowSizeLimits(window: ?*Window, minwidth: c_int, minheight: c_int, maxwidth: c_int, maxheight: c_int) !void { glfwSetWindowSizeLimits(window, minwidth, minheight, maxwidth, maxheight); try errorCheck(); } extern fn glfwSetWindowAspectRatio(window: ?*Window, numer: c_int, denom: c_int) void; pub fn setWindowAspectRatio(window: ?*Window, numer: c_int, denom: c_int) !void { glfwSetWindowAspectRatio(window, numer, denom); try errorCheck(); } extern fn glfwSetWindowSize(window: ?*Window, width: c_int, height: c_int) void; pub fn setWindowSize(window: ?*Window, width: c_int, height: c_int) !void { glfwSetWindowSize(window, width, height); try errorCheck(); } extern fn glfwGetFramebufferSize(window: ?*Window, width: *c_int, height: *c_int) void; pub fn getFramebufferSize(window: ?*Window, width: *c_int, height: *c_int) !void { glfwGetFramebufferSize(window, width, height); try errorCheck(); } extern fn glfwGetWindowFrameSize(window: ?*Window, left: *c_int, top: *c_int, right: *c_int, bottom: *c_int) void; pub fn getWindowFrameSize(window: ?*Window, left: *c_int, top: *c_int, right: *c_int, bottom: *c_int) !void { glfwGetWindowFrameSize(window, left, top, right, bottom); try errorCheck(); } extern fn glfwGetWindowContentScale(window: ?*Window, xscale: *f32, yscale: *f32) void; pub fn getWindowContentScale(window: ?*Window, xscale: *f32, yscale: *f32) !void { glfwGetWindowContentScale(window, xscale, yscale); try errorCheck(); } extern fn glfwGetWindowOpacity(window: ?*Window) f32; pub fn getWindowOpacity(window: ?*Window) f32 { var res = glfwGetWindowOpacity(window); try errorCheck(); return res; } extern fn glfwSetWindowOpacity(window: ?*Window, opacity: f32) void; pub fn setWindowOpacity(window: ?*Window, opacity: f32) !void { glfwSetWindowOpacity(window, opacity); try errorCheck(); } extern fn glfwIconifyWindow(window: ?*Window) void; pub fn iconifyWindow(window: ?*Window) !void { glfwIconifyWindow(window); try errorCheck(); } extern fn glfwRestoreWindow(window: ?*Window) void; pub fn restoreWindow(window: ?*Window) !void { glfwRestoreWindow(window); try errorCheck(); } extern fn glfwMaximizeWindow(window: ?*Window) void; pub fn maximizeWindow(window: ?*Window) !void { glfwMaximizeWindow(window); try errorCheck(); } extern fn glfwShowWindow(window: ?*Window) void; pub fn showWindow(window: ?*Window) !void { glfwShowWindow(window); try errorCheck(); } extern fn glfwHideWindow(window: ?*Window) void; pub fn hideWindow(window: ?*Window) !void { glfwHideWindow(window); try errorCheck(); } extern fn glfwFocusWindow(window: ?*Window) void; pub fn focusWindow(window: ?*Window) !void { glfwFocusWindow(window); try errorCheck(); } extern fn glfwRequestWindowAttention(window: ?*Window) void; pub fn requestWindowAttention(window: ?*Window) void { glfwRequestWindowAttention(window); try errorCheck(); } extern fn glfwGetWindowMonitor(window: ?*Window) ?*Monitor; pub fn getWindowMonitor(window: ?*Window) !?*Monitor { var res = glfwGetWindowMonitor(window); try errorCheck(); return res; } extern fn glfwSetWindowMonitor(window: ?*Window, monitor: ?*Monitor, xpos: c_int, ypos: c_int, width: c_int, height: c_int, refreshRate: c_int) void; pub fn setWindowMonitor(window: ?*Window, monitor: ?*Monitor, xpos: c_int, ypos: c_int, width: c_int, height: c_int, refreshRate: c_int) void { glfwSetWindowMonitor(window, monitor, xpos, ypos, width, height, refreshRate); try errorCheck(); } extern fn glfwGetWindowAttrib(window: ?*Window, attrib: c_int) c_int; pub fn getWindowAttrib(window: ?*Window, attrib: WindowHint) !c_int { var res = glfwGetWindowAttrib(window, @enumToInt(attrib)); try errorCheck(); return res; } extern fn glfwSetWindowAttrib(window: ?*Window, attrib: c_int, value: c_int) void; pub fn setWindowAttrib(window: ?*Window, attrib: WindowHint, value: c_int) !void { glfwSetWindowAttrib(window, @enumToInt(attrib), value); try errorCheck(); } extern fn glfwSetWindowUserPointer(window: ?*Window, pointer: *c_void) void; pub fn setWindowUserPointer(window: ?*Window, pointer: *c_void) void { glfwSetWindowUserPointer(window, pointer); try errorCheck(); } extern fn glfwGetWindowUserPointer(window: ?*Window) ?*c_void; pub fn getWindowUserPointer(window: ?*Window) !?*c_void { var res = glfwGetWindowUserPointer(window); try errorCheck(); return res; } extern fn glfwSetWindowPosCallback(window: ?*Window, callback: WindowPosFun) WindowPosFun; extern fn glfwSetWindowSizeCallback(window: ?*Window, callback: WindowSizeFun) WindowSizeFun; extern fn glfwSetWindowCloseCallback(window: ?*Window, callback: WindowCloseFun) WindowCloseFun; extern fn glfwSetWindowRefreshCallback(window: ?*Window, callback: WindowRefreshFun) WindowRefreshFun; extern fn glfwSetWindowFocusCallback(window: ?*Window, callback: WindowFocusFun) WindowFocusFun; extern fn glfwSetWindowIconifyCallback(window: ?*Window, callback: WindowIconifyFun) WindowIconifyFun; extern fn glfwSetWindowMaximizeCallback(window: ?*Window, callback: WindowMaximizeFun) WindowMaximizeFun; extern fn glfwSetFramebufferSizeCallback(window: ?*Window, callback: FramebufferSizeFun) FramebufferSizeFun; extern fn glfwSetWindowContentScaleCallback(window: ?*Window, callback: WindowContentScaleFun) WindowContentScaleFun; pub fn setWindowPosCallback(window: ?*Window, callback: WindowPosFun) !WindowPosFun { var res = glfwSetWindowPosCallback(window, callback); try errorCheck(); return res; } pub fn setWindowSizeCallback(window: ?*Window, callback: WindowSizeFun) !WindowSizeFun { var res = glfwSetWindowSizeCallback(window, callback); try errorCheck(); return res; } pub fn setWindowCloseCallback(window: ?*Window, callback: WindowCloseFun) !WindowCloseFun { var res = glfwSetWindowCloseCallback(window, callback); try errorCheck(); return res; } pub fn setWindowRefreshCallback(window: ?*Window, callback: WindowRefreshFun) !WindowRefreshFun { var res = glfwSetWindowRefreshCallback(window, callback); try errorCheck(); return res; } pub fn setWindowFocusCallback(window: ?*Window, callback: WindowFocusFun) !WindowFocusFun { var res = glfwSetWindowFocusCallback(window, callback); try errorCheck(); return res; } pub fn setWindowIconifyCallback(window: ?*Window, callback: WindowIconifyFun) !WindowIconifyFun { var res = glfwSetWindowIconifyCallback(window, callback); try errorCheck(); return res; } pub fn setWindowMaximizeCallback(window: ?*Window, callback: WindowMaximizeFun) !WindowMaximizeFun { var res = glfwSetWindowMaximizeCallback(window, callback); try errorCheck(); return res; } pub fn setFramebufferSizeCallback(window: ?*Window, callback: FramebufferSizeFun) !FramebufferSizeFun { var res = glfwSetFramebufferSizeCallback(window, callback); try errorCheck(); return res; } pub fn setWindowContentScaleCallback(window: ?*Window, callback: WindowContentScaleFun) !WindowContentScaleFun { var res = glfwSetWindowContentScaleCallback(window, callback); try errorCheck(); return res; } extern fn glfwPollEvents() void; pub fn pollEvents() !void { glfwPollEvents(); try errorCheck(); } extern fn glfwWaitEvents() void; pub fn waitEvents() !void { glfwWaitEvents(); try errorCheck(); } extern fn glfwWaitEventsTimeout(timeout: f64) void; pub fn waitEventsTimeout(timeout: f64) !void { glfwWaitEventsTimeout(timeout); try errorCheck(); } extern fn glfwPostEmptyEvent() void; pub fn postEmptyEvent() !void { glfwPostEmptyEvent(); try errorCheck(); } extern fn glfwGetInputMode(window: ?*Window, mode: c_int) c_int; //Depending on what your input mode is, you can change to true/false or one of the attribute enums pub fn getInputMode(window: ?*Window, mode: InputMode) !c_int { var res = glfwGetInputMode(window, @enumToInt(mode)); try errorCheck(); return res; } extern fn glfwSetInputMode(window: ?*Window, mode: InputMode, value: c_int) void; pub fn setInputMode(window: ?*Window, mode: InputMode, value: c_int) !void { glfwSetInputMode(window, @enumToInt(mode), value); try errorCheck(); } extern fn glfwRawMouseMotionSupported() c_int; pub fn rawMouseMotionSupported() !bool { var res = glfwRawMouseMotionSupported(); try errorCheck(); return res != 0; } const std = @import("std"); extern fn glfwGetKeyName(key: c_int, scancode: c_int) ?[*:0]const u8; pub fn getKeyName(key: Key, scancode: c_int) !?[:0]const u8 { var res = glfwGetKeyName(@enumToInt(key), scancode); try errorCheck(); return std.mem.spanZ(res); } extern fn glfwGetKeyScancode(key: c_int) c_int; pub fn getKeyScancode(key: Key) !c_int { var res = glfwGetKeyScancode(@enumToInt(key)); try errorCheck(); return res; } extern fn glfwGetKey(window: ?*Window, key: c_int) c_int; pub fn getKey(window: ?*Window, key: Key) !KeyState { var res = glfwGetKey(window, @enumToInt(key)); try errorCheck(); return @intToEnum(KeyState, res); } extern fn glfwGetMouseButton(window: ?*Window, button: c_int) c_int; pub fn getMouseButton(window: ?*Window, button: Mouse) !KeyState { var res = glfwGetMouseButton(window, @enumToInt(button)); try errorCheck(); return @intToEnum(KeyState, res); } extern fn glfwGetCursorPos(window: ?*Window, xpos: *f64, ypos: *f64) void; pub fn getCursorPos(window: ?*Window, xpos: *f64, ypos: *f64) !void { glfwGetCursorPos(window, xpos, ypos); try errorCheck(); } extern fn glfwSetCursorPos(window: ?*Window, xpos: f64, ypos: f64) void; pub fn setCursorPos(window: ?*Window, xpos: f64, ypos: f64) !void { glfwSetCursorPos(window, xpos, ypos); try errorCheck(); } extern fn glfwCreateCursor(image: ?*Image, xhot: c_int, yhot: c_int) ?*Cursor; pub fn createCursor(image: ?*Image, xhot: c_int, yhot: c_int) !?*Cursor { var res = glfwCreateCursor(image, xhot, yhot); try errorCheck(); return res; } extern fn glfwCreateStandardCursor(shape: c_int) ?*Cursor; pub fn createStandardCursor(shape: CursorShape) !?*Cursor { var res = glfwCreateStandardCursor(@enumToInt(shape)); try errorCheck(); return res; } extern fn glfwDestroyCursor(cursor: ?*Cursor) void; pub fn destroyCursor(cursor: ?*Cursor) !void { glfwDestroyCursor(cursor); try errorCheck(); } extern fn glfwSetCursor(window: ?*Window, cursor: ?*Cursor) void; pub fn setCursor(window: ?*Window, cursor: ?*Cursor) !void { glfwSetCursor(window, cursor); try errorCheck(); } extern fn glfwSetKeyCallback(window: ?*Window, callback: KeyFun) KeyFun; extern fn glfwSetCharCallback(window: ?*Window, callback: CharFun) CharFun; extern fn glfwSetCharModsCallback(window: ?*Window, callback: CharmodsFun) CharmodsFun; extern fn glfwSetMouseButtonCallback(window: ?*Window, callback: MouseButtonFun) MouseButtonFun; extern fn glfwSetCursorPosCallback(window: ?*Window, callback: CursorPosFun) CursorPosFun; extern fn glfwSetCursorEnterCallback(window: ?*Window, callback: CursorEnterFun) CursorEnterFun; extern fn glfwSetScrollCallback(window: ?*Window, callback: ScrollFun) ScrollFun; extern fn glfwSetDropCallback(window: ?*Window, callback: DropFun) DropFun; pub fn setKeyCallback(window: ?*Window, callback: KeyFun) !KeyFun { var res = glfwSetKeyCallback(window, callback); try errorCheck(); return res; } pub fn setCharCallback(window: ?*Window, callback: CharFun) !CharFun { var res = glfwSetCharCallback(window, callback); try errorCheck(); return res; } pub fn setCharModsCallback(window: ?*Window, callback: CharmodsFun) !CharmodsFun { var res = glfwSetCharModsCallback(window, callback); try errorCheck(); return res; } pub fn setMouseButtonCallback(window: ?*Window, callback: MouseButtonFun) !MouseButtonFun { var res = glfwSetMouseButtonCallback(window, callback); try errorCheck(); return res; } pub fn setCursorPosCallback(window: ?*Window, callback: CursorPosFun) !CursorPosFun { var res = glfwSetCursorPosCallback(window, callback); try errorCheck(); return res; } pub fn setCursorEnterCallback(window: ?*Window, callback: CursorEnterFun) !CursorEnterFun { var res = glfwSetCursorEnterCallback(window, callback); try errorCheck(); return res; } pub fn setScrollCallback(window: ?*Window, callback: ScrollFun) !ScrollFun { var res = glfwSetScrollCallback(window, callback); try errorCheck(); return res; } pub fn setDropCallback(window: ?*Window, callback: DropFun) !DropFun { var res = glfwSetDropCallback(window, callback); try errorCheck(); return res; } extern fn glfwJoystickPresent(jid: c_int) c_int; pub fn joystickPresent(jid: c_int) !bool { var res = glfwJoystickPresent(jid); try errorCheck(); return res != 0; } extern fn glfwGetJoystickAxes(jid: c_int, count: *c_int) ?[*]const f32; pub fn getJoystickAxes(jid: c_int, count: *c_int) !?[*]const f32 { var res = glfwGetJoystickAxes(jid, count); try errorCheck(); } extern fn glfwGetJoystickButtons(jid: c_int, count: *c_int) ?[*]const u8; pub fn getJoystickButtons(jid: c_int, count: *c_int) !?[*]const u8 { var res = glfwGetJoystickButtons(jid, count); try errorCheck(); return res; } extern fn glfwGetJoystickHats(jid: c_int, count: *c_int) ?[*]const u8; pub fn getJoystickHats(jid: c_int, count: *c_int) !?[*]const u8 { var res = glfwGetJoystickHats(jid, count); try errorCheck(); return res; } extern fn glfwGetJoystickName(jid: c_int) ?[*:0]const u8; pub fn getJoystickName(jid: c_int) !?[*:0]const u8 { var res = glfwGetJoystickName(jid); try errorCheck(); return res; } extern fn glfwGetJoystickGUID(jid: c_int) ?[*:0]const u8; pub fn getJoystickGUID(jid: c_int) !?[*:0]const u8 { var res = glfwGetJoystickGUID(jid); try errorCheck(); return res; } extern fn glfwSetJoystickUserPointer(jid: c_int, pointer: *c_void) void; pub fn setJoystickUserPointer(jid: c_int, pointer: *c_void) !void { var res = glfwSetJoystickUserPointer(jid, pointer); try errorCheck(); return res; } extern fn glfwGetJoystickUserPointer(jid: c_int) *c_void; pub fn getJoystickUserPointer(jid: c_int) !*c_void { var res = getJoystickUserPointer(jid); try errorCheck(); return res; } extern fn glfwJoystickIsGamepad(jid: c_int) c_int; pub fn joystickIsGamepad(jid: c_int) !c_int { var res = glfwJoystickIsGamepad(jid); try errorCheck(); return res; } extern fn glfwSetJoystickCallback(callback: JoystickFun) JoystickFun; pub fn setJoystickCallback(callback: JoystickFun) !JoystickFun { var res = glfwSetJoystickCallback(callback); try errorCheck(); return res; } extern fn glfwUpdateGamepadMappings(string: [*:0]const u8) c_int; pub fn updateGamepadMappings(string: [*:0]const u8) !c_int { var res = glfwUpdateGamepadMappings(string); try errorCheck(); return res; } extern fn glfwGetGamepadName(jid: c_int) ?[*:0]const u8; pub fn getGamepadName(jid: c_int) !?[*:0]const u8 { var res = glfwGetGamepadName(jid); try errorCheck(); return res; } extern fn glfwGetGamepadState(jid: c_int, state: ?*GamepadState) c_int; pub fn getGamepadState(jid: c_int, state: ?*GamepadState) !c_int { var res = glfwGetGamepadState(jid, state); try errorCheck(); return res; } extern fn glfwSetClipboardString(window: ?*Window, string: [*:0]const u8) void; pub fn setClipboardString(window: ?*Window, string: [*:0]const u8) !void { glfwSetClipboardString(window, string); try errorCheck(); } extern fn glfwGetClipboardString(window: ?*Window) ?[*:0]const u8; pub fn getClipboardString(window: ?*Window) !?[:0]const u8 { var res = glfwGetClipboardString(window); try errorCheck(); return std.mem.spanZ(res); } extern fn glfwGetTime() f64; pub fn getTime() !f64 { var res = glfwGetTime(); try errorCheck(); return res; } extern fn glfwSetTime(time: f64) void; pub fn setTime(time: f64) !void { glfwSetTime(time); try errorCheck(); } extern fn glfwGetTimerValue() u64; pub fn getTimerValue() !u64 { var res = glfwGetTimerValue(); try errorCheck(); return res; } extern fn glfwGetTimerFrequency() u64; pub fn getTimerFrequency() !u64 { var res = glfwGetTimerFrequency(); try errorCheck(); return res(); } //Context extern fn glfwMakeContextCurrent(window: ?*Window) void; pub fn makeContextCurrent(window: ?*Window) !void { glfwMakeContextCurrent(window); try errorCheck(); } extern fn glfwGetCurrentContext() ?*Window; pub fn getCurrentContext() !?*Window { var res = glfwGetCurrentContext(window); try errorCheck(); return res; } extern fn glfwSwapBuffers(window: ?*Window) void; pub fn swapBuffers(window: ?*Window) !void { glfwSwapBuffers(window); try errorCheck(); } extern fn glfwSwapInterval(interval: c_int) void; pub fn swapInterval(interval: c_int) !void { glfwSwapInterval(interval); try errorCheck(); } //GL Stuff extern fn glfwExtensionSupported(extension: [*:0]const u8) c_int; pub fn extensionSupported(extension: [*:0]const u8) !c_int { var res = glfwExtensionSupported(extension); try errorCheck(); return res; } extern fn glfwGetProcAddress(procname: [*:0]const u8) GLproc; pub fn getProcAddress(procname: [*:0]const u8) !GLproc { var res = glfwGetProcAddress(procname); try errorCheck(); return res; } //Vulkan stuff //extern fn GLFWvkproc glfwGetInstanceProcAddress(VkInstance instance, const char* procname); //extern fn int glfwGetPhysicalDevicePresentationSupport(VkInstance instance, VkPhysicalDevice device, uint32_t queuefamily); //extern fn VkResult glfwCreateWindowSurface(VkInstance instance, GLFWwindow* window, const VkAllocationCallbacks* allocator, VkSurfaceKHR* surface); extern fn glfwVulkanSupported() c_int; pub fn vulkanSupported() bool { var res = glfwVulkanSupported(); try errorCheck(); return res != 0; } extern fn glfwGetRequiredInstanceExtensions(count: *u32) ?[*][*:0]const u8; pub fn getRequiredInstanceExtensions(count: *u32) !?[*][*:0]const u8 { var res = glfwGetRequiredInstanceExtensions(count); try errorCheck(); return res; }
src/core/glfw.zig
const std = @import("std"); const stdx = @import("../stdx.zig"); const ds = stdx.ds; const t = stdx.testing; const log = stdx.log.scoped(.walk); // Iterative walking. Let's us reuse the same walkers for dfs/bfs walking. // Also makes it easier to add features at comptime like abort during a visit. // Depends on a buffer or creates it's own from provided allocator. pub fn walkPre( comptime Config: WalkerConfig, comptime Context: type, user_ctx: Context, comptime Node: type, root: Node, walker: *WalkerIface(Node), user_visit: UserVisit(Config, Context, Node), buf: *std.ArrayList(Node), ) void { var queuer = ReverseAddToBuffer(Node){ .buf = buf }; const S = struct { queuer: *QueueIface(Node), buf: *std.ArrayList(Node), walker: *WalkerIface(Node), ctx: *VisitContext(Config), user_ctx: Context, user_visit: UserVisit(Config, Context, Node), fn walk(self: *@This(), node: Node) void { self.walker.setQueuer(self.queuer); self.queuer.addNodes(&.{node}); while (self.buf.items.len > 0) { const last = self.buf.pop(); self.user_visit(self.ctx, self.user_ctx, last); if (Config.enable_abort and self.ctx.aborted) { break; } if (Config.enable_skip and self.ctx.skipped) { self.ctx.skipped = false; continue; } self.walker.walk(last); } } }; var ctx: VisitContext(Config) = .{}; var state = S{ .queuer = &queuer.iface, .buf = buf, .walker = walker, .ctx = &ctx, .user_ctx = user_ctx, .user_visit = user_visit, }; buf.clearRetainingCapacity(); state.walk(root); } pub fn walkPreAlloc( alloc: std.mem.Allocator, comptime Config: WalkerConfig, comptime Context: type, user_ctx: Context, comptime Node: type, root: Node, walker: *WalkerIface(Node), user_visit: UserVisit(Config, Context, Node), ) void { var buf = std.ArrayList(Node).init(alloc); defer buf.deinit(); walkPre(Config, Context, user_ctx, Node, root, walker, user_visit, &buf); } test "walkPreAlloc" { const S = struct { fn visit(_: *VisitContext(.{}), res: *std.ArrayList(u32), node: TestNode) void { res.append(node.val) catch unreachable; } }; var res = std.ArrayList(u32).init(t.alloc); defer res.deinit(); walkPreAlloc(t.alloc, .{}, *std.ArrayList(u32), &res, TestNode, TestGraph, TestWalker.getIface(), S.visit); try t.eqSlice(u32, res.items, &[_]u32{ 1, 2, 4, 3 }); } // Uses a bit_buf to track whether a node in the stack has pushed its children onto the stack. // Repeatedly checks top of the stack. If it has been expanded then it's visited and popped, // otherwise its children are pushed onto the stack. pub fn walkPost( comptime Config: WalkerConfig, comptime Context: type, user_ctx: Context, comptime Node: type, root: Node, walker: *WalkerIface(Node), user_visit: UserVisit(Config, Context, Node), buf: *std.ArrayList(Node), bit_buf: *ds.BitArrayList, ) void { var queuer = ReverseAddToBuffer(Node){ .buf = buf }; const S = struct { queuer: *QueueIface(Node), buf: *std.ArrayList(Node), bit_buf: *ds.BitArrayList, walker: *WalkerIface(Node), ctx: *VisitContext(Config), user_ctx: Context, user_visit: UserVisit(Config, Context, Node), fn walk(self: *@This(), node: Node) void { self.walker.setQueuer(self.queuer); self.queuer.addNodes(&.{node}); self.bit_buf.appendUnset() catch unreachable; while (self.buf.items.len > 0) { if (self.bit_buf.isSet(self.buf.items.len - 1)) { const last = self.buf.pop(); self.user_visit(self.ctx, self.user_ctx, last); } else { const last = self.buf.items[self.buf.items.len - 1]; self.bit_buf.set(self.buf.items.len - 1); const last_len = self.buf.items.len; self.walker.walk(last); self.bit_buf.resize(self.buf.items.len) catch unreachable; self.bit_buf.unsetRange(last_len, self.buf.items.len); } } } }; var ctx: VisitContext(Config) = .{}; var state = S{ .queuer = &queuer.iface, .buf = buf, .bit_buf = bit_buf, .walker = walker, .ctx = &ctx, .user_ctx = user_ctx, .user_visit = user_visit, }; buf.clearRetainingCapacity(); bit_buf.clearRetainingCapacity(); state.walk(root); } pub fn walkPostAlloc( alloc: std.mem.Allocator, comptime Config: WalkerConfig, comptime Context: type, user_ctx: Context, comptime Node: type, root: Node, walker: *WalkerIface(Node), user_visit: UserVisit(Config, Context, Node), ) void { var buf = std.ArrayList(Node).init(alloc); defer buf.deinit(); var bit_buf = ds.BitArrayList.init(alloc); defer bit_buf.deinit(); walkPost(Config, Context, user_ctx, Node, root, walker, user_visit, &buf, &bit_buf); } test "walkPostAlloc" { const S = struct { fn visit(_: *VisitContext(.{}), res: *std.ArrayList(u32), node: TestNode) void { res.append(node.val) catch unreachable; } }; var res = std.ArrayList(u32).init(t.alloc); defer res.deinit(); walkPostAlloc(t.alloc, .{}, *std.ArrayList(u32), &res, TestNode, TestGraph, TestWalker.getIface(), S.visit); try t.eqSlice(u32, res.items, &[_]u32{ 4, 2, 3, 1 }); } // Uses a bit_buf to track whether a node in the stack has pushed its children onto the stack. // Repeatedly checks top of the stack. If it has been expanded then it's visited and popped, // otherwise its children is pushed onto the stack. // VisitContext.enter is set true when we first process the node and add it's children, // and false when we pop it from the stack. pub fn walkPrePost( comptime Config: WalkerConfig, comptime Context: type, user_ctx: Context, comptime Node: type, root: Node, walker: *WalkerIface(Node), user_visit: UserVisit(Config, Context, Node), buf: *std.ArrayList(Node), bit_buf: *ds.BitArrayList, ) void { var queuer = ReverseAddToBuffer(Node){ .buf = buf }; const S = struct { queuer: *QueueIface(Node), buf: *std.ArrayList(Node), bit_buf: *ds.BitArrayList, walker: *WalkerIface(Node), ctx: *VisitContext(Config), user_ctx: Context, user_visit: UserVisit(Config, Context, Node), fn walk(self: *@This(), node: Node) void { self.walker.setQueuer(self.queuer); self.queuer.addNodes(&.{node}); self.bit_buf.appendUnset() catch unreachable; while (self.buf.items.len > 0) { if (self.bit_buf.isSet(self.buf.items.len - 1)) { const last = self.buf.pop(); self.ctx.enter = false; self.user_visit(self.ctx, self.user_ctx, last); } else { const last = self.buf.items[self.buf.items.len - 1]; self.ctx.enter = true; self.user_visit(self.ctx, self.user_ctx, last); self.bit_buf.set(self.buf.items.len - 1); if (Config.enable_skip and self.ctx.skipped) { _ = self.buf.pop(); self.ctx.skipped = false; continue; } const last_len = self.buf.items.len; self.walker.walk(last); self.bit_buf.resize(self.buf.items.len) catch unreachable; self.bit_buf.unsetRange(last_len, self.buf.items.len); } } } }; var ctx: VisitContext(Config) = .{}; var state = S{ .queuer = &queuer.iface, .buf = buf, .bit_buf = bit_buf, .walker = walker, .ctx = &ctx, .user_ctx = user_ctx, .user_visit = user_visit, }; buf.clearRetainingCapacity(); bit_buf.clearRetainingCapacity(); state.walk(root); } pub fn walkPrePostAlloc( alloc: std.mem.Allocator, comptime Config: WalkerConfig, comptime Context: type, user_ctx: Context, comptime Node: type, root: Node, walker: *WalkerIface(Node), user_visit: UserVisit(Config, Context, Node), ) void { var buf = std.ArrayList(Node).init(alloc); defer buf.deinit(); var bit_buf = ds.BitArrayList.init(alloc); defer bit_buf.deinit(); walkPrePost(Config, Context, user_ctx, Node, root, walker, user_visit, &buf, &bit_buf); } test "walkPrePostAlloc" { const S = struct { fn visit(_: *VisitContext(.{}), res: *std.ArrayList(u32), node: TestNode) void { res.append(node.val) catch unreachable; } }; var res = std.ArrayList(u32).init(t.alloc); defer res.deinit(); walkPrePostAlloc(t.alloc, .{}, *std.ArrayList(u32), &res, TestNode, TestGraph, TestWalker.getIface(), S.visit); try t.eqSlice(u32, res.items, &[_]u32{ 1, 2, 4, 4, 2, 3, 3, 1 }); } test "walkPrePostAlloc with skip" { const Config = WalkerConfig{ .enable_skip = true }; const S = struct { fn visit(ctx: *VisitContext(Config), res: *std.ArrayList(u32), node: TestNode) void { if (ctx.enter) { if (node.val == 2) { ctx.skip(); } } res.append(node.val) catch unreachable; } }; var res = std.ArrayList(u32).init(t.alloc); defer res.deinit(); walkPrePostAlloc(t.alloc, Config, *std.ArrayList(u32), &res, TestNode, TestGraph, TestWalker.getIface(), S.visit); try t.eqSlice(u32, res.items, &[_]u32{ 1, 2, 3, 3, 1 }); } pub const WalkerConfig = struct { // Allows visitor to stop the code. enable_abort: bool = false, // Allows visitor to skip the current node before it walks to its children. enable_skip: bool = false, }; fn AddToBuffer(comptime Node: type) type { return struct { iface: QueueIface(Node) = .{ .begin_add_node_fn = beginAddNode, .add_node_fn = addNode, .add_nodes_fn = addNodes, }, buf: *std.ArrayList(Node), cur_insert_idx: u32 = 0, fn beginAddNode(iface: *QueueIface(Node), size: u32) void { const self = @fieldParentPtr(@This(), "iface", iface); const new_len = @intCast(u32, self.buf.items.len) + size; self.cur_insert_idx = self.buf.items.len; self.buf.resize(new_len) catch unreachable; } fn addNode(iface: *QueueIface(Node), node: Node) void { const self = @fieldParentPtr(@This(), "iface", iface); self.buf.items[self.cur_insert_idx] = node; self.cur_insert_idx += 1; } fn addNodes(iface: *QueueIface(Node), nodes: []const Node) void { const self = @fieldParentPtr(@This(), "iface", iface); self.buf.appendSlice(nodes) catch unreachable; } }; } pub fn ReverseAddToBuffer(comptime Node: type) type { return struct { iface: QueueIface(Node) = .{ .begin_add_node_fn = beginAddNode, .add_node_fn = addNode, .add_nodes_fn = addNodes, }, buf: *std.ArrayList(Node), // Use idx plus one to avoid integer overflow. cur_insert_idx_p1: u32 = 0, fn beginAddNode(iface: *QueueIface(Node), size: u32) void { const self = @fieldParentPtr(@This(), "iface", iface); const new_len = @intCast(u32, self.buf.items.len) + size; self.cur_insert_idx_p1 = new_len; self.buf.resize(new_len) catch unreachable; } fn addNode(iface: *QueueIface(Node), node: Node) void { const self = @fieldParentPtr(@This(), "iface", iface); self.cur_insert_idx_p1 -= 1; self.buf.items[self.cur_insert_idx_p1] = node; } fn addNodes(iface: *QueueIface(Node), nodes: []const Node) void { const self = @fieldParentPtr(@This(), "iface", iface); var i: u32 = @intCast(u32, nodes.len); while (i > 0) { i -= 1; self.buf.append(nodes[i]) catch unreachable; } } }; } fn QueueIface(comptime Node: type) type { return struct { begin_add_node_fn: fn (*@This(), u32) void, add_node_fn: fn (*@This(), Node) void, add_nodes_fn: fn (*@This(), []const Node) void, // When using addNode, a size is required if you want the order natural order to be FIFO. // You are then expected to supply that many nodes with addNode. fn beginAddNode(self: *@This(), size: u32) void { self.begin_add_node_fn(self, size); } fn addNode(self: *@This(), node: Node) void { self.add_node_fn(self, node); } pub fn addNodes(self: *@This(), nodes: []const Node) void { self.add_nodes_fn(self, nodes); } }; } fn UserVisit(comptime Config: WalkerConfig, comptime Context: type, comptime Node: type) type { return fn (*VisitContext(Config), Context, Node) void; } pub fn VisitContext(comptime Config: WalkerConfig) type { return struct { const Self = @This(); aborted: bool = false, // Used by walkPrePost to indicate entering/leaving the node. enter: bool = true, // Used by walkPre to skip walking to children for the current node. skipped: bool = false, usingnamespace if (Config.enable_abort) struct { pub fn abort(self: *Self) void { self.aborted = true; } } else struct {}; usingnamespace if (Config.enable_skip) struct { pub fn skip(self: *Self) void { self.skipped = true; } } else struct {}; }; } fn UserWalker(comptime Context: type, comptime Node: type) type { return fn (*WalkerContext(Node), Context, Node) void; } pub fn WalkerContext(comptime Node: type) type { return struct { queuer: *QueueIface(Node), pub fn beginAddNode(self: *@This(), size: u32) void { self.queuer.beginAddNode(size); } pub fn addNode(self: *@This(), node: Node) void { self.queuer.addNode(node); } pub fn addNodes(self: *@This(), nodes: []const Node) void { self.queuer.addNodes(nodes); } }; } pub fn Walker(comptime Context: type, comptime Node: type) type { return struct { iface: WalkerIface(Node) = .{ .walk_fn = walk, .set_queuer_fn = setQueuer, }, ctx: WalkerContext(Node), user_ctx: Context, user_walk: UserWalker(Context, Node), pub fn init(user_ctx: Context, user_walk: UserWalker(Context, Node)) @This() { return .{ .ctx = .{ .queuer = undefined, }, .user_ctx = user_ctx, .user_walk = user_walk, }; } pub fn getIface(self: *@This()) *WalkerIface(Node) { return &self.iface; } pub fn walk(iface: *WalkerIface(Node), node: Node) void { const self = @fieldParentPtr(@This(), "iface", iface); self.user_walk(&self.ctx, self.user_ctx, node); } pub fn setQueuer(iface: *WalkerIface(Node), queuer: *QueueIface(Node)) void { const self = @fieldParentPtr(@This(), "iface", iface); self.ctx.queuer = queuer; } }; } pub fn WalkerIface(comptime Node: type) type { return struct { walk_fn: fn (*@This(), node: Node) void, set_queuer_fn: fn (*@This(), queuer: *QueueIface(Node)) void, pub fn walk(self: *@This(), node: Node) void { self.walk_fn(self, node); } pub fn setQueuer(self: *@This(), queuer: *QueueIface(Node)) void { self.set_queuer_fn(self, queuer); } }; } pub const TestNode = struct { val: u32, children: []const @This(), }; pub const TestGraph = TestNode{ .val = 1, .children = &[_]TestNode{ .{ .val = 2, .children = &[_]TestNode{.{ .val = 4, .children = &.{}, }}, }, .{ .val = 3, .children = &.{}, }, }, }; pub var TestWalker = b: { const S = struct { fn walk(ctx: *WalkerContext(TestNode), _: void, node: TestNode) void { ctx.addNodes(node.children); } }; break :b Walker(void, TestNode).init({}, S.walk); };
stdx/algo/walk.zig
const std = @import("std"); const cli = @import("cli.zig"); const utils = @import("utils.zig"); const templator = @import("templator.zig"); var a: std.mem.Allocator = undefined; const io = std.io; const help = \\USAGE: \\$ colorstorm [-o outdir] [-g generator] input \\ \\-o|--outdir: The directory to output themes to (default: "./colorstorm-out") \\-g|--gen: Generator type (default: all) \\ Available types: all, atom, vscode, vim, sublime, iterm2, hyper \\-i|--input: The JSON input file to use for generating the themes \\ See: https://github.com/benbusby/colorstorm#creating-themes ; fn parse_args() !void { const stdout = std.io.getStdOut().writer(); var arena = std.heap.ArenaAllocator.init(std.heap.page_allocator); defer arena.deinit(); a = arena.allocator(); var iter = std.process.args(); var flag: cli.Flag = cli.Flag.na; // Skip first arg _ = iter.next(a); while (iter.next(a)) |arg| { const argument = arg catch break; if (flag != cli.Flag.na) { try cli.set_flag_val(flag, argument); flag = cli.Flag.na; } else { flag = cli.parse_flag(argument); if (flag == cli.Flag.help) { try stdout.print("\n{s}\n\n", .{help}); std.os.exit(0); } } // input will always be the last argument, if not // explicitly set elsewhere via flag if (cli.get_flag_val(cli.Flag.input).?.len == 0) { try cli.set_flag_val(cli.Flag.input, argument); } a.free(argument); } } pub fn main() !void { const stdout = std.io.getStdOut().writer(); try cli.init(); try parse_args(); var input = cli.get_flag_val(cli.Flag.input).?; if (input.len == 0) { try stdout.print("ERROR: Missing input file\n{s}\n\n", .{help}); std.os.exit(1); } const f = std.fs.cwd().openFile(input, std.fs.File.OpenFlags{ .read = true }) catch { try stdout.print("ERROR: Unable to open file '{s}'\n", .{input}); std.os.exit(1); }; var outdir = cli.get_flag_val(cli.Flag.outdir).?; try std.fs.cwd().makePath(cli.get_flag_val(cli.Flag.outdir).?); try templator.create_themes(f, outdir, cli.get_flag_val(cli.Flag.gen).?); }
src/main.zig
const std = @import("std"); const sqlite = @import("sqlite"); const manage_main = @import("main.zig"); const Context = manage_main.Context; const tunez = @import("tunez"); const libpcre = @import("libpcre"); const log = std.log.scoped(.ainclude); const VERSION = "0.0.1"; const HELPTEXT = \\ ainclude: include a file/folder into the awtfdb \\ \\ usage: \\ ainclude [options..] <file/folder path...> \\ \\ options: \\ -h prints this help and exits \\ -V prints version and exits \\ -v turns on verbosity (debug logging) \\ -t <tag>, --tag <tag> add the following tag to the given path \\ (if its a folder, add the tag to all files in the folder) \\ --infer-tags <inferrer> infer tags using a processor. \\ all tags after that argument shall be \\ processed using that inferrer's options, \\ if any of them don't match, then argument \\ processing comes back to normal options \\ (available processors: regex, audio, mime) \\ --filter-indexed-files-only only include files already indexed \\ (useful if you're moving files around \\ and they're not catched by the \\ rename watcher) \\ --dry-run do not do any index file modifications \\ \\ example, adding a single file: \\ ainclude --tag format:mp4 --tag "meme:what the dog doing" /downloads/funny_meme.mp4 \\ \\ example, adding a batch of files: \\ ainclude --tag format:mp4 --tag "meme:what the dog doing" /downloads/funny_meme.mp4 /download/another_dog_meme.mp4 /downloads/butter_dog.mp4 \\ \\ example, adding a media library: \\ ainclude --tag type:music --infer-tags media /my/music/collection \\ \\ regex tag inferrer: \\ runs a regex over the filename of each included file and adds every \\ match as a tag for that file in the index. \\ \\ every match group in the regex will be processed as a new tag \\ \\ regex tag inferrer options: \\ --regex text the regex to use (PCRE syntax) \\ --regex-use-full-path if we should infer tags from the entire \\ path, instead of only the filename \\ --regex-text-scope scope the tag scope to use (say, "mytag:") \\ --regex-cast-lowercase if the content of the tag should be \\ converted to lowercase before adding it \\ \\ example, using regex to infer tags based on filenames with "[tag]" as tags: \\ ainclude --infer-tags regex --regex '\[(.*?)\]' /my/movies/collection ; fn utilAddScope(maybe_tag_scope: ?[]const u8, out: *std.ArrayList(u8).Writer) !usize { if (maybe_tag_scope) |tag_scope| { return try out.write(tag_scope); } else { return 0; } } fn utilAddRawTag(config: anytype, raw_tag_text: []const u8, out: *std.ArrayList(u8).Writer) !usize { if (config.cast_lowercase) { for (raw_tag_text) |raw_tag_character| { const written = try out.write( &[_]u8{std.ascii.toLower(raw_tag_character)}, ); std.debug.assert(written == 1); } } else { const written = try out.write(raw_tag_text); std.debug.assert(written == raw_tag_text.len); } return raw_tag_text.len; } fn utilAddTag( allocator: std.mem.Allocator, config: anytype, maybe_raw_tag: ?[]const u8, maybe_tag_scope: ?[]const u8, output_tags_list: *std.ArrayList([]const u8), ) !void { var list = std.ArrayList(u8).init(allocator); defer list.deinit(); if (maybe_raw_tag) |raw_tag| { _ = try utilAddScope(maybe_tag_scope, &list.writer()); _ = try utilAddRawTag(config, raw_tag, &list.writer()); try output_tags_list.append( list.toOwnedSlice(), ); } } const TestUtil = struct { pub fn runTestInferrerFile( allocator: std.mem.Allocator, filename: []const u8, test_vector_bytes: []const u8, comptime InferrerType: type, first_args: anytype, ctx: *Context, wanted_tags: anytype, ) !void { var tmp = std.testing.tmpDir(.{}); defer tmp.cleanup(); var file = try tmp.dir.createFile(filename, .{}); defer file.close(); const written_bytes = try file.write(test_vector_bytes); std.debug.assert(written_bytes == test_vector_bytes.len); var indexed_file = try ctx.createFileFromDir(tmp.dir, filename); defer indexed_file.deinit(); const hashlist = try indexed_file.fetchTags(allocator); defer allocator.free(hashlist); try std.testing.expectEqual(@as(usize, 0), hashlist.len); var tags_to_add = std.ArrayList([]const u8).init(allocator); defer { for (tags_to_add.items) |tag| allocator.free(tag); tags_to_add.deinit(); } // actually run inferrer try @call(.{}, InferrerType.run, first_args ++ .{ &indexed_file, &tags_to_add }); try addTagList(ctx, &indexed_file, tags_to_add); const hashlist_after = try indexed_file.fetchTags(allocator); defer allocator.free(hashlist_after); var found_tags: [wanted_tags.len]bool = undefined; // initialize for (found_tags) |_, idx| found_tags[idx] = false; for (hashlist_after) |tag_core| { const tag_list = try ctx.fetchTagsFromCore(allocator, tag_core); defer tag_list.deinit(); try std.testing.expectEqual(@as(usize, 1), tag_list.items.len); const tag = tag_list.items[0]; try std.testing.expectEqual(tag_core.id, tag.core.id); inline for (wanted_tags) |wanted_tag, index| { if (std.mem.eql(u8, wanted_tag, tag.kind.Named.text)) { found_tags[index] = true; } } } // assert its all true for (found_tags) |value, index| { if (!value) { log.err("tag on index {d} not found", .{index}); for (tags_to_add.items) |tag| { log.err("given tag {s}", .{tag}); } return error.TestUnexpectedResult; } } try std.testing.expectEqual(@as(usize, wanted_tags.len), hashlist_after.len); try std.testing.expectEqual(@as(usize, wanted_tags.len), tags_to_add.items.len); } }; const TagInferrer = enum { regex, audio, mime, }; const TagInferrerConfig = struct { last_argument: []const u8, config: union(TagInferrer) { regex: RegexTagInferrer.Config, audio: AudioMetadataTagInferrer.Config, mime: MimeTagInferrer.Config, }, }; const TagInferrerContext = union(TagInferrer) { regex: RegexTagInferrer.RunContext, audio: AudioMetadataTagInferrer.RunContext, mime: MimeTagInferrer.RunContext, }; const RegexTagInferrer = struct { pub const Config = struct { text: ?[]const u8 = null, use_full_path: bool = false, tag_scope: ?[]const u8 = null, cast_lowercase: bool = false, }; pub const RunContext = struct { allocator: std.mem.Allocator, config: Config, regex_cstr: [:0]const u8, regex: libpcre.Regex, }; pub fn consumeArguments(args_it: *std.process.ArgIterator) !TagInferrerConfig { var arg_state: enum { None, Text, TagScope } = .None; var config: TagInferrerConfig = .{ .last_argument = undefined, .config = .{ .regex = .{} } }; var arg: []const u8 = undefined; while (args_it.next()) |arg_from_loop| { arg = arg_from_loop; log.debug("(regex tag inferrer) state: {} arg: {s}", .{ arg_state, arg }); switch (arg_state) { .None => {}, .Text => config.config.regex.text = arg, .TagScope => config.config.regex.tag_scope = arg, } // if we hit non-None states, we need to know if we're going // to have another configuration parameter or not // // and we do this by next()'ing into the next argument if (arg_state != .None) { arg = args_it.next() orelse break; arg_state = .None; } log.debug("(regex tag inferrer, main loop) state: {s} arg: {s}", .{ arg_state, arg }); if (std.mem.eql(u8, arg, "--regex")) { arg_state = .Text; } else if (std.mem.eql(u8, arg, "--regex-text-scope")) { arg_state = .TagScope; } else if (std.mem.eql(u8, arg, "--regex-cast-lowercase")) { config.config.regex.cast_lowercase = true; } else if (std.mem.eql(u8, arg, "--regex-use-full-path")) { config.config.regex.use_full_path = true; } else { config.last_argument = arg; break; } } if (config.config.regex.text == null) return error.RegexArgumentRequired; return config; } pub fn init(config: TagInferrerConfig, allocator: std.mem.Allocator) !RunContext { const regex_config = config.config.regex; const regex_cstr = try std.cstr.addNullByte(allocator, regex_config.text.?); return RunContext{ .allocator = allocator, .config = regex_config, .regex_cstr = regex_cstr, .regex = try libpcre.Regex.compile(regex_cstr, .{}), }; } pub fn deinit(self: *RunContext) void { self.allocator.free(self.regex_cstr); } pub fn run( self: *RunContext, file: *const Context.File, tags_to_add: *std.ArrayList([]const u8), ) !void { const basename = if (self.config.use_full_path) file.local_path else std.fs.path.basename(file.local_path); var offset: usize = 0; while (true) { var maybe_captures = try self.regex.captures(self.allocator, basename[offset..], .{}); if (maybe_captures) |captures| { defer self.allocator.free(captures); const full_match = captures[0].?; for (captures[1..]) |capture| { const tag_group = capture.?; const raw_tag_text = basename[offset + tag_group.start .. offset + tag_group.end]; var tag_text_list = std.ArrayList(u8).init(self.allocator); defer tag_text_list.deinit(); _ = try utilAddScope(self.config.tag_scope, &tag_text_list.writer()); _ = try utilAddRawTag(self.config, raw_tag_text, &tag_text_list.writer()); try tags_to_add.append(tag_text_list.toOwnedSlice()); } offset += full_match.end; } else { break; } } } }; test "regex tag inferrer" { var ctx = try manage_main.makeTestContext(); defer ctx.deinit(); // setup regex inferrer const regex_config = RegexTagInferrer.Config{ .text = "\\[(.*?)\\]", }; const allocator = std.testing.allocator; var context = try RegexTagInferrer.init( .{ .last_argument = undefined, .config = .{ .regex = regex_config } }, allocator, ); defer RegexTagInferrer.deinit(&context); try TestUtil.runTestInferrerFile( allocator, "test_[tag3] file [tag1] [tag2][tag4]", "awooga", RegexTagInferrer, .{&context}, &ctx, .{ "tag1", "tag2", "tag3", "tag4" }, ); } const AudioMetadataTagInferrer = struct { pub const Config = struct { tag_scope_album: ?[]const u8 = null, tag_scope_artist: ?[]const u8 = null, tag_scope_title: ?[]const u8 = null, cast_lowercase: bool = false, }; pub const RunContext = struct { allocator: std.mem.Allocator, config: Config, }; pub fn consumeArguments(args_it: *std.process.ArgIterator) !TagInferrerConfig { var arg_state: enum { None, AlbumTagScope, ArtistTagScope, TitleTagScope } = .None; var config: TagInferrerConfig = .{ .last_argument = undefined, .config = .{ .audio = .{} }, }; var arg: []const u8 = undefined; while (args_it.next()) |arg_from_loop| { arg = arg_from_loop; log.debug("(audio tag inferrer) state: {} arg: {s}", .{ arg_state, arg }); switch (arg_state) { .None => {}, .AlbumTagScope => config.config.audio.tag_scope_album = arg, .ArtistTagScope => config.config.audio.tag_scope_artist = arg, .TitleTagScope => config.config.audio.tag_scope_title = arg, } // if we hit non-None states, we need to know if we're going // to have another configuration parameter or not // // and we do this by next()'ing into the next argument if (arg_state != .None) { arg = args_it.next() orelse break; arg_state = .None; } log.debug("(audio tag inferrer, main loop) state: {s} arg: {s}", .{ arg_state, arg }); if (std.mem.eql(u8, arg, "--artist-tag-scope")) { arg_state = .ArtistTagScope; } else if (std.mem.eql(u8, arg, "--album-tag-scope")) { arg_state = .AlbumTagScope; } else if (std.mem.eql(u8, arg, "--title-tag-scope")) { arg_state = .TitleTagScope; } else if (std.mem.eql(u8, arg, "--cast-lowercase")) { config.config.regex.cast_lowercase = true; } else { config.last_argument = arg; break; } } return config; } pub fn init(config: TagInferrerConfig, allocator: std.mem.Allocator) !RunContext { return RunContext{ .allocator = allocator, .config = config.config.audio, }; } pub fn deinit(self: *RunContext) void { _ = self; } pub fn run( self: *RunContext, file: *const Context.File, tags_to_add: *std.ArrayList([]const u8), ) !void { const extension = std.fs.path.extension(file.local_path); const is_mp3 = std.mem.eql(u8, extension, ".mp3"); const is_flac = std.mem.eql(u8, extension, ".flac"); if (!is_mp3 and !is_flac) { log.err( "file {s} is not mp3 or flac (extension '{s}'), please exclude from paths", .{ file.local_path, extension }, ); return error.InvalidAudioFile; } var file_fd = try std.fs.cwd().openFile(file.local_path, .{ .mode = .read_only }); defer file_fd.close(); var buffered_reader = std.io.bufferedReader(file_fd.reader()); var audio_meta = if (is_mp3) try tunez.resolveId3(buffered_reader.reader(), self.allocator) else if (is_flac) try tunez.resolveFlac(buffered_reader.reader(), self.allocator) else unreachable; defer audio_meta.deinit(); try utilAddTag( self.allocator, self.config, audio_meta.maybe_track_album, self.config.tag_scope_album, tags_to_add, ); try utilAddTag( self.allocator, self.config, audio_meta.maybe_track_title, self.config.tag_scope_title, tags_to_add, ); if (audio_meta.maybe_track_artists) |artists| { for (artists) |artist_name| { try utilAddTag( self.allocator, self.config, artist_name, self.config.tag_scope_artist, tags_to_add, ); } } } }; const AUDIO_TEST_VECTORS = .{ "test_vectors/audio_test_vector.mp3", }; test "audio tag inferrer" { var ctx = try manage_main.makeTestContext(); defer ctx.deinit(); inline for (AUDIO_TEST_VECTORS) |test_vector_path| { std.log.warn("testing {s}", .{test_vector_path}); const test_vector_bytes = @embedFile(test_vector_path); // setup audio inferrer const config = AudioMetadataTagInferrer.Config{ .tag_scope_album = "album:", .tag_scope_artist = "artist:", .tag_scope_title = "title:", }; const allocator = std.testing.allocator; var context = try AudioMetadataTagInferrer.init( .{ .last_argument = undefined, .config = .{ .audio = config } }, allocator, ); defer AudioMetadataTagInferrer.deinit(&context); // setup test file try TestUtil.runTestInferrerFile( allocator, "test.mp3", test_vector_bytes, AudioMetadataTagInferrer, .{&context}, &ctx, .{ "artist:Test Artist", "album:Test Album", "title:Test Track" }, ); } } const c = @cImport({ @cInclude("magic.h"); }); const MimeCookie = struct { cookie: c.magic_t, const Self = @This(); const POSSIBLE_MAGICDB_PREFIXES = [_][:0]const u8{ "/usr/share/misc", "/usr/local/share/misc", "/etc", }; pub fn init(allocator: std.mem.Allocator) !Self { var cookie = c.magic_open( c.MAGIC_MIME_TYPE | c.MAGIC_CHECK | c.MAGIC_SYMLINK | c.MAGIC_ERROR, ) orelse return error.MagicCookieFail; // this attempts to find the path for the magic db file dynamically // through some paths i have found around the systems i have. // // libmagic's build process enables you to override the default // path to the magic file, which means that doing a static build of it // means it won't work on a separate system since it doesn't have // that one hardcoded in. // // a future iteration might bundle the magic database with the // executable through possibly, @embedFile, then dump that into a // temporary file for super compatibility with windows and macos var found_prefix: ?usize = null; for (POSSIBLE_MAGICDB_PREFIXES) |prefix, prefix_index| { var dir = std.fs.cwd().openDir(prefix, .{}) catch |err| switch (err) { error.FileNotFound, error.NotDir => continue, else => return err, }; defer dir.close(); var magic_file = dir.openFile("magic.mgc", .{}) catch |err| switch (err) { error.FileNotFound => continue, else => return err, }; defer magic_file.close(); // we have a magic_file found_prefix = prefix_index; break; } const magicdb_prefix = POSSIBLE_MAGICDB_PREFIXES[ found_prefix orelse { log.err("failed to locate magic file", .{}); return error.MagicNotFound; } ]; const magicdb_path = try std.fmt.allocPrint(allocator, "{s}/magic", .{magicdb_prefix}); defer allocator.free(magicdb_path); const path_cstr = try std.cstr.addNullByte(allocator, magicdb_path); defer allocator.free(path_cstr); log.info("loading magic file at prefix {s}", .{path_cstr}); if (c.magic_load(cookie, path_cstr) == -1) { const magic_error_value = c.magic_error(cookie); log.err("failed to load magic file: {s}", .{magic_error_value}); return error.MagicFileFail; } if (c.magic_check(cookie, path_cstr) == -1) { const magic_error_value = c.magic_error(cookie); log.err("failed to check magic file: {s}", .{magic_error_value}); return error.MagicFileFail; } return MimeCookie{ .cookie = cookie }; } pub fn deinit(self: Self) void { c.magic_close(self.cookie); } pub fn inferFile(self: Self, path: [:0]const u8) ![]const u8 { const mimetype = c.magic_file(self.cookie, path) orelse { const magic_error_value = c.magic_error(self.cookie); log.err("failed to infer mimetype: {s}", .{magic_error_value}); return error.MimetypeFail; }; return std.mem.span(mimetype); } }; const MimeTagInferrer = struct { pub const Config = struct { tag_scope_mimetype: ?[]const u8 = null, tag_for_all_images: ?[]const u8 = null, tag_for_all_audio: ?[]const u8 = null, tag_for_all_video: ?[]const u8 = null, cast_lowercase: bool = true, }; pub const RunContext = struct { allocator: std.mem.Allocator, cookie: MimeCookie, config: Config, }; pub fn consumeArguments(args_it: *std.process.ArgIterator) !TagInferrerConfig { var arg_state: enum { None, TagScopeMimetype, TagImage, TagAudio, TagVideo } = .None; var config: TagInferrerConfig = .{ .last_argument = undefined, .config = .{ .mime = .{} }, }; var arg: []const u8 = undefined; while (args_it.next()) |arg_from_loop| { arg = arg_from_loop; log.debug("(mime tag inferrer) state: {} arg: {s}", .{ arg_state, arg }); switch (arg_state) { .None => {}, .TagScopeMimetype => config.config.mime.tag_scope_mimetype = arg, .TagAudio => config.config.mime.tag_for_all_audio = arg, .TagVideo => config.config.mime.tag_for_all_video = arg, .TagImage => config.config.mime.tag_for_all_images = arg, } // if we hit non-None states, we need to know if we're going // to have another configuration parameter or not // // and we do this by next()'ing into the next argument if (arg_state != .None) { arg = args_it.next() orelse break; arg_state = .None; } log.debug("(mime tag inferrer, main loop) state: {s} arg: {s}", .{ arg_state, arg }); if (std.mem.eql(u8, arg, "--mime-tag-scope")) { arg_state = .TagScopeMimetype; } else if (std.mem.eql(u8, arg, "--image-tag")) { arg_state = .TagImage; } else if (std.mem.eql(u8, arg, "--audio-tag")) { arg_state = .TagAudio; } else if (std.mem.eql(u8, arg, "--video-tag")) { arg_state = .TagVideo; } else { config.last_argument = arg; break; } } return config; } pub fn init(config: TagInferrerConfig, allocator: std.mem.Allocator) !RunContext { std.debug.assert(c.MAGIC_VERSION == c.magic_version()); log.debug("version: {d}", .{c.magic_version()}); return RunContext{ .allocator = allocator, .cookie = try MimeCookie.init(allocator), .config = config.config.mime, }; } pub fn deinit(self: *RunContext) void { self.cookie.deinit(); } pub fn run( self: *RunContext, file: *const Context.File, tags_to_add: *std.ArrayList([]const u8), ) !void { _ = self; _ = tags_to_add; const path_cstr = try std.cstr.addNullByte(self.allocator, file.local_path); defer self.allocator.free(path_cstr); var mimetype = try self.cookie.inferFile(path_cstr); log.debug("mime: {s}", .{mimetype}); if (self.config.tag_scope_mimetype != null) { try utilAddTag( self.allocator, self.config, mimetype, self.config.tag_scope_mimetype, tags_to_add, ); } if (std.mem.startsWith(u8, mimetype, "image/")) { try utilAddTag( self.allocator, self.config, self.config.tag_for_all_images, null, tags_to_add, ); } if (std.mem.startsWith(u8, mimetype, "audio/")) { try utilAddTag( self.allocator, self.config, self.config.tag_for_all_audio, null, tags_to_add, ); } if (std.mem.startsWith(u8, mimetype, "video/")) { try utilAddTag( self.allocator, self.config, self.config.tag_for_all_video, null, tags_to_add, ); } } }; test "mime tag inferrer" { var ctx = try manage_main.makeTestContext(); defer ctx.deinit(); const test_vector_bytes = @embedFile("./test_vectors/audio_test_vector.mp3"); const config = MimeTagInferrer.Config{ .tag_scope_mimetype = "mime:", .tag_for_all_audio = "funky", }; const allocator = std.testing.allocator; var context = try MimeTagInferrer.init( .{ .last_argument = undefined, .config = .{ .mime = config } }, allocator, ); defer MimeTagInferrer.deinit(&context); try TestUtil.runTestInferrerFile( allocator, "test.mp3", test_vector_bytes, MimeTagInferrer, .{&context}, &ctx, .{ "mime:audio/mpeg", "funky" }, ); } const StringList = std.ArrayList([]const u8); const ConfigList = std.ArrayList(TagInferrerConfig); pub const Args = struct { help: bool = false, verbose: bool = false, version: bool = false, filter_indexed_files_only: bool = false, dry_run: bool = false, default_tags: StringList, wanted_inferrers: ConfigList, include_paths: StringList, pub fn deinit(self: *@This()) void { self.default_tags.deinit(); self.wanted_inferrers.deinit(); self.include_paths.deinit(); } }; fn addTagList( ctx: *Context, file: *Context.File, tags_to_add: std.ArrayList([]const u8), ) !void { for (tags_to_add.items) |named_tag_text| { log.info("adding tag {s}", .{named_tag_text}); var maybe_tag = try ctx.fetchNamedTag(named_tag_text, "en"); if (maybe_tag) |tag| { try file.addTag(tag.core); } else { var tag = try ctx.createNamedTag(named_tag_text, "en", null); try file.addTag(tag.core); } } } pub fn main() anyerror!void { const rc = sqlite.c.sqlite3_config(sqlite.c.SQLITE_CONFIG_LOG, manage_main.sqliteLog, @as(?*anyopaque, null)); if (rc != sqlite.c.SQLITE_OK) { std.log.err("failed to configure: {d} '{s}'", .{ rc, sqlite.c.sqlite3_errstr(rc), }); return error.ConfigFail; } var gpa = std.heap.GeneralPurposeAllocator(.{}){}; defer _ = gpa.deinit(); var allocator = gpa.allocator(); var args_it = std.process.args(); _ = args_it.skip(); const ArgState = enum { None, FetchTag, InferMoreTags }; var state: ArgState = .None; var given_args = Args{ .default_tags = StringList.init(allocator), .wanted_inferrers = ConfigList.init(allocator), .include_paths = StringList.init(allocator), }; defer given_args.deinit(); var arg: []const u8 = undefined; while (args_it.next()) |arg_from_loop| { arg = arg_from_loop; log.debug("state: {s} arg: {s}", .{ state, arg }); switch (state) { .FetchTag => { try given_args.default_tags.append(arg); state = .None; continue; }, .InferMoreTags => { const tag_inferrer = std.meta.stringToEnum(TagInferrer, arg) orelse return error.InvalidTagInferrer; var inferrer_config = switch (tag_inferrer) { .regex => try RegexTagInferrer.consumeArguments(&args_it), .audio => try AudioMetadataTagInferrer.consumeArguments(&args_it), .mime => try MimeTagInferrer.consumeArguments(&args_it), }; try given_args.wanted_inferrers.append(inferrer_config); arg = inferrer_config.last_argument; state = .None; }, .None => {}, } log.debug("(possible transition) state: {s} arg: {s}", .{ state, arg }); if (std.mem.eql(u8, arg, "-h")) { given_args.help = true; } else if (std.mem.eql(u8, arg, "-v")) { given_args.verbose = true; } else if (std.mem.eql(u8, arg, "-V")) { given_args.version = true; } else if (std.mem.eql(u8, arg, "--filter-indexed-files-only")) { given_args.filter_indexed_files_only = true; } else if (std.mem.eql(u8, arg, "--dry-run")) { given_args.dry_run = true; } else if (std.mem.eql(u8, arg, "--tag") or std.mem.eql(u8, arg, "-t")) { state = .FetchTag; // tag inferrers require more than one arg, so we need to load // those args beforehand and then pass the arg state forward } else if (std.mem.eql(u8, arg, "--infer-tags")) { state = .InferMoreTags; // TODO check if this is supposed to be an argument or an // actual option by peeking over args_it. paths can have -- // after all. } else if (std.mem.startsWith(u8, arg, "--")) { return error.InvalidArgument; } else { try given_args.include_paths.append(arg); } } if (given_args.help) { std.debug.print(HELPTEXT, .{}); return; } else if (given_args.version) { std.debug.print("ainclude {s}\n", .{VERSION}); return; } if (given_args.verbose) { std.debug.todo("aa"); } if (given_args.include_paths.items.len == 0) { std.log.err("at least one include path needs to be given", .{}); return error.MissingArgument; } var ctx = Context{ .home_path = null, .args_it = undefined, .stdout = undefined, .db = null, .allocator = allocator, }; defer ctx.deinit(); try ctx.loadDatabase(.{}); if (given_args.dry_run) try ctx.turnIntoMemoryDb(); std.log.info("args: {}", .{given_args}); // map tag names to their relevant cores in db var default_tag_cores = Context.HashList.init(allocator); defer default_tag_cores.deinit(); for (given_args.default_tags.items) |named_tag_text| { const maybe_tag = try ctx.fetchNamedTag(named_tag_text, "en"); if (maybe_tag) |tag| { log.debug( "tag '{s}' is core {s}", .{ named_tag_text, tag.core }, ); try default_tag_cores.append(tag.core); } else { // TODO support ISO 639-2 var new_tag = try ctx.createNamedTag(named_tag_text, "en", null); log.debug( "(created!) tag '{s}' with core {s}", .{ named_tag_text, new_tag.core }, ); try default_tag_cores.append(new_tag.core); } } var contexts = std.ArrayList(TagInferrerContext).init(allocator); defer contexts.deinit(); for (given_args.wanted_inferrers.items) |inferrer_config| { switch (inferrer_config.config) { .regex => try contexts.append(.{ .regex = try RegexTagInferrer.init(inferrer_config, allocator) }), .audio => try contexts.append(.{ .audio = try AudioMetadataTagInferrer.init(inferrer_config, allocator) }), .mime => try contexts.append(.{ .mime = try MimeTagInferrer.init(inferrer_config, allocator) }), } } defer for (contexts.items) |*context| switch (context.*) { .regex => |*regex_ctx| RegexTagInferrer.deinit(regex_ctx), .audio => |*audio_ctx| AudioMetadataTagInferrer.deinit(audio_ctx), .mime => |*mime_ctx| MimeTagInferrer.deinit(mime_ctx), }; for (given_args.include_paths.items) |path_to_include| { var dir: ?std.fs.Dir = std.fs.cwd().openDir(path_to_include, .{ .iterate = true }) catch |err| blk: { if (err == error.NotDir) break :blk null; log.err("error while including path '{s}': {s}", .{ path_to_include, @errorName(err) }); return err; }; defer if (dir) |*unpacked_dir| unpacked_dir.close(); if (dir == null) { if (given_args.filter_indexed_files_only) std.debug.todo("TODO support filter_indexed_files_only on file paths"); var file = try ctx.createFileFromPath(path_to_include); defer file.deinit(); log.debug("adding file '{s}'", .{file.local_path}); var savepoint = try ctx.db.?.savepoint("tags"); errdefer savepoint.rollback(); defer savepoint.commit(); for (default_tag_cores.items) |tag_core| { try file.addTag(tag_core); } var tags_to_add = std.ArrayList([]const u8).init(allocator); defer { for (tags_to_add.items) |tag| allocator.free(tag); tags_to_add.deinit(); } for (given_args.wanted_inferrers.items) |inferrer_config, index| { log.info("found config for {}", .{inferrer_config}); var inferrer_ctx = &contexts.items[index]; switch (inferrer_ctx.*) { .regex => |*regex_ctx| try RegexTagInferrer.run(regex_ctx, &file, &tags_to_add), .audio => |*audio_ctx| try AudioMetadataTagInferrer.run(audio_ctx, &file, &tags_to_add), .mime => |*mime_ctx| try MimeTagInferrer.run(mime_ctx, &file, &tags_to_add), } } try addTagList(&ctx, &file, tags_to_add); } else { var walker = try dir.?.walk(allocator); defer walker.deinit(); while (try walker.next()) |entry| { switch (entry.kind) { .File, .SymLink => { log.debug( "adding child path '{s}{s}{s}'", .{ path_to_include, std.fs.path.sep_str, entry.path }, ); // if we only want to reindex files already in // the system, hash them first and try to fetch the file // if it exists, move forward, if not, skip that file if (given_args.filter_indexed_files_only) { var fs_file = try entry.dir.openFile( entry.basename, .{ .mode = .read_only }, ); defer fs_file.close(); const hash = try ctx.calculateHash(fs_file, .{ .insert_new_hash = false }); log.debug("hash is {s}", .{hash}); const maybe_file = try ctx.fetchFileByHash(hash.hash_data); if (maybe_file) |file| { file.deinit(); } else { log.debug("skipping due to selected filter", .{}); continue; } } var file = try ctx.createFileFromDir(entry.dir, entry.basename); defer file.deinit(); { var savepoint = try ctx.db.?.savepoint("tags"); errdefer savepoint.rollback(); defer savepoint.commit(); var tags_to_add = std.ArrayList([]const u8).init(allocator); defer { for (tags_to_add.items) |tag| allocator.free(tag); tags_to_add.deinit(); } for (default_tag_cores.items) |tag_core| { try file.addTag(tag_core); } for (given_args.wanted_inferrers.items) |inferrer_config, index| { log.info("found config for {}", .{inferrer_config}); var inferrer_ctx = &contexts.items[index]; switch (inferrer_ctx.*) { .regex => |*regex_ctx| try RegexTagInferrer.run(regex_ctx, &file, &tags_to_add), .audio => |*audio_ctx| try AudioMetadataTagInferrer.run(audio_ctx, &file, &tags_to_add), .mime => |*mime_ctx| try MimeTagInferrer.run(mime_ctx, &file, &tags_to_add), } } try addTagList(&ctx, &file, tags_to_add); } }, else => {}, } } } } }
src/include_main.zig
const std = @import("std"); const DiagnosticTag = @import("Diagnostics.zig").Tag; const LangOpts = @This(); const Standard = enum { /// ISO C 1990 c89, /// ISO C 1990 with amendment 1 iso9899, /// ISO C 1990 with GNU extensions gnu89, /// ISO C 1999 c99, /// ISO C 1999 with GNU extensions gnu99, /// ISO C 2011 c11, /// ISO C 2011 with GNU extensions gnu11, /// ISO C 2017 c17, /// Default value if nothing specified; adds the GNU keywords to /// C17 but does not suppress warnings about using GNU extensions default, /// ISO C 2017 with GNU extensions gnu17, /// Working Draft for ISO C2x c2x, /// Working Draft for ISO C2x with GNU extensions gnu2x, const NameMap = std.ComptimeStringMap(Standard, .{ .{ "c89", .c89 }, .{ "c90", .c89 }, .{ "iso9899:1990", .c89 }, .{ "iso9899:199409", .iso9899}, .{ "gnu89", .gnu89 }, .{ "gnu90", .gnu89 }, .{ "c99", .c99 }, .{ "iso9899:1999", .c99 }, .{ "gnu99", .gnu99 }, .{ "c11", .c11 }, .{ "iso9899:2011", .c11 }, .{ "gnu11", .gnu11 }, .{ "c17", .c17 }, .{ "iso9899:2017", .c17 }, .{ "c18", .c17 }, .{ "iso9899:2018", .c17 }, .{ "gnu17", .gnu17 }, .{ "gnu18", .gnu17 }, .{ "c2x", .c2x }, .{ "gnu2x", .gnu2x }, }); pub fn atLeast(self: Standard, other: Standard) bool { return @enumToInt(self) >= @enumToInt(other); } pub fn isGNU(standard: Standard) bool { return switch (standard) { .gnu89, .gnu99, .gnu11, .default, .gnu17, .gnu2x => true, else => false, }; } pub fn isExplicitGNU(standard: Standard) bool { return standard.isGNU() and standard != .default; } }; standard: Standard = .default, pub fn setStandard(self: *LangOpts, name: []const u8) error{InvalidStandard}!void { self.standard = Standard.NameMap.get(name) orelse return error.InvalidStandard; } pub fn suppress(langopts: LangOpts, tag: DiagnosticTag) bool { return switch (tag) { .static_assert_missing_message => langopts.standard.atLeast(.c2x), .alignof_expr => langopts.standard.isExplicitGNU(), else => false, }; }
src/LangOpts.zig
const std = @import("std"); const learn = @import("learnBPE.zig"); const Allocator = std.mem.Allocator; const File = std.fs.File; const assert = std.debug.assert; const warn = std.debug.warn; const debug = std.debug.warn; const OutOfMemory = std.mem.Allocator.Error; pub fn applybpe(input: File, codes: File, vocab_path: []const u8, base_allocator: *Allocator) !void { var arena = std.heap.ArenaAllocator.init(base_allocator); defer arena.deinit(); var allocator = &arena.allocator; var applyer = try BPEApplyer.fromFile(codes, vocab_path, allocator); const buff: comptime usize = 8192; var line_buff: [buff]u8 = undefined; var result_buff = try std.ArrayList(u8).initCapacity(allocator, 2 * buff); const in_stream = std.io.bufferedInStream(input.inStream()).inStream(); const print = std.io.getStdOut().outStream().print; while (in_stream.readUntilDelimiterOrEof(&line_buff, '\n') catch |err| switch (err) { error.StreamTooLong => blk: { // Line is longer than buf size, skip it. // TODO: treat the buffer as a sentence try in_stream.skipUntilDelimiterOrEof('\n'); break :blk &line_buff; }, else => { warn("I/O error while reading {}", .{input}); return err; }, }) |line| { try print("{}\n", .{applyer.applySentence(line, &result_buff)}); // doesn't change underlying memory, but reset the write pointer. result_buff.items.len = 0; } } const eqlString = std.hash_map.eqlString; const WordPair = struct { left: []const u8, right: []const u8, fn eql(a: WordPair, b: WordPair) bool { return eqlString(a.left, b.left) and eqlString(a.right, b.right); } fn hash(a: WordPair) u64 { const hashString = std.hash_map.hashString; var h1 = hashString(a.left); var h2 = hashString(a.right); // boost::hash_combine return h2 +% 0x9e3779b9 +% (h1 << 6) +% (h1 >> 2); } }; export fn ctypes_bpe(codes_file: [*:0]const u8) ?*BPEApplyer { const allocator = std.heap.c_allocator; var buf: [std.fs.MAX_PATH_BYTES]u8 = undefined; var realpath = std.os.realpathZ(codes_file, &buf) catch |err| { warn("Failed to resolve code file '{}': {}\n", .{ codes_file, err }); return null; }; const file = std.mem.dupe(allocator, u8, realpath) catch |err| { warn("Failed to copy filename '{}': {}\n", .{ realpath, err }); return null; }; defer allocator.free(file); const handle = std.fs.openFileAbsolute(file, .{ .read = true }) catch |e| { warn("Error '{}' when opening {}\n", .{ e, file }); return null; }; const codes = readCodes(handle, allocator) catch |err| { warn("Error when reading codes from {}: {}\n", .{ file, err }); return null; }; var applier = BPEApplyer.init(codes, allocator) catch |err| { warn("Not enough memory: {}\n", .{err}); return null; }; var heap_bpe: *BPEApplyer = allocator.create(BPEApplyer) catch |err| { warn("Not enough memory: {}\n", .{err}); return null; }; heap_bpe.* = applier; return heap_bpe; } export fn ctypes_learnbpe(n_pairs: i32, inputFile1: [*:0]const u8) void { const allocator = std.heap.c_allocator; var buf: [std.fs.MAX_PATH_BYTES]u8 = undefined; var realpath = std.os.realpathZ(inputFile1, &buf) catch |err| { warn("Failed to resolve code file '{}': {}\n", .{ inputFile1, err }); return; }; const file = std.mem.dupe(allocator, u8, realpath) catch |err| { warn("Failed to copy filename '{}': {}\n", .{ realpath, err }); return; }; defer allocator.free(file); learn.learnbpe(n_pairs, file, "", allocator) catch unreachable; } var ctypes_output_buffer: std.ArrayList(u8) = undefined; export fn ctypes_apply_sentence(bpe: *BPEApplyer, sentence: [*]const u8, sentence_len: usize, out: [*]u8) usize { // Ensure the sentence isn't too big for the buffer. assert(sentence_len < 2048); ctypes_output_buffer.capacity = 4096; ctypes_output_buffer.items.len = 0; ctypes_output_buffer.items.ptr = out; var res = bpe.applySentence(sentence[0..sentence_len], &ctypes_output_buffer); return res.len; } const Codes = std.HashMap(WordPair, u32, WordPair.hash, WordPair.eql, std.hash_map.DefaultMaxLoadPercentage); const BPEApplyer = struct { /// Class to apply BPE to text. /// Pass by pointer: this struct is very wide because it contains buffers for the conversion. /// Not thread safe. Several applier can safely share the same codes. codes: Codes, // TODO: decide if we keep vocab. // vocab: learn.Vocab, _word_buffer: [512]u8, _subwords: [2]std.ArrayList([]const u8), fn init(codes: Codes, allocator: *Allocator) OutOfMemory!BPEApplyer { var applier = BPEApplyer{ .codes = codes, ._word_buffer = undefined, ._subwords = [_]std.ArrayList([]const u8){ undefined, } ** 2, }; var buff = &applier._word_buffer; std.mem.copy(u8, buff[buff.len - learn.kEndWord.len ..], learn.kEndWord); for (applier._subwords) |*buffer| { buffer.* = try std.ArrayList([]const u8).initCapacity(allocator, 512); } return applier; } fn fromFile(codes_file: File, vocab_path: []const u8, allocator: *Allocator) !BPEApplyer { var codes = try readCodes(codes_file, allocator); return try BPEApplyer.init(codes, allocator); } fn applySentence(self: *BPEApplyer, sentence: []const u8, out: *std.ArrayList(u8)) []const u8 { // debug("Sentence: {}\n", .{sentence}); const start = out.items.len; if (sentence.len == 0) return out.items[start..]; var it = std.mem.split(sentence, " "); if (it.next()) |word| { _ = self.applyWord(word, out); } while (it.next()) |word| { out.appendAssumeCapacity(' '); _ = self.applyWord(word, out); } return out.items[start..]; } inline fn add_endword(self: *BPEApplyer, word: []const u8) []const u8 { const off = self._word_buffer.len - learn.kEndWord.len - word.len; var word_with_endword = self._word_buffer[off..]; std.mem.copy(u8, word_with_endword, word); return word_with_endword; } /// Compute BPE for given words. Result is copied to "out". fn applyWord(self: *BPEApplyer, _word: []const u8, out: *std.ArrayList(u8)) []const u8 { // reset subwords buffer for (self._subwords) |*sw| sw.*.items.len = 0; var subwords = &self._subwords[0]; var new_subwords = &self._subwords[1]; var start = out.items.len; const word = self.add_endword(_word); // split the word into UTF8 chars var last_start: usize = 0; // TODO: try std.unicode.Utf8Iterator for (word) |char, pos| { if (pos == 0) continue; if (pos >= word.len - learn.kEndWord.len) { break; } if ((char & 0xc0) == 0x80) // continuation byte continue; var new_token = word[last_start..pos]; subwords.appendAssumeCapacity(new_token); last_start = pos; } var last_word_len = word.len - last_start; subwords.appendAssumeCapacity(word[last_start..]); // debug_subwords("Initial state", subwords.*); while (subwords.items.len > 1) { // find the best pair var best_pair_pos: i32 = -1; var best_pair: Codes.Entry = undefined; for (subwords.items[0 .. subwords.items.len - 1]) |sw, i| { if (self.codes.getEntry(.{ .left = sw, .right = subwords.items[i + 1] })) |pair| { var pair_rank = pair.value; if (pair_rank >= 0 and (best_pair_pos == -1 or best_pair.value > pair_rank)) { best_pair = pair.*; best_pair_pos = @intCast(i32, i); } } } // if we cannot merge anything, stop if (best_pair_pos == -1) { break; } // otherwise, merge subWords // do we need to iterate again across subwords ? var just_merged = false; var n = subwords.items.len; for (subwords.items) |left, i| { if ((i + 1 < n) and (!just_merged) and eqlString(left, best_pair.key.left) and eqlString(subwords.items[i + 1], best_pair.key.right)) { var right = subwords.items[i + 1]; // check that right is located next to left var concat: []const u8 = left.ptr[0 .. left.len + subwords.items[i + 1].len]; // debug("left '{}', right '{}' concat '{}'\n", .{ left, right, concat }); // debug("left ({}, {}), right ({}, {})\n", .{ left.ptr, left.len, right.ptr, right.len }); assert(eqlString(right, left.ptr[left.len .. left.len + right.len])); new_subwords.appendAssumeCapacity(concat); just_merged = true; } else { if (!just_merged) { new_subwords.appendAssumeCapacity(left); } just_merged = false; } } // Swap the two subwords buffer. var tmp_subwords = subwords; subwords = new_subwords; new_subwords = tmp_subwords; new_subwords.*.items.len = 0; // debug_subwords("iteration", subwords.*); } // TODO: is this feature used ? can't this be done by editing the codes file ? // check that we are only using words in the dictionary // if (vocab.size() > 0) { // limitVocab(subwords, new_subwords, reversed_codes, vocab); // subwords = new_subwords; // // TODO: reset new_subwords // } // concat subWords var n = subwords.items.len; for (subwords.items) |x, i| { if (i == n - 1) { // do not output EndWord markers. appendSliceAssumeCapacity(out, x[0 .. x.len - learn.kEndWord.len]); break; } appendSliceAssumeCapacity(out, x); appendSliceAssumeCapacity(out, learn.kTokenDelim); out.appendAssumeCapacity(' '); } return out.items[start..]; } fn deinit(self: *BPEApplyer) void { self.codes.deinit(); for (self._subwords) |*buffer| { buffer.deinit(); } } fn addPairOrCrash(self: *BPEApplyer, left: []const u8, right: []const u8) void { const pair = WordPair{ .left = left, .right = right }; assert(!self.codes.contains(pair)); _ = self.codes.put(pair, @intCast(u32, self.codes.count())) catch unreachable; } }; fn appendSliceAssumeCapacity(self: *std.ArrayList(u8), items: []const u8) void { const oldlen = self.items.len; const newlen = self.items.len + items.len; assert(self.capacity > newlen); self.items.len = newlen; std.mem.copy(u8, self.items[oldlen..], items); } fn str_copy(allocator: *Allocator, a: []const u8) ![]u8 { const result = try allocator.alloc(u8, a.len); std.mem.copy(u8, result, a); return result; } fn debug_subwords(label: []const u8, subwords: std.ArrayList([]const u8)) void { debug("{}: ", .{label}); for (subwords.items) |sw| { debug("{},", .{sw}); } debug("\n", .{}); } // warn("Loading codes from {} ...\n", .{fp}); fn readCodes(file: File, allocator: *Allocator) !Codes { var stream = std.io.bufferedInStream(file.inStream()).inStream(); var codes = Codes.init(allocator); var line_buf: [4096]u8 = undefined; var l: u32 = 1; while (stream.readUntilDelimiterOrEof(&line_buf, '\n') catch |err| switch (err) { error.StreamTooLong => blk: { // This looks like a crazy line warn("Skipping line {} which is too long: {}\n", .{ l, line_buf[0..80] }); try stream.skipUntilDelimiterOrEof('\n'); break :blk &line_buf; }, else => |e| return e, }) |line| { var it = std.mem.split(line, " "); // reset subwords const pair = WordPair{ .left = try str_copy(allocator, it.next().?), .right = try str_copy(allocator, it.next().?) }; const count = try std.fmt.parseInt(i32, it.next().?, 10); assert(it.next() == null); assert(!codes.contains(pair)); _ = try codes.put(pair, @intCast(u32, codes.count())); // string concat = splits[0] + splits[1]; // assert(reversed_codes.find(concat) == reversed_codes.end()); // reversed_codes[concat] = pair; l +%= 1; } warn("Read {} codes from the codes file.\n", .{codes.count()}); return codes; } fn assertEqlString(message: []const u8, actual: []const u8, expected: []const u8) void { const eq = eqlString(actual, expected); if (eq) return; warn("\n - {}: received '{}', expected: '{}'\n", .{ message, actual, expected }); if (actual.len != expected.len) { warn(" received len {}, expected len {}\n", .{ actual.len, expected.len }); assert(false); } for (expected) |char, i| { const actual_char = actual[i]; if (actual_char != char) { warn(" char mismatch at index {}: received '{}', expected '{}", .{ i, actual[i .. i + 1], expected[i .. i + 1] }); } } assert(eq); } test "apply word" { var allocator = std.testing.allocator; var codes = Codes.init(allocator); try codes.ensureCapacity(512); var bpe = try BPEApplyer.init(codes, allocator); defer bpe.deinit(); var out = try std.ArrayList(u8).initCapacity(allocator, 512); defer out.deinit(); assertEqlString( "codes=[]", bpe.applyWord("hello", &out), "h@@ e@@ l@@ l@@ o", ); bpe.addPairOrCrash("h", "e"); assertEqlString( "codes=[he]", bpe.applyWord("hello", &out), "he@@ l@@ l@@ o", ); bpe.addPairOrCrash("l", "l"); assertEqlString( "codes=[he, ll]", bpe.applyWord("hello", &out), "he@@ ll@@ o", ); bpe.addPairOrCrash("ll", "o</w>"); assertEqlString( "codes=[he, ll, llo]", bpe.applyWord("hello", &out), "he@@ llo", ); }
fastBPE/applyBPE.zig
const std = @import("std"); const log = std.log.scoped(.zben); const testing = std.testing; // Parser section pub const BencodeTypes = enum { String, Integer, List, Dictionary, }; const Dictionary = std.StringHashMap(Value); const List = std.ArrayList(Value); pub const Value = union(enum) { Empty: void, Integer: i64, String: []const u8, List: List, Dictionary: Dictionary, pub fn make_emtpy() Value { return .{ .Empty = .{}, }; } pub fn make_int(v: i64) Value { return .{ .Integer = v, }; } pub fn make_string(s: []const u8) Value { return .{ .String = s, }; } pub fn make_list(allocator: *std.mem.Allocator) Value { return .{ .List = List.init(allocator), }; } pub fn make_dict(allocator: *std.mem.Allocator) Value { return .{ .Dictionary = Dictionary.init(allocator), }; } fn maybe_deinit(self: *@This()) void { switch (self.*) { .Empty, .Integer, .String => {}, .List => |*l| l.deinit(), .Dictionary => |*d| d.deinit(), } } pub fn set_empty(self: *@This()) void { maybe_deinit(self); self.* = Value.make_emtpy(); } pub fn set_int(self: *@This(), v: i64) void { maybe_deinit(self); self.* = make_int(v); } pub fn set_string(self: *@This(), s: []const u8) void { maybe_deinit(self); self.* = make_string(s); } pub fn set_list(self: *@This(), alloc: *std.mem.Allocator) !void { maybe_deinit(self); self.* = make_list(alloc); } pub fn set_dict(self: *@This(), alloc: *std.mem.Allocator) !void { maybe_deinit(self); self.* = make_dict(alloc); } }; pub const BencodeTree = struct { arena: std.heap.ArenaAllocator, root: Value, pub fn init(allocator: *std.mem.Allocator) BencodeTree { return .{ .arena = std.heap.ArenaAllocator.init(allocator), .root = Value.make_emtpy(), }; } pub fn deinit(self: *@This()) void { self.arena.deinit(); } }; /// Parses a bencode string into a BencodeTree /// or returns a parsing error. /// This parser allocates memory though it will /// place the entire BencodeTree into an arena /// so the tree can be cleaned up properly. pub const Parser = struct { parser: ParserImpl, /// Construct a Parser with a backing allocator pub fn init(allocator: *std.mem.Allocator) @This() { return .{ .parser = ParserImpl.init(allocator), }; } /// Construct a parser with a backing allocator /// and the string to be parsed pub fn initWithData(allocator: *std.mem.Allocator, data: []const u8) @This() { return .{ .parser = ParserImpl.initWithData(allocator, data), }; } /// Release any resources acquired by the Parser pub fn deinit(self: *@This()) void { self.parser.deinit(); } /// Resets the parser state to init and the string to be parsed pub fn reset(self: *@This(), data: []const u8) void { self.parser.reset(data); } /// Attempt to parse the string pub fn parse(self: *@This()) !BencodeTree { return self.parser.parse(); } }; pub const BencodeTokens = enum { dictionary_begin, list_begin, integer_begin, integer, string_length, string_split, string, end, EOF, }; pub const Token = struct { token_type: BencodeTokens, data: []const u8, }; /// This tokenizer requires no memory allocation and does *not* /// take ownership of the given data /// All returned tokens are slices over the underlying data so users /// need to ensure the data won't go out of scope /// TODO: Make this work with streams rather than slices pub const Lexer = struct { lexer: LexerImpl, pub fn init() @This() { return .{ .lexer = LexerImpl.init(), }; } pub fn initWithData(data: []const u8) @This() { return .{ .lexer = LexerImpl.initWithData(data), }; } pub fn reset(self: *@This(), data: []const u8) void { self.lexer.reset(data); } pub fn next(self: *@This()) ?Token { return self.lexer.next(); } }; //////////////////////////////////////////////// // Implementations below /////////////////////// //////////////////////////////////////////////// const ParserImpl = struct { allocator: *std.mem.Allocator, lexer: Lexer, state: State, object_stack: std.ArrayList(ObjectType), value_stack: std.ArrayList(*Value), const State = enum { start, dict_key, dict_value, list_value, valid, }; /// Add to the stack since "end" is generic const ObjectType = enum { dictionary, list, integer, }; pub fn init(allocator: *std.mem.Allocator) @This() { return .{ .allocator = allocator, .lexer = Lexer.init(), .state = .start, .object_stack = std.ArrayList(ObjectType).init(allocator), .value_stack = std.ArrayList(*Value).init(allocator), }; } pub fn initWithData(allocator: *std.mem.Allocator, data: []const u8) @This() { return .{ .allocator = allocator, .lexer = Lexer.initWithData(data), .state = .start, .object_stack = std.ArrayList(ObjectType).init(allocator), .value_stack = std.ArrayList(*Value).init(allocator), }; } pub fn reset(self: *@This(), data: []const u8) void { self.state = .start; self.object_stack.resize(0); self.value_stack.resize(0); self.lexer.reset(data); } pub fn deinit(self: *@This()) void { self.object_stack.deinit(); self.value_stack.deinit(); } /// Turns the given data into a Tree of items pub fn parse(self: *@This()) !BencodeTree { var tree = BencodeTree{ .arena = std.heap.ArenaAllocator.init(self.allocator), .root = Value.make_emtpy(), }; const alloc = &tree.arena.allocator; errdefer tree.arena.deinit(); var current_dict_key: []const u8 = ""; while (self.lexer.next()) |token| { log.debug("Parsing token: {}", .{token}); switch (self.state) { .start => { switch (token.token_type) { .dictionary_begin => { try self.object_stack.append(.dictionary); try tree.root.set_dict(alloc); try self.value_stack.append(&tree.root); self.state = .dict_key; }, .list_begin => { try self.object_stack.append(.list); try tree.root.set_list(alloc); try self.value_stack.append(&tree.root); self.state = .list_value; }, .integer_begin => { const value: i64 = try parseInteger(token, &self.lexer); tree.root.set_int(value); self.state = .valid; }, .string_length => { const str = try parseString(token, &self.lexer); tree.root.set_string(try alloc.dupe(u8, str)); self.state = .valid; }, else => { return error.malformed_data; }, } }, .dict_key => { switch (token.token_type) { .string_length => { const cur_key = try parseString(token, &self.lexer); self.state = .dict_value; current_dict_key = cur_key; }, .end => { if (stackTop(self.object_stack.items).* != .dictionary) { return error.parse_error; } _ = self.object_stack.pop(); _ = self.value_stack.pop(); if (self.object_stack.items.len == 0) { std.debug.assert(self.value_stack.items.len == 0); self.state = .valid; } else { switch (stackTop(self.object_stack.items).*) { .dictionary => self.state = .dict_key, .list => self.state = .list_value, else => { return error.parse_error; }, } } }, else => return error.dictionary_key_not_string, } }, .dict_value => { switch (token.token_type) { .list_begin => { var dict_node = stackTop(self.value_stack.items).*; var entry = try dict_node.Dictionary.getOrPutValue(current_dict_key, Value.make_list(alloc)); try self.object_stack.append(.list); try self.value_stack.append(&entry.value); self.state = .list_value; }, .dictionary_begin => { var dict_node = stackTop(self.value_stack.items).*; var entry = try dict_node.Dictionary.getOrPutValue(current_dict_key, Value.make_dict(alloc)); try self.object_stack.append(.dictionary); try self.value_stack.append(&entry.value); self.state = .dict_key; }, .string_length => { const str = try parseString(token, &self.lexer); var dict_node = stackTop(self.value_stack.items).*; var entry = try dict_node.Dictionary.getOrPutValue(current_dict_key, Value.make_string(try alloc.dupe(u8, str))); self.state = .dict_key; }, .integer_begin => { const value: i64 = try parseInteger(token, &self.lexer); var dict_node = stackTop(self.value_stack.items).*; var entry = try dict_node.Dictionary.getOrPutValue(current_dict_key, Value.make_int(value)); self.state = .dict_key; }, else => return error.parse_error, } }, .list_value => { switch (token.token_type) { .end => { if (stackTop(self.object_stack.items).* != .list) { return error.parse_error; } _ = self.object_stack.pop(); _ = self.value_stack.pop(); if (self.object_stack.items.len == 0) { std.debug.assert(self.value_stack.items.len == 0); self.state = .valid; } else { switch (stackTop(self.object_stack.items).*) { .dictionary => self.state = .dict_key, .list => self.state = .list_value, else => { return error.parse_error; }, } } }, .integer_begin => { const value: i64 = try parseInteger(token, &self.lexer); var list_node = stackTop(self.value_stack.items).*; try list_node.List.append(Value.make_int(value)); }, .string_length => { const str = try parseString(token, &self.lexer); var list_node = stackTop(self.value_stack.items).*; try list_node.List.append(Value.make_string(try alloc.dupe(u8, str))); }, .list_begin => { try self.object_stack.append(.list); var list_node = stackTop(self.value_stack.items).*; try list_node.List.append(Value.make_list(alloc)); try self.value_stack.append(stackTop(list_node.List.items)); }, .dictionary_begin => { try self.object_stack.append(.dictionary); var list_node = stackTop(self.value_stack.items).*; try list_node.List.append(Value.make_dict(alloc)); try self.value_stack.append(stackTop(list_node.List.items)); self.state = .dict_key; }, else => { return error.parse_error; }, } }, .valid => { // we're already valid, shouldn't get more values return error.malformed_bencode_object; }, } } if (self.state != .valid) { return error.parse_error; } return tree; } }; fn parseString(token: Token, lexer: *Lexer) ![]const u8 { try ensureTokenType(token, .string_length); const str_len = try std.fmt.parseInt(usize, token.data, 10); const split = lexer.next() orelse return error.missing_token; try ensureTokenType(split, .string_split); const str = lexer.next() orelse return error.missing_token; try ensureTokenType(str, .string); return str.data; } fn parseInteger(token: Token, lexer: *Lexer) !i64 { try ensureTokenType(token, .integer_begin); const value = lexer.next() orelse return error.missing_token; try ensureTokenType(value, .integer); const i = try std.fmt.parseInt(i64, value.data, 10); const end_token = lexer.next() orelse return error.missing_token; try ensureTokenType(end_token, .end); return i; } fn ensureTokenType(t: Token, tt: BencodeTokens) !void { log.debug("Comparing Tokens: {}, {}", .{ t, tt }); if (t.token_type != tt) { return error.incorrect_token_type; } } fn stackTop(data: anytype) *@typeInfo(@TypeOf(data)).Pointer.child { return &data[data.len - 1]; } test "parse integer" { const data = "i230e"; var parser = Parser.initWithData(testing.allocator, data); defer parser.deinit(); const tree = try parser.parse(); defer tree.arena.deinit(); switch (tree.root) { .Integer => |v| { testing.expectEqual(v, 230); }, else => { testing.expect(false); }, } } test "parse string" { const data = "5:hello"; var parser = Parser.initWithData(testing.allocator, data); defer parser.deinit(); var tree = try parser.parse(); defer tree.deinit(); switch (tree.root) { .String => |s| { testing.expectEqualStrings(s, "hello"); }, else => { testing.expect(false); }, } } fn testValueIsInteger(v: Value, i: i64) bool { return switch (v) { .Integer => |x| x == i, else => false, }; } test "parse basic list of integers" { const data = "li2ei3ei4ee"; var parser = Parser.initWithData(testing.allocator, data); defer parser.deinit(); var tree = try parser.parse(); defer tree.deinit(); switch (tree.root) { .List => |l| { testing.expectEqual(l.items.len, 3); testing.expect(testValueIsInteger(l.items[0], 2)); testing.expect(testValueIsInteger(l.items[1], 3)); testing.expect(testValueIsInteger(l.items[2], 4)); }, else => { testing.expect(false); }, } } test "list of list of integers and integers" { const data = "lli1ei2ei3eei4ei5ee"; var parser = Parser.initWithData(testing.allocator, data); defer parser.deinit(); var tree = try parser.parse(); defer tree.deinit(); switch (tree.root) { .List => |l| { testing.expectEqual(l.items.len, 3); switch (l.items[0]) { .List => |l2| { testing.expect(testValueIsInteger(l2.items[0], 1)); testing.expect(testValueIsInteger(l2.items[1], 2)); testing.expect(testValueIsInteger(l2.items[2], 3)); }, else => testing.expect(false), } testing.expect(testValueIsInteger(l.items[1], 4)); testing.expect(testValueIsInteger(l.items[2], 5)); }, else => { testing.expect(false); }, } } test "parse basic dictionary" { const data = "d5:helloi200ee"; var parser = Parser.initWithData(testing.allocator, data); defer parser.deinit(); var tree = try parser.parse(); defer tree.deinit(); switch (tree.root) { .Dictionary => |d| { var it = d.iterator(); while (it.next()) |entry| { testing.expectEqualStrings(entry.key, "hello"); switch (entry.value) { .Integer => |i| testing.expectEqual(i, 200), else => testing.expect(false), } } }, else => testing.expect(false), } } test "parse list inside dictionary" { const data = "d4:listli1ei2ei3eee"; var parser = Parser.initWithData(testing.allocator, data); defer parser.deinit(); var tree = try parser.parse(); defer tree.deinit(); switch (tree.root) { .Dictionary => |d| { const list = d.get("list") orelse return error.list_missing; testing.expect(std.meta.activeTag(list) == .List); testing.expectEqual(list.List.items.len, 3); testing.expect(testValueIsInteger(list.List.items[0], 1)); testing.expect(testValueIsInteger(list.List.items[1], 2)); testing.expect(testValueIsInteger(list.List.items[2], 3)); }, else => testing.expect(false), } } /// Implementation is private as it uses the LexerState /// to conditionally add in some fields when only in /// particular and the functionality makes it hard to read /// what's actually in the impl / functions are available /// Instead there's an Interface wrapper `Lexer` const LexerImpl = struct { state: LexerState, data: []const u8, const LexerState = union(enum) { start: struct {}, //parsing_dict: struct {}, parsing_string: struct { str_len: usize, split: bool, }, parsing_integer: struct {}, }; pub fn init() @This() { var l: LexerImpl = .{ .data = undefined, .state = LexerState{ .start = .{} }, }; l.data.len = 0; return l; } pub fn initWithData(data: []const u8) @This() { var self = init(); self.reset(data); return self; } pub fn reset(self: *@This(), data: []const u8) void { self.data = data; self.state = LexerState{ .start = .{} }; } pub fn next(self: *@This()) ?Token { if (self.data.len == 0) { return null; } switch (self.state) { .start => { switch (self.data[0]) { 'd' => { const token = Token{ .token_type = BencodeTokens.dictionary_begin, .data = self.data[0..1], }; self.data = self.data[1..]; return token; }, 'l' => { const token = Token{ .token_type = BencodeTokens.list_begin, .data = self.data[0..1], }; self.data = self.data[1..]; return token; }, 'i' => { self.state = LexerState{ .parsing_integer = .{} }; const token = Token{ .token_type = BencodeTokens.integer_begin, .data = self.data[0..1], }; self.data = self.data[1..]; return token; }, '0'...'9' => { var i: usize = 0; while (self.data[i] != ':') : (i += 1) {} const str_len = std.fmt.parseInt(usize, self.data[0..i], 10) catch { return null; }; self.state = LexerState{ .parsing_string = .{ .str_len = str_len, .split = false } }; const token = Token{ .token_type = BencodeTokens.string_length, .data = self.data[0..i], }; self.data = self.data[i..]; return token; }, 'e' => { const token = Token{ .token_type = BencodeTokens.end, .data = self.data[0..1], }; self.data = self.data[1..]; return token; }, else => { return null; }, } }, .parsing_string => { if (!self.state.parsing_string.split) { if (self.data[0] != ':') { return null; } const token = Token{ .token_type = BencodeTokens.string_split, .data = self.data[0..1], }; self.data = self.data[1..]; self.state.parsing_string.split = true; return token; } else { const token = Token{ .token_type = BencodeTokens.string, .data = self.data[0..self.state.parsing_string.str_len], }; self.data = self.data[self.state.parsing_string.str_len..]; self.state = LexerState{ .start = .{} }; return token; } }, .parsing_integer => { switch (self.data[0]) { '-', '0'...'9' => { var i: usize = 0; // we can have negative numbers if (self.data[i] == '-') { i += 1; } while (self.data[i] != 'e') : (i += 1) { if (self.data[i] < '0' or self.data[i] > '9') { return null; } } const token = Token{ .token_type = BencodeTokens.integer, .data = self.data[0..i], }; self.data = self.data[i..]; return token; }, 'e' => { const token = Token{ .token_type = BencodeTokens.end, .data = self.data[0..1], }; self.data = self.data[1..]; self.state = LexerState{ .start = .{} }; return token; }, else => { return null; }, } }, } } }; /// Only use in tests. fn testTokenStream(lexer: *Lexer, expected_tokens: []const Token) void { var token_count: usize = 0; while (lexer.next()) |token| : (token_count += 1) { const cur_expect_token = expected_tokens[token_count]; testing.expectEqual(cur_expect_token.token_type, token.token_type); testing.expectEqualStrings(cur_expect_token.data, token.data); } testing.expectEqual(expected_tokens.len, token_count); } test "basic dictionary tokens" { const data = "d5:hello5:worlde"; var lex = Lexer.initWithData(data); const expected_tokens = [_]Token{ .{ .token_type = .dictionary_begin, .data = "d" }, .{ .token_type = .string_length, .data = "5" }, .{ .token_type = .string_split, .data = ":" }, .{ .token_type = .string, .data = "hello" }, .{ .token_type = .string_length, .data = "5" }, .{ .token_type = .string_split, .data = ":" }, .{ .token_type = .string, .data = "world" }, .{ .token_type = .end, .data = "e" }, }; } test "parse a list" { const data = "l5:helloi230ee"; var lex = Lexer.initWithData(data); const expected_tokens = [_]Token{ .{ .token_type = .list_begin, .data = "l" }, .{ .token_type = .string_length, .data = "5" }, .{ .token_type = .string_split, .data = ":" }, .{ .token_type = .string, .data = "hello" }, .{ .token_type = .integer_begin, .data = "i" }, .{ .token_type = .integer, .data = "230" }, .{ .token_type = .end, .data = "e" }, .{ .token_type = .end, .data = "e" }, }; testTokenStream(&lex, expected_tokens[0..]); } test "list nested in dictionary" { const data = "d5:hellol3:eat4:firei230eee"; var lex = Lexer.initWithData(data); const expected_tokens = [_]Token{ .{ .token_type = .dictionary_begin, .data = "d" }, .{ .token_type = .string_length, .data = "5" }, .{ .token_type = .string_split, .data = ":" }, .{ .token_type = .string, .data = "hello" }, .{ .token_type = .list_begin, .data = "l" }, .{ .token_type = .string_length, .data = "3" }, .{ .token_type = .string_split, .data = ":" }, .{ .token_type = .string, .data = "eat" }, .{ .token_type = .string_length, .data = "4" }, .{ .token_type = .string_split, .data = ":" }, .{ .token_type = .string, .data = "fire" }, .{ .token_type = .integer_begin, .data = "i" }, .{ .token_type = .integer, .data = "230" }, .{ .token_type = .end, .data = "e" }, .{ .token_type = .end, .data = "e" }, .{ .token_type = .end, .data = "e" }, }; testTokenStream(&lex, expected_tokens[0..]); }
src/main.zig
const std = @import("std"); const upaya = @import("upaya"); usingnamespace upaya.imgui; usingnamespace upaya.sokol; const Mat4 = upaya.math.Mat4; const Vec3 = upaya.math.Vec3; var state = struct { render_texture: upaya.RenderTexture = undefined, offscreen_pass: sg_pass = undefined, pass_action: sg_pass_action = undefined, pipeline: sg_pipeline = undefined, bindings: sg_bindings = undefined, }{}; const VertShaderParams = struct { mvp: Mat4 = undefined }; pub fn main() !void { upaya.run(.{ .init = init, .update = update, .docking = false, }); } fn init() void { state.pass_action.colors[0].action = .SG_ACTION_CLEAR; state.pass_action.colors[0].val = [_]f32{ 0.2, 0.2, 0.2, 1.0 }; state.render_texture = upaya.RenderTexture.init(380, 256, .linear); var pass_desc = std.mem.zeroes(sg_pass_desc); pass_desc.color_attachments[0].image = state.render_texture.img; state.offscreen_pass = sg_make_pass(&pass_desc); const vertices = [_]f32{ // positions // colors -1.0, -1.0, -1.0, 1.0, 0.0, 0.0, 1.0, 1.0, -1.0, -1.0, 1.0, 0.0, 0.0, 1.0, 1.0, 1.0, -1.0, 1.0, 0.0, 0.0, 1.0, -1.0, 1.0, -1.0, 1.0, 0.0, 0.0, 1.0, -1.0, -1.0, 1.0, 0.0, 1.0, 0.0, 1.0, 1.0, -1.0, 1.0, 0.0, 1.0, 0.0, 1.0, 1.0, 1.0, 1.0, 0.0, 1.0, 0.0, 1.0, -1.0, 1.0, 1.0, 0.0, 1.0, 0.0, 1.0, -1.0, -1.0, -1.0, 0.0, 0.0, 1.0, 1.0, -1.0, 1.0, -1.0, 0.0, 0.0, 1.0, 1.0, -1.0, 1.0, 1.0, 0.0, 0.0, 1.0, 1.0, -1.0, -1.0, 1.0, 0.0, 0.0, 1.0, 1.0, 1.0, -1.0, -1.0, 1.0, 0.5, 0.0, 1.0, 1.0, 1.0, -1.0, 1.0, 0.5, 0.0, 1.0, 1.0, 1.0, 1.0, 1.0, 0.5, 0.0, 1.0, 1.0, -1.0, 1.0, 1.0, 0.5, 0.0, 1.0, -1.0, -1.0, -1.0, 0.0, 0.5, 1.0, 1.0, -1.0, -1.0, 1.0, 0.0, 0.5, 1.0, 1.0, 1.0, -1.0, 1.0, 0.0, 0.5, 1.0, 1.0, 1.0, -1.0, -1.0, 0.0, 0.5, 1.0, 1.0, -1.0, 1.0, -1.0, 1.0, 0.0, 0.5, 1.0, -1.0, 1.0, 1.0, 1.0, 0.0, 0.5, 1.0, 1.0, 1.0, 1.0, 1.0, 0.0, 0.5, 1.0, 1.0, 1.0, -1.0, 1.0, 0.0, 0.5, 1.0, }; const indices = [_]u16{ 0, 1, 2, 0, 2, 3, 6, 5, 4, 7, 6, 4, 8, 9, 10, 8, 10, 11, 14, 13, 12, 15, 14, 12, 16, 17, 18, 16, 18, 19, 22, 21, 20, 23, 22, 20, }; var buffer_desc = std.mem.zeroes(sg_buffer_desc); buffer_desc.size = vertices.len * @sizeOf(f32); buffer_desc.content = &vertices[0]; state.bindings.vertex_buffers[0] = sg_make_buffer(&buffer_desc); buffer_desc = std.mem.zeroes(sg_buffer_desc); buffer_desc.type = .SG_BUFFERTYPE_INDEXBUFFER; buffer_desc.size = indices.len * @sizeOf(u16); buffer_desc.content = &indices[0]; state.bindings.index_buffer = sg_make_buffer(&buffer_desc); var shader_desc = std.mem.zeroes(sg_shader_desc); shader_desc.vs.uniform_blocks[0].size = @sizeOf(VertShaderParams); shader_desc.vs.uniform_blocks[0].uniforms[0] = .{ .name = "mvp", .type = .SG_UNIFORMTYPE_MAT4, .array_count = 0, }; shader_desc.vs.source = if (std.Target.current.os.tag == .macosx) @embedFile("assets/shaders/vertcolor_metal.vs") else @embedFile("assets/shaders/vertcolor_gl.vs"); shader_desc.fs.source = if (std.Target.current.os.tag == .macosx) @embedFile("assets/shaders/vertcolor_metal.fs") else @embedFile("assets/shaders/vertcolor_gl.fs"); var pipeline_desc = std.mem.zeroes(sg_pipeline_desc); pipeline_desc.layout.attrs[0].format = .SG_VERTEXFORMAT_FLOAT3; pipeline_desc.layout.attrs[1].format = .SG_VERTEXFORMAT_FLOAT4; pipeline_desc.layout.buffers[0].stride = 28; pipeline_desc.shader = sg_make_shader(&shader_desc); pipeline_desc.index_type = .SG_INDEXTYPE_UINT16; pipeline_desc.depth_stencil.depth_compare_func = .SG_COMPAREFUNC_LESS_EQUAL; pipeline_desc.depth_stencil.depth_write_enabled = false; pipeline_desc.blend.color_format = .SG_PIXELFORMAT_RGBA8; pipeline_desc.blend.depth_format = .SG_PIXELFORMAT_NONE; pipeline_desc.rasterizer.cull_mode = .SG_CULLMODE_BACK; state.pipeline = sg_make_pipeline(&pipeline_desc); } fn update() void { renderOffscreen(); if (igBegin("My First Window", null, ImGuiWindowFlags_None)) { igText("Hello, world!"); igText("We get built-in icons too: " ++ icons.igloo); } igEnd(); igPushStyleVarVec2(ImGuiStyleVar_WindowPadding, .{}); if (igBegin("Offscreen Rendering", null, ImGuiWindowFlags_AlwaysAutoResize)) { ogImage(state.render_texture.imTextureID(), state.render_texture.width, state.render_texture.height); } igEnd(); igPopStyleVar(1); } var rx: f32 = 0.0; var ry: f32 = 0.0; fn renderOffscreen() void { var g = state.pass_action.colors[0].val[1] + 0.01; if (g > 1) g = 0; state.pass_action.colors[0].val[1] = g; const radians: f32 = 1.0472; //60 degrees var proj = Mat4.createPerspective(radians, @intToFloat(f32, state.render_texture.width) / @intToFloat(f32, state.render_texture.height), 0.01, 100.0); var view = Mat4.createLookAt(Vec3.new(2.0, 3.5, 2.0), Vec3.new(0.0, 0.0, 0.0), Vec3.new(0.0, 1.0, 0.0)); var view_proj = Mat4.mul(proj, view); rx += 1.0 / 220.0; ry += 2.0 / 220.0; var rxm = Mat4.createAngleAxis(Vec3.new(1, 0, 0), rx); var rym = Mat4.createAngleAxis(Vec3.new(0, 1, 0), ry); var model = Mat4.mul(rxm, rym); var mvp = Mat4.mul(view_proj, model); var vs_params = VertShaderParams{ .mvp = mvp, }; sg_begin_pass(state.offscreen_pass, &state.pass_action); sg_apply_pipeline(state.pipeline); sg_apply_bindings(&state.bindings); sg_apply_uniforms(.SG_SHADERSTAGE_VS, 0, &vs_params, @sizeOf(VertShaderParams)); sg_draw(0, 36, 1); sg_end_pass(); }
examples/offscreen_rendering.zig
const std = @import("std"); const unistd = @cImport(@cInclude("unistd.h")); fn notify(msg: []const u8) void { const addr = std.net.Address.parseIp("127.0.0.1", 9001) catch unreachable; if (std.net.tcpConnectToAddress(addr)) |stream| { defer stream.close(); _ = stream.write(msg) catch unreachable; } else |_| {} } pub fn main() !void { var arena = std.heap.ArenaAllocator.init(std.heap.c_allocator); defer arena.deinit(); var alloc: *std.mem.Allocator = &arena.allocator; const b64 = std.base64.standard; const fixtures: [2]struct { src: []const u8, dst: []const u8 } = .{ .{ .src = "hello", .dst = "aGVsbG8=" }, .{ .src = "world", .dst = "d29ybGQ=" }, }; for (fixtures) |fix| { var buffer: [0x100]u8 = undefined; const encoded = b64.Encoder.encode(&buffer, fix.src); if (!std.mem.eql(u8, encoded, fix.dst)) { std.debug.panic("'{s}' != '{s}'\n", .{ encoded, fix.dst }); } std.mem.set(u8, &buffer, 0); try b64.Decoder.decode(&buffer, fix.dst); if (!std.mem.eql(u8, buffer[0..fix.src.len], fix.src)) { std.debug.panic("'{s}' != '{s}'\n", .{ &buffer, fix.src }); } } const STR_SIZE = 131072; const TRIES = 8192; const str1 = "a" ** STR_SIZE; const encodeSize = b64.Encoder.calcSize(STR_SIZE); const str2 = try alloc.alloc(u8, encodeSize); const encoded = b64.Encoder.encode(str2, str1); const decodeSize = try b64.Decoder.calcSizeForSlice(encoded); const str3 = try alloc.alloc(u8, decodeSize); b64.Decoder.decode(str3, str2) catch unreachable; var buffer = try alloc.alloc(u8, std.math.max(encodeSize, decodeSize)); const fb_alloc = &std.heap.FixedBufferAllocator.init(buffer).allocator; const pid = unistd.getpid(); const pid_str = try std.fmt.allocPrint(alloc, "Zig\t{d}", .{pid}); notify(pid_str); var i: i32 = 0; var s_encoded: usize = 0; const t1 = std.time.milliTimestamp(); while (i < TRIES) : (i += 1) { var str21 = fb_alloc.alloc(u8, encodeSize) catch unreachable; s_encoded += b64.Encoder.encode(str21, str1).len; fb_alloc.free(str21); } const t_encoded: f64 = @intToFloat(f64, std.time.milliTimestamp() - t1) / std.time.ms_per_s; i = 0; var s_decoded: usize = 0; const t2 = std.time.milliTimestamp(); while (i < TRIES) : (i += 1) { var str31 = fb_alloc.alloc(u8, decodeSize) catch unreachable; b64.Decoder.decode(str31, str2) catch unreachable; s_decoded += str31.len; fb_alloc.free(str31); } const t_decoded: f64 = @intToFloat(f64, std.time.milliTimestamp() - t2) / std.time.ms_per_s; notify("stop"); std.debug.print("encode: {s}... to {s}...: {}, {d:.2}\n", .{ str1[0..4], str2[0..4], s_encoded, t_encoded }); std.debug.print("decode: {s}... to {s}...: {}, {d:.2}\n", .{ str2[0..4], str3[0..4], s_decoded, t_decoded }); }
base64/test.zig
const std = @import("std"); const Allocator = std.mem.Allocator; const ArrayList = std.ArrayList; const assert = std.debug.assert; const print = std.debug.print; const input = @embedFile("../input/day11.txt"); fn loadLines(allocator: *Allocator, string: []const u8) !ArrayList([]const u8) { var lines = ArrayList([]const u8).init(allocator); var tokens = std.mem.tokenize(string, "\r\n"); while (tokens.next()) |token| { try lines.append(token); } return lines; } fn printGrid(buf: []u8) void { var y: usize = 0; while (y < h) : (y += 1) { print("{}\n", .{buf[y * w .. y * w + w]}); } } fn seesOccupied(grid: []u8, sx: usize, sy: usize, dx: i32, dy: i32, blocking_floor: bool) bool { var x = @intCast(i32, sx); var y = @intCast(i32, sy); while (true) { x += dx; y += dy; if (x < 0 or y < 0 or x >= w or y >= h) return false; const safe_x = @intCast(usize, x); const safe_y = @intCast(usize, y); switch (grid[safe_y * w + safe_x]) { '#' => return true, 'L' => return false, else => { if (blocking_floor) return false; }, } } } fn applyRules(in: []u8, out: []u8, blocking_floor: bool, tolerance: usize) void { var y: usize = 0; while (y < h) : (y += 1) { var x: usize = 0; while (x < w) : (x += 1) { var occupied: usize = 0; var dx: i32 = -1; while (dx <= 1) : (dx += 1) { var dy: i32 = -1; while (dy <= 1) : (dy += 1) { if (dx == 0 and dy == 0) continue; if (seesOccupied(in, x, y, dx, dy, blocking_floor)) occupied += 1; } } const i = y * w + x; switch (in[i]) { 'L' => {if (occupied == 0) out[i] = '#';}, '#' => {if (occupied >= tolerance) out[i] = 'L';}, else => {} } } } } var w: usize = undefined; var h: usize = undefined; pub fn main() !void { var gpa = std.heap.GeneralPurposeAllocator(.{}){}; var allocator = &gpa.allocator; var lines = try loadLines(allocator, input); defer lines.deinit(); w = lines.items[0].len; h = lines.items.len; var part: usize = 1; while (part <= 2) : (part += 1) { var buf0 = try allocator.alloc(u8, w * h); defer allocator.free(buf0); for (lines.items) |line, i| { std.mem.copy(u8, buf0[w * i..], line[0..w]); } var buf1 = try allocator.dupe(u8, buf0); defer allocator.free(buf1); var prev_occupied = std.mem.count(u8, buf0, "#"); while (true) { std.mem.copy(u8, buf0, buf1); if (part == 1) applyRules(buf0, buf1, true, 4) else applyRules(buf0, buf1, false, 5); const occupied = std.mem.count(u8, buf1, "#"); if (occupied == prev_occupied) { print("part{}: {}\n", .{part, occupied}); break; } prev_occupied = occupied; } } } const example = \\L.LL.LL.LL \\LLLLLLL.LL \\L.L.L..L.. \\LLLL.LL.LL \\L.LL.LL.LL \\L.LLLLL.LL \\..L.L..... \\LLLLLLLLLL \\L.LLLLLL.L \\L.LLLLL.LL ;
src/day11.zig
const std = @import("std"); const build_map = @import("build_map.zig"); const Node = std.zig.ast.Node; const Tree = std.zig.ast.Tree; const StateMap = std.StringHashMap([]u8); /// Serialize a string into the given serializer. Uses a simple u29 length /// prefix + the string itself. fn serializeStr(serializer: var, string: []const u8) !void { try serializer.serialize(@intCast(u29, string.len)); for (string) |byte| { try serializer.serialize(byte); } } /// Represents the current amount of knowledge being held by the state /// file into memory. pub const State = struct { allocator: *std.mem.Allocator, map: StateMap, pub fn init(allocator: *std.mem.Allocator) State { return State{ .allocator = allocator, .map = StateMap.init(allocator), }; } pub fn deinit(self: *State) void { self.map.deinit(); } /// Deserialize a string from the stream into memory. fn deserializeStr( self: *State, deserializer: var, length_opt: ?u29, ) ![]u8 { var i: usize = 0; var res: []u8 = undefined; var length: u29 = undefined; if (length_opt) |length_actual| { length = length_actual; res = try self.allocator.alloc(u8, length); } else { length = try deserializer.deserialize(u29); res = try self.allocator.alloc(u8, length); } while (i < length) : (i += 1) { var byte = try deserializer.deserialize(u8); res[i] = byte; } return res; } pub fn deserialize(self: *State, deserializer: var) !void { while (true) { var length = deserializer.deserialize(u29) catch |err| { if (err == error.EndOfStream) break; return err; }; if (length == 0) break; // deserialize a KV pair and put() it const key = try self.deserializeStr(deserializer, length); var value = try self.deserializeStr(deserializer, null); _ = try self.map.put(key, value); } } pub fn serialize(self: *State, serializer: var) !void { var it = self.map.iterator(); var cnt: usize = 0; while (it.next()) |kv| { std.debug.warn("serializing '{}' ({} bytes)\n", .{ kv.key, kv.value.len, }); try serializeStr(serializer, kv.key); try serializeStr(serializer, kv.value); cnt += 1; } // sentry value to determine end of hashmap // maybe we could just catch an endofstream instead, idk. try serializer.serialize(@as(u29, 0)); std.debug.warn("finished {} elements\n", .{cnt}); } /// From a given Node.DocComment, convert it to [][]const u8, with the /// doc comment tokens trimmed out. fn docToSlice(self: *State, tree: var, doc_opt: ?*Node.DocComment) ![][]const u8 { // TODO: use ArrayList var lines: [][]const u8 = try self.allocator.alloc([]u8, 0); if (doc_opt) |doc| { var it = doc.lines.iterator(0); while (it.next()) |line_idx| { lines = try self.allocator.realloc(lines, lines.len + 1); var line = tree.tokenSlice(line_idx.*); lines[lines.len - 1] = std.mem.trimLeft(u8, line, "/// "); } return lines; } else { return lines; } } /// Add a given node (not the full Node structure) into the state. pub fn addNode( self: *State, tree: *Tree, namespace: []const u8, node_name: []const u8, doc: ?*Node.DocComment, ) !void { var full_name = try build_map.appendNamespace( self.allocator, namespace, node_name, ); std.debug.warn("node: {}\n", .{full_name}); var lines = try self.docToSlice(tree, doc); for (lines) |line| { std.debug.warn("\tdoc: {}\n", .{line}); } var lines_single = try std.mem.join(self.allocator, "\n", lines); _ = try self.map.put(full_name, lines_single); } };
src/state.zig
const inputFile = @embedFile("./input/day09.txt"); const std = @import("std"); const Allocator = std.mem.Allocator; const ArrayList = std.ArrayList; const Str = []const u8; const BitSet = std.DynamicBitSet; const assert = std.debug.assert; const tokenize = std.mem.tokenize; const print = std.debug.print; fn sort(comptime T: type, items: []T) void { std.sort.sort(T, items, {}, comptime std.sort.asc(T)); } fn partOne(grid: Input) usize { var result: usize = 0; for (grid.items) |d, i| { const row = i / grid.nCols; const col = i % grid.nCols; // left, right if (col > 0 and d >= grid.items[i - 1]) continue; if (col < grid.nCols - 1 and d >= grid.items[i + 1]) continue; // top, bottom if (row > 0 and d >= grid.items[i - grid.nCols]) continue; if (row < grid.nRows - 1 and d >= grid.items[i + grid.nCols]) continue; result += 1 + d; } return result; } fn partTwo(grid: Input, allocator: Allocator) !usize { var visited = try BitSet.initEmpty(allocator, grid.items.len); defer visited.deinit(); // the last 3 are the top 3 basins, the first one is scratch space var basins = [4]usize{ 0, 0, 0, 0 }; for (grid.items) |d, i| { const row = i / grid.nCols; const col = i % grid.nCols; // Find a low point, same as part 1 if (col > 0 and d >= grid.items[i - 1]) continue; if (col < grid.nCols - 1 and d >= grid.items[i + 1]) continue; if (row > 0 and d >= grid.items[i - grid.nCols]) continue; if (row < grid.nRows - 1 and d >= grid.items[i + grid.nCols]) continue; // from the low point, expand outwards const basinSize = findBasinSize(grid, i, &visited); basins[0] = basinSize; sort(usize, &basins); } return basins[1] * basins[2] * basins[3]; } fn findBasinSize(grid: Input, pt: usize, visited: *BitSet) usize { if (visited.isSet(pt) or grid.items[pt] == 9) return 0; var result: usize = 1; visited.set(pt); const row = pt / grid.nCols; const col = pt % grid.nCols; const d = grid.items[pt]; if (col > 0 and d < grid.items[pt - 1]) { result += findBasinSize(grid, pt - 1, visited); } if (col < grid.nCols - 1 and d < grid.items[pt + 1]) { result += findBasinSize(grid, pt + 1, visited); } if (row > 0 and d < grid.items[pt - grid.nCols]) { result += findBasinSize(grid, pt - grid.nCols, visited); } if (row < grid.nRows - 1 and d < grid.items[pt + grid.nCols]) { result += findBasinSize(grid, pt + grid.nCols, visited); } return result; } const Input = struct { items: Str, nRows: usize, nCols: usize, }; fn parseInput(input: Str, allocator: Allocator) !Input { var lines = ArrayList(u8).init(allocator); errdefer lines.deinit(); const nCols = std.mem.indexOfScalar(u8, input, '\n').?; var nRows: usize = 0; var it = tokenize(u8, input, "\n"); while (it.next()) |line| : (nRows += 1) { for (line) |c| { try lines.append(c - '0'); } } return Input{ .items = lines.toOwnedSlice(), .nRows = nRows, .nCols = nCols }; } pub fn main() !void { // Standard boilerplate for Aoc problems const stdout = std.io.getStdOut().writer(); var gpa = std.heap.GeneralPurposeAllocator(.{}){}; var gpaAllocator = gpa.allocator(); defer assert(!gpa.deinit()); // Check for memory leaks var arena = std.heap.ArenaAllocator.init(gpaAllocator); defer arena.deinit(); var allocator = arena.allocator(); // use an arena const grid = try parseInput(inputFile, allocator); try stdout.print("Part1: {d}\nPart2: {d}", .{ partOne(grid), try partTwo(grid, allocator) }); } test "part 1" { const testInput = \\2199943210 \\3987894921 \\9856789892 \\8767896789 \\9899965678 \\7829965671 \\ ; var allocator = std.testing.allocator; const grid = try parseInput(testInput, allocator); defer allocator.free(grid.items); try std.testing.expectEqual(@as(usize, 22), partOne(grid)); } test "part 2" { const testInput = \\2199943210 \\3987894921 \\9856789892 \\8767896789 \\9899965678 \\ ; var allocator = std.testing.allocator; const grid = try parseInput(testInput, allocator); defer allocator.free(grid.items); try std.testing.expectEqual(@as(usize, 1134), try partTwo(grid, allocator)); }
src/day09.zig
const std = @import("std"); const chunks = @import("./chunks.zig"); const values = @import("./value.zig"); const Chunk = chunks.Chunk; const OpCode = chunks.OpCode; pub fn dissasembleChunk(chunk: *Chunk, comptime name: []const u8) void { std.debug.print("=== {s} ===\n", .{name}); const code = chunk.code; var offset: usize = 0; while (offset < code.count) { disassembleInstruction(chunk, offset); offset = calcOffset(code.items[offset], offset); } } fn calcOffset(instruction_code: u8, current_offset: usize) usize { const instruction = @intToEnum(OpCode, instruction_code); return current_offset + instruction.num_operands() + 1; } pub fn disassembleInstruction(chunk: *Chunk, offset: usize) void { std.debug.print("{d:0>4} ", .{offset}); const code = chunk.code; const lines = chunk.lines; if (offset > 0 and lines.items[offset] == lines.items[offset - 1]) { std.debug.print(" | ", .{}); } else { std.debug.print("{d: >4} ", .{lines.items[offset]}); } const instruction = @intToEnum(OpCode, code.items[offset]); switch (instruction) { .op_constant => constantInstruction("OP_CONSTANT", chunk, offset), .op_define_gloabl => constantInstruction("OP_DEFINE_GLOBAL", chunk, offset), .op_get_global => constantInstruction("OP_GET_GLOBAL", chunk, offset), .op_set_global => constantInstruction("OP_SET_GLOBAL", chunk, offset), .op_negate => simpleInstruction("OP_NEGATE"), .op_not => simpleInstruction("OP_NOT"), .op_nil => simpleInstruction("OP_NIL"), .op_equal => simpleInstruction("OP_EQUAL"), .op_false => simpleInstruction("OP_FALSE"), .op_greater => simpleInstruction("OP_GREATER"), .op_less => simpleInstruction("OP_LESS"), .op_true => simpleInstruction("OP_TRUE"), .op_add => simpleInstruction("OP_ADD"), .op_sub => simpleInstruction("OP_SUBSTRACT"), .op_mul => simpleInstruction("OP_MULTIPLY"), .op_div => simpleInstruction("OP_DIVIDE"), .op_print => simpleInstruction("OP_PRINT"), .op_pop => simpleInstruction("OP_POP"), .op_ret => simpleInstruction("OP_RETURN"), } } fn simpleInstruction(comptime name: []const u8) void { std.debug.print("{s}\n", .{name}); } fn constantInstruction(name: []const u8, chunk: *Chunk, offset: usize) void { const constant_idx = chunk.code.items[offset + 1]; const constant = chunk.constants.items[constant_idx]; std.debug.print("{s: <16} {d: >4} '{}'\n", .{ name, constant_idx, constant }); }
src/debug.zig
pub const BufferMapCallback = fn ( status: BufferMapAsyncStatus, userdata: *c_void, ) callconv(.C) void; pub const CreateComputePipelineAsyncCallback = fn ( status: CreatePipelineAsyncStatus, pipeline: ComputePipeline, message: [*:0]const u8, userdata: *c_void, ) callconv(.C) void; pub const CreateRenderPipelineAsyncCallback = fn ( status: CreatePipelineAsyncStatus, pipeline: RenderPipeline, message: [*:0]const u8, userdata: *c_void, ) callconv(.C) void; pub const DeviceLostCallback = fn ( reason: DeviceLostReason, message: [*:0]const u8, userdata: *c_void, ) callconv(.C) void; pub const ErrorCallback = fn ( type: ErrorType, message: [*:0]const u8, userdata: *c_void, ) callconv(.C) void; pub const QueueWorkDoneCallback = fn ( status: QueueWorkDoneStatus, userdata: *c_void, ) callconv(.C) void; pub const RequestAdapterCallback = fn ( status: RequestAdapterStatus, adapter: Adapter, message: ?[*:0]const u8, userdata: *c_void, ) callconv(.C) void; pub const RequestDeviceCallback = fn ( status: RequestDeviceStatus, device: Device, message: ?[*:0]const u8, userdata: *c_void, ) callconv(.C) void; pub const createInstance = wgpuCreateInstance; extern fn wgpuCreateInstance(descriptor: *const InstanceDescriptor) Instance; pub const getProcAddress = wgpuGetProcAddress; extern fn wgpuGetProcAddress(device: Device, proc_name: [*:0]const u8) Proc; pub const Proc = fn () callconv(.C) void; pub const Adapter = *opaque { pub const getLimits = wgpuAdapterGetLimits; extern fn wgpuAdapterGetLimits(adapter: Adapter, limits: *SupportedLimits) void; pub const getProperties = wgpuAdapterGetProperties; extern fn wgpuAdapterGetProperties(adapter: Adapter, properties: *AdapterProperties) void; pub const hasFeature = wgpuAdapterHasFeature; extern fn wgpuAdapterHasFeature(adapter: Adapter, feature: FeatureName) bool; pub const requestDevice = wgpuAdapterRequestDevice; extern fn wgpuAdapterRequestDevice( adapter: Adapter, descriptor: *const DeviceDescriptor, callback: RequestDeviceCallback, userdata: *c_void, ) void; }; pub const BindGroup = *opaque { // WGPU extras pub const drop = wgpuBindGroupDrop; extern fn wgpuBindGroupDrop(bind_group: BindGroup) void; }; pub const BindGroupLayout = *opaque { // WGPU extras pub const drop = wgpuBindGroupLayoutDrop; extern fn wgpuBindGroupLayoutDrop(bind_group_layout: BindGroupLayout) void; }; pub const Buffer = *opaque { pub const destroy = wgpuBufferDestroy; extern fn wgpuBufferDestroy(buffer: Buffer) void; pub const getConstMappedRange = wgpuBufferGetConstMappedRange; extern fn wgpuBufferGetConstMappedRange(buffer: Buffer, offset: usize, size: usize) *const c_void; pub const getMappedRange = wgpuBufferGetMappedRange; extern fn wgpuBufferGetMappedRange(buffer: Buffer, offset: usize, size: usize) *c_void; pub const mapAsync = wgpuBufferMapAsync; extern fn wgpuBufferMapAsync( buffer: Buffer, mode: MapMode, offset: usize, size: usize, callback: BufferMapCallback, userdata: *c_void, ) void; pub const unmap = wgpuBufferUnmap; extern fn wgpuBufferUnmap(buffer: Buffer) void; // WGPU extras pub const drop = wgpuBufferDrop; extern fn wgpuBufferDrop(buffer: Buffer) void; }; pub const CommandBuffer = *opaque { // WGPU extras pub const drop = wgpuCommandBufferDrop; extern fn wgpuCommandBufferDrop(command_buffer: CommandBuffer) void; }; pub const CommandEncoder = *opaque { pub const beginComputePass = wgpuCommandEncoderBeginComputePass; extern fn wgpuCommandEncoderBeginComputePass( command_encoder: CommandEncoder, descriptor: *const ComputePassDescriptor, ) ComputePassEncoder; pub const beginRenderPass = wgpuCommandEncoderBeginRenderPass; extern fn wgpuCommandEncoderBeginRenderPass( command_encoder: CommandEncoder, descriptor: *const RenderPassDescriptor, ) RenderPassEncoder; pub const copyBufferToBuffer = wgpuCommandEncoderCopyBufferToBuffer; extern fn wgpuCommandEncoderCopyBufferToBuffer( command_encoder: CommandEncoder, source: Buffer, source_offset: u64, destination: Buffer, destination_offset: u64, size: u64, ) void; pub const copyBufferToTexture = wgpuCommandEncoderCopyBufferToTexture; extern fn wgpuCommandEncoderCopyBufferToTexture( command_encoder: CommandEncoder, source: *const ImageCopyBuffer, destination: *const ImageCopyTexture, copy_size: *const Extent3D, ) void; pub const copyTextureToBuffer = wgpuCommandEncoderCopyTextureToBuffer; extern fn wgpuCommandEncoderCopyTextureToBuffer( command_encoder: CommandEncoder, source: *const ImageCopyTexture, destination: *const ImageCopyBuffer, copy_size: *const Extent3D, ) void; pub const copyTextureToTexture = wgpuCommandEncoderCopyTextureToTexture; extern fn wgpuCommandEncoderCopyTextureToTexture( command_encoder: CommandEncoder, source: *const ImageCopyTexture, destination: *const ImageCopyTexture, copy_size: *const Extent3D, ) void; pub const finish = wgpuCommandEncoderFinish; extern fn wgpuCommandEncoderFinish( command_encoder: CommandEncoder, descriptor: *const CommandBufferDescriptor, ) CommandBuffer; pub const insertDebugMarker = wgpuCommandEncoderInsertDebugMarker; extern fn wgpuCommandEncoderInsertDebugMarker(command_encoder: CommandEncoder, marker_label: [*:0]const u8) void; pub const popDebugGroup = wgpuCommandEncoderPopDebugGroup; extern fn wgpuCommandEncoderPopDebugGroup(command_encoder: CommandEncoder) void; pub const pushDebugGroup = wgpuCommandEncoderPushDebugGroup; extern fn wgpuCommandEncoderPushDebugGroup(command_encoder: CommandEncoder, group_label: [*:0]const u8) void; pub const resolveQuerySet = wgpuCommandEncoderResolveQuerySet; extern fn wgpuCommandEncoderResolveQuerySet( command_encoder: CommandEncoder, query_set: QuerySet, first_query: u32, query_count: u32, destination: Buffer, destination_offset: u64, ) void; pub const writeTimestamp = wgpuCommandEncoderWriteTimestamp; extern fn wgpuCommandEncoderWriteTimestamp( command_encoder: CommandEncoder, query_set: QuerySet, query_index: u32, ) void; // WGPU extras pub const drop = wgpuCommandEncoderDrop; extern fn wgpuCommandEncoderDrop(command_encoder: CommandEncoder) void; }; pub const ComputePassEncoder = *opaque { pub const beginPipelineStatisticsQuery = wgpuComputePassEncoderBeginPipelineStatisticsQuery; extern fn wgpuComputePassEncoderBeginPipelineStatisticsQuery( compute_pass_encoder: ComputePassEncoder, query_set: QuerySet, query_index: u32, ) void; pub const dispatch = wgpuComputePassEncoderDispatch; extern fn wgpuComputePassEncoderDispatch(compute_pass_encoder: ComputePassEncoder, x: u32, y: u32, z: u32) void; pub const dispatchIndirect = wgpuComputePassEncoderDispatchIndirect; extern fn wgpuComputePassEncoderDispatchIndirect( compute_pass_encoder: ComputePassEncoder, indirect_buffer: Buffer, indirect_offset: u64, ) void; pub const endPass = wgpuComputePassEncoderEndPass; extern fn wgpuComputePassEncoderEndPass(compute_pass_encoder: ComputePassEncoder) void; pub const endPipelineStatisticsQuery = wgpuComputePassEncoderEndPipelineStatisticsQuery; extern fn wgpuComputePassEncoderEndPipelineStatisticsQuery(compute_pass_encoder: ComputePassEncoder) void; pub const insertDebugMarker = wgpuComputePassEncoderInsertDebugMarker; extern fn wgpuComputePassEncoderInsertDebugMarker(compute_pass_encoder: ComputePassEncoder, marker_label: [*:0]const u8) void; pub const popDebugGroup = wgpuComputePassEncoderPopDebugGroup; extern fn wgpuComputePassEncoderPopDebugGroup(compute_pass_encoder: ComputePassEncoder) void; pub const pushDebugGroup = wgpuComputePassEncoderPushDebugGroup; extern fn wgpuComputePassEncoderPushDebugGroup(compute_pass_encoder: ComputePassEncoder, group_label: [*:0]const u8) void; pub const setBindGroup = wgpuComputePassEncoderSetBindGroup; extern fn wgpuComputePassEncoderSetBindGroup( compute_pass_encoder: ComputePassEncoder, group_index: u32, group: BindGroup, dynamic_offset_count: u32, dynamic_offsets: [*]const u32, ) void; pub const setPipeline = wgpuComputePassEncoderSetPipeline; extern fn wgpuComputePassEncoderSetPipeline(compute_pass_encoder: ComputePassEncoder, pipeline: ComputePipeline) void; pub const writeTimestamp = wgpuComputePassEncoderWriteTimestamp; extern fn wgpuComputePassEncoderWriteTimestamp( compute_pass_encoder: ComputePassEncoder, query_set: QuerySet, query_index: u32, ) void; }; pub const ComputePipeline = *opaque { pub const getBindGroupLayout = wgpuComputePipelineGetBindGroupLayout; extern fn wgpuComputePipelineGetBindGroupLayout(compute_pipeline: ComputePipeline, group_index: u32) BindGroupLayout; pub const setLabel = wgpuComputePipelineSetLabel; extern fn wgpuComputePipelineSetLabel(compute_pipeline: ComputePipeline, label: ?[*:0]const u8) void; // WGPU extras pub const drop = wgpuComputePipelineDrop; extern fn wgpuComputePipelineDrop(compute_pipeline: ComputePipeline) void; }; pub const Device = *opaque { pub const createBindGroup = wgpuDeviceCreateBindGroup; extern fn wgpuDeviceCreateBindGroup(device: Device, descriptor: *const BindGroupDescriptor) BindGroup; pub const createBindGroupLayout = wgpuDeviceCreateBindGroupLayout; extern fn wgpuDeviceCreateBindGroupLayout( device: Device, descriptor: *const BindGroupLayoutDescriptor, ) BindGroupLayout; pub const createBuffer = wgpuDeviceCreateBuffer; extern fn wgpuDeviceCreateBuffer(device: Device, descriptor: *const BufferDescriptor) Buffer; pub const createCommandEncoder = wgpuDeviceCreateCommandEncoder; extern fn wgpuDeviceCreateCommandEncoder( device: Device, descriptor: *const CommandEncoderDescriptor, ) CommandEncoder; pub const createComputePipeline = wgpuDeviceCreateComputePipeline; extern fn wgpuDeviceCreateComputePipeline( device: Device, descriptor: *const ComputePipelineDescriptor, ) ComputePipeline; pub const createComputePipelineAsync = wgpuDeviceCreateComputePipelineAsync; extern fn wgpuDeviceCreateComputePipelineAsync( device: Device, descriptor: *const ComputePipelineDescriptor, callback: CreateComputePipelineAsyncCallback, userdata: *c_void, ) void; pub const createPipelineLayout = wgpuDeviceCreatePipelineLayout; extern fn wgpuDeviceCreatePipelineLayout( device: Device, descriptor: *const PipelineLayoutDescriptor, ) PipelineLayout; pub const createQuerySet = wgpuDeviceCreateQuerySet; extern fn wgpuDeviceCreateQuerySet(device: Device, descriptor: *const QuerySetDescriptor) QuerySet; pub const createRenderBundleEncoder = wgpuDeviceCreateRenderBundleEncoder; extern fn wgpuDeviceCreateRenderBundleEncoder( device: Device, descriptor: *const RenderBundleEncoderDescriptor, ) RenderBundleEncoder; pub const createRenderPipeline = wgpuDeviceCreateRenderPipeline; extern fn wgpuDeviceCreateRenderPipeline( device: Device, descriptor: *const RenderPipelineDescriptor, ) RenderPipeline; pub const createRenderPipelineAsync = wgpuDeviceCreateRenderPipelineAsync; extern fn wgpuDeviceCreateRenderPipelineAsync( device: Device, descriptor: *const RenderPipelineDescriptor, callback: CreateRenderPipelineAsyncCallback, userdata: *c_void, ) void; pub const createSampler = wgpuDeviceCreateSampler; extern fn wgpuDeviceCreateSampler(device: Device, descriptor: *const SamplerDescriptor) Sampler; pub const createShaderModule = wgpuDeviceCreateShaderModule; extern fn wgpuDeviceCreateShaderModule(device: Device, descriptor: *const ShaderModuleDescriptor) ShaderModule; pub const createSwapChain = wgpuDeviceCreateSwapChain; extern fn wgpuDeviceCreateSwapChain( device: Device, surface: Surface, descriptor: *const SwapChainDescriptor, ) SwapChain; pub const createTexture = wgpuDeviceCreateTexture; extern fn wgpuDeviceCreateTexture(device: Device, descriptor: *const TextureDescriptor) Texture; pub const destroy = wgpuDeviceDestroy; extern fn wgpuDeviceDestroy(device: Device) void; pub const getLimits = wgpuDeviceGetLimits; extern fn wgpuDeviceGetLimits(device: Device, limits: *SupportedLimits) bool; pub const getQueue = wgpuDeviceGetQueue; extern fn wgpuDeviceGetQueue(device: Device) Queue; pub const popErrorScope = wgpuDevicePopErrorScope; extern fn wgpuDevicePopErrorScope(device: Device, callback: ErrorCallback, userdata: *c_void) bool; pub const pushErrorScope = wgpuDevicePushErrorScope; extern fn wgpuDevicePushErrorScope(device: Device, filter: ErrorFilter) void; pub const setDeviceLostCallback = wgpuDeviceSetDeviceLostCallback; extern fn wgpuDeviceSetDeviceLostCallback( device: Device, callback: DeviceLostCallback, userdata: *c_void, ) void; pub const setUncapturedErrorCallback = wgpuDeviceSetUncapturedErrorCallback; extern fn wgpuDeviceSetUncapturedErrorCallback( device: Device, callback: ErrorCallback, userdata: *c_void, ) void; // WGPU extras pub const poll = wgpuDevicePoll; extern fn wgpuDevicePoll(device: Device, force_wait: bool) void; pub const drop = wgpuDeviceDrop; extern fn wgpuDeviceDrop(device: Device) void; }; pub const Instance = *allowzero opaque { pub const createSurface = wgpuInstanceCreateSurface; extern fn wgpuInstanceCreateSurface(instance: Instance, descriptor: *const SurfaceDescriptor) Surface; pub const processEvents = wgpuInstanceProcessEvents; extern fn wgpuInstanceProcessEvents(instance: Instance) void; pub const requestAdapter = wgpuInstanceRequestAdapter; extern fn wgpuInstanceRequestAdapter( instance: Instance, options: *const RequestAdapterOptions, callback: RequestAdapterCallback, userdata: ?*c_void, ) void; }; pub const base = @intToPtr(Instance, 0); pub const PipelineLayout = *opaque { // WGPU extras pub const drop = wgpuPipelineLayoutDrop; extern fn wgpuPipelineLayoutDrop(pipeline_layout: PipelineLayout) void; }; pub const QuerySet = *opaque { pub const destroy = wgpuQuerySetDestroy; extern fn wgpuQuerySetDestroy(query_set: QuerySet) void; // WGPU extras pub const drop = wgpuQuerySetDrop; extern fn wgpuQuerySetDrop(query_set: QuerySet) void; }; pub const Queue = *opaque { pub const onSubmittedWorkDone = wgpuQueueOnSubmittedWorkDone; extern fn wgpuQueueOnSubmittedWorkDone( queue: Queue, signal_value: u64, callback: QueueWorkDoneCallback, userdata: *c_void, ) void; pub const submit = wgpuQueueSubmit; extern fn wgpuQueueSubmit(queue: Queue, command_count: u32, commands: [*]const CommandBuffer) void; pub const writeBuffer = wgpuQueueWriteBuffer; extern fn wgpuQueueWriteBuffer( queue: Queue, buffer: Buffer, buffer_offset: u64, data: *const c_void, size: usize, ) void; pub const writeTexture = wgpuQueueWriteTexture; extern fn wgpuQueueWriteTexture( queue: Queue, destination: *const ImageCopyTexture, data: *const c_void, data_size: usize, data_layout: *const TextureDataLayout, write_size: *const Extent3D, ) void; }; pub const RenderBundle = *opaque { // WGPU extras pub const drop = wgpuRenderBundleDrop; extern fn wgpuRenderBundleDrop(render_bundle: RenderBundle) void; }; pub const RenderBundleEncoder = *opaque { pub const draw = wgpuRenderBundleEncoderDraw; extern fn wgpuRenderBundleEncoderDraw( render_bundle_encoder: RenderBundleEncoder, vertex_count: u32, instance_count: u32, first_vertex: u32, first_instance: u32, ) void; pub const drawIndexed = wgpuRenderBundleEncoderDrawIndexed; extern fn wgpuRenderBundleEncoderDrawIndexed( render_bundle_encoder: RenderBundleEncoder, index_count: u32, instance_count: u32, first_index: u32, base_vertex: i32, first_instance: u32, ) void; pub const drawIndexedIndirect = wgpuRenderBundleEncoderDrawIndexedIndirect; extern fn wgpuRenderBundleEncoderDrawIndexedIndirect( render_bundle_encoder: RenderBundleEncoder, indirect_buffer: Buffer, indirect_offset: u64, ) void; pub const drawIndirect = wgpuRenderBundleEncoderDrawIndirect; extern fn wgpuRenderBundleEncoderDrawIndirect( render_bundle_encoder: RenderBundleEncoder, indirect_buffer: Buffer, indirect_offset: u64, ) void; pub const finish = wgpuRenderBundleEncoderFinish; extern fn wgpuRenderBundleEncoderFinish( render_bundle_encoder: RenderBundleEncoder, descriptor: *const RenderBundleDescriptor, ) RenderBundle; pub const insertDebugMarker = wgpuRenderBundleEncoderInsertDebugMarker; extern fn wgpuRenderBundleEncoderInsertDebugMarker( render_bundle_encoder: RenderBundleEncoder, marker_label: [*:0]const u8, ) void; pub const popDebugGroup = wgpuRenderBundleEncoderPopDebugGroup; extern fn wgpuRenderBundleEncoderPopDebugGroup(render_bundle_encoder: RenderBundleEncoder) void; pub const pushDebugGroup = wgpuRenderBundleEncoderPushDebugGroup; extern fn wgpuRenderBundleEncoderPushDebugGroup( render_bundle_encoder: RenderBundleEncoder, group_label: [*:0]const u8, ) void; pub const setBindGroup = wgpuRenderBundleEncoderSetBindGroup; extern fn wgpuRenderBundleEncoderSetBindGroup( render_bundle_encoder: RenderBundleEncoder, group_index: u32, group: BindGroup, dynamic_offset_count: u32, dynamic_offsets: [*]const u32, ) void; pub const setIndexBuffer = wgpuRenderBundleEncoderSetIndexBuffer; extern fn wgpuRenderBundleEncoderSetIndexBuffer( render_bundle_encoder: RenderBundleEncoder, buffer: Buffer, format: IndexFormat, offset: u64, size: u64, ) void; pub const setPipeline = wgpuRenderBundleEncoderSetPipeline; extern fn wgpuRenderBundleEncoderSetPipeline(render_bundle_encoder: RenderBundleEncoder, pipeline: RenderPipeline) void; pub const setVertexBuffer = wgpuRenderBundleEncoderSetVertexBuffer; extern fn wgpuRenderBundleEncoderSetVertexBuffer( render_bundle_encoder: RenderBundleEncoder, slot: u32, buffer: Buffer, offset: u64, size: u64, ) void; }; pub const RenderPassEncoder = *opaque { pub const beginOcclusionQuery = wgpuRenderPassEncoderBeginOcclusionQuery; extern fn wgpuRenderPassEncoderBeginOcclusionQuery(render_pass_encoder: RenderPassEncoder, query_index: u32) void; pub const beginPipelineStatisticsQuery = wgpuRenderPassEncoderBeginPipelineStatisticsQuery; extern fn wgpuRenderPassEncoderBeginPipelineStatisticsQuery( render_pass_encoder: RenderPassEncoder, query_set: QuerySet, query_index: u32, ) void; pub const draw = wgpuRenderPassEncoderDraw; extern fn wgpuRenderPassEncoderDraw( render_pass_encoder: RenderPassEncoder, vertex_count: u32, instance_count: u32, first_vertex: u32, first_instance: u32, ) void; pub const drawIndexed = wgpuRenderPassEncoderDrawIndexed; extern fn wgpuRenderPassEncoderDrawIndexed( render_pass_encoder: RenderPassEncoder, index_count: u32, instance_count: u32, first_index: u32, base_vertex: i32, first_instance: u32, ) void; pub const drawIndexedIndirect = wgpuRenderPassEncoderDrawIndexedIndirect; extern fn wgpuRenderPassEncoderDrawIndexedIndirect( render_pass_encoder: RenderPassEncoder, indirect_buffer: Buffer, indirect_offset: u64, ) void; pub const drawIndirect = wgpuRenderPassEncoderDrawIndirect; extern fn wgpuRenderPassEncoderDrawIndirect( render_pass_encoder: RenderPassEncoder, indirect_buffer: Buffer, indirect_offset: u64, ) void; pub const endOcclusionQuery = wgpuRenderPassEncoderEndOcclusionQuery; extern fn wgpuRenderPassEncoderEndOcclusionQuery(render_pass_encoder: RenderPassEncoder) void; pub const endPass = wgpuRenderPassEncoderEndPass; extern fn wgpuRenderPassEncoderEndPass(render_pass_encoder: RenderPassEncoder) void; pub const endPipelineStatisticsQuery = wgpuRenderPassEncoderEndPipelineStatisticsQuery; extern fn wgpuRenderPassEncoderEndPipelineStatisticsQuery(render_pass_encoder: RenderPassEncoder) void; pub const executeBundles = wgpuRenderPassEncoderExecuteBundles; extern fn wgpuRenderPassEncoderExecuteBundles( render_pass_encoder: RenderPassEncoder, bundles_count: u32, bundles: *RenderBundle, ) void; pub const insertDebugMarker = wgpuRenderPassEncoderInsertDebugMarker; extern fn wgpuRenderPassEncoderInsertDebugMarker(render_pass_encoder: RenderPassEncoder, marker_label: [*:0]const u8) void; pub const popDebugGroup = wgpuRenderPassEncoderPopDebugGroup; extern fn wgpuRenderPassEncoderPopDebugGroup(render_pass_encoder: RenderPassEncoder) void; pub const pushDebugGroup = wgpuRenderPassEncoderPushDebugGroup; extern fn wgpuRenderPassEncoderPushDebugGroup(render_pass_encoder: RenderPassEncoder, group_label: [*:0]const u8) void; pub const setBindGroup = wgpuRenderPassEncoderSetBindGroup; extern fn wgpuRenderPassEncoderSetBindGroup( render_pass_encoder: RenderPassEncoder, group_index: u32, group: BindGroup, dynamic_offset_count: u32, dynamic_offsets: *u32, ) void; pub const setBlendConstant = wgpuRenderPassEncoderSetBlendConstant; extern fn wgpuRenderPassEncoderSetBlendConstant(render_pass_encoder: RenderPassEncoder, color: *Color) void; pub const setIndexBuffer = wgpuRenderPassEncoderSetIndexBuffer; extern fn wgpuRenderPassEncoderSetIndexBuffer( render_pass_encoder: RenderPassEncoder, buffer: Buffer, format: IndexFormat, offset: u64, size: u64, ) void; pub const setPipeline = wgpuRenderPassEncoderSetPipeline; extern fn wgpuRenderPassEncoderSetPipeline(render_pass_encoder: RenderPassEncoder, pipeline: RenderPipeline) void; pub const setScissorRect = wgpuRenderPassEncoderSetScissorRect; extern fn wgpuRenderPassEncoderSetScissorRect( render_pass_encoder: RenderPassEncoder, x: u32, y: u32, width: u32, height: u32, ) void; pub const setStencilReference = wgpuRenderPassEncoderSetStencilReference; extern fn wgpuRenderPassEncoderSetStencilReference(render_pass_encoder: RenderPassEncoder, reference: u32) void; pub const setVertexBuffer = wgpuRenderPassEncoderSetVertexBuffer; extern fn wgpuRenderPassEncoderSetVertexBuffer( render_pass_encoder: RenderPassEncoder, slot: u32, buffer: Buffer, offset: u64, size: u64, ) void; pub const setViewport = wgpuRenderPassEncoderSetViewport; extern fn wgpuRenderPassEncoderSetViewport( render_pass_encoder: RenderPassEncoder, x: f32, y: f32, width: f32, height: f32, min_depth: f32, max_depth: f32, ) void; pub const writeTimestamp = wgpuRenderPassEncoderWriteTimestamp; extern fn wgpuRenderPassEncoderWriteTimestamp( render_pass_encoder: RenderPassEncoder, query_set: QuerySet, query_index: u32, ) void; // WGPU extras pub const setPushConstants = wgpuRenderPassEncoderSetPushConstants; extern fn wgpuRenderPassEncoderSetPushConstants( encoder: RenderPassEncoder, stages: ShaderStage, offset: u32, sizeBytes: u32, data: *const c_void, ) void; }; pub const RenderPipeline = *opaque { pub const getBindGroupLayout = wgpuRenderPipelineGetBindGroupLayout; extern fn wgpuRenderPipelineGetBindGroupLayout(render_pipeline: RenderPipeline, group_index: u32) BindGroupLayout; pub const setLabel = wgpuRenderPipelineSetLabel; extern fn wgpuRenderPipelineSetLabel(render_pipeline: RenderPipeline, label: ?[*:0]const u8) void; // WGPU extras pub const drop = wgpuRenderPipelineDrop; extern fn wgpuRenderPipelineDrop(render_pipeline: RenderPipeline) void; }; pub const Sampler = *opaque { // WGPU extras pub const drop = wgpuSamplerDrop; extern fn wgpuSamplerDrop(sampler: Sampler) void; }; pub const ShaderModule = *opaque { pub const setLabel = wgpuShaderModuleSetLabel; extern fn wgpuShaderModuleSetLabel(shader_module: ShaderModule, label: ?[*:0]const u8) void; // WGPU extras pub const drop = wgpuShaderModuleDrop; extern fn wgpuShaderModuleDrop(shader_module: ShaderModule) void; }; pub const Surface = *opaque { pub const getPreferredFormat = wgpuSurfaceGetPreferredFormat; extern fn wgpuSurfaceGetPreferredFormat( surface: Surface, adapter: Adapter, ) TextureFormat; }; pub const SwapChain = *opaque { pub const getCurrentTextureView = wgpuSwapChainGetCurrentTextureView; extern fn wgpuSwapChainGetCurrentTextureView(swap_chain: SwapChain) ?TextureView; pub const present = wgpuSwapChainPresent; extern fn wgpuSwapChainPresent(swap_chain: SwapChain) void; }; pub const Texture = *opaque { pub const createView = wgpuTextureCreateView; extern fn wgpuTextureCreateView(texture: Texture, descriptor: *TextureViewDescriptor) TextureView; pub const destroy = wgpuTextureDestroy; extern fn wgpuTextureDestroy(texture: Texture) void; // WGPU extras pub const drop = wgpuTextureDrop; extern fn wgpuTextureDrop(texture: Texture) void; }; pub const TextureView = *opaque { // WGPU extras pub const drop = wgpuTextureViewDrop; extern fn wgpuTextureViewDrop(texture_view: TextureView) void; }; pub const AdapterType = enum(u32) { discrete_gpu = 0x00000000, integrated_gpu = 0x00000001, cpu = 0x00000002, unknown = 0x00000003, }; pub const AddressMode = enum(u32) { repeat = 0x00000000, mirror_repeat = 0x00000001, clamp_to_edge = 0x00000002, }; pub const BackendType = enum(u32) { none, webgpu, d3d11, d3d12, metal, vulkan, opengl, opengles, }; pub const BlendFactor = enum(u32) { zero = 0x00000000, one = 0x00000001, src = 0x00000002, one_minus_src = 0x00000003, src_alpha = 0x00000004, one_minus_src_alpha = 0x00000005, dst = 0x00000006, one_minus_dst = 0x00000007, dst_alpha = 0x00000008, one_minus_dst_alpha = 0x00000009, src_alpha_saturated = 0x0000000A, constant = 0x0000000B, one_minus_constant = 0x0000000C, }; pub const BlendOperation = enum(u32) { add = 0x00000000, subtract = 0x00000001, reverse_subtract = 0x00000002, min = 0x00000003, max = 0x00000004, }; pub const BufferBindingType = enum(u32) { uniform = 0x00000001, storage = 0x00000002, read_only_storage = 0x00000003, }; pub const BufferMapAsyncStatus = enum(u32) { success = 0x00000000, @"error" = 0x00000001, unknown = 0x00000002, device_lost = 0x00000003, destroyed_before_callback = 0x00000004, unmapped_before_callback = 0x00000005, }; pub const CompareFunction = enum(u32) { never = 0x00000001, less = 0x00000002, less_equal = 0x00000003, greater = 0x00000004, greater_equal = 0x00000005, equal = 0x00000006, not_equal = 0x00000007, always = 0x00000008, }; pub const CompilationMessageType = enum(u32) { @"error", warning, info, }; pub const CreatePipelineAsyncStatus = enum(u32) { success = 0x00000000, @"error" = 0x00000001, device_lost = 0x00000002, device_destroyed = 0x00000003, unknown = 0x00000004, }; pub const CullMode = enum(u32) { none = 0x00000000, front = 0x00000001, back = 0x00000002, }; pub const DeviceLostReason = enum(u32) { @"undefined", destroyed, }; pub const ErrorFilter = enum(u32) { none = 0x00000000, validation = 0x00000001, out_of_memory = 0x00000002, }; pub const ErrorType = enum(u32) { no_error = 0x00000000, validation = 0x00000001, out_of_memory = 0x00000002, unknown = 0x00000003, device_lost = 0x00000004, }; pub const FeatureName = enum(u32) { @"undefined", depth_clamping, depth24_unorm_stencil8, depth32_float_stencil8, timestamp_query, pipeline_statistics_query, texture_compression_bc, }; pub const FilterMode = enum(u32) { nearest = 0x00000000, linear = 0x00000001, }; pub const FrontFace = enum(u32) { ccw = 0x00000000, cw = 0x00000001, }; pub const IndexFormat = enum(u32) { unknown = 0, uint16 = 0x00000001, uint32 = 0x00000002, }; pub const LoadOp = enum(u32) { clear = 0x00000000, load = 0x00000001, }; pub const PipelineStatisticName = enum(u32) { vertex_shader_invocations = 0x00000000, clipper_invocations = 0x00000001, clipper_primitives_out = 0x00000002, fragment_shader_invocations = 0x00000003, compute_shader_invocations = 0x00000004, }; pub const PowerPreference = enum(u32) { low_power, high_performance, }; pub const PresentMode = enum(u32) { immediate = 0x00000000, mailbox = 0x00000001, fifo = 0x00000002, }; pub const PrimitiveTopology = enum(u32) { pointlist = 0x00000000, line_list = 0x00000001, line_strip = 0x00000002, triangle_list = 0x00000003, triangle_strip = 0x00000004, }; pub const QueryType = enum(u32) { occlusion = 0x00000000, pipeline_statistics = 0x00000001, timestamp = 0x00000002, }; pub const QueueWorkDoneStatus = enum(u32) { success = 0x00000000, @"error" = 0x00000001, unknown = 0x00000002, device_lost = 0x00000003, }; pub const RequestAdapterStatus = enum(u32) { success, unavailable, @"error", unknown, }; pub const RequestDeviceStatus = enum(u32) { success, @"error", unknown, }; pub const SType = enum(u32) { invalid = 0x00000000, surface_descriptor_from_metal_layer = 0x00000001, surface_descriptor_from_windows_hwnd = 0x00000002, surface_descriptor_from_xlib = 0x00000003, surface_descriptor_from_canvas_html_selector = 0x00000004, shader_module_spirv_descriptor = 0x00000005, shader_module_wgsl_descriptor = 0x00000006, primitive_depth_clamping_state = 0x00000007, // WGPU extras // Start at 6 to prevent collisions with webgpu STypes device_extras = 0x60000001, adapter_extras = 0x60000002, }; pub const SamplerBindingType = enum(u32) { filtering = 0x00000001, non_filtering = 0x00000002, comparison = 0x00000003, }; pub const StencilOperation = enum(u32) { keep = 0x00000000, zero = 0x00000001, replace = 0x00000002, invert = 0x00000003, increment_clamp = 0x00000004, decrement_clamp = 0x00000005, increment_wrap = 0x00000006, decrement_wrap = 0x00000007, }; pub const StorageTextureAccess = enum(u32) { @"undefined", write_only, }; pub const StoreOp = enum(u32) { store, discard, }; pub const TextureAspect = enum(u32) { all = 0x00000000, stencil_only = 0x00000001, depth_only = 0x00000002, }; pub const TextureComponentType = enum(u32) { float = 0x00000000, sint = 0x00000001, uint = 0x00000002, depth_comparison = 0x00000003, }; pub const TextureDimension = enum(u32) { @"1d" = 0x00000000, @"2d" = 0x00000001, @"3d" = 0x00000002, }; pub const TextureFormat = enum(u32) { r8_unorm = 1, r8_snorm, r8_uint, r8_sint, r16_uint, r16_sint, r16_float, rg8_unorm, rg8_snorm, rg8_uint, rg8_sint, r32_float, r32_uint, r32_sint, rg16_uint, rg16_sint, rg16_float, rgba8_unorm, rgba8_unorm_srgb, rgba8_snorm, rgba8_uint, rgba8_sint, bgra8_unorm, bgra8_unorm_srgb, rgb10_a_2_unorm, rg11b10_ufloat, rgb9e5_ufloat, rg32_float, rg32_uint, rg32_sint, rgba16_uint, rgba16_sint, rgba16_float, rgba32_float, rgba32_uint, rgba32_sint, stencil8, depth16_unorm, depth24_plus, depth24_plus_stencil_8, depth32_float, bc1_rgba_unorm, bc1_rgba_unorm_srgb, bc2_rgba_unorm, bc2_rgba_unorm_srgb, bc3_rgba_unorm, bc3_rgba_unorm_srgb, bc4_r_unorm, bc4_r_snorm, bc5_rg_unorm, bc5_rg_snorm, bc6h_rgb_ufloat, bc6h_rgb_float, bc7_rgba_unorm, bc7_rgba_unorm_srgb, }; pub const TextureSampleType = enum(u32) { float = 0x00000001, unfilterable_float = 0x00000002, depth = 0x00000003, sint = 0x00000004, uint = 0x00000005, }; pub const TextureViewDimension = enum(u32) { @"1d" = 0x00000001, @"2d" = 0x00000002, @"2darray" = 0x00000003, cube = 0x00000004, cube_array = 0x00000005, @"3d" = 0x00000006, }; pub const VertexFormat = enum(u32) { uint8x_2 = 0x00000001, uint8x_4 = 0x00000002, sint8x_2 = 0x00000003, sint8x_4 = 0x00000004, unorm_8x_2 = 0x00000005, unorm_8x_4 = 0x00000006, snorm_8x_2 = 0x00000007, snorm_8x_4 = 0x00000008, uint16x_2 = 0x00000009, uint16x_4 = 0x0000000A, sint16x_2 = 0x0000000B, sint16x_4 = 0x0000000C, unorm_16x_2 = 0x0000000D, unorm_16x_4 = 0x0000000E, snorm_16x_2 = 0x0000000F, snorm_16x_4 = 0x00000010, float_16x_2 = 0x00000011, float_16x_4 = 0x00000012, float_32 = 0x00000013, float_32x_2 = 0x00000014, float_32x_3 = 0x00000015, float_32x_4 = 0x00000016, uint32 = 0x00000017, uint32x_2 = 0x00000018, uint32x_3 = 0x00000019, uint32x_4 = 0x0000001A, sint32 = 0x0000001B, sint32x_2 = 0x0000001C, sint32x_3 = 0x0000001D, sint32x_4 = 0x0000001E, }; pub const VertexStepMode = enum(u32) { vertex, instance, }; fn Flags(comptime names: []const []const u8, default: bool) type { const std = @import("std"); var bool_fields: [names.len]std.builtin.TypeInfo.StructField = undefined; for (names) |name, i| { bool_fields[i] = .{ .name = name, .field_type = bool, .alignment = 0, .default_value = default, .is_comptime = false, }; } var fields: []const std.builtin.TypeInfo.StructField = &bool_fields; if (names.len % 8 != 0) { // Pad bits const T = std.meta.Int(.unsigned, 8 - names.len % 8); const pad_default: T = 0; fields = fields ++ &[_]std.builtin.TypeInfo.StructField{.{ .name = "_bit_pad", .field_type = T, .alignment = 0, .default_value = pad_default, .is_comptime = false, }}; } var byte_size = (names.len - 1) / 8 + 1; while (byte_size < 4) : (byte_size += 1) { const pad_default: u8 = 0; fields = fields ++ &[_]std.builtin.TypeInfo.StructField{.{ .name = std.fmt.comptimePrint("_byte_pad{}", .{byte_size}), .field_type = u8, .alignment = 0, .default_value = pad_default, .is_comptime = false, }}; } const T = @Type(.{ .Struct = .{ .layout = .Packed, .fields = fields, .decls = &.{}, .is_tuple = false, } }); std.debug.assert(@bitSizeOf(T) == 32 and @sizeOf(T) == 4); return T; } pub const BufferUsage = Flags(&.{ "map_read", "map_write", "copy_src", "copy_dst", "index", "vertex", "uniform", "storage", "indirect", "query_resolve", }, false); pub const ColorWriteMask = Flags(&.{ "red", "green", "blue", "alpha", }, true); pub const MapMode = Flags(&.{ "read", "write" }, false); pub const ShaderStage = Flags(&.{ "vertex", "fragment", "compute" }, false); pub const TextureUsage = Flags(&.{ "copy_src", "copy_dst", "texture_binding", "storage_binding", "render_attachment", }, false); pub const ChainedStruct = extern struct { next: ?*const ChainedStruct, s_type: SType, }; pub const ChainedStructOut = extern struct { next: ?*ChainedStructOut, s_type: SType, }; pub const AdapterProperties = extern struct { next_in_chain: ?*ChainedStructOut = null, vendor_id: u32, device_id: u32, name: [*:0]const u8, driver_description: [*:0]const u8, adapter_type: AdapterType, backend_type: BackendType, }; pub const BindGroupEntry = extern struct { next_in_chain: ?*const ChainedStruct = null, binding: u32, buffer: Buffer, offset: u64, size: u64, sampler: Sampler, texture_view: TextureView, }; pub const BlendComponent = extern struct { operation: BlendOperation, src_factor: BlendFactor, dst_factor: BlendFactor, }; pub const BufferBindingLayout = extern struct { next_in_chain: ?*const ChainedStruct = null, type: BufferBindingType, has_dynamic_offset: bool, min_binding_size: u64, }; pub const BufferDescriptor = extern struct { next_in_chain: ?*const ChainedStruct = null, label: ?[*:0]const u8 = null, usage: BufferUsage, size: u64, mapped_at_creation: bool, }; pub const Color = extern struct { r: f64, g: f64, b: f64, a: f64, }; pub const CommandBufferDescriptor = extern struct { next_in_chain: ?*const ChainedStruct = null, label: ?[*:0]const u8 = null, }; pub const CommandEncoderDescriptor = extern struct { next_in_chain: ?*const ChainedStruct = null, label: ?[*:0]const u8 = null, }; pub const CompilationMessage = extern struct { next_in_chain: ?*const ChainedStruct = null, message: [*:0]const u8, type: CompilationMessageType, line_num: u64, line_pos: u64, offset: u64, length: u64, }; pub const ComputePassDescriptor = extern struct { next_in_chain: ?*const ChainedStruct = null, label: ?[*:0]const u8 = null, }; pub const ConstantEntry = extern struct { next_in_chain: ?*const ChainedStruct = null, key: [*:0]const u8, value: f64, }; pub const Extent3D = extern struct { width: u32, height: u32, depth_or_array_layers: u32, }; pub const InstanceDescriptor = extern struct { next_in_chain: ?*const ChainedStruct = null, }; pub const Limits = extern struct { max_texture_dimension_1d: u32 = 0, max_texture_dimension_2d: u32 = 0, max_texture_dimension_3d: u32 = 0, max_texture_array_layers: u32 = 0, max_bind_groups: u32 = 0, max_dynamic_uniform_buffers_per_pipeline_layout: u32 = 0, max_dynamic_storage_buffers_per_pipeline_layout: u32 = 0, max_sampled_textures_per_shader_stage: u32 = 0, max_samplers_per_shader_stage: u32 = 0, max_storage_buffers_per_shader_stage: u32 = 0, max_storage_textures_per_shader_stage: u32 = 0, max_uniform_buffers_per_shader_stage: u32 = 0, max_uniform_buffer_binding_size: u64 = 0, max_storage_buffer_binding_size: u64 = 0, min_uniform_buffer_offset_alignment: u32 = 0, min_storage_buffer_offset_alignment: u32 = 0, max_vertex_buffers: u32 = 0, max_vertex_attributes: u32 = 0, max_vertex_buffer_array_stride: u32 = 0, max_inter_stage_shader_components: u32 = 0, max_compute_workgroup_storage_size: u32 = 0, max_compute_invocations_per_workgroup: u32 = 0, max_compute_workgroup_size_x: u32 = 0, max_compute_workgroup_size_y: u32 = 0, max_compute_workgroup_size_z: u32 = 0, max_compute_workgroups_per_dimension: u32 = 0, }; pub const MultisampleState = extern struct { next_in_chain: ?*const ChainedStruct = null, count: u32, mask: u32, alpha_to_coverage_enabled: bool, }; pub const Origin3D = extern struct { x: u32, y: u32, z: u32, }; pub const PipelineLayoutDescriptor = extern struct { next_in_chain: ?*const ChainedStruct = null, label: ?[*:0]const u8 = null, bind_group_layout_count: u32, bind_group_layouts: ?*BindGroupLayout, }; pub const PrimitiveDepthClampingState = extern struct { chain: ChainedStruct, clamp_depth: bool, }; pub const PrimitiveState = extern struct { next_in_chain: ?*const ChainedStruct = null, topology: PrimitiveTopology, strip_index_format: IndexFormat, front_face: FrontFace, cull_mode: CullMode, }; pub const QuerySetDescriptor = extern struct { next_in_chain: ?*const ChainedStruct = null, label: ?[*:0]const u8 = null, type: QueryType, count: u32, pipeline_statistics: *PipelineStatisticName, pipeline_statistics_count: u32, }; pub const RenderBundleDescriptor = extern struct { next_in_chain: ?*const ChainedStruct = null, label: ?[*:0]const u8 = null, }; pub const RenderBundleEncoderDescriptor = extern struct { next_in_chain: ?*const ChainedStruct = null, label: ?[*:0]const u8 = null, color_formats_count: u32, color_formats: *TextureFormat, depth_stencil_format: TextureFormat, sample_count: u32, }; pub const RenderPassDepthStencilAttachment = extern struct { view: TextureView, depth_load_op: LoadOp, depth_store_op: StoreOp, clear_depth: f32, depth_read_only: bool, stencil_load_op: LoadOp, stencil_store_op: StoreOp, clear_stencil: u32, stencil_read_only: bool, }; pub const RequestAdapterOptions = extern struct { next_in_chain: ?*const ChainedStruct = null, compatible_surface: Surface, power_preference: PowerPreference, force_fallback_adapter: bool, }; pub const SamplerBindingLayout = extern struct { next_in_chain: ?*const ChainedStruct = null, type: SamplerBindingType, }; pub const SamplerDescriptor = extern struct { next_in_chain: ?*const ChainedStruct = null, label: ?[*:0]const u8 = null, address_mode_u: AddressMode, address_mode_v: AddressMode, address_mode_w: AddressMode, mag_filter: FilterMode, min_filter: FilterMode, mipmap_filter: FilterMode, lod_min_clamp: f32, lod_max_clamp: f32, compare: CompareFunction, max_anisotropy: u16, }; pub const ShaderModuleDescriptor = extern struct { next_in_chain: ?*const ChainedStruct = null, label: ?[*:0]const u8 = null, }; pub const ShaderModuleSPIRVDescriptor = extern struct { chain: ChainedStruct, code_size: u32, code: *u32, }; pub const ShaderModuleWGSLDescriptor = extern struct { chain: ChainedStruct = .{ .next = null, .s_type = .shader_module_wgsl_descriptor, }, source: [*:0]const u8, }; pub const StencilFaceState = extern struct { compare: CompareFunction, fail_op: StencilOperation, depth_fail_op: StencilOperation, pass_op: StencilOperation, }; pub const StorageTextureBindingLayout = extern struct { next_in_chain: ?*const ChainedStruct = null, access: StorageTextureAccess, format: TextureFormat, view_dimension: TextureViewDimension, }; pub const SurfaceDescriptor = extern struct { next_in_chain: ?*const ChainedStruct = null, label: ?[*:0]const u8 = null, }; pub const SurfaceDescriptorFromCanvasHTMLSelector = extern struct { chain: ChainedStruct, selector: [*:0]const u8, }; pub const SurfaceDescriptorFromMetalLayer = extern struct { chain: ChainedStruct, layer: *c_void, }; pub const SurfaceDescriptorFromWindowsHWND = extern struct { chain: ChainedStruct, hinstance: *c_void, hwnd: *c_void, }; pub const SurfaceDescriptorFromXlib = extern struct { chain: ChainedStruct = .{ .next = null, .s_type = .surface_descriptor_from_xlib, }, display: *c_void, window: u32, }; pub const SwapChainDescriptor = extern struct { next_in_chain: ?*const ChainedStruct = null, label: ?[*:0]const u8 = null, usage: TextureUsage, format: TextureFormat, width: u32, height: u32, present_mode: PresentMode, }; pub const TextureBindingLayout = extern struct { next_in_chain: ?*const ChainedStruct = null, sample_type: TextureSampleType, view_dimension: TextureViewDimension, multisampled: bool, }; pub const TextureDataLayout = extern struct { next_in_chain: ?*const ChainedStruct = null, offset: u64, bytes_per_row: u32, rows_per_image: u32, }; pub const TextureViewDescriptor = extern struct { next_in_chain: ?*const ChainedStruct = null, label: ?[*:0]const u8 = null, format: TextureFormat, dimension: TextureViewDimension, base_mip_level: u32, mip_level_count: u32, base_array_layer: u32, array_layer_count: u32, aspect: TextureAspect, }; pub const VertexAttribute = extern struct { format: VertexFormat, offset: u64, shader_location: u32, }; pub const BindGroupDescriptor = extern struct { next_in_chain: ?*const ChainedStruct = null, label: ?[*:0]const u8 = null, layout: BindGroupLayout, entry_count: u32, entries: *BindGroupEntry, }; pub const BindGroupLayoutEntry = extern struct { next_in_chain: ?*const ChainedStruct = null, binding: u32, visibility: ShaderStage, buffer: BufferBindingLayout, sampler: SamplerBindingLayout, texture: TextureBindingLayout, storage_texture: StorageTextureBindingLayout, }; pub const BlendState = extern struct { color: BlendComponent, alpha: BlendComponent, }; pub const CompilationInfo = extern struct { next_in_chain: ?*const ChainedStruct = null, message_count: u32, messages: [*]const CompilationMessage, }; pub const DepthStencilState = extern struct { next_in_chain: ?*const ChainedStruct = null, format: TextureFormat, depth_write_enabled: bool, depth_compare: CompareFunction, stencil_front: StencilFaceState, stencil_back: StencilFaceState, stencil_read_mask: u32, stencil_write_mask: u32, depth_bias: i32, depth_bias_slope_scale: f32, depth_bias_clamp: f32, }; pub const ImageCopyBuffer = extern struct { next_in_chain: ?*const ChainedStruct = null, layout: TextureDataLayout, buffer: Buffer, }; pub const ImageCopyTexture = extern struct { next_in_chain: ?*const ChainedStruct = null, texture: Texture, mip_level: u32, origin: Origin3D, aspect: TextureAspect, }; pub const ProgrammableStageDescriptor = extern struct { next_in_chain: ?*const ChainedStruct = null, module: ShaderModule, entry_point: [*:0]const u8, constant_count: u32, constants: [*]const ConstantEntry, }; pub const RenderPassColorAttachment = extern struct { view: TextureView, resolve_target: ?TextureView, load_op: LoadOp, store_op: StoreOp, clear_color: Color, }; pub const RequiredLimits = extern struct { next_in_chain: ?*const ChainedStruct = null, limits: Limits, }; pub const SupportedLimits = extern struct { next_in_chain: ?*ChainedStructOut = null, limits: Limits, }; pub const TextureDescriptor = extern struct { next_in_chain: ?*const ChainedStruct = null, label: ?[*:0]const u8 = null, usage: TextureUsage, dimension: TextureDimension, size: Extent3D, format: TextureFormat, mip_level_count: u32, sample_count: u32, }; pub const VertexBufferLayout = extern struct { array_stride: u64, step_mode: VertexStepMode, attribute_count: u32, attributes: *VertexAttribute, }; pub const BindGroupLayoutDescriptor = extern struct { next_in_chain: ?*const ChainedStruct = null, label: ?[*:0]const u8 = null, entry_count: u32, entries: *BindGroupLayoutEntry, }; pub const ColorTargetState = extern struct { next_in_chain: ?*const ChainedStruct = null, format: TextureFormat, blend: *const BlendState, write_mask: ColorWriteMask, }; pub const ComputePipelineDescriptor = extern struct { next_in_chain: ?*const ChainedStruct = null, label: ?[*:0]const u8 = null, layout: PipelineLayout, compute: ProgrammableStageDescriptor, }; pub const DeviceDescriptor = extern struct { next_in_chain: ?*const ChainedStruct = null, required_features_count: u32, required_features: [*]const FeatureName, required_limits: ?*const RequiredLimits, }; pub const RenderPassDescriptor = extern struct { next_in_chain: ?*const ChainedStruct = null, label: ?[*:0]const u8 = null, color_attachment_count: u32, color_attachments: ?[*]RenderPassColorAttachment, depth_stencil_attachment: ?*RenderPassDepthStencilAttachment = null, occlusion_query_set: ?QuerySet = null, }; pub const VertexState = extern struct { next_in_chain: ?*const ChainedStruct = null, module: ShaderModule, entry_point: [*:0]const u8, constant_count: u32, constants: [*]const ConstantEntry, buffer_count: u32, buffers: [*]const VertexBufferLayout, }; pub const FragmentState = extern struct { next_in_chain: ?*const ChainedStruct = null, module: ShaderModule, entry_point: [*:0]const u8, constant_count: u32, constants: [*]const ConstantEntry, target_count: u32, targets: *const ColorTargetState, }; pub const RenderPipelineDescriptor = extern struct { next_in_chain: ?*const ChainedStruct = null, label: ?[*:0]const u8 = null, layout: PipelineLayout, vertex: VertexState, primitive: PrimitiveState, depth_stencil: ?*const DepthStencilState, multisample: MultisampleState, fragment: ?*const FragmentState, }; // WGPU extras pub const NativeFeature = enum(u32) { none = 0, texture_adapter_specific_format_features = 0x10000000, }; pub const LogLevel = enum(u32) { off = 0x00000000, err = 0x00000001, warn = 0x00000002, info = 0x00000003, debug = 0x00000004, trace = 0x00000005, }; pub const AdapterExtras = extern struct { chain: ChainedStruct, backend: BackendType, }; pub const DeviceExtras = extern struct { chain: ChainedStruct = .{ .next = null, .s_type = .device_extras, }, native_features: NativeFeature = .none, label: ?[*:0]const u8 = null, trace_path: ?[*:0]const u8 = null, }; pub const LogCallback = fn (level: LogLevel, msg: [*:0]const u8) callconv(.C) void; pub const setLogCallback = wgpuSetLogCallback; extern fn wgpuSetLogCallback(callback: LogCallback) void; pub const setLogLevel = wgpuSetLogLevel; extern fn wgpuSetLogLevel(level: LogLevel) void; pub const getVersion = wgpuGetVersion; extern fn wgpuGetVersion() u32;
zgpu.zig
const std = @import("std"); const protobuf = @import("protobuf.zig"); usingnamespace protobuf; usingnamespace std; const eql = mem.eql; const Demo1 = struct { a: ?u32, pub const _desc_table = .{ .a = fd(1, FieldType{ .Varint = .Simple }) }; pub fn encode(self: Demo1, allocator: *mem.Allocator) ![]u8 { return pb_encode(self, allocator); } pub fn decode(input: []const u8, allocator: *mem.Allocator) !Demo1 { return pb_decode(Demo1, input, allocator); } pub fn deinit(self: Demo1) void { pb_deinit(self); } }; test "basic encoding" { var demo = Demo1{ .a = 150 }; const obtained = try demo.encode(testing.allocator); defer testing.allocator.free(obtained); // 0x08 , 0x96, 0x01 try testing.expectEqualSlices(u8, &[_]u8{ 0x08, 0x96, 0x01 }, obtained); demo.a = 0; const obtained2 = try demo.encode(testing.allocator); defer testing.allocator.free(obtained2); // 0x08 , 0x96, 0x01 try testing.expectEqualSlices(u8, &[_]u8{ 0x08, 0x00 }, obtained2); } test "basic decoding" { const input = [_]u8{ 0x08, 0x96, 0x01 }; const obtained = try Demo1.decode(&input, testing.allocator); try testing.expectEqual(Demo1{ .a = 150 }, obtained); const input2 = [_]u8{ 0x08, 0x00 }; const obtained2 = try Demo1.decode(&input2, testing.allocator); try testing.expectEqual(Demo1{ .a = 0 }, obtained2); } const Demo2 = struct { a: ?u32, b: ?u32, pub const _desc_table = .{ .a = fd(1, .{ .Varint = .Simple }), .b = fd(2, .{ .Varint = .Simple }), }; pub fn encode(self: Demo2, allocator: *mem.Allocator) ![]u8 { return pb_encode(self, allocator); } pub fn deinit(self: Demo2) void { pb_deinit(self); } }; test "basic encoding with optionals" { const demo = Demo2{ .a = 150, .b = null }; const obtained = try demo.encode(testing.allocator); defer testing.allocator.free(obtained); // 0x08 , 0x96, 0x01 try testing.expectEqualSlices(u8, &[_]u8{ 0x08, 0x96, 0x01 }, obtained); const demo2 = Demo2{ .a = 150, .b = 150 }; const obtained2 = try demo2.encode(testing.allocator); defer testing.allocator.free(obtained2); // 0x08 , 0x96, 0x01 try testing.expectEqualSlices(u8, &[_]u8{ 0x08, 0x96, 0x01, 0x10, 0x96, 0x01 }, obtained2); } const WithNegativeIntegers = struct { a: ?i32, // int32 b: ?i32, // sint32 pub const _desc_table = .{ .a = fd(1, .{ .Varint = .ZigZagOptimized }), .b = fd(2, .{ .Varint = .Simple }), }; pub fn encode(self: WithNegativeIntegers, allocator: *mem.Allocator) ![]u8 { return pb_encode(self, allocator); } pub fn deinit(self: WithNegativeIntegers) void { pb_deinit(self); } pub fn decode(input: []const u8, allocator: *mem.Allocator) !WithNegativeIntegers { return pb_decode(WithNegativeIntegers, input, allocator); } }; test "basic encoding with negative numbers" { var demo = WithNegativeIntegers{ .a = -2, .b = -1 }; const obtained = try demo.encode(testing.allocator); defer demo.deinit(); defer testing.allocator.free(obtained); // 0x08 try testing.expectEqualSlices(u8, &[_]u8{ 0x08, 0x03, 0x10, 0xFF, 0xFF, 0xFF, 0xFF, 0x0F }, obtained); const decoded = try WithNegativeIntegers.decode(obtained, testing.allocator); try testing.expectEqual(demo, decoded); } const DemoWithAllVarint = struct { const DemoEnum = enum(i32) { SomeValue, SomeOther, AndAnother }; sint32: ?i32, //sint32 sint64: ?i64, //sint64 uint32: ?u32, //uint32 uint64: ?u64, //uint64 a_bool: ?bool, //bool a_enum: ?DemoEnum, // enum pos_int32: ?i32, pos_int64: ?i64, neg_int32: ?i32, neg_int64: ?i64, pub const _desc_table = .{ .sint32 = fd(1, .{ .Varint = .ZigZagOptimized }), .sint64 = fd(2, .{ .Varint = .ZigZagOptimized }), .uint32 = fd(3, .{ .Varint = .Simple }), .uint64 = fd(4, .{ .Varint = .Simple }), .a_bool = fd(5, .{ .Varint = .Simple }), .a_enum = fd(6, .{ .Varint = .Simple }), .pos_int32 = fd(7, .{ .Varint = .Simple }), .pos_int64 = fd(8, .{ .Varint = .Simple }), .neg_int32 = fd(9, .{ .Varint = .Simple }), .neg_int64 = fd(10, .{ .Varint = .Simple }), }; pub fn encode(self: DemoWithAllVarint, allocator: *mem.Allocator) ![]u8 { return pb_encode(self, allocator); } pub fn decode(input: []const u8, allocator: *mem.Allocator) !DemoWithAllVarint { return pb_decode(DemoWithAllVarint, input, allocator); } pub fn deinit(self: DemoWithAllVarint) void { pb_deinit(self); } }; test "DemoWithAllVarint" { var demo = DemoWithAllVarint{ .sint32 = -1, .sint64 = -1, .uint32 = 150, .uint64 = 150, .a_bool = true, .a_enum = DemoWithAllVarint.DemoEnum.AndAnother, .pos_int32 = 1, .pos_int64 = 2, .neg_int32 = -1, .neg_int64 = -2 }; const obtained = try demo.encode(testing.allocator); defer testing.allocator.free(obtained); // 0x08 , 0x96, 0x01 try testing.expectEqualSlices(u8, &[_]u8{ 0x08, 0x01, 0x10, 0x01, 0x18, 0x96, 0x01, 0x20, 0x96, 0x01, 0x28, 0x01, 0x30, 0x02, 0x38, 0x01, 0x40, 0x02, 0x48, 0xFF, 0xFF, 0xFF, 0xFF, 0x0F, 0x50, 0xFE, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x01 }, obtained); const decoded = try DemoWithAllVarint.decode(obtained, testing.allocator); try testing.expectEqual(demo, decoded); } const FixedSizes = struct { sfixed64: ?i64, sfixed32: ?i32, fixed32: ?u32, fixed64: ?u64, double: ?f64, float: ?f32, pub const _desc_table = .{ .sfixed64 = fd(1, .FixedInt), .sfixed32 = fd(2, .FixedInt), .fixed32 = fd(3, .FixedInt), .fixed64 = fd(4, .FixedInt), .double = fd(5, .FixedInt), .float = fd(6, .FixedInt), }; pub fn encode(self: FixedSizes, allocator: *mem.Allocator) ![]u8 { return pb_encode(self, allocator); } pub fn decode(input: []const u8, allocator: *mem.Allocator) !FixedSizes { return pb_decode(FixedSizes, input, allocator); } pub fn deinit(self: FixedSizes) void { pb_deinit(self); } }; test "FixedSizes" { var demo = FixedSizes{ .sfixed64 = -1, .sfixed32 = -2, .fixed32 = 1, .fixed64 = 2, .double = 5.0, // 0x4014000000000000 .float = 5.0, // 0x40a00000 }; const obtained = try demo.encode(testing.allocator); defer testing.allocator.free(obtained); const expected = [_]u8{ 0x08 + 1, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x10 + 5, 0xFE, 0xFF, 0xFF, 0xFF, 0x18 + 5, 0x01, 0x00, 0x00, 0x00, 0x20 + 1, 0x02, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x28 + 1, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x14, 0x40, 0x30 + 5, 0x00, 0x00, 0xa0, 0x40 }; try testing.expectEqualSlices(u8, &expected, obtained); // decoding const decoded = try FixedSizes.decode(&expected, testing.allocator); try testing.expectEqual(demo, decoded); } const WithSubmessages = struct { sub_demo1: ?Demo1, sub_demo2: ?Demo2, pub const _desc_table = .{ .sub_demo1 = fd(1, .SubMessage), .sub_demo2 = fd(2, .SubMessage), }; pub fn encode(self: WithSubmessages, allocator: *mem.Allocator) ![]u8 { return pb_encode(self, allocator); } pub fn deinit(self: WithSubmessages) void { pb_deinit(self); } pub fn decode(input: []const u8, allocator: *mem.Allocator) !WithSubmessages { return pb_decode(WithSubmessages, input, allocator); } pub fn init(allocator: *mem.Allocator) WithSubmessages { return pb_init(WithSubmessages, allocator); } }; test "WithSubmessages" { var demo = WithSubmessages{ .sub_demo1 = .{ .a = 1 }, .sub_demo2 = .{ .a = 2, .b = 3 } }; const obtained = try demo.encode(testing.allocator); defer testing.allocator.free(obtained); try testing.expectEqualSlices(u8, &[_]u8{ 0x08 + 2, 0x02, 0x08, 0x01, 0x10 + 2, 0x04, 0x08, 0x02, 0x10, 0x03 }, obtained); const decoded = try WithSubmessages.decode(obtained, testing.allocator); try testing.expectEqual(demo, decoded); } const WithBytes = struct { list_of_data: ArrayList(u8), pub const _desc_table = .{ .list_of_data = fd(1, .{ .List = .FixedInt }), }; pub fn encode(self: WithBytes, allocator: *mem.Allocator) ![]u8 { return pb_encode(self, allocator); } pub fn deinit(self: WithBytes) void { pb_deinit(self); } pub fn init(allocator: *mem.Allocator) WithBytes { return pb_init(WithBytes, allocator); } pub fn decode(input: []const u8, allocator: *mem.Allocator) !WithBytes { return pb_decode(WithBytes, input, allocator); } }; test "bytes" { var demo = WithBytes.init(testing.allocator); try demo.list_of_data.append(0x08); try demo.list_of_data.append(0x01); defer demo.deinit(); const obtained = try demo.encode(testing.allocator); defer testing.allocator.free(obtained); try testing.expectEqualSlices(u8, &[_]u8{ 0x08 + 2, 0x02, 0x08, 0x01, }, obtained); const decoded = try WithBytes.decode(obtained, testing.allocator); defer decoded.deinit(); try testing.expectEqualSlices(u8, demo.list_of_data.items, decoded.list_of_data.items); } const FixedSizesList = struct { fixed32List: ArrayList(u32), pub const _desc_table = .{ .fixed32List = fd(1, .{ .List = .FixedInt }), }; pub fn encode(self: FixedSizesList, allocator: *mem.Allocator) ![]u8 { return pb_encode(self, allocator); } pub fn deinit(self: FixedSizesList) void { pb_deinit(self); } pub fn init(allocator: *mem.Allocator) FixedSizesList { return pb_init(FixedSizesList, allocator); } pub fn decode(input: []const u8, allocator: *mem.Allocator) !FixedSizesList { return pb_decode(FixedSizesList, input, allocator); } }; fn log_slice(slice: []const u8) void { std.log.warn("{}", .{std.fmt.fmtSliceHexUpper(slice)}); } test "FixedSizesList" { var demo = FixedSizesList.init(testing.allocator); try demo.fixed32List.append(0x01); try demo.fixed32List.append(0x02); try demo.fixed32List.append(0x03); try demo.fixed32List.append(0x04); defer demo.deinit(); const obtained = try demo.encode(testing.allocator); defer testing.allocator.free(obtained); try testing.expectEqualSlices(u8, &[_]u8{ 0x08 + 2, 0x10, 0x01, 0x00, 0x00, 0x00, 0x02, 0x00, 0x00, 0x00, 0x03, 0x00, 0x00, 0x00, 0x04, 0x00, 0x00, 0x00, }, obtained); const decoded = try FixedSizesList.decode(obtained, testing.allocator); defer decoded.deinit(); try testing.expectEqualSlices(u32, demo.fixed32List.items, decoded.fixed32List.items); } const VarintList = struct { varuint32List: ArrayList(u32), pub const _desc_table = .{ .varuint32List = fd(1, .{ .List = .{ .Varint = .Simple } }), }; pub fn encode(self: VarintList, allocator: *mem.Allocator) ![]u8 { return pb_encode(self, allocator); } pub fn deinit(self: VarintList) void { pb_deinit(self); } pub fn init(allocator: *mem.Allocator) VarintList { return pb_init(VarintList, allocator); } pub fn decode(input: []const u8, allocator: *mem.Allocator) !VarintList { return pb_decode(VarintList, input, allocator); } }; test "VarintList" { var demo = VarintList.init(testing.allocator); try demo.varuint32List.append(0x01); try demo.varuint32List.append(0x02); try demo.varuint32List.append(0x03); try demo.varuint32List.append(0x04); defer demo.deinit(); const obtained = try demo.encode(testing.allocator); defer testing.allocator.free(obtained); try testing.expectEqualSlices(u8, &[_]u8{ 0x08 + 2, 0x04, 0x01, 0x02, 0x03, 0x04, }, obtained); const decoded = try VarintList.decode(obtained, testing.allocator); defer decoded.deinit(); try testing.expectEqualSlices(u32, demo.varuint32List.items, decoded.varuint32List.items); } const SubMessageList = struct { subMessageList: ArrayList(Demo1), pub const _desc_table = .{ .subMessageList = fd(1, .{ .List = .SubMessage }), }; pub fn encode(self: SubMessageList, allocator: *mem.Allocator) ![]u8 { return pb_encode(self, allocator); } pub fn deinit(self: SubMessageList) void { pb_deinit(self); } pub fn init(allocator: *mem.Allocator) SubMessageList { return pb_init(SubMessageList, allocator); } pub fn decode(input: []const u8, allocator: *mem.Allocator) !SubMessageList { return pb_decode(SubMessageList, input, allocator); } }; // .{.a = 1} test "SubMessageList" { var demo = SubMessageList.init(testing.allocator); try demo.subMessageList.append(.{ .a = 1 }); try demo.subMessageList.append(.{ .a = 2 }); try demo.subMessageList.append(.{ .a = 3 }); try demo.subMessageList.append(.{ .a = 4 }); defer demo.deinit(); const obtained = try demo.encode(testing.allocator); defer testing.allocator.free(obtained); try testing.expectEqualSlices(u8, &[_]u8{ 0x08 + 2, 0x0C, 0x02, 0x08, 0x01, 0x02, 0x08, 0x02, 0x02, 0x08, 0x03, 0x02, 0x08, 0x04, }, obtained); const decoded = try SubMessageList.decode(obtained, testing.allocator); defer decoded.deinit(); try testing.expectEqualSlices(Demo1, demo.subMessageList.items, decoded.subMessageList.items); } const EmptyLists = struct { varuint32List: ArrayList(u32), varuint32Empty: ArrayList(u32), pub const _desc_table = .{ .varuint32List = fd(1, .{ .List = .{ .Varint = .Simple } }), .varuint32Empty = fd(2, .{ .List = .{ .Varint = .Simple } }), }; pub fn encode(self: EmptyLists, allocator: *mem.Allocator) ![]u8 { return pb_encode(self, allocator); } pub fn deinit(self: EmptyLists) void { pb_deinit(self); } pub fn init(allocator: *mem.Allocator) EmptyLists { return pb_init(EmptyLists, allocator); } pub fn decode(input: []const u8, allocator: *mem.Allocator) !EmptyLists { return pb_decode(EmptyLists, input, allocator); } }; test "EmptyLists" { var demo = EmptyLists.init(testing.allocator); try demo.varuint32List.append(0x01); try demo.varuint32List.append(0x02); try demo.varuint32List.append(0x03); try demo.varuint32List.append(0x04); defer demo.deinit(); const obtained = try demo.encode(testing.allocator); defer testing.allocator.free(obtained); try testing.expectEqualSlices(u8, &[_]u8{ 0x08 + 2, 0x04, 0x01, 0x02, 0x03, 0x04, }, obtained); const decoded = try EmptyLists.decode(obtained, testing.allocator); defer decoded.deinit(); try testing.expectEqualSlices(u32, demo.varuint32List.items, decoded.varuint32List.items); try testing.expectEqualSlices(u32, demo.varuint32Empty.items, decoded.varuint32Empty.items); } const EmptyMessage = struct { pub const _desc_table = .{}; pub fn encode(self: EmptyMessage, allocator: *mem.Allocator) ![]u8 { return pb_encode(self, allocator); } pub fn deinit(self: EmptyMessage) void { pb_deinit(self); } pub fn init(allocator: *mem.Allocator) EmptyMessage { return pb_init(EmptyMessage, allocator); } pub fn decode(input: []const u8, allocator: *mem.Allocator) !EmptyMessage { return pb_decode(EmptyMessage, input, allocator); } }; test "EmptyMessage" { var demo = EmptyMessage.init(testing.allocator); defer demo.deinit(); const obtained = try demo.encode(testing.allocator); defer testing.allocator.free(obtained); try testing.expectEqualSlices(u8, &[_]u8{}, obtained); const decoded = try EmptyMessage.decode(obtained, testing.allocator); defer decoded.deinit(); try testing.expectEqual(demo, decoded); } const DefaultValuesInit = struct { a: ?u32 = 5, b: ?u32, c: ?u32 = 3, d: ?u32, pub const _desc_table = .{ .a = fd(1, .{ .Varint = .Simple }), .b = fd(2, .{ .Varint = .Simple }), .c = fd(3, .{ .Varint = .Simple }), .d = fd(4, .{ .Varint = .Simple }), }; pub fn encode(self: DefaultValuesInit, allocator: *mem.Allocator) ![]u8 { return pb_encode(self, allocator); } pub fn init(allocator: *mem.Allocator) DefaultValuesInit { return pb_init(DefaultValuesInit, allocator); } pub fn deinit(self: DefaultValuesInit) void { pb_deinit(self); } }; test "DefaultValuesInit" { var demo = DefaultValuesInit.init(testing.allocator); try testing.expectEqual(@as(u32, 5), demo.a.?); try testing.expectEqual(@as(u32, 3), demo.c.?); try testing.expect(if (demo.b) |_| false else true); try testing.expect(if (demo.d) |_| false else true); } const OneOfDemo = struct { const a_case = enum { value_1, value_2 }; const a_union = union(a_case) { value_1: u32, value_2: ArrayList(u32), pub const _union_desc = .{ .value_1 = fd(1, .{ .Varint = .Simple }), .value_2 = fd(2, .{ .List = .{ .Varint = .Simple } }) }; }; a: ?a_union, pub const _desc_table = .{ .a = fd(null, .{ .OneOf = a_union }) }; pub fn encode(self: OneOfDemo, allocator: *mem.Allocator) ![]u8 { return pb_encode(self, allocator); } pub fn init(allocator: *mem.Allocator) OneOfDemo { return pb_init(OneOfDemo, allocator); } pub fn deinit(self: OneOfDemo) void { pb_deinit(self); } }; test "OneOfDemo" { var demo = OneOfDemo.init(testing.allocator); defer demo.deinit(); demo.a = .{ .value_1 = 10 }; const obtained = try demo.encode(testing.allocator); defer testing.allocator.free(obtained); try testing.expectEqualSlices(u8, &[_]u8{ 0x08, 10, }, obtained); demo.a = .{ .value_2 = ArrayList(u32).init(testing.allocator) }; try demo.a.?.value_2.append(1); try demo.a.?.value_2.append(2); try demo.a.?.value_2.append(3); try demo.a.?.value_2.append(4); const obtained2 = try demo.encode(testing.allocator); defer testing.allocator.free(obtained2); try testing.expectEqualSlices(u8, &[_]u8{ 0x10 + 2, 0x04, 0x01, 0x02, 0x03, 0x04, }, obtained2); } const MapDemo = struct { a_map: AutoHashMap(u64, u64), pub const _desc_table = .{ .a_map = fd(1, .{ .Map = .{ .key = .{ .t = u64, .pb_data = .{ .Varint = .ZigZagOptimized } }, .value = .{ .t = u64, .pb_data = .{ .Varint = .ZigZagOptimized } }, } }), }; pub fn encode(self: MapDemo, allocator: *mem.Allocator) ![]u8 { return pb_encode(self, allocator); } pub fn init(allocator: *mem.Allocator) MapDemo { return pb_init(MapDemo, allocator); } pub fn deinit(self: MapDemo) void { pb_deinit(self); } }; test "MapDemo" { var demo = MapDemo.init(testing.allocator); defer demo.deinit(); try demo.a_map.put(1, 2); const obtained = try demo.encode(testing.allocator); defer testing.allocator.free(obtained); try testing.expectEqualSlices(u8, &[_]u8{ 0x08 + 2, // tag of a_map 5, // size of a_map 4, // size of the first item in a_map 0x08, // key tag 0x01, // key value 0x10, // value tag 0x02, // value value }, obtained); }
src/tests.zig
const std = @import("std"); const io = std.io; const Allocator = std.mem.Allocator; const File = std.fs.File; const ascI64 = std.sort.asc(i64); fn closeFile(f: *File) void { f.close(); } fn closeNop(f: *File) void {} pub fn main() anyerror!void { const stdout = io.getStdOut().writer(); var arena = std.heap.ArenaAllocator.init(std.heap.page_allocator); defer arena.deinit(); const alloc = &arena.allocator; var args = std.process.args(); _ = args.skip(); // skip arg0 var numbers = std.ArrayList(i64).init(alloc); defer numbers.deinit(); try numbers.append(0); // This line here factors into why part 2 was harder than it needed to be. // Read input file. { var buf: [4000]u8 = undefined; var file: File = undefined; var close = closeFile; if (args.nextPosix()) |path| { const cwd = std.fs.cwd(); file = try cwd.openFile(path, .{}); } else { file = io.getStdIn(); close = closeNop; } defer close(&file); var stream = io.bufferedReader(file.reader()); var rd = stream.reader(); while (try rd.readUntilDelimiterOrEof(&buf, '\n')) |line| { const i = try std.fmt.parseInt(i64, line, 10); try numbers.append(i); } std.sort.sort(i64, numbers.items, {}, ascI64); } // Part 1: { const counts = differences(numbers.items); try stdout.print("Ones = {} Threes = {} Product = {}\n", .{ counts.ones, counts.threes, counts.ones * counts.threes, }); } // Part 2, or: I don't like this part. // // This has added commentary because I think it's a fun problem once it's // explained, but I made some dumb mistakes in writing the answer out. // // First, the tribonacci sequence is not my idea, I am not that smart and // I was going to reuse the Combination iterator I wrote previously for // this. Someone on reddit, bless them, mentioned that the number of // combinations for a run of numbers in this sequence lines up with the // tribonacci sequence. If you write this out by hand, it makes sense, but // is not a dot I would've connected on my own and especially not at 10pm // after a long day of debugging things. // // Seconds, if you look up where I first add the number zero to the list of // numbers, that wasn't there until the very end. This threw off the count // by a factor of two. This is because the first run of numbers was counted // incorrectly as {1,2,3} insted of {0,1,2,3}, so its factor was trib(3) // instead of trib(4). { const data = numbers.items; const count = combinations(data); try stdout.print("Count = {}\n", .{count}); } } const Counter = struct { ones: usize = 0, threes: usize = 0, }; fn differences(data: []const i64) Counter { var c = Counter{}; var last: i64 = 0; for (data) |i| { const delta = i - last; last = i; switch (delta) { 0 => {}, 1 => c.ones += 1, 3 => c.threes += 1, else => { std.debug.warn("Unreachable code with delta {}", .{delta}); unreachable; }, } } return c; } test "part 1 example" { var sampleData = [_]i64{ 0, 16, 10, 15, 5, 1, 11, 7, 19, 6, 12, 4, }; std.sort.sort(i64, &sampleData, {}, ascI64); const counts = differences(&sampleData); // Part 1 std.testing.expectEqual(@as(usize, 7), counts.ones); // +1 to account for the fact that we're not modifying the sample data in // the test to include max+3. std.testing.expectEqual(@as(usize, 5), counts.threes + 1); // Part 2 std.testing.expectEqual(@as(i64, 8), combinations(&sampleData)); } test "part 1 longer example" { var sampleData = [_]i64{ 0, // Implied 0 made explicit. 28, 33, 18, 42, 31, 14, 46, 20, 48, 47, 24, 23, 49, 45, 19, 38, 39, 11, 1, 32, 25, 35, 8, 17, 7, 9, 4, 2, 34, 10, 3, }; std.sort.sort(i64, &sampleData, {}, ascI64); const counts = differences(&sampleData); // Part 1 std.testing.expectEqual(@as(usize, 22), counts.ones); std.testing.expectEqual(@as(usize, 10), counts.threes + 1); // Part 2 std.testing.expectEqual(@as(i64, 19208), combinations(&sampleData)); } fn trib(n: i64) i64 { if (n <= 0) return 0; switch (n) { 1, 2 => return 1, else => {}, } var c = [3]i64{ 0, 1, 1 }; var i = n - 2; while (i > 0) : (i -= 1) { const sum = c[0] + c[1] + c[2]; c[0] = c[1]; c[1] = c[2]; c[2] = sum; } return c[2]; } test "tribonacci sequence" { const eq = std.testing.expectEqual; eq(@as(i64, 0), trib(0)); eq(@as(i64, 1), trib(1)); eq(@as(i64, 1), trib(2)); eq(@as(i64, 2), trib(3)); eq(@as(i64, 4), trib(4)); eq(@as(i64, 7), trib(5)); eq(@as(i64, 13), trib(6)); // NOTE: this never occurs in the dataset. } fn combinations(data: []const i64) i64 { var count: i64 = 1; var i: usize = 0; while (i < data.len - 1) { var j: usize = i + 1; while (j < data.len and data[j] == data[j - 1] + 1) : (j += 1) {} count *= trib(@intCast(i64, @truncate(u32, j - i))); i = j; } return count; }
day10/src/main.zig
const std = @import("std"); const io = std.io; const Allocator = std.mem.Allocator; const BitSet = @import("nil").bits.BitSet; pub fn main() anyerror!void { var arena = std.heap.ArenaAllocator.init(std.heap.page_allocator); defer arena.deinit(); const alloc = &arena.allocator; var buf: [4000]u8 = undefined; var stream = io.bufferedReader(io.getStdIn().reader()); var rd = stream.reader(); var bits = BitSet.init(alloc); // Print the largest ID seen (part 1). var largest: usize = 0; while (try rd.readUntilDelimiterOrEof(&buf, '\n')) |line| { const pos = passPosition(line) catch continue; const id = pos.id(); if (id > largest) largest = id; try bits.set(id, true); } std.log.notice("Largest ID = {}", .{largest}); // Invert the bitset and look for bits where the surrounding bits are unset. bits.invert(); var iter = bits.iter(); while (iter.next()) |bit| { // Ignore underflow on this because the 2**64-th bit won't be set. if (!bits.get(bit -% 1) and !bits.get(bit + 1)) { // Print empty-but-surrounded bits (part 2). std.log.notice("Empty ID = {}", .{bit}); } } } const Pos = struct { const Self = @This(); row: usize, column: usize, fn id(self: Self) usize { return self.row * 8 + self.column; } }; const PosError = error{ ExpectFB, ExpectLR, }; fn passPosition(pass: []const u8) !Pos { var row: usize = 0; var col: usize = 0; var div: usize = 64; var next: ?usize = null; for (pass) |c, i| { next = i; switch (c) { 'B' => row += div, 'F' => {}, 'L', 'R' => { next = i; break; }, else => return PosError.ExpectFB, } div /= 2; } if (next == null) return PosError.ExpectLR; div = 4; for (pass[next.?..]) |c, i| { next = i; switch (c) { 'R' => col += div, 'L' => {}, else => return PosError.ExpectLR, } div /= 2; } return Pos{ .row = row, .column = col }; } test "passPosition returns correct values" { const eql = std.testing.expectEqual; const Case = struct { input: []const u8, want: Pos, id: usize, }; const cases = [_]Case{ .{ .input = "BFFFBBFRRR", .want = Pos{ .row = 70, .column = 7 }, .id = 567 }, .{ .input = "FFFBBBFRRR", .want = Pos{ .row = 14, .column = 7 }, .id = 119 }, .{ .input = "BBFFBBFRLL", .want = Pos{ .row = 102, .column = 4 }, .id = 820 }, }; for (cases) |c| { const pos = try passPosition(c.input); eql(pos.row, c.want.row); eql(pos.column, c.want.column); eql(pos.id(), c.id); } }
day5/src/main.zig
pub const __builtin_bswap16 = @import("std").zig.c_builtins.__builtin_bswap16; pub const __builtin_bswap32 = @import("std").zig.c_builtins.__builtin_bswap32; pub const __builtin_bswap64 = @import("std").zig.c_builtins.__builtin_bswap64; pub const __builtin_signbit = @import("std").zig.c_builtins.__builtin_signbit; pub const __builtin_signbitf = @import("std").zig.c_builtins.__builtin_signbitf; pub const __builtin_popcount = @import("std").zig.c_builtins.__builtin_popcount; pub const __builtin_ctz = @import("std").zig.c_builtins.__builtin_ctz; pub const __builtin_clz = @import("std").zig.c_builtins.__builtin_clz; pub const __builtin_sqrt = @import("std").zig.c_builtins.__builtin_sqrt; pub const __builtin_sqrtf = @import("std").zig.c_builtins.__builtin_sqrtf; pub const __builtin_sin = @import("std").zig.c_builtins.__builtin_sin; pub const __builtin_sinf = @import("std").zig.c_builtins.__builtin_sinf; pub const __builtin_cos = @import("std").zig.c_builtins.__builtin_cos; pub const __builtin_cosf = @import("std").zig.c_builtins.__builtin_cosf; pub const __builtin_exp = @import("std").zig.c_builtins.__builtin_exp; pub const __builtin_expf = @import("std").zig.c_builtins.__builtin_expf; pub const __builtin_exp2 = @import("std").zig.c_builtins.__builtin_exp2; pub const __builtin_exp2f = @import("std").zig.c_builtins.__builtin_exp2f; pub const __builtin_log = @import("std").zig.c_builtins.__builtin_log; pub const __builtin_logf = @import("std").zig.c_builtins.__builtin_logf; pub const __builtin_log2 = @import("std").zig.c_builtins.__builtin_log2; pub const __builtin_log2f = @import("std").zig.c_builtins.__builtin_log2f; pub const __builtin_log10 = @import("std").zig.c_builtins.__builtin_log10; pub const __builtin_log10f = @import("std").zig.c_builtins.__builtin_log10f; pub const __builtin_abs = @import("std").zig.c_builtins.__builtin_abs; pub const __builtin_fabs = @import("std").zig.c_builtins.__builtin_fabs; pub const __builtin_fabsf = @import("std").zig.c_builtins.__builtin_fabsf; pub const __builtin_floor = @import("std").zig.c_builtins.__builtin_floor; pub const __builtin_floorf = @import("std").zig.c_builtins.__builtin_floorf; pub const __builtin_ceil = @import("std").zig.c_builtins.__builtin_ceil; pub const __builtin_ceilf = @import("std").zig.c_builtins.__builtin_ceilf; pub const __builtin_trunc = @import("std").zig.c_builtins.__builtin_trunc; pub const __builtin_truncf = @import("std").zig.c_builtins.__builtin_truncf; pub const __builtin_round = @import("std").zig.c_builtins.__builtin_round; pub const __builtin_roundf = @import("std").zig.c_builtins.__builtin_roundf; pub const __builtin_strlen = @import("std").zig.c_builtins.__builtin_strlen; pub const __builtin_strcmp = @import("std").zig.c_builtins.__builtin_strcmp; pub const __builtin_object_size = @import("std").zig.c_builtins.__builtin_object_size; pub const __builtin___memset_chk = @import("std").zig.c_builtins.__builtin___memset_chk; pub const __builtin_memset = @import("std").zig.c_builtins.__builtin_memset; pub const __builtin___memcpy_chk = @import("std").zig.c_builtins.__builtin___memcpy_chk; pub const __builtin_memcpy = @import("std").zig.c_builtins.__builtin_memcpy; pub const __builtin_expect = @import("std").zig.c_builtins.__builtin_expect; pub const __builtin_nanf = @import("std").zig.c_builtins.__builtin_nanf; pub const __builtin_huge_valf = @import("std").zig.c_builtins.__builtin_huge_valf; pub const __builtin_inff = @import("std").zig.c_builtins.__builtin_inff; pub const __builtin_isnan = @import("std").zig.c_builtins.__builtin_isnan; pub const __builtin_isinf = @import("std").zig.c_builtins.__builtin_isinf; pub const __builtin_isinf_sign = @import("std").zig.c_builtins.__builtin_isinf_sign; pub const __builtin_va_list = [*c]u8; pub const va_list = __builtin_va_list; pub const __gnuc_va_list = __builtin_va_list; pub const struct_Vector2 = extern struct { x: f32, y: f32, }; pub const Vector2 = struct_Vector2; pub const struct_Vector3 = extern struct { x: f32, y: f32, z: f32, }; pub const Vector3 = struct_Vector3; pub const struct_Vector4 = extern struct { x: f32, y: f32, z: f32, w: f32, }; pub const Vector4 = struct_Vector4; pub const Quaternion = Vector4; pub const struct_Matrix = extern struct { m0: f32, m4: f32, m8: f32, m12: f32, m1: f32, m5: f32, m9: f32, m13: f32, m2: f32, m6: f32, m10: f32, m14: f32, m3: f32, m7: f32, m11: f32, m15: f32, }; pub const Matrix = struct_Matrix; pub const struct_Color = extern struct { r: u8, g: u8, b: u8, a: u8, }; pub const Color = struct_Color; pub const struct_Rectangle = extern struct { x: f32, y: f32, width: f32, height: f32, }; pub const Rectangle = struct_Rectangle; pub const struct_Image = extern struct { data: ?*c_void, width: c_int, height: c_int, mipmaps: c_int, format: c_int, }; pub const Image = struct_Image; pub const struct_Texture = extern struct { id: c_uint, width: c_int, height: c_int, mipmaps: c_int, format: c_int, }; pub const Texture = struct_Texture; pub const Texture2D = Texture; pub const TextureCubemap = Texture; pub const struct_RenderTexture = extern struct { id: c_uint, texture: Texture, depth: Texture, }; pub const RenderTexture = struct_RenderTexture; pub const RenderTexture2D = RenderTexture; pub const struct_NPatchInfo = extern struct { source: Rectangle, left: c_int, top: c_int, right: c_int, bottom: c_int, layout: c_int, }; pub const NPatchInfo = struct_NPatchInfo; pub const struct_CharInfo = extern struct { value: c_int, offsetX: c_int, offsetY: c_int, advanceX: c_int, image: Image, }; pub const CharInfo = struct_CharInfo; pub const struct_Font = extern struct { baseSize: c_int, charsCount: c_int, charsPadding: c_int, texture: Texture2D, recs: [*c]Rectangle, chars: [*c]CharInfo, }; pub const Font = struct_Font; pub const struct_Camera3D = extern struct { position: Vector3, target: Vector3, up: Vector3, fovy: f32, projection: c_int, }; pub const Camera3D = struct_Camera3D; pub const Camera = Camera3D; pub const struct_Camera2D = extern struct { offset: Vector2, target: Vector2, rotation: f32, zoom: f32, }; pub const Camera2D = struct_Camera2D; pub const struct_Mesh = extern struct { vertexCount: c_int, triangleCount: c_int, vertices: [*c]f32, texcoords: [*c]f32, texcoords2: [*c]f32, normals: [*c]f32, tangents: [*c]f32, colors: [*c]u8, indices: [*c]c_ushort, animVertices: [*c]f32, animNormals: [*c]f32, boneIds: [*c]c_int, boneWeights: [*c]f32, vaoId: c_uint, vboId: [*c]c_uint, }; pub const Mesh = struct_Mesh; pub const struct_Shader = extern struct { id: c_uint, locs: [*c]c_int, }; pub const Shader = struct_Shader; pub const struct_MaterialMap = extern struct { texture: Texture2D, color: Color, value: f32, }; pub const MaterialMap = struct_MaterialMap; pub const struct_Material = extern struct { shader: Shader, maps: [*c]MaterialMap, params: [4]f32, }; pub const Material = struct_Material; pub const struct_Transform = extern struct { translation: Vector3, rotation: Quaternion, scale: Vector3, }; pub const Transform = struct_Transform; pub const struct_BoneInfo = extern struct { name: [32]u8, parent: c_int, }; pub const BoneInfo = struct_BoneInfo; pub const struct_Model = extern struct { transform: Matrix, meshCount: c_int, materialCount: c_int, meshes: [*c]Mesh, materials: [*c]Material, meshMaterial: [*c]c_int, boneCount: c_int, bones: [*c]BoneInfo, bindPose: [*c]Transform, }; pub const Model = struct_Model; pub const struct_ModelAnimation = extern struct { boneCount: c_int, frameCount: c_int, bones: [*c]BoneInfo, framePoses: [*c][*c]Transform, }; pub const ModelAnimation = struct_ModelAnimation; pub const struct_Ray = extern struct { position: Vector3, direction: Vector3, }; pub const Ray = struct_Ray; pub const struct_RayCollision = extern struct { hit: bool, distance: f32, point: Vector3, normal: Vector3, }; pub const RayCollision = struct_RayCollision; pub const struct_BoundingBox = extern struct { min: Vector3, max: Vector3, }; pub const BoundingBox = struct_BoundingBox; pub const struct_Wave = extern struct { sampleCount: c_uint, sampleRate: c_uint, sampleSize: c_uint, channels: c_uint, data: ?*c_void, }; pub const Wave = struct_Wave; pub const struct_rAudioBuffer = opaque {}; pub const rAudioBuffer = struct_rAudioBuffer; pub const struct_AudioStream = extern struct { buffer: ?*rAudioBuffer, sampleRate: c_uint, sampleSize: c_uint, channels: c_uint, }; pub const AudioStream = struct_AudioStream; pub const struct_Sound = extern struct { stream: AudioStream, sampleCount: c_uint, }; pub const Sound = struct_Sound; pub const struct_Music = extern struct { stream: AudioStream, sampleCount: c_uint, looping: bool, ctxType: c_int, ctxData: ?*c_void, }; pub const Music = struct_Music; pub const struct_VrDeviceInfo = extern struct { hResolution: c_int, vResolution: c_int, hScreenSize: f32, vScreenSize: f32, vScreenCenter: f32, eyeToScreenDistance: f32, lensSeparationDistance: f32, interpupillaryDistance: f32, lensDistortionValues: [4]f32, chromaAbCorrection: [4]f32, }; pub const VrDeviceInfo = struct_VrDeviceInfo; pub const struct_VrStereoConfig = extern struct { projection: [2]Matrix, viewOffset: [2]Matrix, leftLensCenter: [2]f32, rightLensCenter: [2]f32, leftScreenCenter: [2]f32, rightScreenCenter: [2]f32, scale: [2]f32, scaleIn: [2]f32, }; pub const VrStereoConfig = struct_VrStereoConfig; pub const FLAG_VSYNC_HINT: c_int = 64; pub const FLAG_FULLSCREEN_MODE: c_int = 2; pub const FLAG_WINDOW_RESIZABLE: c_int = 4; pub const FLAG_WINDOW_UNDECORATED: c_int = 8; pub const FLAG_WINDOW_HIDDEN: c_int = 128; pub const FLAG_WINDOW_MINIMIZED: c_int = 512; pub const FLAG_WINDOW_MAXIMIZED: c_int = 1024; pub const FLAG_WINDOW_UNFOCUSED: c_int = 2048; pub const FLAG_WINDOW_TOPMOST: c_int = 4096; pub const FLAG_WINDOW_ALWAYS_RUN: c_int = 256; pub const FLAG_WINDOW_TRANSPARENT: c_int = 16; pub const FLAG_WINDOW_HIGHDPI: c_int = 8192; pub const FLAG_MSAA_4X_HINT: c_int = 32; pub const FLAG_INTERLACED_HINT: c_int = 65536; pub const ConfigFlags = c_uint; pub const LOG_ALL: c_int = 0; pub const LOG_TRACE: c_int = 1; pub const LOG_DEBUG: c_int = 2; pub const LOG_INFO: c_int = 3; pub const LOG_WARNING: c_int = 4; pub const LOG_ERROR: c_int = 5; pub const LOG_FATAL: c_int = 6; pub const LOG_NONE: c_int = 7; pub const TraceLogLevel = c_uint; pub const KEY_NULL: c_int = 0; pub const KEY_APOSTROPHE: c_int = 39; pub const KEY_COMMA: c_int = 44; pub const KEY_MINUS: c_int = 45; pub const KEY_PERIOD: c_int = 46; pub const KEY_SLASH: c_int = 47; pub const KEY_ZERO: c_int = 48; pub const KEY_ONE: c_int = 49; pub const KEY_TWO: c_int = 50; pub const KEY_THREE: c_int = 51; pub const KEY_FOUR: c_int = 52; pub const KEY_FIVE: c_int = 53; pub const KEY_SIX: c_int = 54; pub const KEY_SEVEN: c_int = 55; pub const KEY_EIGHT: c_int = 56; pub const KEY_NINE: c_int = 57; pub const KEY_SEMICOLON: c_int = 59; pub const KEY_EQUAL: c_int = 61; pub const KEY_A: c_int = 65; pub const KEY_B: c_int = 66; pub const KEY_C: c_int = 67; pub const KEY_D: c_int = 68; pub const KEY_E: c_int = 69; pub const KEY_F: c_int = 70; pub const KEY_G: c_int = 71; pub const KEY_H: c_int = 72; pub const KEY_I: c_int = 73; pub const KEY_J: c_int = 74; pub const KEY_K: c_int = 75; pub const KEY_L: c_int = 76; pub const KEY_M: c_int = 77; pub const KEY_N: c_int = 78; pub const KEY_O: c_int = 79; pub const KEY_P: c_int = 80; pub const KEY_Q: c_int = 81; pub const KEY_R: c_int = 82; pub const KEY_S: c_int = 83; pub const KEY_T: c_int = 84; pub const KEY_U: c_int = 85; pub const KEY_V: c_int = 86; pub const KEY_W: c_int = 87; pub const KEY_X: c_int = 88; pub const KEY_Y: c_int = 89; pub const KEY_Z: c_int = 90; pub const KEY_LEFT_BRACKET: c_int = 91; pub const KEY_BACKSLASH: c_int = 92; pub const KEY_RIGHT_BRACKET: c_int = 93; pub const KEY_GRAVE: c_int = 96; pub const KEY_SPACE: c_int = 32; pub const KEY_ESCAPE: c_int = 256; pub const KEY_ENTER: c_int = 257; pub const KEY_TAB: c_int = 258; pub const KEY_BACKSPACE: c_int = 259; pub const KEY_INSERT: c_int = 260; pub const KEY_DELETE: c_int = 261; pub const KEY_RIGHT: c_int = 262; pub const KEY_LEFT: c_int = 263; pub const KEY_DOWN: c_int = 264; pub const KEY_UP: c_int = 265; pub const KEY_PAGE_UP: c_int = 266; pub const KEY_PAGE_DOWN: c_int = 267; pub const KEY_HOME: c_int = 268; pub const KEY_END: c_int = 269; pub const KEY_CAPS_LOCK: c_int = 280; pub const KEY_SCROLL_LOCK: c_int = 281; pub const KEY_NUM_LOCK: c_int = 282; pub const KEY_PRINT_SCREEN: c_int = 283; pub const KEY_PAUSE: c_int = 284; pub const KEY_F1: c_int = 290; pub const KEY_F2: c_int = 291; pub const KEY_F3: c_int = 292; pub const KEY_F4: c_int = 293; pub const KEY_F5: c_int = 294; pub const KEY_F6: c_int = 295; pub const KEY_F7: c_int = 296; pub const KEY_F8: c_int = 297; pub const KEY_F9: c_int = 298; pub const KEY_F10: c_int = 299; pub const KEY_F11: c_int = 300; pub const KEY_F12: c_int = 301; pub const KEY_LEFT_SHIFT: c_int = 340; pub const KEY_LEFT_CONTROL: c_int = 341; pub const KEY_LEFT_ALT: c_int = 342; pub const KEY_LEFT_SUPER: c_int = 343; pub const KEY_RIGHT_SHIFT: c_int = 344; pub const KEY_RIGHT_CONTROL: c_int = 345; pub const KEY_RIGHT_ALT: c_int = 346; pub const KEY_RIGHT_SUPER: c_int = 347; pub const KEY_KB_MENU: c_int = 348; pub const KEY_KP_0: c_int = 320; pub const KEY_KP_1: c_int = 321; pub const KEY_KP_2: c_int = 322; pub const KEY_KP_3: c_int = 323; pub const KEY_KP_4: c_int = 324; pub const KEY_KP_5: c_int = 325; pub const KEY_KP_6: c_int = 326; pub const KEY_KP_7: c_int = 327; pub const KEY_KP_8: c_int = 328; pub const KEY_KP_9: c_int = 329; pub const KEY_KP_DECIMAL: c_int = 330; pub const KEY_KP_DIVIDE: c_int = 331; pub const KEY_KP_MULTIPLY: c_int = 332; pub const KEY_KP_SUBTRACT: c_int = 333; pub const KEY_KP_ADD: c_int = 334; pub const KEY_KP_ENTER: c_int = 335; pub const KEY_KP_EQUAL: c_int = 336; pub const KEY_BACK: c_int = 4; pub const KEY_MENU: c_int = 82; pub const KEY_VOLUME_UP: c_int = 24; pub const KEY_VOLUME_DOWN: c_int = 25; pub const KeyboardKey = c_uint; pub const MOUSE_BUTTON_LEFT: c_int = 0; pub const MOUSE_BUTTON_RIGHT: c_int = 1; pub const MOUSE_BUTTON_MIDDLE: c_int = 2; pub const MOUSE_BUTTON_SIDE: c_int = 3; pub const MOUSE_BUTTON_EXTRA: c_int = 4; pub const MOUSE_BUTTON_FORWARD: c_int = 5; pub const MOUSE_BUTTON_BACK: c_int = 6; pub const MouseButton = c_uint; pub const MOUSE_CURSOR_DEFAULT: c_int = 0; pub const MOUSE_CURSOR_ARROW: c_int = 1; pub const MOUSE_CURSOR_IBEAM: c_int = 2; pub const MOUSE_CURSOR_CROSSHAIR: c_int = 3; pub const MOUSE_CURSOR_POINTING_HAND: c_int = 4; pub const MOUSE_CURSOR_RESIZE_EW: c_int = 5; pub const MOUSE_CURSOR_RESIZE_NS: c_int = 6; pub const MOUSE_CURSOR_RESIZE_NWSE: c_int = 7; pub const MOUSE_CURSOR_RESIZE_NESW: c_int = 8; pub const MOUSE_CURSOR_RESIZE_ALL: c_int = 9; pub const MOUSE_CURSOR_NOT_ALLOWED: c_int = 10; pub const MouseCursor = c_uint; pub const GAMEPAD_BUTTON_UNKNOWN: c_int = 0; pub const GAMEPAD_BUTTON_LEFT_FACE_UP: c_int = 1; pub const GAMEPAD_BUTTON_LEFT_FACE_RIGHT: c_int = 2; pub const GAMEPAD_BUTTON_LEFT_FACE_DOWN: c_int = 3; pub const GAMEPAD_BUTTON_LEFT_FACE_LEFT: c_int = 4; pub const GAMEPAD_BUTTON_RIGHT_FACE_UP: c_int = 5; pub const GAMEPAD_BUTTON_RIGHT_FACE_RIGHT: c_int = 6; pub const GAMEPAD_BUTTON_RIGHT_FACE_DOWN: c_int = 7; pub const GAMEPAD_BUTTON_RIGHT_FACE_LEFT: c_int = 8; pub const GAMEPAD_BUTTON_LEFT_TRIGGER_1: c_int = 9; pub const GAMEPAD_BUTTON_LEFT_TRIGGER_2: c_int = 10; pub const GAMEPAD_BUTTON_RIGHT_TRIGGER_1: c_int = 11; pub const GAMEPAD_BUTTON_RIGHT_TRIGGER_2: c_int = 12; pub const GAMEPAD_BUTTON_MIDDLE_LEFT: c_int = 13; pub const GAMEPAD_BUTTON_MIDDLE: c_int = 14; pub const GAMEPAD_BUTTON_MIDDLE_RIGHT: c_int = 15; pub const GAMEPAD_BUTTON_LEFT_THUMB: c_int = 16; pub const GAMEPAD_BUTTON_RIGHT_THUMB: c_int = 17; pub const GamepadButton = c_uint; pub const GAMEPAD_AXIS_LEFT_X: c_int = 0; pub const GAMEPAD_AXIS_LEFT_Y: c_int = 1; pub const GAMEPAD_AXIS_RIGHT_X: c_int = 2; pub const GAMEPAD_AXIS_RIGHT_Y: c_int = 3; pub const GAMEPAD_AXIS_LEFT_TRIGGER: c_int = 4; pub const GAMEPAD_AXIS_RIGHT_TRIGGER: c_int = 5; pub const GamepadAxis = c_uint; pub const MATERIAL_MAP_ALBEDO: c_int = 0; pub const MATERIAL_MAP_METALNESS: c_int = 1; pub const MATERIAL_MAP_NORMAL: c_int = 2; pub const MATERIAL_MAP_ROUGHNESS: c_int = 3; pub const MATERIAL_MAP_OCCLUSION: c_int = 4; pub const MATERIAL_MAP_EMISSION: c_int = 5; pub const MATERIAL_MAP_HEIGHT: c_int = 6; pub const MATERIAL_MAP_CUBEMAP: c_int = 7; pub const MATERIAL_MAP_IRRADIANCE: c_int = 8; pub const MATERIAL_MAP_PREFILTER: c_int = 9; pub const MATERIAL_MAP_BRDG: c_int = 10; pub const MaterialMapIndex = c_uint; pub const SHADER_LOC_VERTEX_POSITION: c_int = 0; pub const SHADER_LOC_VERTEX_TEXCOORD01: c_int = 1; pub const SHADER_LOC_VERTEX_TEXCOORD02: c_int = 2; pub const SHADER_LOC_VERTEX_NORMAL: c_int = 3; pub const SHADER_LOC_VERTEX_TANGENT: c_int = 4; pub const SHADER_LOC_VERTEX_COLOR: c_int = 5; pub const SHADER_LOC_MATRIX_MVP: c_int = 6; pub const SHADER_LOC_MATRIX_VIEW: c_int = 7; pub const SHADER_LOC_MATRIX_PROJECTION: c_int = 8; pub const SHADER_LOC_MATRIX_MODEL: c_int = 9; pub const SHADER_LOC_MATRIX_NORMAL: c_int = 10; pub const SHADER_LOC_VECTOR_VIEW: c_int = 11; pub const SHADER_LOC_COLOR_DIFFUSE: c_int = 12; pub const SHADER_LOC_COLOR_SPECULAR: c_int = 13; pub const SHADER_LOC_COLOR_AMBIENT: c_int = 14; pub const SHADER_LOC_MAP_ALBEDO: c_int = 15; pub const SHADER_LOC_MAP_METALNESS: c_int = 16; pub const SHADER_LOC_MAP_NORMAL: c_int = 17; pub const SHADER_LOC_MAP_ROUGHNESS: c_int = 18; pub const SHADER_LOC_MAP_OCCLUSION: c_int = 19; pub const SHADER_LOC_MAP_EMISSION: c_int = 20; pub const SHADER_LOC_MAP_HEIGHT: c_int = 21; pub const SHADER_LOC_MAP_CUBEMAP: c_int = 22; pub const SHADER_LOC_MAP_IRRADIANCE: c_int = 23; pub const SHADER_LOC_MAP_PREFILTER: c_int = 24; pub const SHADER_LOC_MAP_BRDF: c_int = 25; pub const ShaderLocationIndex = c_uint; pub const SHADER_UNIFORM_FLOAT: c_int = 0; pub const SHADER_UNIFORM_VEC2: c_int = 1; pub const SHADER_UNIFORM_VEC3: c_int = 2; pub const SHADER_UNIFORM_VEC4: c_int = 3; pub const SHADER_UNIFORM_INT: c_int = 4; pub const SHADER_UNIFORM_IVEC2: c_int = 5; pub const SHADER_UNIFORM_IVEC3: c_int = 6; pub const SHADER_UNIFORM_IVEC4: c_int = 7; pub const SHADER_UNIFORM_SAMPLER2D: c_int = 8; pub const ShaderUniformDataType = c_uint; pub const SHADER_ATTRIB_FLOAT: c_int = 0; pub const SHADER_ATTRIB_VEC2: c_int = 1; pub const SHADER_ATTRIB_VEC3: c_int = 2; pub const SHADER_ATTRIB_VEC4: c_int = 3; pub const ShaderAttributeDataType = c_uint; pub const PIXELFORMAT_UNCOMPRESSED_GRAYSCALE: c_int = 1; pub const PIXELFORMAT_UNCOMPRESSED_GRAY_ALPHA: c_int = 2; pub const PIXELFORMAT_UNCOMPRESSED_R5G6B5: c_int = 3; pub const PIXELFORMAT_UNCOMPRESSED_R8G8B8: c_int = 4; pub const PIXELFORMAT_UNCOMPRESSED_R5G5B5A1: c_int = 5; pub const PIXELFORMAT_UNCOMPRESSED_R4G4B4A4: c_int = 6; pub const PIXELFORMAT_UNCOMPRESSED_R8G8B8A8: c_int = 7; pub const PIXELFORMAT_UNCOMPRESSED_R32: c_int = 8; pub const PIXELFORMAT_UNCOMPRESSED_R32G32B32: c_int = 9; pub const PIXELFORMAT_UNCOMPRESSED_R32G32B32A32: c_int = 10; pub const PIXELFORMAT_COMPRESSED_DXT1_RGB: c_int = 11; pub const PIXELFORMAT_COMPRESSED_DXT1_RGBA: c_int = 12; pub const PIXELFORMAT_COMPRESSED_DXT3_RGBA: c_int = 13; pub const PIXELFORMAT_COMPRESSED_DXT5_RGBA: c_int = 14; pub const PIXELFORMAT_COMPRESSED_ETC1_RGB: c_int = 15; pub const PIXELFORMAT_COMPRESSED_ETC2_RGB: c_int = 16; pub const PIXELFORMAT_COMPRESSED_ETC2_EAC_RGBA: c_int = 17; pub const PIXELFORMAT_COMPRESSED_PVRT_RGB: c_int = 18; pub const PIXELFORMAT_COMPRESSED_PVRT_RGBA: c_int = 19; pub const PIXELFORMAT_COMPRESSED_ASTC_4x4_RGBA: c_int = 20; pub const PIXELFORMAT_COMPRESSED_ASTC_8x8_RGBA: c_int = 21; pub const PixelFormat = c_uint; pub const TEXTURE_FILTER_POINT: c_int = 0; pub const TEXTURE_FILTER_BILINEAR: c_int = 1; pub const TEXTURE_FILTER_TRILINEAR: c_int = 2; pub const TEXTURE_FILTER_ANISOTROPIC_4X: c_int = 3; pub const TEXTURE_FILTER_ANISOTROPIC_8X: c_int = 4; pub const TEXTURE_FILTER_ANISOTROPIC_16X: c_int = 5; pub const TextureFilter = c_uint; pub const TEXTURE_WRAP_REPEAT: c_int = 0; pub const TEXTURE_WRAP_CLAMP: c_int = 1; pub const TEXTURE_WRAP_MIRROR_REPEAT: c_int = 2; pub const TEXTURE_WRAP_MIRROR_CLAMP: c_int = 3; pub const TextureWrap = c_uint; pub const CUBEMAP_LAYOUT_AUTO_DETECT: c_int = 0; pub const CUBEMAP_LAYOUT_LINE_VERTICAL: c_int = 1; pub const CUBEMAP_LAYOUT_LINE_HORIZONTAL: c_int = 2; pub const CUBEMAP_LAYOUT_CROSS_THREE_BY_FOUR: c_int = 3; pub const CUBEMAP_LAYOUT_CROSS_FOUR_BY_THREE: c_int = 4; pub const CUBEMAP_LAYOUT_PANORAMA: c_int = 5; pub const CubemapLayout = c_uint; pub const FONT_DEFAULT: c_int = 0; pub const FONT_BITMAP: c_int = 1; pub const FONT_SDF: c_int = 2; pub const FontType = c_uint; pub const BLEND_ALPHA: c_int = 0; pub const BLEND_ADDITIVE: c_int = 1; pub const BLEND_MULTIPLIED: c_int = 2; pub const BLEND_ADD_COLORS: c_int = 3; pub const BLEND_SUBTRACT_COLORS: c_int = 4; pub const BLEND_CUSTOM: c_int = 5; pub const BlendMode = c_uint; pub const GESTURE_NONE: c_int = 0; pub const GESTURE_TAP: c_int = 1; pub const GESTURE_DOUBLETAP: c_int = 2; pub const GESTURE_HOLD: c_int = 4; pub const GESTURE_DRAG: c_int = 8; pub const GESTURE_SWIPE_RIGHT: c_int = 16; pub const GESTURE_SWIPE_LEFT: c_int = 32; pub const GESTURE_SWIPE_UP: c_int = 64; pub const GESTURE_SWIPE_DOWN: c_int = 128; pub const GESTURE_PINCH_IN: c_int = 256; pub const GESTURE_PINCH_OUT: c_int = 512; pub const Gesture = c_uint; pub const CAMERA_CUSTOM: c_int = 0; pub const CAMERA_FREE: c_int = 1; pub const CAMERA_ORBITAL: c_int = 2; pub const CAMERA_FIRST_PERSON: c_int = 3; pub const CAMERA_THIRD_PERSON: c_int = 4; pub const CameraMode = c_uint; pub const CAMERA_PERSPECTIVE: c_int = 0; pub const CAMERA_ORTHOGRAPHIC: c_int = 1; pub const CameraProjection = c_uint; pub const NPATCH_NINE_PATCH: c_int = 0; pub const NPATCH_THREE_PATCH_VERTICAL: c_int = 1; pub const NPATCH_THREE_PATCH_HORIZONTAL: c_int = 2; pub const NPatchLayout = c_uint; pub const TraceLogCallback = ?fn (c_int, [*c]const u8, va_list) callconv(.C) void; pub const LoadFileDataCallback = ?fn ([*c]const u8, [*c]c_uint) callconv(.C) [*c]u8; pub const SaveFileDataCallback = ?fn ([*c]const u8, ?*c_void, c_uint) callconv(.C) bool; pub const LoadFileTextCallback = ?fn ([*c]const u8) callconv(.C) [*c]u8; pub const SaveFileTextCallback = ?fn ([*c]const u8, [*c]u8) callconv(.C) bool; pub extern fn InitWindow(width: c_int, height: c_int, title: [*c]const u8) void; pub extern fn WindowShouldClose() bool; pub extern fn CloseWindow() void; pub extern fn IsWindowReady() bool; pub extern fn IsWindowFullscreen() bool; pub extern fn IsWindowHidden() bool; pub extern fn IsWindowMinimized() bool; pub extern fn IsWindowMaximized() bool; pub extern fn IsWindowFocused() bool; pub extern fn IsWindowResized() bool; pub extern fn IsWindowState(flag: c_uint) bool; pub extern fn SetWindowState(flags: c_uint) void; pub extern fn ClearWindowState(flags: c_uint) void; pub extern fn ToggleFullscreen() void; pub extern fn MaximizeWindow() void; pub extern fn MinimizeWindow() void; pub extern fn RestoreWindow() void; pub extern fn SetWindowIcon(image: Image) void; pub extern fn SetWindowTitle(title: [*c]const u8) void; pub extern fn SetWindowPosition(x: c_int, y: c_int) void; pub extern fn SetWindowMonitor(monitor: c_int) void; pub extern fn SetWindowMinSize(width: c_int, height: c_int) void; pub extern fn SetWindowSize(width: c_int, height: c_int) void; pub extern fn GetWindowHandle() ?*c_void; pub extern fn GetScreenWidth() c_int; pub extern fn GetScreenHeight() c_int; pub extern fn GetMonitorCount() c_int; pub extern fn GetCurrentMonitor() c_int; pub extern fn GetMonitorPosition(monitor: c_int) Vector2; pub extern fn GetMonitorWidth(monitor: c_int) c_int; pub extern fn GetMonitorHeight(monitor: c_int) c_int; pub extern fn GetMonitorPhysicalWidth(monitor: c_int) c_int; pub extern fn GetMonitorPhysicalHeight(monitor: c_int) c_int; pub extern fn GetMonitorRefreshRate(monitor: c_int) c_int; pub extern fn GetWindowPosition() Vector2; pub extern fn GetWindowScaleDPI() Vector2; pub extern fn GetMonitorName(monitor: c_int) [*c]const u8; pub extern fn SetClipboardText(text: [*c]const u8) void; pub extern fn GetClipboardText() [*c]const u8; pub extern fn SwapScreenBuffer() void; pub extern fn PollInputEvents() void; pub extern fn WaitTime(ms: f32) void; pub extern fn ShowCursor() void; pub extern fn HideCursor() void; pub extern fn IsCursorHidden() bool; pub extern fn EnableCursor() void; pub extern fn DisableCursor() void; pub extern fn IsCursorOnScreen() bool; pub extern fn ClearBackground(color: Color) void; pub extern fn BeginDrawing() void; pub extern fn EndDrawing() void; pub extern fn BeginMode2D(camera: Camera2D) void; pub extern fn EndMode2D() void; pub extern fn BeginMode3D(camera: Camera3D) void; pub extern fn EndMode3D() void; pub extern fn BeginTextureMode(target: RenderTexture2D) void; pub extern fn EndTextureMode() void; pub extern fn BeginShaderMode(shader: Shader) void; pub extern fn EndShaderMode() void; pub extern fn BeginBlendMode(mode: c_int) void; pub extern fn EndBlendMode() void; pub extern fn BeginScissorMode(x: c_int, y: c_int, width: c_int, height: c_int) void; pub extern fn EndScissorMode() void; pub extern fn BeginVrStereoMode(config: VrStereoConfig) void; pub extern fn EndVrStereoMode() void; pub extern fn LoadVrStereoConfig(device: VrDeviceInfo) VrStereoConfig; pub extern fn UnloadVrStereoConfig(config: VrStereoConfig) void; pub extern fn LoadShader(vsFileName: [*c]const u8, fsFileName: [*c]const u8) Shader; pub extern fn LoadShaderFromMemory(vsCode: [*c]const u8, fsCode: [*c]const u8) Shader; pub extern fn GetShaderLocation(shader: Shader, uniformName: [*c]const u8) c_int; pub extern fn GetShaderLocationAttrib(shader: Shader, attribName: [*c]const u8) c_int; pub extern fn SetShaderValue(shader: Shader, locIndex: c_int, value: ?*const c_void, uniformType: c_int) void; pub extern fn SetShaderValueV(shader: Shader, locIndex: c_int, value: ?*const c_void, uniformType: c_int, count: c_int) void; pub extern fn SetShaderValueMatrix(shader: Shader, locIndex: c_int, mat: Matrix) void; pub extern fn SetShaderValueTexture(shader: Shader, locIndex: c_int, texture: Texture2D) void; pub extern fn UnloadShader(shader: Shader) void; pub extern fn GetMouseRay(mousePosition: Vector2, camera: Camera) Ray; pub extern fn GetCameraMatrix(camera: Camera) Matrix; pub extern fn GetCameraMatrix2D(camera: Camera2D) Matrix; pub extern fn GetWorldToScreen(position: Vector3, camera: Camera) Vector2; pub extern fn GetWorldToScreenEx(position: Vector3, camera: Camera, width: c_int, height: c_int) Vector2; pub extern fn GetWorldToScreen2D(position: Vector2, camera: Camera2D) Vector2; pub extern fn GetScreenToWorld2D(position: Vector2, camera: Camera2D) Vector2; pub extern fn SetTargetFPS(fps: c_int) void; pub extern fn GetFPS() c_int; pub extern fn GetFrameTime() f32; pub extern fn GetTime() f64; pub extern fn GetRandomValue(min: c_int, max: c_int) c_int; pub extern fn TakeScreenshot(fileName: [*c]const u8) void; pub extern fn SetConfigFlags(flags: c_uint) void; pub extern fn TraceLog(logLevel: c_int, text: [*c]const u8, ...) void; pub extern fn SetTraceLogLevel(logLevel: c_int) void; pub extern fn MemAlloc(size: c_int) ?*c_void; pub extern fn MemRealloc(ptr: ?*c_void, size: c_int) ?*c_void; pub extern fn MemFree(ptr: ?*c_void) void; pub extern fn SetTraceLogCallback(callback: TraceLogCallback) void; pub extern fn SetLoadFileDataCallback(callback: LoadFileDataCallback) void; pub extern fn SetSaveFileDataCallback(callback: SaveFileDataCallback) void; pub extern fn SetLoadFileTextCallback(callback: LoadFileTextCallback) void; pub extern fn SetSaveFileTextCallback(callback: SaveFileTextCallback) void; pub extern fn LoadFileData(fileName: [*c]const u8, bytesRead: [*c]c_uint) [*c]u8; pub extern fn UnloadFileData(data: [*c]u8) void; pub extern fn SaveFileData(fileName: [*c]const u8, data: ?*c_void, bytesToWrite: c_uint) bool; pub extern fn LoadFileText(fileName: [*c]const u8) [*c]u8; pub extern fn UnloadFileText(text: [*c]u8) void; pub extern fn SaveFileText(fileName: [*c]const u8, text: [*c]u8) bool; pub extern fn FileExists(fileName: [*c]const u8) bool; pub extern fn DirectoryExists(dirPath: [*c]const u8) bool; pub extern fn IsFileExtension(fileName: [*c]const u8, ext: [*c]const u8) bool; pub extern fn GetFileExtension(fileName: [*c]const u8) [*c]const u8; pub extern fn GetFileName(filePath: [*c]const u8) [*c]const u8; pub extern fn GetFileNameWithoutExt(filePath: [*c]const u8) [*c]const u8; pub extern fn GetDirectoryPath(filePath: [*c]const u8) [*c]const u8; pub extern fn GetPrevDirectoryPath(dirPath: [*c]const u8) [*c]const u8; pub extern fn GetWorkingDirectory() [*c]const u8; pub extern fn GetDirectoryFiles(dirPath: [*c]const u8, count: [*c]c_int) [*c][*c]u8; pub extern fn ClearDirectoryFiles() void; pub extern fn ChangeDirectory(dir: [*c]const u8) bool; pub extern fn IsFileDropped() bool; pub extern fn GetDroppedFiles(count: [*c]c_int) [*c][*c]u8; pub extern fn ClearDroppedFiles() void; pub extern fn GetFileModTime(fileName: [*c]const u8) c_long; pub extern fn CompressData(data: [*c]u8, dataLength: c_int, compDataLength: [*c]c_int) [*c]u8; pub extern fn DecompressData(compData: [*c]u8, compDataLength: c_int, dataLength: [*c]c_int) [*c]u8; pub extern fn SaveStorageValue(position: c_uint, value: c_int) bool; pub extern fn LoadStorageValue(position: c_uint) c_int; pub extern fn OpenURL(url: [*c]const u8) void; pub extern fn IsKeyPressed(key: c_int) bool; pub extern fn IsKeyDown(key: c_int) bool; pub extern fn IsKeyReleased(key: c_int) bool; pub extern fn IsKeyUp(key: c_int) bool; pub extern fn SetExitKey(key: c_int) void; pub extern fn GetKeyPressed() c_int; pub extern fn GetCharPressed() c_int; pub extern fn IsGamepadAvailable(gamepad: c_int) bool; pub extern fn IsGamepadName(gamepad: c_int, name: [*c]const u8) bool; pub extern fn GetGamepadName(gamepad: c_int) [*c]const u8; pub extern fn IsGamepadButtonPressed(gamepad: c_int, button: c_int) bool; pub extern fn IsGamepadButtonDown(gamepad: c_int, button: c_int) bool; pub extern fn IsGamepadButtonReleased(gamepad: c_int, button: c_int) bool; pub extern fn IsGamepadButtonUp(gamepad: c_int, button: c_int) bool; pub extern fn GetGamepadButtonPressed() c_int; pub extern fn GetGamepadAxisCount(gamepad: c_int) c_int; pub extern fn GetGamepadAxisMovement(gamepad: c_int, axis: c_int) f32; pub extern fn SetGamepadMappings(mappings: [*c]const u8) c_int; pub extern fn IsMouseButtonPressed(button: c_int) bool; pub extern fn IsMouseButtonDown(button: c_int) bool; pub extern fn IsMouseButtonReleased(button: c_int) bool; pub extern fn IsMouseButtonUp(button: c_int) bool; pub extern fn GetMouseX() c_int; pub extern fn GetMouseY() c_int; pub extern fn GetMousePosition() Vector2; pub extern fn GetMouseDelta() Vector2; pub extern fn SetMousePosition(x: c_int, y: c_int) void; pub extern fn SetMouseOffset(offsetX: c_int, offsetY: c_int) void; pub extern fn SetMouseScale(scaleX: f32, scaleY: f32) void; pub extern fn GetMouseWheelMove() f32; pub extern fn SetMouseCursor(cursor: c_int) void; pub extern fn GetTouchX() c_int; pub extern fn GetTouchY() c_int; pub extern fn GetTouchPosition(index: c_int) Vector2; pub extern fn SetGesturesEnabled(flags: c_uint) void; pub extern fn IsGestureDetected(gesture: c_int) bool; pub extern fn GetGestureDetected() c_int; pub extern fn GetTouchPointsCount() c_int; pub extern fn GetGestureHoldDuration() f32; pub extern fn GetGestureDragVector() Vector2; pub extern fn GetGestureDragAngle() f32; pub extern fn GetGesturePinchVector() Vector2; pub extern fn GetGesturePinchAngle() f32; pub extern fn SetCameraMode(camera: Camera, mode: c_int) void; pub extern fn UpdateCamera(camera: [*c]Camera) void; pub extern fn SetCameraPanControl(keyPan: c_int) void; pub extern fn SetCameraAltControl(keyAlt: c_int) void; pub extern fn SetCameraSmoothZoomControl(keySmoothZoom: c_int) void; pub extern fn SetCameraMoveControls(keyFront: c_int, keyBack: c_int, keyRight: c_int, keyLeft: c_int, keyUp: c_int, keyDown: c_int) void; pub extern fn SetShapesTexture(texture: Texture2D, source: Rectangle) void; pub extern fn DrawPixel(posX: c_int, posY: c_int, color: Color) void; pub extern fn DrawPixelV(position: Vector2, color: Color) void; pub extern fn DrawLine(startPosX: c_int, startPosY: c_int, endPosX: c_int, endPosY: c_int, color: Color) void; pub extern fn DrawLineV(startPos: Vector2, endPos: Vector2, color: Color) void; pub extern fn DrawLineEx(startPos: Vector2, endPos: Vector2, thick: f32, color: Color) void; pub extern fn DrawLineBezier(startPos: Vector2, endPos: Vector2, thick: f32, color: Color) void; pub extern fn DrawLineBezierQuad(startPos: Vector2, endPos: Vector2, controlPos: Vector2, thick: f32, color: Color) void; pub extern fn DrawLineStrip(points: [*c]Vector2, pointsCount: c_int, color: Color) void; pub extern fn DrawCircle(centerX: c_int, centerY: c_int, radius: f32, color: Color) void; pub extern fn DrawCircleSector(center: Vector2, radius: f32, startAngle: f32, endAngle: f32, segments: c_int, color: Color) void; pub extern fn DrawCircleSectorLines(center: Vector2, radius: f32, startAngle: f32, endAngle: f32, segments: c_int, color: Color) void; pub extern fn DrawCircleGradient(centerX: c_int, centerY: c_int, radius: f32, color1: Color, color2: Color) void; pub extern fn DrawCircleV(center: Vector2, radius: f32, color: Color) void; pub extern fn DrawCircleLines(centerX: c_int, centerY: c_int, radius: f32, color: Color) void; pub extern fn DrawEllipse(centerX: c_int, centerY: c_int, radiusH: f32, radiusV: f32, color: Color) void; pub extern fn DrawEllipseLines(centerX: c_int, centerY: c_int, radiusH: f32, radiusV: f32, color: Color) void; pub extern fn DrawRing(center: Vector2, innerRadius: f32, outerRadius: f32, startAngle: f32, endAngle: f32, segments: c_int, color: Color) void; pub extern fn DrawRingLines(center: Vector2, innerRadius: f32, outerRadius: f32, startAngle: f32, endAngle: f32, segments: c_int, color: Color) void; pub extern fn DrawRectangle(posX: c_int, posY: c_int, width: c_int, height: c_int, color: Color) void; pub extern fn DrawRectangleV(position: Vector2, size: Vector2, color: Color) void; pub extern fn DrawRectangleRec(rec: Rectangle, color: Color) void; pub extern fn DrawRectanglePro(rec: Rectangle, origin: Vector2, rotation: f32, color: Color) void; pub extern fn DrawRectangleGradientV(posX: c_int, posY: c_int, width: c_int, height: c_int, color1: Color, color2: Color) void; pub extern fn DrawRectangleGradientH(posX: c_int, posY: c_int, width: c_int, height: c_int, color1: Color, color2: Color) void; pub extern fn DrawRectangleGradientEx(rec: Rectangle, col1: Color, col2: Color, col3: Color, col4: Color) void; pub extern fn DrawRectangleLines(posX: c_int, posY: c_int, width: c_int, height: c_int, color: Color) void; pub extern fn DrawRectangleLinesEx(rec: Rectangle, lineThick: f32, color: Color) void; pub extern fn DrawRectangleRounded(rec: Rectangle, roundness: f32, segments: c_int, color: Color) void; pub extern fn DrawRectangleRoundedLines(rec: Rectangle, roundness: f32, segments: c_int, lineThick: f32, color: Color) void; pub extern fn DrawTriangle(v1: Vector2, v2: Vector2, v3: Vector2, color: Color) void; pub extern fn DrawTriangleLines(v1: Vector2, v2: Vector2, v3: Vector2, color: Color) void; pub extern fn DrawTriangleFan(points: [*c]Vector2, pointsCount: c_int, color: Color) void; pub extern fn DrawTriangleStrip(points: [*c]Vector2, pointsCount: c_int, color: Color) void; pub extern fn DrawPoly(center: Vector2, sides: c_int, radius: f32, rotation: f32, color: Color) void; pub extern fn DrawPolyLines(center: Vector2, sides: c_int, radius: f32, rotation: f32, color: Color) void; pub extern fn DrawPolyLinesEx(center: Vector2, sides: c_int, radius: f32, rotation: f32, lineThick: f32, color: Color) void; pub extern fn CheckCollisionRecs(rec1: Rectangle, rec2: Rectangle) bool; pub extern fn CheckCollisionCircles(center1: Vector2, radius1: f32, center2: Vector2, radius2: f32) bool; pub extern fn CheckCollisionCircleRec(center: Vector2, radius: f32, rec: Rectangle) bool; pub extern fn CheckCollisionPointRec(point: Vector2, rec: Rectangle) bool; pub extern fn CheckCollisionPointCircle(point: Vector2, center: Vector2, radius: f32) bool; pub extern fn CheckCollisionPointTriangle(point: Vector2, p1: Vector2, p2: Vector2, p3: Vector2) bool; pub extern fn CheckCollisionLines(startPos1: Vector2, endPos1: Vector2, startPos2: Vector2, endPos2: Vector2, collisionPoint: [*c]Vector2) bool; pub extern fn GetCollisionRec(rec1: Rectangle, rec2: Rectangle) Rectangle; pub extern fn LoadImage(fileName: [*c]const u8) Image; pub extern fn LoadImageRaw(fileName: [*c]const u8, width: c_int, height: c_int, format: c_int, headerSize: c_int) Image; pub extern fn LoadImageAnim(fileName: [*c]const u8, frames: [*c]c_int) Image; pub extern fn LoadImageFromMemory(fileType: [*c]const u8, fileData: [*c]const u8, dataSize: c_int) Image; pub extern fn LoadImageFromTexture(texture: Texture2D) Image; pub extern fn LoadImageFromScreen() Image; pub extern fn UnloadImage(image: Image) void; pub extern fn ExportImage(image: Image, fileName: [*c]const u8) bool; pub extern fn ExportImageAsCode(image: Image, fileName: [*c]const u8) bool; pub extern fn GenImageColor(width: c_int, height: c_int, color: Color) Image; pub extern fn GenImageGradientV(width: c_int, height: c_int, top: Color, bottom: Color) Image; pub extern fn GenImageGradientH(width: c_int, height: c_int, left: Color, right: Color) Image; pub extern fn GenImageGradientRadial(width: c_int, height: c_int, density: f32, inner: Color, outer: Color) Image; pub extern fn GenImageChecked(width: c_int, height: c_int, checksX: c_int, checksY: c_int, col1: Color, col2: Color) Image; pub extern fn GenImageWhiteNoise(width: c_int, height: c_int, factor: f32) Image; pub extern fn GenImagePerlinNoise(width: c_int, height: c_int, offsetX: c_int, offsetY: c_int, scale: f32) Image; pub extern fn GenImageCellular(width: c_int, height: c_int, tileSize: c_int) Image; pub extern fn ImageCopy(image: Image) Image; pub extern fn ImageFromImage(image: Image, rec: Rectangle) Image; pub extern fn ImageText(text: [*c]const u8, fontSize: c_int, color: Color) Image; pub extern fn ImageTextEx(font: Font, text: [*c]const u8, fontSize: f32, spacing: f32, tint: Color) Image; pub extern fn ImageFormat(image: [*c]Image, newFormat: c_int) void; pub extern fn ImageToPOT(image: [*c]Image, fill: Color) void; pub extern fn ImageCrop(image: [*c]Image, crop: Rectangle) void; pub extern fn ImageAlphaCrop(image: [*c]Image, threshold: f32) void; pub extern fn ImageAlphaClear(image: [*c]Image, color: Color, threshold: f32) void; pub extern fn ImageAlphaMask(image: [*c]Image, alphaMask: Image) void; pub extern fn ImageAlphaPremultiply(image: [*c]Image) void; pub extern fn ImageResize(image: [*c]Image, newWidth: c_int, newHeight: c_int) void; pub extern fn ImageResizeNN(image: [*c]Image, newWidth: c_int, newHeight: c_int) void; pub extern fn ImageResizeCanvas(image: [*c]Image, newWidth: c_int, newHeight: c_int, offsetX: c_int, offsetY: c_int, fill: Color) void; pub extern fn ImageMipmaps(image: [*c]Image) void; pub extern fn ImageDither(image: [*c]Image, rBpp: c_int, gBpp: c_int, bBpp: c_int, aBpp: c_int) void; pub extern fn ImageFlipVertical(image: [*c]Image) void; pub extern fn ImageFlipHorizontal(image: [*c]Image) void; pub extern fn ImageRotateCW(image: [*c]Image) void; pub extern fn ImageRotateCCW(image: [*c]Image) void; pub extern fn ImageColorTint(image: [*c]Image, color: Color) void; pub extern fn ImageColorInvert(image: [*c]Image) void; pub extern fn ImageColorGrayscale(image: [*c]Image) void; pub extern fn ImageColorContrast(image: [*c]Image, contrast: f32) void; pub extern fn ImageColorBrightness(image: [*c]Image, brightness: c_int) void; pub extern fn ImageColorReplace(image: [*c]Image, color: Color, replace: Color) void; pub extern fn LoadImageColors(image: Image) [*c]Color; pub extern fn LoadImagePalette(image: Image, maxPaletteSize: c_int, colorsCount: [*c]c_int) [*c]Color; pub extern fn UnloadImageColors(colors: [*c]Color) void; pub extern fn UnloadImagePalette(colors: [*c]Color) void; pub extern fn GetImageAlphaBorder(image: Image, threshold: f32) Rectangle; pub extern fn ImageClearBackground(dst: [*c]Image, color: Color) void; pub extern fn ImageDrawPixel(dst: [*c]Image, posX: c_int, posY: c_int, color: Color) void; pub extern fn ImageDrawPixelV(dst: [*c]Image, position: Vector2, color: Color) void; pub extern fn ImageDrawLine(dst: [*c]Image, startPosX: c_int, startPosY: c_int, endPosX: c_int, endPosY: c_int, color: Color) void; pub extern fn ImageDrawLineV(dst: [*c]Image, start: Vector2, end: Vector2, color: Color) void; pub extern fn ImageDrawCircle(dst: [*c]Image, centerX: c_int, centerY: c_int, radius: c_int, color: Color) void; pub extern fn ImageDrawCircleV(dst: [*c]Image, center: Vector2, radius: c_int, color: Color) void; pub extern fn ImageDrawRectangle(dst: [*c]Image, posX: c_int, posY: c_int, width: c_int, height: c_int, color: Color) void; pub extern fn ImageDrawRectangleV(dst: [*c]Image, position: Vector2, size: Vector2, color: Color) void; pub extern fn ImageDrawRectangleRec(dst: [*c]Image, rec: Rectangle, color: Color) void; pub extern fn ImageDrawRectangleLines(dst: [*c]Image, rec: Rectangle, thick: c_int, color: Color) void; pub extern fn ImageDraw(dst: [*c]Image, src: Image, srcRec: Rectangle, dstRec: Rectangle, tint: Color) void; pub extern fn ImageDrawText(dst: [*c]Image, text: [*c]const u8, posX: c_int, posY: c_int, fontSize: c_int, color: Color) void; pub extern fn ImageDrawTextEx(dst: [*c]Image, font: Font, text: [*c]const u8, position: Vector2, fontSize: f32, spacing: f32, tint: Color) void; pub extern fn LoadTexture(fileName: [*c]const u8) Texture2D; pub extern fn LoadTextureFromImage(image: Image) Texture2D; pub extern fn LoadTextureCubemap(image: Image, layout: c_int) TextureCubemap; pub extern fn LoadRenderTexture(width: c_int, height: c_int) RenderTexture2D; pub extern fn UnloadTexture(texture: Texture2D) void; pub extern fn UnloadRenderTexture(target: RenderTexture2D) void; pub extern fn UpdateTexture(texture: Texture2D, pixels: ?*const c_void) void; pub extern fn UpdateTextureRec(texture: Texture2D, rec: Rectangle, pixels: ?*const c_void) void; pub extern fn GenTextureMipmaps(texture: [*c]Texture2D) void; pub extern fn SetTextureFilter(texture: Texture2D, filter: c_int) void; pub extern fn SetTextureWrap(texture: Texture2D, wrap: c_int) void; pub extern fn DrawTexture(texture: Texture2D, posX: c_int, posY: c_int, tint: Color) void; pub extern fn DrawTextureV(texture: Texture2D, position: Vector2, tint: Color) void; pub extern fn DrawTextureEx(texture: Texture2D, position: Vector2, rotation: f32, scale: f32, tint: Color) void; pub extern fn DrawTextureRec(texture: Texture2D, source: Rectangle, position: Vector2, tint: Color) void; pub extern fn DrawTextureQuad(texture: Texture2D, tiling: Vector2, offset: Vector2, quad: Rectangle, tint: Color) void; pub extern fn DrawTextureTiled(texture: Texture2D, source: Rectangle, dest: Rectangle, origin: Vector2, rotation: f32, scale: f32, tint: Color) void; pub extern fn DrawTexturePro(texture: Texture2D, source: Rectangle, dest: Rectangle, origin: Vector2, rotation: f32, tint: Color) void; pub extern fn DrawTextureNPatch(texture: Texture2D, nPatchInfo: NPatchInfo, dest: Rectangle, origin: Vector2, rotation: f32, tint: Color) void; pub extern fn DrawTexturePoly(texture: Texture2D, center: Vector2, points: [*c]Vector2, texcoords: [*c]Vector2, pointsCount: c_int, tint: Color) void; pub extern fn Fade(color: Color, alpha: f32) Color; pub extern fn ColorToInt(color: Color) c_int; pub extern fn ColorNormalize(color: Color) Vector4; pub extern fn ColorFromNormalized(normalized: Vector4) Color; pub extern fn ColorToHSV(color: Color) Vector3; pub extern fn ColorFromHSV(hue: f32, saturation: f32, value: f32) Color; pub extern fn ColorAlpha(color: Color, alpha: f32) Color; pub extern fn ColorAlphaBlend(dst: Color, src: Color, tint: Color) Color; pub extern fn GetColor(hexValue: c_int) Color; pub extern fn GetPixelColor(srcPtr: ?*c_void, format: c_int) Color; pub extern fn SetPixelColor(dstPtr: ?*c_void, color: Color, format: c_int) void; pub extern fn GetPixelDataSize(width: c_int, height: c_int, format: c_int) c_int; pub extern fn GetFontDefault() Font; pub extern fn LoadFont(fileName: [*c]const u8) Font; pub extern fn LoadFontEx(fileName: [*c]const u8, fontSize: c_int, fontChars: [*c]c_int, charsCount: c_int) Font; pub extern fn LoadFontFromImage(image: Image, key: Color, firstChar: c_int) Font; pub extern fn LoadFontFromMemory(fileType: [*c]const u8, fileData: [*c]const u8, dataSize: c_int, fontSize: c_int, fontChars: [*c]c_int, charsCount: c_int) Font; pub extern fn LoadFontData(fileData: [*c]const u8, dataSize: c_int, fontSize: c_int, fontChars: [*c]c_int, charsCount: c_int, @"type": c_int) [*c]CharInfo; pub extern fn GenImageFontAtlas(chars: [*c]const CharInfo, recs: [*c][*c]Rectangle, charsCount: c_int, fontSize: c_int, padding: c_int, packMethod: c_int) Image; pub extern fn UnloadFontData(chars: [*c]CharInfo, charsCount: c_int) void; pub extern fn UnloadFont(font: Font) void; pub extern fn DrawFPS(posX: c_int, posY: c_int) void; pub extern fn DrawText(text: [*c]const u8, posX: c_int, posY: c_int, fontSize: c_int, color: Color) void; pub extern fn DrawTextEx(font: Font, text: [*c]const u8, position: Vector2, fontSize: f32, spacing: f32, tint: Color) void; pub extern fn DrawTextRec(font: Font, text: [*c]const u8, rec: Rectangle, fontSize: f32, spacing: f32, wordWrap: bool, tint: Color) void; pub extern fn DrawTextRecEx(font: Font, text: [*c]const u8, rec: Rectangle, fontSize: f32, spacing: f32, wordWrap: bool, tint: Color, selectStart: c_int, selectLength: c_int, selectTint: Color, selectBackTint: Color) void; pub extern fn DrawTextCodepoint(font: Font, codepoint: c_int, position: Vector2, fontSize: f32, tint: Color) void; pub extern fn MeasureText(text: [*c]const u8, fontSize: c_int) c_int; pub extern fn MeasureTextEx(font: Font, text: [*c]const u8, fontSize: f32, spacing: f32) Vector2; pub extern fn GetGlyphIndex(font: Font, codepoint: c_int) c_int; pub extern fn TextCopy(dst: [*c]u8, src: [*c]const u8) c_int; pub extern fn TextIsEqual(text1: [*c]const u8, text2: [*c]const u8) bool; pub extern fn TextLength(text: [*c]const u8) c_uint; pub extern fn TextFormat(text: [*c]const u8, ...) [*c]const u8; pub extern fn TextSubtext(text: [*c]const u8, position: c_int, length: c_int) [*c]const u8; pub extern fn TextReplace(text: [*c]u8, replace: [*c]const u8, by: [*c]const u8) [*c]u8; pub extern fn TextInsert(text: [*c]const u8, insert: [*c]const u8, position: c_int) [*c]u8; pub extern fn TextJoin(textList: [*c][*c]const u8, count: c_int, delimiter: [*c]const u8) [*c]const u8; pub extern fn TextSplit(text: [*c]const u8, delimiter: u8, count: [*c]c_int) [*c][*c]const u8; pub extern fn TextAppend(text: [*c]u8, append: [*c]const u8, position: [*c]c_int) void; pub extern fn TextFindIndex(text: [*c]const u8, find: [*c]const u8) c_int; pub extern fn TextToUpper(text: [*c]const u8) [*c]const u8; pub extern fn TextToLower(text: [*c]const u8) [*c]const u8; pub extern fn TextToPascal(text: [*c]const u8) [*c]const u8; pub extern fn TextToInteger(text: [*c]const u8) c_int; pub extern fn TextToUtf8(codepoints: [*c]c_int, length: c_int) [*c]u8; pub extern fn LoadCodepoints(text: [*c]const u8, count: [*c]c_int) [*c]c_int; pub extern fn UnloadCodepoints(codepoints: [*c]c_int) void; pub extern fn GetCodepointsCount(text: [*c]const u8) c_int; pub extern fn GetCodepoint(text: [*c]const u8, bytesProcessed: [*c]c_int) c_int; pub extern fn CodepointToUtf8(codepoint: c_int, byteLength: [*c]c_int) [*c]const u8; pub extern fn DrawLine3D(startPos: Vector3, endPos: Vector3, color: Color) void; pub extern fn DrawPoint3D(position: Vector3, color: Color) void; pub extern fn DrawCircle3D(center: Vector3, radius: f32, rotationAxis: Vector3, rotationAngle: f32, color: Color) void; pub extern fn DrawTriangle3D(v1: Vector3, v2: Vector3, v3: Vector3, color: Color) void; pub extern fn DrawTriangleStrip3D(points: [*c]Vector3, pointsCount: c_int, color: Color) void; pub extern fn DrawCube(position: Vector3, width: f32, height: f32, length: f32, color: Color) void; pub extern fn DrawCubeV(position: Vector3, size: Vector3, color: Color) void; pub extern fn DrawCubeWires(position: Vector3, width: f32, height: f32, length: f32, color: Color) void; pub extern fn DrawCubeWiresV(position: Vector3, size: Vector3, color: Color) void; pub extern fn DrawCubeTexture(texture: Texture2D, position: Vector3, width: f32, height: f32, length: f32, color: Color) void; pub extern fn DrawSphere(centerPos: Vector3, radius: f32, color: Color) void; pub extern fn DrawSphereEx(centerPos: Vector3, radius: f32, rings: c_int, slices: c_int, color: Color) void; pub extern fn DrawSphereWires(centerPos: Vector3, radius: f32, rings: c_int, slices: c_int, color: Color) void; pub extern fn DrawCylinder(position: Vector3, radiusTop: f32, radiusBottom: f32, height: f32, slices: c_int, color: Color) void; pub extern fn DrawCylinderWires(position: Vector3, radiusTop: f32, radiusBottom: f32, height: f32, slices: c_int, color: Color) void; pub extern fn DrawPlane(centerPos: Vector3, size: Vector2, color: Color) void; pub extern fn DrawRay(ray: Ray, color: Color) void; pub extern fn DrawGrid(slices: c_int, spacing: f32) void; pub extern fn LoadModel(fileName: [*c]const u8) Model; pub extern fn LoadModelFromMesh(mesh: Mesh) Model; pub extern fn UnloadModel(model: Model) void; pub extern fn UnloadModelKeepMeshes(model: Model) void; pub extern fn UploadMesh(mesh: [*c]Mesh, dynamic: bool) void; pub extern fn UpdateMeshBuffer(mesh: Mesh, index: c_int, data: ?*c_void, dataSize: c_int, offset: c_int) void; pub extern fn DrawMesh(mesh: Mesh, material: Material, transform: Matrix) void; pub extern fn DrawMeshInstanced(mesh: Mesh, material: Material, transforms: [*c]Matrix, instances: c_int) void; pub extern fn UnloadMesh(mesh: Mesh) void; pub extern fn ExportMesh(mesh: Mesh, fileName: [*c]const u8) bool; pub extern fn LoadMaterials(fileName: [*c]const u8, materialCount: [*c]c_int) [*c]Material; pub extern fn LoadMaterialDefault() Material; pub extern fn UnloadMaterial(material: Material) void; pub extern fn SetMaterialTexture(material: [*c]Material, mapType: c_int, texture: Texture2D) void; pub extern fn SetModelMeshMaterial(model: [*c]Model, meshId: c_int, materialId: c_int) void; pub extern fn LoadModelAnimations(fileName: [*c]const u8, animsCount: [*c]c_int) [*c]ModelAnimation; pub extern fn UpdateModelAnimation(model: Model, anim: ModelAnimation, frame: c_int) void; pub extern fn UnloadModelAnimation(anim: ModelAnimation) void; pub extern fn UnloadModelAnimations(animations: [*c]ModelAnimation, count: c_uint) void; pub extern fn IsModelAnimationValid(model: Model, anim: ModelAnimation) bool; pub extern fn GenMeshPoly(sides: c_int, radius: f32) Mesh; pub extern fn GenMeshPlane(width: f32, length: f32, resX: c_int, resZ: c_int) Mesh; pub extern fn GenMeshCube(width: f32, height: f32, length: f32) Mesh; pub extern fn GenMeshSphere(radius: f32, rings: c_int, slices: c_int) Mesh; pub extern fn GenMeshHemiSphere(radius: f32, rings: c_int, slices: c_int) Mesh; pub extern fn GenMeshCylinder(radius: f32, height: f32, slices: c_int) Mesh; pub extern fn GenMeshTorus(radius: f32, size: f32, radSeg: c_int, sides: c_int) Mesh; pub extern fn GenMeshKnot(radius: f32, size: f32, radSeg: c_int, sides: c_int) Mesh; pub extern fn GenMeshHeightmap(heightmap: Image, size: Vector3) Mesh; pub extern fn GenMeshCubicmap(cubicmap: Image, cubeSize: Vector3) Mesh; pub extern fn GetMeshBoundingBox(mesh: Mesh) BoundingBox; pub extern fn GenMeshTangents(mesh: [*c]Mesh) void; pub extern fn GenMeshBinormals(mesh: [*c]Mesh) void; pub extern fn DrawModel(model: Model, position: Vector3, scale: f32, tint: Color) void; pub extern fn DrawModelEx(model: Model, position: Vector3, rotationAxis: Vector3, rotationAngle: f32, scale: Vector3, tint: Color) void; pub extern fn DrawModelWires(model: Model, position: Vector3, scale: f32, tint: Color) void; pub extern fn DrawModelWiresEx(model: Model, position: Vector3, rotationAxis: Vector3, rotationAngle: f32, scale: Vector3, tint: Color) void; pub extern fn DrawBoundingBox(box: BoundingBox, color: Color) void; pub extern fn DrawBillboard(camera: Camera, texture: Texture2D, position: Vector3, size: f32, tint: Color) void; pub extern fn DrawBillboardRec(camera: Camera, texture: Texture2D, source: Rectangle, position: Vector3, size: Vector2, tint: Color) void; pub extern fn DrawBillboardPro(camera: Camera, texture: Texture2D, source: Rectangle, position: Vector3, size: Vector2, origin: Vector2, rotation: f32, tint: Color) void; pub extern fn CheckCollisionSpheres(center1: Vector3, radius1: f32, center2: Vector3, radius2: f32) bool; pub extern fn CheckCollisionBoxes(box1: BoundingBox, box2: BoundingBox) bool; pub extern fn CheckCollisionBoxSphere(box: BoundingBox, center: Vector3, radius: f32) bool; pub extern fn GetRayCollisionSphere(ray: Ray, center: Vector3, radius: f32) RayCollision; pub extern fn GetRayCollisionBox(ray: Ray, box: BoundingBox) RayCollision; pub extern fn GetRayCollisionModel(ray: Ray, model: Model) RayCollision; pub extern fn GetRayCollisionMesh(ray: Ray, mesh: Mesh, transform: Matrix) RayCollision; pub extern fn GetRayCollisionTriangle(ray: Ray, p1: Vector3, p2: Vector3, p3: Vector3) RayCollision; pub extern fn GetRayCollisionQuad(ray: Ray, p1: Vector3, p2: Vector3, p3: Vector3, p4: Vector3) RayCollision; pub extern fn InitAudioDevice() void; pub extern fn CloseAudioDevice() void; pub extern fn IsAudioDeviceReady() bool; pub extern fn SetMasterVolume(volume: f32) void; pub extern fn LoadWave(fileName: [*c]const u8) Wave; pub extern fn LoadWaveFromMemory(fileType: [*c]const u8, fileData: [*c]const u8, dataSize: c_int) Wave; pub extern fn LoadSound(fileName: [*c]const u8) Sound; pub extern fn LoadSoundFromWave(wave: Wave) Sound; pub extern fn UpdateSound(sound: Sound, data: ?*const c_void, samplesCount: c_int) void; pub extern fn UnloadWave(wave: Wave) void; pub extern fn UnloadSound(sound: Sound) void; pub extern fn ExportWave(wave: Wave, fileName: [*c]const u8) bool; pub extern fn ExportWaveAsCode(wave: Wave, fileName: [*c]const u8) bool; pub extern fn PlaySound(sound: Sound) void; pub extern fn StopSound(sound: Sound) void; pub extern fn PauseSound(sound: Sound) void; pub extern fn ResumeSound(sound: Sound) void; pub extern fn PlaySoundMulti(sound: Sound) void; pub extern fn StopSoundMulti() void; pub extern fn GetSoundsPlaying() c_int; pub extern fn IsSoundPlaying(sound: Sound) bool; pub extern fn SetSoundVolume(sound: Sound, volume: f32) void; pub extern fn SetSoundPitch(sound: Sound, pitch: f32) void; pub extern fn WaveFormat(wave: [*c]Wave, sampleRate: c_int, sampleSize: c_int, channels: c_int) void; pub extern fn WaveCopy(wave: Wave) Wave; pub extern fn WaveCrop(wave: [*c]Wave, initSample: c_int, finalSample: c_int) void; pub extern fn LoadWaveSamples(wave: Wave) [*c]f32; pub extern fn UnloadWaveSamples(samples: [*c]f32) void; pub extern fn LoadMusicStream(fileName: [*c]const u8) Music; pub extern fn LoadMusicStreamFromMemory(fileType: [*c]const u8, data: [*c]u8, dataSize: c_int) Music; pub extern fn UnloadMusicStream(music: Music) void; pub extern fn PlayMusicStream(music: Music) void; pub extern fn IsMusicStreamPlaying(music: Music) bool; pub extern fn UpdateMusicStream(music: Music) void; pub extern fn StopMusicStream(music: Music) void; pub extern fn PauseMusicStream(music: Music) void; pub extern fn ResumeMusicStream(music: Music) void; pub extern fn SetMusicVolume(music: Music, volume: f32) void; pub extern fn SetMusicPitch(music: Music, pitch: f32) void; pub extern fn GetMusicTimeLength(music: Music) f32; pub extern fn GetMusicTimePlayed(music: Music) f32; pub extern fn LoadAudioStream(sampleRate: c_uint, sampleSize: c_uint, channels: c_uint) AudioStream; pub extern fn UnloadAudioStream(stream: AudioStream) void; pub extern fn UpdateAudioStream(stream: AudioStream, data: ?*const c_void, samplesCount: c_int) void; pub extern fn IsAudioStreamProcessed(stream: AudioStream) bool; pub extern fn PlayAudioStream(stream: AudioStream) void; pub extern fn PauseAudioStream(stream: AudioStream) void; pub extern fn ResumeAudioStream(stream: AudioStream) void; pub extern fn IsAudioStreamPlaying(stream: AudioStream) bool; pub extern fn StopAudioStream(stream: AudioStream) void; pub extern fn SetAudioStreamVolume(stream: AudioStream, volume: f32) void; pub extern fn SetAudioStreamPitch(stream: AudioStream, pitch: f32) void; pub extern fn SetAudioStreamBufferSizeDefault(size: c_int) void; pub const struct_float3 = extern struct { v: [3]f32, }; pub const float3 = struct_float3; pub const struct_float16 = extern struct { v: [16]f32, }; pub const float16 = struct_float16; // C:\Users\user\scoop\apps\zig-dev\current\lib\libc\include\any-windows-any\_mingw.h:584:3: warning: TODO implement translation of stmt class GCCAsmStmtClass // C:\Users\user\scoop\apps\zig-dev\current\lib\libc\include\any-windows-any\_mingw.h:581:36: warning: unable to translate function, demoted to extern pub extern fn __debugbreak() void; pub extern fn __mingw_get_crt_info() [*c]const u8; pub const rsize_t = usize; pub const ptrdiff_t = c_longlong; pub const wchar_t = c_ushort; pub const wint_t = c_ushort; pub const wctype_t = c_ushort; pub const errno_t = c_int; pub const __time32_t = c_long; pub const __time64_t = c_longlong; pub const time_t = __time64_t; pub const struct_tagLC_ID = extern struct { wLanguage: c_ushort, wCountry: c_ushort, wCodePage: c_ushort, }; pub const LC_ID = struct_tagLC_ID; const struct_unnamed_1 = extern struct { locale: [*c]u8, wlocale: [*c]wchar_t, refcount: [*c]c_int, wrefcount: [*c]c_int, }; pub const struct_lconv = opaque {}; pub const struct___lc_time_data = opaque {}; pub const struct_threadlocaleinfostruct = extern struct { refcount: c_int, lc_codepage: c_uint, lc_collate_cp: c_uint, lc_handle: [6]c_ulong, lc_id: [6]LC_ID, lc_category: [6]struct_unnamed_1, lc_clike: c_int, mb_cur_max: c_int, lconv_intl_refcount: [*c]c_int, lconv_num_refcount: [*c]c_int, lconv_mon_refcount: [*c]c_int, lconv: ?*struct_lconv, ctype1_refcount: [*c]c_int, ctype1: [*c]c_ushort, pctype: [*c]const c_ushort, pclmap: [*c]const u8, pcumap: [*c]const u8, lc_time_curr: ?*struct___lc_time_data, }; pub const struct_threadmbcinfostruct = opaque {}; pub const pthreadlocinfo = [*c]struct_threadlocaleinfostruct; pub const pthreadmbcinfo = ?*struct_threadmbcinfostruct; pub const struct_localeinfo_struct = extern struct { locinfo: pthreadlocinfo, mbcinfo: pthreadmbcinfo, }; pub const _locale_tstruct = struct_localeinfo_struct; pub const _locale_t = [*c]struct_localeinfo_struct; pub const LPLC_ID = [*c]struct_tagLC_ID; pub const threadlocinfo = struct_threadlocaleinfostruct; pub const struct__exception = extern struct { type: c_int, name: [*c]const u8, arg1: f64, arg2: f64, retval: f64, }; const struct_unnamed_2 = extern struct { low: c_uint, high: c_uint, }; pub const union___mingw_dbl_type_t = extern union { x: f64, val: c_ulonglong, lh: struct_unnamed_2, }; pub const __mingw_dbl_type_t = union___mingw_dbl_type_t; pub const union___mingw_flt_type_t = extern union { x: f32, val: c_uint, }; pub const __mingw_flt_type_t = union___mingw_flt_type_t; // C:\Users\user\scoop\apps\zig-dev\current\lib\libc\include\any-windows-any\math.h:137:11: warning: struct demoted to opaque type - has bitfield const struct_unnamed_3 = opaque {}; pub const union___mingw_ldbl_type_t = extern union { x: c_longdouble, lh: struct_unnamed_3, }; pub const __mingw_ldbl_type_t = union___mingw_ldbl_type_t; pub extern var __imp__HUGE: [*c]f64; pub extern fn __mingw_raise_matherr(typ: c_int, name: [*c]const u8, a1: f64, a2: f64, rslt: f64) void; pub extern fn __mingw_setusermatherr(?fn ([*c]struct__exception) callconv(.C) c_int) void; pub extern fn __setusermatherr(?fn ([*c]struct__exception) callconv(.C) c_int) void; pub extern fn sin(_X: f64) f64; pub extern fn cos(_X: f64) f64; pub extern fn tan(_X: f64) f64; pub extern fn sinh(_X: f64) f64; pub extern fn cosh(_X: f64) f64; pub extern fn tanh(_X: f64) f64; pub extern fn asin(_X: f64) f64; pub extern fn acos(_X: f64) f64; pub extern fn atan(_X: f64) f64; pub extern fn atan2(_Y: f64, _X: f64) f64; pub extern fn exp(_X: f64) f64; pub extern fn log(_X: f64) f64; pub extern fn log10(_X: f64) f64; pub extern fn pow(_X: f64, _Y: f64) f64; pub extern fn sqrt(_X: f64) f64; pub extern fn ceil(_X: f64) f64; pub extern fn floor(_X: f64) f64; pub fn fabsf(arg_x: f32) callconv(.C) f32 { var x = arg_x; return __builtin_fabsf(x); } // C:\Users\user\scoop\apps\zig-dev\current\lib\libc\include\any-windows-any\math.h:219:23: warning: unsupported floating point constant format APFloatBaseSemantics.x86DoubleExtended // C:\Users\user\scoop\apps\zig-dev\current\lib\libc\include\any-windows-any\math.h:214:36: warning: unable to translate function, demoted to extern pub extern fn fabsl(arg_x: c_longdouble) callconv(.C) c_longdouble; pub fn fabs(arg_x: f64) callconv(.C) f64 { var x = arg_x; return __builtin_fabs(x); } pub extern fn ldexp(_X: f64, _Y: c_int) f64; pub extern fn frexp(_X: f64, _Y: [*c]c_int) f64; pub extern fn modf(_X: f64, _Y: [*c]f64) f64; pub extern fn fmod(_X: f64, _Y: f64) f64; pub extern fn sincos(__x: f64, p_sin: [*c]f64, p_cos: [*c]f64) void; pub extern fn sincosl(__x: c_longdouble, p_sin: [*c]c_longdouble, p_cos: [*c]c_longdouble) void; pub extern fn sincosf(__x: f32, p_sin: [*c]f32, p_cos: [*c]f32) void; pub extern fn abs(_X: c_int) c_int; pub extern fn labs(_X: c_long) c_long; pub extern fn atof(_String: [*c]const u8) f64; pub extern fn _atof_l(_String: [*c]const u8, _Locale: _locale_t) f64; pub const struct__complex = extern struct { x: f64, y: f64, }; pub extern fn _cabs(_ComplexA: struct__complex) f64; pub extern fn _hypot(_X: f64, _Y: f64) f64; pub extern fn _j0(_X: f64) f64; pub extern fn _j1(_X: f64) f64; pub extern fn _jn(_X: c_int, _Y: f64) f64; pub extern fn _y0(_X: f64) f64; pub extern fn _y1(_X: f64) f64; pub extern fn _yn(_X: c_int, _Y: f64) f64; pub extern fn _matherr([*c]struct__exception) c_int; pub extern fn _chgsign(_X: f64) f64; pub extern fn _copysign(_Number: f64, _Sign: f64) f64; pub extern fn _logb(f64) f64; pub extern fn _nextafter(f64, f64) f64; pub extern fn _scalb(f64, c_long) f64; pub extern fn _finite(f64) c_int; pub extern fn _fpclass(f64) c_int; pub extern fn _isnan(f64) c_int; pub extern fn j0(f64) f64; pub extern fn j1(f64) f64; pub extern fn jn(c_int, f64) f64; pub extern fn y0(f64) f64; pub extern fn y1(f64) f64; pub extern fn yn(c_int, f64) f64; pub extern fn chgsign(f64) f64; pub extern fn finite(f64) c_int; pub extern fn fpclass(f64) c_int; pub const float_t = f32; pub const double_t = f64; pub fn __fpclassifyl(arg_x: c_longdouble) callconv(.C) c_int { var x = arg_x; var hlp: __mingw_ldbl_type_t = undefined; var e: c_uint = undefined; hlp.x = x; e = @bitCast(c_uint, hlp.lh.sign_exponent & @as(c_int, 32767)); if (!(e != 0)) { var h: c_uint = hlp.lh.high; if (!((hlp.lh.low | h) != 0)) return 16384 else if (!((h & @as(c_uint, 2147483648)) != 0)) return @as(c_int, 1024) | @as(c_int, 16384); } else if (e == @bitCast(c_uint, @as(c_int, 32767))) return if (((hlp.lh.high & @bitCast(c_uint, @as(c_int, 2147483647))) | hlp.lh.low) == @bitCast(c_uint, @as(c_int, 0))) @as(c_int, 256) | @as(c_int, 1024) else @as(c_int, 256); return 1024; } pub fn __fpclassifyf(arg_x: f32) callconv(.C) c_int { var x = arg_x; var hlp: __mingw_flt_type_t = undefined; hlp.x = x; hlp.val &= @bitCast(c_uint, @as(c_int, 2147483647)); if (hlp.val == @bitCast(c_uint, @as(c_int, 0))) return 16384; if (hlp.val < @bitCast(c_uint, @as(c_int, 8388608))) return @as(c_int, 1024) | @as(c_int, 16384); if (hlp.val >= @bitCast(c_uint, @as(c_int, 2139095040))) return if (hlp.val > @bitCast(c_uint, @as(c_int, 2139095040))) @as(c_int, 256) else @as(c_int, 256) | @as(c_int, 1024); return 1024; } pub fn __fpclassify(arg_x: f64) callconv(.C) c_int { var x = arg_x; var hlp: __mingw_dbl_type_t = undefined; var l: c_uint = undefined; var h: c_uint = undefined; hlp.x = x; h = hlp.lh.high; l = hlp.lh.low | (h & @bitCast(c_uint, @as(c_int, 1048575))); h &= @bitCast(c_uint, @as(c_int, 2146435072)); if ((h | l) == @bitCast(c_uint, @as(c_int, 0))) return 16384; if (!(h != 0)) return @as(c_int, 1024) | @as(c_int, 16384); if (h == @bitCast(c_uint, @as(c_int, 2146435072))) return if (l != 0) @as(c_int, 256) else @as(c_int, 256) | @as(c_int, 1024); return 1024; } pub fn __isnan(arg__x: f64) callconv(.C) c_int { var _x = arg__x; var hlp: __mingw_dbl_type_t = undefined; var l: c_int = undefined; var h: c_int = undefined; hlp.x = _x; l = @bitCast(c_int, hlp.lh.low); h = @bitCast(c_int, hlp.lh.high & @bitCast(c_uint, @as(c_int, 2147483647))); h |= @bitCast(c_int, @bitCast(c_uint, l | -l) >> @intCast(@import("std").math.Log2Int(c_uint), 31)); h = @as(c_int, 2146435072) - h; return @bitCast(c_int, @bitCast(c_uint, h)) >> @intCast(@import("std").math.Log2Int(c_int), 31); } pub fn __isnanf(arg__x: f32) callconv(.C) c_int { var _x = arg__x; var hlp: __mingw_flt_type_t = undefined; var i: c_int = undefined; hlp.x = _x; i = @bitCast(c_int, hlp.val & @bitCast(c_uint, @as(c_int, 2147483647))); i = @as(c_int, 2139095040) - i; return @bitCast(c_int, @bitCast(c_uint, i) >> @intCast(@import("std").math.Log2Int(c_uint), 31)); } pub fn __isnanl(arg__x: c_longdouble) callconv(.C) c_int { var _x = arg__x; var ld: __mingw_ldbl_type_t = undefined; var xx: c_int = undefined; var signexp: c_int = undefined; ld.x = _x; signexp = (ld.lh.sign_exponent & @as(c_int, 32767)) << @intCast(@import("std").math.Log2Int(c_int), 1); xx = @bitCast(c_int, ld.lh.low | (ld.lh.high & @as(c_uint, 2147483647))); signexp |= @bitCast(c_int, @bitCast(c_uint, xx | -xx) >> @intCast(@import("std").math.Log2Int(c_uint), 31)); signexp = @as(c_int, 65534) - signexp; return @bitCast(c_int, @bitCast(c_uint, signexp)) >> @intCast(@import("std").math.Log2Int(c_int), 16); } pub fn __signbit(arg_x: f64) callconv(.C) c_int { var x = arg_x; var hlp: __mingw_dbl_type_t = undefined; hlp.x = x; return @boolToInt((hlp.lh.high & @as(c_uint, 2147483648)) != @bitCast(c_uint, @as(c_int, 0))); } pub fn __signbitf(arg_x: f32) callconv(.C) c_int { var x = arg_x; var hlp: __mingw_flt_type_t = undefined; hlp.x = x; return @boolToInt((hlp.val & @as(c_uint, 2147483648)) != @bitCast(c_uint, @as(c_int, 0))); } pub fn __signbitl(arg_x: c_longdouble) callconv(.C) c_int { var x = arg_x; var ld: __mingw_ldbl_type_t = undefined; ld.x = x; return @boolToInt((ld.lh.sign_exponent & @as(c_int, 32768)) != @as(c_int, 0)); } pub extern fn sinf(_X: f32) f32; pub extern fn sinl(c_longdouble) c_longdouble; pub extern fn cosf(_X: f32) f32; pub extern fn cosl(c_longdouble) c_longdouble; pub extern fn tanf(_X: f32) f32; pub extern fn tanl(c_longdouble) c_longdouble; pub extern fn asinf(_X: f32) f32; pub extern fn asinl(c_longdouble) c_longdouble; pub extern fn acosf(f32) f32; pub extern fn acosl(c_longdouble) c_longdouble; pub extern fn atanf(f32) f32; pub extern fn atanl(c_longdouble) c_longdouble; pub extern fn atan2f(f32, f32) f32; pub extern fn atan2l(c_longdouble, c_longdouble) c_longdouble; pub fn sinhf(arg__X: f32) callconv(.C) f32 { var _X = arg__X; return @floatCast(f32, sinh(@floatCast(f64, _X))); } pub extern fn sinhl(c_longdouble) c_longdouble; pub fn coshf(arg__X: f32) callconv(.C) f32 { var _X = arg__X; return @floatCast(f32, cosh(@floatCast(f64, _X))); } pub extern fn coshl(c_longdouble) c_longdouble; pub fn tanhf(arg__X: f32) callconv(.C) f32 { var _X = arg__X; return @floatCast(f32, tanh(@floatCast(f64, _X))); } pub extern fn tanhl(c_longdouble) c_longdouble; pub extern fn acosh(f64) f64; pub extern fn acoshf(f32) f32; pub extern fn acoshl(c_longdouble) c_longdouble; pub extern fn asinh(f64) f64; pub extern fn asinhf(f32) f32; pub extern fn asinhl(c_longdouble) c_longdouble; pub extern fn atanh(f64) f64; pub extern fn atanhf(f32) f32; pub extern fn atanhl(c_longdouble) c_longdouble; pub fn expf(arg__X: f32) callconv(.C) f32 { var _X = arg__X; return @floatCast(f32, exp(@floatCast(f64, _X))); } pub extern fn expl(c_longdouble) c_longdouble; pub extern fn exp2(f64) f64; pub extern fn exp2f(f32) f32; pub extern fn exp2l(c_longdouble) c_longdouble; pub extern fn expm1(f64) f64; pub extern fn expm1f(f32) f32; pub extern fn expm1l(c_longdouble) c_longdouble; pub fn frexpf(arg__X: f32, arg__Y: [*c]c_int) callconv(.C) f32 { var _X = arg__X; var _Y = arg__Y; return @floatCast(f32, frexp(@floatCast(f64, _X), _Y)); } pub extern fn frexpl(c_longdouble, [*c]c_int) c_longdouble; pub extern fn ilogb(f64) c_int; pub extern fn ilogbf(f32) c_int; pub extern fn ilogbl(c_longdouble) c_int; pub fn ldexpf(arg_x: f32, arg_expn: c_int) callconv(.C) f32 { var x = arg_x; var expn = arg_expn; return @floatCast(f32, ldexp(@floatCast(f64, x), expn)); } pub extern fn ldexpl(c_longdouble, c_int) c_longdouble; pub extern fn logf(f32) f32; pub extern fn logl(c_longdouble) c_longdouble; pub extern fn log10f(f32) f32; pub extern fn log10l(c_longdouble) c_longdouble; pub extern fn log1p(f64) f64; pub extern fn log1pf(f32) f32; pub extern fn log1pl(c_longdouble) c_longdouble; pub extern fn log2(f64) f64; pub extern fn log2f(f32) f32; pub extern fn log2l(c_longdouble) c_longdouble; pub extern fn logb(f64) f64; pub extern fn logbf(f32) f32; pub extern fn logbl(c_longdouble) c_longdouble; pub extern fn modff(f32, [*c]f32) f32; pub extern fn modfl(c_longdouble, [*c]c_longdouble) c_longdouble; pub extern fn scalbn(f64, c_int) f64; pub extern fn scalbnf(f32, c_int) f32; pub extern fn scalbnl(c_longdouble, c_int) c_longdouble; pub extern fn scalbln(f64, c_long) f64; pub extern fn scalblnf(f32, c_long) f32; pub extern fn scalblnl(c_longdouble, c_long) c_longdouble; pub extern fn cbrt(f64) f64; pub extern fn cbrtf(f32) f32; pub extern fn cbrtl(c_longdouble) c_longdouble; pub extern fn hypot(f64, f64) f64; pub fn hypotf(arg_x: f32, arg_y: f32) callconv(.C) f32 { var x = arg_x; var y = arg_y; return @floatCast(f32, hypot(@floatCast(f64, x), @floatCast(f64, y))); } pub extern fn hypotl(c_longdouble, c_longdouble) c_longdouble; pub fn powf(arg__X: f32, arg__Y: f32) callconv(.C) f32 { var _X = arg__X; var _Y = arg__Y; return @floatCast(f32, pow(@floatCast(f64, _X), @floatCast(f64, _Y))); } pub extern fn powl(c_longdouble, c_longdouble) c_longdouble; pub extern fn sqrtf(f32) f32; pub extern fn sqrtl(c_longdouble) c_longdouble; pub extern fn erf(f64) f64; pub extern fn erff(f32) f32; pub extern fn erfl(c_longdouble) c_longdouble; pub extern fn erfc(f64) f64; pub extern fn erfcf(f32) f32; pub extern fn erfcl(c_longdouble) c_longdouble; pub extern fn lgamma(f64) f64; pub extern fn lgammaf(f32) f32; pub extern fn lgammal(c_longdouble) c_longdouble; pub extern var signgam: c_int; pub extern fn tgamma(f64) f64; pub extern fn tgammaf(f32) f32; pub extern fn tgammal(c_longdouble) c_longdouble; pub extern fn ceilf(f32) f32; pub extern fn ceill(c_longdouble) c_longdouble; pub extern fn floorf(f32) f32; pub extern fn floorl(c_longdouble) c_longdouble; pub extern fn nearbyint(f64) f64; pub extern fn nearbyintf(f32) f32; pub extern fn nearbyintl(c_longdouble) c_longdouble; pub extern fn rint(f64) f64; pub extern fn rintf(f32) f32; pub extern fn rintl(c_longdouble) c_longdouble; pub extern fn lrint(f64) c_long; pub extern fn lrintf(f32) c_long; pub extern fn lrintl(c_longdouble) c_long; pub extern fn llrint(f64) c_longlong; pub extern fn llrintf(f32) c_longlong; pub extern fn llrintl(c_longdouble) c_longlong; pub extern fn round(f64) f64; pub extern fn roundf(f32) f32; pub extern fn roundl(c_longdouble) c_longdouble; pub extern fn lround(f64) c_long; pub extern fn lroundf(f32) c_long; pub extern fn lroundl(c_longdouble) c_long; pub extern fn llround(f64) c_longlong; pub extern fn llroundf(f32) c_longlong; pub extern fn llroundl(c_longdouble) c_longlong; pub extern fn trunc(f64) f64; pub extern fn truncf(f32) f32; pub extern fn truncl(c_longdouble) c_longdouble; pub extern fn fmodf(f32, f32) f32; pub extern fn fmodl(c_longdouble, c_longdouble) c_longdouble; pub extern fn remainder(f64, f64) f64; pub extern fn remainderf(f32, f32) f32; pub extern fn remainderl(c_longdouble, c_longdouble) c_longdouble; pub extern fn remquo(f64, f64, [*c]c_int) f64; pub extern fn remquof(f32, f32, [*c]c_int) f32; pub extern fn remquol(c_longdouble, c_longdouble, [*c]c_int) c_longdouble; pub fn copysign(arg_x: f64, arg_y: f64) callconv(.C) f64 { var x = arg_x; var y = arg_y; var hx: __mingw_dbl_type_t = undefined; var hy: __mingw_dbl_type_t = undefined; hx.x = x; hy.x = y; hx.lh.high = (hx.lh.high & @bitCast(c_uint, @as(c_int, 2147483647))) | (hy.lh.high & @as(c_uint, 2147483648)); return hx.x; } pub fn copysignf(arg_x: f32, arg_y: f32) callconv(.C) f32 { var x = arg_x; var y = arg_y; var hx: __mingw_flt_type_t = undefined; var hy: __mingw_flt_type_t = undefined; hx.x = x; hy.x = y; hx.val = (hx.val & @bitCast(c_uint, @as(c_int, 2147483647))) | (hy.val & @as(c_uint, 2147483648)); return hx.x; } pub extern fn copysignl(c_longdouble, c_longdouble) c_longdouble; pub extern fn nan(tagp: [*c]const u8) f64; pub extern fn nanf(tagp: [*c]const u8) f32; pub extern fn nanl(tagp: [*c]const u8) c_longdouble; pub extern fn nextafter(f64, f64) f64; pub extern fn nextafterf(f32, f32) f32; pub extern fn nextafterl(c_longdouble, c_longdouble) c_longdouble; pub extern fn nexttoward(f64, c_longdouble) f64; pub extern fn nexttowardf(f32, c_longdouble) f32; pub extern fn nexttowardl(c_longdouble, c_longdouble) c_longdouble; pub extern fn fdim(x: f64, y: f64) f64; pub extern fn fdimf(x: f32, y: f32) f32; pub extern fn fdiml(x: c_longdouble, y: c_longdouble) c_longdouble; pub extern fn fmax(f64, f64) f64; pub extern fn fmaxf(f32, f32) f32; pub extern fn fmaxl(c_longdouble, c_longdouble) c_longdouble; pub extern fn fmin(f64, f64) f64; pub extern fn fminf(f32, f32) f32; pub extern fn fminl(c_longdouble, c_longdouble) c_longdouble; pub extern fn fma(f64, f64, f64) f64; pub extern fn fmaf(f32, f32, f32) f32; pub extern fn fmal(c_longdouble, c_longdouble, c_longdouble) c_longdouble; pub extern fn _copysignf(_Number: f32, _Sign: f32) f32; pub extern fn _chgsignf(_X: f32) f32; pub extern fn _logbf(_X: f32) f32; pub extern fn _nextafterf(_X: f32, _Y: f32) f32; pub extern fn _finitef(_X: f32) c_int; pub extern fn _isnanf(_X: f32) c_int; pub extern fn _fpclassf(_X: f32) c_int; pub extern fn _chgsignl(c_longdouble) c_longdouble; pub fn Clamp(arg_value: f32, arg_min: f32, arg_max: f32) callconv(.C) f32 { var value = arg_value; var min = arg_min; var max = arg_max; const res: f32 = if (value < min) min else value; return if (res > max) max else res; } pub fn Lerp(arg_start: f32, arg_end: f32, arg_amount: f32) callconv(.C) f32 { var start = arg_start; var end = arg_end; var amount = arg_amount; return start + (amount * (end - start)); } pub fn Normalize(arg_value: f32, arg_start: f32, arg_end: f32) callconv(.C) f32 { var value = arg_value; var start = arg_start; var end = arg_end; return (value - start) / (end - start); } pub fn Remap(arg_value: f32, arg_inputStart: f32, arg_inputEnd: f32, arg_outputStart: f32, arg_outputEnd: f32) callconv(.C) f32 { var value = arg_value; var inputStart = arg_inputStart; var inputEnd = arg_inputEnd; var outputStart = arg_outputStart; var outputEnd = arg_outputEnd; return (((value - inputStart) / (inputEnd - inputStart)) * (outputEnd - outputStart)) + outputStart; } pub fn Vector2Zero() callconv(.C) Vector2 { var result: Vector2 = Vector2{ .x = 0.0, .y = 0.0, }; return result; } pub fn Vector2One() callconv(.C) Vector2 { var result: Vector2 = Vector2{ .x = 1.0, .y = 1.0, }; return result; } pub fn Vector2Add(arg_v1: Vector2, arg_v2: Vector2) callconv(.C) Vector2 { var v1 = arg_v1; var v2 = arg_v2; var result: Vector2 = Vector2{ .x = v1.x + v2.x, .y = v1.y + v2.y, }; return result; } pub fn Vector2AddValue(arg_v: Vector2, arg_add: f32) callconv(.C) Vector2 { var v = arg_v; var add = arg_add; var result: Vector2 = Vector2{ .x = v.x + add, .y = v.y + add, }; return result; } pub fn Vector2Subtract(arg_v1: Vector2, arg_v2: Vector2) callconv(.C) Vector2 { var v1 = arg_v1; var v2 = arg_v2; var result: Vector2 = Vector2{ .x = v1.x - v2.x, .y = v1.y - v2.y, }; return result; } pub fn Vector2SubtractValue(arg_v: Vector2, arg_sub: f32) callconv(.C) Vector2 { var v = arg_v; var sub = arg_sub; var result: Vector2 = Vector2{ .x = v.x - sub, .y = v.y - sub, }; return result; } pub fn Vector2Length(arg_v: Vector2) callconv(.C) f32 { var v = arg_v; var result: f32 = sqrtf((v.x * v.x) + (v.y * v.y)); return result; } pub fn Vector2LengthSqr(arg_v: Vector2) callconv(.C) f32 { var v = arg_v; var result: f32 = (v.x * v.x) + (v.y * v.y); return result; } pub fn Vector2DotProduct(arg_v1: Vector2, arg_v2: Vector2) callconv(.C) f32 { var v1 = arg_v1; var v2 = arg_v2; var result: f32 = (v1.x * v2.x) + (v1.y * v2.y); return result; } pub fn Vector2Distance(arg_v1: Vector2, arg_v2: Vector2) callconv(.C) f32 { var v1 = arg_v1; var v2 = arg_v2; var result: f32 = sqrtf(((v1.x - v2.x) * (v1.x - v2.x)) + ((v1.y - v2.y) * (v1.y - v2.y))); return result; } pub fn Vector2Angle(arg_v1: Vector2, arg_v2: Vector2) callconv(.C) f32 { var v1 = arg_v1; var v2 = arg_v2; var result: f32 = atan2f(v2.y - v1.y, v2.x - v1.x) * (180.0 / 3.1415927410125732); if (result < @intToFloat(f32, @as(c_int, 0))) { result += 360.0; } return result; } pub fn Vector2Scale(arg_v: Vector2, arg_scale: f32) callconv(.C) Vector2 { var v = arg_v; var scale = arg_scale; var result: Vector2 = Vector2{ .x = v.x * scale, .y = v.y * scale, }; return result; } pub fn Vector2Multiply(arg_v1: Vector2, arg_v2: Vector2) callconv(.C) Vector2 { var v1 = arg_v1; var v2 = arg_v2; var result: Vector2 = Vector2{ .x = v1.x * v2.x, .y = v1.y * v2.y, }; return result; } pub fn Vector2Negate(arg_v: Vector2) callconv(.C) Vector2 { var v = arg_v; var result: Vector2 = Vector2{ .x = -v.x, .y = -v.y, }; return result; } pub fn Vector2Divide(arg_v1: Vector2, arg_v2: Vector2) callconv(.C) Vector2 { var v1 = arg_v1; var v2 = arg_v2; var result: Vector2 = Vector2{ .x = v1.x / v2.x, .y = v1.y / v2.y, }; return result; } pub fn Vector2Normalize(arg_v: Vector2) callconv(.C) Vector2 { var v = arg_v; var result: Vector2 = Vector2Scale(v, @intToFloat(f32, @as(c_int, 1)) / Vector2Length(v)); return result; } pub fn Vector2Lerp(arg_v1: Vector2, arg_v2: Vector2, arg_amount: f32) callconv(.C) Vector2 { var v1 = arg_v1; var v2 = arg_v2; var amount = arg_amount; var result: Vector2 = Vector2{ .x = @intToFloat(f32, @as(c_int, 0)), .y = 0, }; result.x = v1.x + (amount * (v2.x - v1.x)); result.y = v1.y + (amount * (v2.y - v1.y)); return result; } pub fn Vector2Reflect(arg_v: Vector2, arg_normal: Vector2) callconv(.C) Vector2 { var v = arg_v; var normal = arg_normal; var result: Vector2 = Vector2{ .x = @intToFloat(f32, @as(c_int, 0)), .y = 0, }; var dotProduct: f32 = Vector2DotProduct(v, normal); result.x = v.x - ((2.0 * normal.x) * dotProduct); result.y = v.y - ((2.0 * normal.y) * dotProduct); return result; } pub fn Vector2Rotate(arg_v: Vector2, arg_degs: f32) callconv(.C) Vector2 { var v = arg_v; var degs = arg_degs; var rads: f32 = degs * (3.1415927410125732 / 180.0); var result: Vector2 = Vector2{ .x = (v.x * cosf(rads)) - (v.y * sinf(rads)), .y = (v.x * sinf(rads)) + (v.y * cosf(rads)), }; return result; } pub fn Vector2MoveTowards(arg_v: Vector2, arg_target: Vector2, arg_maxDistance: f32) callconv(.C) Vector2 { var v = arg_v; var target = arg_target; var maxDistance = arg_maxDistance; var result: Vector2 = Vector2{ .x = @intToFloat(f32, @as(c_int, 0)), .y = 0, }; var dx: f32 = target.x - v.x; var dy: f32 = target.y - v.y; var value: f32 = (dx * dx) + (dy * dy); if ((value == @intToFloat(f32, @as(c_int, 0))) or ((maxDistance >= @intToFloat(f32, @as(c_int, 0))) and (value <= (maxDistance * maxDistance)))) return target; var dist: f32 = sqrtf(value); result.x = v.x + ((dx / dist) * maxDistance); result.y = v.y + ((dy / dist) * maxDistance); return result; } pub fn Vector3Zero() callconv(.C) Vector3 { var result: Vector3 = Vector3{ .x = 0.0, .y = 0.0, .z = 0.0, }; return result; } pub fn Vector3One() callconv(.C) Vector3 { var result: Vector3 = Vector3{ .x = 1.0, .y = 1.0, .z = 1.0, }; return result; } pub fn Vector3Add(arg_v1: Vector3, arg_v2: Vector3) callconv(.C) Vector3 { var v1 = arg_v1; var v2 = arg_v2; var result: Vector3 = Vector3{ .x = v1.x + v2.x, .y = v1.y + v2.y, .z = v1.z + v2.z, }; return result; } pub fn Vector3AddValue(arg_v: Vector3, arg_add: f32) callconv(.C) Vector3 { var v = arg_v; var add = arg_add; var result: Vector3 = Vector3{ .x = v.x + add, .y = v.y + add, .z = v.z + add, }; return result; } pub fn Vector3Subtract(arg_v1: Vector3, arg_v2: Vector3) callconv(.C) Vector3 { var v1 = arg_v1; var v2 = arg_v2; var result: Vector3 = Vector3{ .x = v1.x - v2.x, .y = v1.y - v2.y, .z = v1.z - v2.z, }; return result; } pub fn Vector3SubtractValue(arg_v: Vector3, arg_sub: f32) callconv(.C) Vector3 { var v = arg_v; var sub = arg_sub; var result: Vector3 = Vector3{ .x = v.x - sub, .y = v.y - sub, .z = v.z - sub, }; return result; } pub fn Vector3Scale(arg_v: Vector3, arg_scalar: f32) callconv(.C) Vector3 { var v = arg_v; var scalar = arg_scalar; var result: Vector3 = Vector3{ .x = v.x * scalar, .y = v.y * scalar, .z = v.z * scalar, }; return result; } pub fn Vector3Multiply(arg_v1: Vector3, arg_v2: Vector3) callconv(.C) Vector3 { var v1 = arg_v1; var v2 = arg_v2; var result: Vector3 = Vector3{ .x = v1.x * v2.x, .y = v1.y * v2.y, .z = v1.z * v2.z, }; return result; } pub fn Vector3CrossProduct(arg_v1: Vector3, arg_v2: Vector3) callconv(.C) Vector3 { var v1 = arg_v1; var v2 = arg_v2; var result: Vector3 = Vector3{ .x = (v1.y * v2.z) - (v1.z * v2.y), .y = (v1.z * v2.x) - (v1.x * v2.z), .z = (v1.x * v2.y) - (v1.y * v2.x), }; return result; } pub fn Vector3Perpendicular(arg_v: Vector3) callconv(.C) Vector3 { var v = arg_v; var result: Vector3 = Vector3{ .x = @intToFloat(f32, @as(c_int, 0)), .y = 0, .z = 0, }; var min: f32 = @floatCast(f32, fabs(@floatCast(f64, v.x))); var cardinalAxis: Vector3 = Vector3{ .x = 1.0, .y = 0.0, .z = 0.0, }; if (fabs(@floatCast(f64, v.y)) < @floatCast(f64, min)) { min = @floatCast(f32, fabs(@floatCast(f64, v.y))); var tmp: Vector3 = Vector3{ .x = 0.0, .y = 1.0, .z = 0.0, }; cardinalAxis = tmp; } if (fabs(@floatCast(f64, v.z)) < @floatCast(f64, min)) { var tmp: Vector3 = Vector3{ .x = 0.0, .y = 0.0, .z = 1.0, }; cardinalAxis = tmp; } result = Vector3CrossProduct(v, cardinalAxis); return result; } pub fn Vector3Length(v: Vector3) callconv(.C) f32 { var result: f32 = sqrtf(((v.x * v.x) + (v.y * v.y)) + (v.z * v.z)); return result; } pub fn Vector3LengthSqr(v: Vector3) callconv(.C) f32 { var result: f32 = ((v.x * v.x) + (v.y * v.y)) + (v.z * v.z); return result; } pub fn Vector3DotProduct(arg_v1: Vector3, arg_v2: Vector3) callconv(.C) f32 { var v1 = arg_v1; var v2 = arg_v2; var result: f32 = ((v1.x * v2.x) + (v1.y * v2.y)) + (v1.z * v2.z); return result; } pub fn Vector3Distance(arg_v1: Vector3, arg_v2: Vector3) callconv(.C) f32 { var v1 = arg_v1; var v2 = arg_v2; var dx: f32 = v2.x - v1.x; var dy: f32 = v2.y - v1.y; var dz: f32 = v2.z - v1.z; var result: f32 = sqrtf(((dx * dx) + (dy * dy)) + (dz * dz)); return result; } pub fn Vector3Negate(arg_v: Vector3) callconv(.C) Vector3 { var v = arg_v; var result: Vector3 = Vector3{ .x = -v.x, .y = -v.y, .z = -v.z, }; return result; } pub fn Vector3Divide(arg_v1: Vector3, arg_v2: Vector3) callconv(.C) Vector3 { var v1 = arg_v1; var v2 = arg_v2; var result: Vector3 = Vector3{ .x = v1.x / v2.x, .y = v1.y / v2.y, .z = v1.z / v2.z, }; return result; } pub fn Vector3Normalize(arg_v: Vector3) callconv(.C) Vector3 { var v = arg_v; var result: Vector3 = v; var length: f32 = undefined; var ilength: f32 = undefined; length = Vector3Length(v); if (length == 0.0) { length = 1.0; } ilength = 1.0 / length; result.x *= ilength; result.y *= ilength; result.z *= ilength; return result; } pub fn Vector3OrthoNormalize(arg_v1: [*c]Vector3, arg_v2: [*c]Vector3) callconv(.C) void { var v1 = arg_v1; var v2 = arg_v2; v1.* = Vector3Normalize(v1.*); var vn: Vector3 = Vector3CrossProduct(v1.*, v2.*); vn = Vector3Normalize(vn); v2.* = Vector3CrossProduct(vn, v1.*); } pub fn Vector3Transform(arg_v: Vector3, arg_mat: Matrix) callconv(.C) Vector3 { var v = arg_v; var mat = arg_mat; var result: Vector3 = Vector3{ .x = @intToFloat(f32, @as(c_int, 0)), .y = 0, .z = 0, }; var x: f32 = v.x; var y: f32 = v.y; var z: f32 = v.z; result.x = (((mat.m0 * x) + (mat.m4 * y)) + (mat.m8 * z)) + mat.m12; result.y = (((mat.m1 * x) + (mat.m5 * y)) + (mat.m9 * z)) + mat.m13; result.z = (((mat.m2 * x) + (mat.m6 * y)) + (mat.m10 * z)) + mat.m14; return result; } pub fn Vector3RotateByQuaternion(arg_v: Vector3, arg_q: Quaternion) callconv(.C) Vector3 { var v = arg_v; var q = arg_q; var result: Vector3 = Vector3{ .x = @intToFloat(f32, @as(c_int, 0)), .y = 0, .z = 0, }; result.x = ((v.x * ((((q.x * q.x) + (q.w * q.w)) - (q.y * q.y)) - (q.z * q.z))) + (v.y * (((@intToFloat(f32, @as(c_int, 2)) * q.x) * q.y) - ((@intToFloat(f32, @as(c_int, 2)) * q.w) * q.z)))) + (v.z * (((@intToFloat(f32, @as(c_int, 2)) * q.x) * q.z) + ((@intToFloat(f32, @as(c_int, 2)) * q.w) * q.y))); result.y = ((v.x * (((@intToFloat(f32, @as(c_int, 2)) * q.w) * q.z) + ((@intToFloat(f32, @as(c_int, 2)) * q.x) * q.y))) + (v.y * ((((q.w * q.w) - (q.x * q.x)) + (q.y * q.y)) - (q.z * q.z)))) + (v.z * (((@intToFloat(f32, -@as(c_int, 2)) * q.w) * q.x) + ((@intToFloat(f32, @as(c_int, 2)) * q.y) * q.z))); result.z = ((v.x * (((@intToFloat(f32, -@as(c_int, 2)) * q.w) * q.y) + ((@intToFloat(f32, @as(c_int, 2)) * q.x) * q.z))) + (v.y * (((@intToFloat(f32, @as(c_int, 2)) * q.w) * q.x) + ((@intToFloat(f32, @as(c_int, 2)) * q.y) * q.z)))) + (v.z * ((((q.w * q.w) - (q.x * q.x)) - (q.y * q.y)) + (q.z * q.z))); return result; } pub fn Vector3Lerp(arg_v1: Vector3, arg_v2: Vector3, arg_amount: f32) callconv(.C) Vector3 { var v1 = arg_v1; var v2 = arg_v2; var amount = arg_amount; var result: Vector3 = Vector3{ .x = @intToFloat(f32, @as(c_int, 0)), .y = 0, .z = 0, }; result.x = v1.x + (amount * (v2.x - v1.x)); result.y = v1.y + (amount * (v2.y - v1.y)); result.z = v1.z + (amount * (v2.z - v1.z)); return result; } pub fn Vector3Reflect(arg_v: Vector3, arg_normal: Vector3) callconv(.C) Vector3 { var v = arg_v; var normal = arg_normal; var result: Vector3 = Vector3{ .x = @intToFloat(f32, @as(c_int, 0)), .y = 0, .z = 0, }; var dotProduct: f32 = Vector3DotProduct(v, normal); result.x = v.x - ((2.0 * normal.x) * dotProduct); result.y = v.y - ((2.0 * normal.y) * dotProduct); result.z = v.z - ((2.0 * normal.z) * dotProduct); return result; } pub fn Vector3Min(arg_v1: Vector3, arg_v2: Vector3) callconv(.C) Vector3 { var v1 = arg_v1; var v2 = arg_v2; var result: Vector3 = Vector3{ .x = @intToFloat(f32, @as(c_int, 0)), .y = 0, .z = 0, }; result.x = fminf(v1.x, v2.x); result.y = fminf(v1.y, v2.y); result.z = fminf(v1.z, v2.z); return result; } pub fn Vector3Max(arg_v1: Vector3, arg_v2: Vector3) callconv(.C) Vector3 { var v1 = arg_v1; var v2 = arg_v2; var result: Vector3 = Vector3{ .x = @intToFloat(f32, @as(c_int, 0)), .y = 0, .z = 0, }; result.x = fmaxf(v1.x, v2.x); result.y = fmaxf(v1.y, v2.y); result.z = fmaxf(v1.z, v2.z); return result; } pub fn Vector3Barycenter(arg_p: Vector3, arg_a: Vector3, arg_b: Vector3, arg_c: Vector3) callconv(.C) Vector3 { var p = arg_p; var a = arg_a; var b = arg_b; var c = arg_c; var v0: Vector3 = Vector3Subtract(b, a); var v1: Vector3 = Vector3Subtract(c, a); var v2: Vector3 = Vector3Subtract(p, a); var d00: f32 = Vector3DotProduct(v0, v0); var d01: f32 = Vector3DotProduct(v0, v1); var d11: f32 = Vector3DotProduct(v1, v1); var d20: f32 = Vector3DotProduct(v2, v0); var d21: f32 = Vector3DotProduct(v2, v1); var denom: f32 = (d00 * d11) - (d01 * d01); var result: Vector3 = Vector3{ .x = @intToFloat(f32, @as(c_int, 0)), .y = 0, .z = 0, }; result.y = ((d11 * d20) - (d01 * d21)) / denom; result.z = ((d00 * d21) - (d01 * d20)) / denom; result.x = 1.0 - (result.z + result.y); return result; } pub fn Vector3ToFloatV(arg_v: Vector3) callconv(.C) float3 { var v = arg_v; var buffer: float3 = float3{ .v = [1]f32{ 0, } ++ [1]f32{0} ** 2, }; buffer.v[@intCast(c_uint, @as(c_int, 0))] = v.x; buffer.v[@intCast(c_uint, @as(c_int, 1))] = v.y; buffer.v[@intCast(c_uint, @as(c_int, 2))] = v.z; return buffer; } pub fn MatrixDeterminant(arg_mat: Matrix) callconv(.C) f32 { var mat = arg_mat; var a00: f32 = mat.m0; var a01: f32 = mat.m1; var a02: f32 = mat.m2; var a03: f32 = mat.m3; var a10: f32 = mat.m4; var a11: f32 = mat.m5; var a12: f32 = mat.m6; var a13: f32 = mat.m7; var a20: f32 = mat.m8; var a21: f32 = mat.m9; var a22: f32 = mat.m10; var a23: f32 = mat.m11; var a30: f32 = mat.m12; var a31: f32 = mat.m13; var a32: f32 = mat.m14; var a33: f32 = mat.m15; var result: f32 = (((((((((((((((((((((((((a30 * a21) * a12) * a03) - (((a20 * a31) * a12) * a03)) - (((a30 * a11) * a22) * a03)) + (((a10 * a31) * a22) * a03)) + (((a20 * a11) * a32) * a03)) - (((a10 * a21) * a32) * a03)) - (((a30 * a21) * a02) * a13)) + (((a20 * a31) * a02) * a13)) + (((a30 * a01) * a22) * a13)) - (((a00 * a31) * a22) * a13)) - (((a20 * a01) * a32) * a13)) + (((a00 * a21) * a32) * a13)) + (((a30 * a11) * a02) * a23)) - (((a10 * a31) * a02) * a23)) - (((a30 * a01) * a12) * a23)) + (((a00 * a31) * a12) * a23)) + (((a10 * a01) * a32) * a23)) - (((a00 * a11) * a32) * a23)) - (((a20 * a11) * a02) * a33)) + (((a10 * a21) * a02) * a33)) + (((a20 * a01) * a12) * a33)) - (((a00 * a21) * a12) * a33)) - (((a10 * a01) * a22) * a33)) + (((a00 * a11) * a22) * a33); return result; } pub fn MatrixTrace(arg_mat: Matrix) callconv(.C) f32 { var mat = arg_mat; var result: f32 = ((mat.m0 + mat.m5) + mat.m10) + mat.m15; return result; } pub fn MatrixTranspose(arg_mat: Matrix) callconv(.C) Matrix { var mat = arg_mat; var result: Matrix = Matrix{ .m0 = @intToFloat(f32, @as(c_int, 0)), .m4 = 0, .m8 = 0, .m12 = 0, .m1 = 0, .m5 = 0, .m9 = 0, .m13 = 0, .m2 = 0, .m6 = 0, .m10 = 0, .m14 = 0, .m3 = 0, .m7 = 0, .m11 = 0, .m15 = 0, }; result.m0 = mat.m0; result.m1 = mat.m4; result.m2 = mat.m8; result.m3 = mat.m12; result.m4 = mat.m1; result.m5 = mat.m5; result.m6 = mat.m9; result.m7 = mat.m13; result.m8 = mat.m2; result.m9 = mat.m6; result.m10 = mat.m10; result.m11 = mat.m14; result.m12 = mat.m3; result.m13 = mat.m7; result.m14 = mat.m11; result.m15 = mat.m15; return result; } pub fn MatrixInvert(arg_mat: Matrix) callconv(.C) Matrix { var mat = arg_mat; var result: Matrix = Matrix{ .m0 = @intToFloat(f32, @as(c_int, 0)), .m4 = 0, .m8 = 0, .m12 = 0, .m1 = 0, .m5 = 0, .m9 = 0, .m13 = 0, .m2 = 0, .m6 = 0, .m10 = 0, .m14 = 0, .m3 = 0, .m7 = 0, .m11 = 0, .m15 = 0, }; var a00: f32 = mat.m0; var a01: f32 = mat.m1; var a02: f32 = mat.m2; var a03: f32 = mat.m3; var a10: f32 = mat.m4; var a11: f32 = mat.m5; var a12: f32 = mat.m6; var a13: f32 = mat.m7; var a20: f32 = mat.m8; var a21: f32 = mat.m9; var a22: f32 = mat.m10; var a23: f32 = mat.m11; var a30: f32 = mat.m12; var a31: f32 = mat.m13; var a32: f32 = mat.m14; var a33: f32 = mat.m15; var b00: f32 = (a00 * a11) - (a01 * a10); var b01: f32 = (a00 * a12) - (a02 * a10); var b02: f32 = (a00 * a13) - (a03 * a10); var b03: f32 = (a01 * a12) - (a02 * a11); var b04: f32 = (a01 * a13) - (a03 * a11); var b05: f32 = (a02 * a13) - (a03 * a12); var b06: f32 = (a20 * a31) - (a21 * a30); var b07: f32 = (a20 * a32) - (a22 * a30); var b08: f32 = (a20 * a33) - (a23 * a30); var b09: f32 = (a21 * a32) - (a22 * a31); var b10: f32 = (a21 * a33) - (a23 * a31); var b11: f32 = (a22 * a33) - (a23 * a32); var invDet: f32 = 1.0 / ((((((b00 * b11) - (b01 * b10)) + (b02 * b09)) + (b03 * b08)) - (b04 * b07)) + (b05 * b06)); result.m0 = (((a11 * b11) - (a12 * b10)) + (a13 * b09)) * invDet; result.m1 = (((-a01 * b11) + (a02 * b10)) - (a03 * b09)) * invDet; result.m2 = (((a31 * b05) - (a32 * b04)) + (a33 * b03)) * invDet; result.m3 = (((-a21 * b05) + (a22 * b04)) - (a23 * b03)) * invDet; result.m4 = (((-a10 * b11) + (a12 * b08)) - (a13 * b07)) * invDet; result.m5 = (((a00 * b11) - (a02 * b08)) + (a03 * b07)) * invDet; result.m6 = (((-a30 * b05) + (a32 * b02)) - (a33 * b01)) * invDet; result.m7 = (((a20 * b05) - (a22 * b02)) + (a23 * b01)) * invDet; result.m8 = (((a10 * b10) - (a11 * b08)) + (a13 * b06)) * invDet; result.m9 = (((-a00 * b10) + (a01 * b08)) - (a03 * b06)) * invDet; result.m10 = (((a30 * b04) - (a31 * b02)) + (a33 * b00)) * invDet; result.m11 = (((-a20 * b04) + (a21 * b02)) - (a23 * b00)) * invDet; result.m12 = (((-a10 * b09) + (a11 * b07)) - (a12 * b06)) * invDet; result.m13 = (((a00 * b09) - (a01 * b07)) + (a02 * b06)) * invDet; result.m14 = (((-a30 * b03) + (a31 * b01)) - (a32 * b00)) * invDet; result.m15 = (((a20 * b03) - (a21 * b01)) + (a22 * b00)) * invDet; return result; } pub fn MatrixNormalize(arg_mat: Matrix) callconv(.C) Matrix { var mat = arg_mat; var result: Matrix = Matrix{ .m0 = @intToFloat(f32, @as(c_int, 0)), .m4 = 0, .m8 = 0, .m12 = 0, .m1 = 0, .m5 = 0, .m9 = 0, .m13 = 0, .m2 = 0, .m6 = 0, .m10 = 0, .m14 = 0, .m3 = 0, .m7 = 0, .m11 = 0, .m15 = 0, }; var det: f32 = MatrixDeterminant(mat); result.m0 = mat.m0 / det; result.m1 = mat.m1 / det; result.m2 = mat.m2 / det; result.m3 = mat.m3 / det; result.m4 = mat.m4 / det; result.m5 = mat.m5 / det; result.m6 = mat.m6 / det; result.m7 = mat.m7 / det; result.m8 = mat.m8 / det; result.m9 = mat.m9 / det; result.m10 = mat.m10 / det; result.m11 = mat.m11 / det; result.m12 = mat.m12 / det; result.m13 = mat.m13 / det; result.m14 = mat.m14 / det; result.m15 = mat.m15 / det; return result; } pub fn MatrixIdentity() callconv(.C) Matrix { var result: Matrix = Matrix{ .m0 = 1.0, .m4 = 0.0, .m8 = 0.0, .m12 = 0.0, .m1 = 0.0, .m5 = 1.0, .m9 = 0.0, .m13 = 0.0, .m2 = 0.0, .m6 = 0.0, .m10 = 1.0, .m14 = 0.0, .m3 = 0.0, .m7 = 0.0, .m11 = 0.0, .m15 = 1.0, }; return result; } pub fn MatrixAdd(arg_left: Matrix, arg_right: Matrix) callconv(.C) Matrix { var left = arg_left; var right = arg_right; var result: Matrix = MatrixIdentity(); result.m0 = left.m0 + right.m0; result.m1 = left.m1 + right.m1; result.m2 = left.m2 + right.m2; result.m3 = left.m3 + right.m3; result.m4 = left.m4 + right.m4; result.m5 = left.m5 + right.m5; result.m6 = left.m6 + right.m6; result.m7 = left.m7 + right.m7; result.m8 = left.m8 + right.m8; result.m9 = left.m9 + right.m9; result.m10 = left.m10 + right.m10; result.m11 = left.m11 + right.m11; result.m12 = left.m12 + right.m12; result.m13 = left.m13 + right.m13; result.m14 = left.m14 + right.m14; result.m15 = left.m15 + right.m15; return result; } pub fn MatrixSubtract(arg_left: Matrix, arg_right: Matrix) callconv(.C) Matrix { var left = arg_left; var right = arg_right; var result: Matrix = MatrixIdentity(); result.m0 = left.m0 - right.m0; result.m1 = left.m1 - right.m1; result.m2 = left.m2 - right.m2; result.m3 = left.m3 - right.m3; result.m4 = left.m4 - right.m4; result.m5 = left.m5 - right.m5; result.m6 = left.m6 - right.m6; result.m7 = left.m7 - right.m7; result.m8 = left.m8 - right.m8; result.m9 = left.m9 - right.m9; result.m10 = left.m10 - right.m10; result.m11 = left.m11 - right.m11; result.m12 = left.m12 - right.m12; result.m13 = left.m13 - right.m13; result.m14 = left.m14 - right.m14; result.m15 = left.m15 - right.m15; return result; } pub fn MatrixMultiply(arg_left: Matrix, arg_right: Matrix) callconv(.C) Matrix { var left = arg_left; var right = arg_right; var result: Matrix = Matrix{ .m0 = @intToFloat(f32, @as(c_int, 0)), .m4 = 0, .m8 = 0, .m12 = 0, .m1 = 0, .m5 = 0, .m9 = 0, .m13 = 0, .m2 = 0, .m6 = 0, .m10 = 0, .m14 = 0, .m3 = 0, .m7 = 0, .m11 = 0, .m15 = 0, }; result.m0 = (((left.m0 * right.m0) + (left.m1 * right.m4)) + (left.m2 * right.m8)) + (left.m3 * right.m12); result.m1 = (((left.m0 * right.m1) + (left.m1 * right.m5)) + (left.m2 * right.m9)) + (left.m3 * right.m13); result.m2 = (((left.m0 * right.m2) + (left.m1 * right.m6)) + (left.m2 * right.m10)) + (left.m3 * right.m14); result.m3 = (((left.m0 * right.m3) + (left.m1 * right.m7)) + (left.m2 * right.m11)) + (left.m3 * right.m15); result.m4 = (((left.m4 * right.m0) + (left.m5 * right.m4)) + (left.m6 * right.m8)) + (left.m7 * right.m12); result.m5 = (((left.m4 * right.m1) + (left.m5 * right.m5)) + (left.m6 * right.m9)) + (left.m7 * right.m13); result.m6 = (((left.m4 * right.m2) + (left.m5 * right.m6)) + (left.m6 * right.m10)) + (left.m7 * right.m14); result.m7 = (((left.m4 * right.m3) + (left.m5 * right.m7)) + (left.m6 * right.m11)) + (left.m7 * right.m15); result.m8 = (((left.m8 * right.m0) + (left.m9 * right.m4)) + (left.m10 * right.m8)) + (left.m11 * right.m12); result.m9 = (((left.m8 * right.m1) + (left.m9 * right.m5)) + (left.m10 * right.m9)) + (left.m11 * right.m13); result.m10 = (((left.m8 * right.m2) + (left.m9 * right.m6)) + (left.m10 * right.m10)) + (left.m11 * right.m14); result.m11 = (((left.m8 * right.m3) + (left.m9 * right.m7)) + (left.m10 * right.m11)) + (left.m11 * right.m15); result.m12 = (((left.m12 * right.m0) + (left.m13 * right.m4)) + (left.m14 * right.m8)) + (left.m15 * right.m12); result.m13 = (((left.m12 * right.m1) + (left.m13 * right.m5)) + (left.m14 * right.m9)) + (left.m15 * right.m13); result.m14 = (((left.m12 * right.m2) + (left.m13 * right.m6)) + (left.m14 * right.m10)) + (left.m15 * right.m14); result.m15 = (((left.m12 * right.m3) + (left.m13 * right.m7)) + (left.m14 * right.m11)) + (left.m15 * right.m15); return result; } pub fn MatrixTranslate(arg_x: f32, arg_y: f32, arg_z: f32) callconv(.C) Matrix { var x = arg_x; var y = arg_y; var z = arg_z; var result: Matrix = Matrix{ .m0 = 1.0, .m4 = 0.0, .m8 = 0.0, .m12 = x, .m1 = 0.0, .m5 = 1.0, .m9 = 0.0, .m13 = y, .m2 = 0.0, .m6 = 0.0, .m10 = 1.0, .m14 = z, .m3 = 0.0, .m7 = 0.0, .m11 = 0.0, .m15 = 1.0, }; return result; } pub fn MatrixRotate(arg_axis: Vector3, arg_angle: f32) callconv(.C) Matrix { var axis = arg_axis; var angle = arg_angle; var result: Matrix = Matrix{ .m0 = @intToFloat(f32, @as(c_int, 0)), .m4 = 0, .m8 = 0, .m12 = 0, .m1 = 0, .m5 = 0, .m9 = 0, .m13 = 0, .m2 = 0, .m6 = 0, .m10 = 0, .m14 = 0, .m3 = 0, .m7 = 0, .m11 = 0, .m15 = 0, }; var x: f32 = axis.x; var y: f32 = axis.y; var z: f32 = axis.z; var lengthSquared: f32 = ((x * x) + (y * y)) + (z * z); if ((lengthSquared != 1.0) and (lengthSquared != 0.0)) { var inverseLength: f32 = 1.0 / sqrtf(lengthSquared); x *= inverseLength; y *= inverseLength; z *= inverseLength; } var sinres: f32 = sinf(angle); var cosres: f32 = cosf(angle); var t: f32 = 1.0 - cosres; result.m0 = ((x * x) * t) + cosres; result.m1 = ((y * x) * t) + (z * sinres); result.m2 = ((z * x) * t) - (y * sinres); result.m3 = 0.0; result.m4 = ((x * y) * t) - (z * sinres); result.m5 = ((y * y) * t) + cosres; result.m6 = ((z * y) * t) + (x * sinres); result.m7 = 0.0; result.m8 = ((x * z) * t) + (y * sinres); result.m9 = ((y * z) * t) - (x * sinres); result.m10 = ((z * z) * t) + cosres; result.m11 = 0.0; result.m12 = 0.0; result.m13 = 0.0; result.m14 = 0.0; result.m15 = 1.0; return result; } pub fn MatrixRotateX(arg_angle: f32) callconv(.C) Matrix { var angle = arg_angle; var result: Matrix = MatrixIdentity(); var cosres: f32 = cosf(angle); var sinres: f32 = sinf(angle); result.m5 = cosres; result.m6 = -sinres; result.m9 = sinres; result.m10 = cosres; return result; } pub fn MatrixRotateY(arg_angle: f32) callconv(.C) Matrix { var angle = arg_angle; var result: Matrix = MatrixIdentity(); var cosres: f32 = cosf(angle); var sinres: f32 = sinf(angle); result.m0 = cosres; result.m2 = sinres; result.m8 = -sinres; result.m10 = cosres; return result; } pub fn MatrixRotateZ(arg_angle: f32) callconv(.C) Matrix { var angle = arg_angle; var result: Matrix = MatrixIdentity(); var cosres: f32 = cosf(angle); var sinres: f32 = sinf(angle); result.m0 = cosres; result.m1 = -sinres; result.m4 = sinres; result.m5 = cosres; return result; } pub fn MatrixRotateXYZ(arg_ang: Vector3) callconv(.C) Matrix { var ang = arg_ang; var result: Matrix = MatrixIdentity(); var cosz: f32 = cosf(-ang.z); var sinz: f32 = sinf(-ang.z); var cosy: f32 = cosf(-ang.y); var siny: f32 = sinf(-ang.y); var cosx: f32 = cosf(-ang.x); var sinx: f32 = sinf(-ang.x); result.m0 = cosz * cosy; result.m4 = ((cosz * siny) * sinx) - (sinz * cosx); result.m8 = ((cosz * siny) * cosx) + (sinz * sinx); result.m1 = sinz * cosy; result.m5 = ((sinz * siny) * sinx) + (cosz * cosx); result.m9 = ((sinz * siny) * cosx) - (cosz * sinx); result.m2 = -siny; result.m6 = cosy * sinx; result.m10 = cosy * cosx; return result; } pub fn MatrixRotateZYX(arg_ang: Vector3) callconv(.C) Matrix { var ang = arg_ang; var result: Matrix = Matrix{ .m0 = @intToFloat(f32, @as(c_int, 0)), .m4 = 0, .m8 = 0, .m12 = 0, .m1 = 0, .m5 = 0, .m9 = 0, .m13 = 0, .m2 = 0, .m6 = 0, .m10 = 0, .m14 = 0, .m3 = 0, .m7 = 0, .m11 = 0, .m15 = 0, }; var cz: f32 = cosf(ang.z); var sz: f32 = sinf(ang.z); var cy: f32 = cosf(ang.y); var sy: f32 = sinf(ang.y); var cx: f32 = cosf(ang.x); var sx: f32 = sinf(ang.x); result.m0 = cz * cy; result.m1 = ((cz * sy) * sx) - (cx * sz); result.m2 = (sz * sx) + ((cz * cx) * sy); result.m3 = 0; result.m4 = cy * sz; result.m5 = (cz * cx) + ((sz * sy) * sx); result.m6 = ((cx * sz) * sy) - (cz * sx); result.m7 = 0; result.m8 = -sy; result.m9 = cy * sx; result.m10 = cy * cx; result.m11 = 0; result.m12 = 0; result.m13 = 0; result.m14 = 0; result.m15 = 1; return result; } pub fn MatrixScale(arg_x: f32, arg_y: f32, arg_z: f32) callconv(.C) Matrix { var x = arg_x; var y = arg_y; var z = arg_z; var result: Matrix = Matrix{ .m0 = x, .m4 = 0.0, .m8 = 0.0, .m12 = 0.0, .m1 = 0.0, .m5 = y, .m9 = 0.0, .m13 = 0.0, .m2 = 0.0, .m6 = 0.0, .m10 = z, .m14 = 0.0, .m3 = 0.0, .m7 = 0.0, .m11 = 0.0, .m15 = 1.0, }; return result; } pub fn MatrixFrustum(arg_left: f64, arg_right: f64, arg_bottom: f64, arg_top: f64, arg_near: f64, arg_far: f64) callconv(.C) Matrix { var left = arg_left; var right = arg_right; var bottom = arg_bottom; var top = arg_top; var near = arg_near; var far = arg_far; var result: Matrix = Matrix{ .m0 = @intToFloat(f32, @as(c_int, 0)), .m4 = 0, .m8 = 0, .m12 = 0, .m1 = 0, .m5 = 0, .m9 = 0, .m13 = 0, .m2 = 0, .m6 = 0, .m10 = 0, .m14 = 0, .m3 = 0, .m7 = 0, .m11 = 0, .m15 = 0, }; var rl: f32 = @floatCast(f32, right - left); var tb: f32 = @floatCast(f32, top - bottom); var @"fn": f32 = @floatCast(f32, far - near); result.m0 = (@floatCast(f32, near) * 2.0) / rl; result.m1 = 0.0; result.m2 = 0.0; result.m3 = 0.0; result.m4 = 0.0; result.m5 = (@floatCast(f32, near) * 2.0) / tb; result.m6 = 0.0; result.m7 = 0.0; result.m8 = (@floatCast(f32, right) + @floatCast(f32, left)) / rl; result.m9 = (@floatCast(f32, top) + @floatCast(f32, bottom)) / tb; result.m10 = -(@floatCast(f32, far) + @floatCast(f32, near)) / @"fn"; result.m11 = -1.0; result.m12 = 0.0; result.m13 = 0.0; result.m14 = -((@floatCast(f32, far) * @floatCast(f32, near)) * 2.0) / @"fn"; result.m15 = 0.0; return result; } pub fn MatrixPerspective(arg_fovy: f64, arg_aspect: f64, arg_near: f64, arg_far: f64) callconv(.C) Matrix { var fovy = arg_fovy; var aspect = arg_aspect; var near = arg_near; var far = arg_far; var top: f64 = near * tan(fovy * 0.5); var right: f64 = top * aspect; var result: Matrix = MatrixFrustum(-right, right, -top, top, near, far); return result; } pub fn MatrixOrtho(arg_left: f64, arg_right: f64, arg_bottom: f64, arg_top: f64, arg_near: f64, arg_far: f64) callconv(.C) Matrix { var left = arg_left; var right = arg_right; var bottom = arg_bottom; var top = arg_top; var near = arg_near; var far = arg_far; var result: Matrix = Matrix{ .m0 = @intToFloat(f32, @as(c_int, 0)), .m4 = 0, .m8 = 0, .m12 = 0, .m1 = 0, .m5 = 0, .m9 = 0, .m13 = 0, .m2 = 0, .m6 = 0, .m10 = 0, .m14 = 0, .m3 = 0, .m7 = 0, .m11 = 0, .m15 = 0, }; var rl: f32 = @floatCast(f32, right - left); var tb: f32 = @floatCast(f32, top - bottom); var @"fn": f32 = @floatCast(f32, far - near); result.m0 = 2.0 / rl; result.m1 = 0.0; result.m2 = 0.0; result.m3 = 0.0; result.m4 = 0.0; result.m5 = 2.0 / tb; result.m6 = 0.0; result.m7 = 0.0; result.m8 = 0.0; result.m9 = 0.0; result.m10 = -2.0 / @"fn"; result.m11 = 0.0; result.m12 = -(@floatCast(f32, left) + @floatCast(f32, right)) / rl; result.m13 = -(@floatCast(f32, top) + @floatCast(f32, bottom)) / tb; result.m14 = -(@floatCast(f32, far) + @floatCast(f32, near)) / @"fn"; result.m15 = 1.0; return result; } pub fn MatrixLookAt(arg_eye: Vector3, arg_target: Vector3, arg_up: Vector3) callconv(.C) Matrix { var eye = arg_eye; var target = arg_target; var up = arg_up; var result: Matrix = Matrix{ .m0 = @intToFloat(f32, @as(c_int, 0)), .m4 = 0, .m8 = 0, .m12 = 0, .m1 = 0, .m5 = 0, .m9 = 0, .m13 = 0, .m2 = 0, .m6 = 0, .m10 = 0, .m14 = 0, .m3 = 0, .m7 = 0, .m11 = 0, .m15 = 0, }; var z: Vector3 = Vector3Subtract(eye, target); z = Vector3Normalize(z); var x: Vector3 = Vector3CrossProduct(up, z); x = Vector3Normalize(x); var y: Vector3 = Vector3CrossProduct(z, x); result.m0 = x.x; result.m1 = y.x; result.m2 = z.x; result.m3 = 0.0; result.m4 = x.y; result.m5 = y.y; result.m6 = z.y; result.m7 = 0.0; result.m8 = x.z; result.m9 = y.z; result.m10 = z.z; result.m11 = 0.0; result.m12 = -Vector3DotProduct(x, eye); result.m13 = -Vector3DotProduct(y, eye); result.m14 = -Vector3DotProduct(z, eye); result.m15 = 1.0; return result; } pub fn MatrixToFloatV(arg_mat: Matrix) callconv(.C) float16 { var mat = arg_mat; var buffer: float16 = float16{ .v = [1]f32{ 0, } ++ [1]f32{0} ** 15, }; buffer.v[@intCast(c_uint, @as(c_int, 0))] = mat.m0; buffer.v[@intCast(c_uint, @as(c_int, 1))] = mat.m1; buffer.v[@intCast(c_uint, @as(c_int, 2))] = mat.m2; buffer.v[@intCast(c_uint, @as(c_int, 3))] = mat.m3; buffer.v[@intCast(c_uint, @as(c_int, 4))] = mat.m4; buffer.v[@intCast(c_uint, @as(c_int, 5))] = mat.m5; buffer.v[@intCast(c_uint, @as(c_int, 6))] = mat.m6; buffer.v[@intCast(c_uint, @as(c_int, 7))] = mat.m7; buffer.v[@intCast(c_uint, @as(c_int, 8))] = mat.m8; buffer.v[@intCast(c_uint, @as(c_int, 9))] = mat.m9; buffer.v[@intCast(c_uint, @as(c_int, 10))] = mat.m10; buffer.v[@intCast(c_uint, @as(c_int, 11))] = mat.m11; buffer.v[@intCast(c_uint, @as(c_int, 12))] = mat.m12; buffer.v[@intCast(c_uint, @as(c_int, 13))] = mat.m13; buffer.v[@intCast(c_uint, @as(c_int, 14))] = mat.m14; buffer.v[@intCast(c_uint, @as(c_int, 15))] = mat.m15; return buffer; } pub fn QuaternionAdd(arg_q1: Quaternion, arg_q2: Quaternion) callconv(.C) Quaternion { var q1 = arg_q1; var q2 = arg_q2; var result: Quaternion = Quaternion{ .x = q1.x + q2.x, .y = q1.y + q2.y, .z = q1.z + q2.z, .w = q1.w + q2.w, }; return result; } pub fn QuaternionAddValue(arg_q: Quaternion, arg_add: f32) callconv(.C) Quaternion { var q = arg_q; var add = arg_add; var result: Quaternion = Quaternion{ .x = q.x + add, .y = q.y + add, .z = q.z + add, .w = q.w + add, }; return result; } pub fn QuaternionSubtract(arg_q1: Quaternion, arg_q2: Quaternion) callconv(.C) Quaternion { var q1 = arg_q1; var q2 = arg_q2; var result: Quaternion = Quaternion{ .x = q1.x - q2.x, .y = q1.y - q2.y, .z = q1.z - q2.z, .w = q1.w - q2.w, }; return result; } pub fn QuaternionSubtractValue(arg_q: Quaternion, arg_sub: f32) callconv(.C) Quaternion { var q = arg_q; var sub = arg_sub; var result: Quaternion = Quaternion{ .x = q.x - sub, .y = q.y - sub, .z = q.z - sub, .w = q.w - sub, }; return result; } pub fn QuaternionIdentity() callconv(.C) Quaternion { var result: Quaternion = Quaternion{ .x = 0.0, .y = 0.0, .z = 0.0, .w = 1.0, }; return result; } pub fn QuaternionLength(arg_q: Quaternion) callconv(.C) f32 { var q = arg_q; var result: f32 = sqrtf((((q.x * q.x) + (q.y * q.y)) + (q.z * q.z)) + (q.w * q.w)); return result; } pub fn QuaternionNormalize(arg_q: Quaternion) callconv(.C) Quaternion { var q = arg_q; var result: Quaternion = Quaternion{ .x = @intToFloat(f32, @as(c_int, 0)), .y = 0, .z = 0, .w = 0, }; var length: f32 = undefined; var ilength: f32 = undefined; length = QuaternionLength(q); if (length == 0.0) { length = 1.0; } ilength = 1.0 / length; result.x = q.x * ilength; result.y = q.y * ilength; result.z = q.z * ilength; result.w = q.w * ilength; return result; } pub fn QuaternionInvert(arg_q: Quaternion) callconv(.C) Quaternion { var q = arg_q; var result: Quaternion = q; var length: f32 = QuaternionLength(q); var lengthSq: f32 = length * length; if (@floatCast(f64, lengthSq) != 0.0) { var i: f32 = 1.0 / lengthSq; result.x *= -i; result.y *= -i; result.z *= -i; result.w *= i; } return result; } pub fn QuaternionMultiply(arg_q1: Quaternion, arg_q2: Quaternion) callconv(.C) Quaternion { var q1 = arg_q1; var q2 = arg_q2; var result: Quaternion = Quaternion{ .x = @intToFloat(f32, @as(c_int, 0)), .y = 0, .z = 0, .w = 0, }; var qax: f32 = q1.x; var qay: f32 = q1.y; var qaz: f32 = q1.z; var qaw: f32 = q1.w; var qbx: f32 = q2.x; var qby: f32 = q2.y; var qbz: f32 = q2.z; var qbw: f32 = q2.w; result.x = (((qax * qbw) + (qaw * qbx)) + (qay * qbz)) - (qaz * qby); result.y = (((qay * qbw) + (qaw * qby)) + (qaz * qbx)) - (qax * qbz); result.z = (((qaz * qbw) + (qaw * qbz)) + (qax * qby)) - (qay * qbx); result.w = (((qaw * qbw) - (qax * qbx)) - (qay * qby)) - (qaz * qbz); return result; } pub fn QuaternionScale(arg_q: Quaternion, arg_mul: f32) callconv(.C) Quaternion { var q = arg_q; var mul = arg_mul; var result: Quaternion = Quaternion{ .x = @intToFloat(f32, @as(c_int, 0)), .y = 0, .z = 0, .w = 0, }; var qax: f32 = q.x; var qay: f32 = q.y; var qaz: f32 = q.z; var qaw: f32 = q.w; result.x = (((qax * mul) + (qaw * mul)) + (qay * mul)) - (qaz * mul); result.y = (((qay * mul) + (qaw * mul)) + (qaz * mul)) - (qax * mul); result.z = (((qaz * mul) + (qaw * mul)) + (qax * mul)) - (qay * mul); result.w = (((qaw * mul) - (qax * mul)) - (qay * mul)) - (qaz * mul); return result; } pub fn QuaternionDivide(arg_q1: Quaternion, arg_q2: Quaternion) callconv(.C) Quaternion { var q1 = arg_q1; var q2 = arg_q2; var result: Quaternion = Quaternion{ .x = q1.x / q2.x, .y = q1.y / q2.y, .z = q1.z / q2.z, .w = q1.w / q2.w, }; return result; } pub fn QuaternionLerp(arg_q1: Quaternion, arg_q2: Quaternion, arg_amount: f32) callconv(.C) Quaternion { var q1 = arg_q1; var q2 = arg_q2; var amount = arg_amount; var result: Quaternion = Quaternion{ .x = @intToFloat(f32, @as(c_int, 0)), .y = 0, .z = 0, .w = 0, }; result.x = q1.x + (amount * (q2.x - q1.x)); result.y = q1.y + (amount * (q2.y - q1.y)); result.z = q1.z + (amount * (q2.z - q1.z)); result.w = q1.w + (amount * (q2.w - q1.w)); return result; } pub fn QuaternionNlerp(arg_q1: Quaternion, arg_q2: Quaternion, arg_amount: f32) callconv(.C) Quaternion { var q1 = arg_q1; var q2 = arg_q2; var amount = arg_amount; var result: Quaternion = QuaternionLerp(q1, q2, amount); result = QuaternionNormalize(result); return result; } pub fn QuaternionSlerp(arg_q1: Quaternion, arg_q2: Quaternion, arg_amount: f32) callconv(.C) Quaternion { var q1 = arg_q1; var q2 = arg_q2; var amount = arg_amount; var result: Quaternion = Quaternion{ .x = @intToFloat(f32, @as(c_int, 0)), .y = 0, .z = 0, .w = 0, }; var cosHalfTheta: f32 = (((q1.x * q2.x) + (q1.y * q2.y)) + (q1.z * q2.z)) + (q1.w * q2.w); if (cosHalfTheta < @intToFloat(f32, @as(c_int, 0))) { q2.x = -q2.x; q2.y = -q2.y; q2.z = -q2.z; q2.w = -q2.w; cosHalfTheta = -cosHalfTheta; } if (fabs(@floatCast(f64, cosHalfTheta)) >= @floatCast(f64, 1.0)) { result = q1; } else if (cosHalfTheta > 0.949999988079071) { result = QuaternionNlerp(q1, q2, amount); } else { var halfTheta: f32 = acosf(cosHalfTheta); var sinHalfTheta: f32 = sqrtf(1.0 - (cosHalfTheta * cosHalfTheta)); if (fabs(@floatCast(f64, sinHalfTheta)) < @floatCast(f64, 0.0010000000474974513)) { result.x = (q1.x * 0.5) + (q2.x * 0.5); result.y = (q1.y * 0.5) + (q2.y * 0.5); result.z = (q1.z * 0.5) + (q2.z * 0.5); result.w = (q1.w * 0.5) + (q2.w * 0.5); } else { var ratioA: f32 = sinf((@intToFloat(f32, @as(c_int, 1)) - amount) * halfTheta) / sinHalfTheta; var ratioB: f32 = sinf(amount * halfTheta) / sinHalfTheta; result.x = (q1.x * ratioA) + (q2.x * ratioB); result.y = (q1.y * ratioA) + (q2.y * ratioB); result.z = (q1.z * ratioA) + (q2.z * ratioB); result.w = (q1.w * ratioA) + (q2.w * ratioB); } } return result; } pub fn QuaternionFromVector3ToVector3(arg_from: Vector3, arg_to: Vector3) callconv(.C) Quaternion { var from = arg_from; var to = arg_to; var result: Quaternion = Quaternion{ .x = @intToFloat(f32, @as(c_int, 0)), .y = 0, .z = 0, .w = 0, }; var cos2Theta: f32 = Vector3DotProduct(from, to); var cross: Vector3 = Vector3CrossProduct(from, to); result.x = cross.x; result.y = cross.y; result.z = cross.z; result.w = 1.0 + cos2Theta; result = QuaternionNormalize(result); return result; } pub fn QuaternionFromMatrix(arg_mat: Matrix) callconv(.C) Quaternion { var mat = arg_mat; var result: Quaternion = Quaternion{ .x = @intToFloat(f32, @as(c_int, 0)), .y = 0, .z = 0, .w = 0, }; if ((mat.m0 > mat.m5) and (mat.m0 > mat.m10)) { var s: f32 = sqrtf(((1.0 + mat.m0) - mat.m5) - mat.m10) * @intToFloat(f32, @as(c_int, 2)); result.x = 0.25 * s; result.y = (mat.m4 + mat.m1) / s; result.z = (mat.m2 + mat.m8) / s; result.w = (mat.m9 - mat.m6) / s; } else if (mat.m5 > mat.m10) { var s: f32 = sqrtf(((1.0 + mat.m5) - mat.m0) - mat.m10) * @intToFloat(f32, @as(c_int, 2)); result.x = (mat.m4 + mat.m1) / s; result.y = 0.25 * s; result.z = (mat.m9 + mat.m6) / s; result.w = (mat.m2 - mat.m8) / s; } else { var s: f32 = sqrtf(((1.0 + mat.m10) - mat.m0) - mat.m5) * @intToFloat(f32, @as(c_int, 2)); result.x = (mat.m2 + mat.m8) / s; result.y = (mat.m9 + mat.m6) / s; result.z = 0.25 * s; result.w = (mat.m4 - mat.m1) / s; } return result; } pub fn QuaternionToMatrix(arg_q: Quaternion) callconv(.C) Matrix { var q = arg_q; var result: Matrix = MatrixIdentity(); var a2: f32 = q.x * q.x; var b2: f32 = q.y * q.y; var c2: f32 = q.z * q.z; var ac: f32 = q.x * q.z; var ab: f32 = q.x * q.y; var bc: f32 = q.y * q.z; var ad: f32 = q.w * q.x; var bd: f32 = q.w * q.y; var cd: f32 = q.w * q.z; result.m0 = @intToFloat(f32, @as(c_int, 1)) - (@intToFloat(f32, @as(c_int, 2)) * (b2 + c2)); result.m1 = @intToFloat(f32, @as(c_int, 2)) * (ab + cd); result.m2 = @intToFloat(f32, @as(c_int, 2)) * (ac - bd); result.m4 = @intToFloat(f32, @as(c_int, 2)) * (ab - cd); result.m5 = @intToFloat(f32, @as(c_int, 1)) - (@intToFloat(f32, @as(c_int, 2)) * (a2 + c2)); result.m6 = @intToFloat(f32, @as(c_int, 2)) * (bc + ad); result.m8 = @intToFloat(f32, @as(c_int, 2)) * (ac + bd); result.m9 = @intToFloat(f32, @as(c_int, 2)) * (bc - ad); result.m10 = @intToFloat(f32, @as(c_int, 1)) - (@intToFloat(f32, @as(c_int, 2)) * (a2 + b2)); return result; } pub fn QuaternionFromAxisAngle(arg_axis: Vector3, arg_angle: f32) callconv(.C) Quaternion { var axis = arg_axis; var angle = arg_angle; var result: Quaternion = Quaternion{ .x = 0.0, .y = 0.0, .z = 0.0, .w = 1.0, }; if (Vector3Length(axis) != 0.0) { angle *= 0.5; } axis = Vector3Normalize(axis); var sinres: f32 = sinf(angle); var cosres: f32 = cosf(angle); result.x = axis.x * sinres; result.y = axis.y * sinres; result.z = axis.z * sinres; result.w = cosres; result = QuaternionNormalize(result); return result; } pub fn QuaternionToAxisAngle(arg_q: Quaternion, arg_outAxis: [*c]Vector3, arg_outAngle: [*c]f32) callconv(.C) void { var q = arg_q; var outAxis = arg_outAxis; var outAngle = arg_outAngle; if (fabs(@floatCast(f64, q.w)) > @floatCast(f64, 1.0)) { q = QuaternionNormalize(q); } var resAxis: Vector3 = Vector3{ .x = 0.0, .y = 0.0, .z = 0.0, }; var resAngle: f32 = 2.0 * acosf(q.w); var den: f32 = sqrtf(1.0 - (q.w * q.w)); if (den > 0.00009999999747378752) { resAxis.x = q.x / den; resAxis.y = q.y / den; resAxis.z = q.z / den; } else { resAxis.x = 1.0; } outAxis.* = resAxis; outAngle.* = resAngle; } pub fn QuaternionFromEuler(arg_pitch: f32, arg_yaw: f32, arg_roll: f32) callconv(.C) Quaternion { var pitch = arg_pitch; var yaw = arg_yaw; var roll = arg_roll; var q: Quaternion = Quaternion{ .x = @intToFloat(f32, @as(c_int, 0)), .y = 0, .z = 0, .w = 0, }; var x0: f32 = cosf(pitch * 0.5); var x1: f32 = sinf(pitch * 0.5); var y0_1: f32 = cosf(yaw * 0.5); var y1_2: f32 = sinf(yaw * 0.5); var z0: f32 = cosf(roll * 0.5); var z1: f32 = sinf(roll * 0.5); q.x = ((x1 * y0_1) * z0) - ((x0 * y1_2) * z1); q.y = ((x0 * y1_2) * z0) + ((x1 * y0_1) * z1); q.z = ((x0 * y0_1) * z1) - ((x1 * y1_2) * z0); q.w = ((x0 * y0_1) * z0) + ((x1 * y1_2) * z1); return q; } pub fn QuaternionToEuler(arg_q: Quaternion) callconv(.C) Vector3 { var q = arg_q; var result: Vector3 = Vector3{ .x = @intToFloat(f32, @as(c_int, 0)), .y = 0, .z = 0, }; var x0: f32 = 2.0 * ((q.w * q.x) + (q.y * q.z)); var x1: f32 = 1.0 - (2.0 * ((q.x * q.x) + (q.y * q.y))); result.x = atan2f(x0, x1) * (180.0 / 3.1415927410125732); var y0_1: f32 = 2.0 * ((q.w * q.y) - (q.z * q.x)); y0_1 = if (y0_1 > 1.0) 1.0 else y0_1; y0_1 = if (y0_1 < -1.0) -1.0 else y0_1; result.y = asinf(y0_1) * (180.0 / 3.1415927410125732); var z0: f32 = 2.0 * ((q.w * q.z) + (q.x * q.y)); var z1: f32 = 1.0 - (2.0 * ((q.y * q.y) + (q.z * q.z))); result.z = atan2f(z0, z1) * (180.0 / 3.1415927410125732); return result; } pub fn QuaternionTransform(arg_q: Quaternion, arg_mat: Matrix) callconv(.C) Quaternion { var q = arg_q; var mat = arg_mat; var result: Quaternion = Quaternion{ .x = @intToFloat(f32, @as(c_int, 0)), .y = 0, .z = 0, .w = 0, }; result.x = (((mat.m0 * q.x) + (mat.m4 * q.y)) + (mat.m8 * q.z)) + (mat.m12 * q.w); result.y = (((mat.m1 * q.x) + (mat.m5 * q.y)) + (mat.m9 * q.z)) + (mat.m13 * q.w); result.z = (((mat.m2 * q.x) + (mat.m6 * q.y)) + (mat.m10 * q.z)) + (mat.m14 * q.w); result.w = (((mat.m3 * q.x) + (mat.m7 * q.y)) + (mat.m11 * q.z)) + (mat.m15 * q.w); return result; } pub fn Vector3Unproject(arg_source: Vector3, arg_projection: Matrix, arg_view: Matrix) callconv(.C) Vector3 { var source = arg_source; var projection = arg_projection; var view = arg_view; var result: Vector3 = Vector3{ .x = 0.0, .y = 0.0, .z = 0.0, }; var matViewProj: Matrix = MatrixMultiply(view, projection); matViewProj = MatrixInvert(matViewProj); var quat: Quaternion = Quaternion{ .x = source.x, .y = source.y, .z = source.z, .w = 1.0, }; quat = QuaternionTransform(quat, matViewProj); result.x = quat.x / quat.w; result.y = quat.y / quat.w; result.z = quat.z / quat.w; return result; } pub const __INTMAX_C_SUFFIX__ = @compileError("unable to translate macro: undefined identifier `LL`"); // (no file):66:9 pub const __UINTMAX_C_SUFFIX__ = @compileError("unable to translate macro: undefined identifier `ULL`"); // (no file):72:9 pub const __INT64_C_SUFFIX__ = @compileError("unable to translate macro: undefined identifier `LL`"); // (no file):164:9 pub const __UINT32_C_SUFFIX__ = @compileError("unable to translate macro: undefined identifier `U`"); // (no file):186:9 pub const __UINT64_C_SUFFIX__ = @compileError("unable to translate macro: undefined identifier `ULL`"); // (no file):194:9 pub const __seg_gs = @compileError("unable to translate macro: undefined identifier `__attribute__`"); // (no file):315:9 pub const __seg_fs = @compileError("unable to translate macro: undefined identifier `__attribute__`"); // (no file):316:9 pub const __declspec = @compileError("unable to translate macro: undefined identifier `__attribute__`"); // (no file):372:9 pub const _cdecl = @compileError("unable to translate macro: undefined identifier `__attribute__`"); // (no file):373:9 pub const __cdecl = @compileError("unable to translate macro: undefined identifier `__attribute__`"); // (no file):374:9 pub const _stdcall = @compileError("unable to translate macro: undefined identifier `__attribute__`"); // (no file):375:9 pub const __stdcall = @compileError("unable to translate macro: undefined identifier `__attribute__`"); // (no file):376:9 pub const _fastcall = @compileError("unable to translate macro: undefined identifier `__attribute__`"); // (no file):377:9 pub const __fastcall = @compileError("unable to translate macro: undefined identifier `__attribute__`"); // (no file):378:9 pub const _thiscall = @compileError("unable to translate macro: undefined identifier `__attribute__`"); // (no file):379:9 pub const __thiscall = @compileError("unable to translate macro: undefined identifier `__attribute__`"); // (no file):380:9 pub const _pascal = @compileError("unable to translate macro: undefined identifier `__attribute__`"); // (no file):381:9 pub const __pascal = @compileError("unable to translate macro: undefined identifier `__attribute__`"); // (no file):382:9 pub const va_start = @compileError("unable to translate macro: undefined identifier `__builtin_va_start`"); // C:\Users\user\scoop\apps\zig-dev\current\lib\include\stdarg.h:17:9 pub const va_end = @compileError("unable to translate macro: undefined identifier `__builtin_va_end`"); // C:\Users\user\scoop\apps\zig-dev\current\lib\include\stdarg.h:18:9 pub const va_arg = @compileError("unable to translate macro: undefined identifier `__builtin_va_arg`"); // C:\Users\user\scoop\apps\zig-dev\current\lib\include\stdarg.h:19:9 pub const __va_copy = @compileError("unable to translate macro: undefined identifier `__builtin_va_copy`"); // C:\Users\user\scoop\apps\zig-dev\current\lib\include\stdarg.h:24:9 pub const va_copy = @compileError("unable to translate macro: undefined identifier `__builtin_va_copy`"); // C:\Users\user\scoop\apps\zig-dev\current\lib\include\stdarg.h:27:9 pub const RL_MALLOC = @compileError("unable to translate macro: undefined identifier `malloc`"); // .\src\translate-c/../../3rd/raylib/src/raylib.h:111:13 pub const RL_CALLOC = @compileError("unable to translate macro: undefined identifier `calloc`"); // .\src\translate-c/../../3rd/raylib/src/raylib.h:114:13 pub const RL_REALLOC = @compileError("unable to translate macro: undefined identifier `realloc`"); // .\src\translate-c/../../3rd/raylib/src/raylib.h:117:13 pub const RL_FREE = @compileError("unable to translate macro: undefined identifier `free`"); // .\src\translate-c/../../3rd/raylib/src/raylib.h:120:13 pub const RMDEF = @compileError("unable to translate C expr: unexpected token .Keyword_inline"); // .\src\translate-c/../../3rd/raylib/src/raymath.h:70:17 pub const __STRINGIFY = @compileError("unable to translate C expr: unexpected token .Hash"); // C:\Users\user\scoop\apps\zig-dev\current\lib\libc\include\any-windows-any/_mingw_mac.h:10:9 pub const __MINGW64_VERSION_STR = @compileError("unable to translate C expr: unexpected token .StringLiteral"); // C:\Users\user\scoop\apps\zig-dev\current\lib\libc\include\any-windows-any/_mingw_mac.h:26:9 pub const __MINGW_IMP_SYMBOL = @compileError("unable to translate macro: undefined identifier `__imp_`"); // C:\Users\user\scoop\apps\zig-dev\current\lib\libc\include\any-windows-any/_mingw_mac.h:119:11 pub const __MINGW_IMP_LSYMBOL = @compileError("unable to translate macro: undefined identifier `__imp_`"); // C:\Users\user\scoop\apps\zig-dev\current\lib\libc\include\any-windows-any/_mingw_mac.h:120:11 pub const __MINGW_LSYMBOL = @compileError("unable to translate C expr: unexpected token .HashHash"); // C:\Users\user\scoop\apps\zig-dev\current\lib\libc\include\any-windows-any/_mingw_mac.h:122:11 pub const __MINGW_ASM_CALL = @compileError("unable to translate macro: undefined identifier `__asm__`"); // C:\Users\user\scoop\apps\zig-dev\current\lib\libc\include\any-windows-any/_mingw_mac.h:130:9 pub const __MINGW_ASM_CRT_CALL = @compileError("unable to translate macro: undefined identifier `__asm__`"); // C:\Users\user\scoop\apps\zig-dev\current\lib\libc\include\any-windows-any/_mingw_mac.h:131:9 pub const __MINGW_EXTENSION = @compileError("unable to translate macro: undefined identifier `__extension__`"); // C:\Users\user\scoop\apps\zig-dev\current\lib\libc\include\any-windows-any/_mingw_mac.h:163:13 pub const __MINGW_POISON_NAME = @compileError("unable to translate macro: undefined identifier `_layout_has_not_been_verified_and_its_declaration_is_most_likely_incorrect`"); // C:\Users\user\scoop\apps\zig-dev\current\lib\libc\include\any-windows-any/_mingw_mac.h:203:11 pub const __MSABI_LONG = @compileError("unable to translate macro: undefined identifier `l`"); // C:\Users\user\scoop\apps\zig-dev\current\lib\libc\include\any-windows-any/_mingw_mac.h:209:13 pub const __MINGW_ATTRIB_DEPRECATED_STR = @compileError("unable to translate C expr: unexpected token .Eof"); // C:\Users\user\scoop\apps\zig-dev\current\lib\libc\include\any-windows-any/_mingw_mac.h:247:11 pub const __MINGW_MS_PRINTF = @compileError("unable to translate macro: undefined identifier `__attribute__`"); // C:\Users\user\scoop\apps\zig-dev\current\lib\libc\include\any-windows-any/_mingw_mac.h:270:9 pub const __MINGW_MS_SCANF = @compileError("unable to translate macro: undefined identifier `__attribute__`"); // C:\Users\user\scoop\apps\zig-dev\current\lib\libc\include\any-windows-any/_mingw_mac.h:273:9 pub const __MINGW_GNU_PRINTF = @compileError("unable to translate macro: undefined identifier `__attribute__`"); // C:\Users\user\scoop\apps\zig-dev\current\lib\libc\include\any-windows-any/_mingw_mac.h:276:9 pub const __MINGW_GNU_SCANF = @compileError("unable to translate macro: undefined identifier `__attribute__`"); // C:\Users\user\scoop\apps\zig-dev\current\lib\libc\include\any-windows-any/_mingw_mac.h:279:9 pub const __mingw_ovr = @compileError("unable to translate macro: undefined identifier `__attribute__`"); // C:\Users\user\scoop\apps\zig-dev\current\lib\libc\include\any-windows-any/_mingw_mac.h:289:11 pub const __MINGW_CRT_NAME_CONCAT2 = @compileError("unable to translate macro: undefined identifier `_s`"); // C:\Users\user\scoop\apps\zig-dev\current\lib\libc\include\any-windows-any/_mingw_secapi.h:41:9 pub const __CRT_SECURE_CPP_OVERLOAD_STANDARD_NAMES_MEMORY_0_3_ = @compileError("unable to translate C expr: unexpected token .Identifier"); // C:\Users\user\scoop\apps\zig-dev\current\lib\libc\include\any-windows-any/_mingw_secapi.h:69:9 pub const __MINGW_IMPORT = @compileError("unable to translate macro: undefined identifier `__attribute__`"); // C:\Users\user\scoop\apps\zig-dev\current\lib\libc\include\any-windows-any\_mingw.h:51:12 pub const _CRTIMP = @compileError("unable to translate macro: undefined identifier `__attribute__`"); // C:\Users\user\scoop\apps\zig-dev\current\lib\libc\include\any-windows-any\_mingw.h:59:15 pub const _inline = @compileError("unable to translate macro: undefined identifier `__inline`"); // C:\Users\user\scoop\apps\zig-dev\current\lib\libc\include\any-windows-any\_mingw.h:81:9 pub const __CRT_INLINE = @compileError("unable to translate macro: undefined identifier `__attribute__`"); // C:\Users\user\scoop\apps\zig-dev\current\lib\libc\include\any-windows-any\_mingw.h:90:11 pub const __MINGW_INTRIN_INLINE = @compileError("unable to translate macro: undefined identifier `__inline__`"); // C:\Users\user\scoop\apps\zig-dev\current\lib\libc\include\any-windows-any\_mingw.h:97:9 pub const __UNUSED_PARAM = @compileError("unable to translate macro: undefined identifier `__attribute__`"); // C:\Users\user\scoop\apps\zig-dev\current\lib\libc\include\any-windows-any\_mingw.h:111:11 pub const __restrict_arr = @compileError("unable to translate macro: undefined identifier `__restrict`"); // C:\Users\user\scoop\apps\zig-dev\current\lib\libc\include\any-windows-any\_mingw.h:126:10 pub const __MINGW_ATTRIB_NORETURN = @compileError("unable to translate macro: undefined identifier `__attribute__`"); // C:\Users\user\scoop\apps\zig-dev\current\lib\libc\include\any-windows-any\_mingw.h:142:9 pub const __MINGW_ATTRIB_CONST = @compileError("unable to translate macro: undefined identifier `__attribute__`"); // C:\Users\user\scoop\apps\zig-dev\current\lib\libc\include\any-windows-any\_mingw.h:143:9 pub const __MINGW_ATTRIB_MALLOC = @compileError("unable to translate macro: undefined identifier `__attribute__`"); // C:\Users\user\scoop\apps\zig-dev\current\lib\libc\include\any-windows-any\_mingw.h:153:9 pub const __MINGW_ATTRIB_PURE = @compileError("unable to translate macro: undefined identifier `__attribute__`"); // C:\Users\user\scoop\apps\zig-dev\current\lib\libc\include\any-windows-any\_mingw.h:154:9 pub const __MINGW_ATTRIB_NONNULL = @compileError("unable to translate macro: undefined identifier `__attribute__`"); // C:\Users\user\scoop\apps\zig-dev\current\lib\libc\include\any-windows-any\_mingw.h:167:9 pub const __MINGW_ATTRIB_UNUSED = @compileError("unable to translate macro: undefined identifier `__attribute__`"); // C:\Users\user\scoop\apps\zig-dev\current\lib\libc\include\any-windows-any\_mingw.h:173:9 pub const __MINGW_ATTRIB_USED = @compileError("unable to translate macro: undefined identifier `__attribute__`"); // C:\Users\user\scoop\apps\zig-dev\current\lib\libc\include\any-windows-any\_mingw.h:179:9 pub const __MINGW_ATTRIB_DEPRECATED = @compileError("unable to translate macro: undefined identifier `__attribute__`"); // C:\Users\user\scoop\apps\zig-dev\current\lib\libc\include\any-windows-any\_mingw.h:180:9 pub const __MINGW_ATTRIB_DEPRECATED_MSG = @compileError("unable to translate macro: undefined identifier `__attribute__`"); // C:\Users\user\scoop\apps\zig-dev\current\lib\libc\include\any-windows-any\_mingw.h:182:9 pub const __MINGW_NOTHROW = @compileError("unable to translate macro: undefined identifier `__attribute__`"); // C:\Users\user\scoop\apps\zig-dev\current\lib\libc\include\any-windows-any\_mingw.h:197:9 pub const __MINGW_PRAGMA_PARAM = @compileError("unable to translate C expr: unexpected token .Eof"); // C:\Users\user\scoop\apps\zig-dev\current\lib\libc\include\any-windows-any\_mingw.h:215:9 pub const __MINGW_BROKEN_INTERFACE = @compileError("unable to translate macro: undefined identifier `message`"); // C:\Users\user\scoop\apps\zig-dev\current\lib\libc\include\any-windows-any\_mingw.h:218:9 pub const __forceinline = @compileError("unable to translate macro: undefined identifier `__inline__`"); // C:\Users\user\scoop\apps\zig-dev\current\lib\libc\include\any-windows-any\_mingw.h:267:9 pub const _crt_va_start = @compileError("unable to translate macro: undefined identifier `__builtin_va_start`"); // C:\Users\user\scoop\apps\zig-dev\current\lib\libc\include\any-windows-any\vadefs.h:48:9 pub const _crt_va_arg = @compileError("unable to translate macro: undefined identifier `__builtin_va_arg`"); // C:\Users\user\scoop\apps\zig-dev\current\lib\libc\include\any-windows-any\vadefs.h:49:9 pub const _crt_va_end = @compileError("unable to translate macro: undefined identifier `__builtin_va_end`"); // C:\Users\user\scoop\apps\zig-dev\current\lib\libc\include\any-windows-any\vadefs.h:50:9 pub const _crt_va_copy = @compileError("unable to translate macro: undefined identifier `__builtin_va_copy`"); // C:\Users\user\scoop\apps\zig-dev\current\lib\libc\include\any-windows-any\vadefs.h:51:9 pub const __CRT_STRINGIZE = @compileError("unable to translate C expr: unexpected token .Hash"); // C:\Users\user\scoop\apps\zig-dev\current\lib\libc\include\any-windows-any\_mingw.h:286:9 pub const __CRT_WIDE = @compileError("unable to translate macro: undefined identifier `L`"); // C:\Users\user\scoop\apps\zig-dev\current\lib\libc\include\any-windows-any\_mingw.h:291:9 pub const _CRT_DEPRECATE_TEXT = @compileError("unable to translate macro: undefined identifier `deprecated`"); // C:\Users\user\scoop\apps\zig-dev\current\lib\libc\include\any-windows-any\_mingw.h:350:9 pub const _CRT_INSECURE_DEPRECATE_MEMORY = @compileError("unable to translate C expr: unexpected token .Eof"); // C:\Users\user\scoop\apps\zig-dev\current\lib\libc\include\any-windows-any\_mingw.h:353:9 pub const _CRT_INSECURE_DEPRECATE_GLOBALS = @compileError("unable to translate C expr: unexpected token .Eof"); // C:\Users\user\scoop\apps\zig-dev\current\lib\libc\include\any-windows-any\_mingw.h:357:9 pub const _CRT_OBSOLETE = @compileError("unable to translate C expr: unexpected token .Eof"); // C:\Users\user\scoop\apps\zig-dev\current\lib\libc\include\any-windows-any\_mingw.h:365:9 pub const _CRT_ALIGN = @compileError("unable to translate macro: undefined identifier `__attribute__`"); // C:\Users\user\scoop\apps\zig-dev\current\lib\libc\include\any-windows-any\_mingw.h:392:9 pub const _CRT_glob = @compileError("unable to translate macro: undefined identifier `_dowildcard`"); // C:\Users\user\scoop\apps\zig-dev\current\lib\libc\include\any-windows-any\_mingw.h:456:9 pub const _UNION_NAME = @compileError("unable to translate C expr: unexpected token .Eof"); // C:\Users\user\scoop\apps\zig-dev\current\lib\libc\include\any-windows-any\_mingw.h:476:9 pub const _STRUCT_NAME = @compileError("unable to translate C expr: unexpected token .Eof"); // C:\Users\user\scoop\apps\zig-dev\current\lib\libc\include\any-windows-any\_mingw.h:477:9 pub const __CRT_UUID_DECL = @compileError("unable to translate C expr: unexpected token .Eof"); // C:\Users\user\scoop\apps\zig-dev\current\lib\libc\include\any-windows-any\_mingw.h:564:9 pub const __MINGW_DEBUGBREAK_IMPL = @compileError("unable to translate macro: undefined identifier `__has_builtin`"); // C:\Users\user\scoop\apps\zig-dev\current\lib\libc\include\any-windows-any\_mingw.h:575:9 pub const _CRT_SECURE_CPP_NOTHROW = @compileError("unable to translate macro: undefined identifier `throw`"); // C:\Users\user\scoop\apps\zig-dev\current\lib\libc\include\any-windows-any\corecrt.h:148:9 pub const __DEFINE_CPP_OVERLOAD_SECURE_FUNC_0_0 = @compileError("unable to translate C expr: unexpected token .Eof"); // C:\Users\user\scoop\apps\zig-dev\current\lib\libc\include\any-windows-any\corecrt.h:267:9 pub const __DEFINE_CPP_OVERLOAD_SECURE_FUNC_0_1 = @compileError("unable to translate C expr: unexpected token .Eof"); // C:\Users\user\scoop\apps\zig-dev\current\lib\libc\include\any-windows-any\corecrt.h:268:9 pub const __DEFINE_CPP_OVERLOAD_SECURE_FUNC_0_2 = @compileError("unable to translate C expr: unexpected token .Eof"); // C:\Users\user\scoop\apps\zig-dev\current\lib\libc\include\any-windows-any\corecrt.h:269:9 pub const __DEFINE_CPP_OVERLOAD_SECURE_FUNC_0_3 = @compileError("unable to translate C expr: unexpected token .Eof"); // C:\Users\user\scoop\apps\zig-dev\current\lib\libc\include\any-windows-any\corecrt.h:270:9 pub const __DEFINE_CPP_OVERLOAD_SECURE_FUNC_0_4 = @compileError("unable to translate C expr: unexpected token .Eof"); // C:\Users\user\scoop\apps\zig-dev\current\lib\libc\include\any-windows-any\corecrt.h:271:9 pub const __DEFINE_CPP_OVERLOAD_SECURE_FUNC_1_1 = @compileError("unable to translate C expr: unexpected token .Eof"); // C:\Users\user\scoop\apps\zig-dev\current\lib\libc\include\any-windows-any\corecrt.h:272:9 pub const __DEFINE_CPP_OVERLOAD_SECURE_FUNC_1_2 = @compileError("unable to translate C expr: unexpected token .Eof"); // C:\Users\user\scoop\apps\zig-dev\current\lib\libc\include\any-windows-any\corecrt.h:273:9 pub const __DEFINE_CPP_OVERLOAD_SECURE_FUNC_1_3 = @compileError("unable to translate C expr: unexpected token .Eof"); // C:\Users\user\scoop\apps\zig-dev\current\lib\libc\include\any-windows-any\corecrt.h:274:9 pub const __DEFINE_CPP_OVERLOAD_SECURE_FUNC_2_0 = @compileError("unable to translate C expr: unexpected token .Eof"); // C:\Users\user\scoop\apps\zig-dev\current\lib\libc\include\any-windows-any\corecrt.h:275:9 pub const __DEFINE_CPP_OVERLOAD_SECURE_FUNC_0_1_ARGLIST = @compileError("unable to translate C expr: unexpected token .Eof"); // C:\Users\user\scoop\apps\zig-dev\current\lib\libc\include\any-windows-any\corecrt.h:276:9 pub const __DEFINE_CPP_OVERLOAD_SECURE_FUNC_0_2_ARGLIST = @compileError("unable to translate C expr: unexpected token .Eof"); // C:\Users\user\scoop\apps\zig-dev\current\lib\libc\include\any-windows-any\corecrt.h:277:9 pub const __DEFINE_CPP_OVERLOAD_SECURE_FUNC_SPLITPATH = @compileError("unable to translate C expr: unexpected token .Eof"); // C:\Users\user\scoop\apps\zig-dev\current\lib\libc\include\any-windows-any\corecrt.h:278:9 pub const __DEFINE_CPP_OVERLOAD_STANDARD_FUNC_0_0 = @compileError("unable to translate macro: undefined identifier `__func_name`"); // C:\Users\user\scoop\apps\zig-dev\current\lib\libc\include\any-windows-any\corecrt.h:282:9 pub const __DEFINE_CPP_OVERLOAD_STANDARD_FUNC_0_1 = @compileError("unable to translate macro: undefined identifier `__func_name`"); // C:\Users\user\scoop\apps\zig-dev\current\lib\libc\include\any-windows-any\corecrt.h:284:9 pub const __DEFINE_CPP_OVERLOAD_STANDARD_FUNC_0_2 = @compileError("unable to translate macro: undefined identifier `__func_name`"); // C:\Users\user\scoop\apps\zig-dev\current\lib\libc\include\any-windows-any\corecrt.h:286:9 pub const __DEFINE_CPP_OVERLOAD_STANDARD_FUNC_0_3 = @compileError("unable to translate macro: undefined identifier `__func_name`"); // C:\Users\user\scoop\apps\zig-dev\current\lib\libc\include\any-windows-any\corecrt.h:288:9 pub const __DEFINE_CPP_OVERLOAD_STANDARD_FUNC_0_4 = @compileError("unable to translate macro: undefined identifier `__func_name`"); // C:\Users\user\scoop\apps\zig-dev\current\lib\libc\include\any-windows-any\corecrt.h:290:9 pub const __DEFINE_CPP_OVERLOAD_STANDARD_FUNC_0_0_EX = @compileError("unable to translate C expr: unexpected token .Eof"); // C:\Users\user\scoop\apps\zig-dev\current\lib\libc\include\any-windows-any\corecrt.h:427:9 pub const __DEFINE_CPP_OVERLOAD_STANDARD_FUNC_0_1_EX = @compileError("unable to translate C expr: unexpected token .Eof"); // C:\Users\user\scoop\apps\zig-dev\current\lib\libc\include\any-windows-any\corecrt.h:428:9 pub const __DEFINE_CPP_OVERLOAD_STANDARD_FUNC_0_2_EX = @compileError("unable to translate C expr: unexpected token .Eof"); // C:\Users\user\scoop\apps\zig-dev\current\lib\libc\include\any-windows-any\corecrt.h:429:9 pub const __DEFINE_CPP_OVERLOAD_STANDARD_FUNC_0_3_EX = @compileError("unable to translate C expr: unexpected token .Eof"); // C:\Users\user\scoop\apps\zig-dev\current\lib\libc\include\any-windows-any\corecrt.h:430:9 pub const __DEFINE_CPP_OVERLOAD_STANDARD_FUNC_0_4_EX = @compileError("unable to translate C expr: unexpected token .Eof"); // C:\Users\user\scoop\apps\zig-dev\current\lib\libc\include\any-windows-any\corecrt.h:431:9 pub const __crt_typefix = @compileError("unable to translate C expr: unexpected token .Eof"); // C:\Users\user\scoop\apps\zig-dev\current\lib\libc\include\any-windows-any\corecrt.h:491:9 pub const __mingw_types_compatible_p = @compileError("unable to translate macro: undefined identifier `__builtin_types_compatible_p`"); // C:\Users\user\scoop\apps\zig-dev\current\lib\libc\include\any-windows-any\math.h:97:9 pub const __mingw_choose_expr = @compileError("unable to translate macro: undefined identifier `__builtin_choose_expr`"); // C:\Users\user\scoop\apps\zig-dev\current\lib\libc\include\any-windows-any\math.h:105:9 pub const HUGE_VAL = @compileError("unable to translate macro: undefined identifier `__builtin_huge_val`"); // C:\Users\user\scoop\apps\zig-dev\current\lib\libc\include\any-windows-any\math.h:156:9 pub const HUGE_VALL = @compileError("unable to translate macro: undefined identifier `__builtin_huge_vall`"); // C:\Users\user\scoop\apps\zig-dev\current\lib\libc\include\any-windows-any\math.h:350:9 pub const fpclassify = @compileError("unable to translate macro: undefined identifier `__typeof__`"); // C:\Users\user\scoop\apps\zig-dev\current\lib\libc\include\any-windows-any\math.h:492:9 pub const isnan = @compileError("unable to translate macro: undefined identifier `__typeof__`"); // C:\Users\user\scoop\apps\zig-dev\current\lib\libc\include\any-windows-any\math.h:586:9 pub const signbit = @compileError("unable to translate macro: undefined identifier `__typeof__`"); // C:\Users\user\scoop\apps\zig-dev\current\lib\libc\include\any-windows-any\math.h:646:9 pub const isgreater = @compileError("unable to translate macro: undefined identifier `__builtin_isgreater`"); // C:\Users\user\scoop\apps\zig-dev\current\lib\libc\include\any-windows-any\math.h:1144:9 pub const isgreaterequal = @compileError("unable to translate macro: undefined identifier `__builtin_isgreaterequal`"); // C:\Users\user\scoop\apps\zig-dev\current\lib\libc\include\any-windows-any\math.h:1145:9 pub const isless = @compileError("unable to translate macro: undefined identifier `__builtin_isless`"); // C:\Users\user\scoop\apps\zig-dev\current\lib\libc\include\any-windows-any\math.h:1146:9 pub const islessequal = @compileError("unable to translate macro: undefined identifier `__builtin_islessequal`"); // C:\Users\user\scoop\apps\zig-dev\current\lib\libc\include\any-windows-any\math.h:1147:9 pub const islessgreater = @compileError("unable to translate macro: undefined identifier `__builtin_islessgreater`"); // C:\Users\user\scoop\apps\zig-dev\current\lib\libc\include\any-windows-any\math.h:1148:9 pub const isunordered = @compileError("unable to translate macro: undefined identifier `__builtin_isunordered`"); // C:\Users\user\scoop\apps\zig-dev\current\lib\libc\include\any-windows-any\math.h:1149:9 pub const __llvm__ = @as(c_int, 1); pub const __clang__ = @as(c_int, 1); pub const __clang_major__ = @as(c_int, 13); pub const __clang_minor__ = @as(c_int, 0); pub const __clang_patchlevel__ = @as(c_int, 0); pub const __clang_version__ = "13.0.0 (https://github.com/llvm/llvm-project d7b669b3a30345cfcdb2fde2af6f48aa4b94845d)"; pub const __GNUC__ = @as(c_int, 4); pub const __GNUC_MINOR__ = @as(c_int, 2); pub const __GNUC_PATCHLEVEL__ = @as(c_int, 1); pub const __GXX_ABI_VERSION = @as(c_int, 1002); pub const __ATOMIC_RELAXED = @as(c_int, 0); pub const __ATOMIC_CONSUME = @as(c_int, 1); pub const __ATOMIC_ACQUIRE = @as(c_int, 2); pub const __ATOMIC_RELEASE = @as(c_int, 3); pub const __ATOMIC_ACQ_REL = @as(c_int, 4); pub const __ATOMIC_SEQ_CST = @as(c_int, 5); pub const __OPENCL_MEMORY_SCOPE_WORK_ITEM = @as(c_int, 0); pub const __OPENCL_MEMORY_SCOPE_WORK_GROUP = @as(c_int, 1); pub const __OPENCL_MEMORY_SCOPE_DEVICE = @as(c_int, 2); pub const __OPENCL_MEMORY_SCOPE_ALL_SVM_DEVICES = @as(c_int, 3); pub const __OPENCL_MEMORY_SCOPE_SUB_GROUP = @as(c_int, 4); pub const __PRAGMA_REDEFINE_EXTNAME = @as(c_int, 1); pub const __VERSION__ = "Clang 13.0.0 (https://github.com/llvm/llvm-project d7b669b3a30345cfcdb2fde2af6f48aa4b94845d)"; pub const __OBJC_BOOL_IS_BOOL = @as(c_int, 0); pub const __CONSTANT_CFSTRINGS__ = @as(c_int, 1); pub const __SEH__ = @as(c_int, 1); pub const __clang_literal_encoding__ = "UTF-8"; pub const __clang_wide_literal_encoding__ = "UTF-16"; pub const __OPTIMIZE__ = @as(c_int, 1); pub const __ORDER_LITTLE_ENDIAN__ = @as(c_int, 1234); pub const __ORDER_BIG_ENDIAN__ = @as(c_int, 4321); pub const __ORDER_PDP_ENDIAN__ = @as(c_int, 3412); pub const __BYTE_ORDER__ = __ORDER_LITTLE_ENDIAN__; pub const __LITTLE_ENDIAN__ = @as(c_int, 1); pub const __CHAR_BIT__ = @as(c_int, 8); pub const __SCHAR_MAX__ = @as(c_int, 127); pub const __SHRT_MAX__ = @as(c_int, 32767); pub const __INT_MAX__ = @import("std").zig.c_translation.promoteIntLiteral(c_int, 2147483647, .decimal); pub const __LONG_MAX__ = @as(c_long, 2147483647); pub const __LONG_LONG_MAX__ = @as(c_longlong, 9223372036854775807); pub const __WCHAR_MAX__ = @import("std").zig.c_translation.promoteIntLiteral(c_int, 65535, .decimal); pub const __WINT_MAX__ = @import("std").zig.c_translation.promoteIntLiteral(c_int, 65535, .decimal); pub const __INTMAX_MAX__ = @as(c_longlong, 9223372036854775807); pub const __SIZE_MAX__ = @as(c_ulonglong, 18446744073709551615); pub const __UINTMAX_MAX__ = @as(c_ulonglong, 18446744073709551615); pub const __PTRDIFF_MAX__ = @as(c_longlong, 9223372036854775807); pub const __INTPTR_MAX__ = @as(c_longlong, 9223372036854775807); pub const __UINTPTR_MAX__ = @as(c_ulonglong, 18446744073709551615); pub const __SIZEOF_DOUBLE__ = @as(c_int, 8); pub const __SIZEOF_FLOAT__ = @as(c_int, 4); pub const __SIZEOF_INT__ = @as(c_int, 4); pub const __SIZEOF_LONG__ = @as(c_int, 4); pub const __SIZEOF_LONG_DOUBLE__ = @as(c_int, 16); pub const __SIZEOF_LONG_LONG__ = @as(c_int, 8); pub const __SIZEOF_POINTER__ = @as(c_int, 8); pub const __SIZEOF_SHORT__ = @as(c_int, 2); pub const __SIZEOF_PTRDIFF_T__ = @as(c_int, 8); pub const __SIZEOF_SIZE_T__ = @as(c_int, 8); pub const __SIZEOF_WCHAR_T__ = @as(c_int, 2); pub const __SIZEOF_WINT_T__ = @as(c_int, 2); pub const __SIZEOF_INT128__ = @as(c_int, 16); pub const __INTMAX_TYPE__ = c_longlong; pub const __INTMAX_FMTd__ = "lld"; pub const __INTMAX_FMTi__ = "lli"; pub const __UINTMAX_TYPE__ = c_ulonglong; pub const __UINTMAX_FMTo__ = "llo"; pub const __UINTMAX_FMTu__ = "llu"; pub const __UINTMAX_FMTx__ = "llx"; pub const __UINTMAX_FMTX__ = "llX"; pub const __INTMAX_WIDTH__ = @as(c_int, 64); pub const __PTRDIFF_TYPE__ = c_longlong; pub const __PTRDIFF_FMTd__ = "lld"; pub const __PTRDIFF_FMTi__ = "lli"; pub const __PTRDIFF_WIDTH__ = @as(c_int, 64); pub const __INTPTR_TYPE__ = c_longlong; pub const __INTPTR_FMTd__ = "lld"; pub const __INTPTR_FMTi__ = "lli"; pub const __INTPTR_WIDTH__ = @as(c_int, 64); pub const __SIZE_TYPE__ = c_ulonglong; pub const __SIZE_FMTo__ = "llo"; pub const __SIZE_FMTu__ = "llu"; pub const __SIZE_FMTx__ = "llx"; pub const __SIZE_FMTX__ = "llX"; pub const __SIZE_WIDTH__ = @as(c_int, 64); pub const __WCHAR_TYPE__ = c_ushort; pub const __WCHAR_WIDTH__ = @as(c_int, 16); pub const __WINT_TYPE__ = c_ushort; pub const __WINT_WIDTH__ = @as(c_int, 16); pub const __SIG_ATOMIC_WIDTH__ = @as(c_int, 32); pub const __SIG_ATOMIC_MAX__ = @import("std").zig.c_translation.promoteIntLiteral(c_int, 2147483647, .decimal); pub const __CHAR16_TYPE__ = c_ushort; pub const __CHAR32_TYPE__ = c_uint; pub const __UINTMAX_WIDTH__ = @as(c_int, 64); pub const __UINTPTR_TYPE__ = c_ulonglong; pub const __UINTPTR_FMTo__ = "llo"; pub const __UINTPTR_FMTu__ = "llu"; pub const __UINTPTR_FMTx__ = "llx"; pub const __UINTPTR_FMTX__ = "llX"; pub const __UINTPTR_WIDTH__ = @as(c_int, 64); pub const __FLT_DENORM_MIN__ = @as(f32, 1.40129846e-45); pub const __FLT_HAS_DENORM__ = @as(c_int, 1); pub const __FLT_DIG__ = @as(c_int, 6); pub const __FLT_DECIMAL_DIG__ = @as(c_int, 9); pub const __FLT_EPSILON__ = @as(f32, 1.19209290e-7); pub const __FLT_HAS_INFINITY__ = @as(c_int, 1); pub const __FLT_HAS_QUIET_NAN__ = @as(c_int, 1); pub const __FLT_MANT_DIG__ = @as(c_int, 24); pub const __FLT_MAX_10_EXP__ = @as(c_int, 38); pub const __FLT_MAX_EXP__ = @as(c_int, 128); pub const __FLT_MAX__ = @as(f32, 3.40282347e+38); pub const __FLT_MIN_10_EXP__ = -@as(c_int, 37); pub const __FLT_MIN_EXP__ = -@as(c_int, 125); pub const __FLT_MIN__ = @as(f32, 1.17549435e-38); pub const __DBL_DENORM_MIN__ = 4.9406564584124654e-324; pub const __DBL_HAS_DENORM__ = @as(c_int, 1); pub const __DBL_DIG__ = @as(c_int, 15); pub const __DBL_DECIMAL_DIG__ = @as(c_int, 17); pub const __DBL_EPSILON__ = 2.2204460492503131e-16; pub const __DBL_HAS_INFINITY__ = @as(c_int, 1); pub const __DBL_HAS_QUIET_NAN__ = @as(c_int, 1); pub const __DBL_MANT_DIG__ = @as(c_int, 53); pub const __DBL_MAX_10_EXP__ = @as(c_int, 308); pub const __DBL_MAX_EXP__ = @as(c_int, 1024); pub const __DBL_MAX__ = 1.7976931348623157e+308; pub const __DBL_MIN_10_EXP__ = -@as(c_int, 307); pub const __DBL_MIN_EXP__ = -@as(c_int, 1021); pub const __DBL_MIN__ = 2.2250738585072014e-308; pub const __LDBL_DENORM_MIN__ = @as(c_longdouble, 3.64519953188247460253e-4951); pub const __LDBL_HAS_DENORM__ = @as(c_int, 1); pub const __LDBL_DIG__ = @as(c_int, 18); pub const __LDBL_DECIMAL_DIG__ = @as(c_int, 21); pub const __LDBL_EPSILON__ = @as(c_longdouble, 1.08420217248550443401e-19); pub const __LDBL_HAS_INFINITY__ = @as(c_int, 1); pub const __LDBL_HAS_QUIET_NAN__ = @as(c_int, 1); pub const __LDBL_MANT_DIG__ = @as(c_int, 64); pub const __LDBL_MAX_10_EXP__ = @as(c_int, 4932); pub const __LDBL_MAX_EXP__ = @as(c_int, 16384); pub const __LDBL_MAX__ = @as(c_longdouble, 1.18973149535723176502e+4932); pub const __LDBL_MIN_10_EXP__ = -@as(c_int, 4931); pub const __LDBL_MIN_EXP__ = -@as(c_int, 16381); pub const __LDBL_MIN__ = @as(c_longdouble, 3.36210314311209350626e-4932); pub const __POINTER_WIDTH__ = @as(c_int, 64); pub const __BIGGEST_ALIGNMENT__ = @as(c_int, 16); pub const __WCHAR_UNSIGNED__ = @as(c_int, 1); pub const __WINT_UNSIGNED__ = @as(c_int, 1); pub const __INT8_TYPE__ = i8; pub const __INT8_FMTd__ = "hhd"; pub const __INT8_FMTi__ = "hhi"; pub const __INT8_C_SUFFIX__ = ""; pub const __INT16_TYPE__ = c_short; pub const __INT16_FMTd__ = "hd"; pub const __INT16_FMTi__ = "hi"; pub const __INT16_C_SUFFIX__ = ""; pub const __INT32_TYPE__ = c_int; pub const __INT32_FMTd__ = "d"; pub const __INT32_FMTi__ = "i"; pub const __INT32_C_SUFFIX__ = ""; pub const __INT64_TYPE__ = c_longlong; pub const __INT64_FMTd__ = "lld"; pub const __INT64_FMTi__ = "lli"; pub const __UINT8_TYPE__ = u8; pub const __UINT8_FMTo__ = "hho"; pub const __UINT8_FMTu__ = "hhu"; pub const __UINT8_FMTx__ = "hhx"; pub const __UINT8_FMTX__ = "hhX"; pub const __UINT8_C_SUFFIX__ = ""; pub const __UINT8_MAX__ = @as(c_int, 255); pub const __INT8_MAX__ = @as(c_int, 127); pub const __UINT16_TYPE__ = c_ushort; pub const __UINT16_FMTo__ = "ho"; pub const __UINT16_FMTu__ = "hu"; pub const __UINT16_FMTx__ = "hx"; pub const __UINT16_FMTX__ = "hX"; pub const __UINT16_C_SUFFIX__ = ""; pub const __UINT16_MAX__ = @import("std").zig.c_translation.promoteIntLiteral(c_int, 65535, .decimal); pub const __INT16_MAX__ = @as(c_int, 32767); pub const __UINT32_TYPE__ = c_uint; pub const __UINT32_FMTo__ = "o"; pub const __UINT32_FMTu__ = "u"; pub const __UINT32_FMTx__ = "x"; pub const __UINT32_FMTX__ = "X"; pub const __UINT32_MAX__ = @import("std").zig.c_translation.promoteIntLiteral(c_uint, 4294967295, .decimal); pub const __INT32_MAX__ = @import("std").zig.c_translation.promoteIntLiteral(c_int, 2147483647, .decimal); pub const __UINT64_TYPE__ = c_ulonglong; pub const __UINT64_FMTo__ = "llo"; pub const __UINT64_FMTu__ = "llu"; pub const __UINT64_FMTx__ = "llx"; pub const __UINT64_FMTX__ = "llX"; pub const __UINT64_MAX__ = @as(c_ulonglong, 18446744073709551615); pub const __INT64_MAX__ = @as(c_longlong, 9223372036854775807); pub const __INT_LEAST8_TYPE__ = i8; pub const __INT_LEAST8_MAX__ = @as(c_int, 127); pub const __INT_LEAST8_FMTd__ = "hhd"; pub const __INT_LEAST8_FMTi__ = "hhi"; pub const __UINT_LEAST8_TYPE__ = u8; pub const __UINT_LEAST8_MAX__ = @as(c_int, 255); pub const __UINT_LEAST8_FMTo__ = "hho"; pub const __UINT_LEAST8_FMTu__ = "hhu"; pub const __UINT_LEAST8_FMTx__ = "hhx"; pub const __UINT_LEAST8_FMTX__ = "hhX"; pub const __INT_LEAST16_TYPE__ = c_short; pub const __INT_LEAST16_MAX__ = @as(c_int, 32767); pub const __INT_LEAST16_FMTd__ = "hd"; pub const __INT_LEAST16_FMTi__ = "hi"; pub const __UINT_LEAST16_TYPE__ = c_ushort; pub const __UINT_LEAST16_MAX__ = @import("std").zig.c_translation.promoteIntLiteral(c_int, 65535, .decimal); pub const __UINT_LEAST16_FMTo__ = "ho"; pub const __UINT_LEAST16_FMTu__ = "hu"; pub const __UINT_LEAST16_FMTx__ = "hx"; pub const __UINT_LEAST16_FMTX__ = "hX"; pub const __INT_LEAST32_TYPE__ = c_int; pub const __INT_LEAST32_MAX__ = @import("std").zig.c_translation.promoteIntLiteral(c_int, 2147483647, .decimal); pub const __INT_LEAST32_FMTd__ = "d"; pub const __INT_LEAST32_FMTi__ = "i"; pub const __UINT_LEAST32_TYPE__ = c_uint; pub const __UINT_LEAST32_MAX__ = @import("std").zig.c_translation.promoteIntLiteral(c_uint, 4294967295, .decimal); pub const __UINT_LEAST32_FMTo__ = "o"; pub const __UINT_LEAST32_FMTu__ = "u"; pub const __UINT_LEAST32_FMTx__ = "x"; pub const __UINT_LEAST32_FMTX__ = "X"; pub const __INT_LEAST64_TYPE__ = c_longlong; pub const __INT_LEAST64_MAX__ = @as(c_longlong, 9223372036854775807); pub const __INT_LEAST64_FMTd__ = "lld"; pub const __INT_LEAST64_FMTi__ = "lli"; pub const __UINT_LEAST64_TYPE__ = c_ulonglong; pub const __UINT_LEAST64_MAX__ = @as(c_ulonglong, 18446744073709551615); pub const __UINT_LEAST64_FMTo__ = "llo"; pub const __UINT_LEAST64_FMTu__ = "llu"; pub const __UINT_LEAST64_FMTx__ = "llx"; pub const __UINT_LEAST64_FMTX__ = "llX"; pub const __INT_FAST8_TYPE__ = i8; pub const __INT_FAST8_MAX__ = @as(c_int, 127); pub const __INT_FAST8_FMTd__ = "hhd"; pub const __INT_FAST8_FMTi__ = "hhi"; pub const __UINT_FAST8_TYPE__ = u8; pub const __UINT_FAST8_MAX__ = @as(c_int, 255); pub const __UINT_FAST8_FMTo__ = "hho"; pub const __UINT_FAST8_FMTu__ = "hhu"; pub const __UINT_FAST8_FMTx__ = "hhx"; pub const __UINT_FAST8_FMTX__ = "hhX"; pub const __INT_FAST16_TYPE__ = c_short; pub const __INT_FAST16_MAX__ = @as(c_int, 32767); pub const __INT_FAST16_FMTd__ = "hd"; pub const __INT_FAST16_FMTi__ = "hi"; pub const __UINT_FAST16_TYPE__ = c_ushort; pub const __UINT_FAST16_MAX__ = @import("std").zig.c_translation.promoteIntLiteral(c_int, 65535, .decimal); pub const __UINT_FAST16_FMTo__ = "ho"; pub const __UINT_FAST16_FMTu__ = "hu"; pub const __UINT_FAST16_FMTx__ = "hx"; pub const __UINT_FAST16_FMTX__ = "hX"; pub const __INT_FAST32_TYPE__ = c_int; pub const __INT_FAST32_MAX__ = @import("std").zig.c_translation.promoteIntLiteral(c_int, 2147483647, .decimal); pub const __INT_FAST32_FMTd__ = "d"; pub const __INT_FAST32_FMTi__ = "i"; pub const __UINT_FAST32_TYPE__ = c_uint; pub const __UINT_FAST32_MAX__ = @import("std").zig.c_translation.promoteIntLiteral(c_uint, 4294967295, .decimal); pub const __UINT_FAST32_FMTo__ = "o"; pub const __UINT_FAST32_FMTu__ = "u"; pub const __UINT_FAST32_FMTx__ = "x"; pub const __UINT_FAST32_FMTX__ = "X"; pub const __INT_FAST64_TYPE__ = c_longlong; pub const __INT_FAST64_MAX__ = @as(c_longlong, 9223372036854775807); pub const __INT_FAST64_FMTd__ = "lld"; pub const __INT_FAST64_FMTi__ = "lli"; pub const __UINT_FAST64_TYPE__ = c_ulonglong; pub const __UINT_FAST64_MAX__ = @as(c_ulonglong, 18446744073709551615); pub const __UINT_FAST64_FMTo__ = "llo"; pub const __UINT_FAST64_FMTu__ = "llu"; pub const __UINT_FAST64_FMTx__ = "llx"; pub const __UINT_FAST64_FMTX__ = "llX"; pub const __USER_LABEL_PREFIX__ = ""; pub const __FINITE_MATH_ONLY__ = @as(c_int, 0); pub const __GNUC_STDC_INLINE__ = @as(c_int, 1); pub const __GCC_ATOMIC_TEST_AND_SET_TRUEVAL = @as(c_int, 1); pub const __CLANG_ATOMIC_BOOL_LOCK_FREE = @as(c_int, 2); pub const __CLANG_ATOMIC_CHAR_LOCK_FREE = @as(c_int, 2); pub const __CLANG_ATOMIC_CHAR16_T_LOCK_FREE = @as(c_int, 2); pub const __CLANG_ATOMIC_CHAR32_T_LOCK_FREE = @as(c_int, 2); pub const __CLANG_ATOMIC_WCHAR_T_LOCK_FREE = @as(c_int, 2); pub const __CLANG_ATOMIC_SHORT_LOCK_FREE = @as(c_int, 2); pub const __CLANG_ATOMIC_INT_LOCK_FREE = @as(c_int, 2); pub const __CLANG_ATOMIC_LONG_LOCK_FREE = @as(c_int, 2); pub const __CLANG_ATOMIC_LLONG_LOCK_FREE = @as(c_int, 2); pub const __CLANG_ATOMIC_POINTER_LOCK_FREE = @as(c_int, 2); pub const __GCC_ATOMIC_BOOL_LOCK_FREE = @as(c_int, 2); pub const __GCC_ATOMIC_CHAR_LOCK_FREE = @as(c_int, 2); pub const __GCC_ATOMIC_CHAR16_T_LOCK_FREE = @as(c_int, 2); pub const __GCC_ATOMIC_CHAR32_T_LOCK_FREE = @as(c_int, 2); pub const __GCC_ATOMIC_WCHAR_T_LOCK_FREE = @as(c_int, 2); pub const __GCC_ATOMIC_SHORT_LOCK_FREE = @as(c_int, 2); pub const __GCC_ATOMIC_INT_LOCK_FREE = @as(c_int, 2); pub const __GCC_ATOMIC_LONG_LOCK_FREE = @as(c_int, 2); pub const __GCC_ATOMIC_LLONG_LOCK_FREE = @as(c_int, 2); pub const __GCC_ATOMIC_POINTER_LOCK_FREE = @as(c_int, 2); pub const __PIC__ = @as(c_int, 2); pub const __pic__ = @as(c_int, 2); pub const __FLT_EVAL_METHOD__ = @as(c_int, 0); pub const __FLT_RADIX__ = @as(c_int, 2); pub const __DECIMAL_DIG__ = __LDBL_DECIMAL_DIG__; pub const __SSP_STRONG__ = @as(c_int, 2); pub const __GCC_ASM_FLAG_OUTPUTS__ = @as(c_int, 1); pub const __code_model_small__ = @as(c_int, 1); pub const __amd64__ = @as(c_int, 1); pub const __amd64 = @as(c_int, 1); pub const __x86_64 = @as(c_int, 1); pub const __x86_64__ = @as(c_int, 1); pub const __SEG_GS = @as(c_int, 1); pub const __SEG_FS = @as(c_int, 1); pub const __corei7 = @as(c_int, 1); pub const __corei7__ = @as(c_int, 1); pub const __tune_corei7__ = @as(c_int, 1); pub const __REGISTER_PREFIX__ = ""; pub const __NO_MATH_INLINES = @as(c_int, 1); pub const __AES__ = @as(c_int, 1); pub const __PCLMUL__ = @as(c_int, 1); pub const __LAHF_SAHF__ = @as(c_int, 1); pub const __LZCNT__ = @as(c_int, 1); pub const __RDRND__ = @as(c_int, 1); pub const __FSGSBASE__ = @as(c_int, 1); pub const __BMI__ = @as(c_int, 1); pub const __BMI2__ = @as(c_int, 1); pub const __POPCNT__ = @as(c_int, 1); pub const __PRFCHW__ = @as(c_int, 1); pub const __RDSEED__ = @as(c_int, 1); pub const __ADX__ = @as(c_int, 1); pub const __MOVBE__ = @as(c_int, 1); pub const __FMA__ = @as(c_int, 1); pub const __F16C__ = @as(c_int, 1); pub const __FXSR__ = @as(c_int, 1); pub const __XSAVE__ = @as(c_int, 1); pub const __XSAVEOPT__ = @as(c_int, 1); pub const __INVPCID__ = @as(c_int, 1); pub const __AVX2__ = @as(c_int, 1); pub const __AVX__ = @as(c_int, 1); pub const __SSE4_2__ = @as(c_int, 1); pub const __SSE4_1__ = @as(c_int, 1); pub const __SSSE3__ = @as(c_int, 1); pub const __SSE3__ = @as(c_int, 1); pub const __SSE2__ = @as(c_int, 1); pub const __SSE2_MATH__ = @as(c_int, 1); pub const __SSE__ = @as(c_int, 1); pub const __SSE_MATH__ = @as(c_int, 1); pub const __MMX__ = @as(c_int, 1); pub const __GCC_HAVE_SYNC_COMPARE_AND_SWAP_1 = @as(c_int, 1); pub const __GCC_HAVE_SYNC_COMPARE_AND_SWAP_2 = @as(c_int, 1); pub const __GCC_HAVE_SYNC_COMPARE_AND_SWAP_4 = @as(c_int, 1); pub const __GCC_HAVE_SYNC_COMPARE_AND_SWAP_8 = @as(c_int, 1); pub const __GCC_HAVE_SYNC_COMPARE_AND_SWAP_16 = @as(c_int, 1); pub const __SIZEOF_FLOAT128__ = @as(c_int, 16); pub const _WIN32 = @as(c_int, 1); pub const _WIN64 = @as(c_int, 1); pub const WIN32 = @as(c_int, 1); pub const __WIN32 = @as(c_int, 1); pub const __WIN32__ = @as(c_int, 1); pub const WINNT = @as(c_int, 1); pub const __WINNT = @as(c_int, 1); pub const __WINNT__ = @as(c_int, 1); pub const WIN64 = @as(c_int, 1); pub const __WIN64 = @as(c_int, 1); pub const __WIN64__ = @as(c_int, 1); pub const __MINGW64__ = @as(c_int, 1); pub const __MSVCRT__ = @as(c_int, 1); pub const __MINGW32__ = @as(c_int, 1); pub const __STDC__ = @as(c_int, 1); pub const __STDC_HOSTED__ = @as(c_int, 1); pub const __STDC_VERSION__ = @as(c_long, 201710); pub const __STDC_UTF_16__ = @as(c_int, 1); pub const __STDC_UTF_32__ = @as(c_int, 1); pub const _DEBUG = @as(c_int, 1); pub const RAYLIB_H = ""; pub const __STDARG_H = ""; pub const _VA_LIST = ""; pub const __GNUC_VA_LIST = @as(c_int, 1); pub const RAYLIB_VERSION = "3.8-dev"; pub const RLAPI = ""; pub const PI = @as(f32, 3.14159265358979323846); pub const DEG2RAD = PI / @as(f32, 180.0); pub const RAD2DEG = @as(f32, 180.0) / PI; pub inline fn CLITERAL(@"type": anytype) @TypeOf(@"type") { return @"type"; } pub const LIGHTGRAY = @import("std").mem.zeroInit(CLITERAL(Color), .{ @as(c_int, 200), @as(c_int, 200), @as(c_int, 200), @as(c_int, 255) }); pub const GRAY = @import("std").mem.zeroInit(CLITERAL(Color), .{ @as(c_int, 130), @as(c_int, 130), @as(c_int, 130), @as(c_int, 255) }); pub const DARKGRAY = @import("std").mem.zeroInit(CLITERAL(Color), .{ @as(c_int, 80), @as(c_int, 80), @as(c_int, 80), @as(c_int, 255) }); pub const YELLOW = @import("std").mem.zeroInit(CLITERAL(Color), .{ @as(c_int, 253), @as(c_int, 249), @as(c_int, 0), @as(c_int, 255) }); pub const GOLD = @import("std").mem.zeroInit(CLITERAL(Color), .{ @as(c_int, 255), @as(c_int, 203), @as(c_int, 0), @as(c_int, 255) }); pub const ORANGE = @import("std").mem.zeroInit(CLITERAL(Color), .{ @as(c_int, 255), @as(c_int, 161), @as(c_int, 0), @as(c_int, 255) }); pub const PINK = @import("std").mem.zeroInit(CLITERAL(Color), .{ @as(c_int, 255), @as(c_int, 109), @as(c_int, 194), @as(c_int, 255) }); pub const RED = @import("std").mem.zeroInit(CLITERAL(Color), .{ @as(c_int, 230), @as(c_int, 41), @as(c_int, 55), @as(c_int, 255) }); pub const MAROON = @import("std").mem.zeroInit(CLITERAL(Color), .{ @as(c_int, 190), @as(c_int, 33), @as(c_int, 55), @as(c_int, 255) }); pub const GREEN = @import("std").mem.zeroInit(CLITERAL(Color), .{ @as(c_int, 0), @as(c_int, 228), @as(c_int, 48), @as(c_int, 255) }); pub const LIME = @import("std").mem.zeroInit(CLITERAL(Color), .{ @as(c_int, 0), @as(c_int, 158), @as(c_int, 47), @as(c_int, 255) }); pub const DARKGREEN = @import("std").mem.zeroInit(CLITERAL(Color), .{ @as(c_int, 0), @as(c_int, 117), @as(c_int, 44), @as(c_int, 255) }); pub const SKYBLUE = @import("std").mem.zeroInit(CLITERAL(Color), .{ @as(c_int, 102), @as(c_int, 191), @as(c_int, 255), @as(c_int, 255) }); pub const BLUE = @import("std").mem.zeroInit(CLITERAL(Color), .{ @as(c_int, 0), @as(c_int, 121), @as(c_int, 241), @as(c_int, 255) }); pub const DARKBLUE = @import("std").mem.zeroInit(CLITERAL(Color), .{ @as(c_int, 0), @as(c_int, 82), @as(c_int, 172), @as(c_int, 255) }); pub const PURPLE = @import("std").mem.zeroInit(CLITERAL(Color), .{ @as(c_int, 200), @as(c_int, 122), @as(c_int, 255), @as(c_int, 255) }); pub const VIOLET = @import("std").mem.zeroInit(CLITERAL(Color), .{ @as(c_int, 135), @as(c_int, 60), @as(c_int, 190), @as(c_int, 255) }); pub const DARKPURPLE = @import("std").mem.zeroInit(CLITERAL(Color), .{ @as(c_int, 112), @as(c_int, 31), @as(c_int, 126), @as(c_int, 255) }); pub const BEIGE = @import("std").mem.zeroInit(CLITERAL(Color), .{ @as(c_int, 211), @as(c_int, 176), @as(c_int, 131), @as(c_int, 255) }); pub const BROWN = @import("std").mem.zeroInit(CLITERAL(Color), .{ @as(c_int, 127), @as(c_int, 106), @as(c_int, 79), @as(c_int, 255) }); pub const DARKBROWN = @import("std").mem.zeroInit(CLITERAL(Color), .{ @as(c_int, 76), @as(c_int, 63), @as(c_int, 47), @as(c_int, 255) }); pub const WHITE = @import("std").mem.zeroInit(CLITERAL(Color), .{ @as(c_int, 255), @as(c_int, 255), @as(c_int, 255), @as(c_int, 255) }); pub const BLACK = @import("std").mem.zeroInit(CLITERAL(Color), .{ @as(c_int, 0), @as(c_int, 0), @as(c_int, 0), @as(c_int, 255) }); pub const BLANK = @import("std").mem.zeroInit(CLITERAL(Color), .{ @as(c_int, 0), @as(c_int, 0), @as(c_int, 0), @as(c_int, 0) }); pub const MAGENTA = @import("std").mem.zeroInit(CLITERAL(Color), .{ @as(c_int, 255), @as(c_int, 0), @as(c_int, 255), @as(c_int, 255) }); pub const RAYWHITE = @import("std").mem.zeroInit(CLITERAL(Color), .{ @as(c_int, 245), @as(c_int, 245), @as(c_int, 245), @as(c_int, 255) }); pub const GetImageData = LoadImageColors; pub const FILTER_POINT = TEXTURE_FILTER_POINT; pub const FILTER_BILINEAR = TEXTURE_FILTER_BILINEAR; pub const MAP_DIFFUSE = MATERIAL_MAP_DIFFUSE; pub const UNCOMPRESSED_R8G8B8A8 = PIXELFORMAT_UNCOMPRESSED_R8G8B8A8; pub const __STDBOOL_H = ""; pub const @"bool" = bool; pub const @"true" = @as(c_int, 1); pub const @"false" = @as(c_int, 0); pub const __bool_true_false_are_defined = @as(c_int, 1); pub const MOUSE_LEFT_BUTTON = MOUSE_BUTTON_LEFT; pub const MOUSE_RIGHT_BUTTON = MOUSE_BUTTON_RIGHT; pub const MOUSE_MIDDLE_BUTTON = MOUSE_BUTTON_MIDDLE; pub const MATERIAL_MAP_DIFFUSE = MATERIAL_MAP_ALBEDO; pub const MATERIAL_MAP_SPECULAR = MATERIAL_MAP_METALNESS; pub const SHADER_LOC_MAP_DIFFUSE = SHADER_LOC_MAP_ALBEDO; pub const SHADER_LOC_MAP_SPECULAR = SHADER_LOC_MAP_METALNESS; pub const RAYMATH_H = ""; pub inline fn MatrixToFloat(mat: anytype) @TypeOf(MatrixToFloatV(mat).v) { return MatrixToFloatV(mat).v; } pub inline fn Vector3ToFloat(vec: anytype) @TypeOf(Vector3ToFloatV(vec).v) { return Vector3ToFloatV(vec).v; } pub const _MATH_H_ = ""; pub const _INC_CRTDEFS = ""; pub const _INC_CORECRT = ""; pub const _INC__MINGW_H = ""; pub const _INC_CRTDEFS_MACRO = ""; pub inline fn __MINGW64_STRINGIFY(x: anytype) @TypeOf(__STRINGIFY(x)) { return __STRINGIFY(x); } pub const __MINGW64_VERSION_MAJOR = @as(c_int, 9); pub const __MINGW64_VERSION_MINOR = @as(c_int, 0); pub const __MINGW64_VERSION_BUGFIX = @as(c_int, 0); pub const __MINGW64_VERSION_RC = @as(c_int, 0); pub const __MINGW64_VERSION_STATE = "alpha"; pub const __MINGW32_MAJOR_VERSION = @as(c_int, 3); pub const __MINGW32_MINOR_VERSION = @as(c_int, 11); pub const _M_AMD64 = @as(c_int, 100); pub const _M_X64 = @as(c_int, 100); pub const @"_" = @as(c_int, 1); pub const __MINGW_USE_UNDERSCORE_PREFIX = @as(c_int, 0); pub inline fn __MINGW_USYMBOL(sym: anytype) @TypeOf(sym) { return sym; } pub const __C89_NAMELESS = __MINGW_EXTENSION; pub const __C89_NAMELESSSTRUCTNAME = ""; pub const __C89_NAMELESSSTRUCTNAME1 = ""; pub const __C89_NAMELESSSTRUCTNAME2 = ""; pub const __C89_NAMELESSSTRUCTNAME3 = ""; pub const __C89_NAMELESSSTRUCTNAME4 = ""; pub const __C89_NAMELESSSTRUCTNAME5 = ""; pub const __C89_NAMELESSUNIONNAME = ""; pub const __C89_NAMELESSUNIONNAME1 = ""; pub const __C89_NAMELESSUNIONNAME2 = ""; pub const __C89_NAMELESSUNIONNAME3 = ""; pub const __C89_NAMELESSUNIONNAME4 = ""; pub const __C89_NAMELESSUNIONNAME5 = ""; pub const __C89_NAMELESSUNIONNAME6 = ""; pub const __C89_NAMELESSUNIONNAME7 = ""; pub const __C89_NAMELESSUNIONNAME8 = ""; pub const __GNU_EXTENSION = __MINGW_EXTENSION; pub const __MINGW_HAVE_ANSI_C99_PRINTF = @as(c_int, 1); pub const __MINGW_HAVE_WIDE_C99_PRINTF = @as(c_int, 1); pub const __MINGW_HAVE_ANSI_C99_SCANF = @as(c_int, 1); pub const __MINGW_HAVE_WIDE_C99_SCANF = @as(c_int, 1); pub const __MINGW_GCC_VERSION = ((__GNUC__ * @as(c_int, 10000)) + (__GNUC_MINOR__ * @as(c_int, 100))) + __GNUC_PATCHLEVEL__; pub inline fn __MINGW_GNUC_PREREQ(major: anytype, minor: anytype) @TypeOf((__GNUC__ > major) or ((__GNUC__ == major) and (__GNUC_MINOR__ >= minor))) { return (__GNUC__ > major) or ((__GNUC__ == major) and (__GNUC_MINOR__ >= minor)); } pub inline fn __MINGW_MSC_PREREQ(major: anytype, minor: anytype) @TypeOf(@as(c_int, 0)) { _ = major; _ = minor; return @as(c_int, 0); } pub const __MINGW_SEC_WARN_STR = "This function or variable may be unsafe, use _CRT_SECURE_NO_WARNINGS to disable deprecation"; pub const __MINGW_MSVC2005_DEPREC_STR = "This POSIX function is deprecated beginning in Visual C++ 2005, use _CRT_NONSTDC_NO_DEPRECATE to disable deprecation"; pub const __MINGW_ATTRIB_DEPRECATED_MSVC2005 = __MINGW_ATTRIB_DEPRECATED_STR(__MINGW_MSVC2005_DEPREC_STR); pub const __MINGW_ATTRIB_DEPRECATED_SEC_WARN = __MINGW_ATTRIB_DEPRECATED_STR(__MINGW_SEC_WARN_STR); pub const __mingw_static_ovr = __mingw_ovr; pub const __mingw_attribute_artificial = ""; pub const __MINGW_FORTIFY_LEVEL = @as(c_int, 0); pub const __mingw_bos_ovr = __mingw_ovr; pub const __MINGW_FORTIFY_VA_ARG = @as(c_int, 0); pub const _INC_MINGW_SECAPI = ""; pub const _CRT_SECURE_CPP_OVERLOAD_SECURE_NAMES = @as(c_int, 0); pub const _CRT_SECURE_CPP_OVERLOAD_SECURE_NAMES_MEMORY = @as(c_int, 0); pub const _CRT_SECURE_CPP_OVERLOAD_STANDARD_NAMES = @as(c_int, 0); pub const _CRT_SECURE_CPP_OVERLOAD_STANDARD_NAMES_COUNT = @as(c_int, 0); pub const _CRT_SECURE_CPP_OVERLOAD_STANDARD_NAMES_MEMORY = @as(c_int, 0); pub const __LONG32 = c_long; pub const __USE_CRTIMP = @as(c_int, 1); pub const __DECLSPEC_SUPPORTED = ""; pub const USE___UUIDOF = @as(c_int, 0); pub const __MINGW_ATTRIB_NO_OPTIMIZE = ""; pub const __MSVCRT_VERSION__ = @as(c_int, 0x700); pub const _WIN32_WINNT = @as(c_int, 0x0603); pub const _INT128_DEFINED = ""; pub const __int8 = u8; pub const __int16 = c_short; pub const __int32 = c_int; pub const __int64 = c_longlong; pub const __ptr32 = ""; pub const __ptr64 = ""; pub const __unaligned = ""; pub const __w64 = ""; pub const __nothrow = ""; pub const _INC_VADEFS = ""; pub const MINGW_SDK_INIT = ""; pub const MINGW_HAS_SECURE_API = @as(c_int, 1); pub const __STDC_SECURE_LIB__ = @as(c_long, 200411); pub const __GOT_SECURE_LIB__ = __STDC_SECURE_LIB__; pub const MINGW_DDK_H = ""; pub const MINGW_HAS_DDK_H = @as(c_int, 1); pub const _CRT_PACKING = @as(c_int, 8); pub const _VA_LIST_DEFINED = ""; pub inline fn _ADDRESSOF(v: anytype) @TypeOf(&v) { return &v; } pub inline fn _CRT_STRINGIZE(_Value: anytype) @TypeOf(__CRT_STRINGIZE(_Value)) { return __CRT_STRINGIZE(_Value); } pub inline fn _CRT_WIDE(_String: anytype) @TypeOf(__CRT_WIDE(_String)) { return __CRT_WIDE(_String); } pub const _W64 = ""; pub const _CRTIMP_NOIA64 = _CRTIMP; pub const _CRTIMP2 = _CRTIMP; pub const _CRTIMP_ALTERNATIVE = _CRTIMP; pub const _CRT_ALTERNATIVE_IMPORTED = ""; pub const _MRTIMP2 = _CRTIMP; pub const _DLL = ""; pub const _MT = ""; pub const _MCRTIMP = _CRTIMP; pub const _CRTIMP_PURE = _CRTIMP; pub const _PGLOBAL = ""; pub const _AGLOBAL = ""; pub const _SECURECRT_FILL_BUFFER_PATTERN = @as(c_int, 0xFD); pub const _CRT_MANAGED_HEAP_DEPRECATE = ""; pub const _CONST_RETURN = ""; pub const UNALIGNED = __unaligned; pub const __CRTDECL = __cdecl; pub const _ARGMAX = @as(c_int, 100); pub const _TRUNCATE = @import("std").zig.c_translation.cast(usize, -@as(c_int, 1)); pub inline fn _CRT_UNUSED(x: anytype) c_void { return @import("std").zig.c_translation.cast(c_void, x); } pub const __USE_MINGW_ANSI_STDIO = @as(c_int, 1); pub const __ANONYMOUS_DEFINED = ""; pub const _ANONYMOUS_UNION = __MINGW_EXTENSION; pub const _ANONYMOUS_STRUCT = __MINGW_EXTENSION; pub const DUMMYUNIONNAME = ""; pub const DUMMYUNIONNAME1 = ""; pub const DUMMYUNIONNAME2 = ""; pub const DUMMYUNIONNAME3 = ""; pub const DUMMYUNIONNAME4 = ""; pub const DUMMYUNIONNAME5 = ""; pub const DUMMYUNIONNAME6 = ""; pub const DUMMYUNIONNAME7 = ""; pub const DUMMYUNIONNAME8 = ""; pub const DUMMYUNIONNAME9 = ""; pub const DUMMYSTRUCTNAME = ""; pub const DUMMYSTRUCTNAME1 = ""; pub const DUMMYSTRUCTNAME2 = ""; pub const DUMMYSTRUCTNAME3 = ""; pub const DUMMYSTRUCTNAME4 = ""; pub const DUMMYSTRUCTNAME5 = ""; pub const _CRTNOALIAS = ""; pub const _CRTRESTRICT = ""; pub const _SIZE_T_DEFINED = ""; pub const _SSIZE_T_DEFINED = ""; pub const _RSIZE_T_DEFINED = ""; pub const _INTPTR_T_DEFINED = ""; pub const __intptr_t_defined = ""; pub const _UINTPTR_T_DEFINED = ""; pub const __uintptr_t_defined = ""; pub const _PTRDIFF_T_DEFINED = ""; pub const _PTRDIFF_T_ = ""; pub const _WCHAR_T_DEFINED = ""; pub const _WCTYPE_T_DEFINED = ""; pub const _WINT_T = ""; pub const _ERRCODE_DEFINED = ""; pub const _TIME32_T_DEFINED = ""; pub const _TIME64_T_DEFINED = ""; pub const _TIME_T_DEFINED = ""; pub const _TAGLC_ID_DEFINED = ""; pub const _THREADLOCALEINFO = ""; pub const _CRT_USE_WINAPI_FAMILY_DESKTOP_APP = ""; pub const _DOMAIN = @as(c_int, 1); pub const _SING = @as(c_int, 2); pub const _OVERFLOW = @as(c_int, 3); pub const _UNDERFLOW = @as(c_int, 4); pub const _TLOSS = @as(c_int, 5); pub const _PLOSS = @as(c_int, 6); pub const DOMAIN = _DOMAIN; pub const SING = _SING; pub const OVERFLOW = _OVERFLOW; pub const UNDERFLOW = _UNDERFLOW; pub const TLOSS = _TLOSS; pub const PLOSS = _PLOSS; pub const M_E = 2.7182818284590452354; pub const M_LOG2E = 1.4426950408889634074; pub const M_LOG10E = 0.43429448190325182765; pub const M_LN2 = 0.69314718055994530942; pub const M_LN10 = 2.30258509299404568402; pub const M_PI = 3.14159265358979323846; pub const M_PI_2 = 1.57079632679489661923; pub const M_PI_4 = 0.78539816339744830962; pub const M_1_PI = 0.31830988618379067154; pub const M_2_PI = 0.63661977236758134308; pub const M_2_SQRTPI = 1.12837916709551257390; pub const M_SQRT2 = 1.41421356237309504880; pub const M_SQRT1_2 = 0.70710678118654752440; pub const __MINGW_FPCLASS_DEFINED = @as(c_int, 1); pub const _FPCLASS_SNAN = @as(c_int, 0x0001); pub const _FPCLASS_QNAN = @as(c_int, 0x0002); pub const _FPCLASS_NINF = @as(c_int, 0x0004); pub const _FPCLASS_NN = @as(c_int, 0x0008); pub const _FPCLASS_ND = @as(c_int, 0x0010); pub const _FPCLASS_NZ = @as(c_int, 0x0020); pub const _FPCLASS_PZ = @as(c_int, 0x0040); pub const _FPCLASS_PD = @as(c_int, 0x0080); pub const _FPCLASS_PN = @as(c_int, 0x0100); pub const _FPCLASS_PINF = @as(c_int, 0x0200); pub const __MINGW_SOFTMATH = ""; pub const _HUGE = __MINGW_IMP_SYMBOL(_HUGE).*; pub const _EXCEPTION_DEFINED = ""; pub const _CRT_ABS_DEFINED = ""; pub const _CRT_ATOF_DEFINED = ""; pub const EDOM = @as(c_int, 33); pub const ERANGE = @as(c_int, 34); pub const _COMPLEX_DEFINED = ""; pub const _CRT_MATHERR_DEFINED = ""; pub const _SIGN_DEFINED = ""; pub const FP_SNAN = _FPCLASS_SNAN; pub const FP_QNAN = _FPCLASS_QNAN; pub const FP_NINF = _FPCLASS_NINF; pub const FP_PINF = _FPCLASS_PINF; pub const FP_NDENORM = _FPCLASS_ND; pub const FP_PDENORM = _FPCLASS_PD; pub const FP_NZERO = _FPCLASS_NZ; pub const FP_PZERO = _FPCLASS_PZ; pub const FP_NNORM = _FPCLASS_NN; pub const FP_PNORM = _FPCLASS_PN; pub const HUGE_VALF = __builtin_huge_valf(); pub const INFINITY = __builtin_inff(); pub const NAN = __builtin_nanf(""); pub const FP_NAN = @as(c_int, 0x0100); pub const FP_NORMAL = @as(c_int, 0x0400); pub const FP_INFINITE = FP_NAN | FP_NORMAL; pub const FP_ZERO = @as(c_int, 0x4000); pub const FP_SUBNORMAL = FP_NORMAL | FP_ZERO; pub inline fn __dfp_expansion(__call: anytype, __fin: anytype, x: anytype) @TypeOf(__fin) { _ = __call; _ = x; return __fin; } pub inline fn isfinite(x: anytype) @TypeOf((fpclassify(x) & FP_NAN) == @as(c_int, 0)) { return (fpclassify(x) & FP_NAN) == @as(c_int, 0); } pub inline fn isinf(x: anytype) @TypeOf(fpclassify(x) == FP_INFINITE) { return fpclassify(x) == FP_INFINITE; } pub inline fn isnormal(x: anytype) @TypeOf(fpclassify(x) == FP_NORMAL) { return fpclassify(x) == FP_NORMAL; } pub const FP_ILOGB0 = @import("std").zig.c_translation.cast(c_int, @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x80000000, .hexadecimal)); pub const FP_ILOGBNAN = @import("std").zig.c_translation.cast(c_int, @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x7fffffff, .hexadecimal)); pub inline fn _nan() @TypeOf(nan("")) { return nan(""); } pub inline fn _nanf() @TypeOf(nanf("")) { return nanf(""); } pub inline fn _nanl() @TypeOf(nanl("")) { return nanl(""); } pub const _copysignl = copysignl; pub const _hypotl = hypotl; pub const matherr = _matherr; pub const HUGE = _HUGE; pub const tagLC_ID = struct_tagLC_ID; pub const lconv = struct_lconv; pub const __lc_time_data = struct___lc_time_data; pub const threadlocaleinfostruct = struct_threadlocaleinfostruct; pub const threadmbcinfostruct = struct_threadmbcinfostruct; pub const localeinfo_struct = struct_localeinfo_struct; pub const _exception = struct__exception; pub const _complex = struct__complex;
src/translate-c/raylib_all.zig