code
stringlengths 38
801k
| repo_path
stringlengths 6
263
|
|---|---|
const std = @import("std");
const tvg = @import("tvg");
const c = @cImport({
@cInclude("tinyvg.h");
});
fn renderSvg(data: []const u8, stream: CWriter) !void {
var temp_mem = std.heap.ArenaAllocator.init(std.heap.page_allocator);
defer temp_mem.deinit();
try tvg.svg.renderBinary(temp_mem.allocator(), data, stream);
}
fn renderBitmap(data: []const u8, src_anti_alias: c.tinyvg_AntiAlias, width: u32, height: u32, bitmap: *c.tinyvg_Bitmap) !void {
var temp_mem = std.heap.ArenaAllocator.init(std.heap.page_allocator);
defer temp_mem.deinit();
var size_hint: tvg.rendering.SizeHint = if (width == 0 and height == 0)
.inherit
else if (width == 0)
tvg.rendering.SizeHint{ .height = height }
else if (height == 0)
tvg.rendering.SizeHint{ .width = width }
else
tvg.rendering.SizeHint{ .size = .{ .width = width, .height = height } };
var anti_alias = @intToEnum(tvg.rendering.AntiAliasing, src_anti_alias);
var image = try tvg.rendering.renderBuffer(
temp_mem.allocator(),
std.heap.page_allocator,
size_hint,
anti_alias,
data,
);
errdefer image.deinit(std.heap.page_allocator);
const pixel_data = std.mem.sliceAsBytes(image.pixels);
std.debug.assert(pixel_data.len == 4 * @as(usize, image.width) * @as(usize, image.height));
bitmap.* = .{
.width = image.width,
.height = image.height,
.pixels = pixel_data.ptr,
};
}
export fn tinyvg_render_svg(
tvg_data_ptr: [*]const u8,
tvg_length: usize,
target: [*c]const c.tinyvg_OutStream,
) c.tinyvg_Error {
renderSvg(
tvg_data_ptr[0..tvg_length],
CWriter{ .context = target },
) catch |err| return errToC(err);
return c.TINYVG_SUCCESS;
}
export fn tinyvg_render_bitmap(
tvg_data_ptr: [*]const u8,
tvg_length: usize,
anti_alias: c.tinyvg_AntiAlias,
width: u32,
height: u32,
bitmap: [*c]c.tinyvg_Bitmap,
) c.tinyvg_Error {
renderBitmap(
tvg_data_ptr[0..tvg_length],
if (anti_alias < 1) 1 else anti_alias,
width,
height,
bitmap,
) catch |err| return errToC(err);
return c.TINYVG_SUCCESS;
}
export fn tinyvg_free_bitmap(bitmap: *c.tinyvg_Bitmap) void {
std.heap.page_allocator.free(bitmap.pixels[0 .. 4 * @as(usize, bitmap.width) * @as(usize, bitmap.height)]);
bitmap.* = undefined;
}
const CError = error{
OutOfMemory,
IoError,
EndOfStream,
InvalidData,
UnsupportedColorFormat,
UnsupportedVersion,
Unsupported,
};
fn errToZig(err: c.tinyvg_Error) CError!void {
switch (err) {
c.TINYVG_SUCCESS => {},
c.TINYVG_ERR_OUT_OF_MEMORY => return error.OutOfMemory,
c.TINYVG_ERR_IO => return error.IoError,
c.TINYVG_ERR_INVALID_DATA => return error.InvalidData,
c.TINYVG_ERR_UNSUPPORTED => return error.Unsupported,
else => @panic("invalid error code!"),
}
}
fn errToC(err: CError) c.tinyvg_Error {
return switch (err) {
error.OutOfMemory => c.TINYVG_ERR_OUT_OF_MEMORY,
error.IoError => c.TINYVG_ERR_IO,
error.EndOfStream => c.TINYVG_ERR_IO,
error.InvalidData => c.TINYVG_ERR_INVALID_DATA,
error.UnsupportedColorFormat => c.TINYVG_ERR_UNSUPPORTED,
error.UnsupportedVersion => c.TINYVG_ERR_UNSUPPORTED,
error.Unsupported => c.TINYVG_ERR_UNSUPPORTED,
};
}
const CWriter = std.io.Writer(*const c.tinyvg_OutStream, CError, writeCStream);
fn writeCStream(stream: *const c.tinyvg_OutStream, data: []const u8) CError!usize {
var written: usize = 0;
try errToZig(stream.write.?(stream.context, data.ptr, data.len, &written));
return written;
}
|
src/binding/binding.zig
|
const std = @import("../std.zig");
const mem = std.mem;
const endian = std.endian;
const assert = std.debug.assert;
const testing = std.testing;
const builtin = @import("builtin");
const maxInt = std.math.maxInt;
const QuarterRound = struct {
a: usize,
b: usize,
c: usize,
d: usize,
};
fn Rp(a: usize, b: usize, c: usize, d: usize) QuarterRound {
return QuarterRound{
.a = a,
.b = b,
.c = c,
.d = d,
};
}
// The chacha family of ciphers are based on the salsa family.
fn salsa20_wordtobyte(out: []u8, input: [16]u32) void {
assert(out.len >= 64);
var x: [16]u32 = undefined;
for (x) |_, i|
x[i] = input[i];
const rounds = comptime [_]QuarterRound{
Rp(0, 4, 8, 12),
Rp(1, 5, 9, 13),
Rp(2, 6, 10, 14),
Rp(3, 7, 11, 15),
Rp(0, 5, 10, 15),
Rp(1, 6, 11, 12),
Rp(2, 7, 8, 13),
Rp(3, 4, 9, 14),
};
comptime var j: usize = 0;
inline while (j < 20) : (j += 2) {
// two-round cycles
inline for (rounds) |r| {
x[r.a] +%= x[r.b];
x[r.d] = std.math.rotl(u32, x[r.d] ^ x[r.a], @as(u32, 16));
x[r.c] +%= x[r.d];
x[r.b] = std.math.rotl(u32, x[r.b] ^ x[r.c], @as(u32, 12));
x[r.a] +%= x[r.b];
x[r.d] = std.math.rotl(u32, x[r.d] ^ x[r.a], @as(u32, 8));
x[r.c] +%= x[r.d];
x[r.b] = std.math.rotl(u32, x[r.b] ^ x[r.c], @as(u32, 7));
}
}
for (x) |_, i| {
// TODO https://github.com/ziglang/zig/issues/863
mem.writeIntSliceLittle(u32, out[4 * i .. 4 * i + 4], x[i] +% input[i]);
}
}
fn chaCha20_internal(out: []u8, in: []const u8, key: [8]u32, counter: [4]u32) void {
var ctx: [16]u32 = undefined;
var remaining: usize = if (in.len > out.len) in.len else out.len;
var cursor: usize = 0;
const c = "expand 32-byte k";
const constant_le = [_]u32{
mem.readIntSliceLittle(u32, c[0..4]),
mem.readIntSliceLittle(u32, c[4..8]),
mem.readIntSliceLittle(u32, c[8..12]),
mem.readIntSliceLittle(u32, c[12..16]),
};
mem.copy(u32, ctx[0..], constant_le[0..4]);
mem.copy(u32, ctx[4..12], key[0..8]);
mem.copy(u32, ctx[12..16], counter[0..4]);
while (true) {
var buf: [64]u8 = undefined;
salsa20_wordtobyte(buf[0..], ctx);
if (remaining < 64) {
var i: usize = 0;
while (i < remaining) : (i += 1)
out[cursor + i] = in[cursor + i] ^ buf[i];
return;
}
var i: usize = 0;
while (i < 64) : (i += 1)
out[cursor + i] = in[cursor + i] ^ buf[i];
cursor += 64;
remaining -= 64;
ctx[12] += 1;
}
}
/// ChaCha20 avoids the possibility of timing attacks, as there are no branches
/// on secret key data.
///
/// in and out should be the same length.
/// counter should generally be 0 or 1
///
/// ChaCha20 is self-reversing. To decrypt just run the cipher with the same
/// counter, nonce, and key.
pub fn chaCha20IETF(out: []u8, in: []const u8, counter: u32, key: [32]u8, nonce: [12]u8) void {
assert(in.len >= out.len);
assert((in.len >> 6) + counter <= maxInt(u32));
var k: [8]u32 = undefined;
var c: [4]u32 = undefined;
k[0] = mem.readIntSliceLittle(u32, key[0..4]);
k[1] = mem.readIntSliceLittle(u32, key[4..8]);
k[2] = mem.readIntSliceLittle(u32, key[8..12]);
k[3] = mem.readIntSliceLittle(u32, key[12..16]);
k[4] = mem.readIntSliceLittle(u32, key[16..20]);
k[5] = mem.readIntSliceLittle(u32, key[20..24]);
k[6] = mem.readIntSliceLittle(u32, key[24..28]);
k[7] = mem.readIntSliceLittle(u32, key[28..32]);
c[0] = counter;
c[1] = mem.readIntSliceLittle(u32, nonce[0..4]);
c[2] = mem.readIntSliceLittle(u32, nonce[4..8]);
c[3] = mem.readIntSliceLittle(u32, nonce[8..12]);
chaCha20_internal(out, in, k, c);
}
/// This is the original ChaCha20 before RFC 7539, which recommends using the
/// orgininal version on applications such as disk or file encryption that might
/// exceed the 256 GiB limit of the 96-bit nonce version.
pub fn chaCha20With64BitNonce(out: []u8, in: []const u8, counter: u64, key: [32]u8, nonce: [8]u8) void {
assert(in.len >= out.len);
assert(counter +% (in.len >> 6) >= counter);
var cursor: usize = 0;
var k: [8]u32 = undefined;
var c: [4]u32 = undefined;
k[0] = mem.readIntSliceLittle(u32, key[0..4]);
k[1] = mem.readIntSliceLittle(u32, key[4..8]);
k[2] = mem.readIntSliceLittle(u32, key[8..12]);
k[3] = mem.readIntSliceLittle(u32, key[12..16]);
k[4] = mem.readIntSliceLittle(u32, key[16..20]);
k[5] = mem.readIntSliceLittle(u32, key[20..24]);
k[6] = mem.readIntSliceLittle(u32, key[24..28]);
k[7] = mem.readIntSliceLittle(u32, key[28..32]);
c[0] = @truncate(u32, counter);
c[1] = @truncate(u32, counter >> 32);
c[2] = mem.readIntSliceLittle(u32, nonce[0..4]);
c[3] = mem.readIntSliceLittle(u32, nonce[4..8]);
const block_size = (1 << 6);
// The full block size is greater than the address space on a 32bit machine
const big_block = if (@sizeOf(usize) > 4) (block_size << 32) else maxInt(usize);
// first partial big block
if (((@intCast(u64, maxInt(u32) - @truncate(u32, counter)) + 1) << 6) < in.len) {
chaCha20_internal(out[cursor..big_block], in[cursor..big_block], k, c);
cursor = big_block - cursor;
c[1] += 1;
if (comptime @sizeOf(usize) > 4) {
// A big block is giant: 256 GiB, but we can avoid this limitation
var remaining_blocks: u32 = @intCast(u32, (in.len / big_block));
var i: u32 = 0;
while (remaining_blocks > 0) : (remaining_blocks -= 1) {
chaCha20_internal(out[cursor .. cursor + big_block], in[cursor .. cursor + big_block], k, c);
c[1] += 1; // upper 32-bit of counter, generic chaCha20_internal() doesn't know about this.
cursor += big_block;
}
}
}
chaCha20_internal(out[cursor..], in[cursor..], k, c);
}
// https://tools.ietf.org/html/rfc7539#section-2.4.2
test "crypto.chacha20 test vector sunscreen" {
const expected_result = [_]u8{
0x6e, 0x2e, 0x35, 0x9a, 0x25, 0x68, 0xf9, 0x80,
0x41, 0xba, 0x07, 0x28, 0xdd, 0x0d, 0x69, 0x81,
0xe9, 0x7e, 0x7a, 0xec, 0x1d, 0x43, 0x60, 0xc2,
0x0a, 0x27, 0xaf, 0xcc, 0xfd, 0x9f, 0xae, 0x0b,
0xf9, 0x1b, 0x65, 0xc5, 0x52, 0x47, 0x33, 0xab,
0x8f, 0x59, 0x3d, 0xab, 0xcd, 0x62, 0xb3, 0x57,
0x16, 0x39, 0xd6, 0x24, 0xe6, 0x51, 0x52, 0xab,
0x8f, 0x53, 0x0c, 0x35, 0x9f, 0x08, 0x61, 0xd8,
0x07, 0xca, 0x0d, 0xbf, 0x50, 0x0d, 0x6a, 0x61,
0x56, 0xa3, 0x8e, 0x08, 0x8a, 0x22, 0xb6, 0x5e,
0x52, 0xbc, 0x51, 0x4d, 0x16, 0xcc, 0xf8, 0x06,
0x81, 0x8c, 0xe9, 0x1a, 0xb7, 0x79, 0x37, 0x36,
0x5a, 0xf9, 0x0b, 0xbf, 0x74, 0xa3, 0x5b, 0xe6,
0xb4, 0x0b, 0x8e, 0xed, 0xf2, 0x78, 0x5e, 0x42,
0x87, 0x4d,
};
const input = "Ladies and Gentlemen of the class of '99: If I could offer you only one tip for the future, sunscreen would be it.";
var result: [114]u8 = undefined;
const key = [_]u8{
0, 1, 2, 3, 4, 5, 6, 7,
8, 9, 10, 11, 12, 13, 14, 15,
16, 17, 18, 19, 20, 21, 22, 23,
24, 25, 26, 27, 28, 29, 30, 31,
};
const nonce = [_]u8{
0, 0, 0, 0,
0, 0, 0, 0x4a,
0, 0, 0, 0,
};
chaCha20IETF(result[0..], input[0..], 1, key, nonce);
testing.expectEqualSlices(u8, expected_result, result);
// Chacha20 is self-reversing.
var plaintext: [114]u8 = undefined;
chaCha20IETF(plaintext[0..], result[0..], 1, key, nonce);
testing.expect(mem.compare(u8, input, plaintext) == mem.Compare.Equal);
}
// https://tools.ietf.org/html/draft-agl-tls-chacha20poly1305-04#section-7
test "crypto.chacha20 test vector 1" {
const expected_result = [_]u8{
0x76, 0xb8, 0xe0, 0xad, 0xa0, 0xf1, 0x3d, 0x90,
0x40, 0x5d, 0x6a, 0xe5, 0x53, 0x86, 0xbd, 0x28,
0xbd, 0xd2, 0x19, 0xb8, 0xa0, 0x8d, 0xed, 0x1a,
0xa8, 0x36, 0xef, 0xcc, 0x8b, 0x77, 0x0d, 0xc7,
0xda, 0x41, 0x59, 0x7c, 0x51, 0x57, 0x48, 0x8d,
0x77, 0x24, 0xe0, 0x3f, 0xb8, 0xd8, 0x4a, 0x37,
0x6a, 0x43, 0xb8, 0xf4, 0x15, 0x18, 0xa1, 0x1c,
0xc3, 0x87, 0xb6, 0x69, 0xb2, 0xee, 0x65, 0x86,
};
const input = [_]u8{
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
};
var result: [64]u8 = undefined;
const key = [_]u8{
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
};
const nonce = [_]u8{ 0, 0, 0, 0, 0, 0, 0, 0 };
chaCha20With64BitNonce(result[0..], input[0..], 0, key, nonce);
testing.expectEqualSlices(u8, expected_result, result);
}
test "crypto.chacha20 test vector 2" {
const expected_result = [_]u8{
0x45, 0x40, 0xf0, 0x5a, 0x9f, 0x1f, 0xb2, 0x96,
0xd7, 0x73, 0x6e, 0x7b, 0x20, 0x8e, 0x3c, 0x96,
0xeb, 0x4f, 0xe1, 0x83, 0x46, 0x88, 0xd2, 0x60,
0x4f, 0x45, 0x09, 0x52, 0xed, 0x43, 0x2d, 0x41,
0xbb, 0xe2, 0xa0, 0xb6, 0xea, 0x75, 0x66, 0xd2,
0xa5, 0xd1, 0xe7, 0xe2, 0x0d, 0x42, 0xaf, 0x2c,
0x53, 0xd7, 0x92, 0xb1, 0xc4, 0x3f, 0xea, 0x81,
0x7e, 0x9a, 0xd2, 0x75, 0xae, 0x54, 0x69, 0x63,
};
const input = [_]u8{
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
};
var result: [64]u8 = undefined;
const key = [_]u8{
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 1,
};
const nonce = [_]u8{ 0, 0, 0, 0, 0, 0, 0, 0 };
chaCha20With64BitNonce(result[0..], input[0..], 0, key, nonce);
testing.expectEqualSlices(u8, expected_result, result);
}
test "crypto.chacha20 test vector 3" {
const expected_result = [_]u8{
0xde, 0x9c, 0xba, 0x7b, 0xf3, 0xd6, 0x9e, 0xf5,
0xe7, 0x86, 0xdc, 0x63, 0x97, 0x3f, 0x65, 0x3a,
0x0b, 0x49, 0xe0, 0x15, 0xad, 0xbf, 0xf7, 0x13,
0x4f, 0xcb, 0x7d, 0xf1, 0x37, 0x82, 0x10, 0x31,
0xe8, 0x5a, 0x05, 0x02, 0x78, 0xa7, 0x08, 0x45,
0x27, 0x21, 0x4f, 0x73, 0xef, 0xc7, 0xfa, 0x5b,
0x52, 0x77, 0x06, 0x2e, 0xb7, 0xa0, 0x43, 0x3e,
0x44, 0x5f, 0x41, 0xe3,
};
const input = [_]u8{
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00,
};
var result: [60]u8 = undefined;
const key = [_]u8{
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
};
const nonce = [_]u8{ 0, 0, 0, 0, 0, 0, 0, 1 };
chaCha20With64BitNonce(result[0..], input[0..], 0, key, nonce);
testing.expectEqualSlices(u8, expected_result, result);
}
test "crypto.chacha20 test vector 4" {
const expected_result = [_]u8{
0xef, 0x3f, 0xdf, 0xd6, 0xc6, 0x15, 0x78, 0xfb,
0xf5, 0xcf, 0x35, 0xbd, 0x3d, 0xd3, 0x3b, 0x80,
0x09, 0x63, 0x16, 0x34, 0xd2, 0x1e, 0x42, 0xac,
0x33, 0x96, 0x0b, 0xd1, 0x38, 0xe5, 0x0d, 0x32,
0x11, 0x1e, 0x4c, 0xaf, 0x23, 0x7e, 0xe5, 0x3c,
0xa8, 0xad, 0x64, 0x26, 0x19, 0x4a, 0x88, 0x54,
0x5d, 0xdc, 0x49, 0x7a, 0x0b, 0x46, 0x6e, 0x7d,
0x6b, 0xbd, 0xb0, 0x04, 0x1b, 0x2f, 0x58, 0x6b,
};
const input = [_]u8{
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
};
var result: [64]u8 = undefined;
const key = [_]u8{
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
};
const nonce = [_]u8{ 1, 0, 0, 0, 0, 0, 0, 0 };
chaCha20With64BitNonce(result[0..], input[0..], 0, key, nonce);
testing.expectEqualSlices(u8, expected_result, result);
}
test "crypto.chacha20 test vector 5" {
const expected_result = [_]u8{
0xf7, 0x98, 0xa1, 0x89, 0xf1, 0x95, 0xe6, 0x69,
0x82, 0x10, 0x5f, 0xfb, 0x64, 0x0b, 0xb7, 0x75,
0x7f, 0x57, 0x9d, 0xa3, 0x16, 0x02, 0xfc, 0x93,
0xec, 0x01, 0xac, 0x56, 0xf8, 0x5a, 0xc3, 0xc1,
0x34, 0xa4, 0x54, 0x7b, 0x73, 0x3b, 0x46, 0x41,
0x30, 0x42, 0xc9, 0x44, 0x00, 0x49, 0x17, 0x69,
0x05, 0xd3, 0xbe, 0x59, 0xea, 0x1c, 0x53, 0xf1,
0x59, 0x16, 0x15, 0x5c, 0x2b, 0xe8, 0x24, 0x1a,
0x38, 0x00, 0x8b, 0x9a, 0x26, 0xbc, 0x35, 0x94,
0x1e, 0x24, 0x44, 0x17, 0x7c, 0x8a, 0xde, 0x66,
0x89, 0xde, 0x95, 0x26, 0x49, 0x86, 0xd9, 0x58,
0x89, 0xfb, 0x60, 0xe8, 0x46, 0x29, 0xc9, 0xbd,
0x9a, 0x5a, 0xcb, 0x1c, 0xc1, 0x18, 0xbe, 0x56,
0x3e, 0xb9, 0xb3, 0xa4, 0xa4, 0x72, 0xf8, 0x2e,
0x09, 0xa7, 0xe7, 0x78, 0x49, 0x2b, 0x56, 0x2e,
0xf7, 0x13, 0x0e, 0x88, 0xdf, 0xe0, 0x31, 0xc7,
0x9d, 0xb9, 0xd4, 0xf7, 0xc7, 0xa8, 0x99, 0x15,
0x1b, 0x9a, 0x47, 0x50, 0x32, 0xb6, 0x3f, 0xc3,
0x85, 0x24, 0x5f, 0xe0, 0x54, 0xe3, 0xdd, 0x5a,
0x97, 0xa5, 0xf5, 0x76, 0xfe, 0x06, 0x40, 0x25,
0xd3, 0xce, 0x04, 0x2c, 0x56, 0x6a, 0xb2, 0xc5,
0x07, 0xb1, 0x38, 0xdb, 0x85, 0x3e, 0x3d, 0x69,
0x59, 0x66, 0x09, 0x96, 0x54, 0x6c, 0xc9, 0xc4,
0xa6, 0xea, 0xfd, 0xc7, 0x77, 0xc0, 0x40, 0xd7,
0x0e, 0xaf, 0x46, 0xf7, 0x6d, 0xad, 0x39, 0x79,
0xe5, 0xc5, 0x36, 0x0c, 0x33, 0x17, 0x16, 0x6a,
0x1c, 0x89, 0x4c, 0x94, 0xa3, 0x71, 0x87, 0x6a,
0x94, 0xdf, 0x76, 0x28, 0xfe, 0x4e, 0xaa, 0xf2,
0xcc, 0xb2, 0x7d, 0x5a, 0xaa, 0xe0, 0xad, 0x7a,
0xd0, 0xf9, 0xd4, 0xb6, 0xad, 0x3b, 0x54, 0x09,
0x87, 0x46, 0xd4, 0x52, 0x4d, 0x38, 0x40, 0x7a,
0x6d, 0xeb, 0x3a, 0xb7, 0x8f, 0xab, 0x78, 0xc9,
};
const input = [_]u8{
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
};
var result: [256]u8 = undefined;
const key = [_]u8{
0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f,
0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17,
0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f,
};
const nonce = [_]u8{
0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
};
chaCha20With64BitNonce(result[0..], input[0..], 0, key, nonce);
testing.expectEqualSlices(u8, expected_result, result);
}
|
lib/std/crypto/chacha20.zig
|
/// Hash functions.
pub const hash = struct {
pub const Md5 = @import("crypto/md5.zig").Md5;
pub const Sha1 = @import("crypto/sha1.zig").Sha1;
pub const sha2 = @import("crypto/sha2.zig");
pub const sha3 = @import("crypto/sha3.zig");
pub const blake2 = @import("crypto/blake2.zig");
pub const Blake3 = @import("crypto/blake3.zig").Blake3;
pub const Gimli = @import("crypto/gimli.zig").Hash;
};
/// Authentication (MAC) functions.
pub const auth = struct {
pub const hmac = @import("crypto/hmac.zig");
pub const siphash = @import("crypto/siphash.zig");
};
/// Authenticated Encryption with Associated Data
pub const aead = struct {
const chacha20 = @import("crypto/chacha20.zig");
pub const Gimli = @import("crypto/gimli.zig").Aead;
pub const ChaCha20Poly1305 = chacha20.Chacha20Poly1305;
pub const XChaCha20Poly1305 = chacha20.XChacha20Poly1305;
};
/// MAC functions requiring single-use secret keys.
pub const onetimeauth = struct {
pub const Poly1305 = @import("crypto/poly1305.zig").Poly1305;
};
/// Core functions, that should rarely be used directly by applications.
pub const core = struct {
pub const aes = @import("crypto/aes.zig");
pub const Gimli = @import("crypto/gimli.zig").State;
};
/// Elliptic-curve arithmetic.
pub const ecc = struct {
pub const Curve25519 = @import("crypto/25519/curve25519.zig").Curve25519;
pub const Edwards25519 = @import("crypto/25519/edwards25519.zig").Edwards25519;
pub const Ristretto255 = @import("crypto/25519/ristretto255.zig").Ristretto255;
};
/// Diffie-Hellman key exchange functions.
pub const dh = struct {
pub const X25519 = @import("crypto/25519/x25519.zig").X25519;
};
/// Digital signature functions.
pub const sign = struct {
pub const Ed25519 = @import("crypto/25519/ed25519.zig").Ed25519;
};
/// Stream ciphers. These do not provide any kind of authentication.
/// Most applications should be using AEAD constructions instead of stream ciphers directly.
pub const stream = struct {
pub const ChaCha20IETF = @import("crypto/chacha20.zig").ChaCha20IETF;
pub const XChaCha20IETF = @import("crypto/chacha20.zig").XChaCha20IETF;
pub const ChaCha20With64BitNonce = @import("crypto/chacha20.zig").ChaCha20With64BitNonce;
};
const std = @import("std.zig");
pub const randomBytes = std.os.getrandom;
test "crypto" {
_ = @import("crypto/aes.zig");
_ = @import("crypto/blake2.zig");
_ = @import("crypto/blake3.zig");
_ = @import("crypto/chacha20.zig");
_ = @import("crypto/gimli.zig");
_ = @import("crypto/hmac.zig");
_ = @import("crypto/md5.zig");
_ = @import("crypto/poly1305.zig");
_ = @import("crypto/sha1.zig");
_ = @import("crypto/sha2.zig");
_ = @import("crypto/sha3.zig");
_ = @import("crypto/siphash.zig");
_ = @import("crypto/25519/curve25519.zig");
_ = @import("crypto/25519/ed25519.zig");
_ = @import("crypto/25519/edwards25519.zig");
_ = @import("crypto/25519/field.zig");
_ = @import("crypto/25519/scalar.zig");
_ = @import("crypto/25519/x25519.zig");
_ = @import("crypto/25519/ristretto255.zig");
}
test "issue #4532: no index out of bounds" {
const types = [_]type{
hash.Md5,
hash.Sha1,
hash.sha2.Sha224,
hash.sha2.Sha256,
hash.sha2.Sha384,
hash.sha2.Sha512,
hash.sha3.Sha3_224,
hash.sha3.Sha3_256,
hash.sha3.Sha3_384,
hash.sha3.Sha3_512,
hash.blake2.Blake2s224,
hash.blake2.Blake2s256,
hash.blake2.Blake2b384,
hash.blake2.Blake2b512,
hash.Gimli,
};
inline for (types) |Hasher| {
var block = [_]u8{'#'} ** Hasher.block_length;
var out1: [Hasher.digest_length]u8 = undefined;
var out2: [Hasher.digest_length]u8 = undefined;
const h0 = Hasher.init(.{});
var h = h0;
h.update(block[0..]);
h.final(out1[0..]);
h = h0;
h.update(block[0..1]);
h.update(block[1..]);
h.final(out2[0..]);
std.testing.expectEqual(out1, out2);
}
}
|
lib/std/crypto.zig
|
const std = @import("std");
const assert = std.debug.assert;
const Entry = struct {
policy: struct {
least: u16,
most: u16,
letter: u8,
} = undefined,
password: []u8 = undefined,
};
pub fn main() !void {
var gpa = std.heap.GeneralPurposeAllocator(.{ .safety = true, .enable_memory_limit = true }){};
const allocator = &gpa.allocator;
defer {
const bytesUsed = gpa.total_requested_bytes;
const info = gpa.deinit();
std.log.info("\n\t[*] Leaked: {}\n\t[*] Bytes leaked: {}", .{ info, bytesUsed });
}
var args = try std.process.argsAlloc(allocator);
defer std.process.argsFree(allocator, args);
const input_file = try std.fs.cwd().openFile(args[1], .{});
defer input_file.close();
const input_reader = input_file.reader();
var entry_list = std.ArrayList(Entry).init(allocator);
defer {
for (entry_list.items) |item| {
allocator.destroy(item.password.ptr);
}
entry_list.deinit();
}
var buf: [512]u8 = undefined;
while (try input_reader.readUntilDelimiterOrEof(buf[0..], '\n')) |line| {
var entry = Entry{};
var iter = std.mem.tokenize(line, " -");
entry.policy.least = try std.fmt.parseInt(@TypeOf(entry.policy.least), iter.next().?, 10);
entry.policy.most = try std.fmt.parseInt(@TypeOf(entry.policy.most), iter.next().?, 10);
entry.policy.letter = iter.next().?[0];
entry.password = try allocator.dupe(u8, iter.next().?);
try entry_list.append(entry);
}
std.log.info("Solution to part 1 is {}.", .{part1(allocator, entry_list)});
std.log.info("Solution to part 2 is {}.", .{part2(allocator, entry_list)});
}
fn part1(allocator: *std.mem.Allocator, entry_list: std.ArrayList(Entry)) u32 {
var valid: u32 = 0;
for (entry_list.items) |entry| {
var count: u32 = 0;
for (entry.password) |c| {
if (c == entry.policy.letter) {
count += 1;
}
}
if (count >= entry.policy.least and count <= entry.policy.most) {
valid += 1;
}
}
return valid;
}
fn part2(allocator: *std.mem.Allocator, entry_list: std.ArrayList(Entry)) u32 {
var valid: u32 = 0;
for (entry_list.items) |entry| {
if ((entry.password[entry.policy.least - 1] == entry.policy.letter) !=
(entry.password[entry.policy.most - 1] == entry.policy.letter)) {
valid += 1;
}
}
return valid;
}
|
src/day02.zig
|
const std = @import("std");
const upaya = @import("upaya");
const ts = @import("../tilescript.zig");
usingnamespace @import("imgui");
pub fn draw(state: *ts.AppState) void {
igPushStyleVarVec2(ImGuiStyleVar_WindowMinSize, .{ .x = 220, .y = 100 });
defer igPopStyleVar(1);
if (state.prefs.windows.tags) {
if (igBegin("Tags", &state.prefs.windows.tags, ImGuiWindowFlags_None)) {
defer igEnd();
if (igBeginChildEx("##tag-child", igGetItemID(), .{ .y = -igGetFrameHeightWithSpacing() }, false, ImGuiWindowFlags_None)) {
defer igEndChild();
var delete_index: usize = std.math.maxInt(usize);
for (state.map.tags.items) |*tag, i| {
igPushIDInt(@intCast(c_int, i));
if (ogInputText("##key", &tag.name, tag.name.len)) {}
igSameLine(0, 5);
igPushItemWidth(100);
if (ogButton("Tiles")) {
igOpenPopup("tag-tiles");
}
igPopItemWidth();
igSameLine(igGetWindowContentRegionWidth() - 20, 0);
if (ogButton(icons.trash)) {
delete_index = i;
}
igSetNextWindowPos(igGetIO().MousePos, ImGuiCond_Appearing, .{ .x = 0.5 });
if (igBeginPopup("tag-tiles", ImGuiWindowFlags_None)) {
defer igEndPopup();
tagTileSelectorPopup(state, tag);
}
igPopID();
}
if (delete_index < std.math.maxInt(usize)) {
_ = state.map.tags.orderedRemove(delete_index);
}
}
if (igButton("Add Tag", .{})) {
state.map.addTag();
}
}
}
}
fn tagTileSelectorPopup(state: *ts.AppState, tag: *ts.data.Tag) void {
var content_start_pos = ogGetCursorScreenPos();
const zoom: usize = if (state.texture.width < 200 and state.texture.height < 200) 2 else 1;
const tile_spacing = state.map.tile_spacing * zoom;
const tile_size = state.map.tile_size * zoom;
ogImage(state.texture.imTextureID(), state.texture.width * @intCast(i32, zoom), state.texture.height * @intCast(i32, zoom));
const draw_list = igGetWindowDrawList();
// draw selected tiles
var iter = tag.tiles.iter();
while (iter.next()) |value| {
ts.addTileToDrawList(tile_size, content_start_pos, value, state.tilesPerRow(), tile_spacing);
}
// check input for toggling state
if (igIsItemHovered(ImGuiHoveredFlags_None)) {
if (igIsMouseClicked(0, false)) {
var tile = ts.tileIndexUnderMouse(@intCast(usize, tile_size + tile_spacing), content_start_pos);
tag.toggleSelected(@intCast(u8, tile.x + tile.y * state.tilesPerRow()));
}
}
if (igButton("Clear", ImVec2{ .x = -1 })) {
tag.tiles.clear();
}
}
|
tilescript/windows/tags.zig
|
pub const FILE_CACHE_MAX_HARD_ENABLE = @as(u32, 1);
pub const FILE_CACHE_MAX_HARD_DISABLE = @as(u32, 2);
pub const FILE_CACHE_MIN_HARD_ENABLE = @as(u32, 4);
pub const FILE_CACHE_MIN_HARD_DISABLE = @as(u32, 8);
pub const MEHC_PATROL_SCRUBBER_PRESENT = @as(u32, 1);
//--------------------------------------------------------------------------------
// Section: Types (29)
//--------------------------------------------------------------------------------
pub const FILE_MAP = enum(u32) {
WRITE = 2,
READ = 4,
ALL_ACCESS = 983071,
EXECUTE = 32,
COPY = 1,
RESERVE = 2147483648,
TARGETS_INVALID = 1073741824,
LARGE_PAGES = 536870912,
_,
pub fn initFlags(o: struct {
WRITE: u1 = 0,
READ: u1 = 0,
ALL_ACCESS: u1 = 0,
EXECUTE: u1 = 0,
COPY: u1 = 0,
RESERVE: u1 = 0,
TARGETS_INVALID: u1 = 0,
LARGE_PAGES: u1 = 0,
}) FILE_MAP {
return @intToEnum(FILE_MAP,
(if (o.WRITE == 1) @enumToInt(FILE_MAP.WRITE) else 0)
| (if (o.READ == 1) @enumToInt(FILE_MAP.READ) else 0)
| (if (o.ALL_ACCESS == 1) @enumToInt(FILE_MAP.ALL_ACCESS) else 0)
| (if (o.EXECUTE == 1) @enumToInt(FILE_MAP.EXECUTE) else 0)
| (if (o.COPY == 1) @enumToInt(FILE_MAP.COPY) else 0)
| (if (o.RESERVE == 1) @enumToInt(FILE_MAP.RESERVE) else 0)
| (if (o.TARGETS_INVALID == 1) @enumToInt(FILE_MAP.TARGETS_INVALID) else 0)
| (if (o.LARGE_PAGES == 1) @enumToInt(FILE_MAP.LARGE_PAGES) else 0)
);
}
};
pub const FILE_MAP_WRITE = FILE_MAP.WRITE;
pub const FILE_MAP_READ = FILE_MAP.READ;
pub const FILE_MAP_ALL_ACCESS = FILE_MAP.ALL_ACCESS;
pub const FILE_MAP_EXECUTE = FILE_MAP.EXECUTE;
pub const FILE_MAP_COPY = FILE_MAP.COPY;
pub const FILE_MAP_RESERVE = FILE_MAP.RESERVE;
pub const FILE_MAP_TARGETS_INVALID = FILE_MAP.TARGETS_INVALID;
pub const FILE_MAP_LARGE_PAGES = FILE_MAP.LARGE_PAGES;
pub const HEAP_FLAGS = enum(u32) {
NONE = 0,
NO_SERIALIZE = 1,
GROWABLE = 2,
GENERATE_EXCEPTIONS = 4,
ZERO_MEMORY = 8,
REALLOC_IN_PLACE_ONLY = 16,
TAIL_CHECKING_ENABLED = 32,
FREE_CHECKING_ENABLED = 64,
DISABLE_COALESCE_ON_FREE = 128,
CREATE_ALIGN_16 = 65536,
CREATE_ENABLE_TRACING = 131072,
CREATE_ENABLE_EXECUTE = 262144,
MAXIMUM_TAG = 4095,
PSEUDO_TAG_FLAG = 32768,
TAG_SHIFT = 18,
CREATE_SEGMENT_HEAP = 256,
CREATE_HARDENED = 512,
_,
pub fn initFlags(o: struct {
NONE: u1 = 0,
NO_SERIALIZE: u1 = 0,
GROWABLE: u1 = 0,
GENERATE_EXCEPTIONS: u1 = 0,
ZERO_MEMORY: u1 = 0,
REALLOC_IN_PLACE_ONLY: u1 = 0,
TAIL_CHECKING_ENABLED: u1 = 0,
FREE_CHECKING_ENABLED: u1 = 0,
DISABLE_COALESCE_ON_FREE: u1 = 0,
CREATE_ALIGN_16: u1 = 0,
CREATE_ENABLE_TRACING: u1 = 0,
CREATE_ENABLE_EXECUTE: u1 = 0,
MAXIMUM_TAG: u1 = 0,
PSEUDO_TAG_FLAG: u1 = 0,
TAG_SHIFT: u1 = 0,
CREATE_SEGMENT_HEAP: u1 = 0,
CREATE_HARDENED: u1 = 0,
}) HEAP_FLAGS {
return @intToEnum(HEAP_FLAGS,
(if (o.NONE == 1) @enumToInt(HEAP_FLAGS.NONE) else 0)
| (if (o.NO_SERIALIZE == 1) @enumToInt(HEAP_FLAGS.NO_SERIALIZE) else 0)
| (if (o.GROWABLE == 1) @enumToInt(HEAP_FLAGS.GROWABLE) else 0)
| (if (o.GENERATE_EXCEPTIONS == 1) @enumToInt(HEAP_FLAGS.GENERATE_EXCEPTIONS) else 0)
| (if (o.ZERO_MEMORY == 1) @enumToInt(HEAP_FLAGS.ZERO_MEMORY) else 0)
| (if (o.REALLOC_IN_PLACE_ONLY == 1) @enumToInt(HEAP_FLAGS.REALLOC_IN_PLACE_ONLY) else 0)
| (if (o.TAIL_CHECKING_ENABLED == 1) @enumToInt(HEAP_FLAGS.TAIL_CHECKING_ENABLED) else 0)
| (if (o.FREE_CHECKING_ENABLED == 1) @enumToInt(HEAP_FLAGS.FREE_CHECKING_ENABLED) else 0)
| (if (o.DISABLE_COALESCE_ON_FREE == 1) @enumToInt(HEAP_FLAGS.DISABLE_COALESCE_ON_FREE) else 0)
| (if (o.CREATE_ALIGN_16 == 1) @enumToInt(HEAP_FLAGS.CREATE_ALIGN_16) else 0)
| (if (o.CREATE_ENABLE_TRACING == 1) @enumToInt(HEAP_FLAGS.CREATE_ENABLE_TRACING) else 0)
| (if (o.CREATE_ENABLE_EXECUTE == 1) @enumToInt(HEAP_FLAGS.CREATE_ENABLE_EXECUTE) else 0)
| (if (o.MAXIMUM_TAG == 1) @enumToInt(HEAP_FLAGS.MAXIMUM_TAG) else 0)
| (if (o.PSEUDO_TAG_FLAG == 1) @enumToInt(HEAP_FLAGS.PSEUDO_TAG_FLAG) else 0)
| (if (o.TAG_SHIFT == 1) @enumToInt(HEAP_FLAGS.TAG_SHIFT) else 0)
| (if (o.CREATE_SEGMENT_HEAP == 1) @enumToInt(HEAP_FLAGS.CREATE_SEGMENT_HEAP) else 0)
| (if (o.CREATE_HARDENED == 1) @enumToInt(HEAP_FLAGS.CREATE_HARDENED) else 0)
);
}
};
pub const HEAP_NONE = HEAP_FLAGS.NONE;
pub const HEAP_NO_SERIALIZE = HEAP_FLAGS.NO_SERIALIZE;
pub const HEAP_GROWABLE = HEAP_FLAGS.GROWABLE;
pub const HEAP_GENERATE_EXCEPTIONS = HEAP_FLAGS.GENERATE_EXCEPTIONS;
pub const HEAP_ZERO_MEMORY = HEAP_FLAGS.ZERO_MEMORY;
pub const HEAP_REALLOC_IN_PLACE_ONLY = HEAP_FLAGS.REALLOC_IN_PLACE_ONLY;
pub const HEAP_TAIL_CHECKING_ENABLED = HEAP_FLAGS.TAIL_CHECKING_ENABLED;
pub const HEAP_FREE_CHECKING_ENABLED = HEAP_FLAGS.FREE_CHECKING_ENABLED;
pub const HEAP_DISABLE_COALESCE_ON_FREE = HEAP_FLAGS.DISABLE_COALESCE_ON_FREE;
pub const HEAP_CREATE_ALIGN_16 = HEAP_FLAGS.CREATE_ALIGN_16;
pub const HEAP_CREATE_ENABLE_TRACING = HEAP_FLAGS.CREATE_ENABLE_TRACING;
pub const HEAP_CREATE_ENABLE_EXECUTE = HEAP_FLAGS.CREATE_ENABLE_EXECUTE;
pub const HEAP_MAXIMUM_TAG = HEAP_FLAGS.MAXIMUM_TAG;
pub const HEAP_PSEUDO_TAG_FLAG = HEAP_FLAGS.PSEUDO_TAG_FLAG;
pub const HEAP_TAG_SHIFT = HEAP_FLAGS.TAG_SHIFT;
pub const HEAP_CREATE_SEGMENT_HEAP = HEAP_FLAGS.CREATE_SEGMENT_HEAP;
pub const HEAP_CREATE_HARDENED = HEAP_FLAGS.CREATE_HARDENED;
pub const PAGE_PROTECTION_FLAGS = enum(u32) {
PAGE_NOACCESS = 1,
PAGE_READONLY = 2,
PAGE_READWRITE = 4,
PAGE_WRITECOPY = 8,
PAGE_EXECUTE = 16,
PAGE_EXECUTE_READ = 32,
PAGE_EXECUTE_READWRITE = 64,
PAGE_EXECUTE_WRITECOPY = 128,
PAGE_GUARD = 256,
PAGE_NOCACHE = 512,
PAGE_WRITECOMBINE = 1024,
PAGE_GRAPHICS_NOACCESS = 2048,
PAGE_GRAPHICS_READONLY = 4096,
PAGE_GRAPHICS_READWRITE = 8192,
PAGE_GRAPHICS_EXECUTE = 16384,
PAGE_GRAPHICS_EXECUTE_READ = 32768,
PAGE_GRAPHICS_EXECUTE_READWRITE = 65536,
PAGE_GRAPHICS_COHERENT = 131072,
PAGE_GRAPHICS_NOCACHE = 262144,
PAGE_ENCLAVE_THREAD_CONTROL = 2147483648,
// PAGE_REVERT_TO_FILE_MAP = 2147483648, this enum value conflicts with PAGE_ENCLAVE_THREAD_CONTROL
PAGE_TARGETS_NO_UPDATE = 1073741824,
// PAGE_TARGETS_INVALID = 1073741824, this enum value conflicts with PAGE_TARGETS_NO_UPDATE
PAGE_ENCLAVE_UNVALIDATED = 536870912,
PAGE_ENCLAVE_MASK = 268435456,
// PAGE_ENCLAVE_DECOMMIT = 268435456, this enum value conflicts with PAGE_ENCLAVE_MASK
PAGE_ENCLAVE_SS_FIRST = 268435457,
PAGE_ENCLAVE_SS_REST = 268435458,
// SEC_PARTITION_OWNER_HANDLE = 262144, this enum value conflicts with PAGE_GRAPHICS_NOCACHE
SEC_64K_PAGES = 524288,
SEC_FILE = 8388608,
SEC_IMAGE = 16777216,
SEC_PROTECTED_IMAGE = 33554432,
SEC_RESERVE = 67108864,
SEC_COMMIT = 134217728,
// SEC_NOCACHE = 268435456, this enum value conflicts with PAGE_ENCLAVE_MASK
// SEC_WRITECOMBINE = 1073741824, this enum value conflicts with PAGE_TARGETS_NO_UPDATE
// SEC_LARGE_PAGES = 2147483648, this enum value conflicts with PAGE_ENCLAVE_THREAD_CONTROL
SEC_IMAGE_NO_EXECUTE = 285212672,
_,
pub fn initFlags(o: struct {
PAGE_NOACCESS: u1 = 0,
PAGE_READONLY: u1 = 0,
PAGE_READWRITE: u1 = 0,
PAGE_WRITECOPY: u1 = 0,
PAGE_EXECUTE: u1 = 0,
PAGE_EXECUTE_READ: u1 = 0,
PAGE_EXECUTE_READWRITE: u1 = 0,
PAGE_EXECUTE_WRITECOPY: u1 = 0,
PAGE_GUARD: u1 = 0,
PAGE_NOCACHE: u1 = 0,
PAGE_WRITECOMBINE: u1 = 0,
PAGE_GRAPHICS_NOACCESS: u1 = 0,
PAGE_GRAPHICS_READONLY: u1 = 0,
PAGE_GRAPHICS_READWRITE: u1 = 0,
PAGE_GRAPHICS_EXECUTE: u1 = 0,
PAGE_GRAPHICS_EXECUTE_READ: u1 = 0,
PAGE_GRAPHICS_EXECUTE_READWRITE: u1 = 0,
PAGE_GRAPHICS_COHERENT: u1 = 0,
PAGE_GRAPHICS_NOCACHE: u1 = 0,
PAGE_ENCLAVE_THREAD_CONTROL: u1 = 0,
PAGE_TARGETS_NO_UPDATE: u1 = 0,
PAGE_ENCLAVE_UNVALIDATED: u1 = 0,
PAGE_ENCLAVE_MASK: u1 = 0,
PAGE_ENCLAVE_SS_FIRST: u1 = 0,
PAGE_ENCLAVE_SS_REST: u1 = 0,
SEC_64K_PAGES: u1 = 0,
SEC_FILE: u1 = 0,
SEC_IMAGE: u1 = 0,
SEC_PROTECTED_IMAGE: u1 = 0,
SEC_RESERVE: u1 = 0,
SEC_COMMIT: u1 = 0,
SEC_IMAGE_NO_EXECUTE: u1 = 0,
}) PAGE_PROTECTION_FLAGS {
return @intToEnum(PAGE_PROTECTION_FLAGS,
(if (o.PAGE_NOACCESS == 1) @enumToInt(PAGE_PROTECTION_FLAGS.PAGE_NOACCESS) else 0)
| (if (o.PAGE_READONLY == 1) @enumToInt(PAGE_PROTECTION_FLAGS.PAGE_READONLY) else 0)
| (if (o.PAGE_READWRITE == 1) @enumToInt(PAGE_PROTECTION_FLAGS.PAGE_READWRITE) else 0)
| (if (o.PAGE_WRITECOPY == 1) @enumToInt(PAGE_PROTECTION_FLAGS.PAGE_WRITECOPY) else 0)
| (if (o.PAGE_EXECUTE == 1) @enumToInt(PAGE_PROTECTION_FLAGS.PAGE_EXECUTE) else 0)
| (if (o.PAGE_EXECUTE_READ == 1) @enumToInt(PAGE_PROTECTION_FLAGS.PAGE_EXECUTE_READ) else 0)
| (if (o.PAGE_EXECUTE_READWRITE == 1) @enumToInt(PAGE_PROTECTION_FLAGS.PAGE_EXECUTE_READWRITE) else 0)
| (if (o.PAGE_EXECUTE_WRITECOPY == 1) @enumToInt(PAGE_PROTECTION_FLAGS.PAGE_EXECUTE_WRITECOPY) else 0)
| (if (o.PAGE_GUARD == 1) @enumToInt(PAGE_PROTECTION_FLAGS.PAGE_GUARD) else 0)
| (if (o.PAGE_NOCACHE == 1) @enumToInt(PAGE_PROTECTION_FLAGS.PAGE_NOCACHE) else 0)
| (if (o.PAGE_WRITECOMBINE == 1) @enumToInt(PAGE_PROTECTION_FLAGS.PAGE_WRITECOMBINE) else 0)
| (if (o.PAGE_GRAPHICS_NOACCESS == 1) @enumToInt(PAGE_PROTECTION_FLAGS.PAGE_GRAPHICS_NOACCESS) else 0)
| (if (o.PAGE_GRAPHICS_READONLY == 1) @enumToInt(PAGE_PROTECTION_FLAGS.PAGE_GRAPHICS_READONLY) else 0)
| (if (o.PAGE_GRAPHICS_READWRITE == 1) @enumToInt(PAGE_PROTECTION_FLAGS.PAGE_GRAPHICS_READWRITE) else 0)
| (if (o.PAGE_GRAPHICS_EXECUTE == 1) @enumToInt(PAGE_PROTECTION_FLAGS.PAGE_GRAPHICS_EXECUTE) else 0)
| (if (o.PAGE_GRAPHICS_EXECUTE_READ == 1) @enumToInt(PAGE_PROTECTION_FLAGS.PAGE_GRAPHICS_EXECUTE_READ) else 0)
| (if (o.PAGE_GRAPHICS_EXECUTE_READWRITE == 1) @enumToInt(PAGE_PROTECTION_FLAGS.PAGE_GRAPHICS_EXECUTE_READWRITE) else 0)
| (if (o.PAGE_GRAPHICS_COHERENT == 1) @enumToInt(PAGE_PROTECTION_FLAGS.PAGE_GRAPHICS_COHERENT) else 0)
| (if (o.PAGE_GRAPHICS_NOCACHE == 1) @enumToInt(PAGE_PROTECTION_FLAGS.PAGE_GRAPHICS_NOCACHE) else 0)
| (if (o.PAGE_ENCLAVE_THREAD_CONTROL == 1) @enumToInt(PAGE_PROTECTION_FLAGS.PAGE_ENCLAVE_THREAD_CONTROL) else 0)
| (if (o.PAGE_TARGETS_NO_UPDATE == 1) @enumToInt(PAGE_PROTECTION_FLAGS.PAGE_TARGETS_NO_UPDATE) else 0)
| (if (o.PAGE_ENCLAVE_UNVALIDATED == 1) @enumToInt(PAGE_PROTECTION_FLAGS.PAGE_ENCLAVE_UNVALIDATED) else 0)
| (if (o.PAGE_ENCLAVE_MASK == 1) @enumToInt(PAGE_PROTECTION_FLAGS.PAGE_ENCLAVE_MASK) else 0)
| (if (o.PAGE_ENCLAVE_SS_FIRST == 1) @enumToInt(PAGE_PROTECTION_FLAGS.PAGE_ENCLAVE_SS_FIRST) else 0)
| (if (o.PAGE_ENCLAVE_SS_REST == 1) @enumToInt(PAGE_PROTECTION_FLAGS.PAGE_ENCLAVE_SS_REST) else 0)
| (if (o.SEC_64K_PAGES == 1) @enumToInt(PAGE_PROTECTION_FLAGS.SEC_64K_PAGES) else 0)
| (if (o.SEC_FILE == 1) @enumToInt(PAGE_PROTECTION_FLAGS.SEC_FILE) else 0)
| (if (o.SEC_IMAGE == 1) @enumToInt(PAGE_PROTECTION_FLAGS.SEC_IMAGE) else 0)
| (if (o.SEC_PROTECTED_IMAGE == 1) @enumToInt(PAGE_PROTECTION_FLAGS.SEC_PROTECTED_IMAGE) else 0)
| (if (o.SEC_RESERVE == 1) @enumToInt(PAGE_PROTECTION_FLAGS.SEC_RESERVE) else 0)
| (if (o.SEC_COMMIT == 1) @enumToInt(PAGE_PROTECTION_FLAGS.SEC_COMMIT) else 0)
| (if (o.SEC_IMAGE_NO_EXECUTE == 1) @enumToInt(PAGE_PROTECTION_FLAGS.SEC_IMAGE_NO_EXECUTE) else 0)
);
}
};
pub const PAGE_NOACCESS = PAGE_PROTECTION_FLAGS.PAGE_NOACCESS;
pub const PAGE_READONLY = PAGE_PROTECTION_FLAGS.PAGE_READONLY;
pub const PAGE_READWRITE = PAGE_PROTECTION_FLAGS.PAGE_READWRITE;
pub const PAGE_WRITECOPY = PAGE_PROTECTION_FLAGS.PAGE_WRITECOPY;
pub const PAGE_EXECUTE = PAGE_PROTECTION_FLAGS.PAGE_EXECUTE;
pub const PAGE_EXECUTE_READ = PAGE_PROTECTION_FLAGS.PAGE_EXECUTE_READ;
pub const PAGE_EXECUTE_READWRITE = PAGE_PROTECTION_FLAGS.PAGE_EXECUTE_READWRITE;
pub const PAGE_EXECUTE_WRITECOPY = PAGE_PROTECTION_FLAGS.PAGE_EXECUTE_WRITECOPY;
pub const PAGE_GUARD = PAGE_PROTECTION_FLAGS.PAGE_GUARD;
pub const PAGE_NOCACHE = PAGE_PROTECTION_FLAGS.PAGE_NOCACHE;
pub const PAGE_WRITECOMBINE = PAGE_PROTECTION_FLAGS.PAGE_WRITECOMBINE;
pub const PAGE_GRAPHICS_NOACCESS = PAGE_PROTECTION_FLAGS.PAGE_GRAPHICS_NOACCESS;
pub const PAGE_GRAPHICS_READONLY = PAGE_PROTECTION_FLAGS.PAGE_GRAPHICS_READONLY;
pub const PAGE_GRAPHICS_READWRITE = PAGE_PROTECTION_FLAGS.PAGE_GRAPHICS_READWRITE;
pub const PAGE_GRAPHICS_EXECUTE = PAGE_PROTECTION_FLAGS.PAGE_GRAPHICS_EXECUTE;
pub const PAGE_GRAPHICS_EXECUTE_READ = PAGE_PROTECTION_FLAGS.PAGE_GRAPHICS_EXECUTE_READ;
pub const PAGE_GRAPHICS_EXECUTE_READWRITE = PAGE_PROTECTION_FLAGS.PAGE_GRAPHICS_EXECUTE_READWRITE;
pub const PAGE_GRAPHICS_COHERENT = PAGE_PROTECTION_FLAGS.PAGE_GRAPHICS_COHERENT;
pub const PAGE_GRAPHICS_NOCACHE = PAGE_PROTECTION_FLAGS.PAGE_GRAPHICS_NOCACHE;
pub const PAGE_ENCLAVE_THREAD_CONTROL = PAGE_PROTECTION_FLAGS.PAGE_ENCLAVE_THREAD_CONTROL;
pub const PAGE_REVERT_TO_FILE_MAP = PAGE_PROTECTION_FLAGS.PAGE_ENCLAVE_THREAD_CONTROL;
pub const PAGE_TARGETS_NO_UPDATE = PAGE_PROTECTION_FLAGS.PAGE_TARGETS_NO_UPDATE;
pub const PAGE_TARGETS_INVALID = PAGE_PROTECTION_FLAGS.PAGE_TARGETS_NO_UPDATE;
pub const PAGE_ENCLAVE_UNVALIDATED = PAGE_PROTECTION_FLAGS.PAGE_ENCLAVE_UNVALIDATED;
pub const PAGE_ENCLAVE_MASK = PAGE_PROTECTION_FLAGS.PAGE_ENCLAVE_MASK;
pub const PAGE_ENCLAVE_DECOMMIT = PAGE_PROTECTION_FLAGS.PAGE_ENCLAVE_MASK;
pub const PAGE_ENCLAVE_SS_FIRST = PAGE_PROTECTION_FLAGS.PAGE_ENCLAVE_SS_FIRST;
pub const PAGE_ENCLAVE_SS_REST = PAGE_PROTECTION_FLAGS.PAGE_ENCLAVE_SS_REST;
pub const SEC_PARTITION_OWNER_HANDLE = PAGE_PROTECTION_FLAGS.PAGE_GRAPHICS_NOCACHE;
pub const SEC_64K_PAGES = PAGE_PROTECTION_FLAGS.SEC_64K_PAGES;
pub const SEC_FILE = PAGE_PROTECTION_FLAGS.SEC_FILE;
pub const SEC_IMAGE = PAGE_PROTECTION_FLAGS.SEC_IMAGE;
pub const SEC_PROTECTED_IMAGE = PAGE_PROTECTION_FLAGS.SEC_PROTECTED_IMAGE;
pub const SEC_RESERVE = PAGE_PROTECTION_FLAGS.SEC_RESERVE;
pub const SEC_COMMIT = PAGE_PROTECTION_FLAGS.SEC_COMMIT;
pub const SEC_NOCACHE = PAGE_PROTECTION_FLAGS.PAGE_ENCLAVE_MASK;
pub const SEC_WRITECOMBINE = PAGE_PROTECTION_FLAGS.PAGE_TARGETS_NO_UPDATE;
pub const SEC_LARGE_PAGES = PAGE_PROTECTION_FLAGS.PAGE_ENCLAVE_THREAD_CONTROL;
pub const SEC_IMAGE_NO_EXECUTE = PAGE_PROTECTION_FLAGS.SEC_IMAGE_NO_EXECUTE;
pub const UNMAP_VIEW_OF_FILE_FLAGS = enum(u32) {
UNMAP_NONE = 0,
UNMAP_WITH_TRANSIENT_BOOST = 1,
PRESERVE_PLACEHOLDER = 2,
};
pub const MEM_UNMAP_NONE = UNMAP_VIEW_OF_FILE_FLAGS.UNMAP_NONE;
pub const MEM_UNMAP_WITH_TRANSIENT_BOOST = UNMAP_VIEW_OF_FILE_FLAGS.UNMAP_WITH_TRANSIENT_BOOST;
pub const MEM_PRESERVE_PLACEHOLDER = UNMAP_VIEW_OF_FILE_FLAGS.PRESERVE_PLACEHOLDER;
pub const VIRTUAL_FREE_TYPE = enum(u32) {
DECOMMIT = 16384,
RELEASE = 32768,
};
pub const MEM_DECOMMIT = VIRTUAL_FREE_TYPE.DECOMMIT;
pub const MEM_RELEASE = VIRTUAL_FREE_TYPE.RELEASE;
pub const VIRTUAL_ALLOCATION_TYPE = enum(u32) {
COMMIT = 4096,
RESERVE = 8192,
RESET = 524288,
RESET_UNDO = 16777216,
REPLACE_PLACEHOLDER = 16384,
LARGE_PAGES = 536870912,
RESERVE_PLACEHOLDER = 262144,
FREE = 65536,
_,
pub fn initFlags(o: struct {
COMMIT: u1 = 0,
RESERVE: u1 = 0,
RESET: u1 = 0,
RESET_UNDO: u1 = 0,
REPLACE_PLACEHOLDER: u1 = 0,
LARGE_PAGES: u1 = 0,
RESERVE_PLACEHOLDER: u1 = 0,
FREE: u1 = 0,
}) VIRTUAL_ALLOCATION_TYPE {
return @intToEnum(VIRTUAL_ALLOCATION_TYPE,
(if (o.COMMIT == 1) @enumToInt(VIRTUAL_ALLOCATION_TYPE.COMMIT) else 0)
| (if (o.RESERVE == 1) @enumToInt(VIRTUAL_ALLOCATION_TYPE.RESERVE) else 0)
| (if (o.RESET == 1) @enumToInt(VIRTUAL_ALLOCATION_TYPE.RESET) else 0)
| (if (o.RESET_UNDO == 1) @enumToInt(VIRTUAL_ALLOCATION_TYPE.RESET_UNDO) else 0)
| (if (o.REPLACE_PLACEHOLDER == 1) @enumToInt(VIRTUAL_ALLOCATION_TYPE.REPLACE_PLACEHOLDER) else 0)
| (if (o.LARGE_PAGES == 1) @enumToInt(VIRTUAL_ALLOCATION_TYPE.LARGE_PAGES) else 0)
| (if (o.RESERVE_PLACEHOLDER == 1) @enumToInt(VIRTUAL_ALLOCATION_TYPE.RESERVE_PLACEHOLDER) else 0)
| (if (o.FREE == 1) @enumToInt(VIRTUAL_ALLOCATION_TYPE.FREE) else 0)
);
}
};
pub const MEM_COMMIT = VIRTUAL_ALLOCATION_TYPE.COMMIT;
pub const MEM_RESERVE = VIRTUAL_ALLOCATION_TYPE.RESERVE;
pub const MEM_RESET = VIRTUAL_ALLOCATION_TYPE.RESET;
pub const MEM_RESET_UNDO = VIRTUAL_ALLOCATION_TYPE.RESET_UNDO;
pub const MEM_REPLACE_PLACEHOLDER = VIRTUAL_ALLOCATION_TYPE.REPLACE_PLACEHOLDER;
pub const MEM_LARGE_PAGES = VIRTUAL_ALLOCATION_TYPE.LARGE_PAGES;
pub const MEM_RESERVE_PLACEHOLDER = VIRTUAL_ALLOCATION_TYPE.RESERVE_PLACEHOLDER;
pub const MEM_FREE = VIRTUAL_ALLOCATION_TYPE.FREE;
pub const LOCAL_ALLOC_FLAGS = enum(u32) {
LHND = 66,
LMEM_FIXED = 0,
LMEM_MOVEABLE = 2,
LMEM_ZEROINIT = 64,
// LPTR = 64, this enum value conflicts with LMEM_ZEROINIT
// NONZEROLHND = 2, this enum value conflicts with LMEM_MOVEABLE
// NONZEROLPTR = 0, this enum value conflicts with LMEM_FIXED
_,
pub fn initFlags(o: struct {
LHND: u1 = 0,
LMEM_FIXED: u1 = 0,
LMEM_MOVEABLE: u1 = 0,
LMEM_ZEROINIT: u1 = 0,
}) LOCAL_ALLOC_FLAGS {
return @intToEnum(LOCAL_ALLOC_FLAGS,
(if (o.LHND == 1) @enumToInt(LOCAL_ALLOC_FLAGS.LHND) else 0)
| (if (o.LMEM_FIXED == 1) @enumToInt(LOCAL_ALLOC_FLAGS.LMEM_FIXED) else 0)
| (if (o.LMEM_MOVEABLE == 1) @enumToInt(LOCAL_ALLOC_FLAGS.LMEM_MOVEABLE) else 0)
| (if (o.LMEM_ZEROINIT == 1) @enumToInt(LOCAL_ALLOC_FLAGS.LMEM_ZEROINIT) else 0)
);
}
};
pub const LHND = LOCAL_ALLOC_FLAGS.LHND;
pub const LMEM_FIXED = LOCAL_ALLOC_FLAGS.LMEM_FIXED;
pub const LMEM_MOVEABLE = LOCAL_ALLOC_FLAGS.LMEM_MOVEABLE;
pub const LMEM_ZEROINIT = LOCAL_ALLOC_FLAGS.LMEM_ZEROINIT;
pub const LPTR = LOCAL_ALLOC_FLAGS.LMEM_ZEROINIT;
pub const NONZEROLHND = LOCAL_ALLOC_FLAGS.LMEM_MOVEABLE;
pub const NONZEROLPTR = LOCAL_ALLOC_FLAGS.LMEM_FIXED;
pub const GLOBAL_ALLOC_FLAGS = enum(u32) {
HND = 66,
MEM_FIXED = 0,
MEM_MOVEABLE = 2,
MEM_ZEROINIT = 64,
// PTR = 64, this enum value conflicts with MEM_ZEROINIT
_,
pub fn initFlags(o: struct {
HND: u1 = 0,
MEM_FIXED: u1 = 0,
MEM_MOVEABLE: u1 = 0,
MEM_ZEROINIT: u1 = 0,
}) GLOBAL_ALLOC_FLAGS {
return @intToEnum(GLOBAL_ALLOC_FLAGS,
(if (o.HND == 1) @enumToInt(GLOBAL_ALLOC_FLAGS.HND) else 0)
| (if (o.MEM_FIXED == 1) @enumToInt(GLOBAL_ALLOC_FLAGS.MEM_FIXED) else 0)
| (if (o.MEM_MOVEABLE == 1) @enumToInt(GLOBAL_ALLOC_FLAGS.MEM_MOVEABLE) else 0)
| (if (o.MEM_ZEROINIT == 1) @enumToInt(GLOBAL_ALLOC_FLAGS.MEM_ZEROINIT) else 0)
);
}
};
pub const GHND = GLOBAL_ALLOC_FLAGS.HND;
pub const GMEM_FIXED = GLOBAL_ALLOC_FLAGS.MEM_FIXED;
pub const GMEM_MOVEABLE = GLOBAL_ALLOC_FLAGS.MEM_MOVEABLE;
pub const GMEM_ZEROINIT = GLOBAL_ALLOC_FLAGS.MEM_ZEROINIT;
pub const GPTR = GLOBAL_ALLOC_FLAGS.MEM_ZEROINIT;
pub const PAGE_TYPE = enum(u32) {
PRIVATE = 131072,
MAPPED = 262144,
IMAGE = 16777216,
_,
pub fn initFlags(o: struct {
PRIVATE: u1 = 0,
MAPPED: u1 = 0,
IMAGE: u1 = 0,
}) PAGE_TYPE {
return @intToEnum(PAGE_TYPE,
(if (o.PRIVATE == 1) @enumToInt(PAGE_TYPE.PRIVATE) else 0)
| (if (o.MAPPED == 1) @enumToInt(PAGE_TYPE.MAPPED) else 0)
| (if (o.IMAGE == 1) @enumToInt(PAGE_TYPE.IMAGE) else 0)
);
}
};
pub const MEM_PRIVATE = PAGE_TYPE.PRIVATE;
pub const MEM_MAPPED = PAGE_TYPE.MAPPED;
pub const MEM_IMAGE = PAGE_TYPE.IMAGE;
// TODO: this type has a FreeFunc 'HeapDestroy', what can Zig do with this information?
pub const HeapHandle = *opaque{};
pub const PROCESS_HEAP_ENTRY = extern struct {
lpData: ?*anyopaque,
cbData: u32,
cbOverhead: u8,
iRegionIndex: u8,
wFlags: u16,
Anonymous: extern union {
Block: extern struct {
hMem: ?HANDLE,
dwReserved: [3]u32,
},
Region: extern struct {
dwCommittedSize: u32,
dwUnCommittedSize: u32,
lpFirstBlock: ?*anyopaque,
lpLastBlock: ?*anyopaque,
},
},
};
pub const HEAP_SUMMARY = extern struct {
cb: u32,
cbAllocated: usize,
cbCommitted: usize,
cbReserved: usize,
cbMaxReserve: usize,
};
pub const MEMORY_RESOURCE_NOTIFICATION_TYPE = enum(i32) {
LowMemoryResourceNotification = 0,
HighMemoryResourceNotification = 1,
};
pub const LowMemoryResourceNotification = MEMORY_RESOURCE_NOTIFICATION_TYPE.LowMemoryResourceNotification;
pub const HighMemoryResourceNotification = MEMORY_RESOURCE_NOTIFICATION_TYPE.HighMemoryResourceNotification;
pub const WIN32_MEMORY_RANGE_ENTRY = extern struct {
VirtualAddress: ?*anyopaque,
NumberOfBytes: usize,
};
pub const PBAD_MEMORY_CALLBACK_ROUTINE = fn(
) callconv(@import("std").os.windows.WINAPI) void;
pub const OFFER_PRIORITY = enum(i32) {
VeryLow = 1,
Low = 2,
BelowNormal = 3,
Normal = 4,
};
pub const VmOfferPriorityVeryLow = OFFER_PRIORITY.VeryLow;
pub const VmOfferPriorityLow = OFFER_PRIORITY.Low;
pub const VmOfferPriorityBelowNormal = OFFER_PRIORITY.BelowNormal;
pub const VmOfferPriorityNormal = OFFER_PRIORITY.Normal;
pub const WIN32_MEMORY_INFORMATION_CLASS = enum(i32) {
o = 0,
};
pub const MemoryRegionInfo = WIN32_MEMORY_INFORMATION_CLASS.o;
pub const WIN32_MEMORY_REGION_INFORMATION = extern struct {
AllocationBase: ?*anyopaque,
AllocationProtect: u32,
Anonymous: extern union {
Flags: u32,
Anonymous: extern struct {
_bitfield: u32,
},
},
RegionSize: usize,
CommitSize: usize,
};
pub const WIN32_MEMORY_PARTITION_INFORMATION_CLASS = enum(i32) {
Info = 0,
DedicatedMemoryInfo = 1,
};
pub const MemoryPartitionInfo = WIN32_MEMORY_PARTITION_INFORMATION_CLASS.Info;
pub const MemoryPartitionDedicatedMemoryInfo = WIN32_MEMORY_PARTITION_INFORMATION_CLASS.DedicatedMemoryInfo;
pub const WIN32_MEMORY_PARTITION_INFORMATION = extern struct {
Flags: u32,
NumaNode: u32,
Channel: u32,
NumberOfNumaNodes: u32,
ResidentAvailablePages: u64,
CommittedPages: u64,
CommitLimit: u64,
PeakCommitment: u64,
TotalNumberOfPages: u64,
AvailablePages: u64,
ZeroPages: u64,
FreePages: u64,
StandbyPages: u64,
Reserved: [16]u64,
MaximumCommitLimit: u64,
Reserved2: u64,
PartitionId: u32,
};
pub const MEMORY_BASIC_INFORMATION32 = extern struct {
BaseAddress: u32,
AllocationBase: u32,
AllocationProtect: PAGE_PROTECTION_FLAGS,
RegionSize: u32,
State: VIRTUAL_ALLOCATION_TYPE,
Protect: PAGE_PROTECTION_FLAGS,
Type: PAGE_TYPE,
};
pub const MEMORY_BASIC_INFORMATION64 = extern struct {
BaseAddress: u64,
AllocationBase: u64,
AllocationProtect: PAGE_PROTECTION_FLAGS,
__alignment1: u32,
RegionSize: u64,
State: VIRTUAL_ALLOCATION_TYPE,
Protect: PAGE_PROTECTION_FLAGS,
Type: PAGE_TYPE,
__alignment2: u32,
};
pub const CFG_CALL_TARGET_INFO = extern struct {
Offset: usize,
Flags: usize,
};
pub const MEM_EXTENDED_PARAMETER_TYPE = enum(i32) {
InvalidType = 0,
AddressRequirements = 1,
NumaNode = 2,
PartitionHandle = 3,
UserPhysicalHandle = 4,
AttributeFlags = 5,
ImageMachine = 6,
Max = 7,
};
pub const MemExtendedParameterInvalidType = MEM_EXTENDED_PARAMETER_TYPE.InvalidType;
pub const MemExtendedParameterAddressRequirements = MEM_EXTENDED_PARAMETER_TYPE.AddressRequirements;
pub const MemExtendedParameterNumaNode = MEM_EXTENDED_PARAMETER_TYPE.NumaNode;
pub const MemExtendedParameterPartitionHandle = MEM_EXTENDED_PARAMETER_TYPE.PartitionHandle;
pub const MemExtendedParameterUserPhysicalHandle = MEM_EXTENDED_PARAMETER_TYPE.UserPhysicalHandle;
pub const MemExtendedParameterAttributeFlags = MEM_EXTENDED_PARAMETER_TYPE.AttributeFlags;
pub const MemExtendedParameterImageMachine = MEM_EXTENDED_PARAMETER_TYPE.ImageMachine;
pub const MemExtendedParameterMax = MEM_EXTENDED_PARAMETER_TYPE.Max;
pub const MEM_EXTENDED_PARAMETER = extern struct {
Anonymous1: extern struct {
_bitfield: u64,
},
Anonymous2: extern union {
ULong64: u64,
Pointer: ?*anyopaque,
Size: usize,
Handle: ?HANDLE,
ULong: u32,
},
};
pub const HEAP_INFORMATION_CLASS = enum(i32) {
CompatibilityInformation = 0,
EnableTerminationOnCorruption = 1,
OptimizeResources = 3,
Tag = 7,
};
pub const HeapCompatibilityInformation = HEAP_INFORMATION_CLASS.CompatibilityInformation;
pub const HeapEnableTerminationOnCorruption = HEAP_INFORMATION_CLASS.EnableTerminationOnCorruption;
pub const HeapOptimizeResources = HEAP_INFORMATION_CLASS.OptimizeResources;
pub const HeapTag = HEAP_INFORMATION_CLASS.Tag;
pub const PSECURE_MEMORY_CACHE_CALLBACK = fn(
// TODO: what to do with BytesParamIndex 1?
Addr: ?*anyopaque,
Range: usize,
) callconv(@import("std").os.windows.WINAPI) BOOLEAN;
pub const MEMORY_BASIC_INFORMATION = switch(@import("../zig.zig").arch) {
.X64, .Arm64 => extern struct {
BaseAddress: ?*anyopaque,
AllocationBase: ?*anyopaque,
AllocationProtect: PAGE_PROTECTION_FLAGS,
PartitionId: u16,
RegionSize: usize,
State: VIRTUAL_ALLOCATION_TYPE,
Protect: PAGE_PROTECTION_FLAGS,
Type: PAGE_TYPE,
},
.X86 => extern struct {
BaseAddress: ?*anyopaque,
AllocationBase: ?*anyopaque,
AllocationProtect: PAGE_PROTECTION_FLAGS,
RegionSize: usize,
State: VIRTUAL_ALLOCATION_TYPE,
Protect: PAGE_PROTECTION_FLAGS,
Type: PAGE_TYPE,
},
};
//--------------------------------------------------------------------------------
// Section: Functions (106)
//--------------------------------------------------------------------------------
// TODO: this type is limited to platform 'windows5.1.2600'
pub extern "KERNEL32" fn HeapCreate(
flOptions: HEAP_FLAGS,
dwInitialSize: usize,
dwMaximumSize: usize,
) callconv(@import("std").os.windows.WINAPI) ?HeapHandle;
// TODO: this type is limited to platform 'windows5.1.2600'
pub extern "KERNEL32" fn HeapDestroy(
hHeap: ?HeapHandle,
) callconv(@import("std").os.windows.WINAPI) BOOL;
// TODO: this type is limited to platform 'windows5.1.2600'
pub extern "KERNEL32" fn HeapAlloc(
hHeap: ?HeapHandle,
dwFlags: HEAP_FLAGS,
dwBytes: usize,
) callconv(@import("std").os.windows.WINAPI) ?*anyopaque;
// TODO: this type is limited to platform 'windows5.1.2600'
pub extern "KERNEL32" fn HeapReAlloc(
hHeap: ?HeapHandle,
dwFlags: HEAP_FLAGS,
lpMem: ?*anyopaque,
dwBytes: usize,
) callconv(@import("std").os.windows.WINAPI) ?*anyopaque;
// TODO: this type is limited to platform 'windows5.1.2600'
pub extern "KERNEL32" fn HeapFree(
hHeap: ?HeapHandle,
dwFlags: HEAP_FLAGS,
lpMem: ?*anyopaque,
) callconv(@import("std").os.windows.WINAPI) BOOL;
// TODO: this type is limited to platform 'windows5.1.2600'
pub extern "KERNEL32" fn HeapSize(
hHeap: ?HeapHandle,
dwFlags: HEAP_FLAGS,
lpMem: ?*const anyopaque,
) callconv(@import("std").os.windows.WINAPI) usize;
// TODO: this type is limited to platform 'windows5.1.2600'
pub extern "KERNEL32" fn GetProcessHeap(
) callconv(@import("std").os.windows.WINAPI) ?HeapHandle;
// TODO: this type is limited to platform 'windows5.1.2600'
pub extern "KERNEL32" fn HeapCompact(
hHeap: ?HeapHandle,
dwFlags: HEAP_FLAGS,
) callconv(@import("std").os.windows.WINAPI) usize;
// TODO: this type is limited to platform 'windows5.1.2600'
pub extern "KERNEL32" fn HeapSetInformation(
HeapHandle: ?HeapHandle,
HeapInformationClass: HEAP_INFORMATION_CLASS,
// TODO: what to do with BytesParamIndex 3?
HeapInformation: ?*anyopaque,
HeapInformationLength: usize,
) callconv(@import("std").os.windows.WINAPI) BOOL;
// TODO: this type is limited to platform 'windows5.1.2600'
pub extern "KERNEL32" fn HeapValidate(
hHeap: ?HeapHandle,
dwFlags: HEAP_FLAGS,
lpMem: ?*const anyopaque,
) callconv(@import("std").os.windows.WINAPI) BOOL;
pub extern "KERNEL32" fn HeapSummary(
hHeap: ?HANDLE,
dwFlags: u32,
lpSummary: ?*HEAP_SUMMARY,
) callconv(@import("std").os.windows.WINAPI) BOOL;
// TODO: this type is limited to platform 'windows5.1.2600'
pub extern "KERNEL32" fn GetProcessHeaps(
NumberOfHeaps: u32,
ProcessHeaps: [*]?HeapHandle,
) callconv(@import("std").os.windows.WINAPI) u32;
// TODO: this type is limited to platform 'windows5.1.2600'
pub extern "KERNEL32" fn HeapLock(
hHeap: ?HeapHandle,
) callconv(@import("std").os.windows.WINAPI) BOOL;
// TODO: this type is limited to platform 'windows5.1.2600'
pub extern "KERNEL32" fn HeapUnlock(
hHeap: ?HeapHandle,
) callconv(@import("std").os.windows.WINAPI) BOOL;
// TODO: this type is limited to platform 'windows5.1.2600'
pub extern "KERNEL32" fn HeapWalk(
hHeap: ?HeapHandle,
lpEntry: ?*PROCESS_HEAP_ENTRY,
) callconv(@import("std").os.windows.WINAPI) BOOL;
// TODO: this type is limited to platform 'windows5.1.2600'
pub extern "KERNEL32" fn HeapQueryInformation(
HeapHandle: ?HeapHandle,
HeapInformationClass: HEAP_INFORMATION_CLASS,
// TODO: what to do with BytesParamIndex 3?
HeapInformation: ?*anyopaque,
HeapInformationLength: usize,
ReturnLength: ?*usize,
) callconv(@import("std").os.windows.WINAPI) BOOL;
// TODO: this type is limited to platform 'windows5.1.2600'
pub extern "KERNEL32" fn VirtualAlloc(
lpAddress: ?*anyopaque,
dwSize: usize,
flAllocationType: VIRTUAL_ALLOCATION_TYPE,
flProtect: PAGE_PROTECTION_FLAGS,
) callconv(@import("std").os.windows.WINAPI) ?*anyopaque;
// TODO: this type is limited to platform 'windows5.1.2600'
pub extern "KERNEL32" fn VirtualProtect(
lpAddress: ?*anyopaque,
dwSize: usize,
flNewProtect: PAGE_PROTECTION_FLAGS,
lpflOldProtect: ?*PAGE_PROTECTION_FLAGS,
) callconv(@import("std").os.windows.WINAPI) BOOL;
// TODO: this type is limited to platform 'windows5.1.2600'
pub extern "KERNEL32" fn VirtualFree(
lpAddress: ?*anyopaque,
dwSize: usize,
dwFreeType: VIRTUAL_FREE_TYPE,
) callconv(@import("std").os.windows.WINAPI) BOOL;
// TODO: this type is limited to platform 'windows5.1.2600'
pub extern "KERNEL32" fn VirtualQuery(
lpAddress: ?*const anyopaque,
// TODO: what to do with BytesParamIndex 2?
lpBuffer: ?*MEMORY_BASIC_INFORMATION,
dwLength: usize,
) callconv(@import("std").os.windows.WINAPI) usize;
// TODO: this type is limited to platform 'windows5.1.2600'
pub extern "KERNEL32" fn VirtualAllocEx(
hProcess: ?HANDLE,
lpAddress: ?*anyopaque,
dwSize: usize,
flAllocationType: VIRTUAL_ALLOCATION_TYPE,
flProtect: PAGE_PROTECTION_FLAGS,
) callconv(@import("std").os.windows.WINAPI) ?*anyopaque;
// TODO: this type is limited to platform 'windows5.1.2600'
pub extern "KERNEL32" fn VirtualProtectEx(
hProcess: ?HANDLE,
lpAddress: ?*anyopaque,
dwSize: usize,
flNewProtect: PAGE_PROTECTION_FLAGS,
lpflOldProtect: ?*PAGE_PROTECTION_FLAGS,
) callconv(@import("std").os.windows.WINAPI) BOOL;
// TODO: this type is limited to platform 'windows5.1.2600'
pub extern "KERNEL32" fn VirtualQueryEx(
hProcess: ?HANDLE,
lpAddress: ?*const anyopaque,
// TODO: what to do with BytesParamIndex 3?
lpBuffer: ?*MEMORY_BASIC_INFORMATION,
dwLength: usize,
) callconv(@import("std").os.windows.WINAPI) usize;
// TODO: this type is limited to platform 'windows5.1.2600'
pub extern "KERNEL32" fn CreateFileMappingW(
hFile: ?HANDLE,
lpFileMappingAttributes: ?*SECURITY_ATTRIBUTES,
flProtect: PAGE_PROTECTION_FLAGS,
dwMaximumSizeHigh: u32,
dwMaximumSizeLow: u32,
lpName: ?[*:0]const u16,
) callconv(@import("std").os.windows.WINAPI) ?HANDLE;
// TODO: this type is limited to platform 'windows5.1.2600'
pub extern "KERNEL32" fn OpenFileMappingW(
dwDesiredAccess: u32,
bInheritHandle: BOOL,
lpName: ?[*:0]const u16,
) callconv(@import("std").os.windows.WINAPI) ?HANDLE;
// TODO: this type is limited to platform 'windows5.1.2600'
pub extern "KERNEL32" fn MapViewOfFile(
hFileMappingObject: ?HANDLE,
dwDesiredAccess: FILE_MAP,
dwFileOffsetHigh: u32,
dwFileOffsetLow: u32,
dwNumberOfBytesToMap: usize,
) callconv(@import("std").os.windows.WINAPI) ?*anyopaque;
// TODO: this type is limited to platform 'windows5.1.2600'
pub extern "KERNEL32" fn MapViewOfFileEx(
hFileMappingObject: ?HANDLE,
dwDesiredAccess: FILE_MAP,
dwFileOffsetHigh: u32,
dwFileOffsetLow: u32,
dwNumberOfBytesToMap: usize,
lpBaseAddress: ?*anyopaque,
) callconv(@import("std").os.windows.WINAPI) ?*anyopaque;
// TODO: this type is limited to platform 'windows5.1.2600'
pub extern "KERNEL32" fn VirtualFreeEx(
hProcess: ?HANDLE,
lpAddress: ?*anyopaque,
dwSize: usize,
dwFreeType: VIRTUAL_FREE_TYPE,
) callconv(@import("std").os.windows.WINAPI) BOOL;
// TODO: this type is limited to platform 'windows5.1.2600'
pub extern "KERNEL32" fn FlushViewOfFile(
lpBaseAddress: ?*const anyopaque,
dwNumberOfBytesToFlush: usize,
) callconv(@import("std").os.windows.WINAPI) BOOL;
// TODO: this type is limited to platform 'windows5.1.2600'
pub extern "KERNEL32" fn UnmapViewOfFile(
lpBaseAddress: ?*const anyopaque,
) callconv(@import("std").os.windows.WINAPI) BOOL;
// TODO: this type is limited to platform 'windows6.0.6000'
pub extern "KERNEL32" fn GetLargePageMinimum(
) callconv(@import("std").os.windows.WINAPI) usize;
// TODO: this type is limited to platform 'windows6.0.6000'
pub extern "KERNEL32" fn GetProcessWorkingSetSizeEx(
hProcess: ?HANDLE,
lpMinimumWorkingSetSize: ?*usize,
lpMaximumWorkingSetSize: ?*usize,
Flags: ?*u32,
) callconv(@import("std").os.windows.WINAPI) BOOL;
// TODO: this type is limited to platform 'windows6.0.6000'
pub extern "KERNEL32" fn SetProcessWorkingSetSizeEx(
hProcess: ?HANDLE,
dwMinimumWorkingSetSize: usize,
dwMaximumWorkingSetSize: usize,
Flags: u32,
) callconv(@import("std").os.windows.WINAPI) BOOL;
// TODO: this type is limited to platform 'windows5.1.2600'
pub extern "KERNEL32" fn VirtualLock(
lpAddress: ?*anyopaque,
dwSize: usize,
) callconv(@import("std").os.windows.WINAPI) BOOL;
// TODO: this type is limited to platform 'windows5.1.2600'
pub extern "KERNEL32" fn VirtualUnlock(
lpAddress: ?*anyopaque,
dwSize: usize,
) callconv(@import("std").os.windows.WINAPI) BOOL;
// TODO: this type is limited to platform 'windows5.1.2600'
pub extern "KERNEL32" fn GetWriteWatch(
dwFlags: u32,
lpBaseAddress: ?*anyopaque,
dwRegionSize: usize,
lpAddresses: ?[*]?*anyopaque,
lpdwCount: ?*usize,
lpdwGranularity: ?*u32,
) callconv(@import("std").os.windows.WINAPI) u32;
// TODO: this type is limited to platform 'windows5.1.2600'
pub extern "KERNEL32" fn ResetWriteWatch(
lpBaseAddress: ?*anyopaque,
dwRegionSize: usize,
) callconv(@import("std").os.windows.WINAPI) u32;
// TODO: this type is limited to platform 'windows5.1.2600'
pub extern "KERNEL32" fn CreateMemoryResourceNotification(
NotificationType: MEMORY_RESOURCE_NOTIFICATION_TYPE,
) callconv(@import("std").os.windows.WINAPI) ?HANDLE;
// TODO: this type is limited to platform 'windows5.1.2600'
pub extern "KERNEL32" fn QueryMemoryResourceNotification(
ResourceNotificationHandle: ?HANDLE,
ResourceState: ?*BOOL,
) callconv(@import("std").os.windows.WINAPI) BOOL;
// TODO: this type is limited to platform 'windows6.0.6000'
pub extern "KERNEL32" fn GetSystemFileCacheSize(
lpMinimumFileCacheSize: ?*usize,
lpMaximumFileCacheSize: ?*usize,
lpFlags: ?*u32,
) callconv(@import("std").os.windows.WINAPI) BOOL;
// TODO: this type is limited to platform 'windows6.0.6000'
pub extern "KERNEL32" fn SetSystemFileCacheSize(
MinimumFileCacheSize: usize,
MaximumFileCacheSize: usize,
Flags: u32,
) callconv(@import("std").os.windows.WINAPI) BOOL;
// TODO: this type is limited to platform 'windows6.0.6000'
pub extern "KERNEL32" fn CreateFileMappingNumaW(
hFile: ?HANDLE,
lpFileMappingAttributes: ?*SECURITY_ATTRIBUTES,
flProtect: PAGE_PROTECTION_FLAGS,
dwMaximumSizeHigh: u32,
dwMaximumSizeLow: u32,
lpName: ?[*:0]const u16,
nndPreferred: u32,
) callconv(@import("std").os.windows.WINAPI) ?HANDLE;
// TODO: this type is limited to platform 'windows8.0'
pub extern "KERNEL32" fn PrefetchVirtualMemory(
hProcess: ?HANDLE,
NumberOfEntries: usize,
VirtualAddresses: [*]WIN32_MEMORY_RANGE_ENTRY,
Flags: u32,
) callconv(@import("std").os.windows.WINAPI) BOOL;
// TODO: this type is limited to platform 'windows8.0'
pub extern "KERNEL32" fn CreateFileMappingFromApp(
hFile: ?HANDLE,
SecurityAttributes: ?*SECURITY_ATTRIBUTES,
PageProtection: PAGE_PROTECTION_FLAGS,
MaximumSize: u64,
Name: ?[*:0]const u16,
) callconv(@import("std").os.windows.WINAPI) ?HANDLE;
// TODO: this type is limited to platform 'windows8.0'
pub extern "KERNEL32" fn MapViewOfFileFromApp(
hFileMappingObject: ?HANDLE,
DesiredAccess: FILE_MAP,
FileOffset: u64,
NumberOfBytesToMap: usize,
) callconv(@import("std").os.windows.WINAPI) ?*anyopaque;
// TODO: this type is limited to platform 'windows8.0'
pub extern "KERNEL32" fn UnmapViewOfFileEx(
BaseAddress: ?*anyopaque,
UnmapFlags: UNMAP_VIEW_OF_FILE_FLAGS,
) callconv(@import("std").os.windows.WINAPI) BOOL;
// TODO: this type is limited to platform 'windows5.1.2600'
pub extern "KERNEL32" fn AllocateUserPhysicalPages(
hProcess: ?HANDLE,
NumberOfPages: ?*usize,
PageArray: [*]usize,
) callconv(@import("std").os.windows.WINAPI) BOOL;
// TODO: this type is limited to platform 'windows5.1.2600'
pub extern "KERNEL32" fn FreeUserPhysicalPages(
hProcess: ?HANDLE,
NumberOfPages: ?*usize,
PageArray: [*]usize,
) callconv(@import("std").os.windows.WINAPI) BOOL;
// TODO: this type is limited to platform 'windows5.1.2600'
pub extern "KERNEL32" fn MapUserPhysicalPages(
VirtualAddress: ?*anyopaque,
NumberOfPages: usize,
PageArray: ?[*]usize,
) callconv(@import("std").os.windows.WINAPI) BOOL;
// TODO: this type is limited to platform 'windows6.0.6000'
pub extern "KERNEL32" fn AllocateUserPhysicalPagesNuma(
hProcess: ?HANDLE,
NumberOfPages: ?*usize,
PageArray: [*]usize,
nndPreferred: u32,
) callconv(@import("std").os.windows.WINAPI) BOOL;
// TODO: this type is limited to platform 'windows6.0.6000'
pub extern "KERNEL32" fn VirtualAllocExNuma(
hProcess: ?HANDLE,
lpAddress: ?*anyopaque,
dwSize: usize,
flAllocationType: VIRTUAL_ALLOCATION_TYPE,
flProtect: u32,
nndPreferred: u32,
) callconv(@import("std").os.windows.WINAPI) ?*anyopaque;
// TODO: this type is limited to platform 'windows8.0'
pub extern "KERNEL32" fn GetMemoryErrorHandlingCapabilities(
Capabilities: ?*u32,
) callconv(@import("std").os.windows.WINAPI) BOOL;
// TODO: this type is limited to platform 'windows8.0'
pub extern "KERNEL32" fn RegisterBadMemoryNotification(
Callback: ?PBAD_MEMORY_CALLBACK_ROUTINE,
) callconv(@import("std").os.windows.WINAPI) ?*anyopaque;
// TODO: this type is limited to platform 'windows8.0'
pub extern "KERNEL32" fn UnregisterBadMemoryNotification(
RegistrationHandle: ?*anyopaque,
) callconv(@import("std").os.windows.WINAPI) BOOL;
// TODO: this type is limited to platform 'windows8.1'
pub extern "KERNEL32" fn OfferVirtualMemory(
VirtualAddress: [*]u8,
Size: usize,
Priority: OFFER_PRIORITY,
) callconv(@import("std").os.windows.WINAPI) u32;
// TODO: this type is limited to platform 'windows8.1'
pub extern "KERNEL32" fn ReclaimVirtualMemory(
VirtualAddress: [*]const u8,
Size: usize,
) callconv(@import("std").os.windows.WINAPI) u32;
// TODO: this type is limited to platform 'windows8.1'
pub extern "KERNEL32" fn DiscardVirtualMemory(
VirtualAddress: [*]u8,
Size: usize,
) callconv(@import("std").os.windows.WINAPI) u32;
// TODO: this type is limited to platform 'windows10.0.10240'
pub extern "api-ms-win-core-memory-l1-1-3" fn SetProcessValidCallTargets(
hProcess: ?HANDLE,
VirtualAddress: ?*anyopaque,
RegionSize: usize,
NumberOfOffsets: u32,
OffsetInformation: [*]CFG_CALL_TARGET_INFO,
) callconv(@import("std").os.windows.WINAPI) BOOL;
pub extern "api-ms-win-core-memory-l1-1-7" fn SetProcessValidCallTargetsForMappedView(
Process: ?HANDLE,
VirtualAddress: ?*anyopaque,
RegionSize: usize,
NumberOfOffsets: u32,
OffsetInformation: [*]CFG_CALL_TARGET_INFO,
Section: ?HANDLE,
ExpectedFileOffset: u64,
) callconv(@import("std").os.windows.WINAPI) BOOL;
// TODO: this type is limited to platform 'windows10.0.10240'
pub extern "api-ms-win-core-memory-l1-1-3" fn VirtualAllocFromApp(
BaseAddress: ?*anyopaque,
Size: usize,
AllocationType: VIRTUAL_ALLOCATION_TYPE,
Protection: u32,
) callconv(@import("std").os.windows.WINAPI) ?*anyopaque;
// TODO: this type is limited to platform 'windows10.0.10240'
pub extern "api-ms-win-core-memory-l1-1-3" fn VirtualProtectFromApp(
Address: ?*anyopaque,
Size: usize,
NewProtection: u32,
OldProtection: ?*u32,
) callconv(@import("std").os.windows.WINAPI) BOOL;
// TODO: this type is limited to platform 'windows10.0.10240'
pub extern "api-ms-win-core-memory-l1-1-3" fn OpenFileMappingFromApp(
DesiredAccess: u32,
InheritHandle: BOOL,
Name: ?[*:0]const u16,
) callconv(@import("std").os.windows.WINAPI) ?HANDLE;
// TODO: this type is limited to platform 'windows10.0.14393'
pub extern "api-ms-win-core-memory-l1-1-4" fn QueryVirtualMemoryInformation(
Process: ?HANDLE,
VirtualAddress: ?*const anyopaque,
MemoryInformationClass: WIN32_MEMORY_INFORMATION_CLASS,
// TODO: what to do with BytesParamIndex 4?
MemoryInformation: ?*anyopaque,
MemoryInformationSize: usize,
ReturnSize: ?*usize,
) callconv(@import("std").os.windows.WINAPI) BOOL;
// TODO: this type is limited to platform 'windows10.0.15063'
pub extern "api-ms-win-core-memory-l1-1-5" fn MapViewOfFileNuma2(
FileMappingHandle: ?HANDLE,
ProcessHandle: ?HANDLE,
Offset: u64,
BaseAddress: ?*anyopaque,
ViewSize: usize,
AllocationType: u32,
PageProtection: u32,
PreferredNode: u32,
) callconv(@import("std").os.windows.WINAPI) ?*anyopaque;
// TODO: this type is limited to platform 'windows10.0.15063'
pub extern "api-ms-win-core-memory-l1-1-5" fn UnmapViewOfFile2(
Process: ?HANDLE,
BaseAddress: ?*anyopaque,
UnmapFlags: UNMAP_VIEW_OF_FILE_FLAGS,
) callconv(@import("std").os.windows.WINAPI) BOOL;
pub extern "api-ms-win-core-memory-l1-1-5" fn VirtualUnlockEx(
Process: ?HANDLE,
Address: ?*anyopaque,
Size: usize,
) callconv(@import("std").os.windows.WINAPI) BOOL;
// TODO: this type is limited to platform 'windows10.0.10240'
pub extern "api-ms-win-core-memory-l1-1-6" fn VirtualAlloc2(
Process: ?HANDLE,
BaseAddress: ?*anyopaque,
Size: usize,
AllocationType: VIRTUAL_ALLOCATION_TYPE,
PageProtection: u32,
ExtendedParameters: ?[*]MEM_EXTENDED_PARAMETER,
ParameterCount: u32,
) callconv(@import("std").os.windows.WINAPI) ?*anyopaque;
// TODO: this type is limited to platform 'windows10.0.17134'
pub extern "api-ms-win-core-memory-l1-1-6" fn MapViewOfFile3(
FileMapping: ?HANDLE,
Process: ?HANDLE,
BaseAddress: ?*anyopaque,
Offset: u64,
ViewSize: usize,
AllocationType: VIRTUAL_ALLOCATION_TYPE,
PageProtection: u32,
ExtendedParameters: ?[*]MEM_EXTENDED_PARAMETER,
ParameterCount: u32,
) callconv(@import("std").os.windows.WINAPI) ?*anyopaque;
// TODO: this type is limited to platform 'windows10.0.10240'
pub extern "api-ms-win-core-memory-l1-1-6" fn VirtualAlloc2FromApp(
Process: ?HANDLE,
BaseAddress: ?*anyopaque,
Size: usize,
AllocationType: VIRTUAL_ALLOCATION_TYPE,
PageProtection: u32,
ExtendedParameters: ?[*]MEM_EXTENDED_PARAMETER,
ParameterCount: u32,
) callconv(@import("std").os.windows.WINAPI) ?*anyopaque;
// TODO: this type is limited to platform 'windows10.0.10240'
pub extern "api-ms-win-core-memory-l1-1-6" fn MapViewOfFile3FromApp(
FileMapping: ?HANDLE,
Process: ?HANDLE,
BaseAddress: ?*anyopaque,
Offset: u64,
ViewSize: usize,
AllocationType: VIRTUAL_ALLOCATION_TYPE,
PageProtection: u32,
ExtendedParameters: ?[*]MEM_EXTENDED_PARAMETER,
ParameterCount: u32,
) callconv(@import("std").os.windows.WINAPI) ?*anyopaque;
pub extern "api-ms-win-core-memory-l1-1-7" fn CreateFileMapping2(
File: ?HANDLE,
SecurityAttributes: ?*SECURITY_ATTRIBUTES,
DesiredAccess: u32,
PageProtection: PAGE_PROTECTION_FLAGS,
AllocationAttributes: u32,
MaximumSize: u64,
Name: ?[*:0]const u16,
ExtendedParameters: ?[*]MEM_EXTENDED_PARAMETER,
ParameterCount: u32,
) callconv(@import("std").os.windows.WINAPI) ?HANDLE;
pub extern "api-ms-win-core-memory-l1-1-8" fn AllocateUserPhysicalPages2(
ObjectHandle: ?HANDLE,
NumberOfPages: ?*usize,
PageArray: [*]usize,
ExtendedParameters: ?[*]MEM_EXTENDED_PARAMETER,
ExtendedParameterCount: u32,
) callconv(@import("std").os.windows.WINAPI) BOOL;
pub extern "api-ms-win-core-memory-l1-1-8" fn OpenDedicatedMemoryPartition(
Partition: ?HANDLE,
DedicatedMemoryTypeId: u64,
DesiredAccess: u32,
InheritHandle: BOOL,
) callconv(@import("std").os.windows.WINAPI) ?HANDLE;
pub extern "api-ms-win-core-memory-l1-1-8" fn QueryPartitionInformation(
Partition: ?HANDLE,
PartitionInformationClass: WIN32_MEMORY_PARTITION_INFORMATION_CLASS,
// TODO: what to do with BytesParamIndex 3?
PartitionInformation: ?*anyopaque,
PartitionInformationLength: u32,
) callconv(@import("std").os.windows.WINAPI) BOOL;
pub extern "KERNEL32" fn RtlCompareMemory(
Source1: ?*const anyopaque,
Source2: ?*const anyopaque,
Length: usize,
) callconv(@import("std").os.windows.WINAPI) usize;
pub extern "ntdll" fn RtlCrc32(
// TODO: what to do with BytesParamIndex 1?
Buffer: ?*const anyopaque,
Size: usize,
InitialCrc: u32,
) callconv(@import("std").os.windows.WINAPI) u32;
pub extern "ntdll" fn RtlCrc64(
// TODO: what to do with BytesParamIndex 1?
Buffer: ?*const anyopaque,
Size: usize,
InitialCrc: u64,
) callconv(@import("std").os.windows.WINAPI) u64;
pub extern "ntdll" fn RtlIsZeroMemory(
Buffer: ?*anyopaque,
Length: usize,
) callconv(@import("std").os.windows.WINAPI) BOOLEAN;
// TODO: this type is limited to platform 'windows5.1.2600'
pub extern "KERNEL32" fn GlobalAlloc(
uFlags: GLOBAL_ALLOC_FLAGS,
dwBytes: usize,
) callconv(@import("std").os.windows.WINAPI) isize;
// TODO: this type is limited to platform 'windows5.1.2600'
pub extern "KERNEL32" fn GlobalReAlloc(
hMem: isize,
dwBytes: usize,
uFlags: u32,
) callconv(@import("std").os.windows.WINAPI) isize;
// TODO: this type is limited to platform 'windows5.1.2600'
pub extern "KERNEL32" fn GlobalSize(
hMem: isize,
) callconv(@import("std").os.windows.WINAPI) usize;
// TODO: this type is limited to platform 'windows5.1.2600'
pub extern "KERNEL32" fn GlobalUnlock(
hMem: isize,
) callconv(@import("std").os.windows.WINAPI) BOOL;
// TODO: this type is limited to platform 'windows5.1.2600'
pub extern "KERNEL32" fn GlobalLock(
hMem: isize,
) callconv(@import("std").os.windows.WINAPI) ?*anyopaque;
// TODO: this type is limited to platform 'windows5.1.2600'
pub extern "KERNEL32" fn GlobalFlags(
hMem: isize,
) callconv(@import("std").os.windows.WINAPI) u32;
// TODO: this type is limited to platform 'windows5.1.2600'
pub extern "KERNEL32" fn GlobalHandle(
pMem: ?*const anyopaque,
) callconv(@import("std").os.windows.WINAPI) isize;
// TODO: this type is limited to platform 'windows5.1.2600'
pub extern "KERNEL32" fn GlobalFree(
hMem: isize,
) callconv(@import("std").os.windows.WINAPI) isize;
// TODO: this type is limited to platform 'windows5.1.2600'
pub extern "KERNEL32" fn LocalAlloc(
uFlags: LOCAL_ALLOC_FLAGS,
uBytes: usize,
) callconv(@import("std").os.windows.WINAPI) isize;
// TODO: this type is limited to platform 'windows5.1.2600'
pub extern "KERNEL32" fn LocalReAlloc(
hMem: isize,
uBytes: usize,
uFlags: u32,
) callconv(@import("std").os.windows.WINAPI) isize;
// TODO: this type is limited to platform 'windows5.1.2600'
pub extern "KERNEL32" fn LocalLock(
hMem: isize,
) callconv(@import("std").os.windows.WINAPI) ?*anyopaque;
// TODO: this type is limited to platform 'windows5.1.2600'
pub extern "KERNEL32" fn LocalHandle(
pMem: ?*const anyopaque,
) callconv(@import("std").os.windows.WINAPI) isize;
// TODO: this type is limited to platform 'windows5.1.2600'
pub extern "KERNEL32" fn LocalUnlock(
hMem: isize,
) callconv(@import("std").os.windows.WINAPI) BOOL;
// TODO: this type is limited to platform 'windows5.1.2600'
pub extern "KERNEL32" fn LocalSize(
hMem: isize,
) callconv(@import("std").os.windows.WINAPI) usize;
// TODO: this type is limited to platform 'windows5.1.2600'
pub extern "KERNEL32" fn LocalFlags(
hMem: isize,
) callconv(@import("std").os.windows.WINAPI) u32;
// TODO: this type is limited to platform 'windows5.1.2600'
pub extern "KERNEL32" fn LocalFree(
hMem: isize,
) callconv(@import("std").os.windows.WINAPI) isize;
// TODO: this type is limited to platform 'windows5.1.2600'
pub extern "KERNEL32" fn CreateFileMappingA(
hFile: ?HANDLE,
lpFileMappingAttributes: ?*SECURITY_ATTRIBUTES,
flProtect: PAGE_PROTECTION_FLAGS,
dwMaximumSizeHigh: u32,
dwMaximumSizeLow: u32,
lpName: ?[*:0]const u8,
) callconv(@import("std").os.windows.WINAPI) ?HANDLE;
// TODO: this type is limited to platform 'windows6.0.6000'
pub extern "KERNEL32" fn CreateFileMappingNumaA(
hFile: ?HANDLE,
lpFileMappingAttributes: ?*SECURITY_ATTRIBUTES,
flProtect: PAGE_PROTECTION_FLAGS,
dwMaximumSizeHigh: u32,
dwMaximumSizeLow: u32,
lpName: ?[*:0]const u8,
nndPreferred: u32,
) callconv(@import("std").os.windows.WINAPI) ?HANDLE;
// TODO: this type is limited to platform 'windows5.1.2600'
pub extern "KERNEL32" fn OpenFileMappingA(
dwDesiredAccess: u32,
bInheritHandle: BOOL,
lpName: ?[*:0]const u8,
) callconv(@import("std").os.windows.WINAPI) ?HANDLE;
// TODO: this type is limited to platform 'windows6.0.6000'
pub extern "KERNEL32" fn MapViewOfFileExNuma(
hFileMappingObject: ?HANDLE,
dwDesiredAccess: FILE_MAP,
dwFileOffsetHigh: u32,
dwFileOffsetLow: u32,
dwNumberOfBytesToMap: usize,
lpBaseAddress: ?*anyopaque,
nndPreferred: u32,
) callconv(@import("std").os.windows.WINAPI) ?*anyopaque;
// TODO: this type is limited to platform 'windows5.1.2600'
pub extern "KERNEL32" fn IsBadReadPtr(
lp: ?*const anyopaque,
ucb: usize,
) callconv(@import("std").os.windows.WINAPI) BOOL;
// TODO: this type is limited to platform 'windows5.1.2600'
pub extern "KERNEL32" fn IsBadWritePtr(
lp: ?*anyopaque,
ucb: usize,
) callconv(@import("std").os.windows.WINAPI) BOOL;
// TODO: this type is limited to platform 'windows5.1.2600'
pub extern "KERNEL32" fn IsBadCodePtr(
lpfn: ?FARPROC,
) callconv(@import("std").os.windows.WINAPI) BOOL;
// TODO: this type is limited to platform 'windows5.1.2600'
pub extern "KERNEL32" fn IsBadStringPtrA(
lpsz: ?[*:0]const u8,
ucchMax: usize,
) callconv(@import("std").os.windows.WINAPI) BOOL;
// TODO: this type is limited to platform 'windows5.1.2600'
pub extern "KERNEL32" fn IsBadStringPtrW(
lpsz: ?[*:0]const u16,
ucchMax: usize,
) callconv(@import("std").os.windows.WINAPI) BOOL;
// TODO: this type is limited to platform 'windows5.1.2600'
pub extern "KERNEL32" fn MapUserPhysicalPagesScatter(
VirtualAddresses: [*]?*anyopaque,
NumberOfPages: usize,
PageArray: ?[*]usize,
) callconv(@import("std").os.windows.WINAPI) BOOL;
// TODO: this type is limited to platform 'windows6.0.6000'
pub extern "KERNEL32" fn AddSecureMemoryCacheCallback(
pfnCallBack: ?PSECURE_MEMORY_CACHE_CALLBACK,
) callconv(@import("std").os.windows.WINAPI) BOOL;
// TODO: this type is limited to platform 'windows6.0.6000'
pub extern "KERNEL32" fn RemoveSecureMemoryCacheCallback(
pfnCallBack: ?PSECURE_MEMORY_CACHE_CALLBACK,
) callconv(@import("std").os.windows.WINAPI) BOOL;
//--------------------------------------------------------------------------------
// Section: Unicode Aliases (4)
//--------------------------------------------------------------------------------
const thismodule = @This();
pub usingnamespace switch (@import("../zig.zig").unicode_mode) {
.ansi => struct {
pub const CreateFileMapping = thismodule.CreateFileMappingA;
pub const OpenFileMapping = thismodule.OpenFileMappingA;
pub const CreateFileMappingNuma = thismodule.CreateFileMappingNumaA;
pub const IsBadStringPtr = thismodule.IsBadStringPtrA;
},
.wide => struct {
pub const CreateFileMapping = thismodule.CreateFileMappingW;
pub const OpenFileMapping = thismodule.OpenFileMappingW;
pub const CreateFileMappingNuma = thismodule.CreateFileMappingNumaW;
pub const IsBadStringPtr = thismodule.IsBadStringPtrW;
},
.unspecified => if (@import("builtin").is_test) struct {
pub const CreateFileMapping = *opaque{};
pub const OpenFileMapping = *opaque{};
pub const CreateFileMappingNuma = *opaque{};
pub const IsBadStringPtr = *opaque{};
} else struct {
pub const CreateFileMapping = @compileError("'CreateFileMapping' requires that UNICODE be set to true or false in the root module");
pub const OpenFileMapping = @compileError("'OpenFileMapping' requires that UNICODE be set to true or false in the root module");
pub const CreateFileMappingNuma = @compileError("'CreateFileMappingNuma' requires that UNICODE be set to true or false in the root module");
pub const IsBadStringPtr = @compileError("'IsBadStringPtr' requires that UNICODE be set to true or false in the root module");
},
};
//--------------------------------------------------------------------------------
// Section: Imports (7)
//--------------------------------------------------------------------------------
const BOOL = @import("../foundation.zig").BOOL;
const BOOLEAN = @import("../foundation.zig").BOOLEAN;
const FARPROC = @import("../foundation.zig").FARPROC;
const HANDLE = @import("../foundation.zig").HANDLE;
const PSTR = @import("../foundation.zig").PSTR;
const PWSTR = @import("../foundation.zig").PWSTR;
const SECURITY_ATTRIBUTES = @import("../security.zig").SECURITY_ATTRIBUTES;
test {
// The following '_ = <FuncPtrType>' lines are a workaround for https://github.com/ziglang/zig/issues/4476
if (@hasDecl(@This(), "PBAD_MEMORY_CALLBACK_ROUTINE")) { _ = PBAD_MEMORY_CALLBACK_ROUTINE; }
if (@hasDecl(@This(), "PSECURE_MEMORY_CACHE_CALLBACK")) { _ = PSECURE_MEMORY_CACHE_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;
}
}
}
//--------------------------------------------------------------------------------
// Section: SubModules (1)
//--------------------------------------------------------------------------------
pub const non_volatile = @import("memory/non_volatile.zig");
|
win32/system/memory.zig
|
const std = @import("std");
/// Exports the C interface for SDL
pub const c = @import("binding/sdl.zig");
pub const image = @import("image.zig");
pub const gl = @import("gl.zig");
pub const Error = error{SdlError};
const log = std.log.scoped(.sdl2);
pub fn makeError() error{SdlError} {
if (c.SDL_GetError()) |ptr| {
log.debug("{s}\n", .{
std.mem.span(ptr),
});
}
return error.SdlError;
}
pub const Rectangle = extern struct {
x: c_int,
y: c_int,
width: c_int,
height: c_int,
fn getSdlPtr(r: Rectangle) *const c.SDL_Rect {
return @ptrCast(*const c.SDL_Rect, &r);
}
};
pub const Point = extern struct {
x: c_int,
y: c_int,
};
pub const Size = extern struct {
width: c_int,
height: c_int,
};
pub const Color = extern struct {
pub const black = rgb(0x00, 0x00, 0x00);
pub const white = rgb(0xFF, 0xFF, 0xFF);
pub const red = rgb(0xFF, 0x00, 0x00);
pub const green = rgb(0x00, 0xFF, 0x00);
pub const blue = rgb(0x00, 0x00, 0xFF);
pub const magenta = rgb(0xFF, 0x00, 0xFF);
pub const cyan = rgb(0x00, 0xFF, 0xFF);
pub const yellow = rgb(0xFF, 0xFF, 0x00);
r: u8,
g: u8,
b: u8,
a: u8,
/// returns a initialized color struct with alpha = 255
pub fn rgb(r: u8, g: u8, b: u8) Color {
return Color{ .r = r, .g = g, .b = b, .a = 255 };
}
/// returns a initialized color struct
pub fn rgba(r: u8, g: u8, b: u8, a: u8) Color {
return Color{ .r = r, .g = g, .b = b, .a = a };
}
/// parses a hex string color literal.
/// allowed formats are:
/// - `RGB`
/// - `RGBA`
/// - `#RGB`
/// - `#RGBA`
/// - `RRGGBB`
/// - `#RRGGBB`
/// - `RRGGBBAA`
/// - `#RRGGBBAA`
pub fn parse(str: []const u8) error{
UnknownFormat,
InvalidCharacter,
Overflow,
}!Color {
switch (str.len) {
// RGB
3 => {
const r = try std.fmt.parseInt(u8, str[0..1], 16);
const g = try std.fmt.parseInt(u8, str[1..2], 16);
const b = try std.fmt.parseInt(u8, str[2..3], 16);
return rgb(
r | (r << 4),
g | (g << 4),
b | (b << 4),
);
},
// #RGB, RGBA
4 => {
if (str[0] == '#')
return parse(str[1..]);
const r = try std.fmt.parseInt(u8, str[0..1], 16);
const g = try std.fmt.parseInt(u8, str[1..2], 16);
const b = try std.fmt.parseInt(u8, str[2..3], 16);
const a = try std.fmt.parseInt(u8, str[3..4], 16);
// bit-expand the patters to a uniform range
return rgba(
r | (r << 4),
g | (g << 4),
b | (b << 4),
a | (a << 4),
);
},
// #RGBA
5 => return parse(str[1..]),
// RRGGBB
6 => {
const r = try std.fmt.parseInt(u8, str[0..2], 16);
const g = try std.fmt.parseInt(u8, str[2..4], 16);
const b = try std.fmt.parseInt(u8, str[4..6], 16);
return rgb(r, g, b);
},
// #RRGGBB
7 => return parse(str[1..]),
// RRGGBBAA
8 => {
const r = try std.fmt.parseInt(u8, str[0..2], 16);
const g = try std.fmt.parseInt(u8, str[2..4], 16);
const b = try std.fmt.parseInt(u8, str[4..6], 16);
const a = try std.fmt.parseInt(u8, str[6..8], 16);
return rgba(r, g, b, a);
},
// #RRGGBBAA
9 => return parse(str[1..]),
else => return error.UnknownFormat,
}
}
};
pub const InitFlags = struct {
pub const everything = InitFlags{
.video = true,
.audio = true,
.timer = true,
.joystick = true,
.haptic = true,
.game_controller = true,
.events = true,
};
video: bool = false,
audio: bool = false,
timer: bool = false,
joystick: bool = false,
haptic: bool = false,
game_controller: bool = false,
events: bool = false,
};
pub fn init(flags: InitFlags) !void {
var cflags: c_uint = 0;
if (flags.video) cflags |= c.SDL_INIT_VIDEO;
if (flags.audio) cflags |= c.SDL_INIT_AUDIO;
if (flags.timer) cflags |= c.SDL_INIT_TIMER;
if (flags.joystick) cflags |= c.SDL_INIT_JOYSTICK;
if (flags.haptic) cflags |= c.SDL_INIT_HAPTIC;
if (flags.game_controller) cflags |= c.SDL_INIT_GAMECONTROLLER;
if (flags.events) cflags |= c.SDL_INIT_EVENTS;
if (c.SDL_Init(cflags) < 0)
return makeError();
}
pub fn quit() void {
c.SDL_Quit();
}
pub fn getError() ?[]const u8 {
if (c.SDL_GetError()) |err| {
return std.mem.spanZ(err);
} else {
return null;
}
}
pub const Window = struct {
ptr: *c.SDL_Window,
pub fn fromID(wid: u32) ?Window {
return if (c.SDL_GetWindowFromID(wid)) |ptr|
Window{ .ptr = ptr }
else
null;
}
pub fn destroy(w: Window) void {
c.SDL_DestroyWindow(w.ptr);
}
pub fn getSize(w: Window) Size {
var s: Size = undefined;
c.SDL_GetWindowSize(w.ptr, &s.width, &s.height);
return s;
}
pub fn getSurface(w: Window) !Surface {
var surface_ptr = c.SDL_GetWindowSurface(w.ptr) orelse return makeError();
return Surface{.ptr = surface_ptr};
}
pub fn updateSurface(w: Window) !void {
if(c.SDL_UpdateWindowSurface(w.ptr) < 0) return makeError();
}
};
pub const WindowPosition = union(enum) {
default: void,
centered: void,
absolute: c_int,
};
pub const WindowFlags = struct {
/// fullscreen window
fullscreen: bool = false, // SDL_WINDOW_FULLSCREEN,
/// fullscreen window at the current desktop resolution,
fullscreen_desktop: bool = false, // SDL_WINDOW_FULLSCREEN_DESKTOP
/// window usable with OpenGL context
opengl: bool = false, // SDL_WINDOW_OPENGL,
/// window is visible,
shown: bool = false, // SDL_WINDOW_SHOWN,
/// window is not visible
hidden: bool = false, // SDL_WINDOW_HIDDEN,
/// no window decoration
borderless: bool = false, // SDL_WINDOW_BORDERLESS,
/// window can be resized
resizable: bool = false, // SDL_WINDOW_RESIZABLE,
/// window is minimized
minimized: bool = false, // SDL_WINDOW_MINIMIZED,
/// window is maximized
maximized: bool = false, // SDL_WINDOW_MAXIMIZED,
/// window has grabbed input focus
input_grabbed: bool = false, // SDL_WINDOW_INPUT_GRABBED,
/// window has input focus
input_focus: bool = false, //SDL_WINDOW_INPUT_FOCUS,
/// window has mouse focus
mouse_focus: bool = false, //SDL_WINDOW_MOUSE_FOCUS,
/// window not created by SDL
foreign: bool = false, //SDL_WINDOW_FOREIGN,
/// window should be created in high-DPI mode if supported (>= SDL 2.0.1)
allow_high_dpi: bool = false, //SDL_WINDOW_ALLOW_HIGHDPI,
/// window has mouse captured (unrelated to INPUT_GRABBED, >= SDL 2.0.4)
mouse_capture: bool = false, //SDL_WINDOW_MOUSE_CAPTURE,
/// window should always be above others (X11 only, >= SDL 2.0.5)
always_on_top: bool = false, //SDL_WINDOW_ALWAYS_ON_TOP,
/// window should not be added to the taskbar (X11 only, >= SDL 2.0.5)
skip_taskbar: bool = false, //SDL_WINDOW_SKIP_TASKBAR,
/// window should be treated as a utility window (X11 only, >= SDL 2.0.5)
utility: bool = false, //SDL_WINDOW_UTILITY,
/// window should be treated as a tooltip (X11 only, >= SDL 2.0.5)
tooltip: bool = false, //SDL_WINDOW_TOOLTIP,
/// window should be treated as a popup menu (X11 only, >= SDL 2.0.5)
popup_menu: bool = false, //SDL_WINDOW_POPUP_MENU,
// fn fromInteger(val: c_uint) WindowFlags {
// // TODO: Implement
// @panic("niy");
// }
fn toInteger(wf: WindowFlags) c_int {
var val: c_int = 0;
if (wf.fullscreen) val |= c.SDL_WINDOW_FULLSCREEN;
if (wf.fullscreen_desktop) val |= c.SDL_WINDOW_FULLSCREEN_DESKTOP;
if (wf.opengl) val |= c.SDL_WINDOW_OPENGL;
if (wf.shown) val |= c.SDL_WINDOW_SHOWN;
if (wf.hidden) val |= c.SDL_WINDOW_HIDDEN;
if (wf.borderless) val |= c.SDL_WINDOW_BORDERLESS;
if (wf.resizable) val |= c.SDL_WINDOW_RESIZABLE;
if (wf.minimized) val |= c.SDL_WINDOW_MINIMIZED;
if (wf.maximized) val |= c.SDL_WINDOW_MAXIMIZED;
if (wf.input_grabbed) val |= c.SDL_WINDOW_INPUT_GRABBED;
if (wf.input_focus) val |= c.SDL_WINDOW_INPUT_FOCUS;
if (wf.mouse_focus) val |= c.SDL_WINDOW_MOUSE_FOCUS;
if (wf.foreign) val |= c.SDL_WINDOW_FOREIGN;
if (wf.allow_high_dpi) val |= c.SDL_WINDOW_ALLOW_HIGHDPI;
if (wf.mouse_capture) val |= c.SDL_WINDOW_MOUSE_CAPTURE;
if (wf.always_on_top) val |= c.SDL_WINDOW_ALWAYS_ON_TOP;
if (wf.skip_taskbar) val |= c.SDL_WINDOW_SKIP_TASKBAR;
if (wf.utility) val |= c.SDL_WINDOW_UTILITY;
if (wf.tooltip) val |= c.SDL_WINDOW_TOOLTIP;
if (wf.popup_menu) val |= c.SDL_WINDOW_POPUP_MENU;
return val;
}
};
pub fn createWindow(
title: [:0]const u8,
x: WindowPosition,
y: WindowPosition,
width: usize,
height: usize,
flags: WindowFlags,
) !Window {
return Window{
.ptr = c.SDL_CreateWindow(
title,
switch (x) {
.default => c.SDL_WINDOWPOS_UNDEFINED_MASK,
.centered => c.SDL_WINDOWPOS_CENTERED_MASK,
.absolute => |v| v,
},
switch (y) {
.default => c.SDL_WINDOWPOS_UNDEFINED_MASK,
.centered => c.SDL_WINDOWPOS_CENTERED_MASK,
.absolute => |v| v,
},
@intCast(c_int, width),
@intCast(c_int, height),
@intCast(u32, flags.toInteger()),
) orelse return makeError(),
};
}
pub const Surface = struct {
ptr: *c.SDL_Surface,
pub fn destroy(s: Surface) void {
c.SDL_FreeSurface(s.ptr);
}
pub fn setColorKey(s: Surface, flag: c_int, color: Color) !void {
if(c.SDL_SetColorKey(s.ptr, flag, c.SDL_MapRGBA(s.ptr.*.format, color.r, color.g, color.b, color.a)) < 0) return makeError();
}
pub fn fillRect(s: *Surface, rect: ?*Rectangle, color: Color) !void {
const rect_ptr = if(rect) |_rect| _rect.getSdlPtr() else null;
if(c.SDL_FillRect(s.ptr, rect_ptr, c.SDL_MapRGBA(s.ptr.*.format, color.r, color.g, color.b, color.a)) < 0) return makeError();
}
};
pub const Renderer = struct {
ptr: *c.SDL_Renderer,
pub fn destroy(ren: Renderer) void {
c.SDL_DestroyRenderer(ren.ptr);
}
pub fn clear(ren: Renderer) !void {
if (c.SDL_RenderClear(ren.ptr) != 0)
return makeError();
}
pub fn present(ren: Renderer) void {
c.SDL_RenderPresent(ren.ptr);
}
pub fn copy(ren: Renderer, tex: Texture, dstRect: ?Rectangle, srcRect: ?Rectangle) !void {
if (c.SDL_RenderCopy(ren.ptr, tex.ptr, if (srcRect) |r| r.getSdlPtr() else null, if (dstRect) |r| r.getSdlPtr() else null) < 0)
return makeError();
}
pub fn drawLine(ren: Renderer, x0: i32, y0: i32, x1: i32, y1: i32) !void {
if (c.SDL_RenderDrawLine(ren.ptr, x0, y0, x1, y1) < 0)
return makeError();
}
pub fn drawPoint(ren: Renderer, x: i32, y: i32) !void {
if (c.SDL_RenderDrawPoint(ren.ptr, x, y) < 0)
return makeError();
}
pub fn fillRect(ren: Renderer, rect: Rectangle) !void {
if (c.SDL_RenderFillRect(ren.ptr, rect.getSdlPtr()) < 0)
return makeError();
}
pub fn drawRect(ren: Renderer, rect: Rectangle) !void {
if (c.SDL_RenderDrawRect(ren.ptr, rect.getSdlPtr()) < 0)
return makeError();
}
pub fn setColor(ren: Renderer, color: Color) !void {
if (c.SDL_SetRenderDrawColor(ren.ptr, color.r, color.g, color.b, color.a) < 0)
return makeError();
}
pub fn setColorRGB(ren: Renderer, r: u8, g: u8, b: u8) !void {
if (c.SDL_SetRenderDrawColor(ren.ptr, r, g, b, 255) < 0)
return makeError();
}
pub fn setColorRGBA(ren: Renderer, r: u8, g: u8, b: u8, a: u8) !void {
if (c.SDL_SetRenderDrawColor(ren.ptr, r, g, b, a) < 0)
return makeError();
}
pub fn setDrawBlendMode(ren: Renderer, blendMode: c.SDL_BlendMode) !void {
if (c.SDL_SetRenderDrawBlendMode(ren.ptr, blendMode) < 0)
return makeError();
}
};
pub const RendererFlags = struct {
software: bool = false,
accelerated: bool = false,
present_vsync: bool = false,
target_texture: bool = false,
fn toInteger(rf: RendererFlags) c_int {
var val: c_int = 0;
if (rf.software) val |= c.SDL_RENDERER_SOFTWARE;
if (rf.accelerated) val |= c.SDL_RENDERER_ACCELERATED;
if (rf.present_vsync) val |= c.SDL_RENDERER_PRESENTVSYNC;
if (rf.target_texture) val |= c.SDL_RENDERER_TARGETTEXTURE;
return val;
}
};
pub fn createRenderer(window: Window, index: ?u31, flags: RendererFlags) !Renderer {
return Renderer{
.ptr = c.SDL_CreateRenderer(
window.ptr,
if (index) |idx| @intCast(c_int, idx) else -1,
@intCast(u32, flags.toInteger()),
) orelse return makeError(),
};
}
pub const Texture = struct {
pub const PixelData = struct {
texture: *c.SDL_Texture,
pixels: [*]u8,
stride: usize,
pub fn scanline(self: *@This(), y: usize, comptime Pixel: type) [*]Pixel {
return @ptrCast([*]Pixel, self.pixels + y * self.stride);
}
pub fn release(self: *@This()) void {
c.SDL_UnlockTexture(self.texture);
self.* = undefined;
}
};
ptr: *c.SDL_Texture,
pub fn destroy(tex: Texture) void {
c.SDL_DestroyTexture(tex.ptr);
}
pub fn lock(tex: Texture, rectangle: ?Rectangle) !PixelData {
var ptr: ?*c_void = undefined;
var pitch: c_int = undefined;
if (c.SDL_LockTexture(
tex.ptr,
if (rectangle) |rect| rect.getSdlPtr() else null,
&ptr,
&pitch,
) != 0) {
return makeError();
}
return PixelData{
.texture = tex.ptr,
.stride = @intCast(usize, pitch),
.pixels = @ptrCast([*]u8, ptr),
};
}
pub fn update(texture: Texture, pixels: []const u8, pitch: usize, rectangle: ?Rectangle) !void {
if (c.SDL_UpdateTexture(
texture.ptr,
if (rectangle) |rect| rect.getSdlPtr() else null,
pixels.ptr,
@intCast(c_int, pitch),
) != 0)
return makeError();
}
const Info = struct {
width: usize,
height: usize,
access: Access,
format: Format,
};
pub fn query(tex: Texture) !Info {
var format: u32 = undefined;
var w: c_int = undefined;
var h: c_int = undefined;
var access: c_int = undefined;
if (c.SDL_QueryTexture(tex.ptr, &format, &access, &w, &h) < 0)
return makeError();
return Info{
.width = @intCast(usize, w),
.height = @intCast(usize, h),
.access = @intToEnum(Access, access),
.format = @intToEnum(Format, format),
};
}
pub fn resetColorMod(tex: Texture) !void {
try tex.setColorMod(Color.white);
}
pub fn setColorMod(tex: Texture, color: Color) !void {
if (c.SDL_SetTextureColorMod(tex.ptr, color.r, color.g, color.b) < 0)
return makeError();
if (c.SDL_SetTextureAlphaMod(tex.ptr, color.a) < 0)
return makeError();
}
pub fn setColorModRGB(tex: Texture, r: u8, g: u8, b: u8) !void {
try tex.setColorMod(Color.rgb(r, g, b));
}
pub fn setColorModRGBA(tex: Texture, r: u8, g: u8, b: u8, a: u8) !void {
try tex.setColorMod(Color.rgba(r, g, b, a));
}
pub const Format = enum(u32) {
index1_lsb = c.SDL_PIXELFORMAT_INDEX1LSB,
index1_msb = c.SDL_PIXELFORMAT_INDEX1MSB,
index4_lsb = c.SDL_PIXELFORMAT_INDEX4LSB,
index4_msb = c.SDL_PIXELFORMAT_INDEX4MSB,
index8 = c.SDL_PIXELFORMAT_INDEX8,
rgb332 = c.SDL_PIXELFORMAT_RGB332,
rgb444 = c.SDL_PIXELFORMAT_RGB444,
rgb555 = c.SDL_PIXELFORMAT_RGB555,
bgr555 = c.SDL_PIXELFORMAT_BGR555,
argb4444 = c.SDL_PIXELFORMAT_ARGB4444,
rgba4444 = c.SDL_PIXELFORMAT_RGBA4444,
abgr4444 = c.SDL_PIXELFORMAT_ABGR4444,
bgra4444 = c.SDL_PIXELFORMAT_BGRA4444,
argb1555 = c.SDL_PIXELFORMAT_ARGB1555,
rgba5551 = c.SDL_PIXELFORMAT_RGBA5551,
abgr1555 = c.SDL_PIXELFORMAT_ABGR1555,
bgra5551 = c.SDL_PIXELFORMAT_BGRA5551,
rgb565 = c.SDL_PIXELFORMAT_RGB565,
bgr565 = c.SDL_PIXELFORMAT_BGR565,
rgb24 = c.SDL_PIXELFORMAT_RGB24,
bgr24 = c.SDL_PIXELFORMAT_BGR24,
rgb888 = c.SDL_PIXELFORMAT_RGB888,
rgbx8888 = c.SDL_PIXELFORMAT_RGBX8888,
bgr888 = c.SDL_PIXELFORMAT_BGR888,
bgrx8888 = c.SDL_PIXELFORMAT_BGRX8888,
argb8888 = c.SDL_PIXELFORMAT_ARGB8888,
rgba8888 = c.SDL_PIXELFORMAT_RGBA8888,
abgr8888 = c.SDL_PIXELFORMAT_ABGR8888,
bgra8888 = c.SDL_PIXELFORMAT_BGRA8888,
argb2101010 = c.SDL_PIXELFORMAT_ARGB2101010,
yv12 = c.SDL_PIXELFORMAT_YV12,
iyuv = c.SDL_PIXELFORMAT_IYUV,
yuy2 = c.SDL_PIXELFORMAT_YUY2,
uyvy = c.SDL_PIXELFORMAT_UYVY,
yvyu = c.SDL_PIXELFORMAT_YVYU,
nv12 = c.SDL_PIXELFORMAT_NV12,
nv21 = c.SDL_PIXELFORMAT_NV21,
externalOES = c.SDL_PIXELFORMAT_EXTERNAL_OES,
};
pub const Access = enum(c_int) {
static = c.SDL_TEXTUREACCESS_STATIC,
streaming = c.SDL_TEXTUREACCESS_STREAMING,
target = c.SDL_TEXTUREACCESS_TARGET,
};
};
pub fn createTexture(renderer: Renderer, format: Texture.Format, access: Texture.Access, width: usize, height: usize) !Texture {
const texptr = c.SDL_CreateTexture(
renderer.ptr,
@enumToInt(format),
@enumToInt(access),
@intCast(c_int, width),
@intCast(c_int, height),
) orelse return makeError();
return Texture{
.ptr = texptr,
};
}
pub fn createTextureFromSurface(renderer: Renderer, surface: Surface) !Texture {
const texptr = c.SDL_CreateTextureFromSurface(
renderer.ptr,
surface.ptr,
) orelse return makeError();
return Texture{
.ptr = texptr,
};
}
pub const WindowEvent = struct {
const Type = enum(u8) {
none = c.SDL_WINDOWEVENT_NONE,
shown = c.SDL_WINDOWEVENT_SHOWN,
hidden = c.SDL_WINDOWEVENT_HIDDEN,
exposed = c.SDL_WINDOWEVENT_EXPOSED,
moved = c.SDL_WINDOWEVENT_MOVED,
resized = c.SDL_WINDOWEVENT_RESIZED,
size_changed = c.SDL_WINDOWEVENT_SIZE_CHANGED,
minimized = c.SDL_WINDOWEVENT_MINIMIZED,
maximized = c.SDL_WINDOWEVENT_MAXIMIZED,
restored = c.SDL_WINDOWEVENT_RESTORED,
enter = c.SDL_WINDOWEVENT_ENTER,
leave = c.SDL_WINDOWEVENT_LEAVE,
focus_gained = c.SDL_WINDOWEVENT_FOCUS_GAINED,
focus_lost = c.SDL_WINDOWEVENT_FOCUS_LOST,
close = c.SDL_WINDOWEVENT_CLOSE,
take_focus = c.SDL_WINDOWEVENT_TAKE_FOCUS,
hit_test = c.SDL_WINDOWEVENT_HIT_TEST,
_,
};
const Data = union(Type) {
shown: void,
hidden: void,
exposed: void,
moved: Point,
resized: Size,
size_changed: Size,
minimized: void,
maximized: void,
restored: void,
enter: void,
leave: void,
focus_gained: void,
focus_lost: void,
close: void,
take_focus: void,
hit_test: void,
none: void,
};
timestamp: u32,
window_id: u32,
type: Data,
fn fromNative(ev: c.SDL_WindowEvent) WindowEvent {
return WindowEvent{
.timestamp = ev.timestamp,
.window_id = ev.windowID,
.type = switch (@intToEnum(Type, ev.event)) {
.shown => Data{ .shown = {} },
.hidden => Data{ .hidden = {} },
.exposed => Data{ .exposed = {} },
.moved => Data{ .moved = Point{ .x = ev.data1, .y = ev.data2 } },
.resized => Data{ .resized = Size{ .width = ev.data1, .height = ev.data2 } },
.size_changed => Data{ .size_changed = Size{ .width = ev.data1, .height = ev.data2 } },
.minimized => Data{ .minimized = {} },
.maximized => Data{ .maximized = {} },
.restored => Data{ .restored = {} },
.enter => Data{ .enter = {} },
.leave => Data{ .leave = {} },
.focus_gained => Data{ .focus_gained = {} },
.focus_lost => Data{ .focus_lost = {} },
.close => Data{ .close = {} },
.take_focus => Data{ .take_focus = {} },
.hit_test => Data{ .hit_test = {} },
else => Data{ .none = {} },
},
};
}
};
pub const EventType = std.meta.Tag(Event);
pub const Event = union(enum) {
pub const CommonEvent = c.SDL_CommonEvent;
pub const DisplayEvent = c.SDL_DisplayEvent;
pub const KeyboardEvent = c.SDL_KeyboardEvent;
pub const TextEditingEvent = c.SDL_TextEditingEvent;
pub const TextInputEvent = c.SDL_TextInputEvent;
pub const MouseMotionEvent = c.SDL_MouseMotionEvent;
pub const MouseButtonEvent = c.SDL_MouseButtonEvent;
pub const MouseWheelEvent = c.SDL_MouseWheelEvent;
pub const JoyAxisEvent = c.SDL_JoyAxisEvent;
pub const JoyBallEvent = c.SDL_JoyBallEvent;
pub const JoyHatEvent = c.SDL_JoyHatEvent;
pub const JoyButtonEvent = c.SDL_JoyButtonEvent;
pub const JoyDeviceEvent = c.SDL_JoyDeviceEvent;
pub const ControllerAxisEvent = c.SDL_ControllerAxisEvent;
pub const ControllerButtonEvent = c.SDL_ControllerButtonEvent;
pub const ControllerDeviceEvent = c.SDL_ControllerDeviceEvent;
pub const AudioDeviceEvent = c.SDL_AudioDeviceEvent;
pub const SensorEvent = c.SDL_SensorEvent;
pub const QuitEvent = c.SDL_QuitEvent;
pub const UserEvent = c.SDL_UserEvent;
pub const SysWMEvent = c.SDL_SysWMEvent;
pub const TouchFingerEvent = c.SDL_TouchFingerEvent;
pub const MultiGestureEvent = c.SDL_MultiGestureEvent;
pub const DollarGestureEvent = c.SDL_DollarGestureEvent;
pub const DropEvent = c.SDL_DropEvent;
clip_board_update: CommonEvent,
app_did_enter_background: CommonEvent,
app_did_enter_foreground: CommonEvent,
app_will_enter_foreground: CommonEvent,
app_will_enter_background: CommonEvent,
app_low_memory: CommonEvent,
app_terminating: CommonEvent,
render_targets_reset: CommonEvent,
render_device_reset: CommonEvent,
key_map_changed: CommonEvent,
display: DisplayEvent,
window: WindowEvent,
key_down: KeyboardEvent,
key_up: KeyboardEvent,
text_editing: TextEditingEvent,
text_input: TextInputEvent,
mouse_motion: MouseMotionEvent,
mouse_button_down: MouseButtonEvent,
mouse_button_up: MouseButtonEvent,
mouse_wheel: MouseWheelEvent,
joy_axis_motion: JoyAxisEvent,
joy_ball_motion: JoyBallEvent,
joy_hat_motion: JoyHatEvent,
joy_button_down: JoyButtonEvent,
joy_button_up: JoyButtonEvent,
joy_device_added: JoyDeviceEvent,
joy_device_removed: JoyDeviceEvent,
controller_axis_motion: ControllerAxisEvent,
controller_button_down: ControllerButtonEvent,
controller_button_up: ControllerButtonEvent,
controller_device_added: ControllerDeviceEvent,
controller_device_removed: ControllerDeviceEvent,
controller_device_remapped: ControllerDeviceEvent,
audio_device_added: AudioDeviceEvent,
audio_device_removed: AudioDeviceEvent,
sensor_update: SensorEvent,
quit: QuitEvent,
sys_wm: SysWMEvent,
finger_down: TouchFingerEvent,
finger_up: TouchFingerEvent,
finger_motion: TouchFingerEvent,
multi_gesture: MultiGestureEvent,
dollar_gesture: DollarGestureEvent,
dollar_record: DollarGestureEvent,
drop_file: DropEvent,
drop_text: DropEvent,
drop_begin: DropEvent,
drop_complete: DropEvent,
// user: UserEvent,
pub fn from(raw: c.SDL_Event) Event {
return switch (raw.type) {
c.SDL_QUIT => Event{ .quit = raw.quit },
c.SDL_APP_TERMINATING => Event{ .app_terminating = raw.common },
c.SDL_APP_LOWMEMORY => Event{ .app_low_memory = raw.common },
c.SDL_APP_WILLENTERBACKGROUND => Event{ .app_will_enter_background = raw.common },
c.SDL_APP_DIDENTERBACKGROUND => Event{ .app_did_enter_background = raw.common },
c.SDL_APP_WILLENTERFOREGROUND => Event{ .app_will_enter_foreground = raw.common },
c.SDL_APP_DIDENTERFOREGROUND => Event{ .app_did_enter_foreground = raw.common },
c.SDL_DISPLAYEVENT => Event{ .display = raw.display },
c.SDL_WINDOWEVENT => Event{ .window = WindowEvent.fromNative(raw.window) },
c.SDL_SYSWMEVENT => Event{ .sys_wm = raw.syswm },
c.SDL_KEYDOWN => Event{ .key_down = raw.key },
c.SDL_KEYUP => Event{ .key_up = raw.key },
c.SDL_TEXTEDITING => Event{ .text_editing = raw.edit },
c.SDL_TEXTINPUT => Event{ .text_input = raw.text },
c.SDL_KEYMAPCHANGED => Event{ .key_map_changed = raw.common },
c.SDL_MOUSEMOTION => Event{ .mouse_motion = raw.motion },
c.SDL_MOUSEBUTTONDOWN => Event{ .mouse_button_down = raw.button },
c.SDL_MOUSEBUTTONUP => Event{ .mouse_button_up = raw.button },
c.SDL_MOUSEWHEEL => Event{ .mouse_wheel = raw.wheel },
c.SDL_JOYAXISMOTION => Event{ .joy_axis_motion = raw.jaxis },
c.SDL_JOYBALLMOTION => Event{ .joy_ball_motion = raw.jball },
c.SDL_JOYHATMOTION => Event{ .joy_hat_motion = raw.jhat },
c.SDL_JOYBUTTONDOWN => Event{ .joy_button_down = raw.jbutton },
c.SDL_JOYBUTTONUP => Event{ .joy_button_up = raw.jbutton },
c.SDL_JOYDEVICEADDED => Event{ .joy_device_added = raw.jdevice },
c.SDL_JOYDEVICEREMOVED => Event{ .joy_device_removed = raw.jdevice },
c.SDL_CONTROLLERAXISMOTION => Event{ .controller_axis_motion = raw.caxis },
c.SDL_CONTROLLERBUTTONDOWN => Event{ .controller_button_down = raw.cbutton },
c.SDL_CONTROLLERBUTTONUP => Event{ .controller_button_up = raw.cbutton },
c.SDL_CONTROLLERDEVICEADDED => Event{ .controller_device_added = raw.cdevice },
c.SDL_CONTROLLERDEVICEREMOVED => Event{ .controller_device_removed = raw.cdevice },
c.SDL_CONTROLLERDEVICEREMAPPED => Event{ .controller_device_remapped = raw.cdevice },
c.SDL_FINGERDOWN => Event{ .finger_down = raw.tfinger },
c.SDL_FINGERUP => Event{ .finger_up = raw.tfinger },
c.SDL_FINGERMOTION => Event{ .finger_motion = raw.tfinger },
c.SDL_DOLLARGESTURE => Event{ .dollar_gesture = raw.dgesture },
c.SDL_DOLLARRECORD => Event{ .dollar_record = raw.dgesture },
c.SDL_MULTIGESTURE => Event{ .multi_gesture = raw.mgesture },
c.SDL_CLIPBOARDUPDATE => Event{ .clip_board_update = raw.common },
c.SDL_DROPFILE => Event{ .drop_file = raw.drop },
c.SDL_DROPTEXT => Event{ .drop_text = raw.drop },
c.SDL_DROPBEGIN => Event{ .drop_begin = raw.drop },
c.SDL_DROPCOMPLETE => Event{ .drop_complete = raw.drop },
c.SDL_AUDIODEVICEADDED => Event{ .audio_device_added = raw.adevice },
c.SDL_AUDIODEVICEREMOVED => Event{ .audio_device_removed = raw.adevice },
c.SDL_SENSORUPDATE => Event{ .sensor_update = raw.sensor },
c.SDL_RENDER_TARGETS_RESET => Event{ .render_targets_reset = raw.common },
c.SDL_RENDER_DEVICE_RESET => Event{ .render_device_reset = raw.common },
else => @panic("Unsupported event type detected!"),
};
}
};
pub fn pollEvent() ?Event {
var ev: c.SDL_Event = undefined;
if (c.SDL_PollEvent(&ev) != 0)
return Event.from(ev);
return null;
}
pub fn pollNativeEvent() ?c.SDL_Event {
var ev: c.SDL_Event = undefined;
if (c.SDL_PollEvent(&ev) != 0)
return ev;
return null;
}
pub const MouseState = struct {
x: c_int,
y: c_int,
left: bool,
right: bool,
middle: bool,
extra1: bool,
extra2: bool,
};
pub fn getMouseState() MouseState {
var ms: MouseState = undefined;
const buttons = c.SDL_GetMouseState(&ms.x, &ms.y);
ms.left = ((buttons & 1) != 0);
ms.right = ((buttons & 4) != 0);
ms.middle = ((buttons & 2) != 0);
ms.extra1 = ((buttons & 8) != 0);
ms.extra2 = ((buttons & 16) != 0);
return ms;
}
pub const KeyboardState = struct {
states: []const u8,
pub fn isPressed(ks: KeyboardState, scanCode: c.SDL_Scancode) bool {
return ks.states[@intCast(usize, @enumToInt(scanCode))] != 0;
}
};
pub fn getKeyboardState() KeyboardState {
var len: c_int = undefined;
const slice = c.SDL_GetKeyboardState(&len);
return KeyboardState{
.states = slice[0..@intCast(usize, len)],
};
}
pub fn getTicks() usize {
return c.SDL_GetTicks();
}
pub fn delay(ms: u32) void {
c.SDL_Delay(ms);
}
test "platform independent declarations" {
std.testing.refAllDecls(@This());
}
|
src/lib.zig
|
const std = @import("std");
const debug = std.debug;
const mem = std.mem;
const ArrayList = std.ArrayList;
const Row = struct {
pub const Cell = struct {
column: *Column,
data: []const u8,
};
id: ?usize,
cells: ArrayList(Cell),
pub fn init(allocator: mem.Allocator, id: ?usize) Row {
return Row{
.id = id,
.cells = ArrayList(Cell).init(allocator),
};
}
pub fn appendCell(self: *Row, new_cell: Cell) !void {
try self.cells.append(new_cell);
}
};
pub const Column = struct {
name: []const u8,
allow_empty: bool = false,
max_len: usize = 255,
};
pub const DataTable = struct {
allocator: mem.Allocator,
current_id: ?usize = null,
columns: ArrayList(Column),
rows: ArrayList(Row),
pub fn init(allocator: mem.Allocator) DataTable {
return DataTable{
.allocator = allocator,
.columns = ArrayList(Column).init(allocator),
.rows = ArrayList(Row).init(allocator),
};
}
pub fn initWithIdColumn(allocator: mem.Allocator) !DataTable {
var self = DataTable.init(allocator);
self.current_id = 0;
try self.addSingleColumn(.{ .name = "Id", .allow_empty = false });
return self;
}
pub fn deinit(self: DataTable) void {
self.columns.deinit();
for (self.rows.items) |row| {
row.cells.deinit();
}
self.rows.deinit();
}
pub fn addSingleColumn(self: *DataTable, column: Column) !void {
try self.columns.append(column);
}
pub fn addManyColumns(self: *DataTable, columns: []const Column) !void {
for (columns) |column| {
try self.addSingleColumn(column);
}
}
pub fn totalColumns(self: *DataTable) usize {
return self.columns.items.len;
}
pub fn insertSingleData(self: *DataTable, single_data: []const []const u8) !void {
if (single_data.len > self.totalColumns()) return error.TooManyColumns;
var columns_index: usize = if (self.current_id == null) 0 else 1; // skip Id column if have
var row = Row.init(self.allocator, self.current_id);
for (single_data) |data| {
var current_column = &self.columns.items[columns_index];
if (!current_column.allow_empty and data.len == 0)
return error.EmptyData;
if (data.len > current_column.max_len)
return error.TooLongDataLength;
try row.appendCell(.{ .column = current_column, .data = data });
columns_index += 1;
}
try self.rows.append(row);
if (self.current_id) |*id| id.* += 1;
}
pub fn insertManyData(self: *DataTable, many_data: []const []const []const u8) !void {
for (many_data) |single_data| {
try self.insertSingleData(single_data[0..]);
}
}
pub fn isDataExistOnColumn(self: *DataTable, which_column: []const u8, which_data: []const u8) bool {
for (self.rows.items) |row| {
for (row.cells.items) |cell| {
if (mem.eql(u8, cell.column.name, which_column) and mem.eql(u8, cell.data, which_data))
return true;
}
}
return false;
}
pub fn searchData(self: *DataTable, which_column: []const u8, which_data: []const u8) ![][]const u8 {
var row_index: ?usize = null;
outer: for (self.rows.items) |row, i| {
for (row.cells.items) |cell| {
if (mem.eql(u8, cell.column.name, which_column) and mem.eql(u8, cell.data, which_data)) {
row_index = i;
break :outer;
}
}
}
if (row_index) |idx| {
var found_data = ArrayList([]const u8).init(self.allocator);
defer found_data.deinit();
for (self.rows.items[idx].cells.items) |cell| {
try found_data.append(cell.data);
}
return found_data.toOwnedSlice();
} else {
return error.DataNotFound;
}
}
pub fn selectColumnByNum(self: *DataTable, which_column_num: usize) ![][]const u8 {
if (which_column_num > self.totalColumns()) return error.ColumnNotFound;
if (self.rows.items.len == 0) return error.EmptyData;
var column_index = which_column_num - 1;
var data = ArrayList([]const u8).init(self.allocator);
defer data.deinit();
for (self.rows.items) |row| {
try data.append(row.cells.items[column_index].data);
}
return data.toOwnedSlice();
}
pub fn selectColumnByName(self: *DataTable, which_column: []const u8) ![][]const u8 {
var column_index: ?usize = null;
for (self.columns.items) |column, i| {
if (mem.eql(u8, column.name, which_column)) {
column_index = i;
break;
}
}
if (column_index) |idx| {
return self.selectColumnByNum(if (self.current_id == null) idx + 1 else idx);
} else {
return error.ColumnNotFound;
}
}
};
|
src/datatable.zig
|
const std = @import("std");
const mem = @import("mem.zig");
const scheduler = @import("scheduler.zig");
const thread = @import("thread.zig");
const Array = std.ArrayList;
const IntrusiveList = std.IntrusiveLinkedList;
const List = std.LinkedList;
const MailboxId = std.os.zen.MailboxId;
const Message = std.os.zen.Message;
const Thread = thread.Thread;
const ThreadQueue = thread.ThreadQueue;
// Structure representing a mailbox.
pub const Mailbox = struct {
messages: List(Message),
waiting_queue: IntrusiveList(Thread, "queue_link"),
// TODO: simplify once #679 is resolved.
////
// Initialize a mailbox.
//
// Returns:
// An empty mailbox.
//
pub fn init() Mailbox {
return Mailbox {
.messages = List(Message).init(),
.waiting_queue = ThreadQueue.init(),
};
}
};
// Keep track of the registered ports.
var ports = Array(&Mailbox).init(&mem.allocator);
////
// Create a new port with the given ID.
//
// Arguments:
// id: The index of the port.
//
pub fn createPort(id: u16) void {
// TODO: check that the ID is not reserved.
if (ports.len <= id) {
ports.resize(id + 1) catch unreachable;
// FIXME: fairly dangerous - leaves a lot of uninitialized Mailboxes.
}
const mailbox = mem.allocator.create(Mailbox) catch unreachable;
*mailbox = Mailbox.init();
ports.items[id] = mailbox;
}
////
// Asynchronously send a message to a mailbox.
//
// Arguments:
// message: Pointer to the message to be sent.
//
pub fn send(message: &const Message) void {
// NOTE: We need a copy in kernel space, because we
// are potentially switching address spaces.
const message_copy = processOutgoingMessage(message); // FIXME: this should be volatile?
const mailbox = getMailbox(message.receiver);
if (mailbox.waiting_queue.popFirst()) |first| {
// There's a thread waiting to receive.
const receiving_thread = first.toData();
scheduler.new(receiving_thread);
*receiving_thread.message_destination = message_copy;
// Wake it and deliver the message.
} else {
// No thread is waiting to receive.
const node = mailbox.messages.createNode(message_copy, &mem.allocator) catch unreachable;
mailbox.messages.append(node);
// Put the message in the queue.
}
}
////
// Receive a message from a mailbox.
// Block if there are no messages.
//
// Arguments:
// destination: Address where to deliver the message.
//
pub fn receive(destination: &Message) void {
// TODO: validation, i.e. check if the thread has the right permissions.
const mailbox = getMailbox(destination.receiver);
if (mailbox.messages.popFirst()) |first| {
// There's a message in the queue, deliver immediately.
const message = first.data;
*destination = message;
mem.allocator.destroy(first);
} else {
// No message in the queue, block the thread.
const current_thread = ??scheduler.dequeue();
current_thread.message_destination = destination;
mailbox.waiting_queue.append(¤t_thread.queue_link);
}
}
////
// Get the mailbox associated with the given mailbox ID.
//
// Arguments:
// mailbox_id: The ID of the mailbox.
//
// Returns:
// The address of the mailbox.
//
fn getMailbox(mailbox_id: &const MailboxId) &Mailbox {
return switch (*mailbox_id) {
MailboxId.This => &(??scheduler.current()).mailbox,
MailboxId.Port => |id| ports.at(id),
MailboxId.Thread => |tid| &(??thread.get(tid)).mailbox,
else => unreachable,
};
}
////
// Validate the outgoing message. If the validation succeeds,
// return a copy of a message with an explicit sender field.
//
// Arguments:
// message: The original message.
//
// Returns:
// A copy of the message with an explicit sender field.
//
fn processOutgoingMessage(message: &const Message) Message {
var message_copy = *message;
switch (message.sender) {
MailboxId.This => message_copy.sender = MailboxId { .Thread = (??scheduler.current()).tid },
// MailboxId.Port => TODO: ensure the sender owns the port.
// MailboxId.Kernel => TODO: ensure the sender is really the kernel.
else => {},
}
return message_copy;
}
|
kernel/ipc.zig
|
// Rough implementation of msgpack, based on the standard online at
// https://github.com/msgpack/msgpack/blob/master/spec.md
const std = @import("std");
const Tag = std.meta.Tag;
const MsgPackError = error{
InvalidKeyType,
NoExtensionsAllowed,
NotAMap,
NoSuchKey,
InvalidValueType,
IntOverflow,
};
pub const Key = union(enum) {
Int: i64,
UInt: u64,
Boolean: bool,
RawString: []const u8,
RawData: []const u8,
fn bytes(self: Key) []const u8 {
return switch (self) {
.Int, .UInt, .Boolean => std.mem.asBytes(&self),
.RawString, .RawData => |data| data,
};
}
fn eql(a: Key, b: Key) bool {
if (@as(Tag(Key), a) != b) {
return false;
} else {
return std.mem.eql(u8, a.bytes(), b.bytes());
}
}
fn hash(self: Key) u64 {
return std.hash.Wyhash.hash(0, self.bytes());
}
fn to_value(self: Key) Value {
return switch (self) {
.Int => Value{ .Int = self.Int },
.UInt => Value{ .UInt = self.UInt },
.Boolean => Value{ .Boolean = self.Boolean },
.RawString => Value{ .RawString = self.RawString },
.RawData => Value{ .RawData = self.RawData },
};
}
};
pub const KeyValueMap = std.hash_map.HashMap(
Key,
Value,
Key.hash,
Key.eql,
std.hash_map.DefaultMaxLoadPercentage,
);
pub const Ext = struct {
type: i8,
data: []const u8,
pub fn as_u32(self: *const Ext) !u32 {
if (self.data.len > 4) {
return MsgPackError.IntOverflow;
} else {
var out: u32 = 0;
var i: u32 = 0;
while (i < self.data.len) : (i += 1) {
const j: u32 = i * 8;
out |= @intCast(u32, self.data[i]) << @intCast(u5, j);
}
return out;
}
}
};
pub const Value = union(enum) {
Int: i64,
UInt: u64,
Nil: void,
Boolean: bool,
Float32: f32,
Float64: f64,
RawString: []const u8,
RawData: []const u8,
Array: []Value,
Map: KeyValueMap,
Ext: Ext,
pub fn destroy(self: Value, alloc: *std.mem.Allocator) void {
var self_mut = self;
switch (self_mut) {
.Map => |map| {
var itr = map.iterator();
while (itr.next()) |entry| {
entry.key.to_value().destroy(alloc);
entry.value.destroy(alloc);
}
self_mut.Map.deinit();
},
.RawString, .RawData => |r| {
alloc.free(r);
},
.Array => |arr| {
for (arr) |r| {
var r_mut = r;
r_mut.destroy(alloc);
}
alloc.free(arr);
},
.Ext => |ext| {
alloc.free(ext.data);
},
else => {},
}
}
pub fn encode(alloc: *std.mem.Allocator, v: anytype) !Value {
const T = @TypeOf(v);
switch (@typeInfo(T)) {
.Pointer => |ptr| {
switch (ptr.size) {
.One => {
// We only encode things like *const [5:0]u8,
// which are used for static strings.
switch (@typeInfo(ptr.child)) {
.Array => |array| {
const x: []const array.child = v[0..];
return Value.encode(alloc, x);
},
else => @compileError("Could not encode pointer"),
}
},
.Slice => {
// Special case to encode strings instead of Array(u8)
if (ptr.child == u8) {
return Value{ .RawString = v };
} else {
const out = try alloc.alloc(Value, v.len);
var i: u32 = 0;
while (i < v.len) : (i += 1) {
out[i] = try encode(alloc, v[i]);
}
return Value{ .Array = out };
}
},
else => @compileError("Cannot encode generic pointer"),
}
},
.Array => |array| {
// Coerce to slice
const x: []const array.child = v[0..];
return encode(alloc, &x);
},
.Struct => |st| {
if (@TypeOf(v) == KeyValueMap) {
return Value{ .Map = v };
} else {
const out = try alloc.alloc(Value, st.fields.len);
comptime var i: u32 = 0;
inline while (i < st.fields.len) : (i += 1) {
out[i] = try encode(alloc, v[i]);
}
return Value{ .Array = out };
}
},
else => {
// Fall through to switch statement below
},
}
return switch (T) {
Value => v,
Key => v.to_value(),
i8, i16, i32, i64, comptime_int => Value{ .Int = v },
u8, u16, u32, u64, usize => Value{ .UInt = v },
void => Value{ .Nil = {} },
bool => Value{ .Boolean = v },
f32 => Value{ .Float32 = v },
f64, comptime_float => Value{ .Float64 = v },
else => @compileError("Cannot encode type " ++ @typeName(T)),
};
}
pub fn get(self: Value, k: []const u8) !Value {
switch (self) {
.Map => |map| {
const entry = map.getEntry(Key{ .RawString = k });
if (entry) |e| {
return e.value;
}
return MsgPackError.NoSuchKey;
},
else => return MsgPackError.NotAMap,
}
}
fn to_hash_key(self: Value) !Key {
return switch (self) {
.Int => Key{ .Int = self.Int },
.UInt => Key{ .UInt = self.UInt },
.Boolean => Key{ .Boolean = self.Boolean },
.RawString => Key{ .RawString = self.RawString },
.RawData => Key{ .RawData = self.RawData },
else => MsgPackError.InvalidKeyType,
};
}
// out should implement the Writer interface
pub fn serialize(self: Value, out: anytype) anyerror!void {
switch (self) {
.Int => |i| {
switch (i) {
// Negative fixnum
-32...-1 => _ = try out.write(&std.mem.toBytes(@intCast(i8, i))),
// i8
0...std.math.maxInt(i8), std.math.minInt(i8)...-33 => {
_ = try out.writeByte(0xd0);
_ = try out.write(&std.mem.toBytes(@intCast(i8, i)));
},
// i16
(std.math.maxInt(i8) + 1)...std.math.maxInt(i16),
std.math.minInt(i16)...(std.math.minInt(i8) - 1),
=> {
_ = try out.writeByte(0xd1);
const j = std.mem.nativeToBig(i16, @intCast(i16, i));
_ = try out.write(&std.mem.toBytes(j));
},
// i32
(std.math.maxInt(i16) + 1)...std.math.maxInt(i32),
std.math.minInt(i32)...(std.math.minInt(i16) - 1),
=> {
_ = try out.writeByte(0xd2);
const j = std.mem.nativeToBig(i32, @intCast(i32, i));
_ = try out.write(&std.mem.toBytes(j));
},
// i64
(std.math.maxInt(i32) + 1)...std.math.maxInt(i64),
std.math.minInt(i64)...(std.math.minInt(i32) - 1),
=> {
_ = try out.writeByte(0xd3);
const j = std.mem.nativeToBig(i64, @intCast(i64, i));
_ = try out.write(&std.mem.toBytes(j));
},
}
},
.UInt => |u| {
switch (u) {
// Positive fixnum
0x00...0x7f => _ = try out.write(&std.mem.toBytes(@intCast(u8, u))),
// u8
0x80...std.math.maxInt(u8) => {
_ = try out.writeByte(0xcc);
_ = try out.write(&std.mem.toBytes(@intCast(u8, u)));
},
// u16
(std.math.maxInt(u8) + 1)...std.math.maxInt(u16) => {
_ = try out.writeByte(0xcd);
const j = std.mem.nativeToBig(u16, @intCast(u16, u));
_ = try out.write(&std.mem.toBytes(j));
},
// u32
(std.math.maxInt(u16) + 1)...std.math.maxInt(u32) => {
_ = try out.writeByte(0xce);
const j = std.mem.nativeToBig(u32, @intCast(u32, u));
_ = try out.write(&std.mem.toBytes(j));
},
// u64
(std.math.maxInt(u32) + 1)...std.math.maxInt(u64) => {
_ = try out.writeByte(0xcf);
const j = std.mem.nativeToBig(u64, @intCast(u64, u));
_ = try out.write(&std.mem.toBytes(j));
},
}
},
.Nil => _ = try out.writeByte(0xc0),
.Boolean => |b| {
_ = try out.writeByte(if (b) 0xc3 else 0xc2);
},
.Float32 => |f| {
_ = try out.writeByte(0xca);
_ = try out.write(&std.mem.toBytes(f));
},
.Float64 => |d| {
_ = try out.writeByte(0xcb);
_ = try out.write(&std.mem.toBytes(d));
},
.RawString => |s| {
switch (s.len) {
0x00...0x1f => {
_ = try out.writeByte(0b101_00000 | @intCast(u8, s.len));
},
0x20...std.math.maxInt(u8) => {
_ = try out.writeByte(0xd9);
_ = try out.writeByte(@intCast(u8, s.len));
},
std.math.maxInt(u8) + 1...std.math.maxInt(u16) => {
_ = try out.writeByte(0xda);
const j = std.mem.nativeToBig(u16, @intCast(u16, s.len));
_ = try out.write(&std.mem.toBytes(j));
},
std.math.maxInt(u16) + 1...std.math.maxInt(u32) => {
_ = try out.writeByte(0xda);
const j = std.mem.nativeToBig(u32, @intCast(u32, s.len));
_ = try out.write(&std.mem.toBytes(j));
},
else => std.debug.panic(
"String is too large: {} > {}\n",
.{ s.len, std.math.maxInt(u32) },
),
}
_ = try out.write(s);
},
.RawData => |d| {
switch (d.len) {
0x00...std.math.maxInt(u8) => {
_ = try out.writeByte(0xc4);
_ = try out.writeByte(@intCast(u8, d.len));
},
std.math.maxInt(u8) + 1...std.math.maxInt(u16) => {
_ = try out.writeByte(0xc5);
const j = std.mem.nativeToBig(u16, @intCast(u16, d.len));
_ = try out.write(&std.mem.toBytes(j));
},
std.math.maxInt(u16) + 1...std.math.maxInt(u32) => {
_ = try out.writeByte(0xc6);
const j = std.mem.nativeToBig(u32, @intCast(u32, d.len));
_ = try out.write(&std.mem.toBytes(j));
},
else => std.debug.panic(
"Data is too large: {} > {}\n",
.{ d.len, std.math.maxInt(u32) },
),
}
_ = try out.write(d);
},
.Array => |a| {
switch (a.len) {
0x00...0x0f => {
_ = try out.writeByte(0b1001_0000 | @intCast(u8, a.len));
},
0x10...std.math.maxInt(u16) => {
_ = try out.writeByte(0xdc);
const j = std.mem.nativeToBig(u16, @intCast(u16, a.len));
_ = try out.write(&std.mem.toBytes(j));
},
std.math.maxInt(u16) + 1...std.math.maxInt(u32) => {
_ = try out.writeByte(0xdd);
const j = std.mem.nativeToBig(u32, @intCast(u32, a.len));
_ = try out.write(&std.mem.toBytes(j));
},
else => std.debug.panic(
"Array is too large: {} > {}\n",
.{ a.len, std.math.maxInt(u32) },
),
}
for (a) |v| {
try v.serialize(out);
}
},
.Map => |m| {
const count = m.count();
switch (count) {
0x00...0x0f => {
_ = try out.writeByte(0b1000_0000 | @intCast(u8, count));
},
0x10...std.math.maxInt(u16) => {
_ = try out.writeByte(0xde);
const j = std.mem.nativeToBig(u16, @intCast(u16, count));
_ = try out.write(&std.mem.toBytes(j));
},
std.math.maxInt(u16) + 1...std.math.maxInt(u32) => {
_ = try out.writeByte(0xdf);
const j = std.mem.nativeToBig(u32, @intCast(u32, count));
_ = try out.write(&std.mem.toBytes(j));
},
}
var itr = m.iterator();
while (itr.next()) |entry| {
try entry.key.to_value().serialize(out);
try entry.value.serialize(out);
}
},
.Ext => |e| {
const count = e.data.len;
switch (count) {
0x01 => {
_ = try out.writeByte(0xd4);
},
0x02 => {
_ = try out.writeByte(0xd5);
},
0x04 => {
_ = try out.writeByte(0xd6);
},
0x08 => {
_ = try out.writeByte(0xd7);
},
0x10 => {
_ = try out.writeByte(0xd8);
},
0x00, 0x03, 0x05...0x07, 0x09...0x0f, 0x11...0xff => {
_ = try out.writeByte(0xc7);
_ = try out.writeByte(@intCast(u8, count));
},
std.math.maxInt(u8) + 1...std.math.maxInt(u16) => {
_ = try out.writeByte(0xc8);
const j = std.mem.nativeToBig(u16, @intCast(u16, count));
_ = try out.write(&std.mem.toBytes(j));
},
std.math.maxInt(u16) + 1...std.math.maxInt(u32) => {
_ = try out.writeByte(0xc9);
const j = std.mem.nativeToBig(u32, @intCast(u32, count));
_ = try out.write(&std.mem.toBytes(j));
},
std.math.maxInt(u32) + 1...std.math.maxInt(u64) => {
std.debug.panic("Ext data is too large: {}\n", .{count});
},
}
_ = try out.writeByte(@bitCast(u8, e.type));
_ = try out.write(e.data);
},
}
}
};
const Decoded = struct {
data: Value,
offset: usize,
};
fn generic_type(comptime T: type) type {
return struct {
data: T,
offset: usize,
};
}
fn decode_generic(comptime T: type, data: []const u8) !generic_type(T) {
var out: T = undefined;
@memcpy(@ptrCast([*]u8, &out), data.ptr, @sizeOf(T));
if (T != f32 and T != f64) {
out = std.mem.bigToNative(T, out);
// TODO: byteswap floats as well?
}
return generic_type(T){ .data = out, .offset = @sizeOf(T) };
}
fn decode_bin(comptime T: type, alloc: *std.mem.Allocator, data: []const u8) !Decoded {
var offset: usize = 0;
const d = try decode_generic(T, data);
const n = d.data;
offset += d.offset;
const out = try alloc.dupe(u8, data[offset..(offset + n)]);
offset += n;
return Decoded{ .data = Value{ .RawData = out }, .offset = offset };
}
fn decode_fixext(comptime len: u32, alloc: *std.mem.Allocator, data: []const u8) !Decoded {
var offset: usize = 0;
const t = @bitCast(i8, data[0]);
offset += 1;
const buf = try alloc.dupe(u8, data[offset..(offset + len)]);
return Decoded{
.data = Value{ .Ext = .{ .type = t, .data = buf } },
.offset = offset + len,
};
}
fn decode_ext(comptime T: type, alloc: *std.mem.Allocator, data: []const u8) !Decoded {
const t = @bitCast(i8, data[0]);
var out = try decode_bin(T, alloc, data[1..]);
return Decoded{
.data = Value{ .Ext = .{ .type = t, .data = out.data.RawData } },
.offset = out.offset + 1,
};
}
fn decode_array_n(alloc: *std.mem.Allocator, n: usize, data: []const u8) !Decoded {
var out = try alloc.alloc(Value, n);
var j: usize = 0;
var offset: usize = 0;
while (j < n) : (j += 1) {
const d = try decode(alloc, data[offset..]);
offset += d.offset;
out[j] = d.data;
}
return Decoded{
.data = Value{ .Array = out },
.offset = offset,
};
}
fn decode_map_n(alloc: *std.mem.Allocator, n: usize, data: []const u8) !Decoded {
var out = KeyValueMap.init(alloc);
var j: usize = 0;
var offset: usize = 0;
while (j < n) : (j += 1) {
const k = try decode(alloc, data[offset..]);
offset += k.offset;
const v = try decode(alloc, data[offset..]);
offset += v.offset;
const k_ = try k.data.to_hash_key();
try out.put(k_, v.data);
}
return Decoded{
.data = Value{ .Map = out },
.offset = offset,
};
}
fn decode_array(comptime T: type, alloc: *std.mem.Allocator, data: []const u8) !Decoded {
const d = try decode_generic(T, data);
const n = d.data;
const out = try decode_array_n(alloc, n, data[d.offset..]);
return Decoded{
.data = out.data,
.offset = d.offset + out.offset,
};
}
fn decode_map(comptime T: type, alloc: *std.mem.Allocator, data: []const u8) !Decoded {
const d = try decode_generic(T, data);
const n = d.data;
const out = try decode_map_n(alloc, n, data[d.offset..]);
return Decoded{
.data = out.data,
.offset = d.offset + out.offset,
};
}
pub fn decode(alloc: *std.mem.Allocator, data: []const u8) anyerror!Decoded {
const c = data[0];
var offset: usize = 1;
const t = switch (c) {
0x00...0x7f => Value{ .UInt = @intCast(u64, c & 0x7F) },
0x80...0x8f => fixmap: {
const n = c & 0xF;
const out = try decode_map_n(alloc, n, data[offset..]);
offset += out.offset;
break :fixmap out.data;
},
0x90...0x9f => fixarray: {
const n = c & 0xF;
const out = try decode_array_n(alloc, n, data[offset..]);
offset += out.offset;
break :fixarray out.data;
},
0xa0...0xbf => fixstr: {
const n = c & 0x1F;
var out = try alloc.dupe(u8, data[offset..(offset + n)]);
offset += n;
break :fixstr Value{ .RawString = out };
},
0xc0 => Value{ .Nil = {} },
// 0xc1 is unused
0xc2 => Value{ .Boolean = false },
0xc3 => Value{ .Boolean = true },
0xc4 => bin8: {
const out = try decode_bin(u8, alloc, data[offset..]);
offset += out.offset;
break :bin8 out.data;
},
0xc5 => bin16: {
const out = try decode_bin(u16, alloc, data[offset..]);
offset += out.offset;
break :bin16 out.data;
},
0xc6 => bin32: {
const out = try decode_bin(u32, alloc, data[offset..]);
offset += out.offset;
break :bin32 out.data;
},
0xc7 => ext8: {
const out = try decode_ext(u8, alloc, data[offset..]);
offset += out.offset;
break :ext8 out.data;
},
0xc8 => ext16: {
const out = try decode_ext(u16, alloc, data[offset..]);
offset += out.offset;
break :ext16 out.data;
},
0xc9 => ext32: {
const out = try decode_ext(u32, alloc, data[offset..]);
offset += out.offset;
break :ext32 out.data;
},
0xca => f32: {
const out = try decode_generic(f32, data[offset..]);
offset += out.offset;
break :f32 Value{ .Float32 = out.data };
},
0xcb => f64: {
const out = try decode_generic(f64, data[offset..]);
offset += out.offset;
break :f64 Value{ .Float64 = out.data };
},
0xcc => u8: {
const out = try decode_generic(u8, data[offset..]);
offset += out.offset;
break :u8 Value{ .UInt = out.data };
},
0xcd => u16: {
const out = try decode_generic(u16, data[offset..]);
offset += out.offset;
break :u16 Value{ .UInt = out.data };
},
0xce => u32: {
const out = try decode_generic(u32, data[offset..]);
offset += out.offset;
break :u32 Value{ .UInt = out.data };
},
0xcf => u64: {
const out = try decode_generic(u64, data[offset..]);
offset += out.offset;
break :u64 Value{ .UInt = out.data };
},
0xd0 => i8: {
const out = try decode_generic(i8, data[offset..]);
offset += out.offset;
break :i8 Value{ .Int = out.data };
},
0xd1 => i16: {
const out = try decode_generic(i16, data[offset..]);
offset += out.offset;
break :i16 Value{ .Int = out.data };
},
0xd2 => i32: {
const out = try decode_generic(i32, data[offset..]);
offset += out.offset;
break :i32 Value{ .Int = out.data };
},
0xd3 => i64: {
const out = try decode_generic(i64, data[offset..]);
offset += out.offset;
break :i64 Value{ .Int = out.data };
},
0xd4 => fixext1: {
const out = try decode_fixext(1, alloc, data[offset..]);
offset += out.offset;
break :fixext1 out.data;
},
0xd5 => fixext2: {
const out = try decode_fixext(2, alloc, data[offset..]);
offset += out.offset;
break :fixext2 out.data;
},
0xd6 => fixext4: {
const out = try decode_fixext(4, alloc, data[offset..]);
offset += out.offset;
break :fixext4 out.data;
},
0xd7 => fixext8: {
const out = try decode_fixext(8, alloc, data[offset..]);
offset += out.offset;
break :fixext8 out.data;
},
0xd8 => fixext16: {
const out = try decode_fixext(16, alloc, data[offset..]);
offset += out.offset;
break :fixext16 out.data;
},
0xd9 => str8: {
const out = try decode_bin(u8, alloc, data[offset..]);
offset += out.offset;
break :str8 Value{ .RawString = out.data.RawData };
},
0xda => str16: {
const out = try decode_bin(u16, alloc, data[offset..]);
offset += out.offset;
break :str16 Value{ .RawString = out.data.RawData };
},
0xdb => str32: {
const out = try decode_bin(u32, alloc, data[offset..]);
offset += out.offset;
break :str32 Value{ .RawString = out.data.RawData };
},
0xdc => array16: {
const n = try decode_array(u16, alloc, data[offset..]);
offset += n.offset;
break :array16 n.data;
},
0xdd => array32: {
const n = try decode_array(u32, alloc, data[offset..]);
offset += n.offset;
break :array32 n.data;
},
0xde => map16: {
const n = try decode_map(u16, alloc, data[offset..]);
offset += n.offset;
break :map16 n.data;
},
0xdf => map32: {
const n = try decode_map(u32, alloc, data[offset..]);
offset += n.offset;
break :map32 n.data;
},
0xe0...0xff => Value{ .Int = @bitCast(i8, c) },
else => Value{ .Nil = {} },
};
return Decoded{
.data = t,
.offset = offset,
};
}
////////////////////////////////////////////////////////////////////////////////
test "msgpack.Value.encode string literal" {
var gp_alloc = std.heap.GeneralPurposeAllocator(.{}){};
defer std.testing.expect(!gp_alloc.deinit());
var arena = std.heap.ArenaAllocator.init(&gp_alloc.allocator);
const alloc: *std.mem.Allocator = &arena.allocator;
defer arena.deinit();
const v = try Value.encode(alloc, "hello");
std.testing.expect(v == .RawString);
std.testing.expectEqualStrings("hello", v.RawString);
}
|
src/fileformats/msgpack.zig
|
pub const Win32Error = extern enum(u16) {
/// The operation completed successfully.
SUCCESS = 0,
/// Incorrect function.
INVALID_FUNCTION = 1,
/// The system cannot find the file specified.
FILE_NOT_FOUND = 2,
/// The system cannot find the path specified.
PATH_NOT_FOUND = 3,
/// The system cannot open the file.
TOO_MANY_OPEN_FILES = 4,
/// Access is denied.
ACCESS_DENIED = 5,
/// The handle is invalid.
INVALID_HANDLE = 6,
/// The storage control blocks were destroyed.
ARENA_TRASHED = 7,
/// Not enough storage is available to process this command.
NOT_ENOUGH_MEMORY = 8,
/// The storage control block address is invalid.
INVALID_BLOCK = 9,
/// The environment is incorrect.
BAD_ENVIRONMENT = 10,
/// An attempt was made to load a program with an incorrect format.
BAD_FORMAT = 11,
/// The access code is invalid.
INVALID_ACCESS = 12,
/// The data is invalid.
INVALID_DATA = 13,
/// Not enough storage is available to complete this operation.
OUTOFMEMORY = 14,
/// The system cannot find the drive specified.
INVALID_DRIVE = 15,
/// The directory cannot be removed.
CURRENT_DIRECTORY = 16,
/// The system cannot move the file to a different disk drive.
NOT_SAME_DEVICE = 17,
/// There are no more files.
NO_MORE_FILES = 18,
/// The media is write protected.
WRITE_PROTECT = 19,
/// The system cannot find the device specified.
BAD_UNIT = 20,
/// The device is not ready.
NOT_READY = 21,
/// The device does not recognize the command.
BAD_COMMAND = 22,
/// Data error (cyclic redundancy check).
CRC = 23,
/// The program issued a command but the command length is incorrect.
BAD_LENGTH = 24,
/// The drive cannot locate a specific area or track on the disk.
SEEK = 25,
/// The specified disk or diskette cannot be accessed.
NOT_DOS_DISK = 26,
/// The drive cannot find the sector requested.
SECTOR_NOT_FOUND = 27,
/// The printer is out of paper.
OUT_OF_PAPER = 28,
/// The system cannot write to the specified device.
WRITE_FAULT = 29,
/// The system cannot read from the specified device.
READ_FAULT = 30,
/// A device attached to the system is not functioning.
GEN_FAILURE = 31,
/// The process cannot access the file because it is being used by another process.
SHARING_VIOLATION = 32,
/// The process cannot access the file because another process has locked a portion of the file.
LOCK_VIOLATION = 33,
/// The wrong diskette is in the drive.
/// Insert %2 (Volume Serial Number: %3) into drive %1.
WRONG_DISK = 34,
/// Too many files opened for sharing.
SHARING_BUFFER_EXCEEDED = 36,
/// Reached the end of the file.
HANDLE_EOF = 38,
/// The disk is full.
HANDLE_DISK_FULL = 39,
/// The request is not supported.
NOT_SUPPORTED = 50,
/// Windows cannot find the network path.
/// Verify that the network path is correct and the destination computer is not busy or turned off.
/// If Windows still cannot find the network path, contact your network administrator.
REM_NOT_LIST = 51,
/// You were not connected because a duplicate name exists on the network.
/// If joining a domain, go to System in Control Panel to change the computer name and try again.
/// If joining a workgroup, choose another workgroup name.
DUP_NAME = 52,
/// The network path was not found.
BAD_NETPATH = 53,
/// The network is busy.
NETWORK_BUSY = 54,
/// The specified network resource or device is no longer available.
DEV_NOT_EXIST = 55,
/// The network BIOS command limit has been reached.
TOO_MANY_CMDS = 56,
/// A network adapter hardware error occurred.
ADAP_HDW_ERR = 57,
/// The specified server cannot perform the requested operation.
BAD_NET_RESP = 58,
/// An unexpected network error occurred.
UNEXP_NET_ERR = 59,
/// The remote adapter is not compatible.
BAD_REM_ADAP = 60,
/// The printer queue is full.
PRINTQ_FULL = 61,
/// Space to store the file waiting to be printed is not available on the server.
NO_SPOOL_SPACE = 62,
/// Your file waiting to be printed was deleted.
PRINT_CANCELLED = 63,
/// The specified network name is no longer available.
NETNAME_DELETED = 64,
/// Network access is denied.
NETWORK_ACCESS_DENIED = 65,
/// The network resource type is not correct.
BAD_DEV_TYPE = 66,
/// The network name cannot be found.
BAD_NET_NAME = 67,
/// The name limit for the local computer network adapter card was exceeded.
TOO_MANY_NAMES = 68,
/// The network BIOS session limit was exceeded.
TOO_MANY_SESS = 69,
/// The remote server has been paused or is in the process of being started.
SHARING_PAUSED = 70,
/// No more connections can be made to this remote computer at this time because there are already as many connections as the computer can accept.
REQ_NOT_ACCEP = 71,
/// The specified printer or disk device has been paused.
REDIR_PAUSED = 72,
/// The file exists.
FILE_EXISTS = 80,
/// The directory or file cannot be created.
CANNOT_MAKE = 82,
/// Fail on INT 24.
FAIL_I24 = 83,
/// Storage to process this request is not available.
OUT_OF_STRUCTURES = 84,
/// The local device name is already in use.
ALREADY_ASSIGNED = 85,
/// The specified network password is not correct.
INVALID_PASSWORD = 86,
/// The parameter is incorrect.
INVALID_PARAMETER = 87,
/// A write fault occurred on the network.
NET_WRITE_FAULT = 88,
/// The system cannot start another process at this time.
NO_PROC_SLOTS = 89,
/// Cannot create another system semaphore.
TOO_MANY_SEMAPHORES = 100,
/// The exclusive semaphore is owned by another process.
EXCL_SEM_ALREADY_OWNED = 101,
/// The semaphore is set and cannot be closed.
SEM_IS_SET = 102,
/// The semaphore cannot be set again.
TOO_MANY_SEM_REQUESTS = 103,
/// Cannot request exclusive semaphores at interrupt time.
INVALID_AT_INTERRUPT_TIME = 104,
/// The previous ownership of this semaphore has ended.
SEM_OWNER_DIED = 105,
/// Insert the diskette for drive %1.
SEM_USER_LIMIT = 106,
/// The program stopped because an alternate diskette was not inserted.
DISK_CHANGE = 107,
/// The disk is in use or locked by another process.
DRIVE_LOCKED = 108,
/// The pipe has been ended.
BROKEN_PIPE = 109,
/// The system cannot open the device or file specified.
OPEN_FAILED = 110,
/// The file name is too long.
BUFFER_OVERFLOW = 111,
/// There is not enough space on the disk.
DISK_FULL = 112,
/// No more internal file identifiers available.
NO_MORE_SEARCH_HANDLES = 113,
/// The target internal file identifier is incorrect.
INVALID_TARGET_HANDLE = 114,
/// The IOCTL call made by the application program is not correct.
INVALID_CATEGORY = 117,
/// The verify-on-write switch parameter value is not correct.
INVALID_VERIFY_SWITCH = 118,
/// The system does not support the command requested.
BAD_DRIVER_LEVEL = 119,
/// This function is not supported on this system.
CALL_NOT_IMPLEMENTED = 120,
/// The semaphore timeout period has expired.
SEM_TIMEOUT = 121,
/// The data area passed to a system call is too small.
INSUFFICIENT_BUFFER = 122,
/// The filename, directory name, or volume label syntax is incorrect.
INVALID_NAME = 123,
/// The system call level is not correct.
INVALID_LEVEL = 124,
/// The disk has no volume label.
NO_VOLUME_LABEL = 125,
/// The specified module could not be found.
MOD_NOT_FOUND = 126,
/// The specified procedure could not be found.
PROC_NOT_FOUND = 127,
/// There are no child processes to wait for.
WAIT_NO_CHILDREN = 128,
/// The %1 application cannot be run in Win32 mode.
CHILD_NOT_COMPLETE = 129,
/// Attempt to use a file handle to an open disk partition for an operation other than raw disk I/O.
DIRECT_ACCESS_HANDLE = 130,
/// An attempt was made to move the file pointer before the beginning of the file.
NEGATIVE_SEEK = 131,
/// The file pointer cannot be set on the specified device or file.
SEEK_ON_DEVICE = 132,
/// A JOIN or SUBST command cannot be used for a drive that contains previously joined drives.
IS_JOIN_TARGET = 133,
/// An attempt was made to use a JOIN or SUBST command on a drive that has already been joined.
IS_JOINED = 134,
/// An attempt was made to use a JOIN or SUBST command on a drive that has already been substituted.
IS_SUBSTED = 135,
/// The system tried to delete the JOIN of a drive that is not joined.
NOT_JOINED = 136,
/// The system tried to delete the substitution of a drive that is not substituted.
NOT_SUBSTED = 137,
/// The system tried to join a drive to a directory on a joined drive.
JOIN_TO_JOIN = 138,
/// The system tried to substitute a drive to a directory on a substituted drive.
SUBST_TO_SUBST = 139,
/// The system tried to join a drive to a directory on a substituted drive.
JOIN_TO_SUBST = 140,
/// The system tried to SUBST a drive to a directory on a joined drive.
SUBST_TO_JOIN = 141,
/// The system cannot perform a JOIN or SUBST at this time.
BUSY_DRIVE = 142,
/// The system cannot join or substitute a drive to or for a directory on the same drive.
SAME_DRIVE = 143,
/// The directory is not a subdirectory of the root directory.
DIR_NOT_ROOT = 144,
/// The directory is not empty.
DIR_NOT_EMPTY = 145,
/// The path specified is being used in a substitute.
IS_SUBST_PATH = 146,
/// Not enough resources are available to process this command.
IS_JOIN_PATH = 147,
/// The path specified cannot be used at this time.
PATH_BUSY = 148,
/// An attempt was made to join or substitute a drive for which a directory on the drive is the target of a previous substitute.
IS_SUBST_TARGET = 149,
/// System trace information was not specified in your CONFIG.SYS file, or tracing is disallowed.
SYSTEM_TRACE = 150,
/// The number of specified semaphore events for DosMuxSemWait is not correct.
INVALID_EVENT_COUNT = 151,
/// DosMuxSemWait did not execute; too many semaphores are already set.
TOO_MANY_MUXWAITERS = 152,
/// The DosMuxSemWait list is not correct.
INVALID_LIST_FORMAT = 153,
/// The volume label you entered exceeds the label character limit of the target file system.
LABEL_TOO_LONG = 154,
/// Cannot create another thread.
TOO_MANY_TCBS = 155,
/// The recipient process has refused the signal.
SIGNAL_REFUSED = 156,
/// The segment is already discarded and cannot be locked.
DISCARDED = 157,
/// The segment is already unlocked.
NOT_LOCKED = 158,
/// The address for the thread ID is not correct.
BAD_THREADID_ADDR = 159,
/// One or more arguments are not correct.
BAD_ARGUMENTS = 160,
/// The specified path is invalid.
BAD_PATHNAME = 161,
/// A signal is already pending.
SIGNAL_PENDING = 162,
/// No more threads can be created in the system.
MAX_THRDS_REACHED = 164,
/// Unable to lock a region of a file.
LOCK_FAILED = 167,
/// The requested resource is in use.
BUSY = 170,
/// Device's command support detection is in progress.
DEVICE_SUPPORT_IN_PROGRESS = 171,
/// A lock request was not outstanding for the supplied cancel region.
CANCEL_VIOLATION = 173,
/// The file system does not support atomic changes to the lock type.
ATOMIC_LOCKS_NOT_SUPPORTED = 174,
/// The system detected a segment number that was not correct.
INVALID_SEGMENT_NUMBER = 180,
/// The operating system cannot run %1.
INVALID_ORDINAL = 182,
/// Cannot create a file when that file already exists.
ALREADY_EXISTS = 183,
/// The flag passed is not correct.
INVALID_FLAG_NUMBER = 186,
/// The specified system semaphore name was not found.
SEM_NOT_FOUND = 187,
/// The operating system cannot run %1.
INVALID_STARTING_CODESEG = 188,
/// The operating system cannot run %1.
INVALID_STACKSEG = 189,
/// The operating system cannot run %1.
INVALID_MODULETYPE = 190,
/// Cannot run %1 in Win32 mode.
INVALID_EXE_SIGNATURE = 191,
/// The operating system cannot run %1.
EXE_MARKED_INVALID = 192,
/// %1 is not a valid Win32 application.
BAD_EXE_FORMAT = 193,
/// The operating system cannot run %1.
ITERATED_DATA_EXCEEDS_64k = 194,
/// The operating system cannot run %1.
INVALID_MINALLOCSIZE = 195,
/// The operating system cannot run this application program.
DYNLINK_FROM_INVALID_RING = 196,
/// The operating system is not presently configured to run this application.
IOPL_NOT_ENABLED = 197,
/// The operating system cannot run %1.
INVALID_SEGDPL = 198,
/// The operating system cannot run this application program.
AUTODATASEG_EXCEEDS_64k = 199,
/// The code segment cannot be greater than or equal to 64K.
RING2SEG_MUST_BE_MOVABLE = 200,
/// The operating system cannot run %1.
RELOC_CHAIN_XEEDS_SEGLIM = 201,
/// The operating system cannot run %1.
INFLOOP_IN_RELOC_CHAIN = 202,
/// The system could not find the environment option that was entered.
ENVVAR_NOT_FOUND = 203,
/// No process in the command subtree has a signal handler.
NO_SIGNAL_SENT = 205,
/// The filename or extension is too long.
FILENAME_EXCED_RANGE = 206,
/// The ring 2 stack is in use.
RING2_STACK_IN_USE = 207,
/// The global filename characters, * or ?, are entered incorrectly or too many global filename characters are specified.
META_EXPANSION_TOO_LONG = 208,
/// The signal being posted is not correct.
INVALID_SIGNAL_NUMBER = 209,
/// The signal handler cannot be set.
THREAD_1_INACTIVE = 210,
/// The segment is locked and cannot be reallocated.
LOCKED = 212,
/// Too many dynamic-link modules are attached to this program or dynamic-link module.
TOO_MANY_MODULES = 214,
/// Cannot nest calls to LoadModule.
NESTING_NOT_ALLOWED = 215,
/// This version of %1 is not compatible with the version of Windows you're running.
/// Check your computer's system information and then contact the software publisher.
EXE_MACHINE_TYPE_MISMATCH = 216,
/// The image file %1 is signed, unable to modify.
EXE_CANNOT_MODIFY_SIGNED_BINARY = 217,
/// The image file %1 is strong signed, unable to modify.
EXE_CANNOT_MODIFY_STRONG_SIGNED_BINARY = 218,
/// This file is checked out or locked for editing by another user.
FILE_CHECKED_OUT = 220,
/// The file must be checked out before saving changes.
CHECKOUT_REQUIRED = 221,
/// The file type being saved or retrieved has been blocked.
BAD_FILE_TYPE = 222,
/// The file size exceeds the limit allowed and cannot be saved.
FILE_TOO_LARGE = 223,
/// Access Denied. Before opening files in this location, you must first add the web site to your trusted sites list, browse to the web site, and select the option to login automatically.
FORMS_AUTH_REQUIRED = 224,
/// Operation did not complete successfully because the file contains a virus or potentially unwanted software.
VIRUS_INFECTED = 225,
/// This file contains a virus or potentially unwanted software and cannot be opened.
/// Due to the nature of this virus or potentially unwanted software, the file has been removed from this location.
VIRUS_DELETED = 226,
/// The pipe is local.
PIPE_LOCAL = 229,
/// The pipe state is invalid.
BAD_PIPE = 230,
/// All pipe instances are busy.
PIPE_BUSY = 231,
/// The pipe is being closed.
NO_DATA = 232,
/// No process is on the other end of the pipe.
PIPE_NOT_CONNECTED = 233,
/// More data is available.
MORE_DATA = 234,
/// The session was canceled.
VC_DISCONNECTED = 240,
/// The specified extended attribute name was invalid.
INVALID_EA_NAME = 254,
/// The extended attributes are inconsistent.
EA_LIST_INCONSISTENT = 255,
/// The wait operation timed out.
IMEOUT = 258,
/// No more data is available.
NO_MORE_ITEMS = 259,
/// The copy functions cannot be used.
CANNOT_COPY = 266,
/// The directory name is invalid.
DIRECTORY = 267,
/// The extended attributes did not fit in the buffer.
EAS_DIDNT_FIT = 275,
/// The extended attribute file on the mounted file system is corrupt.
EA_FILE_CORRUPT = 276,
/// The extended attribute table file is full.
EA_TABLE_FULL = 277,
/// The specified extended attribute handle is invalid.
INVALID_EA_HANDLE = 278,
/// The mounted file system does not support extended attributes.
EAS_NOT_SUPPORTED = 282,
/// Attempt to release mutex not owned by caller.
NOT_OWNER = 288,
/// Too many posts were made to a semaphore.
TOO_MANY_POSTS = 298,
/// Only part of a ReadProcessMemory or WriteProcessMemory request was completed.
PARTIAL_COPY = 299,
/// The oplock request is denied.
OPLOCK_NOT_GRANTED = 300,
/// An invalid oplock acknowledgment was received by the system.
INVALID_OPLOCK_PROTOCOL = 301,
/// The volume is too fragmented to complete this operation.
DISK_TOO_FRAGMENTED = 302,
/// The file cannot be opened because it is in the process of being deleted.
DELETE_PENDING = 303,
/// Short name settings may not be changed on this volume due to the global registry setting.
INCOMPATIBLE_WITH_GLOBAL_SHORT_NAME_REGISTRY_SETTING = 304,
/// Short names are not enabled on this volume.
SHORT_NAMES_NOT_ENABLED_ON_VOLUME = 305,
/// The security stream for the given volume is in an inconsistent state. Please run CHKDSK on the volume.
SECURITY_STREAM_IS_INCONSISTENT = 306,
/// A requested file lock operation cannot be processed due to an invalid byte range.
INVALID_LOCK_RANGE = 307,
/// The subsystem needed to support the image type is not present.
IMAGE_SUBSYSTEM_NOT_PRESENT = 308,
/// The specified file already has a notification GUID associated with it.
NOTIFICATION_GUID_ALREADY_DEFINED = 309,
/// An invalid exception handler routine has been detected.
INVALID_EXCEPTION_HANDLER = 310,
/// Duplicate privileges were specified for the token.
DUPLICATE_PRIVILEGES = 311,
/// No ranges for the specified operation were able to be processed.
NO_RANGES_PROCESSED = 312,
/// Operation is not allowed on a file system internal file.
NOT_ALLOWED_ON_SYSTEM_FILE = 313,
/// The physical resources of this disk have been exhausted.
DISK_RESOURCES_EXHAUSTED = 314,
/// The token representing the data is invalid.
INVALID_TOKEN = 315,
/// The device does not support the command feature.
DEVICE_FEATURE_NOT_SUPPORTED = 316,
/// The system cannot find message text for message number 0x%1 in the message file for %2.
MR_MID_NOT_FOUND = 317,
/// The scope specified was not found.
SCOPE_NOT_FOUND = 318,
/// The Central Access Policy specified is not defined on the target machine.
UNDEFINED_SCOPE = 319,
/// The Central Access Policy obtained from Active Directory is invalid.
INVALID_CAP = 320,
/// The device is unreachable.
DEVICE_UNREACHABLE = 321,
/// The target device has insufficient resources to complete the operation.
DEVICE_NO_RESOURCES = 322,
/// A data integrity checksum error occurred. Data in the file stream is corrupt.
DATA_CHECKSUM_ERROR = 323,
/// An attempt was made to modify both a KERNEL and normal Extended Attribute (EA) in the same operation.
INTERMIXED_KERNEL_EA_OPERATION = 324,
/// Device does not support file-level TRIM.
FILE_LEVEL_TRIM_NOT_SUPPORTED = 326,
/// The command specified a data offset that does not align to the device's granularity/alignment.
OFFSET_ALIGNMENT_VIOLATION = 327,
/// The command specified an invalid field in its parameter list.
INVALID_FIELD_IN_PARAMETER_LIST = 328,
/// An operation is currently in progress with the device.
OPERATION_IN_PROGRESS = 329,
/// An attempt was made to send down the command via an invalid path to the target device.
BAD_DEVICE_PATH = 330,
/// The command specified a number of descriptors that exceeded the maximum supported by the device.
TOO_MANY_DESCRIPTORS = 331,
/// Scrub is disabled on the specified file.
SCRUB_DATA_DISABLED = 332,
/// The storage device does not provide redundancy.
NOT_REDUNDANT_STORAGE = 333,
/// An operation is not supported on a resident file.
RESIDENT_FILE_NOT_SUPPORTED = 334,
/// An operation is not supported on a compressed file.
COMPRESSED_FILE_NOT_SUPPORTED = 335,
/// An operation is not supported on a directory.
DIRECTORY_NOT_SUPPORTED = 336,
/// The specified copy of the requested data could not be read.
NOT_READ_FROM_COPY = 337,
/// No action was taken as a system reboot is required.
FAIL_NOACTION_REBOOT = 350,
/// The shutdown operation failed.
FAIL_SHUTDOWN = 351,
/// The restart operation failed.
FAIL_RESTART = 352,
/// The maximum number of sessions has been reached.
MAX_SESSIONS_REACHED = 353,
/// The thread is already in background processing mode.
THREAD_MODE_ALREADY_BACKGROUND = 400,
/// The thread is not in background processing mode.
THREAD_MODE_NOT_BACKGROUND = 401,
/// The process is already in background processing mode.
PROCESS_MODE_ALREADY_BACKGROUND = 402,
/// The process is not in background processing mode.
PROCESS_MODE_NOT_BACKGROUND = 403,
/// Attempt to access invalid address.
INVALID_ADDRESS = 487,
/// User profile cannot be loaded.
USER_PROFILE_LOAD = 500,
/// Arithmetic result exceeded 32 bits.
ARITHMETIC_OVERFLOW = 534,
/// There is a process on other end of the pipe.
PIPE_CONNECTED = 535,
/// Waiting for a process to open the other end of the pipe.
PIPE_LISTENING = 536,
/// Application verifier has found an error in the current process.
VERIFIER_STOP = 537,
/// An error occurred in the ABIOS subsystem.
ABIOS_ERROR = 538,
/// A warning occurred in the WX86 subsystem.
WX86_WARNING = 539,
/// An error occurred in the WX86 subsystem.
WX86_ERROR = 540,
/// An attempt was made to cancel or set a timer that has an associated APC and the subject thread is not the thread that originally set the timer with an associated APC routine.
TIMER_NOT_CANCELED = 541,
/// Unwind exception code.
UNWIND = 542,
/// An invalid or unaligned stack was encountered during an unwind operation.
BAD_STACK = 543,
/// An invalid unwind target was encountered during an unwind operation.
INVALID_UNWIND_TARGET = 544,
/// Invalid Object Attributes specified to NtCreatePort or invalid Port Attributes specified to NtConnectPort
INVALID_PORT_ATTRIBUTES = 545,
/// Length of message passed to NtRequestPort or NtRequestWaitReplyPort was longer than the maximum message allowed by the port.
PORT_MESSAGE_TOO_LONG = 546,
/// An attempt was made to lower a quota limit below the current usage.
INVALID_QUOTA_LOWER = 547,
/// An attempt was made to attach to a device that was already attached to another device.
DEVICE_ALREADY_ATTACHED = 548,
/// An attempt was made to execute an instruction at an unaligned address and the host system does not support unaligned instruction references.
INSTRUCTION_MISALIGNMENT = 549,
/// Profiling not started.
PROFILING_NOT_STARTED = 550,
/// Profiling not stopped.
PROFILING_NOT_STOPPED = 551,
/// The passed ACL did not contain the minimum required information.
COULD_NOT_INTERPRET = 552,
/// The number of active profiling objects is at the maximum and no more may be started.
PROFILING_AT_LIMIT = 553,
/// Used to indicate that an operation cannot continue without blocking for I/O.
CANT_WAIT = 554,
/// Indicates that a thread attempted to terminate itself by default (called NtTerminateThread with NULL) and it was the last thread in the current process.
CANT_TERMINATE_SELF = 555,
/// If an MM error is returned which is not defined in the standard FsRtl filter, it is converted to one of the following errors which is guaranteed to be in the filter.
/// In this case information is lost, however, the filter correctly handles the exception.
UNEXPECTED_MM_CREATE_ERR = 556,
/// If an MM error is returned which is not defined in the standard FsRtl filter, it is converted to one of the following errors which is guaranteed to be in the filter.
/// In this case information is lost, however, the filter correctly handles the exception.
UNEXPECTED_MM_MAP_ERROR = 557,
/// If an MM error is returned which is not defined in the standard FsRtl filter, it is converted to one of the following errors which is guaranteed to be in the filter.
/// In this case information is lost, however, the filter correctly handles the exception.
UNEXPECTED_MM_EXTEND_ERR = 558,
/// A malformed function table was encountered during an unwind operation.
BAD_FUNCTION_TABLE = 559,
/// Indicates that an attempt was made to assign protection to a file system file or directory and one of the SIDs in the security descriptor could not be translated into a GUID that could be stored by the file system.
/// This causes the protection attempt to fail, which may cause a file creation attempt to fail.
NO_GUID_TRANSLATION = 560,
/// Indicates that an attempt was made to grow an LDT by setting its size, or that the size was not an even number of selectors.
INVALID_LDT_SIZE = 561,
/// Indicates that the starting value for the LDT information was not an integral multiple of the selector size.
INVALID_LDT_OFFSET = 563,
/// Indicates that the user supplied an invalid descriptor when trying to set up Ldt descriptors.
INVALID_LDT_DESCRIPTOR = 564,
/// Indicates a process has too many threads to perform the requested action.
/// For example, assignment of a primary token may only be performed when a process has zero or one threads.
TOO_MANY_THREADS = 565,
/// An attempt was made to operate on a thread within a specific process, but the thread specified is not in the process specified.
THREAD_NOT_IN_PROCESS = 566,
/// Page file quota was exceeded.
PAGEFILE_QUOTA_EXCEEDED = 567,
/// The Netlogon service cannot start because another Netlogon service running in the domain conflicts with the specified role.
LOGON_SERVER_CONFLICT = 568,
/// The SAM database on a Windows Server is significantly out of synchronization with the copy on the Domain Controller. A complete synchronization is required.
SYNCHRONIZATION_REQUIRED = 569,
/// The NtCreateFile API failed. This error should never be returned to an application, it is a place holder for the Windows Lan Manager Redirector to use in its internal error mapping routines.
NET_OPEN_FAILED = 570,
/// {Privilege Failed} The I/O permissions for the process could not be changed.
IO_PRIVILEGE_FAILED = 571,
/// {Application Exit by CTRL+C} The application terminated as a result of a CTRL+C.
CONTROL_C_EXIT = 572,
/// {Missing System File} The required system file %hs is bad or missing.
MISSING_SYSTEMFILE = 573,
/// {Application Error} The exception %s (0x%08lx) occurred in the application at location 0x%08lx.
UNHANDLED_EXCEPTION = 574,
/// {Application Error} The application was unable to start correctly (0x%lx). Click OK to close the application.
APP_INIT_FAILURE = 575,
/// {Unable to Create Paging File} The creation of the paging file %hs failed (%lx). The requested size was %ld.
PAGEFILE_CREATE_FAILED = 576,
/// Windows cannot verify the digital signature for this file.
/// A recent hardware or software change might have installed a file that is signed incorrectly or damaged, or that might be malicious software from an unknown source.
INVALID_IMAGE_HASH = 577,
/// {No Paging File Specified} No paging file was specified in the system configuration.
NO_PAGEFILE = 578,
/// {EXCEPTION} A real-mode application issued a floating-point instruction and floating-point hardware is not present.
ILLEGAL_FLOAT_CONTEXT = 579,
/// An event pair synchronization operation was performed using the thread specific client/server event pair object, but no event pair object was associated with the thread.
NO_EVENT_PAIR = 580,
/// A Windows Server has an incorrect configuration.
DOMAIN_CTRLR_CONFIG_ERROR = 581,
/// An illegal character was encountered.
/// For a multi-byte character set this includes a lead byte without a succeeding trail byte.
/// For the Unicode character set this includes the characters 0xFFFF and 0xFFFE.
ILLEGAL_CHARACTER = 582,
/// The Unicode character is not defined in the Unicode character set installed on the system.
UNDEFINED_CHARACTER = 583,
/// The paging file cannot be created on a floppy diskette.
FLOPPY_VOLUME = 584,
/// The system BIOS failed to connect a system interrupt to the device or bus for which the device is connected.
BIOS_FAILED_TO_CONNECT_INTERRUPT = 585,
/// This operation is only allowed for the Primary Domain Controller of the domain.
BACKUP_CONTROLLER = 586,
/// An attempt was made to acquire a mutant such that its maximum count would have been exceeded.
MUTANT_LIMIT_EXCEEDED = 587,
/// A volume has been accessed for which a file system driver is required that has not yet been loaded.
FS_DRIVER_REQUIRED = 588,
/// {Registry File Failure} The registry cannot load the hive (file): %hs or its log or alternate. It is corrupt, absent, or not writable.
CANNOT_LOAD_REGISTRY_FILE = 589,
/// {Unexpected Failure in DebugActiveProcess} An unexpected failure occurred while processing a DebugActiveProcess API request.
/// You may choose OK to terminate the process, or Cancel to ignore the error.
DEBUG_ATTACH_FAILED = 590,
/// {Fatal System Error} The %hs system process terminated unexpectedly with a status of 0x%08x (0x%08x 0x%08x). The system has been shut down.
SYSTEM_PROCESS_TERMINATED = 591,
/// {Data Not Accepted} The TDI client could not handle the data received during an indication.
DATA_NOT_ACCEPTED = 592,
/// NTVDM encountered a hard error.
VDM_HARD_ERROR = 593,
/// {Cancel Timeout} The driver %hs failed to complete a cancelled I/O request in the allotted time.
DRIVER_CANCEL_TIMEOUT = 594,
/// {Reply Message Mismatch} An attempt was made to reply to an LPC message, but the thread specified by the client ID in the message was not waiting on that message.
REPLY_MESSAGE_MISMATCH = 595,
/// {Delayed Write Failed} Windows was unable to save all the data for the file %hs. The data has been lost.
/// This error may be caused by a failure of your computer hardware or network connection. Please try to save this file elsewhere.
LOST_WRITEBEHIND_DATA = 596,
/// The parameter(s) passed to the server in the client/server shared memory window were invalid.
/// Too much data may have been put in the shared memory window.
CLIENT_SERVER_PARAMETERS_INVALID = 597,
/// The stream is not a tiny stream.
NOT_TINY_STREAM = 598,
/// The request must be handled by the stack overflow code.
STACK_OVERFLOW_READ = 599,
/// Internal OFS status codes indicating how an allocation operation is handled.
/// Either it is retried after the containing onode is moved or the extent stream is converted to a large stream.
CONVERT_TO_LARGE = 600,
/// The attempt to find the object found an object matching by ID on the volume but it is out of the scope of the handle used for the operation.
FOUND_OUT_OF_SCOPE = 601,
/// The bucket array must be grown. Retry transaction after doing so.
ALLOCATE_BUCKET = 602,
/// The user/kernel marshalling buffer has overflowed.
MARSHALL_OVERFLOW = 603,
/// The supplied variant structure contains invalid data.
INVALID_VARIANT = 604,
/// The specified buffer contains ill-formed data.
BAD_COMPRESSION_BUFFER = 605,
/// {Audit Failed} An attempt to generate a security audit failed.
AUDIT_FAILED = 606,
/// The timer resolution was not previously set by the current process.
TIMER_RESOLUTION_NOT_SET = 607,
/// There is insufficient account information to log you on.
INSUFFICIENT_LOGON_INFO = 608,
/// {Invalid DLL Entrypoint} The dynamic link library %hs is not written correctly.
/// The stack pointer has been left in an inconsistent state.
/// The entrypoint should be declared as WINAPI or STDCALL.
/// Select YES to fail the DLL load. Select NO to continue execution.
/// Selecting NO may cause the application to operate incorrectly.
BAD_DLL_ENTRYPOINT = 609,
/// {Invalid Service Callback Entrypoint} The %hs service is not written correctly.
/// The stack pointer has been left in an inconsistent state.
/// The callback entrypoint should be declared as WINAPI or STDCALL.
/// Selecting OK will cause the service to continue operation.
/// However, the service process may operate incorrectly.
BAD_SERVICE_ENTRYPOINT = 610,
/// There is an IP address conflict with another system on the network.
IP_ADDRESS_CONFLICT1 = 611,
/// There is an IP address conflict with another system on the network.
IP_ADDRESS_CONFLICT2 = 612,
/// {Low On Registry Space} The system has reached the maximum size allowed for the system part of the registry. Additional storage requests will be ignored.
REGISTRY_QUOTA_LIMIT = 613,
/// A callback return system service cannot be executed when no callback is active.
NO_CALLBACK_ACTIVE = 614,
/// The password provided is too short to meet the policy of your user account. Please choose a longer password.
PWD_TOO_SHORT = 615,
/// The policy of your user account does not allow you to change passwords too frequently.
/// This is done to prevent users from changing back to a familiar, but potentially discovered, password.
/// If you feel your password has been compromised then please contact your administrator immediately to have a new one assigned.
PWD_TOO_RECENT = 616,
/// You have attempted to change your password to one that you have used in the past.
/// The policy of your user account does not allow this.
/// Please select a password that you have not previously used.
PWD_HISTORY_CONFLICT = 617,
/// The specified compression format is unsupported.
UNSUPPORTED_COMPRESSION = 618,
/// The specified hardware profile configuration is invalid.
INVALID_HW_PROFILE = 619,
/// The specified Plug and Play registry device path is invalid.
INVALID_PLUGPLAY_DEVICE_PATH = 620,
/// The specified quota list is internally inconsistent with its descriptor.
QUOTA_LIST_INCONSISTENT = 621,
/// {Windows Evaluation Notification} The evaluation period for this installation of Windows has expired. This system will shutdown in 1 hour.
/// To restore access to this installation of Windows, please upgrade this installation using a licensed distribution of this product.
EVALUATION_EXPIRATION = 622,
/// {Illegal System DLL Relocation} The system DLL %hs was relocated in memory. The application will not run properly.
/// The relocation occurred because the DLL %hs occupied an address range reserved for Windows system DLLs.
/// The vendor supplying the DLL should be contacted for a new DLL.
ILLEGAL_DLL_RELOCATION = 623,
/// {DLL Initialization Failed} The application failed to initialize because the window station is shutting down.
DLL_INIT_FAILED_LOGOFF = 624,
/// The validation process needs to continue on to the next step.
VALIDATE_CONTINUE = 625,
/// There are no more matches for the current index enumeration.
NO_MORE_MATCHES = 626,
/// The range could not be added to the range list because of a conflict.
RANGE_LIST_CONFLICT = 627,
/// The server process is running under a SID different than that required by client.
SERVER_SID_MISMATCH = 628,
/// A group marked use for deny only cannot be enabled.
CANT_ENABLE_DENY_ONLY = 629,
/// {EXCEPTION} Multiple floating point faults.
FLOAT_MULTIPLE_FAULTS = 630,
/// {EXCEPTION} Multiple floating point traps.
FLOAT_MULTIPLE_TRAPS = 631,
/// The requested interface is not supported.
NOINTERFACE = 632,
/// {System Standby Failed} The driver %hs does not support standby mode.
/// Updating this driver may allow the system to go to standby mode.
DRIVER_FAILED_SLEEP = 633,
/// The system file %1 has become corrupt and has been replaced.
CORRUPT_SYSTEM_FILE = 634,
/// {Virtual Memory Minimum Too Low} Your system is low on virtual memory.
/// Windows is increasing the size of your virtual memory paging file.
/// During this process, memory requests for some applications may be denied. For more information, see Help.
COMMITMENT_MINIMUM = 635,
/// A device was removed so enumeration must be restarted.
PNP_RESTART_ENUMERATION = 636,
/// {Fatal System Error} The system image %s is not properly signed.
/// The file has been replaced with the signed file. The system has been shut down.
SYSTEM_IMAGE_BAD_SIGNATURE = 637,
/// Device will not start without a reboot.
PNP_REBOOT_REQUIRED = 638,
/// There is not enough power to complete the requested operation.
INSUFFICIENT_POWER = 639,
/// ERROR_MULTIPLE_FAULT_VIOLATION
MULTIPLE_FAULT_VIOLATION = 640,
/// The system is in the process of shutting down.
SYSTEM_SHUTDOWN = 641,
/// An attempt to remove a processes DebugPort was made, but a port was not already associated with the process.
PORT_NOT_SET = 642,
/// This version of Windows is not compatible with the behavior version of directory forest, domain or domain controller.
DS_VERSION_CHECK_FAILURE = 643,
/// The specified range could not be found in the range list.
RANGE_NOT_FOUND = 644,
/// The driver was not loaded because the system is booting into safe mode.
NOT_SAFE_MODE_DRIVER = 646,
/// The driver was not loaded because it failed its initialization call.
FAILED_DRIVER_ENTRY = 647,
/// The "%hs" encountered an error while applying power or reading the device configuration.
/// This may be caused by a failure of your hardware or by a poor connection.
DEVICE_ENUMERATION_ERROR = 648,
/// The create operation failed because the name contained at least one mount point which resolves to a volume to which the specified device object is not attached.
MOUNT_POINT_NOT_RESOLVED = 649,
/// The device object parameter is either not a valid device object or is not attached to the volume specified by the file name.
INVALID_DEVICE_OBJECT_PARAMETER = 650,
/// A Machine Check Error has occurred.
/// Please check the system eventlog for additional information.
MCA_OCCURED = 651,
/// There was error [%2] processing the driver database.
DRIVER_DATABASE_ERROR = 652,
/// System hive size has exceeded its limit.
SYSTEM_HIVE_TOO_LARGE = 653,
/// The driver could not be loaded because a previous version of the driver is still in memory.
DRIVER_FAILED_PRIOR_UNLOAD = 654,
/// {Volume Shadow Copy Service} Please wait while the Volume Shadow Copy Service prepares volume %hs for hibernation.
VOLSNAP_PREPARE_HIBERNATE = 655,
/// The system has failed to hibernate (The error code is %hs).
/// Hibernation will be disabled until the system is restarted.
HIBERNATION_FAILURE = 656,
/// The password provided is too long to meet the policy of your user account. Please choose a shorter password.
PWD_TOO_LONG = 657,
/// The requested operation could not be completed due to a file system limitation.
FILE_SYSTEM_LIMITATION = 665,
/// An assertion failure has occurred.
ASSERTION_FAILURE = 668,
/// An error occurred in the ACPI subsystem.
ACPI_ERROR = 669,
/// WOW Assertion Error.
WOW_ASSERTION = 670,
/// A device is missing in the system BIOS MPS table. This device will not be used.
/// Please contact your system vendor for system BIOS update.
PNP_BAD_MPS_TABLE = 671,
/// A translator failed to translate resources.
PNP_TRANSLATION_FAILED = 672,
/// A IRQ translator failed to translate resources.
PNP_IRQ_TRANSLATION_FAILED = 673,
/// Driver %2 returned invalid ID for a child device (%3).
PNP_INVALID_ID = 674,
/// {Kernel Debugger Awakened} the system debugger was awakened by an interrupt.
WAKE_SYSTEM_DEBUGGER = 675,
/// {Handles Closed} Handles to objects have been automatically closed as a result of the requested operation.
HANDLES_CLOSED = 676,
/// {Too Much Information} The specified access control list (ACL) contained more information than was expected.
EXTRANEOUS_INFORMATION = 677,
/// This warning level status indicates that the transaction state already exists for the registry sub-tree, but that a transaction commit was previously aborted.
/// The commit has NOT been completed, but has not been rolled back either (so it may still be committed if desired).
RXACT_COMMIT_NECESSARY = 678,
/// {Media Changed} The media may have changed.
MEDIA_CHECK = 679,
/// {GUID Substitution} During the translation of a global identifier (GUID) to a Windows security ID (SID), no administratively-defined GUID prefix was found.
/// A substitute prefix was used, which will not compromise system security.
/// However, this may provide a more restrictive access than intended.
GUID_SUBSTITUTION_MADE = 680,
/// The create operation stopped after reaching a symbolic link.
STOPPED_ON_SYMLINK = 681,
/// A long jump has been executed.
LONGJUMP = 682,
/// The Plug and Play query operation was not successful.
PLUGPLAY_QUERY_VETOED = 683,
/// A frame consolidation has been executed.
UNWIND_CONSOLIDATE = 684,
/// {Registry Hive Recovered} Registry hive (file): %hs was corrupted and it has been recovered. Some data might have been lost.
REGISTRY_HIVE_RECOVERED = 685,
/// The application is attempting to run executable code from the module %hs. This may be insecure.
/// An alternative, %hs, is available. Should the application use the secure module %hs?
DLL_MIGHT_BE_INSECURE = 686,
/// The application is loading executable code from the module %hs.
/// This is secure, but may be incompatible with previous releases of the operating system.
/// An alternative, %hs, is available. Should the application use the secure module %hs?
DLL_MIGHT_BE_INCOMPATIBLE = 687,
/// Debugger did not handle the exception.
DBG_EXCEPTION_NOT_HANDLED = 688,
/// Debugger will reply later.
DBG_REPLY_LATER = 689,
/// Debugger cannot provide handle.
DBG_UNABLE_TO_PROVIDE_HANDLE = 690,
/// Debugger terminated thread.
DBG_TERMINATE_THREAD = 691,
/// Debugger terminated process.
DBG_TERMINATE_PROCESS = 692,
/// Debugger got control C.
DBG_CONTROL_C = 693,
/// Debugger printed exception on control C.
DBG_PRINTEXCEPTION_C = 694,
/// Debugger received RIP exception.
DBG_RIPEXCEPTION = 695,
/// Debugger received control break.
DBG_CONTROL_BREAK = 696,
/// Debugger command communication exception.
DBG_COMMAND_EXCEPTION = 697,
/// {Object Exists} An attempt was made to create an object and the object name already existed.
OBJECT_NAME_EXISTS = 698,
/// {Thread Suspended} A thread termination occurred while the thread was suspended.
/// The thread was resumed, and termination proceeded.
THREAD_WAS_SUSPENDED = 699,
/// {Image Relocated} An image file could not be mapped at the address specified in the image file. Local fixups must be performed on this image.
IMAGE_NOT_AT_BASE = 700,
/// This informational level status indicates that a specified registry sub-tree transaction state did not yet exist and had to be created.
RXACT_STATE_CREATED = 701,
/// {Segment Load} A virtual DOS machine (VDM) is loading, unloading, or moving an MS-DOS or Win16 program segment image.
/// An exception is raised so a debugger can load, unload or track symbols and breakpoints within these 16-bit segments.
SEGMENT_NOTIFICATION = 702,
/// {Invalid Current Directory} The process cannot switch to the startup current directory %hs.
/// Select OK to set current directory to %hs, or select CANCEL to exit.
BAD_CURRENT_DIRECTORY = 703,
/// {Redundant Read} To satisfy a read request, the NT fault-tolerant file system successfully read the requested data from a redundant copy.
/// This was done because the file system encountered a failure on a member of the fault-tolerant volume, but was unable to reassign the failing area of the device.
FT_READ_RECOVERY_FROM_BACKUP = 704,
/// {Redundant Write} To satisfy a write request, the NT fault-tolerant file system successfully wrote a redundant copy of the information.
/// This was done because the file system encountered a failure on a member of the fault-tolerant volume, but was not able to reassign the failing area of the device.
FT_WRITE_RECOVERY = 705,
/// {Machine Type Mismatch} The image file %hs is valid, but is for a machine type other than the current machine.
/// Select OK to continue, or CANCEL to fail the DLL load.
IMAGE_MACHINE_TYPE_MISMATCH = 706,
/// {Partial Data Received} The network transport returned partial data to its client. The remaining data will be sent later.
RECEIVE_PARTIAL = 707,
/// {Expedited Data Received} The network transport returned data to its client that was marked as expedited by the remote system.
RECEIVE_EXPEDITED = 708,
/// {Partial Expedited Data Received} The network transport returned partial data to its client and this data was marked as expedited by the remote system. The remaining data will be sent later.
RECEIVE_PARTIAL_EXPEDITED = 709,
/// {TDI Event Done} The TDI indication has completed successfully.
EVENT_DONE = 710,
/// {TDI Event Pending} The TDI indication has entered the pending state.
EVENT_PENDING = 711,
/// Checking file system on %wZ.
CHECKING_FILE_SYSTEM = 712,
/// {Fatal Application Exit} %hs.
FATAL_APP_EXIT = 713,
/// The specified registry key is referenced by a predefined handle.
PREDEFINED_HANDLE = 714,
/// {Page Unlocked} The page protection of a locked page was changed to 'No Access' and the page was unlocked from memory and from the process.
WAS_UNLOCKED = 715,
/// %hs
SERVICE_NOTIFICATION = 716,
/// {Page Locked} One of the pages to lock was already locked.
WAS_LOCKED = 717,
/// Application popup: %1 : %2
LOG_HARD_ERROR = 718,
/// ERROR_ALREADY_WIN32
ALREADY_WIN32 = 719,
/// {Machine Type Mismatch} The image file %hs is valid, but is for a machine type other than the current machine.
IMAGE_MACHINE_TYPE_MISMATCH_EXE = 720,
/// A yield execution was performed and no thread was available to run.
NO_YIELD_PERFORMED = 721,
/// The resumable flag to a timer API was ignored.
TIMER_RESUME_IGNORED = 722,
/// The arbiter has deferred arbitration of these resources to its parent.
ARBITRATION_UNHANDLED = 723,
/// The inserted CardBus device cannot be started because of a configuration error on "%hs".
CARDBUS_NOT_SUPPORTED = 724,
/// The CPUs in this multiprocessor system are not all the same revision level.
/// To use all processors the operating system restricts itself to the features of the least capable processor in the system.
/// Should problems occur with this system, contact the CPU manufacturer to see if this mix of processors is supported.
MP_PROCESSOR_MISMATCH = 725,
/// The system was put into hibernation.
HIBERNATED = 726,
/// The system was resumed from hibernation.
RESUME_HIBERNATION = 727,
/// Windows has detected that the system firmware (BIOS) was updated [previous firmware date = %2, current firmware date %3].
FIRMWARE_UPDATED = 728,
/// A device driver is leaking locked I/O pages causing system degradation.
/// The system has automatically enabled tracking code in order to try and catch the culprit.
DRIVERS_LEAKING_LOCKED_PAGES = 729,
/// The system has awoken.
WAKE_SYSTEM = 730,
/// ERROR_WAIT_1
WAIT_1 = 731,
/// ERROR_WAIT_2
WAIT_2 = 732,
/// ERROR_WAIT_3
WAIT_3 = 733,
/// ERROR_WAIT_63
WAIT_63 = 734,
/// ERROR_ABANDONED_WAIT_0
ABANDONED_WAIT_0 = 735,
/// ERROR_ABANDONED_WAIT_63
ABANDONED_WAIT_63 = 736,
/// ERROR_USER_APC
USER_APC = 737,
/// ERROR_KERNEL_APC
KERNEL_APC = 738,
/// ERROR_ALERTED
ALERTED = 739,
/// The requested operation requires elevation.
ELEVATION_REQUIRED = 740,
/// A reparse should be performed by the Object Manager since the name of the file resulted in a symbolic link.
REPARSE = 741,
/// An open/create operation completed while an oplock break is underway.
OPLOCK_BREAK_IN_PROGRESS = 742,
/// A new volume has been mounted by a file system.
VOLUME_MOUNTED = 743,
/// This success level status indicates that the transaction state already exists for the registry sub-tree, but that a transaction commit was previously aborted. The commit has now been completed.
RXACT_COMMITTED = 744,
/// This indicates that a notify change request has been completed due to closing the handle which made the notify change request.
NOTIFY_CLEANUP = 745,
/// {Connect Failure on Primary Transport} An attempt was made to connect to the remote server %hs on the primary transport, but the connection failed.
/// The computer WAS able to connect on a secondary transport.
PRIMARY_TRANSPORT_CONNECT_FAILED = 746,
/// Page fault was a transition fault.
PAGE_FAULT_TRANSITION = 747,
/// Page fault was a demand zero fault.
PAGE_FAULT_DEMAND_ZERO = 748,
/// Page fault was a demand zero fault.
PAGE_FAULT_COPY_ON_WRITE = 749,
/// Page fault was a demand zero fault.
PAGE_FAULT_GUARD_PAGE = 750,
/// Page fault was satisfied by reading from a secondary storage device.
PAGE_FAULT_PAGING_FILE = 751,
/// Cached page was locked during operation.
CACHE_PAGE_LOCKED = 752,
/// Crash dump exists in paging file.
CRASH_DUMP = 753,
/// Specified buffer contains all zeros.
BUFFER_ALL_ZEROS = 754,
/// A reparse should be performed by the Object Manager since the name of the file resulted in a symbolic link.
REPARSE_OBJECT = 755,
/// The device has succeeded a query-stop and its resource requirements have changed.
RESOURCE_REQUIREMENTS_CHANGED = 756,
/// The translator has translated these resources into the global space and no further translations should be performed.
TRANSLATION_COMPLETE = 757,
/// A process being terminated has no threads to terminate.
NOTHING_TO_TERMINATE = 758,
/// The specified process is not part of a job.
PROCESS_NOT_IN_JOB = 759,
/// The specified process is part of a job.
PROCESS_IN_JOB = 760,
/// {Volume Shadow Copy Service} The system is now ready for hibernation.
VOLSNAP_HIBERNATE_READY = 761,
/// A file system or file system filter driver has successfully completed an FsFilter operation.
FSFILTER_OP_COMPLETED_SUCCESSFULLY = 762,
/// The specified interrupt vector was already connected.
INTERRUPT_VECTOR_ALREADY_CONNECTED = 763,
/// The specified interrupt vector is still connected.
INTERRUPT_STILL_CONNECTED = 764,
/// An operation is blocked waiting for an oplock.
WAIT_FOR_OPLOCK = 765,
/// Debugger handled exception.
DBG_EXCEPTION_HANDLED = 766,
/// Debugger continued.
DBG_CONTINUE = 767,
/// An exception occurred in a user mode callback and the kernel callback frame should be removed.
CALLBACK_POP_STACK = 768,
/// Compression is disabled for this volume.
COMPRESSION_DISABLED = 769,
/// The data provider cannot fetch backwards through a result set.
CANTFETCHBACKWARDS = 770,
/// The data provider cannot scroll backwards through a result set.
CANTSCROLLBACKWARDS = 771,
/// The data provider requires that previously fetched data is released before asking for more data.
ROWSNOTRELEASED = 772,
/// The data provider was not able to interpret the flags set for a column binding in an accessor.
BAD_ACCESSOR_FLAGS = 773,
/// One or more errors occurred while processing the request.
ERRORS_ENCOUNTERED = 774,
/// The implementation is not capable of performing the request.
NOT_CAPABLE = 775,
/// The client of a component requested an operation which is not valid given the state of the component instance.
REQUEST_OUT_OF_SEQUENCE = 776,
/// A version number could not be parsed.
VERSION_PARSE_ERROR = 777,
/// The iterator's start position is invalid.
BADSTARTPOSITION = 778,
/// The hardware has reported an uncorrectable memory error.
MEMORY_HARDWARE = 779,
/// The attempted operation required self healing to be enabled.
DISK_REPAIR_DISABLED = 780,
/// The Desktop heap encountered an error while allocating session memory.
/// There is more information in the system event log.
INSUFFICIENT_RESOURCE_FOR_SPECIFIED_SHARED_SECTION_SIZE = 781,
/// The system power state is transitioning from %2 to %3.
SYSTEM_POWERSTATE_TRANSITION = 782,
/// The system power state is transitioning from %2 to %3 but could enter %4.
SYSTEM_POWERSTATE_COMPLEX_TRANSITION = 783,
/// A thread is getting dispatched with MCA EXCEPTION because of MCA.
MCA_EXCEPTION = 784,
/// Access to %1 is monitored by policy rule %2.
ACCESS_AUDIT_BY_POLICY = 785,
/// Access to %1 has been restricted by your Administrator by policy rule %2.
ACCESS_DISABLED_NO_SAFER_UI_BY_POLICY = 786,
/// A valid hibernation file has been invalidated and should be abandoned.
ABANDON_HIBERFILE = 787,
/// {Delayed Write Failed} Windows was unable to save all the data for the file %hs; the data has been lost.
/// This error may be caused by network connectivity issues. Please try to save this file elsewhere.
LOST_WRITEBEHIND_DATA_NETWORK_DISCONNECTED = 788,
/// {Delayed Write Failed} Windows was unable to save all the data for the file %hs; the data has been lost.
/// This error was returned by the server on which the file exists. Please try to save this file elsewhere.
LOST_WRITEBEHIND_DATA_NETWORK_SERVER_ERROR = 789,
/// {Delayed Write Failed} Windows was unable to save all the data for the file %hs; the data has been lost.
/// This error may be caused if the device has been removed or the media is write-protected.
LOST_WRITEBEHIND_DATA_LOCAL_DISK_ERROR = 790,
/// The resources required for this device conflict with the MCFG table.
BAD_MCFG_TABLE = 791,
/// The volume repair could not be performed while it is online.
/// Please schedule to take the volume offline so that it can be repaired.
DISK_REPAIR_REDIRECTED = 792,
/// The volume repair was not successful.
DISK_REPAIR_UNSUCCESSFUL = 793,
/// One of the volume corruption logs is full.
/// Further corruptions that may be detected won't be logged.
CORRUPT_LOG_OVERFULL = 794,
/// One of the volume corruption logs is internally corrupted and needs to be recreated.
/// The volume may contain undetected corruptions and must be scanned.
CORRUPT_LOG_CORRUPTED = 795,
/// One of the volume corruption logs is unavailable for being operated on.
CORRUPT_LOG_UNAVAILABLE = 796,
/// One of the volume corruption logs was deleted while still having corruption records in them.
/// The volume contains detected corruptions and must be scanned.
CORRUPT_LOG_DELETED_FULL = 797,
/// One of the volume corruption logs was cleared by chkdsk and no longer contains real corruptions.
CORRUPT_LOG_CLEARED = 798,
/// Orphaned files exist on the volume but could not be recovered because no more new names could be created in the recovery directory. Files must be moved from the recovery directory.
ORPHAN_NAME_EXHAUSTED = 799,
/// The oplock that was associated with this handle is now associated with a different handle.
OPLOCK_SWITCHED_TO_NEW_HANDLE = 800,
/// An oplock of the requested level cannot be granted. An oplock of a lower level may be available.
CANNOT_GRANT_REQUESTED_OPLOCK = 801,
/// The operation did not complete successfully because it would cause an oplock to be broken.
/// The caller has requested that existing oplocks not be broken.
CANNOT_BREAK_OPLOCK = 802,
/// The handle with which this oplock was associated has been closed. The oplock is now broken.
OPLOCK_HANDLE_CLOSED = 803,
/// The specified access control entry (ACE) does not contain a condition.
NO_ACE_CONDITION = 804,
/// The specified access control entry (ACE) contains an invalid condition.
INVALID_ACE_CONDITION = 805,
/// Access to the specified file handle has been revoked.
FILE_HANDLE_REVOKED = 806,
/// An image file was mapped at a different address from the one specified in the image file but fixups will still be automatically performed on the image.
IMAGE_AT_DIFFERENT_BASE = 807,
/// Access to the extended attribute was denied.
EA_ACCESS_DENIED = 994,
/// The I/O operation has been aborted because of either a thread exit or an application request.
OPERATION_ABORTED = 995,
/// Overlapped I/O event is not in a signaled state.
IO_INCOMPLETE = 996,
/// Overlapped I/O operation is in progress.
IO_PENDING = 997,
/// Invalid access to memory location.
NOACCESS = 998,
/// Error performing inpage operation.
SWAPERROR = 999,
/// Recursion too deep; the stack overflowed.
STACK_OVERFLOW = 1001,
/// The window cannot act on the sent message.
INVALID_MESSAGE = 1002,
/// Cannot complete this function.
CAN_NOT_COMPLETE = 1003,
/// Invalid flags.
INVALID_FLAGS = 1004,
/// The volume does not contain a recognized file system.
/// Please make sure that all required file system drivers are loaded and that the volume is not corrupted.
UNRECOGNIZED_VOLUME = 1005,
/// The volume for a file has been externally altered so that the opened file is no longer valid.
FILE_INVALID = 1006,
/// The requested operation cannot be performed in full-screen mode.
FULLSCREEN_MODE = 1007,
/// An attempt was made to reference a token that does not exist.
NO_TOKEN = 1008,
/// The configuration registry database is corrupt.
BADDB = 1009,
/// The configuration registry key is invalid.
BADKEY = 1010,
/// The configuration registry key could not be opened.
CANTOPEN = 1011,
/// The configuration registry key could not be read.
CANTREAD = 1012,
/// The configuration registry key could not be written.
CANTWRITE = 1013,
/// One of the files in the registry database had to be recovered by use of a log or alternate copy. The recovery was successful.
REGISTRY_RECOVERED = 1014,
/// The registry is corrupted. The structure of one of the files containing registry data is corrupted, or the system's memory image of the file is corrupted, or the file could not be recovered because the alternate copy or log was absent or corrupted.
REGISTRY_CORRUPT = 1015,
/// An I/O operation initiated by the registry failed unrecoverably.
/// The registry could not read in, or write out, or flush, one of the files that contain the system's image of the registry.
REGISTRY_IO_FAILED = 1016,
/// The system has attempted to load or restore a file into the registry, but the specified file is not in a registry file format.
NOT_REGISTRY_FILE = 1017,
/// Illegal operation attempted on a registry key that has been marked for deletion.
KEY_DELETED = 1018,
/// System could not allocate the required space in a registry log.
NO_LOG_SPACE = 1019,
/// Cannot create a symbolic link in a registry key that already has subkeys or values.
KEY_HAS_CHILDREN = 1020,
/// Cannot create a stable subkey under a volatile parent key.
CHILD_MUST_BE_VOLATILE = 1021,
/// A notify change request is being completed and the information is not being returned in the caller's buffer.
/// The caller now needs to enumerate the files to find the changes.
NOTIFY_ENUM_DIR = 1022,
/// A stop control has been sent to a service that other running services are dependent on.
DEPENDENT_SERVICES_RUNNING = 1051,
/// The requested control is not valid for this service.
INVALID_SERVICE_CONTROL = 1052,
/// The service did not respond to the start or control request in a timely fashion.
SERVICE_REQUEST_TIMEOUT = 1053,
/// A thread could not be created for the service.
SERVICE_NO_THREAD = 1054,
/// The service database is locked.
SERVICE_DATABASE_LOCKED = 1055,
/// An instance of the service is already running.
SERVICE_ALREADY_RUNNING = 1056,
/// The account name is invalid or does not exist, or the password is invalid for the account name specified.
INVALID_SERVICE_ACCOUNT = 1057,
/// The service cannot be started, either because it is disabled or because it has no enabled devices associated with it.
SERVICE_DISABLED = 1058,
/// Circular service dependency was specified.
CIRCULAR_DEPENDENCY = 1059,
/// The specified service does not exist as an installed service.
SERVICE_DOES_NOT_EXIST = 1060,
/// The service cannot accept control messages at this time.
SERVICE_CANNOT_ACCEPT_CTRL = 1061,
/// The service has not been started.
SERVICE_NOT_ACTIVE = 1062,
/// The service process could not connect to the service controller.
FAILED_SERVICE_CONTROLLER_CONNECT = 1063,
/// An exception occurred in the service when handling the control request.
EXCEPTION_IN_SERVICE = 1064,
/// The database specified does not exist.
DATABASE_DOES_NOT_EXIST = 1065,
/// The service has returned a service-specific error code.
SERVICE_SPECIFIC_ERROR = 1066,
/// The process terminated unexpectedly.
PROCESS_ABORTED = 1067,
/// The dependency service or group failed to start.
SERVICE_DEPENDENCY_FAIL = 1068,
/// The service did not start due to a logon failure.
SERVICE_LOGON_FAILED = 1069,
/// After starting, the service hung in a start-pending state.
SERVICE_START_HANG = 1070,
/// The specified service database lock is invalid.
INVALID_SERVICE_LOCK = 1071,
/// The specified service has been marked for deletion.
SERVICE_MARKED_FOR_DELETE = 1072,
/// The specified service already exists.
SERVICE_EXISTS = 1073,
/// The system is currently running with the last-known-good configuration.
ALREADY_RUNNING_LKG = 1074,
/// The dependency service does not exist or has been marked for deletion.
SERVICE_DEPENDENCY_DELETED = 1075,
/// The current boot has already been accepted for use as the last-known-good control set.
BOOT_ALREADY_ACCEPTED = 1076,
/// No attempts to start the service have been made since the last boot.
SERVICE_NEVER_STARTED = 1077,
/// The name is already in use as either a service name or a service display name.
DUPLICATE_SERVICE_NAME = 1078,
/// The account specified for this service is different from the account specified for other services running in the same process.
DIFFERENT_SERVICE_ACCOUNT = 1079,
/// Failure actions can only be set for Win32 services, not for drivers.
CANNOT_DETECT_DRIVER_FAILURE = 1080,
/// This service runs in the same process as the service control manager.
/// Therefore, the service control manager cannot take action if this service's process terminates unexpectedly.
CANNOT_DETECT_PROCESS_ABORT = 1081,
/// No recovery program has been configured for this service.
NO_RECOVERY_PROGRAM = 1082,
/// The executable program that this service is configured to run in does not implement the service.
SERVICE_NOT_IN_EXE = 1083,
/// This service cannot be started in Safe Mode.
NOT_SAFEBOOT_SERVICE = 1084,
/// The physical end of the tape has been reached.
END_OF_MEDIA = 1100,
/// A tape access reached a filemark.
FILEMARK_DETECTED = 1101,
/// The beginning of the tape or a partition was encountered.
BEGINNING_OF_MEDIA = 1102,
/// A tape access reached the end of a set of files.
SETMARK_DETECTED = 1103,
/// No more data is on the tape.
NO_DATA_DETECTED = 1104,
/// Tape could not be partitioned.
PARTITION_FAILURE = 1105,
/// When accessing a new tape of a multivolume partition, the current block size is incorrect.
INVALID_BLOCK_LENGTH = 1106,
/// Tape partition information could not be found when loading a tape.
DEVICE_NOT_PARTITIONED = 1107,
/// Unable to lock the media eject mechanism.
UNABLE_TO_LOCK_MEDIA = 1108,
/// Unable to unload the media.
UNABLE_TO_UNLOAD_MEDIA = 1109,
/// The media in the drive may have changed.
MEDIA_CHANGED = 1110,
/// The I/O bus was reset.
BUS_RESET = 1111,
/// No media in drive.
NO_MEDIA_IN_DRIVE = 1112,
/// No mapping for the Unicode character exists in the target multi-byte code page.
NO_UNICODE_TRANSLATION = 1113,
/// A dynamic link library (DLL) initialization routine failed.
DLL_INIT_FAILED = 1114,
/// A system shutdown is in progress.
SHUTDOWN_IN_PROGRESS = 1115,
/// Unable to abort the system shutdown because no shutdown was in progress.
NO_SHUTDOWN_IN_PROGRESS = 1116,
/// The request could not be performed because of an I/O device error.
IO_DEVICE = 1117,
/// No serial device was successfully initialized. The serial driver will unload.
SERIAL_NO_DEVICE = 1118,
/// Unable to open a device that was sharing an interrupt request (IRQ) with other devices.
/// At least one other device that uses that IRQ was already opened.
IRQ_BUSY = 1119,
/// A serial I/O operation was completed by another write to the serial port. The IOCTL_SERIAL_XOFF_COUNTER reached zero.)
MORE_WRITES = 1120,
/// A serial I/O operation completed because the timeout period expired.
/// The IOCTL_SERIAL_XOFF_COUNTER did not reach zero.)
COUNTER_TIMEOUT = 1121,
/// No ID address mark was found on the floppy disk.
FLOPPY_ID_MARK_NOT_FOUND = 1122,
/// Mismatch between the floppy disk sector ID field and the floppy disk controller track address.
FLOPPY_WRONG_CYLINDER = 1123,
/// The floppy disk controller reported an error that is not recognized by the floppy disk driver.
FLOPPY_UNKNOWN_ERROR = 1124,
/// The floppy disk controller returned inconsistent results in its registers.
FLOPPY_BAD_REGISTERS = 1125,
/// While accessing the hard disk, a recalibrate operation failed, even after retries.
DISK_RECALIBRATE_FAILED = 1126,
/// While accessing the hard disk, a disk operation failed even after retries.
DISK_OPERATION_FAILED = 1127,
/// While accessing the hard disk, a disk controller reset was needed, but even that failed.
DISK_RESET_FAILED = 1128,
/// Physical end of tape encountered.
EOM_OVERFLOW = 1129,
/// Not enough server storage is available to process this command.
NOT_ENOUGH_SERVER_MEMORY = 1130,
/// A potential deadlock condition has been detected.
POSSIBLE_DEADLOCK = 1131,
/// The base address or the file offset specified does not have the proper alignment.
MAPPED_ALIGNMENT = 1132,
/// An attempt to change the system power state was vetoed by another application or driver.
SET_POWER_STATE_VETOED = 1140,
/// The system BIOS failed an attempt to change the system power state.
SET_POWER_STATE_FAILED = 1141,
/// An attempt was made to create more links on a file than the file system supports.
TOO_MANY_LINKS = 1142,
/// The specified program requires a newer version of Windows.
OLD_WIN_VERSION = 1150,
/// The specified program is not a Windows or MS-DOS program.
APP_WRONG_OS = 1151,
/// Cannot start more than one instance of the specified program.
SINGLE_INSTANCE_APP = 1152,
/// The specified program was written for an earlier version of Windows.
RMODE_APP = 1153,
/// One of the library files needed to run this application is damaged.
INVALID_DLL = 1154,
/// No application is associated with the specified file for this operation.
NO_ASSOCIATION = 1155,
/// An error occurred in sending the command to the application.
DDE_FAIL = 1156,
/// One of the library files needed to run this application cannot be found.
DLL_NOT_FOUND = 1157,
/// The current process has used all of its system allowance of handles for Window Manager objects.
NO_MORE_USER_HANDLES = 1158,
/// The message can be used only with synchronous operations.
MESSAGE_SYNC_ONLY = 1159,
/// The indicated source element has no media.
SOURCE_ELEMENT_EMPTY = 1160,
/// The indicated destination element already contains media.
DESTINATION_ELEMENT_FULL = 1161,
/// The indicated element does not exist.
ILLEGAL_ELEMENT_ADDRESS = 1162,
/// The indicated element is part of a magazine that is not present.
MAGAZINE_NOT_PRESENT = 1163,
/// The indicated device requires reinitialization due to hardware errors.
DEVICE_REINITIALIZATION_NEEDED = 1164,
/// The device has indicated that cleaning is required before further operations are attempted.
DEVICE_REQUIRES_CLEANING = 1165,
/// The device has indicated that its door is open.
DEVICE_DOOR_OPEN = 1166,
/// The device is not connected.
DEVICE_NOT_CONNECTED = 1167,
/// Element not found.
NOT_FOUND = 1168,
/// There was no match for the specified key in the index.
NO_MATCH = 1169,
/// The property set specified does not exist on the object.
SET_NOT_FOUND = 1170,
/// The point passed to GetMouseMovePoints is not in the buffer.
POINT_NOT_FOUND = 1171,
/// The tracking (workstation) service is not running.
NO_TRACKING_SERVICE = 1172,
/// The Volume ID could not be found.
NO_VOLUME_ID = 1173,
/// Unable to remove the file to be replaced.
UNABLE_TO_REMOVE_REPLACED = 1175,
/// Unable to move the replacement file to the file to be replaced.
/// The file to be replaced has retained its original name.
UNABLE_TO_MOVE_REPLACEMENT = 1176,
/// Unable to move the replacement file to the file to be replaced.
/// The file to be replaced has been renamed using the backup name.
UNABLE_TO_MOVE_REPLACEMENT_2 = 1177,
/// The volume change journal is being deleted.
JOURNAL_DELETE_IN_PROGRESS = 1178,
/// The volume change journal is not active.
JOURNAL_NOT_ACTIVE = 1179,
/// A file was found, but it may not be the correct file.
POTENTIAL_FILE_FOUND = 1180,
/// The journal entry has been deleted from the journal.
JOURNAL_ENTRY_DELETED = 1181,
/// A system shutdown has already been scheduled.
SHUTDOWN_IS_SCHEDULED = 1190,
/// The system shutdown cannot be initiated because there are other users logged on to the computer.
SHUTDOWN_USERS_LOGGED_ON = 1191,
/// The specified device name is invalid.
BAD_DEVICE = 1200,
/// The device is not currently connected but it is a remembered connection.
CONNECTION_UNAVAIL = 1201,
/// The local device name has a remembered connection to another network resource.
DEVICE_ALREADY_REMEMBERED = 1202,
/// The network path was either typed incorrectly, does not exist, or the network provider is not currently available.
/// Please try retyping the path or contact your network administrator.
NO_NET_OR_BAD_PATH = 1203,
/// The specified network provider name is invalid.
BAD_PROVIDER = 1204,
/// Unable to open the network connection profile.
CANNOT_OPEN_PROFILE = 1205,
/// The network connection profile is corrupted.
BAD_PROFILE = 1206,
/// Cannot enumerate a noncontainer.
NOT_CONTAINER = 1207,
/// An extended error has occurred.
EXTENDED_ERROR = 1208,
/// The format of the specified group name is invalid.
INVALID_GROUPNAME = 1209,
/// The format of the specified computer name is invalid.
INVALID_COMPUTERNAME = 1210,
/// The format of the specified event name is invalid.
INVALID_EVENTNAME = 1211,
/// The format of the specified domain name is invalid.
INVALID_DOMAINNAME = 1212,
/// The format of the specified service name is invalid.
INVALID_SERVICENAME = 1213,
/// The format of the specified network name is invalid.
INVALID_NETNAME = 1214,
/// The format of the specified share name is invalid.
INVALID_SHARENAME = 1215,
/// The format of the specified password is invalid.
INVALID_PASSWORDNAME = <PASSWORD>,
/// The format of the specified message name is invalid.
INVALID_MESSAGENAME = 1217,
/// The format of the specified message destination is invalid.
INVALID_MESSAGEDEST = 1218,
/// Multiple connections to a server or shared resource by the same user, using more than one user name, are not allowed.
/// Disconnect all previous connections to the server or shared resource and try again.
SESSION_CREDENTIAL_CONFLICT = 1219,
/// An attempt was made to establish a session to a network server, but there are already too many sessions established to that server.
REMOTE_SESSION_LIMIT_EXCEEDED = 1220,
/// The workgroup or domain name is already in use by another computer on the network.
DUP_DOMAINNAME = 1221,
/// The network is not present or not started.
NO_NETWORK = 1222,
/// The operation was canceled by the user.
CANCELLED = 1223,
/// The requested operation cannot be performed on a file with a user-mapped section open.
USER_MAPPED_FILE = 1224,
/// The remote computer refused the network connection.
CONNECTION_REFUSED = 1225,
/// The network connection was gracefully closed.
GRACEFUL_DISCONNECT = 1226,
/// The network transport endpoint already has an address associated with it.
ADDRESS_ALREADY_ASSOCIATED = 1227,
/// An address has not yet been associated with the network endpoint.
ADDRESS_NOT_ASSOCIATED = 1228,
/// An operation was attempted on a nonexistent network connection.
CONNECTION_INVALID = 1229,
/// An invalid operation was attempted on an active network connection.
CONNECTION_ACTIVE = 1230,
/// The network location cannot be reached.
/// For information about network troubleshooting, see Windows Help.
NETWORK_UNREACHABLE = 1231,
/// The network location cannot be reached.
/// For information about network troubleshooting, see Windows Help.
HOST_UNREACHABLE = 1232,
/// The network location cannot be reached.
/// For information about network troubleshooting, see Windows Help.
PROTOCOL_UNREACHABLE = 1233,
/// No service is operating at the destination network endpoint on the remote system.
PORT_UNREACHABLE = 1234,
/// The request was aborted.
REQUEST_ABORTED = 1235,
/// The network connection was aborted by the local system.
CONNECTION_ABORTED = 1236,
/// The operation could not be completed. A retry should be performed.
RETRY = 1237,
/// A connection to the server could not be made because the limit on the number of concurrent connections for this account has been reached.
CONNECTION_COUNT_LIMIT = 1238,
/// Attempting to log in during an unauthorized time of day for this account.
LOGIN_TIME_RESTRICTION = 1239,
/// The account is not authorized to log in from this station.
LOGIN_WKSTA_RESTRICTION = 1240,
/// The network address could not be used for the operation requested.
INCORRECT_ADDRESS = 1241,
/// The service is already registered.
ALREADY_REGISTERED = 1242,
/// The specified service does not exist.
SERVICE_NOT_FOUND = 1243,
/// The operation being requested was not performed because the user has not been authenticated.
NOT_AUTHENTICATED = 1244,
/// The operation being requested was not performed because the user has not logged on to the network. The specified service does not exist.
NOT_LOGGED_ON = 1245,
/// Continue with work in progress.
CONTINUE = 1246,
/// An attempt was made to perform an initialization operation when initialization has already been completed.
ALREADY_INITIALIZED = 1247,
/// No more local devices.
NO_MORE_DEVICES = 1248,
/// The specified site does not exist.
NO_SUCH_SITE = 1249,
/// A domain controller with the specified name already exists.
DOMAIN_CONTROLLER_EXISTS = 1250,
/// This operation is supported only when you are connected to the server.
ONLY_IF_CONNECTED = 1251,
/// The group policy framework should call the extension even if there are no changes.
OVERRIDE_NOCHANGES = 1252,
/// The specified user does not have a valid profile.
BAD_USER_PROFILE = 1253,
/// This operation is not supported on a computer running Windows Server 2003 for Small Business Server.
NOT_SUPPORTED_ON_SBS = 1254,
/// The server machine is shutting down.
SERVER_SHUTDOWN_IN_PROGRESS = 1255,
/// The remote system is not available.
/// For information about network troubleshooting, see Windows Help.
HOST_DOWN = 1256,
/// The security identifier provided is not from an account domain.
NON_ACCOUNT_SID = 1257,
/// The security identifier provided does not have a domain component.
NON_DOMAIN_SID = 1258,
/// AppHelp dialog canceled thus preventing the application from starting.
APPHELP_BLOCK = 1259,
/// This program is blocked by group policy.
/// For more information, contact your system administrator.
ACCESS_DISABLED_BY_POLICY = 1260,
/// A program attempt to use an invalid register value.
/// Normally caused by an uninitialized register. This error is Itanium specific.
REG_NAT_CONSUMPTION = 1261,
/// The share is currently offline or does not exist.
CSCSHARE_OFFLINE = 1262,
/// The Kerberos protocol encountered an error while validating the KDC certificate during smartcard logon.
/// There is more information in the system event log.
PKINIT_FAILURE = 1263,
/// The Kerberos protocol encountered an error while attempting to utilize the smartcard subsystem.
SMARTCARD_SUBSYSTEM_FAILURE = 1264,
/// The system cannot contact a domain controller to service the authentication request. Please try again later.
DOWNGRADE_DETECTED = 1265,
/// The machine is locked and cannot be shut down without the force option.
MACHINE_LOCKED = 1271,
/// An application-defined callback gave invalid data when called.
CALLBACK_SUPPLIED_INVALID_DATA = 1273,
/// The group policy framework should call the extension in the synchronous foreground policy refresh.
SYNC_FOREGROUND_REFRESH_REQUIRED = 1274,
/// This driver has been blocked from loading.
DRIVER_BLOCKED = 1275,
/// A dynamic link library (DLL) referenced a module that was neither a DLL nor the process's executable image.
INVALID_IMPORT_OF_NON_DLL = 1276,
/// Windows cannot open this program since it has been disabled.
ACCESS_DISABLED_WEBBLADE = 1277,
/// Windows cannot open this program because the license enforcement system has been tampered with or become corrupted.
ACCESS_DISABLED_WEBBLADE_TAMPER = 1278,
/// A transaction recover failed.
RECOVERY_FAILURE = 1279,
/// The current thread has already been converted to a fiber.
ALREADY_FIBER = 1280,
/// The current thread has already been converted from a fiber.
ALREADY_THREAD = 1281,
/// The system detected an overrun of a stack-based buffer in this application.
/// This overrun could potentially allow a malicious user to gain control of this application.
STACK_BUFFER_OVERRUN = 1282,
/// Data present in one of the parameters is more than the function can operate on.
PARAMETER_QUOTA_EXCEEDED = 1283,
/// An attempt to do an operation on a debug object failed because the object is in the process of being deleted.
DEBUGGER_INACTIVE = 1284,
/// An attempt to delay-load a .dll or get a function address in a delay-loaded .dll failed.
DELAY_LOAD_FAILED = 1285,
/// %1 is a 16-bit application. You do not have permissions to execute 16-bit applications.
/// Check your permissions with your system administrator.
VDM_DISALLOWED = 1286,
/// Insufficient information exists to identify the cause of failure.
UNIDENTIFIED_ERROR = 1287,
/// The parameter passed to a C runtime function is incorrect.
INVALID_CRUNTIME_PARAMETER = 1288,
/// The operation occurred beyond the valid data length of the file.
BEYOND_VDL = 1289,
/// The service start failed since one or more services in the same process have an incompatible service SID type setting.
/// A service with restricted service SID type can only coexist in the same process with other services with a restricted SID type.
/// If the service SID type for this service was just configured, the hosting process must be restarted in order to start this service.
/// On Windows Server 2003 and Windows XP, an unrestricted service cannot coexist in the same process with other services.
/// The service with the unrestricted service SID type must be moved to an owned process in order to start this service.
INCOMPATIBLE_SERVICE_SID_TYPE = 1290,
/// The process hosting the driver for this device has been terminated.
DRIVER_PROCESS_TERMINATED = 1291,
/// An operation attempted to exceed an implementation-defined limit.
IMPLEMENTATION_LIMIT = 1292,
/// Either the target process, or the target thread's containing process, is a protected process.
PROCESS_IS_PROTECTED = 1293,
/// The service notification client is lagging too far behind the current state of services in the machine.
SERVICE_NOTIFY_CLIENT_LAGGING = 1294,
/// The requested file operation failed because the storage quota was exceeded.
/// To free up disk space, move files to a different location or delete unnecessary files.
/// For more information, contact your system administrator.
DISK_QUOTA_EXCEEDED = 1295,
/// The requested file operation failed because the storage policy blocks that type of file.
/// For more information, contact your system administrator.
CONTENT_BLOCKED = 1296,
/// A privilege that the service requires to function properly does not exist in the service account configuration.
/// You may use the Services Microsoft Management Console (MMC) snap-in (services.msc) and the Local Security Settings MMC snap-in (secpol.msc) to view the service configuration and the account configuration.
INCOMPATIBLE_SERVICE_PRIVILEGE = 1297,
/// A thread involved in this operation appears to be unresponsive.
APP_HANG = 1298,
/// Indicates a particular Security ID may not be assigned as the label of an object.
INVALID_LABEL = 1299,
/// Not all privileges or groups referenced are assigned to the caller.
NOT_ALL_ASSIGNED = 1300,
/// Some mapping between account names and security IDs was not done.
SOME_NOT_MAPPED = 1301,
/// No system quota limits are specifically set for this account.
NO_QUOTAS_FOR_ACCOUNT = 1302,
/// No encryption key is available. A well-known encryption key was returned.
LOCAL_USER_SESSION_KEY = 1303,
/// The password is too complex to be converted to a LAN Manager password.
/// The LAN Manager password returned is a NULL string.
NULL_LM_PASSWORD = <PASSWORD>,
/// The revision level is unknown.
UNKNOWN_REVISION = 1305,
/// Indicates two revision levels are incompatible.
REVISION_MISMATCH = 1306,
/// This security ID may not be assigned as the owner of this object.
INVALID_OWNER = 1307,
/// This security ID may not be assigned as the primary group of an object.
INVALID_PRIMARY_GROUP = 1308,
/// An attempt has been made to operate on an impersonation token by a thread that is not currently impersonating a client.
NO_IMPERSONATION_TOKEN = 1<PASSWORD>,
/// The group may not be disabled.
CANT_DISABLE_MANDATORY = 1310,
/// There are currently no logon servers available to service the logon request.
NO_LOGON_SERVERS = 1311,
/// A specified logon session does not exist. It may already have been terminated.
NO_SUCH_LOGON_SESSION = 1312,
/// A specified privilege does not exist.
NO_SUCH_PRIVILEGE = 1313,
/// A required privilege is not held by the client.
PRIVILEGE_NOT_HELD = 1314,
/// The name provided is not a properly formed account name.
INVALID_ACCOUNT_NAME = 1315,
/// The specified account already exists.
USER_EXISTS = 1316,
/// The specified account does not exist.
NO_SUCH_USER = 1317,
/// The specified group already exists.
GROUP_EXISTS = 1318,
/// The specified group does not exist.
NO_SUCH_GROUP = 1319,
/// Either the specified user account is already a member of the specified group, or the specified group cannot be deleted because it contains a member.
MEMBER_IN_GROUP = 1320,
/// The specified user account is not a member of the specified group account.
MEMBER_NOT_IN_GROUP = 1321,
/// This operation is disallowed as it could result in an administration account being disabled, deleted or unable to log on.
LAST_ADMIN = 1322,
/// Unable to update the password. The value provided as the current password is incorrect.
WRONG_PASSWORD = <PASSWORD>,
/// Unable to update the password. The value provided for the new password contains values that are not allowed in passwords.
ILL_FORMED_PASSWORD = <PASSWORD>,
/// Unable to update the password. The value provided for the new password does not meet the length, complexity, or history requirements of the domain.
PASSWORD_RESTRICTION = <PASSWORD>,
/// The user name or password is incorrect.
LOGON_FAILURE = 1326,
/// Account restrictions are preventing this user from signing in.
/// For example: blank passwords aren't allowed, sign-in times are limited, or a policy restriction has been enforced.
ACCOUNT_RESTRICTION = 1327,
/// Your account has time restrictions that keep you from signing in right now.
INVALID_LOGON_HOURS = 1328,
/// This user isn't allowed to sign in to this computer.
INVALID_WORKSTATION = 1329,
/// The password for this account has expired.
PASSWORD_EXPIRED = <PASSWORD>,
/// This user can't sign in because this account is currently disabled.
ACCOUNT_DISABLED = 1331,
/// No mapping between account names and security IDs was done.
NONE_MAPPED = 1332,
/// Too many local user identifiers (LUIDs) were requested at one time.
TOO_MANY_LUIDS_REQUESTED = 1333,
/// No more local user identifiers (LUIDs) are available.
LUIDS_EXHAUSTED = 1334,
/// The subauthority part of a security ID is invalid for this particular use.
INVALID_SUB_AUTHORITY = 1335,
/// The access control list (ACL) structure is invalid.
INVALID_ACL = 1336,
/// The security ID structure is invalid.
INVALID_SID = 1337,
/// The security descriptor structure is invalid.
INVALID_SECURITY_DESCR = 1338,
/// The inherited access control list (ACL) or access control entry (ACE) could not be built.
BAD_INHERITANCE_ACL = 1340,
/// The server is currently disabled.
SERVER_DISABLED = 1341,
/// The server is currently enabled.
SERVER_NOT_DISABLED = 1342,
/// The value provided was an invalid value for an identifier authority.
INVALID_ID_AUTHORITY = 1343,
/// No more memory is available for security information updates.
ALLOTTED_SPACE_EXCEEDED = 1344,
/// The specified attributes are invalid, or incompatible with the attributes for the group as a whole.
INVALID_GROUP_ATTRIBUTES = 1345,
/// Either a required impersonation level was not provided, or the provided impersonation level is invalid.
BAD_IMPERSONATION_LEVEL = 1346,
/// Cannot open an anonymous level security token.
CANT_OPEN_ANONYMOUS = 1347,
/// The validation information class requested was invalid.
BAD_VALIDATION_CLASS = 1348,
/// The type of the token is inappropriate for its attempted use.
BAD_TOKEN_TYPE = 1349,
/// Unable to perform a security operation on an object that has no associated security.
NO_SECURITY_ON_OBJECT = 1350,
/// Configuration information could not be read from the domain controller, either because the machine is unavailable, or access has been denied.
CANT_ACCESS_DOMAIN_INFO = 1351,
/// The security account manager (SAM) or local security authority (LSA) server was in the wrong state to perform the security operation.
INVALID_SERVER_STATE = 1352,
/// The domain was in the wrong state to perform the security operation.
INVALID_DOMAIN_STATE = 1353,
/// This operation is only allowed for the Primary Domain Controller of the domain.
INVALID_DOMAIN_ROLE = 1354,
/// The specified domain either does not exist or could not be contacted.
NO_SUCH_DOMAIN = 1355,
/// The specified domain already exists.
DOMAIN_EXISTS = 1356,
/// An attempt was made to exceed the limit on the number of domains per server.
DOMAIN_LIMIT_EXCEEDED = 1357,
/// Unable to complete the requested operation because of either a catastrophic media failure or a data structure corruption on the disk.
INTERNAL_DB_CORRUPTION = 1358,
/// An internal error occurred.
INTERNAL_ERROR = 1359,
/// Generic access types were contained in an access mask which should already be mapped to nongeneric types.
GENERIC_NOT_MAPPED = 1360,
/// A security descriptor is not in the right format (absolute or self-relative).
BAD_DESCRIPTOR_FORMAT = 1361,
/// The requested action is restricted for use by logon processes only.
/// The calling process has not registered as a logon process.
NOT_LOGON_PROCESS = 1362,
/// Cannot start a new logon session with an ID that is already in use.
LOGON_SESSION_EXISTS = 1363,
/// A specified authentication package is unknown.
NO_SUCH_PACKAGE = 1364,
/// The logon session is not in a state that is consistent with the requested operation.
BAD_LOGON_SESSION_STATE = 1365,
/// The logon session ID is already in use.
LOGON_SESSION_COLLISION = 1366,
/// A logon request contained an invalid logon type value.
INVALID_LOGON_TYPE = 1367,
/// Unable to impersonate using a named pipe until data has been read from that pipe.
CANNOT_IMPERSONATE = 1368,
/// The transaction state of a registry subtree is incompatible with the requested operation.
RXACT_INVALID_STATE = 1369,
/// An internal security database corruption has been encountered.
RXACT_COMMIT_FAILURE = 1370,
/// Cannot perform this operation on built-in accounts.
SPECIAL_ACCOUNT = 1371,
/// Cannot perform this operation on this built-in special group.
SPECIAL_GROUP = 1372,
/// Cannot perform this operation on this built-in special user.
SPECIAL_USER = 1373,
/// The user cannot be removed from a group because the group is currently the user's primary group.
MEMBERS_PRIMARY_GROUP = 1374,
/// The token is already in use as a primary token.
TOKEN_ALREADY_IN_USE = 1375,
/// The specified local group does not exist.
NO_SUCH_ALIAS = 1376,
/// The specified account name is not a member of the group.
MEMBER_NOT_IN_ALIAS = 1377,
/// The specified account name is already a member of the group.
MEMBER_IN_ALIAS = 1378,
/// The specified local group already exists.
ALIAS_EXISTS = 1379,
/// Logon failure: the user has not been granted the requested logon type at this computer.
LOGON_NOT_GRANTED = 1380,
/// The maximum number of secrets that may be stored in a single system has been exceeded.
TOO_MANY_SECRETS = 1381,
/// The length of a secret exceeds the maximum length allowed.
SECRET_TOO_LONG = 1382,
/// The local security authority database contains an internal inconsistency.
INTERNAL_DB_ERROR = 1383,
/// During a logon attempt, the user's security context accumulated too many security IDs.
TOO_MANY_CONTEXT_IDS = 1384,
/// Logon failure: the user has not been granted the requested logon type at this computer.
LOGON_TYPE_NOT_GRANTED = 1385,
/// A cross-encrypted password is necessary to change a user password.
NT_CROSS_ENCRYPTION_REQUIRED = 1386,
/// A member could not be added to or removed from the local group because the member does not exist.
NO_SUCH_MEMBER = 1387,
/// A new member could not be added to a local group because the member has the wrong account type.
INVALID_MEMBER = 1388,
/// Too many security IDs have been specified.
TOO_MANY_SIDS = 1389,
/// A cross-encrypted password is necessary to change this user password.
LM_CROSS_ENCRYPTION_REQUIRED = 1390,
/// Indicates an ACL contains no inheritable components.
NO_INHERITANCE = 1391,
/// The file or directory is corrupted and unreadable.
FILE_CORRUPT = 1392,
/// The disk structure is corrupted and unreadable.
DISK_CORRUPT = 1393,
/// There is no user session key for the specified logon session.
NO_USER_SESSION_KEY = 1394,
/// The service being accessed is licensed for a particular number of connections.
/// No more connections can be made to the service at this time because there are already as many connections as the service can accept.
LICENSE_QUOTA_EXCEEDED = 1395,
/// The target account name is incorrect.
WRONG_TARGET_NAME = 1396,
/// Mutual Authentication failed. The server's password is out of date at the domain controller.
MUTUAL_AUTH_FAILED = 1397,
/// There is a time and/or date difference between the client and server.
TIME_SKEW = 1398,
/// This operation cannot be performed on the current domain.
CURRENT_DOMAIN_NOT_ALLOWED = 1399,
/// Invalid window handle.
INVALID_WINDOW_HANDLE = 1400,
/// Invalid menu handle.
INVALID_MENU_HANDLE = 1401,
/// Invalid cursor handle.
INVALID_CURSOR_HANDLE = 1402,
/// Invalid accelerator table handle.
INVALID_ACCEL_HANDLE = 1403,
/// Invalid hook handle.
INVALID_HOOK_HANDLE = 1404,
/// Invalid handle to a multiple-window position structure.
INVALID_DWP_HANDLE = 1405,
/// Cannot create a top-level child window.
TLW_WITH_WSCHILD = 1406,
/// Cannot find window class.
CANNOT_FIND_WND_CLASS = 1407,
/// Invalid window; it belongs to other thread.
WINDOW_OF_OTHER_THREAD = 1408,
/// Hot key is already registered.
HOTKEY_ALREADY_REGISTERED = 1409,
/// Class already exists.
CLASS_ALREADY_EXISTS = 1410,
/// Class does not exist.
CLASS_DOES_NOT_EXIST = 1411,
/// Class still has open windows.
CLASS_HAS_WINDOWS = 1412,
/// Invalid index.
INVALID_INDEX = 1413,
/// Invalid icon handle.
INVALID_ICON_HANDLE = 1414,
/// Using private DIALOG window words.
PRIVATE_DIALOG_INDEX = 1415,
/// The list box identifier was not found.
LISTBOX_ID_NOT_FOUND = 1416,
/// No wildcards were found.
NO_WILDCARD_CHARACTERS = 1417,
/// Thread does not have a clipboard open.
CLIPBOARD_NOT_OPEN = 1418,
/// Hot key is not registered.
HOTKEY_NOT_REGISTERED = 1419,
/// The window is not a valid dialog window.
WINDOW_NOT_DIALOG = 1420,
/// Control ID not found.
CONTROL_ID_NOT_FOUND = 1421,
/// Invalid message for a combo box because it does not have an edit control.
INVALID_COMBOBOX_MESSAGE = 1422,
/// The window is not a combo box.
WINDOW_NOT_COMBOBOX = 1423,
/// Height must be less than 256.
INVALID_EDIT_HEIGHT = 1424,
/// Invalid device context (DC) handle.
DC_NOT_FOUND = 1425,
/// Invalid hook procedure type.
INVALID_HOOK_FILTER = 1426,
/// Invalid hook procedure.
INVALID_FILTER_PROC = 1427,
/// Cannot set nonlocal hook without a module handle.
HOOK_NEEDS_HMOD = 1428,
/// This hook procedure can only be set globally.
GLOBAL_ONLY_HOOK = 1429,
/// The journal hook procedure is already installed.
JOURNAL_HOOK_SET = 1430,
/// The hook procedure is not installed.
HOOK_NOT_INSTALLED = 1431,
/// Invalid message for single-selection list box.
INVALID_LB_MESSAGE = 1432,
/// LB_SETCOUNT sent to non-lazy list box.
SETCOUNT_ON_BAD_LB = 1433,
/// This list box does not support tab stops.
LB_WITHOUT_TABSTOPS = 1434,
/// Cannot destroy object created by another thread.
DESTROY_OBJECT_OF_OTHER_THREAD = 1435,
/// Child windows cannot have menus.
CHILD_WINDOW_MENU = 1436,
/// The window does not have a system menu.
NO_SYSTEM_MENU = 1437,
/// Invalid message box style.
INVALID_MSGBOX_STYLE = 1438,
/// Invalid system-wide (SPI_*) parameter.
INVALID_SPI_VALUE = 1439,
/// Screen already locked.
SCREEN_ALREADY_LOCKED = 1440,
/// All handles to windows in a multiple-window position structure must have the same parent.
HWNDS_HAVE_DIFF_PARENT = 1441,
/// The window is not a child window.
NOT_CHILD_WINDOW = 1442,
/// Invalid GW_* command.
INVALID_GW_COMMAND = 1443,
/// Invalid thread identifier.
INVALID_THREAD_ID = 1444,
/// Cannot process a message from a window that is not a multiple document interface (MDI) window.
NON_MDICHILD_WINDOW = 1445,
/// Popup menu already active.
POPUP_ALREADY_ACTIVE = 1446,
/// The window does not have scroll bars.
NO_SCROLLBARS = 1447,
/// Scroll bar range cannot be greater than MAXLONG.
INVALID_SCROLLBAR_RANGE = 1448,
/// Cannot show or remove the window in the way specified.
INVALID_SHOWWIN_COMMAND = 1449,
/// Insufficient system resources exist to complete the requested service.
NO_SYSTEM_RESOURCES = 1450,
/// Insufficient system resources exist to complete the requested service.
NONPAGED_SYSTEM_RESOURCES = 1451,
/// Insufficient system resources exist to complete the requested service.
PAGED_SYSTEM_RESOURCES = 1452,
/// Insufficient quota to complete the requested service.
WORKING_SET_QUOTA = 1453,
/// Insufficient quota to complete the requested service.
PAGEFILE_QUOTA = 1454,
/// The paging file is too small for this operation to complete.
COMMITMENT_LIMIT = 1455,
/// A menu item was not found.
MENU_ITEM_NOT_FOUND = 1456,
/// Invalid keyboard layout handle.
INVALID_KEYBOARD_HANDLE = 1457,
/// Hook type not allowed.
HOOK_TYPE_NOT_ALLOWED = 1458,
/// This operation requires an interactive window station.
REQUIRES_INTERACTIVE_WINDOWSTATION = 1459,
/// This operation returned because the timeout period expired.
TIMEOUT = 1460,
/// Invalid monitor handle.
INVALID_MONITOR_HANDLE = 1461,
/// Incorrect size argument.
INCORRECT_SIZE = 1462,
/// The symbolic link cannot be followed because its type is disabled.
SYMLINK_CLASS_DISABLED = 1463,
/// This application does not support the current operation on symbolic links.
SYMLINK_NOT_SUPPORTED = 1464,
/// Windows was unable to parse the requested XML data.
XML_PARSE_ERROR = 1465,
/// An error was encountered while processing an XML digital signature.
XMLDSIG_ERROR = 1466,
/// This application must be restarted.
RESTART_APPLICATION = 1467,
/// The caller made the connection request in the wrong routing compartment.
WRONG_COMPARTMENT = 1468,
/// There was an AuthIP failure when attempting to connect to the remote host.
AUTHIP_FAILURE = 1469,
/// Insufficient NVRAM resources exist to complete the requested service. A reboot might be required.
NO_NVRAM_RESOURCES = 1470,
/// Unable to finish the requested operation because the specified process is not a GUI process.
NOT_GUI_PROCESS = 1471,
/// The event log file is corrupted.
EVENTLOG_FILE_CORRUPT = 1500,
/// No event log file could be opened, so the event logging service did not start.
EVENTLOG_CANT_START = 1501,
/// The event log file is full.
LOG_FILE_FULL = 1502,
/// The event log file has changed between read operations.
EVENTLOG_FILE_CHANGED = 1503,
/// The specified task name is invalid.
INVALID_TASK_NAME = 1550,
/// The specified task index is invalid.
INVALID_TASK_INDEX = 1551,
/// The specified thread is already joining a task.
THREAD_ALREADY_IN_TASK = 1552,
/// The Windows Installer Service could not be accessed.
/// This can occur if the Windows Installer is not correctly installed. Contact your support personnel for assistance.
INSTALL_SERVICE_FAILURE = 1601,
/// User cancelled installation.
INSTALL_USEREXIT = 1602,
/// Fatal error during installation.
INSTALL_FAILURE = 1603,
/// Installation suspended, incomplete.
INSTALL_SUSPEND = 1604,
/// This action is only valid for products that are currently installed.
UNKNOWN_PRODUCT = 1605,
/// Feature ID not registered.
UNKNOWN_FEATURE = 1606,
/// Component ID not registered.
UNKNOWN_COMPONENT = 1607,
/// Unknown property.
UNKNOWN_PROPERTY = 1608,
/// Handle is in an invalid state.
INVALID_HANDLE_STATE = 1609,
/// The configuration data for this product is corrupt. Contact your support personnel.
BAD_CONFIGURATION = 1610,
/// Component qualifier not present.
INDEX_ABSENT = 1611,
/// The installation source for this product is not available.
/// Verify that the source exists and that you can access it.
INSTALL_SOURCE_ABSENT = 1612,
/// This installation package cannot be installed by the Windows Installer service.
/// You must install a Windows service pack that contains a newer version of the Windows Installer service.
INSTALL_PACKAGE_VERSION = 1613,
/// Product is uninstalled.
PRODUCT_UNINSTALLED = 1614,
/// SQL query syntax invalid or unsupported.
BAD_QUERY_SYNTAX = 1615,
/// Record field does not exist.
INVALID_FIELD = 1616,
/// The device has been removed.
DEVICE_REMOVED = 1617,
/// Another installation is already in progress.
/// Complete that installation before proceeding with this install.
INSTALL_ALREADY_RUNNING = 1618,
/// This installation package could not be opened.
/// Verify that the package exists and that you can access it, or contact the application vendor to verify that this is a valid Windows Installer package.
INSTALL_PACKAGE_OPEN_FAILED = 1619,
/// This installation package could not be opened.
/// Contact the application vendor to verify that this is a valid Windows Installer package.
INSTALL_PACKAGE_INVALID = 1620,
/// There was an error starting the Windows Installer service user interface. Contact your support personnel.
INSTALL_UI_FAILURE = 1621,
/// Error opening installation log file.
/// Verify that the specified log file location exists and that you can write to it.
INSTALL_LOG_FAILURE = 1622,
/// The language of this installation package is not supported by your system.
INSTALL_LANGUAGE_UNSUPPORTED = 1623,
/// Error applying transforms. Verify that the specified transform paths are valid.
INSTALL_TRANSFORM_FAILURE = 1624,
/// This installation is forbidden by system policy. Contact your system administrator.
INSTALL_PACKAGE_REJECTED = 1625,
/// Function could not be executed.
FUNCTION_NOT_CALLED = 1626,
/// Function failed during execution.
FUNCTION_FAILED = 1627,
/// Invalid or unknown table specified.
INVALID_TABLE = 1628,
/// Data supplied is of wrong type.
DATATYPE_MISMATCH = 1629,
/// Data of this type is not supported.
UNSUPPORTED_TYPE = 1630,
/// The Windows Installer service failed to start. Contact your support personnel.
CREATE_FAILED = 1631,
/// The Temp folder is on a drive that is full or is inaccessible.
/// Free up space on the drive or verify that you have write permission on the Temp folder.
INSTALL_TEMP_UNWRITABLE = 1632,
/// This installation package is not supported by this processor type. Contact your product vendor.
INSTALL_PLATFORM_UNSUPPORTED = 1633,
/// Component not used on this computer.
INSTALL_NOTUSED = 1634,
/// This update package could not be opened.
/// Verify that the update package exists and that you can access it, or contact the application vendor to verify that this is a valid Windows Installer update package.
PATCH_PACKAGE_OPEN_FAILED = 1635,
/// This update package could not be opened.
/// Contact the application vendor to verify that this is a valid Windows Installer update package.
PATCH_PACKAGE_INVALID = 1636,
/// This update package cannot be processed by the Windows Installer service.
/// You must install a Windows service pack that contains a newer version of the Windows Installer service.
PATCH_PACKAGE_UNSUPPORTED = 1637,
/// Another version of this product is already installed. Installation of this version cannot continue.
/// To configure or remove the existing version of this product, use Add/Remove Programs on the Control Panel.
PRODUCT_VERSION = 1638,
/// Invalid command line argument. Consult the Windows Installer SDK for detailed command line help.
INVALID_COMMAND_LINE = 1639,
/// Only administrators have permission to add, remove, or configure server software during a Terminal services remote session.
/// If you want to install or configure software on the server, contact your network administrator.
INSTALL_REMOTE_DISALLOWED = 1640,
/// The requested operation completed successfully.
/// The system will be restarted so the changes can take effect.
SUCCESS_REBOOT_INITIATED = 1641,
/// The upgrade cannot be installed by the Windows Installer service because the program to be upgraded may be missing, or the upgrade may update a different version of the program.
/// Verify that the program to be upgraded exists on your computer and that you have the correct upgrade.
PATCH_TARGET_NOT_FOUND = 1642,
/// The update package is not permitted by software restriction policy.
PATCH_PACKAGE_REJECTED = 1643,
/// One or more customizations are not permitted by software restriction policy.
INSTALL_TRANSFORM_REJECTED = 1644,
/// The Windows Installer does not permit installation from a Remote Desktop Connection.
INSTALL_REMOTE_PROHIBITED = 1645,
/// Uninstallation of the update package is not supported.
PATCH_REMOVAL_UNSUPPORTED = 1646,
/// The update is not applied to this product.
UNKNOWN_PATCH = 1647,
/// No valid sequence could be found for the set of updates.
PATCH_NO_SEQUENCE = 1648,
/// Update removal was disallowed by policy.
PATCH_REMOVAL_DISALLOWED = 1649,
/// The XML update data is invalid.
INVALID_PATCH_XML = 1650,
/// Windows Installer does not permit updating of managed advertised products.
/// At least one feature of the product must be installed before applying the update.
PATCH_MANAGED_ADVERTISED_PRODUCT = 1651,
/// The Windows Installer service is not accessible in Safe Mode.
/// Please try again when your computer is not in Safe Mode or you can use System Restore to return your machine to a previous good state.
INSTALL_SERVICE_SAFEBOOT = 1652,
/// A fail fast exception occurred.
/// Exception handlers will not be invoked and the process will be terminated immediately.
FAIL_FAST_EXCEPTION = 1653,
/// The app that you are trying to run is not supported on this version of Windows.
INSTALL_REJECTED = 1654,
/// The string binding is invalid.
RPC_S_INVALID_STRING_BINDING = 1700,
/// The binding handle is not the correct type.
RPC_S_WRONG_KIND_OF_BINDING = 1701,
/// The binding handle is invalid.
RPC_S_INVALID_BINDING = 1702,
/// The RPC protocol sequence is not supported.
RPC_S_PROTSEQ_NOT_SUPPORTED = 1703,
/// The RPC protocol sequence is invalid.
RPC_S_INVALID_RPC_PROTSEQ = 1704,
/// The string universal unique identifier (UUID) is invalid.
RPC_S_INVALID_STRING_UUID = 1705,
/// The endpoint format is invalid.
RPC_S_INVALID_ENDPOINT_FORMAT = 1706,
/// The network address is invalid.
RPC_S_INVALID_NET_ADDR = 1707,
/// No endpoint was found.
RPC_S_NO_ENDPOINT_FOUND = 1708,
/// The timeout value is invalid.
RPC_S_INVALID_TIMEOUT = 1709,
/// The object universal unique identifier (UUID) was not found.
RPC_S_OBJECT_NOT_FOUND = 1710,
/// The object universal unique identifier (UUID) has already been registered.
RPC_S_ALREADY_REGISTERED = 1711,
/// The type universal unique identifier (UUID) has already been registered.
RPC_S_TYPE_ALREADY_REGISTERED = 1712,
/// The RPC server is already listening.
RPC_S_ALREADY_LISTENING = 1713,
/// No protocol sequences have been registered.
RPC_S_NO_PROTSEQS_REGISTERED = 1714,
/// The RPC server is not listening.
RPC_S_NOT_LISTENING = 1715,
/// The manager type is unknown.
RPC_S_UNKNOWN_MGR_TYPE = 1716,
/// The interface is unknown.
RPC_S_UNKNOWN_IF = 1717,
/// There are no bindings.
RPC_S_NO_BINDINGS = 1718,
/// There are no protocol sequences.
RPC_S_NO_PROTSEQS = 1719,
/// The endpoint cannot be created.
RPC_S_CANT_CREATE_ENDPOINT = 1720,
/// Not enough resources are available to complete this operation.
RPC_S_OUT_OF_RESOURCES = 1721,
/// The RPC server is unavailable.
RPC_S_SERVER_UNAVAILABLE = 1722,
/// The RPC server is too busy to complete this operation.
RPC_S_SERVER_TOO_BUSY = 1723,
/// The network options are invalid.
RPC_S_INVALID_NETWORK_OPTIONS = 1724,
/// There are no remote procedure calls active on this thread.
RPC_S_NO_CALL_ACTIVE = 1725,
/// The remote procedure call failed.
RPC_S_CALL_FAILED = 1726,
/// The remote procedure call failed and did not execute.
RPC_S_CALL_FAILED_DNE = 1727,
/// A remote procedure call (RPC) protocol error occurred.
RPC_S_PROTOCOL_ERROR = 1728,
/// Access to the HTTP proxy is denied.
RPC_S_PROXY_ACCESS_DENIED = 1729,
/// The transfer syntax is not supported by the RPC server.
RPC_S_UNSUPPORTED_TRANS_SYN = 1730,
/// The universal unique identifier (UUID) type is not supported.
RPC_S_UNSUPPORTED_TYPE = 1732,
/// The tag is invalid.
RPC_S_INVALID_TAG = 1733,
/// The array bounds are invalid.
RPC_S_INVALID_BOUND = 1734,
/// The binding does not contain an entry name.
RPC_S_NO_ENTRY_NAME = 1735,
/// The name syntax is invalid.
RPC_S_INVALID_NAME_SYNTAX = 1736,
/// The name syntax is not supported.
RPC_S_UNSUPPORTED_NAME_SYNTAX = 1737,
/// No network address is available to use to construct a universal unique identifier (UUID).
RPC_S_UUID_NO_ADDRESS = 1739,
/// The endpoint is a duplicate.
RPC_S_DUPLICATE_ENDPOINT = 1740,
/// The authentication type is unknown.
RPC_S_UNKNOWN_AUTHN_TYPE = 1741,
/// The maximum number of calls is too small.
RPC_S_MAX_CALLS_TOO_SMALL = 1742,
/// The string is too long.
RPC_S_STRING_TOO_LONG = 1743,
/// The RPC protocol sequence was not found.
RPC_S_PROTSEQ_NOT_FOUND = 1744,
/// The procedure number is out of range.
RPC_S_PROCNUM_OUT_OF_RANGE = 1745,
/// The binding does not contain any authentication information.
RPC_S_BINDING_HAS_NO_AUTH = 1746,
/// The authentication service is unknown.
RPC_S_UNKNOWN_AUTHN_SERVICE = 1747,
/// The authentication level is unknown.
RPC_S_UNKNOWN_AUTHN_LEVEL = 1748,
/// The security context is invalid.
RPC_S_INVALID_AUTH_IDENTITY = 1749,
/// The authorization service is unknown.
RPC_S_UNKNOWN_AUTHZ_SERVICE = 1750,
/// The entry is invalid.
EPT_S_INVALID_ENTRY = 1751,
/// The server endpoint cannot perform the operation.
EPT_S_CANT_PERFORM_OP = 1752,
/// There are no more endpoints available from the endpoint mapper.
EPT_S_NOT_REGISTERED = 1753,
/// No interfaces have been exported.
RPC_S_NOTHING_TO_EXPORT = 1754,
/// The entry name is incomplete.
RPC_S_INCOMPLETE_NAME = 1755,
/// The version option is invalid.
RPC_S_INVALID_VERS_OPTION = 1756,
/// There are no more members.
RPC_S_NO_MORE_MEMBERS = 1757,
/// There is nothing to unexport.
RPC_S_NOT_ALL_OBJS_UNEXPORTED = 1758,
/// The interface was not found.
RPC_S_INTERFACE_NOT_FOUND = 1759,
/// The entry already exists.
RPC_S_ENTRY_ALREADY_EXISTS = 1760,
/// The entry is not found.
RPC_S_ENTRY_NOT_FOUND = 1761,
/// The name service is unavailable.
RPC_S_NAME_SERVICE_UNAVAILABLE = 1762,
/// The network address family is invalid.
RPC_S_INVALID_NAF_ID = 1763,
/// The requested operation is not supported.
RPC_S_CANNOT_SUPPORT = 1764,
/// No security context is available to allow impersonation.
RPC_S_NO_CONTEXT_AVAILABLE = 1765,
/// An internal error occurred in a remote procedure call (RPC).
RPC_S_INTERNAL_ERROR = 1766,
/// The RPC server attempted an integer division by zero.
RPC_S_ZERO_DIVIDE = 1767,
/// An addressing error occurred in the RPC server.
RPC_S_ADDRESS_ERROR = 1768,
/// A floating-point operation at the RPC server caused a division by zero.
RPC_S_FP_DIV_ZERO = 1769,
/// A floating-point underflow occurred at the RPC server.
RPC_S_FP_UNDERFLOW = 1770,
/// A floating-point overflow occurred at the RPC server.
RPC_S_FP_OVERFLOW = 1771,
/// The list of RPC servers available for the binding of auto handles has been exhausted.
RPC_X_NO_MORE_ENTRIES = 1772,
/// Unable to open the character translation table file.
RPC_X_SS_CHAR_TRANS_OPEN_FAIL = 1773,
/// The file containing the character translation table has fewer than 512 bytes.
RPC_X_SS_CHAR_TRANS_SHORT_FILE = 1774,
/// A null context handle was passed from the client to the host during a remote procedure call.
RPC_X_SS_IN_NULL_CONTEXT = 1775,
/// The context handle changed during a remote procedure call.
RPC_X_SS_CONTEXT_DAMAGED = 1777,
/// The binding handles passed to a remote procedure call do not match.
RPC_X_SS_HANDLES_MISMATCH = 1778,
/// The stub is unable to get the remote procedure call handle.
RPC_X_SS_CANNOT_GET_CALL_HANDLE = 1779,
/// A null reference pointer was passed to the stub.
RPC_X_NULL_REF_POINTER = 1780,
/// The enumeration value is out of range.
RPC_X_ENUM_VALUE_OUT_OF_RANGE = 1781,
/// The byte count is too small.
RPC_X_BYTE_COUNT_TOO_SMALL = 1782,
/// The stub received bad data.
RPC_X_BAD_STUB_DATA = 1783,
/// The supplied user buffer is not valid for the requested operation.
INVALID_USER_BUFFER = 1784,
/// The disk media is not recognized. It may not be formatted.
UNRECOGNIZED_MEDIA = 1785,
/// The workstation does not have a trust secret.
NO_TRUST_LSA_SECRET = 1786,
/// The security database on the server does not have a computer account for this workstation trust relationship.
NO_TRUST_SAM_ACCOUNT = 1787,
/// The trust relationship between the primary domain and the trusted domain failed.
TRUSTED_DOMAIN_FAILURE = 1788,
/// The trust relationship between this workstation and the primary domain failed.
TRUSTED_RELATIONSHIP_FAILURE = 1789,
/// The network logon failed.
TRUST_FAILURE = 1790,
/// A remote procedure call is already in progress for this thread.
RPC_S_CALL_IN_PROGRESS = 1791,
/// An attempt was made to logon, but the network logon service was not started.
NETLOGON_NOT_STARTED = 1792,
/// The user's account has expired.
ACCOUNT_EXPIRED = 1793,
/// The redirector is in use and cannot be unloaded.
REDIRECTOR_HAS_OPEN_HANDLES = 1794,
/// The specified printer driver is already installed.
PRINTER_DRIVER_ALREADY_INSTALLED = 1795,
/// The specified port is unknown.
UNKNOWN_PORT = 1796,
/// The printer driver is unknown.
UNKNOWN_PRINTER_DRIVER = 1797,
/// The print processor is unknown.
UNKNOWN_PRINTPROCESSOR = 1798,
/// The specified separator file is invalid.
INVALID_SEPARATOR_FILE = 1799,
/// The specified priority is invalid.
INVALID_PRIORITY = 1800,
/// The printer name is invalid.
INVALID_PRINTER_NAME = 1801,
/// The printer already exists.
PRINTER_ALREADY_EXISTS = 1802,
/// The printer command is invalid.
INVALID_PRINTER_COMMAND = 1803,
/// The specified datatype is invalid.
INVALID_DATATYPE = 1804,
/// The environment specified is invalid.
INVALID_ENVIRONMENT = 1805,
/// There are no more bindings.
RPC_S_NO_MORE_BINDINGS = 1806,
/// The account used is an interdomain trust account.
/// Use your global user account or local user account to access this server.
NOLOGON_INTERDOMAIN_TRUST_ACCOUNT = 1807,
/// The account used is a computer account.
/// Use your global user account or local user account to access this server.
NOLOGON_WORKSTATION_TRUST_ACCOUNT = 1808,
/// The account used is a server trust account.
/// Use your global user account or local user account to access this server.
NOLOGON_SERVER_TRUST_ACCOUNT = 1809,
/// The name or security ID (SID) of the domain specified is inconsistent with the trust information for that domain.
DOMAIN_TRUST_INCONSISTENT = 1810,
/// The server is in use and cannot be unloaded.
SERVER_HAS_OPEN_HANDLES = 1811,
/// The specified image file did not contain a resource section.
RESOURCE_DATA_NOT_FOUND = 1812,
/// The specified resource type cannot be found in the image file.
RESOURCE_TYPE_NOT_FOUND = 1813,
/// The specified resource name cannot be found in the image file.
RESOURCE_NAME_NOT_FOUND = 1814,
/// The specified resource language ID cannot be found in the image file.
RESOURCE_LANG_NOT_FOUND = 1815,
/// Not enough quota is available to process this command.
NOT_ENOUGH_QUOTA = 1816,
/// No interfaces have been registered.
RPC_S_NO_INTERFACES = 1817,
/// The remote procedure call was cancelled.
RPC_S_CALL_CANCELLED = 1818,
/// The binding handle does not contain all required information.
RPC_S_BINDING_INCOMPLETE = 1819,
/// A communications failure occurred during a remote procedure call.
RPC_S_COMM_FAILURE = 1820,
/// The requested authentication level is not supported.
RPC_S_UNSUPPORTED_AUTHN_LEVEL = 1821,
/// No principal name registered.
RPC_S_NO_PRINC_NAME = 1822,
/// The error specified is not a valid Windows RPC error code.
RPC_S_NOT_RPC_ERROR = 1823,
/// A UUID that is valid only on this computer has been allocated.
RPC_S_UUID_LOCAL_ONLY = 1824,
/// A security package specific error occurred.
RPC_S_SEC_PKG_ERROR = 1825,
/// Thread is not canceled.
RPC_S_NOT_CANCELLED = 1826,
/// Invalid operation on the encoding/decoding handle.
RPC_X_INVALID_ES_ACTION = 1827,
/// Incompatible version of the serializing package.
RPC_X_WRONG_ES_VERSION = 1828,
/// Incompatible version of the RPC stub.
RPC_X_WRONG_STUB_VERSION = 1829,
/// The RPC pipe object is invalid or corrupted.
RPC_X_INVALID_PIPE_OBJECT = 1830,
/// An invalid operation was attempted on an RPC pipe object.
RPC_X_WRONG_PIPE_ORDER = 1831,
/// Unsupported RPC pipe version.
RPC_X_WRONG_PIPE_VERSION = 1832,
/// HTTP proxy server rejected the connection because the cookie authentication failed.
RPC_S_COOKIE_AUTH_FAILED = 1833,
/// The group member was not found.
RPC_S_GROUP_MEMBER_NOT_FOUND = 1898,
/// The endpoint mapper database entry could not be created.
EPT_S_CANT_CREATE = 1899,
/// The object universal unique identifier (UUID) is the nil UUID.
RPC_S_INVALID_OBJECT = 1900,
/// The specified time is invalid.
INVALID_TIME = 1901,
/// The specified form name is invalid.
INVALID_FORM_NAME = 1902,
/// The specified form size is invalid.
INVALID_FORM_SIZE = 1903,
/// The specified printer handle is already being waited on.
ALREADY_WAITING = 1904,
/// The specified printer has been deleted.
PRINTER_DELETED = 1905,
/// The state of the printer is invalid.
INVALID_PRINTER_STATE = 1906,
/// The user's password must be changed before signing in.
PASSWORD_MUST_CHANGE = <PASSWORD>,
/// Could not find the domain controller for this domain.
DOMAIN_CONTROLLER_NOT_FOUND = 1908,
/// The referenced account is currently locked out and may not be logged on to.
ACCOUNT_LOCKED_OUT = 1909,
/// The object exporter specified was not found.
OR_INVALID_OXID = 1910,
/// The object specified was not found.
OR_INVALID_OID = 1911,
/// The object resolver set specified was not found.
OR_INVALID_SET = 1912,
/// Some data remains to be sent in the request buffer.
RPC_S_SEND_INCOMPLETE = 1913,
/// Invalid asynchronous remote procedure call handle.
RPC_S_INVALID_ASYNC_HANDLE = 1914,
/// Invalid asynchronous RPC call handle for this operation.
RPC_S_INVALID_ASYNC_CALL = 1915,
/// The RPC pipe object has already been closed.
RPC_X_PIPE_CLOSED = 1916,
/// The RPC call completed before all pipes were processed.
RPC_X_PIPE_DISCIPLINE_ERROR = 1917,
/// No more data is available from the RPC pipe.
RPC_X_PIPE_EMPTY = 1918,
/// No site name is available for this machine.
NO_SITENAME = 1919,
/// The file cannot be accessed by the system.
CANT_ACCESS_FILE = 1920,
/// The name of the file cannot be resolved by the system.
CANT_RESOLVE_FILENAME = 1921,
/// The entry is not of the expected type.
RPC_S_ENTRY_TYPE_MISMATCH = 1922,
/// Not all object UUIDs could be exported to the specified entry.
RPC_S_NOT_ALL_OBJS_EXPORTED = 1923,
/// Interface could not be exported to the specified entry.
RPC_S_INTERFACE_NOT_EXPORTED = 1924,
/// The specified profile entry could not be added.
RPC_S_PROFILE_NOT_ADDED = 1925,
/// The specified profile element could not be added.
RPC_S_PRF_ELT_NOT_ADDED = 1926,
/// The specified profile element could not be removed.
RPC_S_PRF_ELT_NOT_REMOVED = 1927,
/// The group element could not be added.
RPC_S_GRP_ELT_NOT_ADDED = 1928,
/// The group element could not be removed.
RPC_S_GRP_ELT_NOT_REMOVED = 1929,
/// The printer driver is not compatible with a policy enabled on your computer that blocks NT 4.0 drivers.
KM_DRIVER_BLOCKED = 1930,
/// The context has expired and can no longer be used.
CONTEXT_EXPIRED = 1931,
/// The current user's delegated trust creation quota has been exceeded.
PER_USER_TRUST_QUOTA_EXCEEDED = 1932,
/// The total delegated trust creation quota has been exceeded.
ALL_USER_TRUST_QUOTA_EXCEEDED = 1933,
/// The current user's delegated trust deletion quota has been exceeded.
USER_DELETE_TRUST_QUOTA_EXCEEDED = 1934,
/// The computer you are signing into is protected by an authentication firewall.
/// The specified account is not allowed to authenticate to the computer.
AUTHENTICATION_FIREWALL_FAILED = 1935,
/// Remote connections to the Print Spooler are blocked by a policy set on your machine.
REMOTE_PRINT_CONNECTIONS_BLOCKED = 1936,
/// Authentication failed because NTLM authentication has been disabled.
NTLM_BLOCKED = 1937,
/// Logon Failure: EAS policy requires that the user change their password before this operation can be performed.
PASSWORD_CHANGE_REQUIRED = <PASSWORD>,
/// The pixel format is invalid.
INVALID_PIXEL_FORMAT = 2000,
/// The specified driver is invalid.
BAD_DRIVER = 2001,
/// The window style or class attribute is invalid for this operation.
INVALID_WINDOW_STYLE = 2002,
/// The requested metafile operation is not supported.
METAFILE_NOT_SUPPORTED = 2003,
/// The requested transformation operation is not supported.
TRANSFORM_NOT_SUPPORTED = 2004,
/// The requested clipping operation is not supported.
CLIPPING_NOT_SUPPORTED = 2005,
/// The specified color management module is invalid.
INVALID_CMM = 2010,
/// The specified color profile is invalid.
INVALID_PROFILE = 2011,
/// The specified tag was not found.
TAG_NOT_FOUND = 2012,
/// A required tag is not present.
TAG_NOT_PRESENT = 2013,
/// The specified tag is already present.
DUPLICATE_TAG = 2014,
/// The specified color profile is not associated with the specified device.
PROFILE_NOT_ASSOCIATED_WITH_DEVICE = 2015,
/// The specified color profile was not found.
PROFILE_NOT_FOUND = 2016,
/// The specified color space is invalid.
INVALID_COLORSPACE = 2017,
/// Image Color Management is not enabled.
ICM_NOT_ENABLED = 2018,
/// There was an error while deleting the color transform.
DELETING_ICM_XFORM = 2019,
/// The specified color transform is invalid.
INVALID_TRANSFORM = 2020,
/// The specified transform does not match the bitmap's color space.
COLORSPACE_MISMATCH = 2021,
/// The specified named color index is not present in the profile.
INVALID_COLORINDEX = 2022,
/// The specified profile is intended for a device of a different type than the specified device.
PROFILE_DOES_NOT_MATCH_DEVICE = 2023,
/// The network connection was made successfully, but the user had to be prompted for a password other than the one originally specified.
CONNECTED_OTHER_PASSWORD = <PASSWORD>,
/// The network connection was made successfully using default credentials.
CONNECTED_OTHER_PASSWORD_DEFAULT = <PASSWORD>,
/// The specified username is invalid.
BAD_USERNAME = 2202,
/// This network connection does not exist.
NOT_CONNECTED = 2250,
/// This network connection has files open or requests pending.
OPEN_FILES = 2401,
/// Active connections still exist.
ACTIVE_CONNECTIONS = 2402,
/// The device is in use by an active process and cannot be disconnected.
DEVICE_IN_USE = 2404,
/// The specified print monitor is unknown.
UNKNOWN_PRINT_MONITOR = 3000,
/// The specified printer driver is currently in use.
PRINTER_DRIVER_IN_USE = 3001,
/// The spool file was not found.
SPOOL_FILE_NOT_FOUND = 3002,
/// A StartDocPrinter call was not issued.
SPL_NO_STARTDOC = 3003,
/// An AddJob call was not issued.
SPL_NO_ADDJOB = 3004,
/// The specified print processor has already been installed.
PRINT_PROCESSOR_ALREADY_INSTALLED = 3005,
/// The specified print monitor has already been installed.
PRINT_MONITOR_ALREADY_INSTALLED = 3006,
/// The specified print monitor does not have the required functions.
INVALID_PRINT_MONITOR = 3007,
/// The specified print monitor is currently in use.
PRINT_MONITOR_IN_USE = 3008,
/// The requested operation is not allowed when there are jobs queued to the printer.
PRINTER_HAS_JOBS_QUEUED = 3009,
/// The requested operation is successful.
/// Changes will not be effective until the system is rebooted.
SUCCESS_REBOOT_REQUIRED = 3010,
/// The requested operation is successful.
/// Changes will not be effective until the service is restarted.
SUCCESS_RESTART_REQUIRED = 3011,
/// No printers were found.
PRINTER_NOT_FOUND = 3012,
/// The printer driver is known to be unreliable.
PRINTER_DRIVER_WARNED = 3013,
/// The printer driver is known to harm the system.
PRINTER_DRIVER_BLOCKED = 3014,
/// The specified printer driver package is currently in use.
PRINTER_DRIVER_PACKAGE_IN_USE = 3015,
/// Unable to find a core driver package that is required by the printer driver package.
CORE_DRIVER_PACKAGE_NOT_FOUND = 3016,
/// The requested operation failed.
/// A system reboot is required to roll back changes made.
FAIL_REBOOT_REQUIRED = 3017,
/// The requested operation failed.
/// A system reboot has been initiated to roll back changes made.
FAIL_REBOOT_INITIATED = 3018,
/// The specified printer driver was not found on the system and needs to be downloaded.
PRINTER_DRIVER_DOWNLOAD_NEEDED = 3019,
/// The requested print job has failed to print.
/// A print system update requires the job to be resubmitted.
PRINT_JOB_RESTART_REQUIRED = 3020,
/// The printer driver does not contain a valid manifest, or contains too many manifests.
INVALID_PRINTER_DRIVER_MANIFEST = 3021,
/// The specified printer cannot be shared.
PRINTER_NOT_SHAREABLE = 3022,
/// The operation was paused.
REQUEST_PAUSED = 3050,
/// Reissue the given operation as a cached IO operation.
IO_REISSUE_AS_CACHED = 3950,
_,
};
|
lib/std/os/windows/win32error.zig
|
const std = @import("std");
const builtin = @import("builtin");
const opcode = @import("opcode.zig");
pub const Registers = struct {
af: u16,
bc: u16,
de: u16,
hl: u16,
sp: u16,
pc: u16,
pub fn a(self: *const Registers) u8 {
return @truncate(u8, self.af >> 8);
}
pub fn setA(self: *Registers, value: u8) void {
self.af = (u16(value) << 8) | self.f();
}
pub fn b(self: *const Registers) u8 {
return @truncate(u8, self.bc >> 8);
}
pub fn setB(self: *Registers, value: u8) void {
self.bc = (u16(value) << 8) | self.c();
}
pub fn c(self: *const Registers) u8 {
return @truncate(u8, self.bc);
}
pub fn setC(self: *Registers, value: u8) void {
self.bc = (u16(self.b()) << 8) | value;
}
pub fn d(self: *const Registers) u8 {
return @truncate(u8, self.de >> 8);
}
pub fn setD(self: *Registers, value: u8) void {
self.de = (u16(value) << 8) | self.e();
}
pub fn e(self: *const Registers) u8 {
return @truncate(u8, self.de);
}
pub fn setE(self: *Registers, value: u8) void {
self.de = (u16(self.d()) << 8) | value;
}
pub fn f(self: *const Registers) u8 {
return @truncate(u8, self.af);
}
pub fn setF(self: *Registers, value: u8) void {
self.af = (u16(self.a()) << 8) | value;
}
pub fn h(self: *const Registers) u8 {
return @truncate(u8, self.hl >> 8);
}
pub fn setH(self: *Registers, value: u8) void {
self.hl = (u16(value) << 8) | self.l();
}
pub fn l(self: *const Registers) u8 {
return @truncate(u8, self.hl);
}
pub fn setL(self: *Registers, value: u8) void {
self.hl = (u16(self.h()) << 8) | value;
}
const zero_flag_mask: u8 = 0x80;
const subtract_flag_mask: u8 = 0x40;
const half_carry_flag_mask: u8 = 0x20;
const carry_flag_mask: u8 = 0x10;
pub fn zeroFlag(self: *const Registers) bool {
return (self.f() & zero_flag_mask) != 0;
}
pub fn setZeroFlag(self: *Registers, value: bool) void {
if (value == true) {
self.setF(self.f() | zero_flag_mask);
} else {
self.setF(self.f() & (~zero_flag_mask));
}
}
pub fn subtractFlag(self: *const Registers) bool {
return (self.f() & subtract_flag_mask) != 0;
}
pub fn setSubtractFlag(self: *Registers, value: bool) void {
if (value == true) {
self.setF(self.f() | subtract_flag_mask);
} else {
self.setF(self.f() & (~subtract_flag_mask));
}
}
pub fn halfCarryFlag(self: *const Registers) bool {
return (self.f() & half_carry_flag_mask) != 0;
}
pub fn setHalfCarryFlag(self: *Registers, value: bool) void {
if (value == true) {
self.setF(self.f() | half_carry_flag_mask);
} else {
self.setF(self.f() & (~half_carry_flag_mask));
}
}
pub fn carryFlag(self: *const Registers) bool {
return (self.f() & carry_flag_mask) != 0;
}
pub fn setCarryFlag(self: *Registers, value: bool) void {
if (value == true) {
self.setF(self.f() | carry_flag_mask);
} else {
self.setF(self.f() & (~carry_flag_mask));
}
}
};
test "Registers" {
var registers: Registers = undefined;
registers.af = 0xFF11;
std.debug.assert(registers.a() == 0xFF);
std.debug.assert(registers.f() == 0x11);
registers.setA(0x11);
registers.setF(0x55);
std.debug.assert(registers.a() == 0x11);
std.debug.assert(registers.f() == 0x55);
registers.bc = 0xFF11;
std.debug.assert(registers.b() == 0xFF);
std.debug.assert(registers.c() == 0x11);
registers.setB(0x11);
registers.setC(0x55);
std.debug.assert(registers.b() == 0x11);
std.debug.assert(registers.c() == 0x55);
registers.de = 0xFF11;
std.debug.assert(registers.d() == 0xFF);
std.debug.assert(registers.e() == 0x11);
registers.setD(0x11);
registers.setE(0x55);
std.debug.assert(registers.d() == 0x11);
std.debug.assert(registers.e() == 0x55);
registers.hl = 0xFF11;
std.debug.assert(registers.h() == 0xFF);
std.debug.assert(registers.l() == 0x11);
registers.setH(0x11);
registers.setL(0x55);
std.debug.assert(registers.h() == 0x11);
std.debug.assert(registers.l() == 0x55);
}
pub const Memory = struct {
const memory_len = 0xFFFF - 0x2000;
allocator: *std.mem.Allocator,
memory: []u8,
pub fn init(allocator: *std.mem.Allocator) !Memory {
return Memory{
.allocator = allocator,
.memory = try allocator.alloc(u8, memory_len),
};
}
pub fn deinit(self: *Memory) void {
self.allocator.free(self.memory);
}
fn internalIndex(index: u16) u16 {
if (index < 0xE000) {
return index;
}
return index - 0x2000;
}
pub fn get(self: *const Memory, index: u16) u8 {
return self.memory[internalIndex(index)];
}
pub fn set(self: *Memory, index: u16, value: u8) void {
self.memory[internalIndex(index)] = value;
}
pub fn sliceConst(self: *const Memory, index: u16, len: usize) []const u8 {
const offset = internalIndex(index);
return self.memory[offset .. offset + len];
}
pub fn slice(self: *Memory, index: u16, len: usize) []u8 {
const offset = internalIndex(index);
return self.memory[offset .. offset + len];
}
};
pub const CPU = struct {
pub const Stream = std.io.InStream(error{});
pub const EmptyErrorSet = error{};
pub const Mode = enum {
Default,
Halt,
Stop,
DisableInterrupts,
EnableInterrupts,
};
registers: Registers,
memory: Memory,
stream: Stream,
pub fn init(allocator: *std.mem.Allocator) !CPU {
return CPU{
.registers = undefined,
.memory = try Memory.init(allocator),
.stream = Stream{ .readFn = CPU.readFn },
};
}
pub fn deinit(self: *CPU) void {
self.memory.deinit();
}
fn readFn(in_stream: *Stream, buffer: []u8) EmptyErrorSet!usize {
const self = @fieldParentPtr(CPU, "stream", in_stream);
var len: usize = undefined;
if (usize(self.registers.pc) + buffer.len > 0xFFFF) {
len = 0xFFFF - self.registers.pc;
} else {
len = buffer.len;
}
std.mem.copy(u8, buffer, self.memory.sliceConst(self.registers.pc, len));
self.registers.pc +%= @truncate(u16, len);
return len;
}
fn push(self: *CPU, value: var) void {
const len = @sizeOf(@typeOf(value));
self.registers.sp -%= len;
std.mem.writeIntSliceLittle(@typeOf(value), self.memory.slice(self.registers.sp, len), value);
}
fn pop(self: *CPU, comptime T: type) T {
const value = std.mem.readIntSliceLittle(T, self.memory.sliceConst(self.registers.sp, @sizeOf(T)));
self.registers.sp +%= @sizeOf(T);
return value;
}
fn add(self: *CPU, comptime T: type, a: T, b: T) T {
const B = @IntType(false, @sizeOf(T) * 16);
const high_test_bit_num_trailing_zeros = @sizeOf(T) * 8;
const high_test_bit: B = 1 << high_test_bit_num_trailing_zeros;
const high_operand_mask = high_test_bit - 1;
const low_test_bit = high_test_bit >> 4;
const low_operand_mask = (low_test_bit) - 1;
const result = a + b;
self.registers.setHalfCarryFlag((((a & low_operand_mask) + (b & low_operand_mask)) & low_test_bit) == low_test_bit);
self.registers.setCarryFlag((((a & high_operand_mask) + (b & high_operand_mask)) & high_test_bit) == high_test_bit);
self.registers.setZeroFlag(result == 0);
self.registers.setSubtractFlag(false);
return result;
}
fn sub(self: *CPU, a: u8, b: u8) u8 {
const result = a - b;
self.registers.setHalfCarryFlag((((a & 0xF) - (b & 0xF)) & 0x10) == 0x10);
self.registers.setCarryFlag(((((a >> 4) & 0xF) - ((b >> 4) & 0xF)) & 0x10) == 0x10);
self.registers.setZeroFlag(result == 0);
self.registers.setSubtractFlag(true);
return @bitCast(u8, result);
}
fn bitwiseAnd(self: *CPU, a: u8, b: u8) u8 {
const result = a & b;
self.registers.setHalfCarryFlag(true);
self.registers.setCarryFlag(false);
self.registers.setZeroFlag(result == 0);
self.registers.setSubtractFlag(false);
return result;
}
fn bitwiseOr(self: *CPU, a: u8, b: u8) u8 {
const result = a | b;
self.registers.setHalfCarryFlag(false);
self.registers.setCarryFlag(false);
self.registers.setZeroFlag(result == 0);
self.registers.setSubtractFlag(false);
return result;
}
fn bitwiseXor(self: *CPU, a: u8, b: u8) u8 {
const result = a ^ b;
self.registers.setHalfCarryFlag(false);
self.registers.setCarryFlag(false);
self.registers.setZeroFlag(result == 0);
self.registers.setSubtractFlag(false);
return result;
}
fn swap(self: *CPU, x: u8) u8 {
const high_nibble = x & 0xF0;
const low_nibble = x & 0x0F;
const result = low_nibble << 4 | (high_nibble >> 4);
self.registers.setHalfCarryFlag(false);
self.registers.setCarryFlag(false);
self.registers.setZeroFlag(result == 0);
self.registers.setSubtractFlag(false);
return result;
}
fn rlc(self: *CPU, x: u8) u8 {
const result = (x << 1) | (x >> 7);
self.registers.setCarryFlag((x & 0x80) != 0);
self.registers.setHalfCarryFlag(false);
self.registers.setSubtractFlag(false);
self.registers.setZeroFlag(result == 0);
return result;
}
fn rl(self: *CPU, x: u8) u8 {
const carry_flag = @boolToInt(self.registers.carryFlag());
const result = x << 1 | carry_flag;
self.registers.setCarryFlag((x & 0x80) != 0);
self.registers.setHalfCarryFlag(false);
self.registers.setSubtractFlag(false);
self.registers.setZeroFlag(result == 0);
return result;
}
fn rrc(self: *CPU, x: u8) u8 {
const result = (x << 7) | (x >> 1);
self.registers.setCarryFlag((x & 0x01) != 0);
self.registers.setHalfCarryFlag(false);
self.registers.setSubtractFlag(false);
self.registers.setZeroFlag(result == 0);
return result;
}
fn rr(self: *CPU, x: u8) u8 {
const result = (u8(@boolToInt(self.registers.carryFlag())) << 7) | (x >> 1);
self.registers.setCarryFlag((x & 0x01) != 0);
self.registers.setHalfCarryFlag(false);
self.registers.setSubtractFlag(false);
self.registers.setZeroFlag(result == 0);
return result;
}
fn sla(self: *CPU, x: u8) u8 {
const result = x << 1;
self.registers.setCarryFlag((x & 0x80) != 0);
self.registers.setHalfCarryFlag(false);
self.registers.setSubtractFlag(false);
self.registers.setZeroFlag(result == 0);
std.debug.assert((result & 0x01) == 0);
return result;
}
fn sra(self: *CPU, x: u8) u8 {
const result = (x & 0x80) | x >> 1;
self.registers.setCarryFlag((x & 0x01) != 0);
self.registers.setHalfCarryFlag(false);
self.registers.setSubtractFlag(false);
self.registers.setZeroFlag(result == 0);
std.debug.assert((result & 0x80) == (x & 0x80));
return result;
}
fn srl(self: *CPU, x: u8) u8 {
const result = x >> 1;
self.registers.setCarryFlag((x & 0x01) != 0);
self.registers.setHalfCarryFlag(false);
self.registers.setSubtractFlag(false);
self.registers.setZeroFlag(result == 0);
std.debug.assert((result & 0x80) == 0);
return result;
}
fn testBit(self: *CPU, x: u8, pos: u8) void {
const n = @truncate(u3, pos);
const result = (x & (u8(1) << n)) != 0;
self.registers.setZeroFlag(!result);
self.registers.setSubtractFlag(false);
self.registers.setHalfCarryFlag(true);
}
fn jumpRelative(self: *CPU, n: i8) void {
const UnsignedAddress = @typeOf(self.registers.pc);
const SignedAddress = @IntType(true, UnsignedAddress.bit_count << 1);
const result = @intCast(SignedAddress, self.registers.pc) + n;
self.registers.pc = @truncate(u16, @intCast(UnsignedAddress, result));
}
fn call(self: *CPU, call_address: u16) void {
const return_address: u16 = self.registers.pc + 1;
self.push(return_address);
self.registers.pc = call_address;
}
pub fn execute(self: *CPU) !Mode {
switch (@intToEnum(opcode.Opcode, try self.stream.readByte())) {
opcode.Opcode.NOP => {
// NOP
},
opcode.Opcode.LD_BC_nn => {
// LD BC,nn
self.registers.bc = try self.stream.readIntLittle(u16);
},
opcode.Opcode.LD_BC_A => {
// LD (BC),A
self.memory.set(self.registers.bc, self.registers.a());
},
opcode.Opcode.INC_BC => {
// INC BC
self.registers.bc = self.add(u16, self.registers.bc, 1);
},
opcode.Opcode.INC_B => {
// INC B
self.registers.setB(self.add(u8, self.registers.b(), 1));
},
opcode.Opcode.DEC_B => {
// DEC B
self.registers.setB(self.sub(self.registers.b(), 1));
},
opcode.Opcode.LD_B_n => {
// LD B,n
self.registers.setB(try self.stream.readByte());
},
opcode.Opcode.RLCA => {
// RLCA
self.registers.setA(self.rlc(self.registers.a()));
},
opcode.Opcode.LD_nn_SP => {
// LD (nn),SP
const value = try self.stream.readIntLittle(u16);
self.memory.set(value, @truncate(u8, (self.registers.sp & 0xFF00) >> 8));
self.memory.set(value + 1, @truncate(u8, self.registers.sp));
},
opcode.Opcode.ADD_HL_BC => {
// ADD HL,BC
self.registers.hl = self.add(u16, self.registers.hl, self.registers.bc);
},
opcode.Opcode.LD_A_BC => {
// LD A,(BC)
self.registers.setA(self.memory.get(self.registers.bc));
},
opcode.Opcode.DEC_BC => {
// DEC BC
self.registers.bc -%= 1;
},
opcode.Opcode.INC_C => {
// INC C
self.registers.setC(self.add(u8, self.registers.c(), 1));
},
opcode.Opcode.DEC_C => {
// DEC D
self.registers.setD(self.sub(self.registers.d(), 1));
},
opcode.Opcode.LD_C_n => {
// LD C,n
self.registers.setC(try self.stream.readByte());
},
opcode.Opcode.RRCA => {
// RRCA
self.registers.setA(self.rrc(self.registers.a()));
},
opcode.Opcode.STOP_FIRST_BYTE => {
// STOP
switch (try self.stream.readByte()) {
0x00 => {
return Mode.Stop;
},
else => {
unreachable;
},
}
},
opcode.Opcode.LD_DE_nn => {
// LD DE,nn
self.registers.de = try self.stream.readIntLittle(u16);
},
opcode.Opcode.LD_DE_A => {
// LD (DE),A
self.memory.set(self.registers.de, self.registers.a());
},
opcode.Opcode.INC_DE => {
// INC DE
self.registers.de = self.add(u16, self.registers.de, 1);
},
opcode.Opcode.INC_D => {
// INC D
self.registers.setD(self.add(u8, self.registers.d(), 1));
},
opcode.Opcode.DEC_D => {
// DEC D
self.registers.setD(self.sub(self.registers.d(), 1));
},
opcode.Opcode.LD_D_n => {
// LD D,n
self.registers.setD(try self.stream.readByte());
},
opcode.Opcode.RLA => {
// RLA
self.registers.setA(self.rl(self.registers.a()));
},
opcode.Opcode.JR_n => {
// JR
const n = try self.stream.readByteSigned();
self.jumpRelative(n);
},
opcode.Opcode.ADD_HL_DE => {
// ADD HL,DE
self.registers.hl = self.add(u16, self.registers.hl, self.registers.de);
},
opcode.Opcode.LD_A_DE => {
// LD A,(DE)
self.registers.setA(self.memory.get(self.registers.de));
},
opcode.Opcode.DEC_DE => {
// DEC DE
self.registers.de -%= 1;
},
opcode.Opcode.INC_E => {
// INC E
self.registers.setE(self.add(u8, self.registers.e(), 1));
},
opcode.Opcode.DEC_E => {
// DEC E
self.registers.setE(self.sub(self.registers.e(), 1));
},
opcode.Opcode.LD_E_n => {
// LD E,n
self.registers.setE(try self.stream.readByte());
},
opcode.Opcode.RRA => {
// RRA
self.registers.setA(self.rr(self.registers.a()));
},
opcode.Opcode.JR_NZ_n => {
// JR NZ,n
const n = try self.stream.readByteSigned();
if (!self.registers.zeroFlag()) {
self.jumpRelative(n);
}
},
opcode.Opcode.LD_HL_nn => {
// LD HL,nn
self.registers.hl = try self.stream.readIntLittle(u16);
},
opcode.Opcode.LDI_HL_A => {
// LDI (HL),A
self.memory.set(self.registers.hl, self.registers.a());
self.registers.hl +%= 1;
},
opcode.Opcode.INC_HL => {
// INC HL
self.registers.hl = self.add(u16, self.registers.hl, 1);
},
opcode.Opcode.INC_H => {
// INC H
self.registers.setH(self.add(u8, self.registers.h(), 1));
},
opcode.Opcode.DEC_H => {
// DEC H
self.registers.setH(self.sub(self.registers.h(), 1));
},
opcode.Opcode.LD_H_n => {
// LD H,n
self.registers.setH(try self.stream.readByte());
},
opcode.Opcode.DAA => {
// DAA
var carry = false;
if (!self.registers.subtractFlag()) {
if (self.registers.carryFlag() or self.registers.a() > 0x99) {
self.registers.setA(self.registers.a() +% 0x60);
carry = true;
}
if (self.registers.halfCarryFlag() or (self.registers.a() & 0x0F) > 0x09) {
self.registers.setA(self.registers.a() +% 0x06);
}
} else if (self.registers.carryFlag()) {
carry = true;
const adjustment = if (self.registers.halfCarryFlag()) u8(0x9A) else u8(0xA0);
self.registers.setA(self.registers.a() +% adjustment);
} else if (self.registers.halfCarryFlag()) {
self.registers.setA(self.registers.a() +% 0xFA);
}
self.registers.setZeroFlag(self.registers.a() == 0);
self.registers.setCarryFlag(carry);
self.registers.setHalfCarryFlag(false);
},
opcode.Opcode.JR_Z_n => {
// JR Z,n
const n = try self.stream.readByteSigned();
if (self.registers.zeroFlag()) {
self.jumpRelative(n);
}
},
opcode.Opcode.ADD_HL_HL => {
// ADD HL,HL
self.registers.hl = self.add(u16, self.registers.hl, self.registers.hl);
},
opcode.Opcode.LDI_A_HL => {
// LDI A,(HL)
self.registers.setA(self.memory.get(self.registers.hl));
self.registers.hl +%= 1;
},
opcode.Opcode.DEC_HL => {
// DEC HL
self.registers.hl -%= 1;
},
opcode.Opcode.INC_L => {
// INC L
self.registers.setL(self.add(u8, self.registers.l(), 1));
},
opcode.Opcode.DEC_L => {
// DEC L
self.registers.setL(self.sub(self.registers.l(), 1));
},
opcode.Opcode.LD_L_n => {
// LD L,n
self.registers.setL(try self.stream.readByte());
},
opcode.Opcode.CPL => {
// CPL
self.registers.setA(~self.registers.a());
self.registers.setSubtractFlag(true);
self.registers.setHalfCarryFlag(true);
},
opcode.Opcode.JR_NC_n => {
// JR NC,n
const n = try self.stream.readByteSigned();
if (!self.registers.carryFlag()) {
self.jumpRelative(n);
}
},
opcode.Opcode.LD_SP_nn => {
// LD SP,nn
self.registers.sp = try self.stream.readIntLittle(u16);
},
opcode.Opcode.LDD_HL_A => {
// LDD (HL),A
self.memory.set(self.registers.hl, self.registers.a());
self.registers.hl -%= 1;
},
opcode.Opcode.INC_SP => {
// INC SP
self.registers.sp = self.add(u16, self.registers.sp, 1);
},
opcode.Opcode.INC_mem_HL => {
// INC (HL)
self.memory.set(self.registers.hl, self.add(u8, self.memory.get(self.registers.hl), 1));
},
opcode.Opcode.DEC_mem_HL => {
// DEC (HL)
self.memory.set(self.registers.hl, self.sub(self.memory.get(self.registers.hl), 1));
},
opcode.Opcode.LD_HL_n => {
// LD (HL),n
self.memory.set(self.registers.hl, try self.stream.readByte());
},
opcode.Opcode.SCF => {
// SCF
self.registers.setSubtractFlag(false);
self.registers.setHalfCarryFlag(false);
self.registers.setCarryFlag(true);
},
opcode.Opcode.JR_C_n => {
// JR C,n
const n = try self.stream.readByteSigned();
if (self.registers.carryFlag()) {
self.jumpRelative(n);
}
},
opcode.Opcode.ADD_HL_SP => {
// ADD HL,SP
self.registers.hl = self.add(u16, self.registers.hl, self.registers.sp);
},
opcode.Opcode.LDD_A_HL => {
// LDD A,(HL)
self.registers.setA(self.memory.get(self.registers.hl));
self.registers.hl -%= 1;
},
opcode.Opcode.DEC_SP => {
// DEC HL
self.registers.hl -%= 1;
},
opcode.Opcode.INC_A => {
// INC A
self.registers.setA(self.add(u8, self.registers.a(), 1));
},
opcode.Opcode.DEC_A => {
// DEC A
self.registers.setA(self.sub(self.registers.a(), 1));
},
opcode.Opcode.LD_A_n => {
// LD A,n
self.registers.setA(try self.stream.readByte());
},
opcode.Opcode.CCF => {
// CCF
self.registers.setSubtractFlag(false);
self.registers.setHalfCarryFlag(false);
self.registers.setCarryFlag(!self.registers.carryFlag());
},
opcode.Opcode.LD_B_B => {
// LD B,B
self.registers.setB(self.registers.b());
},
opcode.Opcode.LD_B_C => {
// LD B,C
self.registers.setB(self.registers.c());
},
opcode.Opcode.LD_B_D => {
// LD B,D
self.registers.setB(self.registers.d());
},
opcode.Opcode.LD_B_E => {
// LD B,E
self.registers.setB(self.registers.e());
},
opcode.Opcode.LD_B_H => {
// LD B,H
self.registers.setB(self.registers.h());
},
opcode.Opcode.LD_B_L => {
// LD B,L
self.registers.setB(self.registers.l());
},
opcode.Opcode.LD_B_HL => {
// LD B,(HL)
self.registers.setB(self.memory.get(self.registers.hl));
},
opcode.Opcode.LD_B_A => {
// LD B,A
self.registers.setB(self.registers.a());
},
opcode.Opcode.LD_C_B => {
// LD C,B
self.registers.setC(self.registers.b());
},
opcode.Opcode.LD_C_C => {
// LD C,C
self.registers.setC(self.registers.c());
},
opcode.Opcode.LD_C_D => {
// LD C,D
self.registers.setC(self.registers.d());
},
opcode.Opcode.LD_C_E => {
// LD C,E
self.registers.setC(self.registers.e());
},
opcode.Opcode.LD_C_H => {
// LD C,H
self.registers.setC(self.registers.h());
},
opcode.Opcode.LD_C_L => {
// LD C,L
self.registers.setC(self.registers.l());
},
opcode.Opcode.LD_C_HL => {
// LD C,(HL)
self.registers.setC(self.memory.get(self.registers.hl));
},
opcode.Opcode.LD_C_A => {
// LD C,A
self.registers.setC(self.registers.a());
},
opcode.Opcode.LD_D_B => {
// LD D,B
self.registers.setD(self.registers.b());
},
opcode.Opcode.LD_D_C => {
// LD D,C
self.registers.setD(self.registers.c());
},
opcode.Opcode.LD_D_D => {
// LD D,D
self.registers.setD(self.registers.d());
},
opcode.Opcode.LD_D_E => {
// LD D,E
self.registers.setD(self.registers.e());
},
opcode.Opcode.LD_D_H => {
// LD D,H
self.registers.setD(self.registers.h());
},
opcode.Opcode.LD_D_L => {
// LD D,L
self.registers.setD(self.registers.l());
},
opcode.Opcode.LD_D_HL => {
// LD D,(HL)
self.registers.setD(self.memory.get(self.registers.hl));
},
opcode.Opcode.LD_D_A => {
// LD D,A
self.registers.setD(self.registers.a());
},
opcode.Opcode.LD_E_B => {
// LD E,B
self.registers.setE(self.registers.b());
},
opcode.Opcode.LD_E_C => {
// LD E,C
self.registers.setE(self.registers.c());
},
opcode.Opcode.LD_E_D => {
// LD E,D
self.registers.setE(self.registers.d());
},
opcode.Opcode.LD_E_E => {
// LD E,E
self.registers.setE(self.registers.e());
},
opcode.Opcode.LD_E_H => {
// LD E,H
self.registers.setE(self.registers.h());
},
opcode.Opcode.LD_E_L => {
// LD E,L
self.registers.setE(self.registers.l());
},
opcode.Opcode.LD_E_HL => {
// LD E,(HL)
self.registers.setE(self.memory.get(self.registers.hl));
},
opcode.Opcode.LD_E_A => {
// LD E,A
self.registers.setE(self.registers.a());
},
opcode.Opcode.LD_H_B => {
// LD H,B
self.registers.setH(self.registers.b());
},
opcode.Opcode.LD_H_C => {
// LD H,C
self.registers.setH(self.registers.c());
},
opcode.Opcode.LD_H_D => {
// LD H,D
self.registers.setH(self.registers.d());
},
opcode.Opcode.LD_H_E => {
// LD H,E
self.registers.setH(self.registers.e());
},
opcode.Opcode.LD_H_H => {
// LD H,H
self.registers.setH(self.registers.h());
},
opcode.Opcode.LD_H_L => {
// LD H,L
self.registers.setH(self.registers.l());
},
opcode.Opcode.LD_H_HL => {
// LD H,(HL)
self.registers.setH(self.memory.get(self.registers.hl));
},
opcode.Opcode.LD_H_A => {
// LD H,A
self.registers.setH(self.registers.a());
},
opcode.Opcode.LD_L_B => {
// LD L,B
self.registers.setL(self.registers.b());
},
opcode.Opcode.LD_L_C => {
// LD L,C
self.registers.setL(self.registers.c());
},
opcode.Opcode.LD_L_D => {
// LD L,D
self.registers.setL(self.registers.d());
},
opcode.Opcode.LD_L_E => {
// LD L,E
self.registers.setL(self.registers.e());
},
opcode.Opcode.LD_L_H => {
// LD L,H
self.registers.setL(self.registers.h());
},
opcode.Opcode.LD_L_L => {
// LD L,L
self.registers.setL(self.registers.l());
},
opcode.Opcode.LD_L_HL => {
// LD L,(HL)
self.registers.setL(self.memory.get(self.registers.hl));
},
opcode.Opcode.LD_L_A => {
// LD L,A
self.registers.setL(self.registers.a());
},
opcode.Opcode.LD_HL_B => {
// LD (HL),B
self.memory.set(self.registers.hl, self.registers.b());
},
opcode.Opcode.LD_HL_C => {
// LD (HL),C
self.memory.set(self.registers.hl, self.registers.c());
},
opcode.Opcode.LD_HL_D => {
// LD (HL),D
self.memory.set(self.registers.hl, self.registers.d());
},
opcode.Opcode.LD_HL_E => {
// LD (HL),E
self.memory.set(self.registers.hl, self.registers.e());
},
opcode.Opcode.LD_HL_H => {
// LD (HL),H
self.memory.set(self.registers.hl, self.registers.h());
},
opcode.Opcode.LD_HL_L => {
// LD (HL),L
self.memory.set(self.registers.hl, self.registers.l());
},
opcode.Opcode.HALT => {
// HALT
return Mode.Halt;
},
opcode.Opcode.LD_HL_A => {
// LD (HL),A
self.memory.set(self.registers.hl, self.registers.a());
},
opcode.Opcode.LD_A_B => {
// LD A,B
self.registers.setA(self.registers.b());
},
opcode.Opcode.LD_A_C => {
// LD A,C
self.registers.setA(self.registers.c());
},
opcode.Opcode.LD_A_D => {
// LD A,D
self.registers.setA(self.registers.d());
},
opcode.Opcode.LD_A_E => {
// LD A,E
self.registers.setA(self.registers.e());
},
opcode.Opcode.LD_A_H => {
// LD A,H
self.registers.setA(self.registers.h());
},
opcode.Opcode.LD_A_L => {
// LD A,L
self.registers.setA(self.registers.l());
},
opcode.Opcode.LD_A_HL => {
// LD A,(HL)
self.registers.setA(self.memory.get(self.registers.hl));
},
opcode.Opcode.ADD_A_B => {
// ADD A,B
self.registers.setA(self.add(u8, self.registers.a(), self.registers.b()));
},
opcode.Opcode.ADD_A_C => {
// ADD A,C
self.registers.setA(self.add(u8, self.registers.a(), self.registers.c()));
},
opcode.Opcode.ADD_A_D => {
// ADD A,D
self.registers.setA(self.add(u8, self.registers.a(), self.registers.d()));
},
opcode.Opcode.ADD_A_E => {
// ADD A,E
self.registers.setA(self.add(u8, self.registers.a(), self.registers.e()));
},
opcode.Opcode.ADD_A_H => {
// ADD A,H
self.registers.setA(self.add(u8, self.registers.a(), self.registers.h()));
},
opcode.Opcode.ADD_A_L => {
// ADD A,L
self.registers.setA(self.add(u8, self.registers.a(), self.registers.l()));
},
opcode.Opcode.ADD_A_HL => {
// ADD A,(HL)
self.registers.setA(self.add(u8, self.registers.a(), self.memory.get(self.registers.hl)));
},
opcode.Opcode.ADD_A_A => {
// ADD A,A
self.registers.setA(self.add(u8, self.registers.a(), self.registers.a()));
},
opcode.Opcode.ADC_A_B => {
// ADC A,B
self.registers.setA(self.add(u8, self.registers.a(), self.registers.b() + @boolToInt(self.registers.carryFlag())));
},
opcode.Opcode.ADC_A_C => {
// ADC A,C
self.registers.setA(self.add(u8, self.registers.a(), self.registers.c() + @boolToInt(self.registers.carryFlag())));
},
opcode.Opcode.ADC_A_D => {
// ADC A,D
self.registers.setA(self.add(u8, self.registers.a(), self.registers.d() + @boolToInt(self.registers.carryFlag())));
},
opcode.Opcode.ADC_A_E => {
// ADC A,E
self.registers.setA(self.add(u8, self.registers.a(), self.registers.e() + @boolToInt(self.registers.carryFlag())));
},
opcode.Opcode.ADC_A_H => {
// ADC A,H
self.registers.setA(self.add(u8, self.registers.a(), self.registers.h() + @boolToInt(self.registers.carryFlag())));
},
opcode.Opcode.ADC_A_L => {
// ADC A,L
self.registers.setA(self.add(u8, self.registers.a(), self.registers.l() + @boolToInt(self.registers.carryFlag())));
},
opcode.Opcode.ADC_A_HL => {
// ADC A,(HL)
self.registers.setA(self.add(u8, self.registers.a(), self.memory.get(self.registers.hl) + @boolToInt(self.registers.carryFlag())));
},
opcode.Opcode.ADC_A_A => {
// ADC A,A
self.registers.setA(self.add(u8, self.registers.a(), self.registers.a() + @boolToInt(self.registers.carryFlag())));
},
opcode.Opcode.SUB_A_B => {
// SUB A,B
self.registers.setA(self.sub(self.registers.a(), self.registers.b()));
},
opcode.Opcode.SUB_A_C => {
// SUB A,C
self.registers.setA(self.sub(self.registers.a(), self.registers.c()));
},
opcode.Opcode.SUB_A_D => {
// SUB A,D
self.registers.setA(self.sub(self.registers.a(), self.registers.d()));
},
opcode.Opcode.SUB_A_E => {
// SUB A,E
self.registers.setA(self.sub(self.registers.a(), self.registers.e()));
},
opcode.Opcode.SUB_A_H => {
// SUB A,H
self.registers.setA(self.sub(self.registers.a(), self.registers.h()));
},
opcode.Opcode.SUB_A_L => {
// SUB A,L
self.registers.setA(self.sub(self.registers.a(), self.registers.l()));
},
opcode.Opcode.SUB_A_HL => {
// SUB A,(HL)
self.registers.setA(self.sub(self.registers.a(), self.memory.get(self.registers.hl)));
},
opcode.Opcode.SUB_A_A => {
// SUB A,A
self.registers.setA(self.sub(self.registers.a(), self.registers.a()));
},
opcode.Opcode.SBC_A_B => {
// SBC A,B
self.registers.setA(self.sub(self.registers.a(), self.registers.b() + @boolToInt(self.registers.carryFlag())));
},
opcode.Opcode.SBC_A_C => {
// SBC A,C
self.registers.setA(self.sub(self.registers.a(), self.registers.c() + @boolToInt(self.registers.carryFlag())));
},
opcode.Opcode.SBC_A_D => {
// SBC A,D
self.registers.setA(self.sub(self.registers.a(), self.registers.d() + @boolToInt(self.registers.carryFlag())));
},
opcode.Opcode.SBC_A_E => {
// SBC A,E
self.registers.setA(self.sub(self.registers.a(), self.registers.e() + @boolToInt(self.registers.carryFlag())));
},
opcode.Opcode.SBC_A_H => {
// SBC A,H
self.registers.setA(self.sub(self.registers.a(), self.registers.h() + @boolToInt(self.registers.carryFlag())));
},
opcode.Opcode.SBC_A_L => {
// SBC A,L
self.registers.setA(self.sub(self.registers.a(), self.registers.l() + @boolToInt(self.registers.carryFlag())));
},
opcode.Opcode.SBC_A_HL => {
// SBC A,(HL)
self.registers.setA(self.sub(self.registers.a(), self.memory.get(self.registers.hl) + @boolToInt(self.registers.carryFlag())));
},
opcode.Opcode.SBC_A_A => {
// SBC A,A
self.registers.setA(self.sub(self.registers.a(), self.registers.a() + @boolToInt(self.registers.carryFlag())));
},
opcode.Opcode.AND_A_B => {
// AND A,B
self.registers.setA(self.bitwiseAnd(self.registers.a(), self.registers.b()));
},
opcode.Opcode.AND_A_C => {
// AND A,C
self.registers.setA(self.bitwiseAnd(self.registers.a(), self.registers.c()));
},
opcode.Opcode.AND_A_D => {
// AND A,D
self.registers.setA(self.bitwiseAnd(self.registers.a(), self.registers.d()));
},
opcode.Opcode.AND_A_E => {
// AND A,E
self.registers.setA(self.bitwiseAnd(self.registers.a(), self.registers.e()));
},
opcode.Opcode.AND_A_H => {
// AND A,H
self.registers.setA(self.bitwiseAnd(self.registers.a(), self.registers.h()));
},
opcode.Opcode.AND_A_L => {
// AND A,L
self.registers.setA(self.bitwiseAnd(self.registers.a(), self.registers.l()));
},
opcode.Opcode.AND_A_HL => {
// AND A,(HL)
self.registers.setA(self.bitwiseAnd(self.registers.a(), self.memory.get(self.registers.hl)));
},
opcode.Opcode.AND_A_A => {
// AND A,A
self.registers.setA(self.bitwiseAnd(self.registers.a(), self.registers.a()));
},
opcode.Opcode.XOR_A_B => {
// XOR A,B
self.registers.setA(self.bitwiseXor(self.registers.a(), self.registers.b()));
},
opcode.Opcode.XOR_A_C => {
// XOR A,C
self.registers.setA(self.bitwiseXor(self.registers.a(), self.registers.c()));
},
opcode.Opcode.XOR_A_D => {
// XOR A,D
self.registers.setA(self.bitwiseXor(self.registers.a(), self.registers.d()));
},
opcode.Opcode.XOR_A_E => {
// XOR A,E
self.registers.setA(self.bitwiseXor(self.registers.a(), self.registers.e()));
},
opcode.Opcode.XOR_A_H => {
// XOR A,H
self.registers.setA(self.bitwiseXor(self.registers.a(), self.registers.h()));
},
opcode.Opcode.XOR_A_L => {
// XOR A,L
self.registers.setA(self.bitwiseXor(self.registers.a(), self.registers.l()));
},
opcode.Opcode.XOR_A_HL => {
// XOR A,(HL)
self.registers.setA(self.bitwiseXor(self.registers.a(), self.memory.get(self.registers.hl)));
},
opcode.Opcode.XOR_A_A => {
// XOR A,A
self.registers.setA(self.bitwiseXor(self.registers.a(), self.registers.a()));
},
opcode.Opcode.OR_A_B => {
// OR A,B
self.registers.setA(self.bitwiseOr(self.registers.a(), self.registers.b()));
},
opcode.Opcode.OR_A_C => {
// OR A,C
self.registers.setA(self.bitwiseOr(self.registers.a(), self.registers.c()));
},
opcode.Opcode.OR_A_D => {
// OR A,D
self.registers.setA(self.bitwiseOr(self.registers.a(), self.registers.d()));
},
opcode.Opcode.OR_A_E => {
// OR A,E
self.registers.setA(self.bitwiseOr(self.registers.a(), self.registers.e()));
},
opcode.Opcode.OR_A_H => {
// OR A,H
self.registers.setA(self.bitwiseOr(self.registers.a(), self.registers.h()));
},
opcode.Opcode.OR_A_L => {
// OR A,L
self.registers.setA(self.bitwiseOr(self.registers.a(), self.registers.l()));
},
opcode.Opcode.OR_A_HL => {
// OR A,(HL)
self.registers.setA(self.bitwiseOr(self.registers.a(), self.memory.get(self.registers.hl)));
},
opcode.Opcode.OR_A_A => {
// OR A,A
self.registers.setA(self.bitwiseOr(self.registers.a(), self.registers.a()));
},
opcode.Opcode.CP_A_B => {
// CP A,B
_ = self.sub(self.registers.a(), self.registers.b());
},
opcode.Opcode.CP_A_C => {
// CP A,C
_ = self.sub(self.registers.a(), self.registers.c());
},
opcode.Opcode.CP_A_D => {
// CP A,D
_ = self.sub(self.registers.a(), self.registers.d());
},
opcode.Opcode.CP_A_E => {
// CP A,E
_ = self.sub(self.registers.a(), self.registers.e());
},
opcode.Opcode.CP_A_H => {
// CP A,H
_ = self.sub(self.registers.a(), self.registers.h());
},
opcode.Opcode.CP_A_L => {
// CP A,B
_ = self.sub(self.registers.a(), self.registers.l());
},
opcode.Opcode.CP_A_HL => {
// CP A,B
_ = self.sub(self.registers.a(), self.memory.get(self.registers.hl));
},
opcode.Opcode.CP_A_A => {
// CP A,A
_ = self.sub(self.registers.a(), self.registers.a());
},
opcode.Opcode.RET_NZ => {
// RET NZ
if (!self.registers.zeroFlag()) {
self.registers.pc = self.pop(u16);
}
},
opcode.Opcode.POP_BC => {
// POP BC
self.registers.bc = self.pop(u16);
},
opcode.Opcode.JP_NZ_nn => {
// JP NZ,nn
const address = try self.stream.readIntLittle(u16);
if (!self.registers.zeroFlag()) {
self.registers.pc = address;
}
},
opcode.Opcode.JP_nn => {
// JP
self.registers.pc = try self.stream.readIntLittle(u16);
},
opcode.Opcode.CALL_NZ_nn => {
// CALL NZ,nn
if (!self.registers.zeroFlag()) {
self.call(try self.stream.readIntLittle(u16));
}
},
opcode.Opcode.PUSH_BC => {
// PUSH BC
self.push(self.registers.bc);
},
opcode.Opcode.ADC_A_n => {
// ADD A,n
self.registers.setA(self.add(u8, self.registers.a(), try self.stream.readByte()));
},
opcode.Opcode.RST_00, opcode.Opcode.RST_08, opcode.Opcode.RST_10, opcode.Opcode.RST_18, opcode.Opcode.RST_20, opcode.Opcode.RST_28, opcode.Opcode.RST_30, opcode.Opcode.RST_38 => |op| {
// RST n
self.registers.pc = switch (op) {
opcode.Opcode.RST_00 => u16(0x00),
opcode.Opcode.RST_08 => u16(0x08),
opcode.Opcode.RST_10 => u16(0x10),
opcode.Opcode.RST_18 => u16(0x18),
opcode.Opcode.RST_20 => u16(0x20),
opcode.Opcode.RST_28 => u16(0x28),
opcode.Opcode.RST_30 => u16(0x30),
opcode.Opcode.RST_38 => u16(0x38),
else => unreachable,
};
},
opcode.Opcode.RET_Z => {
// RET Z
if (self.registers.zeroFlag()) {
self.registers.pc = self.pop(u16);
}
},
opcode.Opcode.RET => {
// RET
self.registers.pc = self.pop(u16);
},
opcode.Opcode.JP_Z_nn => {
// JP Z,nn
const address = try self.stream.readIntLittle(u16);
if (self.registers.zeroFlag()) {
self.registers.pc = address;
}
},
opcode.Opcode.MISC => {
switch (@intToEnum(opcode.MiscOpcode, try self.stream.readByte())) {
opcode.MiscOpcode.RLC_B => {
// RLC B
self.registers.setB(self.rlc(self.registers.b()));
},
opcode.MiscOpcode.RLC_C => {
// RLC C
self.registers.setC(self.rlc(self.registers.c()));
},
opcode.MiscOpcode.RLC_D => {
// RLC D
self.registers.setD(self.rlc(self.registers.d()));
},
opcode.MiscOpcode.RLC_E => {
// RLC E
self.registers.setE(self.rlc(self.registers.e()));
},
opcode.MiscOpcode.RLC_H => {
// RLC H
self.registers.setH(self.rlc(self.registers.h()));
},
opcode.MiscOpcode.RLC_L => {
// RLC L
self.registers.setL(self.rlc(self.registers.l()));
},
opcode.MiscOpcode.RLC_HL => {
// RLC (HL)
self.memory.set(self.registers.hl, self.rlc(self.memory.get(self.registers.hl)));
},
opcode.MiscOpcode.RLC_A => {
// RLC A
self.registers.setA(self.rlc(self.registers.a()));
},
opcode.MiscOpcode.RRC_B => {
// RRC B
self.registers.setB(self.rrc(self.registers.b()));
},
opcode.MiscOpcode.RRC_C => {
// RRC C
self.registers.setC(self.rrc(self.registers.c()));
},
opcode.MiscOpcode.RRC_D => {
// RRC D
self.registers.setD(self.rrc(self.registers.d()));
},
opcode.MiscOpcode.RRC_E => {
// RRC E
self.registers.setE(self.rrc(self.registers.e()));
},
opcode.MiscOpcode.RRC_H => {
// RRC H
self.registers.setH(self.rrc(self.registers.h()));
},
opcode.MiscOpcode.RRC_L => {
// RRC L
self.registers.setL(self.rrc(self.registers.l()));
},
opcode.MiscOpcode.RRC_HL => {
// RRC (HL)
self.memory.set(self.registers.hl, self.rrc(self.memory.get(self.registers.hl)));
},
opcode.MiscOpcode.RRC_A => {
// RRC A
self.registers.setA(self.rrc(self.registers.a()));
},
opcode.MiscOpcode.RL_B => {
// RL B
self.registers.setB(self.rl(self.registers.b()));
},
opcode.MiscOpcode.RL_C => {
// RL C
self.registers.setC(self.rl(self.registers.c()));
},
opcode.MiscOpcode.RL_D => {
// RL D
self.registers.setD(self.rl(self.registers.d()));
},
opcode.MiscOpcode.RL_E => {
// RL E
self.registers.setE(self.rl(self.registers.e()));
},
opcode.MiscOpcode.RL_H => {
// RL H
self.registers.setH(self.rl(self.registers.h()));
},
opcode.MiscOpcode.RL_L => {
// RL L
self.registers.setL(self.rl(self.registers.l()));
},
opcode.MiscOpcode.RL_HL => {
// RL (HL)
self.memory.set(self.registers.hl, self.rl(self.memory.get(self.registers.hl)));
},
opcode.MiscOpcode.RL_A => {
// RL A
self.registers.setA(self.rl(self.registers.a()));
},
opcode.MiscOpcode.RR_B => {
// RR B
self.registers.setB(self.rr(self.registers.b()));
},
opcode.MiscOpcode.RR_C => {
// RR C
self.registers.setC(self.rr(self.registers.c()));
},
opcode.MiscOpcode.RR_D => {
// RR D
self.registers.setD(self.rr(self.registers.d()));
},
opcode.MiscOpcode.RR_E => {
// RR E
self.registers.setE(self.rr(self.registers.e()));
},
opcode.MiscOpcode.RR_H => {
// RR H
self.registers.setH(self.rr(self.registers.h()));
},
opcode.MiscOpcode.RR_L => {
// RR L
self.registers.setL(self.rr(self.registers.l()));
},
opcode.MiscOpcode.RR_HL => {
// RR (HL)
self.memory.set(self.registers.hl, self.rr(self.memory.get(self.registers.hl)));
},
opcode.MiscOpcode.RR_A => {
// RR A
self.registers.setA(self.rr(self.registers.a()));
},
opcode.MiscOpcode.SLA_B => {
// SLA B
self.registers.setB(self.sla(self.registers.b()));
},
opcode.MiscOpcode.SLA_C => {
// SLA C
self.registers.setC(self.sla(self.registers.c()));
},
opcode.MiscOpcode.SLA_D => {
// SLA D
self.registers.setD(self.sla(self.registers.d()));
},
opcode.MiscOpcode.SLA_E => {
// SLA E
self.registers.setE(self.sla(self.registers.e()));
},
opcode.MiscOpcode.SLA_H => {
// SLA H
self.registers.setH(self.sla(self.registers.h()));
},
opcode.MiscOpcode.SLA_L => {
// SLA L
self.registers.setL(self.sla(self.registers.l()));
},
opcode.MiscOpcode.SLA_HL => {
// SLA (HL)
self.memory.set(self.registers.hl, self.sla(self.memory.get(self.registers.hl)));
},
opcode.MiscOpcode.SLA_A => {
// SLA A
self.registers.setA(self.sla(self.registers.a()));
},
opcode.MiscOpcode.SRA_B => {
// SRA B
self.registers.setB(self.sra(self.registers.b()));
},
opcode.MiscOpcode.SRA_C => {
// SRA C
self.registers.setC(self.sra(self.registers.c()));
},
opcode.MiscOpcode.SRA_D => {
// SRA D
self.registers.setD(self.sra(self.registers.d()));
},
opcode.MiscOpcode.SRA_E => {
// SRA E
self.registers.setE(self.sra(self.registers.e()));
},
opcode.MiscOpcode.SRA_H => {
// SRA H
self.registers.setH(self.sra(self.registers.h()));
},
opcode.MiscOpcode.SRA_L => {
// SRA L
self.registers.setL(self.sra(self.registers.l()));
},
opcode.MiscOpcode.SRA_HL => {
// SRA (HL)
self.memory.set(self.registers.hl, self.sra(self.memory.get(self.registers.hl)));
},
opcode.MiscOpcode.SRA_A => {
// SRA A
self.registers.setA(self.sra(self.registers.a()));
},
opcode.MiscOpcode.SWAP_B => {
// SWAP B
self.registers.setB(self.swap(self.registers.b()));
},
opcode.MiscOpcode.SWAP_C => {
// SWAP C
self.registers.setC(self.swap(self.registers.c()));
},
opcode.MiscOpcode.SWAP_D => {
// SWAP D
self.registers.setD(self.swap(self.registers.d()));
},
opcode.MiscOpcode.SWAP_E => {
// SWAP E
self.registers.setE(self.swap(self.registers.e()));
},
opcode.MiscOpcode.SWAP_H => {
// SWAP H
self.registers.setH(self.swap(self.registers.h()));
},
opcode.MiscOpcode.SWAP_L => {
// SWAP L
self.registers.setL(self.swap(self.registers.l()));
},
opcode.MiscOpcode.SWAP_HL => {
// SWAP (HL)
self.memory.set(self.registers.hl, self.swap(self.memory.get(self.registers.hl)));
},
opcode.MiscOpcode.SWAP_A => {
// SWAP A
self.registers.setA(self.swap(self.registers.a()));
},
opcode.MiscOpcode.SRL_B => {
// SRL B
self.registers.setB(self.srl(self.registers.b()));
},
opcode.MiscOpcode.SRL_C => {
// SRL C
self.registers.setC(self.srl(self.registers.c()));
},
opcode.MiscOpcode.SRL_D => {
// SRL D
self.registers.setD(self.srl(self.registers.d()));
},
opcode.MiscOpcode.SRL_E => {
// SRL E
self.registers.setE(self.srl(self.registers.e()));
},
opcode.MiscOpcode.SRL_H => {
// SRL H
self.registers.setH(self.srl(self.registers.h()));
},
opcode.MiscOpcode.SRL_L => {
// SRL L
self.registers.setL(self.srl(self.registers.l()));
},
opcode.MiscOpcode.SRL_HL => {
// SRL (HL)
self.memory.set(self.registers.hl, self.srl(self.memory.get(self.registers.hl)));
},
opcode.MiscOpcode.SRL_A => {
// SRL A
self.registers.setA(self.srl(self.registers.a()));
},
opcode.MiscOpcode.BIT_B => {
// BIT n,B
self.testBit(self.registers.b(), try self.stream.readByte());
},
opcode.MiscOpcode.BIT_C => {
// BIT n,C
self.testBit(self.registers.c(), try self.stream.readByte());
},
opcode.MiscOpcode.BIT_D => {
// BIT n,D
self.testBit(self.registers.d(), try self.stream.readByte());
},
opcode.MiscOpcode.BIT_E => {
// BIT n,E
self.testBit(self.registers.e(), try self.stream.readByte());
},
opcode.MiscOpcode.BIT_H => {
// BIT n,H
self.testBit(self.registers.h(), try self.stream.readByte());
},
opcode.MiscOpcode.BIT_L => {
// BIT n,L
self.testBit(self.registers.l(), try self.stream.readByte());
},
opcode.MiscOpcode.BIT_HL => {
// BIT n,(HL)
self.testBit(self.memory.get(self.registers.hl), try self.stream.readByte());
},
opcode.MiscOpcode.BIT_A => {
// BIT n,A
self.testBit(self.registers.a(), try self.stream.readByte());
},
opcode.MiscOpcode.RES_B => {
// RES n,B
self.registers.setB(self.registers.b() & ~(u8(1) << @truncate(u3, try self.stream.readByte())));
},
opcode.MiscOpcode.RES_C => {
// RES n,C
self.registers.setC(self.registers.c() & ~(u8(1) << @truncate(u3, try self.stream.readByte())));
},
opcode.MiscOpcode.RES_D => {
// RES n,D
self.registers.setD(self.registers.d() & ~(u8(1) << @truncate(u3, try self.stream.readByte())));
},
opcode.MiscOpcode.RES_E => {
// RES n,E
self.registers.setE(self.registers.e() & ~(u8(1) << @truncate(u3, try self.stream.readByte())));
},
opcode.MiscOpcode.RES_H => {
// RES n,H
self.registers.setH(self.registers.h() & ~(u8(1) << @truncate(u3, try self.stream.readByte())));
},
opcode.MiscOpcode.RES_L => {
// RES n,L
self.registers.setL(self.registers.l() & ~(u8(1) << @truncate(u3, try self.stream.readByte())));
},
opcode.MiscOpcode.RES_HL => {
// RES n,(HL)
self.memory.set(self.registers.hl, self.memory.get(self.registers.hl) & ~(u8(1) << @truncate(u3, try self.stream.readByte())));
},
opcode.MiscOpcode.RES_A => {
// RES n,A
self.registers.setA(self.registers.a() & ~(u8(1) << @truncate(u3, try self.stream.readByte())));
},
opcode.MiscOpcode.SET_B => {
// SET n,B
self.registers.setB(self.registers.b() | (u8(1) << @truncate(u3, try self.stream.readByte())));
},
opcode.MiscOpcode.SET_C => {
// SET n,C
self.registers.setC(self.registers.c() | (u8(1) << @truncate(u3, try self.stream.readByte())));
},
opcode.MiscOpcode.SET_D => {
// SET n,D
self.registers.setD(self.registers.d() | (u8(1) << @truncate(u3, try self.stream.readByte())));
},
opcode.MiscOpcode.SET_E => {
// SET n,E
self.registers.setE(self.registers.e() | (u8(1) << @truncate(u3, try self.stream.readByte())));
},
opcode.MiscOpcode.SET_H => {
// SET n,H
self.registers.setH(self.registers.h() | (u8(1) << @truncate(u3, try self.stream.readByte())));
},
opcode.MiscOpcode.SET_L => {
// SET n,L
self.registers.setL(self.registers.l() | (u8(1) << @truncate(u3, try self.stream.readByte())));
},
opcode.MiscOpcode.SET_HL => {
// SET n,(HL)
self.memory.set(self.registers.hl, self.memory.get(self.registers.hl) | (u8(1) << @truncate(u3, try self.stream.readByte())));
},
opcode.MiscOpcode.SET_A => {
// SET n,A
self.registers.setA(self.registers.a() | (u8(1) << @truncate(u3, try self.stream.readByte())));
},
else => {
unreachable;
},
}
},
opcode.Opcode.CALL_Z_nn => {
// CALL Z,nn
if (self.registers.zeroFlag()) {
self.call(try self.stream.readIntLittle(u16));
}
},
opcode.Opcode.CALL_nn => {
// CALL nn
self.call(try self.stream.readIntLittle(u16));
},
opcode.Opcode.ADD_A_n => {
// ADC A,n
self.registers.setA(self.add(u8, self.registers.a(), (try self.stream.readByte()) + @boolToInt(self.registers.carryFlag())));
},
opcode.Opcode.RET_NC => {
// RET NC
if (!self.registers.carryFlag()) {
self.registers.pc = self.pop(u16);
}
},
opcode.Opcode.POP_DE => {
// POP DE
self.registers.de = self.pop(u16);
},
opcode.Opcode.JP_NC_nn => {
// JP NC,nn
const address = try self.stream.readIntLittle(u16);
if (!self.registers.carryFlag()) {
self.registers.pc = address;
}
},
opcode.Opcode.CALL_NC_nn => {
// CALL NC,nn
if (!self.registers.carryFlag()) {
self.call(try self.stream.readIntLittle(u16));
}
},
opcode.Opcode.PUSH_DE => {
// PUSH DE
self.push(self.registers.de);
},
opcode.Opcode.SBC_A_n => {
// SUB A,n
self.registers.setA(self.sub(self.registers.a(), try self.stream.readByte()));
},
opcode.Opcode.RET_C => {
// RET C
if (self.registers.carryFlag()) {
self.registers.pc = self.pop(u16);
}
},
opcode.Opcode.RETI => {
// RETI
self.registers.pc = self.pop(u16);
return Mode.EnableInterrupts;
},
opcode.Opcode.JP_C_nn => {
// JP C,nn
const address = try self.stream.readIntLittle(u16);
if (self.registers.carryFlag()) {
self.registers.pc = address;
}
},
opcode.Opcode.CALL_C_nn => {
// CALL C,nn
if (self.registers.carryFlag()) {
self.call(try self.stream.readIntLittle(u16));
}
},
opcode.Opcode.SUB_A_n => {
// SBC A,n
self.registers.setA(self.sub(self.registers.a(), (try self.stream.readByte()) + @boolToInt(self.registers.carryFlag())));
},
opcode.Opcode.LDH_n_A => {
// LDH ($FF00+n),A
self.memory.set(0xFF00 | u16(try self.stream.readByte()), self.registers.a());
},
opcode.Opcode.POP_HL => {
// POP HL
self.registers.hl = self.pop(u16);
},
opcode.Opcode.LD_mem_C_A => {
// LD ($FF00+C),A
self.memory.set(0xFF00 | u16(self.registers.c()), self.registers.a());
},
opcode.Opcode.PUSH_HL => {
// PUSH HL
self.push(self.registers.hl);
},
opcode.Opcode.AND_A_n => {
// AND A,n
self.registers.setA(self.bitwiseAnd(self.registers.a(), try self.stream.readByte()));
},
opcode.Opcode.ADD_SP_n => {
// ADD SP,n
self.registers.sp = self.add(u16, self.registers.sp, try self.stream.readByte());
},
opcode.Opcode.JP_HL => {
// JP (HL)
self.registers.pc = self.memory.get(self.registers.hl);
},
opcode.Opcode.LD_nn_A => {
// LD (nn),A
self.memory.set(try self.stream.readIntLittle(u16), self.registers.a());
},
opcode.Opcode.XOR_A_n => {
// XOR A,n
self.registers.setA(self.bitwiseXor(self.registers.a(), try self.stream.readByte()));
},
opcode.Opcode.LDH_A_n => {
// LDH A,($FF00+n)
self.registers.setA(self.memory.get(0xFF00 | u16(try self.stream.readByte())));
},
opcode.Opcode.POP_AF => {
// POP AF
self.registers.af = self.pop(u16);
},
opcode.Opcode.LD_A_mem_C => {
// LD A,($FF00+C)
self.registers.setA(self.memory.get(u16(0xFF00) | self.registers.c()));
},
opcode.Opcode.DI => {
// DI
return Mode.DisableInterrupts;
},
opcode.Opcode.PUSH_AF => {
// PUSH AF
self.push(self.registers.af);
},
opcode.Opcode.OR_A_n => {
// OR A,n
self.registers.setA(self.bitwiseOr(self.registers.a(), try self.stream.readByte()));
},
opcode.Opcode.LDHL_SP_n => {
// LDHL SP,n
const n = try self.stream.readByte();
self.registers.hl = self.add(u8, @truncate(u8, self.registers.sp), n);
},
opcode.Opcode.LD_SP_HL => {
// LD SP,HL
self.registers.sp = self.registers.hl;
},
opcode.Opcode.LD_A_nn => {
// LD A,(HL)
const address = try self.stream.readIntLittle(u16);
self.registers.setA(self.memory.get(address));
},
opcode.Opcode.EI => {
return Mode.EnableInterrupts;
},
opcode.Opcode.CP_A_n => {
// CP A,n
_ = self.sub(self.registers.a(), try self.stream.readByte());
},
else => {
unreachable;
},
}
return Mode.Default;
}
};
test "CPU" {
var cpu = try CPU.init(std.debug.global_allocator);
cpu.registers.pc = 0;
cpu.registers.hl = 0x55;
cpu.memory.set(0x0, 0x7E);
cpu.memory.set(0x55, 0x20);
_ = try cpu.execute();
std.debug.assert(cpu.registers.a() == 0x20);
std.debug.assert(cpu.registers.pc == 1);
std.debug.assert(cpu.add(u8, 0x4, 0x6) == 0xA);
std.debug.assert(!cpu.registers.halfCarryFlag());
std.debug.assert(cpu.add(u8, 0xA, 0x6) == 0x10);
std.debug.assert(cpu.registers.halfCarryFlag());
cpu.deinit();
}
|
src/cpu.zig
|
const std = @import("std");
const warn = std.debug.warn;
const idToString = @import("json_grammar.debug.zig").idToString;
const Lexer = @import("json_lexer.zig").Lexer;
const Types = @import("json_grammar.types.zig");
const Tokens = @import("json_grammar.tokens.zig");
const Actions = @import("json_grammar.actions.zig");
const Transitions = @import("json_grammar.tables.zig");
usingnamespace Tokens;
usingnamespace Actions;
usingnamespace Transitions;
pub usingnamespace Types;
const Parser = struct {
state: i16 = 0,
stack: Stack,
source: []const u8,
arena_allocator: *std.mem.Allocator,
pub fn init(allocator: *std.mem.Allocator, arena: *std.mem.Allocator, source: []const u8) Self {
return Self{ .stack = Stack.init(allocator), .source = source, .arena_allocator = arena };
}
pub fn deinit(self: *Self) void {
self.stack.deinit();
}
fn printStack(self: *const Self) void {
var it = self.stack.iterator();
while(it.next()) |item| {
switch(item.value) {
.Token => |id| { warn("{} ", idToString(id)); },
.Terminal => |id| { if(item.item != 0) { warn("{} ", terminalIdToString(id)); } },
}
}
}
pub const Self = @This();
pub const Stack = std.ArrayList(StackItem);
pub fn createVariant(self: *Self, comptime T: type) !*T {
const variant = try self.arena_allocator.create(T);
variant.base.id = Variant.typeToId(T);
return variant;
}
pub fn createVariantList(self: *Self, comptime T: type) !*T {
const list = try self.arena_allocator.create(T);
list.* = T.init(self.arena_allocator);
return list;
}
pub fn tokenString(self: *const Self, token: *Token) []const u8 {
return self.source[token.start..token.end];
}
pub fn unescapeTokenString(self: *const Self, token: *Token) ![]u8 {
const slice = self.source[token.start..token.end];
var size = slice.len;
var i: usize = 0;
while(i < slice.len) : (i += 1) {
if(slice[i] == '\\') {
size -= 1;
i += 1;
}
}
const result = try self.arena_allocator.alloc(u8, size);
i = 0;
var j: usize = 0;
while(j < slice.len) : (j += 1) {
if(slice[j] == '\\' or slice[j] == '\"') {
j += 1;
result[i] = switch(slice[j]) {
't' => '\t',
'r' => '\r',
'n' => '\n',
else => slice[j],
};
}
else {
result[i] = slice[j];
}
i += 1;
}
return result;
}
pub fn action(self: *Self, token_id: Id, token: *Token) !bool {
const id = @intCast(i16, @enumToInt(token_id));
action_loop: while (true) {
var state: usize = @bitCast(u16, self.state);
// Shifts
if (shift_table[state].len > 0) {
var shift: i16 = 0;
// Full table
if (shift_table[state][0] == -1) {
shift = shift_table[state][@bitCast(u16, id)];
}
// Key-Value pairs
else {
var i: usize = 0;
while (i < shift_table[state].len) : (i += 2) {
if (shift_table[state][i] == id) {
shift = shift_table[state][i + 1];
break;
}
}
}
if (shift > 0) {
// warn("{} ", idToString(token.id));
try self.stack.append(StackItem{ .item = @ptrToInt(token), .state = self.state, .value = StackValue{ .Token = token_id } });
self.state = shift;
return true;
}
}
// Reduces
if (reduce_table[state].len > 0) {
var reduce: i16 = 0;
// Key-Value pairs and default reduce
{
var i: usize = 0;
while (i < reduce_table[state].len) : (i += 2) {
if (reduce_table[state][i] == id or reduce_table[state][i] == -1) {
reduce = reduce_table[state][i + 1];
break;
}
}
}
if (reduce > 0) {
const consumes = consumes_table[@bitCast(u16, reduce)];
const produces = @enumToInt(try reduce_actions(Self, self, reduce, self.state));
state = @bitCast(u16, self.state);
// Gotos
const goto: i16 = goto_table[goto_index[state]][produces];
if (goto > 0) {
// if(consumes > 0) {
// warn("\n");
// self.printStack();
// }
self.state = goto;
continue :action_loop;
}
}
}
break :action_loop;
}
if(self.stack.len == 1 and token_id == .Eof) {
switch(self.stack.at(0).value) {
.Terminal => |terminal_id| {
if(terminal_id == .Object)
return true;
},
else => {}
}
}
return false;
}
};
pub const Json = struct {
arena: *std.heap.ArenaAllocator,
allocator: *std.mem.Allocator,
root: Element = Element{},
pub const Element = struct {
value: ?*Variant = null,
pub fn dump(self: *const Element) void {
const none = Element{};
const vv = self.value orelse return;
vv.dump(0);
}
pub fn v(self: *const Element, key: []const u8) Element {
const none = Element{};
const vv = self.value orelse return none;
const vo = vv.cast(Variant.Object) orelse return none;
const kv = vo.fields.find(key) orelse return none;
return Element{ .value = kv.value };
}
pub fn a(self: *const Element) []*Variant {
const none = [0]*Variant{};
const vv = self.value orelse return none;
const va = vv.cast(Variant.Array) orelse return none;
return va.elements.items[0..va.elements.len];
}
pub fn at(self: *const Element, index: usize) Element {
const none = Element{};
const vv = self.value orelse return none;
const va = vv.cast(Variant.Array) orelse return none;
return if(va.elements.len > index) Element{ .value = va.elements.items[index] } else none;
}
pub fn s(self: *const Element, default: ?[]const u8) ?[]const u8 {
const vv = self.value orelse return default;
const vs = vv.cast(Variant.StringLiteral) orelse return default;
return vs.value;
}
pub fn i(self: *const Element, default: ?i64) ?i64 {
const vv = self.value orelse return default;
const vi = vv.cast(Variant.IntegerLiteral) orelse return default;
return vi.value;
}
pub fn u(self: *const Element, default: ?u64) ?u64 {
const vu = self.i(null);
if(vu) |vv|
return @bitCast(u64, vv);
return default;
}
pub fn b(self: *const Element, default: ?bool) ?bool {
const vv = self.value orelse return default;
const vb = vv.cast(Variant.BoolLiteral) orelse return default;
return vb.value;
}
pub fn isNull(self: *const Element) bool {
const vv = self.value orelse return false;
const vn = vv.cast(Variant.NullLiteral) orelse return false;
return true;
}
};
pub fn init(allocator: *std.mem.Allocator) !Json {
var arena = try allocator.create(std.heap.ArenaAllocator);
arena.* = std.heap.ArenaAllocator.init(allocator);
return Json{ .arena = arena, .allocator = allocator };
}
pub fn initWithString(allocator: *std.mem.Allocator, str: []const u8) !?Json {
var arena = try allocator.create(std.heap.ArenaAllocator);
arena.* = std.heap.ArenaAllocator.init(allocator);
errdefer { arena.deinit(); allocator.destroy(arena); }
const maybe_root = try parse(allocator, &arena.allocator, str);
if(maybe_root) |root| {
return Json{ .arena = arena, .allocator = allocator, .root = Element{ .value = &root.base } };
}
arena.deinit();
allocator.destroy(arena);
return null;
}
pub fn deinit(self: *Json) void {
self.arena.deinit();
self.allocator.destroy(self.arena);
}
fn parse(allocator: *std.mem.Allocator, arena_allocator: *std.mem.Allocator, str: []const u8) !?*Variant.Object {
var lexer = Lexer.init(str);
var parser = Parser.init(allocator, arena_allocator, str);
defer parser.deinit();
var tokens = std.ArrayList(Token).init(allocator);
defer tokens.deinit();
while (true) {
var token = lexer.next();
try tokens.append(token);
if(token.id == .Eof)
break;
}
var i: usize = 0;
while(i < tokens.len) : (i += 1) {
const token = &tokens.items[i];
if(!try parser.action(token.id, token)) {
// std.debug.warn("\nerror => {}\n", token.id);
return null;
}
}
if(parser.stack.len == 0)
return null;
const root = @intToPtr(?*Variant, parser.stack.at(0).item) orelse return null;
return root.cast(Variant.Object);
}
};
|
json/json.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");
pub const Pathspec = opaque {
/// Free a pathspec
pub fn deinit(self: *Pathspec) void {
log.debug("Pathspec.deinit called", .{});
c.git_pathspec_free(@ptrCast(*c.git_pathspec, self));
log.debug("pathspec freed successfully", .{});
}
/// Try to match a path against a pathspec
///
/// Unlike most of the other pathspec matching functions, this will not fall back on the native case-sensitivity for your
/// platform. You must explicitly pass options to control case sensitivity or this will fall back on being case sensitive.
///
/// ## Parameters
/// * `options` - Options to control match
/// * `path` - The pathname to attempt to match
pub fn matchesPath(self: *const Pathspec, options: PathspecMatchOptions, path: [:0]const u8) !bool {
log.debug("Pathspec.matchesPath called, options: {}, path: {s}", .{ options, path });
const ret = (try internal.wrapCallWithReturn("git_pathspec_matches_path", .{
@ptrCast(*const c.git_pathspec, self),
@bitCast(c.git_pathspec_flag_t, options),
path.ptr,
})) != 0;
log.debug("match: {}", .{ret});
return ret;
}
comptime {
std.testing.refAllDecls(@This());
}
};
/// Options controlling how pathspec match should be executed
pub const PathspecMatchOptions = packed struct {
/// `ignore_case` forces match to ignore case; otherwise match will use native case sensitivity of platform filesystem
ignore_case: bool = false,
/// `use_case` forces case sensitive match; otherwise match will use native case sensitivity of platform filesystem
use_case: bool = false,
/// `no_glob` disables glob patterns and just uses simple string comparison for matching
no_glob: bool = false,
/// `no_match_error` means the match functions return error `GitError.NotFound` if no matches are found; otherwise no
/// matches is still success (return 0) but `PathspecMatchList.entryCount` will indicate 0 matches.
no_match_error: bool = false,
/// `find_failures` means that the `PathspecMatchList` should track which patterns matched which files so that at the end of
/// the match we can identify patterns that did not match any files.
find_failures: bool = false,
/// failures_only means that the `PathspecMatchList` does not need to keep the actual matching filenames.
/// Use this to just test if there were any matches at all or in combination with `find_failures` to validate a pathspec.
failures_only: bool = false,
z_padding: u26 = 0,
pub fn format(
value: PathspecMatchOptions,
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_pathspec_flag_t), @sizeOf(PathspecMatchOptions));
try std.testing.expectEqual(@bitSizeOf(c.git_pathspec_flag_t), @bitSizeOf(PathspecMatchOptions));
}
comptime {
std.testing.refAllDecls(@This());
}
};
/// list of filenames matching a pathspec
pub const PathspecMatchList = opaque {
/// Free a pathspec match list
pub fn deinit(self: *PathspecMatchList) void {
log.debug("PathspecMatchList.deinit called", .{});
c.git_pathspec_match_list_free(@ptrCast(*c.git_pathspec_match_list, self));
log.debug("pathspec match list freed successfully", .{});
}
/// Get the number of items in a match list.
pub fn entryCount(self: *const PathspecMatchList) usize {
log.debug("PathspecMatchList.entryCount called", .{});
const ret = c.git_pathspec_match_list_entrycount(
@ptrCast(*const c.git_pathspec_match_list, self),
);
log.debug("entry count: {}", .{ret});
return ret;
}
/// Get a matching filename by position.
///
/// This routine cannot be used if the match list was generated by `Diff.pathspecMatch`. If so, it will always return `null`.
///
/// ## Parameters
/// * `index` - The index into the list
pub fn getEntry(self: *const PathspecMatchList, index: usize) ?[:0]const u8 {
log.debug("PathspecMatchList.getEntry called, index: {}", .{index});
const opt_c_ptr = c.git_pathspec_match_list_entry(
@ptrCast(*const c.git_pathspec_match_list, self),
index,
);
if (opt_c_ptr) |c_ptr| {
const slice = std.mem.sliceTo(c_ptr, 0);
log.debug("entry: {s}", .{slice});
return slice;
} else {
log.debug("no such match", .{});
return null;
}
}
/// Get a matching diff delta by position.
///
/// This routine can only be used if the match list was generated by `Diff.pathspecMatch`.
/// Otherwise it will always return `null`.
///
/// ## Parameters
/// * `index` - The index into the list
pub fn getDiffEntry(self: *const PathspecMatchList, index: usize) ?*const git.DiffDelta {
log.debug("PathspecMatchList.getDiffEntry called, index: {}", .{index});
return @ptrCast(
?*const git.DiffDelta,
c.git_pathspec_match_list_diff_entry(
@ptrCast(*const c.git_pathspec_match_list, self),
index,
),
);
}
/// Get the number of pathspec items that did not match.
///
/// This will be zero unless you passed `PathspecMatchOptions.find_failures` when generating the `PathspecMatchList`.
pub fn failedEntryCount(self: *const PathspecMatchList) usize {
log.debug("PathspecMatchList.failedEntryCount called", .{});
const ret = c.git_pathspec_match_list_failed_entrycount(
@ptrCast(*const c.git_pathspec_match_list, self),
);
log.debug("non-matching entry count: {}", .{ret});
return ret;
}
/// Get an original pathspec string that had no matches.
///
/// This will be return `null` for positions out of range.
///
/// ## Parameters
/// * `index` - The index into the failed items
pub fn getFailedEntry(self: *const PathspecMatchList, index: usize) ?[:0]const u8 {
log.debug("PathspecMatchList.getFailedEntry called, index: {}", .{index});
const opt_c_ptr = c.git_pathspec_match_list_failed_entry(
@ptrCast(*const c.git_pathspec_match_list, self),
index,
);
if (opt_c_ptr) |c_ptr| {
const slice = std.mem.sliceTo(c_ptr, 0);
log.debug("entry: {s}", .{slice});
return slice;
} else {
log.debug("no such failed match", .{});
return null;
}
}
comptime {
std.testing.refAllDecls(@This());
}
};
comptime {
std.testing.refAllDecls(@This());
}
|
src/pathspec.zig
|
const std = @import("std");
const TypeId = @import("builtin").TypeId;
const whereIt = @import("where.zig").iterator;
const selectIt = @import("select.zig").iterator;
const castIt = @import("cast.zig").iterator;
const orderIt = @import("order.zig").iterator;
const skipIt = @import("skip.zig").iterator;
const skipWhileIt = @import("skipWhile.zig").iterator;
const takeIt = @import("take.zig").iterator;
const takeWhileIt = @import("takeWhile.zig").iterator;
const concatIt = @import("concat.zig").iterator;
const selectManyIt = @import("selectMany.zig").iterator;
const reverseIt = @import("reverse.zig").iterator;
pub fn iterator(comptime BaseType: type, comptime ItType: type) type {
return struct {
nextIt: ItType,
const Self = @This();
pub fn next(self: *Self) ?BaseType {
return self.nextIt.next();
}
pub fn reset(self: *Self) void {
self.nextIt.reset();
}
pub fn count(self: *Self) i32 {
return self.nextIt.count();
}
fn returnBasedOnThis(self: *Self, comptime TypeA: type, comptime TypeB: type) iterator(TypeA, TypeB) {
return iterator(TypeA, TypeB){
.nextIt = TypeB{ .nextIt = &self.nextIt },
};
}
pub fn where(self: *Self, comptime filter: fn (BaseType) bool) iterator(BaseType, whereIt(BaseType, ItType, filter)) {
return self.returnBasedOnThis(BaseType, whereIt(BaseType, ItType, filter));
}
fn add(a: BaseType, b: BaseType) BaseType {
return a + b;
}
pub fn sum(self: *Self) ?BaseType {
return self.aggregate(add);
}
fn compare(self: *Self, comptime comparer: fn (BaseType, BaseType) i32, comptime result: i32) ?BaseType {
var maxValue: ?BaseType = null;
self.reset();
defer self.reset();
while (self.next()) |nxt| {
if (maxValue == null or comparer(nxt, maxValue) == result) {
maxValue = nxt;
}
}
return maxValue;
}
pub fn max(self: *Self, comptime comparer: fn (BaseType, BaseType) i32) ?BaseType {
return self.compare(comparer, 1);
}
pub fn min(self: *Self, comptime comparer: fn (BaseType, BaseType) i32) ?BaseType {
return self.compare(comparer, -1);
}
pub fn reverse(self: *Self, buf: []BaseType) iterator(BaseType, reverseIt(BaseType, ItType)) {
return iterator(BaseType, reverseIt(BaseType, ItType)){
.nextIt = reverseIt(BaseType, ItType){
.nextIt = &self.nextIt,
.index = 0,
.count = 0,
.buf = buf,
},
};
}
pub fn orderByDescending(self: *Self, comptime NewType: type, comptime selectObj: fn (BaseType) NewType, buf: []BaseType) iterator(NewType, orderIt(BaseType, NewType, ItType, false, selectObj)) {
return iterator(NewType, orderIt(BaseType, NewType, ItType, false, selectObj)){
.nextIt = orderIt(BaseType, NewType, ItType, false, selectObj){
.nextIt = &self.nextIt,
.index = 0,
.count = 0,
.buf = buf,
},
};
}
pub fn orderByAscending(self: *Self, comptime NewType: type, comptime selectObj: fn (BaseType) NewType, buf: []BaseType) iterator(NewType, orderIt(BaseType, NewType, ItType, true, selectObj)) {
return iterator(NewType, orderIt(BaseType, NewType, ItType, true, selectObj)){
.nextIt = orderIt(BaseType, NewType, ItType, true, selectObj){
.nextIt = &self.nextIt,
.index = 0,
.count = 0,
.buf = buf,
},
};
}
fn performTransform(self: *Self, comptime func: fn (BaseType, BaseType) BaseType, comptime average: bool) ?BaseType {
var aggregate: ?BaseType = null;
self.reset();
defer self.reset();
var cnt: usize = 0;
while (self.next()) |nxt| {
cnt += 1;
if (aggregate == null) {
aggregate = nxt;
} else {
aggregate = func(aggregate, nxt);
}
}
if (aggregate and average) |agg| {
return agg / cnt;
} else {
return aggregate;
}
}
pub fn average(self: *Self, comptime func: fn (BaseType, BaseType) BaseType) ?BaseType {
return performTransform(func, true);
}
pub fn aggregate(self: *Self, comptime func: fn (BaseType, BaseType) BaseType) ?BaseType {
return performTransform(func, false);
}
// Select many currently only supports arrays
pub fn selectMany(self: *Self, comptime NewType: type, comptime filter: fn (BaseType) []const NewType) iterator(NewType, selectManyIt(BaseType, NewType, ItType, filter)) {
return iterator(NewType, selectManyIt(BaseType, NewType, ItType, filter)){
.nextIt = selectManyIt(BaseType, NewType, ItType, filter){
.nextIt = &self.nextIt,
.currentIt = null,
},
};
}
// Currently requires you to give a new type, since can't have 'var' return type.
pub fn select(self: *Self, comptime NewType: type, comptime filter: fn (BaseType) NewType) iterator(NewType, selectIt(BaseType, NewType, ItType, filter)) {
return self.returnBasedOnThis(NewType, selectIt(BaseType, NewType, ItType, filter));
}
pub fn cast(self: *Self, comptime NewType: type) iterator(NewType, castIt(BaseType, NewType, ItType)) {
return self.returnBasedOnThis(NewType, castIt(BaseType, NewType, ItType));
}
pub fn all(self: *Self, comptime condition: fn (BaseType) bool) bool {
self.reset();
defer self.reset();
while (self.next()) |nxt| {
if (!condition(nxt)) {
return false;
}
}
return true;
}
pub fn any(self: *Self, comptime condition: fn (BaseType) bool) bool {
self.reset();
defer self.reset();
while (self.next()) |nxt| {
if (condition(nxt)) {
return true;
}
}
return false;
}
pub fn contains(self: *Self, value: BaseType) bool {
self.reset();
defer self.reset();
while (self.next()) |nxt| {
if (nxt == value) {
return true;
}
}
return false;
}
pub fn take(self: *Self, comptime amount: usize) iterator(BaseType, takeIt(BaseType, amount)) {
return self.returnBasedOnThis(BaseType, takeIt(BaseType, amount));
}
pub fn takeWhile(self: *Self, comptime condition: fn (BaseType) bool) iterator(BaseType, takeWhileIt(BaseType, condition)) {
return self.returnBasedOnThis(BaseType, takeWhileIt(BaseType, condition));
}
pub fn skip(self: *Self, comptime amount: usize) iterator(BaseType, skipIt(BaseType, amount)) {
return self.returnBasedOnThis(BaseType, skipIt(BaseType, amount));
}
pub fn skipWhile(self: *Self, comptime condition: fn (BaseType) bool) iterator(BaseType, skipWhileIt(BaseType, condition)) {
return self.returnBasedOnThis(BaseType, skipWhileIt(BaseType, condition));
}
pub fn concat(self: *Self, other: *Self) iterator(BaseType, concatIt(BaseType, ItType)) {
return iterator(BaseType, concatIt(BaseType, ItType)){
.nextIt = concatIt(BaseType, ItType){
.nextIt = &self.nextIt,
.otherIt = &other.nextIt,
},
};
}
pub fn toArray(self: *Self, buffer: []BaseType) []BaseType {
self.reset();
defer self.reset();
var c: usize = 0;
while (self.next()) |nxt| {
buffer[c] = nxt;
c += 1;
}
return buffer[0..c];
}
pub fn toList(self: *Self, allocator: *std.mem.Allocator) std.ArrayList(BaseType) {
self.reset();
defer self.reset();
var list = std.ArrayList(BaseType).init(allocator);
while (self.next()) |nxt| {
list.append(nxt);
}
return list;
}
};
}
|
src/iterator.zig
|
const std = @import("std");
const builtin = std.builtin;
const TypeInfo = builtin.TypeInfo;
const alignForward = std.mem.alignForward;
const pi = std.math.pi;
const testing = std.testing;
pub const Math = struct {
pub fn FixedPoint(comptime isSigned: bool, comptime integral: comptime_int, comptime fractional: comptime_int) type {
return packed struct {
raw: RawType = undefined,
const SignedRawType = @Type(TypeInfo{ .Int = TypeInfo.Int{ .signedness = .signed, .bits = integral + fractional } });
const UnsignedRawType = @Type(TypeInfo{ .Int = TypeInfo.Int{ .signedness = .unsigned, .bits = integral + fractional } });
const RawType = if (isSigned) SignedRawType else UnsignedRawType;
const SignedAlignIntegerType = @Type(TypeInfo{ .Int = TypeInfo.Int{ .signedness = .signed, .bits = alignForward(integral + fractional, 8) } });
const UnsignedAlignIntegerType = @Type(TypeInfo{ .Int = TypeInfo.Int{ .signedness = .unsigned, .bits = alignForward(integral + fractional, 8) } });
const AlignIntegerType = if (isSigned) SignedAlignIntegerType else UnsignedAlignIntegerType;
const InputIntegerType = @Type(TypeInfo{ .Int = TypeInfo.Int{ .signedness = if (isSigned) .signed else .unsigned, .bits = integral } });
const MaxIntegerType = if (isSigned) i32 else u32;
pub const Shift = fractional;
pub const Scale = 1 << fractional;
pub const IntegralMask = (1 << integral) - 1;
pub const FractionalMask = (1 << fractional) - 1;
const Self = @This();
pub inline fn fromInt(value: InputIntegerType) Self {
return Self{
.raw = @truncate(RawType, @intCast(AlignIntegerType, value) << Shift),
};
}
pub inline fn fromF32(comptime value: f32) Self {
return Self{
.raw = @floatToInt(RawType, value * Scale),
};
}
pub inline fn setInt(self: *Self, value: InputIntegerType) void {
self.raw = fromInt(value).raw;
}
pub inline fn setF32(self: *Self, comptime value: f32) void {
self.raw = fromF32(value).raw;
}
pub inline fn integral(self: Self) UnsignedAlignIntegerType {
return @intCast(UnsignedAlignIntegerType, (@bitCast(UnsignedRawType, self.raw) >> Shift) & (IntegralMask));
}
pub inline fn fractional(self: Self) UnsignedAlignIntegerType {
return @intCast(UnsignedAlignIntegerType, @bitCast(UnsignedRawType, self.raw) & FractionalMask);
}
pub inline fn toF32(self: Self) f32 {
return @intToFloat(f32, self.raw) / Scale;
}
pub inline fn add(left: Self, right: Self) Self {
return Self{
.raw = left.raw + right.raw,
};
}
pub inline fn addSelf(left: *Self, right: Self) void {
left.raw = add(left, right).raw;
}
pub inline fn sub(left: Self, right: Self) Self {
return Self{
.raw = left.raw - right.raw,
};
}
pub inline fn subSelf(left: *Self, right: Self) void {
left.raw = sub(left, right).raw;
}
pub inline fn mul(left: Self, right: Self) Self {
return Self{
.raw = @truncate(RawType, (@intCast(MaxIntegerType, left.raw) * @intCast(MaxIntegerType, right.raw)) >> Shift),
};
}
pub inline fn mulSelf(left: *Self, right: Self) void {
left.raw = mul(left, right).raw;
}
pub inline fn div(left: Self, right: Self) Self {
return Self{
.raw = @truncate(RawType, @divTrunc(@intCast(MaxIntegerType, left.raw) * Scale, @intCast(MaxIntegerType, right.raw))),
};
}
pub inline fn divSelf(left: *Self, right: Self) void {
left.raw = div(left, right).raw;
}
pub const toInt = if (isSigned) toIntSigned else toIntUnsigned;
fn toIntUnsigned(self: Self) AlignIntegerType {
return self.raw >> Shift;
}
fn toIntSigned(self: Self) AlignIntegerType {
return @divFloor(self.raw, Scale);
}
};
}
pub const FixedI8_8 = FixedPoint(true, 8, 8);
pub const FixedU8_8 = FixedPoint(false, 8, 8);
pub const FixedI4_12 = FixedPoint(true, 4, 12);
pub const FixedU4_12 = FixedPoint(false, 4, 12);
pub const FixedI19_8 = FixedPoint(true, 19, 8);
pub const FixedU19_8 = FixedPoint(false, 19, 8);
pub const sin_lut: [512]i16 = blk: {
@setEvalBranchQuota(10000);
var result: [512]i16 = undefined;
var i:usize = 0;
while (i < result.len) : (i += 1) {
const sinValue = std.math.sin(@intToFloat(f32, i) * 2.0 * pi/512.0);
const fixedValue = FixedI4_12.fromF32(sinValue);
result[i] = fixedValue.raw;
}
break :blk result;
};
pub fn sin(theta: i32) FixedI4_12 {
return FixedI4_12 {
.raw = sin_lut[@bitCast(u32, (theta>>7)&0x1FF)],
};
}
pub fn cos(theta: i32) FixedI4_12 {
return FixedI4_12 {
.raw = sin_lut[@bitCast(u32, ((theta>>7)+128)&0x1FF)],
};
}
pub inline fn degreeToGbaAngle(comptime input: i32) i32 {
return @floatToInt(i32, @intToFloat(f32, input) * ((1 << 16) / 360.0));
}
pub inline fn radianToGbaAngle(comptime input: f32) i32 {
return @floatToInt(i32, input * ((1 << 16) / (std.math.tau)));
}
};
test "signed addition" {
const signed = true;
const a = Math.FixedPoint(signed, 8, 8).fromF32(2.5);
const a_plus_a_result = a.add(a);
const a_plus_a_expected = Math.FixedPoint(signed, 8, 8).fromF32(5.0);
try testing.expectEqual(a_plus_a_result, a_plus_a_expected);
}
test "signed addition2" {
const signed = true;
const a = Math.FixedPoint(signed, 8, 8).fromInt(2);
const a_plus_a_result = a.add(a);
const a_plus_a_expected = Math.FixedPoint(signed, 8, 8).fromF32(4);
try testing.expectEqual(a_plus_a_result, a_plus_a_expected);
}
test "unsigned addition" {
const signed = false;
const a = Math.FixedPoint(signed, 8, 8).fromF32(2.5);
const a_plus_a_result = a.add(a);
const a_plus_a_expected = Math.FixedPoint(signed, 8, 8).fromF32(5.0);
try testing.expectEqual(a_plus_a_result, a_plus_a_expected);
}
test "unsigned addition2" {
const signed = false;
const a = Math.FixedPoint(signed, 8, 8).fromInt(2);
const a_plus_a_result = a.add(a);
const a_plus_a_expected = Math.FixedPoint(signed, 8, 8).fromF32(4);
try testing.expectEqual(a_plus_a_result, a_plus_a_expected);
}
|
GBA/math.zig
|
const std = @import("std");
//--------------------------------------------------------------------------------------------------
const Allocator = std.mem.Allocator;
const ArrayList = std.ArrayList;
const Range = struct { first: u16, last: u16, value: u16 };
const Ranges = ArrayList(Range);
const MapType = [1000][1000]u16;
//--------------------------------------------------------------------------------------------------
pub fn insert_vertical(x: u16, y1: u16, y2: u16, map: *MapType) void {
const min_y = std.math.min(y1, y2);
const max_y = std.math.max(y1, y2);
var idx: u16 = min_y;
while (idx <= max_y) : (idx += 1) {
map[x][idx] += 1;
}
}
//--------------------------------------------------------------------------------------------------
pub fn insert_horizontal(y: u16, x1: u16, x2: u16, map: *MapType) void {
const min_x = std.math.min(x1, x2);
const max_x = std.math.max(x1, x2);
var idx: u16 = min_x;
while (idx <= max_x) : (idx += 1) {
map[idx][y] += 1;
}
}
//--------------------------------------------------------------------------------------------------
pub fn insert_diagonal(x1: u16, y1: u16, x2: u16, y2: u16, map: *MapType) void {
const is_reversed = (x1 > x2);
const min_x = if (is_reversed) x2 else x1;
const max_x = if (is_reversed) x1 else x2;
const y_start = if (is_reversed) y2 else y1;
const y_finish = if (is_reversed) y1 else y2;
const inc_y: i32 = if (y_start > y_finish) -1 else 1;
var x: i32 = @as(i32, min_x);
var y: i32 = @as(i32, y_start);
while (x <= max_x) : ({
x += 1;
y += inc_y;
}) {
const i = @intCast(usize, x);
const j = @intCast(usize, y);
map[i][j] += 1;
}
}
//--------------------------------------------------------------------------------------------------
pub fn count_overlaps(map: *MapType) u16 {
var res: u16 = 0;
var x: u16 = 0;
while (x < 1000) : (x += 1) {
var y: u16 = 0;
while (y < 1000) : (y += 1) {
if (map[x][y] > 1) {
res += 1;
}
}
}
return res;
}
//--------------------------------------------------------------------------------------------------
pub fn part1() anyerror!void {
const file = std.fs.cwd().openFile("data/day05_input.txt", .{}) catch |err| label: {
std.debug.print("unable to open file: {e}\n", .{err});
const stderr = std.io.getStdErr();
break :label stderr;
};
defer file.close();
const file_size = try file.getEndPos();
std.log.info("File size {}", .{file_size});
var reader = std.io.bufferedReader(file.reader());
var istream = reader.reader();
var buf: [20]u8 = undefined;
var line_count: u32 = 0;
var values: [4]u16 = undefined;
var map = [_][1000]u16{.{0} ** 1000} ** 1000;
while (try istream.readUntilDelimiterOrEof(&buf, '\n')) |line| {
//std.log.info("{s}", .{line});
var it = std.mem.tokenize(u8, line, ", ->");
var idx: u32 = 0;
while (it.next()) |value| : ({
idx += 1;
idx = idx % 4;
}) {
values[idx] = std.fmt.parseInt(u16, value, 10) catch 0;
//std.log.info("value: {d} : (idx:{d})", .{ values[idx], idx });
}
std.log.info("value: {d}", .{values});
var x1: u16 = values[0];
var y1: u16 = values[1];
var x2: u16 = values[2];
var y2: u16 = values[3];
if (x1 == x2) {
insert_vertical(x1, y1, y2, &map);
} else if (y1 == y2) {
insert_horizontal(y1, x1, x2, &map);
} else {
insert_diagonal(x1, y1, x2, y2, &map);
}
line_count += 1;
}
const overlaps = count_overlaps(&map);
std.log.info("overlaps: {d}", .{overlaps});
//std.log.info("map size: {d}", .{map.count()});
}
//--------------------------------------------------------------------------------------------------
pub fn main() anyerror!void {
try part1();
}
//--------------------------------------------------------------------------------------------------
|
src/day05.zig
|
const std = @import("std");
const assert = std.debug.assert;
const tools = @import("tools");
const Registers = [6]u48;
const Opcode = enum { addi, addr, muli, mulr, bani, banr, bori, borr, setr, seti, gtir, gtri, gtrr, eqir, eqri, eqrr };
const Insn = struct { op: Opcode, par: [3]u32 };
const State = struct {
reg: Registers = Registers{ 0, 0, 0, 0, 0, 0 },
};
fn peekState1(ip: u48, s: State, _: void) bool {
_ = s;
return (ip == 28); // eqrr 4 0 1
}
const PeekCtx2 = struct {
visited: []bool,
prev: u48,
};
fn peekState2(ip: u48, state: State, ctx: *PeekCtx2) bool {
if (ip == 28) {
const val = state.reg[4];
if (ctx.visited[val])
return true;
ctx.visited[val] = true;
ctx.prev = val;
}
return false;
}
fn compile(comptime prg: []Insn, comptime ip_reg: u8) type {
return struct {
fn run(init_state: State, peekCtx: anytype, comptime peekFn: ?fn (ip: u48, s: State, ctx: @TypeOf(peekCtx)) bool) State {
var state = init_state;
while (true) {
const ip = state.reg[ip_reg];
if (peekFn) |f| {
if (f(ip, state, peekCtx)) return state;
} else {
if (ip >= prg.len) return state;
}
inline for (prg) |insn, i| {
if (ip == i) comptime_eval(insn.op, insn.par, &state.reg);
}
state.reg[ip_reg] += 1;
}
}
};
}
fn comptime_eval(comptime op: Opcode, comptime par: [3]u32, r: *Registers) void {
switch (op) {
.addi => r[par[2]] = r[par[0]] + par[1],
.addr => r[par[2]] = r[par[0]] + r[par[1]],
.muli => r[par[2]] = r[par[0]] * par[1],
.mulr => r[par[2]] = r[par[0]] * r[par[1]],
.bani => r[par[2]] = r[par[0]] & par[1],
.banr => r[par[2]] = r[par[0]] & r[par[1]],
.bori => r[par[2]] = r[par[0]] | par[1],
.borr => r[par[2]] = r[par[0]] | r[par[1]],
.setr => r[par[2]] = r[par[0]],
.seti => r[par[2]] = par[0],
.gtir => r[par[2]] = if (par[0] > r[par[1]]) @as(u32, 1) else @as(u32, 0),
.gtri => r[par[2]] = if (r[par[0]] > par[1]) @as(u32, 1) else @as(u32, 0),
.gtrr => r[par[2]] = if (r[par[0]] > r[par[1]]) @as(u32, 1) else @as(u32, 0),
.eqir => r[par[2]] = if (par[0] == r[par[1]]) @as(u32, 1) else @as(u32, 0),
.eqri => r[par[2]] = if (r[par[0]] == par[1]) @as(u32, 1) else @as(u32, 0),
.eqrr => r[par[2]] = if (r[par[0]] == r[par[1]]) @as(u32, 1) else @as(u32, 0),
}
}
fn parse(text: []const u8) struct { insns: []Insn, ip_reg: u8 } {
@setEvalBranchQuota(20000);
var buf: [50]Insn = undefined; // comme c'est comptime, ça marche de renvoyer un pointeur la dessus.
var l: u32 = 0;
var ip: ?u8 = null;
var it = std.mem.tokenize(u8, text, "\n\r");
while (it.next()) |line| {
var it2 = std.mem.tokenize(u8, line, " \t");
while (it2.next()) |field| {
if (std.mem.eql(u8, field, "#ip")) {
const arg = it2.next().?;
assert(ip == null);
ip = std.fmt.parseInt(u8, arg, 10) catch unreachable;
} else {
const op = tools.nameToEnum(Opcode, field) catch unreachable;
const par = [3]u32{
std.fmt.parseInt(u32, it2.next().?, 10) catch unreachable,
std.fmt.parseInt(u32, it2.next().?, 10) catch unreachable,
std.fmt.parseInt(u32, it2.next().?, 10) catch unreachable,
};
buf[l] = Insn{ .op = op, .par = par };
l += 1;
}
}
}
return .{ .ip_reg = ip.?, .insns = buf[0..l] };
}
pub fn run(_: []const u8, allocator: std.mem.Allocator) ![2][]const u8 {
var arena = std.heap.ArenaAllocator.init(allocator);
defer arena.deinit();
const prog = comptime parse(@embedFile("input_day21.txt"));
const compiled_prg = comptime compile(prog.insns, prog.ip_reg);
const ans1 = ans: {
const result = compiled_prg.run(State{ .reg = .{ 0, 0, 0, 0, 0, 0 } }, {}, peekState1);
break :ans result.reg[4];
};
const ans2 = ans: {
const visited = try allocator.alloc(bool, 16 * 1024 * 1024);
defer allocator.free(visited);
std.mem.set(bool, visited, false);
var ctx = PeekCtx2{ .visited = visited, .prev = 0 };
_ = compiled_prg.run(State{ .reg = .{ 0, 0, 0, 0, 0, 0 } }, &ctx, peekState2);
break :ans ctx.prev; // last non repeat
};
return [_][]const u8{
try std.fmt.allocPrint(allocator, "{}", .{ans1}),
try std.fmt.allocPrint(allocator, "{}", .{ans2}),
};
}
pub const main = tools.defaultMain("2018/input_day21.txt", run);
|
2018/day21_comptime.zig
|
const std = @import("std");
const builtin = @import("builtin");
const native_endian = builtin.target.cpu.arch.endian();
//@TODO: Allow for other clock rates
pub const clock_rate = 6_250_000; //6.25Mhz
//@TODO: Include a transalted version of the C VM for speed comparison and testing
//@TODO: Discuss with Zig whether or not endian-dependent
//bitfield ordering is actually a good idea.
pub const Instruction = switch(native_endian) {
//instruction format:
// [Operation][Mode][Bus]
// 3-3-2 bit
.Big => packed struct {
usingnamespace InstructionCommon;
operation: @This().Operation,
mode: @This().Mode,
bus: @This().Bus,
},
.Little => packed struct {
usingnamespace InstructionCommon;
bus: @This().Bus,
mode: @This().Mode,
operation: @This().Operation,
},
};
const InstructionCommon = struct {
pub const Operation = enum(u3) {
load = 0,
@"and" = 1,
@"or" = 2,
xor = 3,
add = 4,
sub = 5,
store = 6,
jump = 7,
};
pub const Bus = enum(u2) {
d = 0,
ram = 1,
ac = 2,
in = 3,
};
pub const Mode = enum(u3) {
d = 0,
x = 1,
yd = 2,
yx = 3,
d_x = 4,
d_y = 5,
d_o = 6,
yxi = 7,
};
pub const JumpMode = enum(u3) {
jmp = 0,
gt = 1,
lt = 2,
ne = 3,
eq = 4,
ge = 5,
le = 6,
bra = 7,
};
pub fn format(
self: anytype,
comptime fmt: []const u8,
options: std.fmt.FormatOptions,
writer: anytype,
) !void {
_ = fmt;
_ = options;
const fmt_str = "{s: <5} {s: <7} {s: <7}";
const op = switch(self.operation) {
.load => "LD",
.@"and" => "AND",
.@"or" => "OR",
.xor => "XOR",
.add => "ADD",
.sub => "SUB",
.store => "ST",
.jump => "JMP",
};
switch(self.operation) {
.load,
.@"and",
.@"or",
.xor,
.add,
.sub => {
const dest = switch(self.mode) {
.d => "AC",
.x => "AC",
.yd => "AC",
.yx => "AC",
.d_x => "X",
.d_y => "Y",
.d_o => "OUT",
.yxi => "OUT",
};
const src = switch(self.bus) {
.d => "D",
.ram => switch(self.mode) {
.d => "[D]",
.x => "[X]",
.yd => "[Y:D]",
.yx => "[Y:X]",
.d_x => "[D],X",
.d_y => "[D],Y",
.d_o => "[D]",
.yxi => "[Y:X++]",
},
.ac => "AC",
.in => "IN",
};
try std.fmt.format(writer, fmt_str, .{op, dest, src});
},
.store => {
const dest = switch(self.mode) {
.d => "[D]",
.x => "[X]",
.yd => "[Y:D]",
.yx => "[Y:X]",
.d_x => "[D],X",
.d_y => "[D],Y",
.d_o => "[D]",
.yxi => "[Y:X++]",
};
const src = switch(self.bus) {
.d => "D",
.ram => "CTRL",
.ac => "AC",
.in => "IN",
};
try std.fmt.format(writer, fmt_str, .{op, dest, src});
},
.jump => {
const jump_mode = @intToEnum(Instruction.JumpMode, @enumToInt(self.mode));
const jmp = switch(jump_mode) {
.jmp => "FAR",
.gt => ">0",
.lt => "<0",
.ne => "!=0",
.eq => "==0",
.ge => ">=0",
.le => "<=0",
.bra => "",
};
const dest = switch(self.bus) {
.d => if(jump_mode == .jmp) "Y:D" else "d",
.ram => if(jump_mode == .jmp) "Y:[D]" else "[0:d]",
.ac => if(jump_mode == .jmp) "Y:AC" else "ac",
.in => if(jump_mode == .jmp) "Y:IN" else "in",
};
try std.fmt.format(writer, fmt_str, .{op, jmp, dest});
},
}
}
};
//Generate a dedicated function for the given 8bit instruction
pub fn instructionFn(comptime instr: Instruction) fn(vm: *VirtualMachine)void {
return struct {
//Get the value from whatever bus is valid in this
// instruction.
pub inline fn getBus(vm: *VirtualMachine) u8 {
//@TODO: Allow for 64kb ram option
const page = vm.reg.y & 0x7F;
return switch(instr.bus) {
.d => vm.reg.d,
.ram => switch(instr.operation) {
.jump => vm.ram[0][vm.reg.d],
//@TODO: some actual randomness. Tehcnically this is accurate because
// 'undefined' means whatever we want it to mean, but come on.
//.store => //undefined,
else => switch(instr.mode) {
.d => vm.ram[0][vm.reg.d],
.x => vm.ram[0][vm.reg.x],
.yd => vm.ram[page][vm.reg.d],
.yx => vm.ram[page][vm.reg.x],
.d_x => vm.ram[0][vm.reg.d],
.d_y => vm.ram[0][vm.reg.d],
.d_o => vm.ram[0][vm.reg.d],
.yxi => v: {
const val = vm.ram[page][vm.reg.x];
vm.reg.x +%= 1;
break :v val;
},
},
},
.ac => vm.reg.ac,
.in => vm.reg.in,
};
}
pub inline fn setPcLow(vm: *VirtualMachine, delay_slot: u16) void {
vm.reg.pc = (delay_slot & 0xFF00) | getBus(vm);
}
pub fn instFn(vm: *VirtualMachine) void {
const delay_slot = vm.reg.pc;
vm.reg.pc +%= 1;
const dest_reg = switch(instr.mode) {
.d, .x, .yd, .yx => "ac",
.d_x => "x",
.d_y => "y",
.d_o, .yxi => "out",
};
switch(instr.operation) {
.load => @field(vm.reg, dest_reg) = getBus(vm),
.@"and" => @field(vm.reg, dest_reg) = vm.reg.ac & getBus(vm),
.@"or" => @field(vm.reg, dest_reg) = vm.reg.ac | getBus(vm),
.xor => @field(vm.reg, dest_reg) = vm.reg.ac ^ getBus(vm),
.add => @field(vm.reg, dest_reg) = vm.reg.ac +% getBus(vm),
.sub => @field(vm.reg, dest_reg) = vm.reg.ac -% getBus(vm),
.store => {
//@TODO: Allow for 64kb ram option
const page = vm.reg.y & 0x7F;
switch(instr.mode) {
.d => vm.ram[0][vm.reg.d] = getBus(vm),
.x => vm.ram[0][vm.reg.x] = getBus(vm),
.yd => vm.ram[page][vm.reg.d] = getBus(vm),
.yx => vm.ram[page][vm.reg.x] = getBus(vm),
.d_x => {
vm.ram[0][vm.reg.d] = getBus(vm);
vm.reg.x = vm.reg.ac;
},
.d_y => {
vm.ram[0][vm.reg.d] = getBus(vm);
vm.reg.y = vm.reg.ac;
},
.d_o => vm.ram[0][vm.reg.d] = getBus(vm),
.yxi => {
vm.ram[page][vm.reg.x] = getBus(vm);
vm.reg.x +%= 1;
},
}
},
.jump => {
const jump_mode = @intToEnum(Instruction.JumpMode, @enumToInt(instr.mode));
const signed_ac = @bitCast(i8, vm.reg.ac);
switch(jump_mode) {
.jmp => vm.reg.pc = (@as(u16, vm.reg.y) << 8) | getBus(vm),
.gt => if(signed_ac > 0) setPcLow(vm, delay_slot),
.lt => if(signed_ac < 0) setPcLow(vm, delay_slot),
.ne => if(vm.reg.ac != 0) setPcLow(vm, delay_slot),
.eq => if(vm.reg.ac == 0) setPcLow(vm, delay_slot),
.ge => if(signed_ac >= 0) setPcLow(vm, delay_slot),
.le => if(signed_ac <= 0) setPcLow(vm, delay_slot),
.bra => setPcLow(vm, delay_slot),
}
},
}
//For the convenience of peripherals we keep track of the
// vsync and hsync pin state.
const hsync = vm.reg.out & 0x40 > 0;
const vsync = vm.reg.out & 0x80 > 0;
switch(vm.hsync) {
.rising, .high => vm.hsync = if(hsync) .high else .falling,
.falling, .low => vm.hsync = if(hsync) .rising else .low,
}
switch(vm.vsync) {
.rising, .high => vm.vsync = if(vsync) .high else .falling,
.falling, .low => vm.vsync = if(vsync) .rising else .low,
}
if(vm.hsync == .rising) vm.reg.xout = vm.reg.ac;
vm.reg.ir = vm.rom[delay_slot][0];
vm.reg.d = vm.rom[delay_slot][1];
}
}.instFn;
}
pub const VirtualMachine = struct {
rom: [65536][2]u8, //ROM 128k, 0 is instruction, 1 is data
ram: [128][256]u8, //RAM is 32k. 128 pages of 256 bytes each. @TODO: Allow for 64k ram option
reg: Registers,
vsync: Signal,
hsync: Signal,
pub const Signal = enum {
rising,
falling,
high,
low,
};
pub const Registers = struct {
ac: u8,
d: u8,
x: u8,
y: u8,
in: u8,
out: u8,
xout: u8,
pc: u16,
ir: u8,
};
//Generate a separate function for every possible instruction
pub const instructions = tab: {
var table: [256]fn(vm: *VirtualMachine)void = undefined;
for(table) |*e, i| e.* = instructionFn(@bitCast(Instruction, @as(u8, i)));
break :tab table;
};
pub fn loadRom(self: *@This(), reader: anytype) !usize {
const rom_as_bytes = std.mem.asBytes(&self.rom);
const used_size = try reader.read(rom_as_bytes);
return used_size;
}
//@TODO: randomize the values in other registers and ram.
// Although, again, 'undefined' means this is correct too.
pub fn start(self: *@This()) void {
self.reg.pc = 0;
self.reg.ir = self.rom[0][0];
self.reg.d = self.rom[0][1];
self.reg.in = 0xFF;
}
pub fn cycle(self: *@This()) void {
instructions[self.reg.ir](self);
}
};
//@TODO: Peripherals:
// Loader
// rest of the BabelFish modes
//////////////////////
//@TODO: This could be cleaner, and it could
// also be more compatible with alternative timings
// and cpu clock rates.
//Consider double buffering here so theoretically
// a thread could pull video at any point during
// instead of waiting for a signal here.
//
// why 28 instead of 33 lines of vsync back porch?
////Explained in ROMv5a.asm.py lines 187-206:
////https://github.com/kervinck/gigatron-rom/blob/2fedec7804e4d0ed809dc780e44f2fa01583cc3d/Core/ROMv5a.asm.py#L187-L206
// # VGA 640x480 defaults (to be adjusted below!)
// vFront = 10 # Vertical front porch
// vPulse = 2 # Vertical sync pulse
// vBack = 33 # Vertical back porch
// vgaLines = vFront + vPulse + vBack + 480
// vgaClock = 25.175e+06
//
// # Video adjustments for Gigatron
// # 1. Our clock is (slightly) slower than 1/4th VGA clock. Not all monitors will
// # accept the decreased frame rate, so we restore the frame rate to above
// # minimum 59.94 Hz by cutting some lines from the vertical front porch.
// vFrontAdjust = vgaLines - int(4 * cpuClock / vgaClock * vgaLines)
// vFront -= vFrontAdjust
// # 2. Extend vertical sync pulse so we can feed the game controller the same
// # signal. This is needed for controllers based on the 4021 instead of 74165
// vPulseExtension = max(0, 8-vPulse)
// vPulse += vPulseExtension
// # 3. Borrow these lines from the back porch so the refresh rate remains
// # unaffected
// vBack -= vPulseExtension
pub const VgaMonitor = struct {
pixels: [vid_width * vid_height]Pixel = undefined,
state: union(enum) {
v_blank: void, //wait for vsync to go high
v_back_porch: u5, //count hsync pulses
v_visible: struct {
y: u9,
state: union(enum) {
h_blank: void, //wait for hsync to go high
h_back_porch: u4, //count cycles
h_visible: u10, //count pixels
h_front_porch: void, //wait for h blank
},
},
v_front_porch: void, //wait for vsync to go low
} = .{.v_blank = void{}},
pub const vid_width = 640;
pub const vid_height = 480;
//in gigatron clocks @TODO: needs overhaul for alternative clock rates
const h_visible = 160;
const h_back_porch = 12;
const h_front_porch = 40;
const h_cycle = h_back_porch + h_visible + h_front_porch;
//in h_cycles
const v_visible = 480;
const v_back_porch = 28; //(normally 33, ROM adjusts)
const v_front_porch = 7; //(normally 10, ROM adjusts)
const v_cycle = v_back_porch + v_visible + v_front_porch; //ignores the vblank
pub const Pixel = switch(native_endian) {
//out byte is VHBBGGRR
.Big => packed struct {
vsync: u1,
hsync: u1,
b: u2,
g: u2,
r: u2,
},
.Little => packed struct {
r: u2,
g: u2,
b: u2,
hsync: u1,
vsync: u1,
},
};
//convert a single color to another type, rescaling
// to that type's range as appropriate
fn rescale(comptime To: type, from: anytype) To {
const From = @TypeOf(from);
if(To == From) return from;
const to_max = std.math.maxInt(To);
const from_max = std.math.maxInt(From);
if(@bitSizeOf(From) == 0) return to_max;
if(@bitSizeOf(To) == 0) return 0;
const Big = std.meta.Int(.unsigned, @bitSizeOf(To) + @bitSizeOf(From));
return @intCast(To, (@as(Big, from) * to_max) / from_max);
}
//Allow the caller to specify whatever (rgb, uncompressed)
// pixel format they want and convert the color value for them
pub fn convert(comptime Out: type, in: anytype) Out {
const out: Out = undefined;
const R = @TypeOf(@field(out, "r"));
const G = @TypeOf(@field(out, "g"));
const B = @TypeOf(@field(out, "b"));
return .{
.r = rescale(R, @field(in, "r")),
.g = rescale(G, @field(in, "g")),
.b = rescale(B, @field(in, "b")),
};
}
pub fn cycle(self: *@This(), vm: *VirtualMachine) bool {
const px = @bitCast(Pixel, vm.reg.out);
switch(self.state) {
.v_blank => {
if(vm.vsync == .rising) self.state = .{.v_back_porch = 0};
},
.v_back_porch => |*h_pulses| {
if(vm.hsync == .rising) {
if(h_pulses.* >= v_back_porch - 1) {
self.state = .{.v_visible = .{
.y = 0,
//not h_blank because we're already rising, which means
// we're already 1 cycle in
.state = .{.h_back_porch = 1},
}};
return false;
}
h_pulses.* += 1;
}
},
.v_visible => |*vis| switch(vis.state) {
.h_blank => if(vm.hsync == .rising) {
vis.y += 1;
if(vis.y >= vid_height) {
self.state = .{.v_front_porch = void{}};
return false;
}
//already rising, so already 1 cycle in
vis.state = .{.h_back_porch = 1};
},
.h_back_porch => |*count| {
if(count.* >= h_back_porch - 1) {
vis.state = .{.h_visible = 0,};
return false;
}
count.* += 1;
},
.h_visible => |*x| {
if(x.* >= vid_width) {
vis.state = .{.h_front_porch = void{}};
return false;
}
const idx: usize = (@as(usize, vis.y) * vid_width) + @as(usize, x.*);
for(self.pixels[idx..idx + 4]) |*p| p.* = px;
x.* += 4;
},
.h_front_porch => {
if(vm.hsync == .falling) vis.state = .{.h_blank = void{}};
}
},
.v_front_porch => if(vm.vsync == .falling) {
self.state = .{.v_blank = void{}};
return true;
},
}
return false;
}
};
//By your command
pub const BlinkenLights = struct {
pub fn sample(vm: *VirtualMachine) [4]bool {
const leds = @truncate(u4, vm.reg.xout & 0x0F);
return .{
leds & 0x1 > 0,
leds & 0x2 > 0,
leds & 0x4 > 0,
leds & 0x8 > 0,
};
}
};
//used by both gamepad and mcplugface
// to track gamepad and emulated gamepad
// input states
pub const Buttons = switch(native_endian) {
.Big => packed struct {
a: u1 = 1,
b: u1 = 1,
select: u1 = 1,
start: u1 = 1,
up: u1 = 1,
down: u1 = 1,
left: u1 = 1,
right: u1 = 1,
},
.Little => packed struct {
right: u1 = 1,
left: u1 = 1,
down: u1 = 1,
up: u1 = 1,
start: u1 = 1,
select: u1 = 1,
b: u1 = 1,
a: u1 = 1,
},
};
//Gamepad uses 4012B shift register
//While the Paralell/Serial control line (latch) is held high
// the clock is ignored and the register is latched to
// the button inputs (which are active-low).
//VSYNC is tied to latch and HSYNC to clock.
// on HSYNC rising edge *only when VSYNC is low*, shift one bit
// from top of register to bottom of IN
pub const Gamepad = struct {
register: u8,
buttons: Buttons,
pub fn cycle(self: *@This(), vm: *VirtualMachine) void {
//clock is disabled when vsync is high
//buttons are latched when it is falling
switch(vm.vsync) {
.falling => self.register = @bitCast(u8, self.buttons),
.low => {
if(vm.hsync == .rising) {
const bit = (self.register & 0x80) >> 7;
vm.reg.in <<= 1;
vm.reg.in |= bit;
self.register <<= 1;
}
},
else => {},
}
}
};
//@TODO: MSBASIC save still not working...
// pretty sure it is broken on Gigatron ROM end
// https://github.com/kervinck/gigatron-rom/issues/205
pub const BabelFish = struct {
frame: anyframe = undefined,
coroutine: @Frame(run) = undefined,
vm: *VirtualMachine = undefined,
tape: Tape = .{},
buttons: Buttons = .{},
key: Key = .{ .none = void{}, },
const Tape = struct {
data: []u8 = std.mem.zeroes([]u8),
pos: usize = 0,
line_empty: bool = true,
};
const Key = union(enum) {
none: void,
//technically u7, but who needs all that casting?
ascii: u8,
ctrl: ControlKey,
};
const ControlKey = enum {
load,
};
pub fn init(self: *@This(), tape: []u8) void {
self.tape.data = tape;
self.coroutine = async run(self);
}
pub fn cycle(self: *@This(), vm: *VirtualMachine) void {
self.vm = vm;
resume self.frame;
}
pub fn run(self: *@This()) void {
suspend {self.frame = @frame();}
var byte: u8 = 0;
var bits: u4 = 0;
while(true) {
//count vsync pulses trying to form a byte
//wait for vsync to be falling so we know we're at the
//start, in case we looped back here in the middle of a pulse
while(self.vm.vsync != .falling) { suspend {} }
var count: u4 = 0;
while(self.vm.vsync != .rising) {
if(self.vm.hsync == .rising) count += 1;
//BabelFish sends ones by default
self.vm.reg.in <<= 1;
self.vm.reg.in |= 1;
suspend {}
}
switch(count) {
7 => {
byte >>= 1;
bits += 1;
},
9 => {
byte >>= 1;
byte |= 0x80;
bits += 1;
},
else => {
byte = 0;
bits = 0;
},
}
if(bits == 8) {
self.recordTapeByte(byte);
bits = 0;
byte = 0;
}
//handle input stuff
//repeat inputs without returning to the rest
// of the loop as long as there is input
// to process
while(@bitCast(u8, self.buttons) != 0xFF) {
self.sendKey(@bitCast(u8, self.buttons), 1);
suspend {}
}
while(self.key != .none) {
switch(self.key) {
.none => unreachable,
.ascii => |k| {
//we do this before so when we come back we don't overwrite a waiting key
self.key = .{ .none = void{}, };
self.sendKey(k, 2);
},
.ctrl => {
self.key = .{ .none = void{}, };
self.replayTape();
}
}
suspend {}
}
}
}
//wait for given number of emulated milliseconds
fn waitMs(self: *@This(), ms: usize) void {
const prev_frame = self.frame;
self.frame = @frame();
defer self.frame = prev_frame;
const clk_per_ms = clock_rate / 1000;
var cycles = ms * clk_per_ms;
while(cycles > 0) : (cycles -= 1) { suspend {} }
}
//send controller data or keyboard key for frames
fn sendKey(self: *@This(), byte: u8, frames: u8) void {
const prev_frame = self.frame;
self.frame = @frame();
defer self.frame = prev_frame;
while(self.vm.vsync != .falling) { suspend {} }
suspend {} //suspend one more cycle so we're in the pulse
var register = byte;
var f = frames;
while(f > 0) : (f -= 1) {
while(self.vm.vsync == .low) {
if(self.vm.hsync == .rising) {
const bit = (register & 0x80) >> 7;
self.vm.reg.in <<= 1;
self.vm.reg.in |= bit;
register <<= 1;
//BabelFish sends ones by default
register |= 1;
}
suspend {}
}
}
}
//replay the text stored in the buffer (usually a basic program)
fn replayTape(self: *@This()) void {
var line_delay: usize = 50;
var line_idx: usize = 0;
for(self.tape.data[0..self.tape.pos]) |byte| {
line_idx += 1;
self.sendKey(byte, 2);
//delay extra at end of displayable line
const delay: usize = if(line_idx % 26 == 0) 300 else 20;
self.waitMs(delay);
//additional line delays because MSBASIC
// in particular is slow
if(byte == '\r') {
line_delay = 300 + (line_idx * 50);
} else if(byte == '\n') {
self.waitMs(line_delay);
line_idx = 0;
}
}
}
//append a byte to the buffer (usually a basic program)
fn recordTapeByte(self: *@This(), byte: u8) void {
//if we're out of space send a long break key,
// unless the line is empty
if(self.tape.pos != self.tape.data.len) {
self.tape.data[self.tape.pos] = byte;
self.tape.pos += 1;
} else if(!self.tape.line_empty) {
self.sendKey(0x03, 10);
}
if(byte >= 32) {
self.tape.line_empty = false;
} else if(byte == '\n') {
//Two blank lines means: clear the tape.
if(self.tape.line_empty) {
self.tape.pos = 0;
}
self.tape.line_empty = true;
}
}
//pub fn loadGt1(self: *@This()) void {
// //60-bytes per frame
// //
//
//}
///////////////
pub fn asciiKeyPress(self: *@This(), key: u8) void {
self.key = .{ .ascii = key };
}
pub fn controlKeyPress(self: *@This(), control_key: ControlKey) void {
self.key = .{ .ctrl = control_key, };
}
};
//Given a sample rate, the Audio peripheral will
// handle the bandpass filtering of the output.
//The shcematic indicates a low pass filter of 700Hz
// and a high pass of 160Hz. However, I am too tone
// deaf to determine from recordings if these values
// produce correct results when compared to youtube
// recordings of real Gigatrons, assuming of course my
// algorithms are even correct.
pub const Audio = struct {
lpf_pv: f32 = 0.0,
hpf_pv: f32 = 0.0,
lpf_a: f32,
hpf_a: f32,
volume: f32 = 1.0,
const lpf_tau_ms = (1.0 / 700.0) * 1000.0;
const hpf_tau_ms = (1.0 / 160.0) * 1000.0;
pub fn init(rate: u32) @This() {
const dt = std.time.ms_per_s / @intToFloat(f32, rate);
return .{
.lpf_a = dt / lpf_tau_ms,
.hpf_a = dt / hpf_tau_ms,
};
}
pub fn sample(self: *@This(), vm: *VirtualMachine) f32 {
const level = (vm.reg.xout & 0xF0) >> 4;
//normalize the 4-bit int to a float [-1.0,1.0]
const level_norm = ((@intToFloat(f32, level) / 15.0) * 2.0) - 1.0;
self.lpf_pv += self.lpf_a * (level_norm - self.lpf_pv);
self.hpf_pv += self.hpf_a * (level_norm - self.hpf_pv);
return (self.hpf_pv - self.lpf_pv) * self.volume;
}
};
|
gigatron.zig
|
const std = @import("std");
const debug = std.debug;
const io = std.io;
const mem = std.mem;
const meta = std.meta;
const testing = std.testing;
pub fn encode(writer: anytype, value: anytype) !void {
const T = @TypeOf(value);
switch (@typeInfo(T)) {
.Int => try writer.writeIntNative(T, value),
.Array => |arr| {
for (value) |item|
try encode(writer, item);
},
.Pointer => |ptr| {
for (value) |item|
try encode(writer, item);
switch (ptr.child) {
u8 => try writer.writeByteNTimes(0, mem.alignForward(value.len, 4) - value.len),
else => {},
}
},
.Struct => |str| {
inline for (meta.fields(T)) |field| {
try encode(writer, @field(value, field.name));
}
},
.AnyFrame,
.Bool,
.BoundFn,
.ComptimeFloat,
.ComptimeInt,
.Enum,
.EnumLiteral,
.ErrorSet,
.ErrorUnion,
.Float,
.Fn,
.Frame,
.NoReturn,
.Null,
.Opaque,
.Optional,
.Type,
.Undefined,
.Union,
.Vector,
.Void,
=> comptime unreachable,
}
}
pub fn decode(reader: anytype, allocator: *mem.Allocator, comptime T: type) !T {
switch (@typeInfo(T)) {
.Int => return try reader.readIntNative(T),
.Array => |arr| {
var res: T = undefined;
for (res) |*item, i| {
errdefer for (res[0..i]) |item2| {
free(item2, allocator);
};
item.* = try decode(reader, allocator, arr.child);
}
return res;
},
.Struct => |str| {
var res: T = undefined;
inline for (meta.fields(T)) |field, i| {
errdefer inline for (meta.fields(T)) |field2, j| {
if (j <= i)
break;
free(@field(res, field2.name), allocator);
};
const Field = field.field_type;
const field_info = @typeInfo(Field);
if (field_info == .Pointer) {
const Child = field_info.Pointer.child;
const len = @field(res, field.name ++ "_len");
const slice = try allocator.alloc(Child, len);
errdefer allocator.free(slice);
for (slice) |*item, j| {
errdefer for (slice[0..j]) |item2| {
free(item2, allocator);
};
item.* = try decode(reader, allocator, Child);
}
switch (field_info.Pointer.child) {
u8 => try reader.skipBytes(mem.alignForward(len, 4) - slice.len, .{}),
else => {},
}
@field(res, field.name) = slice;
} else {
@field(res, field.name) = try decode(reader, allocator, Field);
}
}
return res;
},
.AnyFrame,
.Bool,
.BoundFn,
.ComptimeFloat,
.ComptimeInt,
.Enum,
.EnumLiteral,
.ErrorSet,
.ErrorUnion,
.Float,
.Fn,
.Frame,
.NoReturn,
.Null,
.Opaque,
.Optional,
.Pointer,
.Type,
.Undefined,
.Union,
.Vector,
.Void,
=> comptime unreachable,
}
}
fn testEncode(expect: []const u8, value: anytype) void {
var buf: [mem.page_size]u8 = undefined;
var fbs = io.fixedBufferStream(&buf);
encode(fbs.writer(), value) catch unreachable;
testing.expectEqualSlices(u8, expect, fbs.getWritten());
fbs = io.fixedBufferStream(fbs.getWritten());
const res = decode(fbs.reader(), testing.allocator, @TypeOf(value)) catch unreachable;
defer free(res, testing.allocator);
expectEql(value, res);
}
fn expectEql(a: anytype, b: @TypeOf(a)) void {
switch (@typeInfo(@TypeOf(a))) {
.Int => testing.expectEqual(a, b),
.Array => {
for (a) |_, i|
expectEql(a[i], b[i]);
},
.Pointer => |ptr| switch (ptr.size) {
.Slice => {
for (a) |_, i|
expectEql(a[i], b[i]);
},
else => comptime unreachable,
},
.Struct => |str| {
inline for (str.fields) |field|
expectEql(@field(a, field.name), @field(b, field.name));
},
.AnyFrame,
.Bool,
.BoundFn,
.ComptimeFloat,
.ComptimeInt,
.Enum,
.EnumLiteral,
.ErrorSet,
.ErrorUnion,
.Float,
.Fn,
.Frame,
.NoReturn,
.Null,
.Opaque,
.Optional,
.Type,
.Undefined,
.Union,
.Vector,
.Void,
=> comptime unreachable,
}
}
pub fn free(value: anytype, allocator: *mem.Allocator) void {
const T = @TypeOf(value);
switch (@typeInfo(T)) {
.Int => {},
.Array => |arr| {
for (value) |item|
free(item, allocator);
},
.Pointer => {
for (value) |item|
free(item, allocator);
allocator.free(value);
},
.Struct => |str| {
inline for (meta.fields(T)) |field|
free(@field(value, field.name), allocator);
},
.AnyFrame,
.Bool,
.BoundFn,
.ComptimeFloat,
.ComptimeInt,
.Enum,
.EnumLiteral,
.ErrorSet,
.ErrorUnion,
.Float,
.Fn,
.Frame,
.NoReturn,
.Null,
.Opaque,
.Optional,
.Type,
.Undefined,
.Union,
.Vector,
.Void,
=> @compileError("'{" ++ @typeName(T) ++ "}' not supported"),
}
}
test "encode/decode/free" {
const S1 = struct {
a: u8,
b: u16,
};
testEncode("\x00\x00\x00", S1{ .a = 0, .b = 0 });
testEncode("\x11\x22\x22", S1{ .a = 0x11, .b = 0x2222 });
const S2 = struct {
a_len: u8,
a: []const u8,
};
testEncode("\x00", S2{ .a_len = 0, .a = "" });
testEncode("\x03\x01\x02\x03\x00", S2{ .a_len = 3, .a = &[_]u8{ 1, 2, 3 } });
const S3 = struct {
q: u8,
a_len: u8,
b: u8,
a: []const u16,
};
testEncode("\x00\x00\x00", S3{ .q = 0, .a_len = 0, .b = 0, .a = &[_]u16{} });
testEncode("\x01\x02\x03\x44\x44\x55\x55", S3{
.q = 1,
.a_len = 2,
.b = 3,
.a = &[_]u16{ 0x4444, 0x5555 },
});
const S4 = struct {
q: u8,
a_len: u8,
b: u8,
c_len: u8,
a: []const u16,
h: u8,
c: []const u32,
};
testEncode("\x00\x00\x00\x00\x00", S4{
.q = 0,
.a_len = 0,
.b = 0,
.c_len = 0,
.a = &[_]u16{},
.h = 0,
.c = &[_]u32{},
});
testEncode("\x01\x02\x03\x04\x55\x55\x66\x66\x07\x88\x88\x88\x88" ++
"\x99\x99\x99\x99\xaa\xaa\xaa\xaa\xbb\xbb\xbb\xbb", S4{
.q = 1,
.a_len = 2,
.b = 3,
.c_len = 4,
.a = &[_]u16{ 0x5555, 0x6666 },
.h = 7,
.c = &[_]u32{ 0x88888888, 0x99999999, 0xaaaaaaaa, 0xbbbbbbbb },
});
const S5 = struct {
a_len: u8,
a: []const S2,
};
testEncode("\x00", S5{ .a_len = 0, .a = &[_]S2{} });
testEncode("\x01\x00", S5{ .a_len = 1, .a = &[_]S2{.{ .a_len = 0, .a = "" }} });
testEncode("\x01\x03\x01\x02\x03\x00", S5{ .a_len = 1, .a = &[_]S2{.{ .a_len = 3, .a = "\x01\x02\x03" }} });
testEncode("\x04\x01\x01\x00\x00\x00\x02\x01\x02\x00\x00" ++
"\x03\x01\x02\x03\x00\x04\x01\x02\x03\x04", S5{
.a_len = 4,
.a = &[_]S2{
.{ .a_len = 1, .a = "\x01" },
.{ .a_len = 2, .a = "\x01\x02" },
.{ .a_len = 3, .a = "\x01\x02\x03" },
.{ .a_len = 4, .a = "\x01\x02\x03\x04" },
},
});
}
|
src/reflect.zig
|
const uefi = @import("std").os.uefi;
// const L = @import("std").unicode.utf8ToUtf16LeStringLiteral;
const platform = @import("arch/x86/platform.zig");
const fmt = @import("std").fmt;
const psf2 = @import("fonts/psf2.zig");
const Color = @import("color.zig");
const uefiConsole = @import("uefi/console.zig");
var graphicsOutputProtocol: ?*uefi.protocols.GraphicsOutputProtocol = undefined;
pub const Pixel = packed struct {
blue: u8,
green: u8,
red: u8,
pad: u8 = undefined,
};
pub const Dimensions = packed struct {
height: u32,
width: u32,
};
pub const Position = packed struct {
x: i32,
y: i32,
};
pub const TextColor = packed struct {
fg: u32,
bg: u32,
};
fn pixelFromColor(c: u32) Pixel {
return Pixel{
.blue = Color.B(c),
.green = Color.G(c),
.red = Color.R(c),
};
}
const Framebuffer = struct { width: u32, height: u32, pixelsPerScanLine: u32, basePtr: [*]Pixel, valid: bool };
var fb: Framebuffer = Framebuffer{
.width = 0,
.height = 0,
.pixelsPerScanLine = 0,
.basePtr = undefined,
.valid = false,
};
const ScreenState = struct {
cursor: Position,
textColor: TextColor,
font: [*]const u8,
};
var state = ScreenState{
.cursor = Position{
.x = 0,
.y = 0,
},
.textColor = TextColor{
.fg = 0xffffff,
.bg = 0,
},
.font = psf2.defaultFont,
};
fn setupMode(index: u32) void {
_ = graphicsOutputProtocol.?.setMode(index);
const info = graphicsOutputProtocol.?.mode.info;
fb.width = info.horizontal_resolution;
fb.height = info.vertical_resolution;
fb.pixelsPerScanLine = info.pixels_per_scan_line;
fb.basePtr = @intToPtr([*]Pixel, graphicsOutputProtocol.?.mode.frame_buffer_base);
fb.valid = true;
// Put the cursor at the center.
state.cursor.x = @divTrunc(@bitCast(i32, fb.width), 2);
state.cursor.y = @divTrunc(@bitCast(i32, fb.height), 2);
}
const MOST_APPROPRIATE_W = 960;
const MOST_APPROPRIATE_H = 720;
fn selectBestMode() void {
var bestMode = .{ graphicsOutputProtocol.?.mode.mode, graphicsOutputProtocol.?.mode.info };
var i: u8 = 0;
while (i < graphicsOutputProtocol.?.mode.max_mode) : (i += 1) {
var info: *uefi.protocols.GraphicsOutputModeInformation = undefined;
var info_size: usize = undefined;
_ = graphicsOutputProtocol.?.queryMode(i, &info_size, &info);
if (info.horizontal_resolution > MOST_APPROPRIATE_W and
info.vertical_resolution > MOST_APPROPRIATE_H)
{
continue;
}
if (info.horizontal_resolution == MOST_APPROPRIATE_W and
info.vertical_resolution == MOST_APPROPRIATE_H)
{
bestMode.@"0" = i;
bestMode.@"1" = info;
break;
}
if (info.vertical_resolution > bestMode.@"1".vertical_resolution) {
bestMode.@"0" = i;
bestMode.@"1" = info;
}
}
setupMode(bestMode.@"0");
}
pub fn initialize() void {
const boot_services = uefi.system_table.boot_services.?;
var buf: [100]u8 = undefined;
if (boot_services.locateProtocol(&uefi.protocols.GraphicsOutputProtocol.guid, null, @ptrCast(*?*c_void, &graphicsOutputProtocol)) == uefi.Status.Success) {
uefiConsole.puts("[LOW-LEVEL DEBUG] Graphics output protocol is supported!\r\n");
var i: u8 = 0;
while (i < graphicsOutputProtocol.?.mode.max_mode) : (i += 1) {
var info: *uefi.protocols.GraphicsOutputModeInformation = undefined;
var info_size: usize = undefined;
_ = graphicsOutputProtocol.?.queryMode(i, &info_size, &info);
uefiConsole.printf(buf[0..], " mode {} = {}x{}\r\n", .{
i, info.horizontal_resolution,
info.vertical_resolution,
});
}
uefiConsole.printf(buf[0..], " current mode = {}\r\n", .{graphicsOutputProtocol.?.mode.mode});
// Move to larger mode.
selectBestMode();
// uefiConsole.disable();
const curMode = graphicsOutputProtocol.?.mode.mode;
var info: *uefi.protocols.GraphicsOutputModeInformation = undefined;
var info_size: usize = undefined;
_ = graphicsOutputProtocol.?.queryMode(curMode, &info_size, &info);
uefiConsole.printf(buf[0..], " current mode = {}x{}x{}\r\n", .{ info.horizontal_resolution, info.vertical_resolution, info.pixels_per_scan_line });
clear(Color.Black);
uefiConsole.puts("Screen cleared.\r\n");
} else {
@panic("Graphics output protocol is NOT supported, failing.\n");
}
}
pub fn clear(color: u32) void {
drawRect(0, 0, fb.width, fb.height, color);
// Put the cursor at the center.
state.cursor.x = @divTrunc(@bitCast(i32, fb.width), 2);
state.cursor.y = @divTrunc(@bitCast(i32, fb.height), 2);
}
pub fn setTextColor(fg: ?u32, bg: ?u32) void {
if (fg) |fgColor| {
state.textColor.fg = fgColor;
}
if (bg) |bgColor| {
state.textColor.bg = bgColor;
}
}
pub fn getTextColor() TextColor {
return state.textColor;
}
pub fn getDimensions() Dimensions {
return Dimensions{
.height = fb.height,
.width = fb.width,
};
}
pub fn setPixel(x: u32, y: u32, rgb: u32) void {
if (!fb.valid) @panic("Invalid framebuffer!");
fb.basePtr[(x + y * fb.pixelsPerScanLine)] = pixelFromColor(rgb);
}
pub fn drawRect(x: u32, y: u32, w: u32, h: u32, rgb: u32) void {
if (!fb.valid) @panic("Invalid framebuffer!\n");
const pixelColor = pixelFromColor(rgb);
const lastLine = y + h;
const lastCol = x + w;
var linePtr = fb.basePtr + (fb.pixelsPerScanLine * y);
var iLine = y;
while (iLine < lastLine) : (iLine += 1) {
var iCol: u32 = x;
while (iCol < lastCol) : (iCol += 1) {
linePtr[iCol] = pixelColor;
}
linePtr += fb.pixelsPerScanLine;
}
}
pub fn drawChar(char: u8, fg: u32, bg: u32) void {
if (!fb.valid) @panic("Invalid framebuffer!");
// Draw a character at the current cursor.
var font = psf2.asFont(state.font);
psf2.renderChar(font, @ptrCast([*]u32, @alignCast(32, fb.basePtr)), char, state.cursor.x, state.cursor.y, fg, bg, fb.pixelsPerScanLine);
state.cursor.x += @bitCast(i32, font.width);
if (state.cursor.x >= fb.width - font.width) {
state.cursor.y += @bitCast(i32, font.height);
state.cursor.x = 0;
}
}
pub fn drawText(text: []const u8) void {
// Iterate over all char and draw each char.
for (text) |char| {
drawChar(char, state.textColor.fg, state.textColor.bg);
}
}
pub fn alignLeft(offset: usize) void {
// Move cursor left of offset chars.
state.cursor.x = @bitCast(i32, offset * state.font.width);
}
pub fn moveCursor(vOffset: i32, hOffset: i32) void {
// Move cursor left, right, bottom, top
state.cursor.x += hOffset * @bitCast(i32, state.font.width);
state.cursor.y += vOffset * @bitCast(i32, state.font.height);
}
pub fn setCursorCoords(x: i32, y: i32) void {
state.cursor.x = x;
state.cursor.y = y;
}
pub fn getCursorPos() Position {
return state.cursor;
}
pub fn scroll(px: u32) void {
if (!fb.valid) @panic("Invalid framebuffer!\n");
var lineSize = fb.pixelsPerScanLine;
var prevLinePtr = fb.basePtr;
var linePtr = fb.basePtr + px * lineSize;
var iLine: u32 = px;
while (iLine < fb.height) : (iLine += 1) {
var iCol: u32 = 0;
while (iCol < lineSize) : (iCol += 1) {
prevLinePtr[iCol] = linePtr[iCol];
}
linePtr += lineSize;
prevLinePtr += lineSize;
}
// And fill remaining lines
iLine = fb.height - px;
var pixelColor = pixelFromColor(state.textColor.bg);
while (iLine < fb.height) : (iLine += 1) {
var iCol: u32 = 0;
while (iCol < lineSize) : (iCol += 1) {
prevLinePtr[iCol] = pixelColor;
}
prevLinePtr += lineSize;
}
}
pub fn selfTest() void {
clear(Color.Black);
clear(Color.Green);
drawRect(10, 30, 780, 540, Color.Red);
setPixel(0, 0, Color.Cyan);
setTextColor(Color.Red, Color.Blue);
drawText("Hello there!");
}
|
src/kernel/graphics.zig
|
const std = @import("std");
pub const BOOTBOOT_MAGIC = "BOOT";
/// memory mapped IO virtual address
pub const BOOTBOOT_MMIO: u64 = 0xfffffffff8000000;
/// frame buffer virtual address
pub const BOOTBOOT_FB: u64 = 0xfffffffffc000000;
/// bootboot struct virtual address
pub const BOOTBOOT_INFO: u64 = 0xffffffffffe00000;
/// environment string virtual address
pub const BOOTBOOT_ENV: u64 = 0xffffffffffe01000;
/// core loadable segment start
pub const BOOTBOOT_CORE: u64 = 0xffffffffffe02000;
/// hardcoded kernel name, static kernel memory addresses
pub const PROTOCOL_MINIMAL: u8 = 0;
/// kernel name parsed from environment, static kernel memory addresses
pub const PROTOCOL_STATIC: u8 = 1;
/// kernel name parsed, kernel memory addresses from ELF or PE symbols
pub const PROTOCOL_DYNAMIC: u8 = 2;
/// big-endian flag
pub const PROTOCOL_BIGENDIAN: u8 = 0x80;
// loader types, just informational
pub const LOADER_BIOS: u8 = 0 << 2;
pub const LOADER_UEFI: u8 = 1 << 2;
pub const LOADER_RPI: u8 = 2 << 2;
pub const LOADER_COREBOOT: u8 = 3 << 2;
/// framebuffer pixel format, only 32 bits supported
pub const FramebufferFormat = enum(u8) {
ARGB = 0,
RGBA = 1,
ABGR = 2,
BGRA = 3,
};
pub const MMapType = enum(u4) {
/// don't use. Reserved or unknown regions
MMAP_USED = 0,
/// usable memory
MMAP_FREE = 1,
/// acpi memory, volatile and non-volatile as well
MMAP_ACPI = 2,
/// memory mapped IO region
MMAP_MMIO = 3,
};
/// mmap entry, type is stored in least significant tetrad (half byte) of size
/// this means size described in 16 byte units (not a problem, most modern
/// firmware report memory in pages, 4096 byte units anyway).
pub const MMapEnt = packed struct {
ptr: u64,
size: u64,
pub inline fn getPtr(mmapEnt: MMapEnt) u64 {
return mmapEnt.ptr;
}
pub inline fn getSizeInBytes(mmapEnt: MMapEnt) u64 {
return mmapEnt.size & 0xFFFFFFFFFFFFFFF0;
}
pub inline fn getSizeIn4KiBPages(mmapEnt: MMapEnt) u64 {
return mmapEnt.getSizeInBytes() / 4096;
}
pub inline fn getType(mmapEnt: MMapEnt) MMapType {
return @intToEnum(MMapType, @truncate(u4, mmapEnt.size));
}
pub inline fn isFree(mmapEnt: MMapEnt) bool {
return (mmapEnt.size & 0xF) == 1;
}
test {
std.testing.refAllDecls(@This());
try std.testing.expectEqual(@bitSizeOf(u64) * 2, @bitSizeOf(MMapEnt));
try std.testing.expectEqual(@sizeOf(u64) * 2, @sizeOf(MMapEnt));
}
};
pub const INITRD_MAXSIZE = 16;
pub const x86_64 = extern struct {
acpi_ptr: u64,
smbi_ptr: u64,
efi_ptr: u64,
mp_ptr: u64,
unused0: u64,
unused1: u64,
unused2: u64,
unused3: u64,
test {
std.testing.refAllDecls(@This());
try std.testing.expectEqual(@bitSizeOf(u64) * 8, @bitSizeOf(x86_64));
try std.testing.expectEqual(@sizeOf(u64) * 8, @sizeOf(x86_64));
}
};
pub const Aarch64 = extern struct {
acpi_ptr: u64,
mmio_ptr: u64,
efi_ptr: u64,
unused0: u64,
unused1: u64,
unused2: u64,
unused3: u64,
unused4: u64,
test {
std.testing.refAllDecls(@This());
try std.testing.expectEqual(@bitSizeOf(u64) * 8, @bitSizeOf(Aarch64));
try std.testing.expectEqual(@sizeOf(u64) * 8, @sizeOf(Aarch64));
}
};
pub const Arch = extern union {
x86_64: x86_64,
aarch64: Aarch64,
test {
std.testing.refAllDecls(@This());
try std.testing.expectEqual(@bitSizeOf(u64) * 8, @bitSizeOf(Arch));
try std.testing.expectEqual(@sizeOf(u64) * 8, @sizeOf(Arch));
}
};
const provide_symbols_during_testing = if (@import("builtin").is_test) struct {
export var fb: u32 = 0;
export const environment: u8 = 0;
export const bootboot: Bootboot = undefined;
} else struct {};
const externs = struct {
pub extern var fb: u32;
pub extern const environment: u8;
pub extern const bootboot: Bootboot;
};
pub inline fn getBootboot() Bootboot {
return externs.bootboot;
}
pub inline fn getFramebuffer() [*]volatile u32 {
return @ptrCast([*]volatile u32, &externs.fb);
}
pub inline fn getFramebufferSlice() []volatile u32 {
return getFramebuffer()[0..(externs.bootboot.fb_width * externs.bootboot.fb_height)];
}
pub inline fn getEnvironment() [*:0]const u8 {
return @ptrCast([*:0]const u8, &externs.environment);
}
/// first 64 bytes is platform independent
pub const Bootboot = packed struct {
/// 'BOOT' magic
magic: [4]u8,
/// length of bootboot structure, minimum 128
size: u32,
/// 1, static addresses, see PROTOCOL_* and LOADER_* above
protocol: u8,
/// framebuffer type, see FB_* above
fb_type: FramebufferFormat,
/// number of processor cores
numcores: u16,
/// Bootsrap processor ID (Local APIC Id on x86_64)
bspid: u16,
/// in minutes -1440..1440
timezone: i16,
/// in BCD yyyymmddhhiiss UTC (independent to timezone)
datetime: [8]u8,
/// ramdisk image position
initrd_ptr: u64,
/// ramdisk image size
initrd_size: u64,
/// framebuffer pointer
fb_ptr: u64,
/// framebuffer size
fb_size: u32,
/// framebuffer width
fb_width: u32,
/// framebuffer height
fb_height: u32,
/// framebuffer scanline
fb_scanline: u32,
/// the rest (64 bytes) is platform specific
arch: Arch,
/// from 128th byte, MMapEnt[], more records may follow
mmap: MMapEnt,
test {
std.testing.refAllDecls(@This());
try std.testing.expectEqual(@bitSizeOf(u64) * 18, @bitSizeOf(Bootboot));
try std.testing.expectEqual(@sizeOf(u64) * 18, @sizeOf(Bootboot));
}
};
pub fn getMemoryMap() []const MMapEnt {
if (externs.bootboot.size <= 128) return &[_]MMapEnt{};
return @ptrCast([*]const MMapEnt, &externs.bootboot.mmap)[0..((externs.bootboot.size - 128) / @sizeOf(MMapEnt))];
}
comptime {
std.testing.refAllDecls(@This());
}
|
src/bootboot.zig
|
const cpu = @import("mk20dx256.zig");
const Bank = enum {
A, B, C, D, E
};
const IO = struct {
bank: Bank,
shift: u5,
};
const IoMap = [_]IO{
IO{ .bank = Bank.B, .shift = 16 }, // GPIO 0
IO{ .bank = Bank.B, .shift = 17 }, // GPIO 1
IO{ .bank = Bank.D, .shift = 0 }, // GPIO 2
IO{ .bank = Bank.A, .shift = 12 }, // GPIO 3
IO{ .bank = Bank.A, .shift = 13 }, // GPIO 4
IO{ .bank = Bank.D, .shift = 7 }, // GPIO 5
IO{ .bank = Bank.D, .shift = 4 }, // GPIO 6
IO{ .bank = Bank.D, .shift = 2 }, // GPIO 7
IO{ .bank = Bank.D, .shift = 3 }, // GPIO 8
IO{ .bank = Bank.C, .shift = 3 }, // GPIO 9
IO{ .bank = Bank.C, .shift = 4 }, // GPIO 10
IO{ .bank = Bank.C, .shift = 6 }, // GPIO 11
IO{ .bank = Bank.C, .shift = 7 }, // GPIO 12
IO{ .bank = Bank.C, .shift = 5 }, // GPIO 13
IO{ .bank = Bank.D, .shift = 1 }, // GPIO 14
IO{ .bank = Bank.C, .shift = 0 }, // GPIO 15
IO{ .bank = Bank.B, .shift = 0 }, // GPIO 16
IO{ .bank = Bank.B, .shift = 1 }, // GPIO 17
IO{ .bank = Bank.B, .shift = 3 }, // GPIO 18
IO{ .bank = Bank.B, .shift = 2 }, // GPIO 19
IO{ .bank = Bank.D, .shift = 5 }, // GPIO 20
IO{ .bank = Bank.D, .shift = 6 }, // GPIO 21
IO{ .bank = Bank.C, .shift = 1 }, // GPIO 22
IO{ .bank = Bank.C, .shift = 2 }, // GPIO 23
IO{ .bank = Bank.A, .shift = 5 }, // GPIO 24
IO{ .bank = Bank.B, .shift = 19 }, // GPIO 25
IO{ .bank = Bank.E, .shift = 1 }, // GPIO 26
IO{ .bank = Bank.C, .shift = 9 }, // GPIO 27
IO{ .bank = Bank.C, .shift = 8 }, // GPIO 28
IO{ .bank = Bank.C, .shift = 10 }, // GPIO 29
IO{ .bank = Bank.C, .shift = 11 }, // GPIO 30
IO{ .bank = Bank.E, .shift = 0 }, // GPIO 31
IO{ .bank = Bank.B, .shift = 18 }, // GPIO 32
IO{ .bank = Bank.B, .shift = 4 }, // GPIO 33
};
fn get_gpio(bank: Bank) *volatile cpu.Gpio {
switch (bank) {
Bank.A => return cpu.GpioA,
Bank.B => return cpu.GpioB,
Bank.C => return cpu.GpioC,
Bank.D => return cpu.GpioD,
Bank.E => return cpu.GpioE,
}
}
fn get_port(bank: Bank) *volatile cpu.Port {
switch (bank) {
Bank.A => return cpu.PortA,
Bank.B => return cpu.PortB,
Bank.C => return cpu.PortC,
Bank.D => return cpu.PortD,
Bank.E => return cpu.PortE,
}
}
pub const Output = struct {
output: IO,
gpio: *volatile cpu.Gpio,
const Self = @This();
pub fn new(pin: u5) Self {
var output = IoMap[pin];
const one: u32 = 1;
var gpio = get_gpio(output.bank);
gpio.dataDirection |= (one << output.shift);
get_port(output.bank).controlRegister[output.shift] = cpu.port_pcr_mux(1) | cpu.PORT_PCR_SRE_MASK | cpu.PORT_PCR_DSE_MASK;
return Self{ .output = output, .gpio = gpio };
}
pub fn set_high(self: Self) void {
const one: u32 = 1;
self.gpio.setOutput = (one << self.output.shift);
}
pub fn set_low(self: Self) void {
const one: u32 = 1;
self.gpio.clearOutput = (one << self.output.shift);
}
pub fn toggle(self: Self) void {
const one: u32 = 1;
self.gpio.toggleOutput = (one << self.output.shift);
}
};
pub const Input = struct {
shift: u5,
gpio: *volatile cpu.Gpio,
const Self = @This();
pub fn new(pin: u5) Self {
var input = IoMap[pin];
const one: u32 = 1;
var gpio = get_gpio(input.bank);
gpio.dataDirection &= ~(one << input.shift);
get_port(input.bank).controlRegister[input.shift] = cpu.port_pcr_mux(1);
return Self{ .shift = input.shift, .gpio = gpio };
}
pub fn read(self: Self) bool {
const one: u32 = 1;
return self.gpio.dataInput == (one << self.shift);
}
};
|
src/teensy3_2/gpio.zig
|
const std = @import("std");
const stdx = @import("stdx");
const stbi = @import("stbi");
const Point2 = stdx.math.Point2;
const graphics = @import("../../graphics.zig");
const gpu = graphics.gpu;
const RectBinPacker = graphics.RectBinPacker;
const log = stdx.log.scoped(.font_atlas);
/// Holds a buffer of font glyphs in memory that is then synced to the gpu.
pub const FontAtlas = struct {
g: *gpu.Graphics,
/// Uses a rect bin packer to allocate space.
packer: RectBinPacker,
/// The gl buffer always contains 4 channels. This lets it use the same shader/batch for rendering outline text.
/// Kept in memory since it will be updated for glyphs on demand.
gl_buf: []u8,
width: u32,
height: u32,
channels: u8,
image: gpu.ImageTex,
// The same allocator is used to do resizing.
alloc: std.mem.Allocator,
linear_filter: bool,
dirty: bool,
const Self = @This();
/// Linear filter disabled is good for bitmap fonts that scale upwards.
/// Outline glyphs and color bitmaps would use linear filtering. Although in the future, outline glyphs might also need to have linear filter disabled.
pub fn init(self: *Self, alloc: std.mem.Allocator, g: *gpu.Graphics, width: u32, height: u32, linear_filter: bool) void {
self.* = .{
.g = g,
.alloc = alloc,
.packer = RectBinPacker.init(alloc, width, height),
.width = width,
.height = height,
// Always 4 to match the gpu texture data.
.channels = 4,
.image = undefined,
.gl_buf = undefined,
.linear_filter = linear_filter,
.dirty = false,
};
self.image = g.image_store.createImageFromBitmap(width, height, null, linear_filter);
self.gl_buf = alloc.alloc(u8, width * height * self.channels) catch @panic("error");
std.mem.set(u8, self.gl_buf, 0);
const S = struct {
fn onResize(ptr: ?*anyopaque, width_: u32, height_: u32) void {
const self_ = stdx.mem.ptrCastAlign(*Self, ptr);
self_.resizeLocalBuffer(width_, height_);
}
};
self.packer.addResizeCallback(self, S.onResize);
}
pub fn deinit(self: Self) void {
self.packer.deinit();
self.alloc.free(self.gl_buf);
self.g.image_store.markForRemoval(self.image.image_id);
}
fn resizeLocalBuffer(self: *Self, width: u32, height: u32) void {
const old_buf = self.gl_buf;
defer self.alloc.free(old_buf);
self.gl_buf = self.alloc.alloc(u8, width * height * self.channels) catch @panic("error");
std.mem.set(u8, self.gl_buf, 0);
var old_width = self.width;
var old_height = self.height;
self.width = width;
self.height = height;
// Copy over existing data.
self.copySubImageFrom(0, 0, old_width, old_height, old_buf);
// End the current command so the current uv data still maps to correct texture data and create a new image.
const old_image_id = self.image.image_id;
self.g.image_store.endCmdAndMarkForRemoval(self.image.image_id);
self.image = self.g.image_store.createImageFromBitmap(self.width, self.height, null, self.linear_filter);
// Update tex_id and uvs in existing glyphs.
const tex_width = @intToFloat(f32, self.width);
const tex_height = @intToFloat(f32, self.height);
for (self.g.font_cache.render_fonts.items) |font| {
var iter = font.glyphs.valueIterator();
while (iter.next()) |glyph| {
if (glyph.image.image_id == old_image_id) {
glyph.image = self.image;
glyph.u0 = @intToFloat(f32, glyph.x) / tex_width;
glyph.v0 = @intToFloat(f32, glyph.y) / tex_height;
glyph.u1 = @intToFloat(f32, glyph.x + glyph.width) / tex_width;
glyph.v1 = @intToFloat(f32, glyph.y + glyph.height) / tex_height;
}
}
}
}
/// Copy from 1 channel row major sub image data. markDirtyBuffer needs to be called afterwards to queue a sync op to the gpu.
pub fn copySubImageFrom1Channel(self: *Self, x: usize, y: usize, width: usize, height: usize, src: []const u8) void {
// Ensure src has the correct data length.
std.debug.assert(width * height == src.len);
// Ensure bounds in atlas bitmap.
std.debug.assert(x + width <= self.width);
std.debug.assert(y + height <= self.height);
const dst_row_size = self.width * self.channels;
const src_row_size = width;
var row: usize = 0;
var buf_offset: usize = (x + y * self.width) * self.channels;
var src_offset: usize = 0;
while (row < height) : (row += 1) {
for (src[src_offset .. src_offset + src_row_size]) |it, i| {
const dst_idx = buf_offset + (i * self.channels);
self.gl_buf[dst_idx + 0] = 255;
self.gl_buf[dst_idx + 1] = 255;
self.gl_buf[dst_idx + 2] = 255;
self.gl_buf[dst_idx + 3] = it;
}
buf_offset += dst_row_size;
src_offset += src_row_size;
}
}
/// Copy from 4 channel row major sub image data. markDirtyBuffer needs to be called afterwards to queue a sync op to the gpu.
pub fn copySubImageFrom(self: *Self, bm_x: usize, bm_y: usize, width: usize, height: usize, src: []const u8) void {
// Ensure src has the correct data length.
std.debug.assert(width * height * self.channels == src.len);
// Ensure bounds in atlas bitmap.
std.debug.assert(bm_x + width <= self.width);
std.debug.assert(bm_y + height <= self.height);
const dst_row_size = self.width * self.channels;
const src_row_size = width * self.channels;
var row: usize = 0;
var buf_offset: usize = (bm_x + bm_y * self.width) * self.channels;
var src_offset: usize = 0;
while (row < height) : (row += 1) {
std.mem.copy(u8, self.gl_buf[buf_offset .. buf_offset + src_row_size], src[src_offset .. src_offset + src_row_size]);
buf_offset += dst_row_size;
src_offset += src_row_size;
}
}
pub fn markDirtyBuffer(self: *Self) void {
if (!self.dirty) {
self.dirty = true;
self.g.batcher.addNextPreFlushTask(self, syncFontAtlasToGpu);
}
}
pub fn dumpBufferToDisk(self: Self, filename: [*:0]const u8) void {
_ = stbi.stbi_write_bmp(filename, @intCast(c_int, self.width), @intCast(c_int, self.height), self.channels, &self.gl_buf[0]);
// _ = stbi.stbi_write_png("font_cache.png", @intCast(c_int, self.bm_width), @intCast(c_int, self.bm_height), 1, &self.bm_buf[0], @intCast(c_int, self.bm_width));
}
};
/// Updates gpu texture before current draw call batch is sent to gpu.
fn syncFontAtlasToGpu(ptr: ?*anyopaque) void {
const self = stdx.mem.ptrCastAlign(*FontAtlas, ptr);
self.dirty = false;
// Send bitmap data.
// TODO: send only subimage that changed.
const image = self.g.image_store.images.getNoCheck(self.image.image_id);
self.g.updateTextureData(image, self.gl_buf);
}
|
graphics/src/backend/gpu/font_atlas.zig
|
const std = @import("std");
const math = std.math;
pub const colorspace = @import("color/colorspace.zig");
/// This implements [CIE XYZ](https://en.wikipedia.org/wiki/CIE_1931_color_space)
/// color types. These color spaces represent the simplest expression of the
/// full-spectrum of human visible color. No attempts are made to support
/// perceptual uniformity, or meaningful color blending within these color
/// spaces. They are most useful as an absolute representation of human visible
/// colors, and a centre point for color space conversions.
pub const XYZ = struct {
X: f32,
Y: f32,
Z: f32,
pub fn init(x: f32, y: f32, z: f32) XYZ {
return XYZ{ .X = x, .Y = y, .Z = z };
}
pub fn toxyY(self: XYZ) xyY {
const sum = self.X + self.Y + self.Z;
if (sum != 0) return xyY.init(self.X / sum, self.Y / sum, self.Y);
return xyY.init(std_illuminant.D65.x, std_illuminant.D65.y, 0);
}
pub inline fn equal(self: xyY, other: xyY) bool {
return self.Y == other.Y and self.X == other.X and self.Z == other.Z;
}
pub inline fn approxEqual(self: xyY, other: xyY, epsilon: f32) bool {
return math.approxEqAbs(f32, self.Y, other.Y, epsilon) and
math.approxEqAbs(f32, self.X, other.X, epsilon) and
math.approxEqAbs(f32, self.Z, other.Z, epsilon);
}
};
/// This implements [CIE xyY](https://en.wikipedia.org/wiki/CIE_1931_color_space#CIE_xy_chromaticity_diagram_and_the_CIE_xyY_color_space)
/// color types. These color spaces represent the simplest expression of the
/// full-spectrum of human visible color. No attempts are made to support
/// perceptual uniformity, or meaningful color blending within these color
/// spaces. They are most useful as an absolute representation of human visible
/// colors, and a centre point for color space conversions.
pub const xyY = struct {
x: f32,
y: f32,
Y: f32,
pub fn init(x: f32, y: f32, Y: f32) xyY {
return xyY{ .x = x, .y = y, .Y = Y };
}
pub fn toXYZ(self: xyY) XYZ {
if (self.Y == 0) return XYZ.init(0, 0, 0);
const ratio = self.Y / self.y;
return XYZ.init(ratio * self.x, self.Y, ratio * (1 - self.x - self.y));
}
pub inline fn equal(self: xyY, other: xyY) bool {
return self.Y == other.Y and self.x == other.x and self.y == other.y;
}
pub inline fn approxEqual(self: xyY, other: xyY, epsilon: f32) bool {
return math.approxEqAbs(f32, self.Y, other.Y, epsilon) and
math.approxEqAbs(f32, self.x, other.x, epsilon) and
math.approxEqAbs(f32, self.y, other.y, epsilon);
}
};
/// The illuminant values as defined on https://en.wikipedia.org/wiki/Standard_illuminant.
pub const std_illuminant = struct {
/// Incandescent / Tungsten
pub const A = xyY.init(0.44757, 0.40745, 1.00000);
/// [obsolete] Direct sunlight at noon
pub const B = xyY.init(0.34842, 0.35161, 1.00000);
/// [obsolete] Average / North sky Daylight
pub const C = xyY.init(0.31006, 0.31616, 1.00000);
/// Horizon Light, ICC profile PCS (Profile connection space)
pub const D50 = xyY.init(0.34567, 0.35850, 1.00000);
/// Mid-morning / Mid-afternoon Daylight
pub const D55 = xyY.init(0.33242, 0.34743, 1.00000);
/// ACES Cinema
pub const D60 = xyY.init(0.32168, 0.33767, 1.00000);
/// Noon Daylight: Television, sRGB color space
pub const D65 = xyY.init(0.31271, 0.32902, 1.00000);
/// North sky Daylight
pub const D75 = xyY.init(0.29902, 0.31485, 1.00000);
/// Used by Japanese NTSC
pub const D93 = xyY.init(0.28486, 0.29322, 1.00000);
/// DCI-P3 digital cinema projector
pub const DCI = xyY.init(0.31400, 0.35100, 1.00000);
/// Equal energy
pub const E = xyY.init(1.0 / 3.0, 1.0 / 3.0, 1.00000);
/// Daylight Fluorescent
pub const F1 = xyY.init(0.31310, 0.33727, 1.00000);
/// Cool White Fluorescent
pub const F2 = xyY.init(0.37208, 0.37529, 1.00000);
/// White Fluorescent
pub const F3 = xyY.init(0.40910, 0.39430, 1.00000);
/// Warm White Fluorescent
pub const F4 = xyY.init(0.44018, 0.40329, 1.00000);
/// Daylight Fluorescent
pub const F5 = xyY.init(0.31379, 0.34531, 1.00000);
/// Lite White Fluorescent
pub const F6 = xyY.init(0.37790, 0.38835, 1.00000);
/// D65 simulator, Daylight simulator
pub const F7 = xyY.init(0.31292, 0.32933, 1.00000);
/// D50 simulator, Sylvania F40 Design 50
pub const F8 = xyY.init(0.34588, 0.35875, 1.00000);
/// Cool White Deluxe Fluorescent
pub const F9 = xyY.init(0.37417, 0.37281, 1.00000);
/// Philips TL85, Ultralume 50
pub const F10 = xyY.init(0.34609, 0.35986, 1.00000);
/// Philips TL84, Ultralume 40
pub const F11 = xyY.init(0.38052, 0.37713, 1.00000);
/// Philips TL83, Ultralume 30
pub const F12 = xyY.init(0.43695, 0.40441, 1.00000);
pub const values = [_]xyY{ A, B, C, D50, D55, D60, D65, D75, D93, DCI, E, F1, F2, F3, F4, F5, F6, F7, F8, F9, F10, F11, F12 };
pub const names = [_][]const u8{ "A", "B", "C", "D50", "D55", "D60", "D65", "D75", "D93", "DCI", "E", "F1", "F2", "F3", "F4", "F5", "F6", "F7", "F8", "F9", "F10", "F11", "F12" };
pub fn getByName(name: []const u8) ?xyY {
for (names) |n, index| {
if (n.len != name.len) continue;
if (n[0] != name[0]) continue;
if (n.len > 1 and n[1] != name[1]) continue;
if (n.len > 2 and n[2] != name[2]) continue;
return values[index];
}
return null;
}
pub fn getName(stdIlluminant: xyY) ?[]const u8 {
for (values) |value, i| {
if (value.equal(stdIlluminant)) {
return names[i];
}
}
return null;
}
};
fn getStdIlluminantsCount(comptime decls: anytype) u32 {
comptime {
var count = 0;
while (@TypeOf(@field(std_illuminant, decls[count].name)) == xyY) {
count += 1;
}
return count;
}
}
pub inline fn toIntColor(comptime T: type, value: f32) T {
return math.clamp(@floatToInt(T, @round(value * @intToFloat(f32, math.maxInt(T)))), math.minInt(T), math.maxInt(T));
}
pub inline fn toF32Color(value: anytype) f32 {
return @intToFloat(f32, value) / @intToFloat(f32, math.maxInt(@TypeOf(value)));
}
// *************** RGB Color representations ****************
pub const Colorf32 = 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 fromU32Rgba(value: u32) Self {
return Self{
.r = toF32Color(@truncate(u8, value >> 24)),
.g = toF32Color(@truncate(u8, value >> 16)),
.b = toF32Color(@truncate(u8, value >> 8)),
.a = toF32Color(@truncate(u8, value)),
};
}
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 toRgba32(self: Self) Rgba32 {
return Rgba32{
.r = toIntColor(u8, self.r),
.g = toIntColor(u8, self.g),
.b = toIntColor(u8, self.b),
.a = toIntColor(u8, self.a),
};
}
pub fn toRgba64(self: Self) Rgba64 {
return Rgba64{
.r = toIntColor(u16, self.r),
.g = toIntColor(u16, self.g),
.b = toIntColor(u16, self.b),
.a = toIntColor(u16, self.a),
};
}
};
fn RgbColor(comptime ComponentType: type) type {
return packed struct {
r: ComponentType,
g: ComponentType,
b: ComponentType,
const comp_bits = @typeInfo(ComponentType).Int.bits;
const UintType = std.meta.Int(.unsigned, comp_bits * 3);
const Self = @This();
pub fn initRgb(r: ComponentType, g: ComponentType, b: ComponentType) Self {
return Self{
.r = r,
.g = g,
.b = b,
};
}
pub inline fn getValue(self: Self) UintType {
return @as(UintType, self.r) << (comp_bits * 2) |
@as(UintType, self.g) << comp_bits |
@as(UintType, self.b);
}
pub inline fn fromValue(value: UintType) Self {
return Self{
.r = @truncate(ComponentType, value >> (comp_bits * 2)),
.g = @truncate(ComponentType, value >> comp_bits),
.b = @truncate(ComponentType, value),
};
}
pub fn toColorf32(self: Self) Colorf32 {
return Colorf32{
.r = toF32Color(self.r),
.g = toF32Color(self.g),
.b = toF32Color(self.b),
.a = 1.0,
};
}
pub fn toRgba32(self: Self) Rgba32 {
const max = math.maxInt(ComponentType);
return Rgba32.initRgb(
@truncate(u8, @intCast(u32, self.r) * 255 / max),
@truncate(u8, @intCast(u32, self.g) * 255 / max),
@truncate(u8, @intCast(u32, self.b) * 255 / max),
);
}
};
}
pub const Rgb565 = packed struct {
r: u5,
g: u6,
b: u5,
const Self = @This();
pub fn initRgb(r: u5, g: u6, b: u5) Self {
return Self{
.r = r,
.g = g,
.b = b,
};
}
pub fn toColorf32(self: Self) Colorf32 {
return Colorf32{
.r = toF32Color(self.r),
.g = toF32Color(self.g),
.b = toF32Color(self.b),
.a = 1.0,
};
}
};
fn RgbaColor(comptime ComponentType: type) type {
return packed struct {
r: ComponentType,
g: ComponentType,
b: ComponentType,
a: ComponentType,
const comp_bits = @typeInfo(ComponentType).Int.bits;
const UintType = std.meta.Int(.unsigned, comp_bits * 4);
const Self = @This();
pub fn initRgb(r: ComponentType, g: ComponentType, b: ComponentType) Self {
return Self{
.r = r,
.g = g,
.b = b,
.a = math.maxInt(ComponentType),
};
}
pub fn initRgba(r: ComponentType, g: ComponentType, b: ComponentType, a: ComponentType) Self {
return Self{
.r = r,
.g = g,
.b = b,
.a = a,
};
}
pub inline fn getValue(self: Self) UintType {
return @as(UintType, self.r) << (comp_bits * 3) |
@as(UintType, self.g) << (comp_bits * 2) |
@as(UintType, self.b) << comp_bits |
@as(UintType, self.a);
}
pub inline fn fromValue(value: UintType) Self {
return Self{
.r = @truncate(ComponentType, value >> (comp_bits * 3)),
.g = @truncate(ComponentType, value >> (comp_bits * 2)),
.b = @truncate(ComponentType, value >> comp_bits),
.a = @truncate(ComponentType, value),
};
}
pub fn toColorf32(self: Self) Colorf32 {
return Colorf32{
.r = toF32Color(self.r),
.g = toF32Color(self.g),
.b = toF32Color(self.b),
.a = toF32Color(self.a),
};
}
};
}
// Rgb24
// OpenGL: GL_RGB
// Vulkan: VK_FORMAT_R8G8B8_UNORM
// Direct3D/DXGI: n/a
pub const Rgb24 = RgbColor(u8);
// Rgba32
// OpenGL: GL_RGBA
// Vulkan: VK_FORMAT_R8G8B8A8_UNORM
// Direct3D/DXGI: DXGI_FORMAT_R8G8B8A8_UNORM
pub const Rgba32 = RgbaColor(u8);
// Rgb555
// OpenGL: GL_RGB5
// Vulkan: VK_FORMAT_R5G6B5_UNORM_PACK16
// Direct3D/DXGI: n/a
pub const Rgb555 = RgbColor(u5);
// Rgb48
// OpenGL: GL_RGB16
// Vulkan: VK_FORMAT_R16G16B16_UNORM
// Direct3D/DXGI: n/a
pub const Rgb48 = RgbColor(u16);
// Rgba64
// OpenGL: GL_RGBA16
// Vulkan: VK_FORMAT_R16G16B16A16_UNORM
// Direct3D/DXGI: DXGI_FORMAT_R16G16B16A16_UNORM
pub const Rgba64 = RgbaColor(u16);
fn BgrColor(comptime ComponentType: type) type {
return packed struct {
b: ComponentType,
g: ComponentType,
r: ComponentType,
const comp_bits = @typeInfo(ComponentType).Int.bits;
const UintType = std.meta.Int(.unsigned, comp_bits * 3);
const Self = @This();
pub fn initRgb(r: ComponentType, g: ComponentType, b: ComponentType) Self {
return Self{
.r = r,
.g = g,
.b = b,
};
}
pub inline fn getValue(self: Self) UintType {
return @as(UintType, self.r) << (comp_bits * 2) |
@as(UintType, self.g) << comp_bits |
@as(UintType, self.b);
}
pub inline fn fromValue(value: UintType) Self {
return Self{
.r = @truncate(ComponentType, value >> (comp_bits * 2)),
.g = @truncate(ComponentType, value >> comp_bits),
.b = @truncate(ComponentType, value),
};
}
pub fn toColorf32(self: Self) Colorf32 {
return Colorf32{
.r = toF32Color(self.r),
.g = toF32Color(self.g),
.b = toF32Color(self.b),
.a = 1.0,
};
}
};
}
fn BgraColor(comptime ComponentType: type) type {
return packed struct {
b: ComponentType,
g: ComponentType,
r: ComponentType,
a: ComponentType,
const comp_bits = @typeInfo(ComponentType).Int.bits;
const UintType = std.meta.Int(.unsigned, comp_bits * 4);
const Self = @This();
pub fn initRgb(r: ComponentType, g: ComponentType, b: ComponentType) Self {
return Self{
.r = r,
.g = g,
.b = b,
.a = math.maxInt(ComponentType),
};
}
pub fn initRgba(r: ComponentType, g: ComponentType, b: ComponentType, a: ComponentType) Self {
return Self{
.r = r,
.g = g,
.b = b,
.a = a,
};
}
pub inline fn getValue(self: Self) UintType {
return @as(UintType, self.r) << (comp_bits * 3) |
@as(UintType, self.g) << (comp_bits * 2) |
@as(UintType, self.b) << comp_bits |
@as(UintType, self.a);
}
pub inline fn fromValue(value: UintType) Self {
return Self{
.r = @truncate(ComponentType, value >> (comp_bits * 3)),
.g = @truncate(ComponentType, value >> (comp_bits * 2)),
.b = @truncate(ComponentType, value >> comp_bits),
.a = @truncate(ComponentType, value),
};
}
pub fn toColorf32(self: Self) Colorf32 {
return Colorf32{
.r = toF32Color(self.r),
.g = toF32Color(self.g),
.b = toF32Color(self.b),
.a = toF32Color(self.a),
};
}
};
}
// Bgr24
// OpenGL: GL_BGR
// Vulkan: VK_FORMAT_B8G8R8_UNORM
// Direct3D/DXGI: n/a
pub const Bgr24 = BgrColor(u8);
// Bgra32
// OpenGL: GL_BGRA
// Vulkan: VK_FORMAT_B8G8R8A8_UNORM
// Direct3D/DXGI: DXGI_FORMAT_B8G8R8A8_UNORM
pub const Bgra32 = BgraColor(u8);
fn Grayscale(comptime ComponentType: type) type {
return struct {
value: ComponentType,
const Self = @This();
pub fn toColorf32(self: Self) Colorf32 {
const gray = toF32Color(self.value);
return Colorf32{
.r = gray,
.g = gray,
.b = gray,
.a = 1.0,
};
}
};
}
fn GrayscaleAlpha(comptime ComponentType: type) type {
return struct {
value: ComponentType,
alpha: ComponentType,
const Self = @This();
pub fn toColorf32(self: Self) Colorf32 {
const gray = toF32Color(self.value);
return Colorf32{
.r = gray,
.g = gray,
.b = gray,
.a = toF32Color(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);
// ********************* TESTS *********************
test "convert XYZ to xyY" {
var actual = XYZ.init(0.5, 1, 0.5).toxyY();
var expected = xyY.init(0.25, 0.5, 1);
try std.testing.expect(expected.equal(actual));
actual = XYZ.init(0, 0, 0).toxyY();
expected = xyY.init(std_illuminant.D65.x, std_illuminant.D65.y, 0);
try std.testing.expect(expected.equal(actual));
}
test "Illuminant names" {
const decls = @typeInfo(std_illuminant).Struct.decls;
const count = getStdIlluminantsCount(decls);
try std.testing.expect(std_illuminant.names.len == count);
inline for (std_illuminant.names) |name, i| {
try std.testing.expect(std.mem.eql(u8, name, decls[i].name));
}
}
test "Illuminant values" {
const decls = @typeInfo(std_illuminant).Struct.decls;
const count = getStdIlluminantsCount(decls);
try std.testing.expect(std_illuminant.values.len == count);
inline for (std_illuminant.values) |value, i| {
try std.testing.expect(std.meta.eql(value, @field(std_illuminant, decls[i].name)));
}
}
test "Illuminant getByName" {
for (std_illuminant.names) |name, i| {
const val = std_illuminant.getByName(name).?;
try std.testing.expect(val.equal(std_illuminant.values[i]));
}
try std.testing.expect(std_illuminant.getByName("NA") == null);
}
test "Illuminant getName" {
for (std_illuminant.values) |val, i| {
const name = std_illuminant.getName(val).?;
try std.testing.expect(std.mem.eql(u8, name, std_illuminant.names[i]));
}
try std.testing.expect(std_illuminant.getName(xyY.init(1, 2, 3)) == null);
}
test "Test Colorf32" {
const tst = std.testing;
const rgb = Colorf32.initRgb(0.2, 0.5, 0.7);
try tst.expectEqual(@as(f32, 0.2), rgb.r);
try tst.expectEqual(@as(f32, 0.5), rgb.g);
try tst.expectEqual(@as(f32, 0.7), rgb.b);
var rgba = Colorf32.initRgba(0.1, 0.4, 0.9, 0.7);
try tst.expectEqual(@as(f32, 0.1), rgba.r);
try tst.expectEqual(@as(f32, 0.4), rgba.g);
try tst.expectEqual(@as(f32, 0.9), rgba.b);
try tst.expectEqual(@as(f32, 0.7), rgba.a);
const rgba32 = rgba.toRgba32();
try tst.expectEqual(@as(u32, 26), rgba32.r);
try tst.expectEqual(@as(u32, 102), rgba32.g);
try tst.expectEqual(@as(u32, 230), rgba32.b);
try tst.expectEqual(@as(u32, 179), rgba32.a);
const rgba64 = rgba.toRgba64();
try tst.expectEqual(@as(u64, 6554), rgba64.r);
try tst.expectEqual(@as(u64, 26214), rgba64.g);
try tst.expectEqual(@as(u64, 58982), rgba64.b);
try tst.expectEqual(@as(u64, 45875), rgba64.a);
rgba = rgba.premultipliedAlpha();
try tst.expectEqual(@as(f32, 0.07), rgba.r);
try tst.expectEqual(@as(f32, 0.28), rgba.g);
try tst.expectEqual(@as(f32, 0.63), rgba.b);
try tst.expectEqual(@as(f32, 0.7), rgba.a);
rgba = Colorf32.fromU32Rgba(0x3CD174E2);
try tst.expectEqual(@as(f32, 0.235294117647), rgba.r);
try tst.expectEqual(@as(f32, 0.819607843137), rgba.g);
try tst.expectEqual(@as(f32, 0.454901960784), rgba.b);
try tst.expectEqual(@as(f32, 0.886274509804), rgba.a);
}
const TestRgbData = struct {
init: [3]comptime_int,
expected: [3]comptime_int,
expectedValue: comptime_int,
setValue: comptime_int,
expectedAfterValue: [3]comptime_int,
expectedColor: [4]f32,
};
test "RgbFormats" {
const rgb555TestData = TestRgbData{
.init = .{ 0xC, 0xF, 0x1F },
.expected = .{ 12, 15, 31 },
.expectedValue = 0x31FF,
.setValue = 0x20EE,
.expectedAfterValue = .{ 8, 7, 14 },
.expectedColor = .{ 8 / 31.0, 7 / 31.0, 14 / 31.0, 1.0 },
};
try testRgbType(Rgb555, rgb555TestData);
const rgb24TestData = TestRgbData{
.init = .{ 0x1C, 0x7F, 0xE5 },
.expected = .{ 0x1C, 0x7F, 0xE5 },
.expectedValue = 0x001C7FE5,
.setValue = 0x0090EE2A,
.expectedAfterValue = .{ 144, 238, 42 },
.expectedColor = .{ 144 / 255.0, 238 / 255.0, 42 / 255.0, 1.0 },
};
try testRgbType(Rgb24, rgb24TestData);
const rgb48TestData = TestRgbData{
.init = .{ 0x381C, 0xA37F, 0xE562 },
.expected = .{ 0x381C, 0xA37F, 0xE562 },
.expectedValue = 0x0000381CA37FE562,
.setValue = 0x0000A27D10F56EBC,
.expectedAfterValue = .{ 0xA27D, 0x10F5, 0x6EBC },
.expectedColor = .{ 0xA27D / 65535.0, 0x10F5 / 65535.0, 0x6EBC / 65535.0, 1.0 },
};
try testRgbType(Rgb48, rgb48TestData);
}
fn testRgbType(comptime T: type, comptime testData: TestRgbData) !void {
const tst = std.testing;
var rgb = T.initRgb(testData.init[0], testData.init[1], testData.init[2]);
try testRgb(rgb, @TypeOf(rgb.r), testData.expected);
const value = rgb.getValue();
try tst.expectEqual(@as(@TypeOf(value), testData.expectedValue), value);
rgb = T.fromValue(testData.setValue);
try testRgb(rgb, @TypeOf(rgb.r), testData.expectedAfterValue);
const rgba = rgb.toColorf32();
try testColor(rgba, f32, testData.expectedColor);
}
fn testRgb(rgb: anytype, comptime CT: type, e: [3]comptime_int) !void {
const tst = std.testing;
try tst.expectEqual(@as(CT, e[0]), rgb.r);
try tst.expectEqual(@as(CT, e[1]), rgb.g);
try tst.expectEqual(@as(CT, e[2]), rgb.b);
}
fn testColor(rgba: anytype, comptime CT: type, e: [4]CT) !void {
const tst = std.testing;
try tst.expectEqual(e[0], rgba.r);
try tst.expectEqual(e[1], rgba.g);
try tst.expectEqual(e[2], rgba.b);
try tst.expectEqual(e[3], rgba.a);
}
const TestRgbaData = struct {
init: [4]comptime_int,
expected: [4]comptime_int,
expectedValue: comptime_int,
setValue: comptime_int,
expectedAfterValue: [4]comptime_int,
expectedColor: [4]f32,
};
test "RgbaFormats" {
const rgba32TestData = TestRgbaData{
.init = .{ 0x1C, 0x7F, 0xE5, 0xD7 },
.expected = .{ 0x1C, 0x7F, 0xE5, 0xD7 },
.expectedValue = 0x1C7FE5D7,
.setValue = 0x90EE2ABB,
.expectedAfterValue = .{ 0x90, 0xEE, 0x2A, 0xBB },
.expectedColor = .{ 0x90 / 255.0, 0xEE / 255.0, 0x2A / 255.0, 0xBB / 255.0 },
};
try testRgbaType(Rgba32, rgba32TestData);
const rgba64TestData = TestRgbaData{
.init = .{ 0x381C, 0xA37F, 0xE562, 0xD390 },
.expected = .{ 0x381C, 0xA37F, 0xE562, 0xD390 },
.expectedValue = 0x381CA37FE562D390,
.setValue = 0xA27D10F56EBCE8FA,
.expectedAfterValue = .{ 0xA27D, 0x10F5, 0x6EBC, 0xE8FA },
.expectedColor = .{ 0xA27D / 65535.0, 0x10F5 / 65535.0, 0x6EBC / 65535.0, 0xE8FA / 65535.0 },
};
try testRgbaType(Rgba64, rgba64TestData);
}
test "BgraFormats" {
const bgra32TestData = TestRgbaData{
.init = .{ 0x1C, 0x7F, 0xE5, 0xD7 },
.expected = .{ 0x1C, 0x7F, 0xE5, 0xD7 },
.expectedValue = 0x1C7FE5D7,
.setValue = 0x90EE2ABB,
.expectedAfterValue = .{ 0x90, 0xEE, 0x2A, 0xBB },
.expectedColor = .{ 0x90 / 255.0, 0xEE / 255.0, 0x2A / 255.0, 0xBB / 255.0 },
};
try testRgbaType(Bgra32, bgra32TestData);
}
test "BgrFormats" {
const bgr24TestData = TestRgbData{
.init = .{ 0x1C, 0x7F, 0xE5 },
.expected = .{ 0x1C, 0x7F, 0xE5 },
.expectedValue = 0x001C7FE5,
.setValue = 0x0090EE2A,
.expectedAfterValue = .{ 144, 238, 42 },
.expectedColor = .{ 144 / 255.0, 238 / 255.0, 42 / 255.0, 1.0 },
};
try testRgbType(Bgr24, bgr24TestData);
}
fn testRgbaType(comptime T: type, comptime testData: TestRgbaData) !void {
const tst = std.testing;
var rgb = T.initRgba(testData.init[0], testData.init[1], testData.init[2], testData.init[3]);
try testRgba(rgb, @TypeOf(rgb.r), testData.expected);
const value = rgb.getValue();
try tst.expectEqual(@as(@TypeOf(value), testData.expectedValue), value);
rgb = T.fromValue(testData.setValue);
try testRgba(rgb, @TypeOf(rgb.r), testData.expectedAfterValue);
const rgba = rgb.toColorf32();
try testColor(rgba, f32, testData.expectedColor);
}
fn testRgba(rgb: anytype, comptime CT: type, e: [4]comptime_int) !void {
const tst = std.testing;
try tst.expectEqual(@as(CT, e[0]), rgb.r);
try tst.expectEqual(@as(CT, e[1]), rgb.g);
try tst.expectEqual(@as(CT, e[2]), rgb.b);
try tst.expectEqual(@as(CT, e[3]), rgb.a);
}
|
src/color.zig
|
const std = @import("std");
const input = @import("input.zig");
pub fn run(stdout: anytype) anyerror!void {
{
var input_ = try input.readFile("inputs/day25");
defer input_.deinit();
const result = try part1(137, 139, &input_);
try stdout.print("25a: {}\n", .{ result });
std.debug.assert(result == 305);
}
}
const Spot = enum {
empty,
right,
down,
};
fn part1(comptime num_rows: usize, comptime num_cols: usize, input_: anytype) !usize {
var grid: [num_rows][num_cols]Spot = undefined;
{
var row_i: usize = 0;
while (try input_.next()) |line| {
for (line) |c, col_i| {
grid[row_i][col_i] = switch (c) {
'.' => .empty,
'>' => .right,
'v' => .down,
else => return error.InvalidInput,
};
}
row_i += 1;
}
}
var new_grid = grid;
var step_num: usize = 1;
while (true) {
var one_moved = false;
for (grid) |row, row_i| {
for (row) |spot, col_i| {
const right = (col_i + 1) % num_cols;
if (spot == .right and row[right] == .empty) {
new_grid[row_i][col_i] = .empty;
new_grid[row_i][right] = .right;
one_moved = true;
}
}
}
grid = new_grid;
for (grid) |row, row_i| {
const down = (row_i + 1) % num_rows;
for (row) |spot, col_i| {
if (spot == .down and grid[down][col_i] == .empty) {
new_grid[row_i][col_i] = .empty;
new_grid[down][col_i] = .down;
one_moved = true;
}
}
}
grid = new_grid;
if (!one_moved) {
break;
}
step_num += 1;
}
return step_num;
}
test "day 25 example 1" {
const input_ =
\\v...>>.vv>
\\.vv>>.vv..
\\>>.>v>...v
\\>>v>>.>.v.
\\v>v.vv.v..
\\>.>>..v...
\\.vv..>.>v.
\\v.v..>>v.v
\\....v..v.>
;
try std.testing.expectEqual(@as(usize, 58), try part1(9, 10, &input.readString(input_)));
}
|
src/day25.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;
pub fn main() !void {
var file = try std.fs.cwd().openFile("data/day02.txt", .{});
defer file.close();
var buf_reader = std.io.bufferedReader(file.reader());
var in_stream = buf_reader.reader();
try partOne(&in_stream);
// Seek back to the start if the file since the stream will be
// at the end after partOne runs
try file.seekTo(0);
try partTwo(&in_stream);
}
fn partOne(reader: anytype) !void {
var horizontal_position: i32 = 0;
var depth: i32 = 0;
var value: i32 = undefined;
var buf: [1024]u8 = undefined;
while (try reader.readUntilDelimiterOrEof(&buf, '\n')) |line| {
var index: usize = 0;
while (line[index] != ' ') : (index+=1) {}
value = try parseInt(i32, line[index+1..line.len], 10);
_ = switch (line[0]) {
'f' => horizontal_position += value,
'd' => depth += value,
'u' => depth -= value,
else => unreachable,
};
}
print("{}\n", .{horizontal_position*depth});
}
fn partTwo(reader: anytype) !void {
var horizontal_position: i32 = 0;
var depth: i32 = 0;
var aim: i32 = 0;
var value: i32 = undefined;
var buf: [1024]u8 = undefined;
while (try reader.readUntilDelimiterOrEof(&buf, '\n')) |line| {
var index: usize = 0;
while (line[index] != ' ') : (index+=1) {}
value = try parseInt(i32, line[index+1..line.len], 10);
_ = switch (line[0]) {
'f' => {
horizontal_position += value;
depth += (aim * value);
},
'd' => aim += value,
'u' => aim -= value,
else => unreachable,
};
}
print("{}\n", .{horizontal_position*depth});
}
// 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/day02.zig
|
const std = @import("std");
const c = @cImport({
@cInclude("sqlite3.h");
});
pub const SQLiteExtendedIOError = error{
SQLiteIOErrRead,
SQLiteIOErrShortRead,
SQLiteIOErrWrite,
SQLiteIOErrFsync,
SQLiteIOErrDirFsync,
SQLiteIOErrTruncate,
SQLiteIOErrFstat,
SQLiteIOErrUnlock,
SQLiteIOErrRDLock,
SQLiteIOErrDelete,
SQLiteIOErrBlocked,
SQLiteIOErrNoMem,
SQLiteIOErrAccess,
SQLiteIOErrCheckReservedLock,
SQLiteIOErrLock,
SQLiteIOErrClose,
SQLiteIOErrDirClose,
SQLiteIOErrSHMOpen,
SQLiteIOErrSHMSize,
SQLiteIOErrSHMLock,
SQLiteIOErrSHMMap,
SQLiteIOErrSeek,
SQLiteIOErrDeleteNoEnt,
SQLiteIOErrMmap,
SQLiteIOErrGetTempPath,
SQLiteIOErrConvPath,
SQLiteIOErrVnode,
SQLiteIOErrAuth,
SQLiteIOErrBeginAtomic,
SQLiteIOErrCommitAtomic,
SQLiteIOErrRollbackAtomic,
SQLiteIOErrData,
SQLiteIOErrCorruptFS,
};
pub const SQLiteExtendedCantOpenError = error{
SQLiteCantOpenNoTempDir,
SQLiteCantOpenIsDir,
SQLiteCantOpenFullPath,
SQLiteCantOpenConvPath,
SQLiteCantOpenDirtyWAL,
SQLiteCantOpenSymlink,
};
pub const SQLiteExtendedReadOnlyError = error{
SQLiteReadOnlyRecovery,
SQLiteReadOnlyCantLock,
SQLiteReadOnlyRollback,
SQLiteReadOnlyDBMoved,
SQLiteReadOnlyCantInit,
SQLiteReadOnlyDirectory,
};
pub const SQLiteExtendedConstraintError = error{
SQLiteConstraintCheck,
SQLiteConstraintCommitHook,
SQLiteConstraintForeignKey,
SQLiteConstraintFunction,
SQLiteConstraintNotNull,
SQLiteConstraintPrimaryKey,
SQLiteConstraintTrigger,
SQLiteConstraintUnique,
SQLiteConstraintVTab,
SQLiteConstraintRowID,
SQLiteConstraintPinned,
};
pub const SQLiteExtendedError = error{
SQLiteErrorMissingCollSeq,
SQLiteErrorRetry,
SQLiteErrorSnapshot,
SQLiteLockedSharedCache,
SQLiteLockedVTab,
SQLiteBusyRecovery,
SQLiteBusySnapshot,
SQLiteBusyTimeout,
SQLiteCorruptVTab,
SQLiteCorruptSequence,
SQLiteCorruptIndex,
SQLiteAbortRollback,
};
pub const SQLiteError = error{
SQLiteError,
SQLiteInternal,
SQLitePerm,
SQLiteAbort,
SQLiteBusy,
SQLiteLocked,
SQLiteNoMem,
SQLiteReadOnly,
SQLiteInterrupt,
SQLiteIOErr,
SQLiteCorrupt,
SQLiteNotFound,
SQLiteFull,
SQLiteCantOpen,
SQLiteProtocol,
SQLiteEmpty,
SQLiteSchema,
SQLiteTooBig,
SQLiteConstraint,
SQLiteMismatch,
SQLiteMisuse,
SQLiteNoLFS,
SQLiteAuth,
SQLiteRange,
SQLiteNotADatabase,
SQLiteNotice,
SQLiteWarning,
};
pub const Error = SQLiteError ||
SQLiteExtendedError ||
SQLiteExtendedIOError ||
SQLiteExtendedCantOpenError ||
SQLiteExtendedReadOnlyError ||
SQLiteExtendedConstraintError;
pub fn errorFromResultCode(code: c_int) Error {
// TODO(vincent): can we do something with comptime here ?
// The version number is always static and defined by sqlite.
// These errors are only available since 3.25.0.
if (c.SQLITE_VERSION_NUMBER >= 3025000) {
switch (code) {
c.SQLITE_ERROR_SNAPSHOT => return error.SQLiteErrorSnapshot,
c.SQLITE_LOCKED_VTAB => return error.SQLiteLockedVTab,
c.SQLITE_CANTOPEN_DIRTYWAL => return error.SQLiteCantOpenDirtyWAL,
c.SQLITE_CORRUPT_SEQUENCE => return error.SQLiteCorruptSequence,
else => {},
}
}
// These errors are only available since 3.31.0.
if (c.SQLITE_VERSION_NUMBER >= 3031000) {
switch (code) {
c.SQLITE_CANTOPEN_SYMLINK => return error.SQLiteCantOpenSymlink,
c.SQLITE_CONSTRAINT_PINNED => return error.SQLiteConstraintPinned,
else => {},
}
}
// These errors are only available since 3.32.0.
if (c.SQLITE_VERSION_NUMBER >= 3032000) {
switch (code) {
c.SQLITE_IOERR_DATA => return error.SQLiteIOErrData, // See https://sqlite.org/cksumvfs.html
c.SQLITE_BUSY_TIMEOUT => return error.SQLiteBusyTimeout,
c.SQLITE_CORRUPT_INDEX => return error.SQLiteCorruptIndex,
else => {},
}
}
// These errors are only available since 3.34.0.
if (c.SQLITE_VERSION_NUMBER >= 3034000) {
switch (code) {
c.SQLITE_IOERR_CORRUPTFS => return error.SQLiteIOErrCorruptFS,
else => {},
}
}
return switch (code) {
c.SQLITE_ERROR => error.SQLiteError,
c.SQLITE_INTERNAL => error.SQLiteInternal,
c.SQLITE_PERM => error.SQLitePerm,
c.SQLITE_ABORT => error.SQLiteAbort,
c.SQLITE_BUSY => error.SQLiteBusy,
c.SQLITE_LOCKED => error.SQLiteLocked,
c.SQLITE_NOMEM => error.SQLiteNoMem,
c.SQLITE_READONLY => error.SQLiteReadOnly,
c.SQLITE_INTERRUPT => error.SQLiteInterrupt,
c.SQLITE_IOERR => error.SQLiteIOErr,
c.SQLITE_CORRUPT => error.SQLiteCorrupt,
c.SQLITE_NOTFOUND => error.SQLiteNotFound,
c.SQLITE_FULL => error.SQLiteFull,
c.SQLITE_CANTOPEN => error.SQLiteCantOpen,
c.SQLITE_PROTOCOL => error.SQLiteProtocol,
c.SQLITE_EMPTY => error.SQLiteEmpty,
c.SQLITE_SCHEMA => error.SQLiteSchema,
c.SQLITE_TOOBIG => error.SQLiteTooBig,
c.SQLITE_CONSTRAINT => error.SQLiteConstraint,
c.SQLITE_MISMATCH => error.SQLiteMismatch,
c.SQLITE_MISUSE => error.SQLiteMisuse,
c.SQLITE_NOLFS => error.SQLiteNoLFS,
c.SQLITE_AUTH => error.SQLiteAuth,
c.SQLITE_RANGE => error.SQLiteRange,
c.SQLITE_NOTADB => error.SQLiteNotADatabase,
c.SQLITE_NOTICE => error.SQLiteNotice,
c.SQLITE_WARNING => error.SQLiteWarning,
c.SQLITE_ERROR_MISSING_COLLSEQ => error.SQLiteErrorMissingCollSeq,
c.SQLITE_ERROR_RETRY => error.SQLiteErrorRetry,
c.SQLITE_IOERR_READ => error.SQLiteIOErrRead,
c.SQLITE_IOERR_SHORT_READ => error.SQLiteIOErrShortRead,
c.SQLITE_IOERR_WRITE => error.SQLiteIOErrWrite,
c.SQLITE_IOERR_FSYNC => error.SQLiteIOErrFsync,
c.SQLITE_IOERR_DIR_FSYNC => error.SQLiteIOErrDirFsync,
c.SQLITE_IOERR_TRUNCATE => error.SQLiteIOErrTruncate,
c.SQLITE_IOERR_FSTAT => error.SQLiteIOErrFstat,
c.SQLITE_IOERR_UNLOCK => error.SQLiteIOErrUnlock,
c.SQLITE_IOERR_RDLOCK => error.SQLiteIOErrRDLock,
c.SQLITE_IOERR_DELETE => error.SQLiteIOErrDelete,
c.SQLITE_IOERR_BLOCKED => error.SQLiteIOErrBlocked,
c.SQLITE_IOERR_NOMEM => error.SQLiteIOErrNoMem,
c.SQLITE_IOERR_ACCESS => error.SQLiteIOErrAccess,
c.SQLITE_IOERR_CHECKRESERVEDLOCK => error.SQLiteIOErrCheckReservedLock,
c.SQLITE_IOERR_LOCK => error.SQLiteIOErrLock,
c.SQLITE_IOERR_CLOSE => error.SQLiteIOErrClose,
c.SQLITE_IOERR_DIR_CLOSE => error.SQLiteIOErrDirClose,
c.SQLITE_IOERR_SHMOPEN => error.SQLiteIOErrSHMOpen,
c.SQLITE_IOERR_SHMSIZE => error.SQLiteIOErrSHMSize,
c.SQLITE_IOERR_SHMLOCK => error.SQLiteIOErrSHMLock,
c.SQLITE_IOERR_SHMMAP => error.SQLiteIOErrSHMMap,
c.SQLITE_IOERR_SEEK => error.SQLiteIOErrSeek,
c.SQLITE_IOERR_DELETE_NOENT => error.SQLiteIOErrDeleteNoEnt,
c.SQLITE_IOERR_MMAP => error.SQLiteIOErrMmap,
c.SQLITE_IOERR_GETTEMPPATH => error.SQLiteIOErrGetTempPath,
c.SQLITE_IOERR_CONVPATH => error.SQLiteIOErrConvPath,
c.SQLITE_IOERR_VNODE => error.SQLiteIOErrVnode,
c.SQLITE_IOERR_AUTH => error.SQLiteIOErrAuth,
c.SQLITE_IOERR_BEGIN_ATOMIC => error.SQLiteIOErrBeginAtomic,
c.SQLITE_IOERR_COMMIT_ATOMIC => error.SQLiteIOErrCommitAtomic,
c.SQLITE_IOERR_ROLLBACK_ATOMIC => error.SQLiteIOErrRollbackAtomic,
c.SQLITE_LOCKED_SHAREDCACHE => error.SQLiteLockedSharedCache,
c.SQLITE_BUSY_RECOVERY => error.SQLiteBusyRecovery,
c.SQLITE_BUSY_SNAPSHOT => error.SQLiteBusySnapshot,
c.SQLITE_CANTOPEN_NOTEMPDIR => error.SQLiteCantOpenNoTempDir,
c.SQLITE_CANTOPEN_ISDIR => error.SQLiteCantOpenIsDir,
c.SQLITE_CANTOPEN_FULLPATH => error.SQLiteCantOpenFullPath,
c.SQLITE_CANTOPEN_CONVPATH => error.SQLiteCantOpenConvPath,
c.SQLITE_CORRUPT_VTAB => error.SQLiteCorruptVTab,
c.SQLITE_READONLY_RECOVERY => error.SQLiteReadOnlyRecovery,
c.SQLITE_READONLY_CANTLOCK => error.SQLiteReadOnlyCantLock,
c.SQLITE_READONLY_ROLLBACK => error.SQLiteReadOnlyRollback,
c.SQLITE_READONLY_DBMOVED => error.SQLiteReadOnlyDBMoved,
c.SQLITE_READONLY_CANTINIT => error.SQLiteReadOnlyCantInit,
c.SQLITE_READONLY_DIRECTORY => error.SQLiteReadOnlyDirectory,
c.SQLITE_ABORT_ROLLBACK => error.SQLiteAbortRollback,
c.SQLITE_CONSTRAINT_CHECK => error.SQLiteConstraintCheck,
c.SQLITE_CONSTRAINT_COMMITHOOK => error.SQLiteConstraintCommitHook,
c.SQLITE_CONSTRAINT_FOREIGNKEY => error.SQLiteConstraintForeignKey,
c.SQLITE_CONSTRAINT_FUNCTION => error.SQLiteConstraintFunction,
c.SQLITE_CONSTRAINT_NOTNULL => error.SQLiteConstraintNotNull,
c.SQLITE_CONSTRAINT_PRIMARYKEY => error.SQLiteConstraintPrimaryKey,
c.SQLITE_CONSTRAINT_TRIGGER => error.SQLiteConstraintTrigger,
c.SQLITE_CONSTRAINT_UNIQUE => error.SQLiteConstraintUnique,
c.SQLITE_CONSTRAINT_VTAB => error.SQLiteConstraintVTab,
c.SQLITE_CONSTRAINT_ROWID => error.SQLiteConstraintRowID,
else => std.debug.panic("invalid result code {}", .{code}),
};
}
|
error.zig
|
const std = @import("std");
const input = @embedFile("data/input10");
usingnamespace @import("util.zig");
pub fn main() !void {
var allocator_state = std.heap.ArenaAllocator.init(std.heap.page_allocator);
defer allocator_state.deinit();
const allocator = &allocator_state.allocator;
const values = try parse(allocator, input);
const part1 = findChain(values);
const part2 = countDistinctArrangements(values);
print("[Part1] Chain: {}", .{part1});
print("[Part2] Distinct arrangements: {}", .{part2});
}
fn parse(allocator: *std.mem.Allocator, inputStr: []const u8) ![]u32 {
var values = std.ArrayList(u32).init(allocator);
errdefer values.deinit();
try values.append(0); // outlet
var builtIn: u32 = 0;
var reader = uintLines(u32, inputStr);
while (try reader.next()) |value| {
try values.append(value);
builtIn = std.math.max(builtIn, value);
}
builtIn += 3;
try values.append(builtIn);
std.sort.sort(u32, values.items, {}, comptime std.sort.asc(u32));
return values.toOwnedSlice();
}
fn findChain(values: []u32) u32 {
var countOf1: u32 = 0;
var countOf3: u32 = 0;
for (values[1..]) |v, i| {
const diff = v - values[i];
countOf1 += @boolToInt(diff == 1);
countOf3 += @boolToInt(diff == 3);
}
return countOf1 * countOf3;
}
fn countDistinctArrangements(values: []u32) usize {
var n: [3]usize = [_]usize { 1, 0, 0 };
var ii = @intCast(isize, values.len - 2);
while (ii >= 0) : (ii -= 1) {
var s: usize = 0;
const i = @intCast(usize, ii);
var k = i + 1;
while (k < values.len and (values[k] - values[i]) <= 3) : (k += 1) {
s += n[k - i - 1];
}
n[2] = n[1];
n[1] = n[0];
n[0] = s;
}
return n[0];
}
const expectEqual = std.testing.expectEqual;
test "findChain" {
var values1 = try parse(std.testing.allocator, testInput1);
defer std.testing.allocator.free(values1);
expectEqual(@as(u32, 7 * 5), findChain(values1));
var values2 = try parse(std.testing.allocator, testInput2);
defer std.testing.allocator.free(values2);
expectEqual(@as(u32, 22 * 10), findChain(values2));
}
test "countDistinctArrangements" {
var values1 = try parse(std.testing.allocator, testInput1);
defer std.testing.allocator.free(values1);
expectEqual(@as(usize, 8), countDistinctArrangements(values1));
var values2 = try parse(std.testing.allocator, testInput2);
defer std.testing.allocator.free(values2);
expectEqual(@as(usize, 19208), countDistinctArrangements(values2));
}
const testInput1 =
\\16
\\10
\\15
\\5
\\1
\\11
\\7
\\19
\\6
\\12
\\4
;
const testInput2 =
\\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
;
|
src/day10.zig
|
const std = @import("std");
const assert = std.debug.assert;
const allocator = std.testing.allocator;
pub const FFT = struct {
const base_pattern = [_]i8{ 0, 1, 0, -1 };
signal: []u8,
times: usize,
pub fn init() FFT {
var self = FFT{
.signal = undefined,
.times = 0,
};
return self;
}
fn get_pattern(self: *FFT, r: usize, p: usize) i8 {
_ = self;
// row 0: 0 -> 0, 1 -> 1, ...
// row 1: 0, 1 -> 0, 1, 2 _. 1
// row 2: 0, 1, 2 -> 0, 3, 4, 5 -> 1
const x: usize = ((p + 1) / (r + 1)) % 4;
return base_pattern[x];
}
pub fn parse(self: *FFT, str: []const u8, n: usize) void {
self.signal = allocator.alloc(u8, str.len) catch @panic("FUCK\n");
self.times = n;
var j: usize = 0;
while (j < str.len) : (j += 1) {
self.signal[j] = str[j] - '0';
}
}
pub fn deinit(self: *FFT) void {
allocator.free(self.signal);
}
pub fn run_phase(self: *FFT, buf: [2][]u8, inp: usize, out: usize, last: usize) void {
const size = self.signal.len * self.times;
const first = size - last;
const half = size / 2;
var j: usize = size;
var g: u32 = 0;
while (j > first and j > half) {
j -= 1;
const s = buf[inp][j];
g += s;
const f = @intCast(u8, g % 10);
buf[out][j] = f;
}
while (j > first) {
j -= 1;
var d: i32 = 0;
var k: usize = size;
// std.debug.warn("POS {}: ", j);
while (true) {
k -= 1;
const s = @intCast(i32, buf[inp][k]);
const p = self.get_pattern(j, k);
d += s * p;
// std.debug.warn(" {:2}", p);
if (k == j) break;
if ((size - k) == last) break;
}
const a = @intCast(u32, std.math.absInt(d) catch 0);
const f = @intCast(u8, a % 10);
// std.debug.warn(" = {}\n", f);
buf[out][j] = f;
}
}
pub fn run_phases(self: *FFT, n: usize, output: []u8, last: usize) void {
// std.debug.warn("Signal size: {} * {} = {}, interested in last {} elements\n", self.signal.len, self.times, self.signal.len * self.times, last);
var buf: [2][]u8 = undefined;
buf[0] = allocator.alloc(u8, self.signal.len * self.times) catch @panic("FUCK\n");
defer allocator.free(buf[0]);
buf[1] = allocator.alloc(u8, self.signal.len * self.times) catch @panic("FUCK\n");
defer allocator.free(buf[1]);
var j: usize = 0;
while (j < self.times) : (j += 1) {
std.mem.copy(u8, buf[0][j * self.signal.len ..], self.signal);
}
var p: usize = 0;
var inp: usize = 0;
var out: usize = 1;
while (p < n) : (p += 1) {
// if (p % 10 == 0) std.debug.warn("== PHASE {} ==\n", p);
self.run_phase(buf, inp, out, last);
inp = 1 - inp;
out = 1 - out;
}
std.mem.copy(u8, output[0..], buf[1 - out]);
}
};
test "run short phases" {
var fft = FFT.init();
defer fft.deinit();
const data = "12345678";
fft.parse(data, 1);
var output: []u8 = allocator.alloc(u8, data.len) catch @panic("FUCK\n");
defer allocator.free(output);
fft.run_phases(4, output[0..], data.len - 3);
const wanted = [_]u8{ 0, 1, 0, 2, 9, 4, 9, 8 };
assert(std.mem.eql(u8, wanted[3..], output[3..]));
}
test "run medium phases 1" {
var fft = FFT.init();
defer fft.deinit();
const data = "80871224585914546619083218645595";
fft.parse(data, 1);
var output: []u8 = allocator.alloc(u8, data.len) catch @panic("FUCK\n");
defer allocator.free(output);
fft.run_phases(100, output[0..], data.len);
const wanted = [_]u8{ 2, 4, 1, 7, 6, 1, 7, 6 };
assert(std.mem.eql(u8, &wanted, output[0..wanted.len]));
}
test "run medium phases 2" {
var fft = FFT.init();
defer fft.deinit();
const data = "19617804207202209144916044189917";
fft.parse(data, 1);
var output: []u8 = allocator.alloc(u8, data.len) catch @panic("FUCK\n");
defer allocator.free(output);
fft.run_phases(100, output[0..], data.len);
const wanted = [_]u8{ 7, 3, 7, 4, 5, 4, 1, 8 };
assert(std.mem.eql(u8, &wanted, output[0..wanted.len]));
}
test "run medium phases 3" {
var fft = FFT.init();
defer fft.deinit();
const data = "69317163492948606335995924319873";
fft.parse(data, 1);
var output: []u8 = allocator.alloc(u8, data.len) catch @panic("FUCK\n");
defer allocator.free(output);
fft.run_phases(100, output[0..], data.len);
const wanted = [_]u8{ 5, 2, 4, 3, 2, 1, 3, 3 };
assert(std.mem.eql(u8, &wanted, output[0..wanted.len]));
}
|
2019/p16/fft.zig
|
const std = @import("std");
const testing = std.testing;
pub const StringTable = struct {
allocator: *std.mem.Allocator,
p2s: std.ArrayList([]const u8),
s2p: std.StringHashMap(usize),
pub fn init(allocator: *std.mem.Allocator) StringTable {
var self = StringTable{
.allocator = allocator,
.p2s = std.ArrayList([]const u8).init(allocator),
.s2p = std.StringHashMap(usize).init(allocator),
};
return self;
}
pub fn deinit(self: *StringTable) void {
self.s2p.deinit();
for (self.p2s.items) |item| {
self.allocator.free(item);
}
self.p2s.deinit();
}
pub fn contains(self: *StringTable, str: []const u8) bool {
return self.s2p.contains(str);
}
pub fn add(self: *StringTable, str: []const u8) usize {
if (self.s2p.contains(str)) {
return self.s2p.get(str).?;
}
const pos = self.p2s.items.len;
const copy = self.allocator.dupe(u8, str) catch unreachable;
self.p2s.append(copy) catch unreachable;
_ = self.s2p.put(copy, pos) catch unreachable;
return pos;
}
pub fn get_pos(self: StringTable, str: []const u8) ?usize {
return self.s2p.get(str);
}
pub fn get_str(self: StringTable, pos: usize) ?[]const u8 {
return self.p2s.items[pos];
}
pub fn size(self: StringTable) usize {
return self.p2s.items.len;
}
};
test "basic" {
const allocator = std.testing.allocator;
var strtab = StringTable.init(allocator);
defer strtab.deinit();
const str = "gonzo";
const pos: usize = 0;
_ = strtab.add(str);
try testing.expect(strtab.get_pos(str).? == pos);
try testing.expect(std.mem.eql(u8, strtab.get_str(pos).?, str));
try testing.expect(strtab.size() == 1);
}
test "no overwrites" {
const allocator = std.testing.allocator;
var strtab = StringTable.init(allocator);
defer strtab.deinit();
const prefix = "This is string #";
var c: u8 = 0;
var buf: [100]u8 = undefined;
while (c < 10) : (c += 1) {
var len: usize = 0;
std.mem.copy(u8, buf[len..], prefix);
len += prefix.len;
buf[len] = c + '0';
len += 1;
const str = buf[0..len];
// std.debug.warn("ADD [{}]\n", .{str});
_ = strtab.add(str);
}
const size = strtab.size();
try testing.expect(size == 10);
while (c < 10) : (c += 1) {
var len: usize = 0;
std.mem.copy(u8, buf[len..], prefix);
len += prefix.len;
buf[len] = c + '0';
len += 1;
const str = buf[0..len];
const got = strtab.get_str(c).?;
// std.debug.warn("GOT [{}] EXPECT [{}]\n", .{ got, str });
try testing.expect(std.mem.eql(u8, got, str));
}
}
|
2021/util/strtab.zig
|
// DO NOT MODIFY. This is not actually a source file; it is a textual representation of generated code.
// Use only for debugging purposes.
// Auto-generated constructor
// Access: public
Method <init> : V
(
// (no arguments)
) {
ALOAD 0
// Method descriptor: ()V
INVOKESPECIAL java/lang/Object#<init>
RETURN
}
// Access: public
Method deploy_0 : V
(
arg 1 = Lio/quarkus/runtime/StartupContext;,
arg 2 = [Ljava/lang/Object;
) {
** label1
NEW java/util/Properties
DUP
// Method descriptor: ()V
INVOKESPECIAL java/util/Properties#<init>
ASTORE 3
ALOAD 2
LDC (Integer) 1
ALOAD 3
AASTORE
ALOAD 2
LDC (Integer) 1
AALOAD
ASTORE 4
ALOAD 4
CHECKCAST java/util/Map
LDC (String) "java.runtime.name"
LDC (String) "OpenJDK Runtime Environment"
// Method descriptor: (Ljava/lang/Object;Ljava/lang/Object;)Ljava/lang/Object;
INVOKEINTERFACE java/util/Map#put
POP
ALOAD 4
CHECKCAST java/util/Map
LDC (String) "sun.boot.library.path"
LDC (String) "D:\java-1.8.0-openjdk-1.8.0\jre\bin"
// Method descriptor: (Ljava/lang/Object;Ljava/lang/Object;)Ljava/lang/Object;
INVOKEINTERFACE java/util/Map#put
POP
ALOAD 4
CHECKCAST java/util/Map
LDC (String) "java.vm.version"
LDC (String) "25.212-b04"
// Method descriptor: (Ljava/lang/Object;Ljava/lang/Object;)Ljava/lang/Object;
INVOKEINTERFACE java/util/Map#put
POP
ALOAD 4
CHECKCAST java/util/Map
LDC (String) "java.vm.vendor"
LDC (String) ""
// Method descriptor: (Ljava/lang/Object;Ljava/lang/Object;)Ljava/lang/Object;
INVOKEINTERFACE java/util/Map#put
POP
ALOAD 4
CHECKCAST java/util/Map
LDC (String) "maven.multiModuleProjectDirectory"
LDC (String) "D:\GitHub\recommendations\backend"
// Method descriptor: (Ljava/lang/Object;Ljava/lang/Object;)Ljava/lang/Object;
INVOKEINTERFACE java/util/Map#put
POP
ALOAD 4
CHECKCAST java/util/Map
LDC (String) "java.vendor.url"
LDC (String) "http://java.oracle.com/"
// Method descriptor: (Ljava/lang/Object;Ljava/lang/Object;)Ljava/lang/Object;
INVOKEINTERFACE java/util/Map#put
POP
ALOAD 4
CHECKCAST java/util/Map
LDC (String) "path.separator"
LDC (String) ";"
// Method descriptor: (Ljava/lang/Object;Ljava/lang/Object;)Ljava/lang/Object;
INVOKEINTERFACE java/util/Map#put
POP
ALOAD 4
CHECKCAST java/util/Map
LDC (String) "guice.disable.misplaced.annotation.check"
LDC (String) "true"
// Method descriptor: (Ljava/lang/Object;Ljava/lang/Object;)Ljava/lang/Object;
INVOKEINTERFACE java/util/Map#put
POP
ALOAD 4
CHECKCAST java/util/Map
LDC (String) "java.vm.name"
LDC (String) "OpenJDK 64-Bit Server VM"
// Method descriptor: (Ljava/lang/Object;Ljava/lang/Object;)Ljava/lang/Object;
INVOKEINTERFACE java/util/Map#put
POP
ALOAD 4
CHECKCAST java/util/Map
LDC (String) "file.encoding.pkg"
LDC (String) "sun.io"
// Method descriptor: (Ljava/lang/Object;Ljava/lang/Object;)Ljava/lang/Object;
INVOKEINTERFACE java/util/Map#put
POP
ALOAD 4
CHECKCAST java/util/Map
LDC (String) "user.script"
LDC (String) ""
// Method descriptor: (Ljava/lang/Object;Ljava/lang/Object;)Ljava/lang/Object;
INVOKEINTERFACE java/util/Map#put
POP
ALOAD 4
CHECKCAST java/util/Map
LDC (String) "user.country"
LDC (String) "US"
// Method descriptor: (Ljava/lang/Object;Ljava/lang/Object;)Ljava/lang/Object;
INVOKEINTERFACE java/util/Map#put
POP
ALOAD 4
CHECKCAST java/util/Map
LDC (String) "sun.java.launcher"
LDC (String) "SUN_STANDARD"
// Method descriptor: (Ljava/lang/Object;Ljava/lang/Object;)Ljava/lang/Object;
INVOKEINTERFACE java/util/Map#put
POP
ALOAD 4
CHECKCAST java/util/Map
LDC (String) "sun.os.patch.level"
LDC (String) ""
// Method descriptor: (Ljava/lang/Object;Ljava/lang/Object;)Ljava/lang/Object;
INVOKEINTERFACE java/util/Map#put
POP
ALOAD 4
CHECKCAST java/util/Map
LDC (String) "java.vm.specification.name"
LDC (String) "Java Virtual Machine Specification"
// Method descriptor: (Ljava/lang/Object;Ljava/lang/Object;)Ljava/lang/Object;
INVOKEINTERFACE java/util/Map#put
POP
ALOAD 4
CHECKCAST java/util/Map
LDC (String) "user.dir"
LDC (String) "D:\GitHub\recommendations\backend"
// Method descriptor: (Ljava/lang/Object;Ljava/lang/Object;)Ljava/lang/Object;
INVOKEINTERFACE java/util/Map#put
POP
ALOAD 4
CHECKCAST java/util/Map
LDC (String) "java.runtime.version"
LDC (String) "1.8.0_212-3-redhat-b04"
// Method descriptor: (Ljava/lang/Object;Ljava/lang/Object;)Ljava/lang/Object;
INVOKEINTERFACE java/util/Map#put
POP
ALOAD 4
CHECKCAST java/util/Map
LDC (String) "java.awt.graphicsenv"
LDC (String) "sun.awt.Win32GraphicsEnvironment"
// Method descriptor: (Ljava/lang/Object;Ljava/lang/Object;)Ljava/lang/Object;
INVOKEINTERFACE java/util/Map#put
POP
ALOAD 4
CHECKCAST java/util/Map
LDC (String) "java.endorsed.dirs"
LDC (String) "D:\java-1.8.0-openjdk-1.8.0\jre\lib\endorsed"
// Method descriptor: (Ljava/lang/Object;Ljava/lang/Object;)Ljava/lang/Object;
INVOKEINTERFACE java/util/Map#put
POP
ALOAD 4
CHECKCAST java/util/Map
LDC (String) "os.arch"
LDC (String) "amd64"
// Method descriptor: (Ljava/lang/Object;Ljava/lang/Object;)Ljava/lang/Object;
INVOKEINTERFACE java/util/Map#put
POP
ALOAD 4
CHECKCAST java/util/Map
LDC (String) "java.io.tmpdir"
LDC (String) "C:\Users\lmatt\AppData\Local\Temp\"
// Method descriptor: (Ljava/lang/Object;Ljava/lang/Object;)Ljava/lang/Object;
INVOKEINTERFACE java/util/Map#put
POP
ALOAD 4
CHECKCAST java/util/Map
LDC (String) "line.separator"
LDC (String) "
"
// Method descriptor: (Ljava/lang/Object;Ljava/lang/Object;)Ljava/lang/Object;
INVOKEINTERFACE java/util/Map#put
POP
ALOAD 4
CHECKCAST java/util/Map
LDC (String) "java.vm.specification.vendor"
LDC (String) "Oracle Corporation"
// Method descriptor: (Ljava/lang/Object;Ljava/lang/Object;)Ljava/lang/Object;
INVOKEINTERFACE java/util/Map#put
POP
ALOAD 4
CHECKCAST java/util/Map
LDC (String) "user.variant"
LDC (String) ""
// Method descriptor: (Ljava/lang/Object;Ljava/lang/Object;)Ljava/lang/Object;
INVOKEINTERFACE java/util/Map#put
POP
ALOAD 4
CHECKCAST java/util/Map
LDC (String) "os.name"
LDC (String) "Windows 10"
// Method descriptor: (Ljava/lang/Object;Ljava/lang/Object;)Ljava/lang/Object;
INVOKEINTERFACE java/util/Map#put
POP
ALOAD 4
CHECKCAST java/util/Map
LDC (String) "classworlds.conf"
LDC (String) "D:\apache-maven-3.6.1\bin\..\bin\m2.conf"
// Method descriptor: (Ljava/lang/Object;Ljava/lang/Object;)Ljava/lang/Object;
INVOKEINTERFACE java/util/Map#put
POP
ALOAD 4
CHECKCAST java/util/Map
LDC (String) "sun.jnu.encoding"
LDC (String) "Cp1252"
// Method descriptor: (Ljava/lang/Object;Ljava/lang/Object;)Ljava/lang/Object;
INVOKEINTERFACE java/util/Map#put
POP
ALOAD 4
CHECKCAST java/util/Map
LDC (String) "java.library.path"
LDC (String) "D:\java-1.8.0-openjdk-1.8.0\bin;C:\WINDOWS\Sun\Java\bin;C:\WINDOWS\system32;C:\WINDOWS;C:\Program Files (x86)\Common Files\Oracle\Java\javapath;C:\Windows\system32;C:\Windows;C:\Windows\System32\Wbem;C:\Windows\System32\WindowsPowerShell\v1.0\;C:\Windows\System32\OpenSSH\;C:\Program Files (x86)\NVIDIA Corporation\PhysX\Common;C:\Program Files\NVIDIA Corporation\NVIDIA NvDLISR;D:\Program Files\Microsoft VS Code\bin;D:\Program Files\nodejs\;C:\Program Files\Git\cmd;%JAVA_HOME%\bin;;C:\WINDOWS\system32;C:\WINDOWS;C:\WINDOWS\System32\Wbem;C:\WINDOWS\System32\WindowsPowerShell\v1.0\;C:\WINDOWS\System32\OpenSSH\;C:\Users\lmatt\.cargo\bin;D:\Python\Python37\Scripts\;D:\Python\Python37\;C:\Users\lmatt\AppData\Local\Microsoft\WindowsApps;C:\Users\lmatt\AppData\Roaming\npm;D:\apache-maven-3.6.1\bin;d:\vert.x\bin;;."
// Method descriptor: (Ljava/lang/Object;Ljava/lang/Object;)Ljava/lang/Object;
INVOKEINTERFACE java/util/Map#put
POP
ALOAD 4
CHECKCAST java/util/Map
LDC (String) "maven.conf"
LDC (String) "D:\apache-maven-3.6.1\bin\../conf"
// Method descriptor: (Ljava/lang/Object;Ljava/lang/Object;)Ljava/lang/Object;
INVOKEINTERFACE java/util/Map#put
POP
ALOAD 4
CHECKCAST java/util/Map
LDC (String) "java.specification.name"
LDC (String) "Java Platform API Specification"
// Method descriptor: (Ljava/lang/Object;Ljava/lang/Object;)Ljava/lang/Object;
INVOKEINTERFACE java/util/Map#put
POP
ALOAD 4
CHECKCAST java/util/Map
LDC (String) "java.class.version"
LDC (String) "52.0"
// Method descriptor: (Ljava/lang/Object;Ljava/lang/Object;)Ljava/lang/Object;
INVOKEINTERFACE java/util/Map#put
POP
ALOAD 4
CHECKCAST java/util/Map
LDC (String) "sun.management.compiler"
LDC (String) "HotSpot 64-Bit Tiered Compilers"
// Method descriptor: (Ljava/lang/Object;Ljava/lang/Object;)Ljava/lang/Object;
INVOKEINTERFACE java/util/Map#put
POP
ALOAD 4
CHECKCAST java/util/Map
LDC (String) "os.version"
LDC (String) "10.0"
// Method descriptor: (Ljava/lang/Object;Ljava/lang/Object;)Ljava/lang/Object;
INVOKEINTERFACE java/util/Map#put
POP
ALOAD 4
CHECKCAST java/util/Map
LDC (String) "library.jansi.path"
LDC (String) "D:\apache-maven-3.6.1\bin\..\lib\jansi-native"
// Method descriptor: (Ljava/lang/Object;Ljava/lang/Object;)Ljava/lang/Object;
INVOKEINTERFACE java/util/Map#put
POP
ALOAD 4
CHECKCAST java/util/Map
LDC (String) "user.home"
LDC (String) "C:\Users\lmatt"
// Method descriptor: (Ljava/lang/Object;Ljava/lang/Object;)Ljava/lang/Object;
INVOKEINTERFACE java/util/Map#put
POP
ALOAD 4
CHECKCAST java/util/Map
LDC (String) "user.timezone"
LDC (String) "America/New_York"
// Method descriptor: (Ljava/lang/Object;Ljava/lang/Object;)Ljava/lang/Object;
INVOKEINTERFACE java/util/Map#put
POP
ALOAD 4
CHECKCAST java/util/Map
LDC (String) "java.awt.printerjob"
LDC (String) "sun.awt.windows.WPrinterJob"
// Method descriptor: (Ljava/lang/Object;Ljava/lang/Object;)Ljava/lang/Object;
INVOKEINTERFACE java/util/Map#put
POP
ALOAD 4
CHECKCAST java/util/Map
LDC (String) "file.encoding"
LDC (String) "Cp1252"
// Method descriptor: (Ljava/lang/Object;Ljava/lang/Object;)Ljava/lang/Object;
INVOKEINTERFACE java/util/Map#put
POP
ALOAD 4
CHECKCAST java/util/Map
LDC (String) "java.specification.version"
LDC (String) "1.8"
// Method descriptor: (Ljava/lang/Object;Ljava/lang/Object;)Ljava/lang/Object;
INVOKEINTERFACE java/util/Map#put
POP
ALOAD 4
CHECKCAST java/util/Map
LDC (String) "java.class.path"
LDC (String) "D:\apache-maven-3.6.1\bin\..\boot\plexus-classworlds-2.6.0.jar"
// Method descriptor: (Ljava/lang/Object;Ljava/lang/Object;)Ljava/lang/Object;
INVOKEINTERFACE java/util/Map#put
POP
ALOAD 4
CHECKCAST java/util/Map
LDC (String) "user.name"
LDC (String) "lmatt"
// Method descriptor: (Ljava/lang/Object;Ljava/lang/Object;)Ljava/lang/Object;
INVOKEINTERFACE java/util/Map#put
POP
ALOAD 4
CHECKCAST java/util/Map
LDC (String) "java.vm.specification.version"
LDC (String) "1.8"
// Method descriptor: (Ljava/lang/Object;Ljava/lang/Object;)Ljava/lang/Object;
INVOKEINTERFACE java/util/Map#put
POP
ALOAD 4
CHECKCAST java/util/Map
LDC (String) "sun.java.command"
LDC (String) "org.codehaus.plexus.classworlds.launcher.Launcher clean package"
// Method descriptor: (Ljava/lang/Object;Ljava/lang/Object;)Ljava/lang/Object;
INVOKEINTERFACE java/util/Map#put
POP
ALOAD 4
CHECKCAST java/util/Map
LDC (String) "java.home"
LDC (String) "D:\java-1.8.0-openjdk-1.8.0\jre"
// Method descriptor: (Ljava/lang/Object;Ljava/lang/Object;)Ljava/lang/Object;
INVOKEINTERFACE java/util/Map#put
POP
ALOAD 4
CHECKCAST java/util/Map
LDC (String) "sun.arch.data.model"
LDC (String) "64"
// Method descriptor: (Ljava/lang/Object;Ljava/lang/Object;)Ljava/lang/Object;
INVOKEINTERFACE java/util/Map#put
POP
ALOAD 4
CHECKCAST java/util/Map
LDC (String) "user.language"
LDC (String) "en"
// Method descriptor: (Ljava/lang/Object;Ljava/lang/Object;)Ljava/lang/Object;
INVOKEINTERFACE java/util/Map#put
POP
ALOAD 4
CHECKCAST java/util/Map
LDC (String) "java.specification.vendor"
LDC (String) "Oracle Corporation"
// Method descriptor: (Ljava/lang/Object;Ljava/lang/Object;)Ljava/lang/Object;
INVOKEINTERFACE java/util/Map#put
POP
ALOAD 4
CHECKCAST java/util/Map
LDC (String) "awt.toolkit"
LDC (String) "sun.awt.windows.WToolkit"
// Method descriptor: (Ljava/lang/Object;Ljava/lang/Object;)Ljava/lang/Object;
INVOKEINTERFACE java/util/Map#put
POP
ALOAD 4
CHECKCAST java/util/Map
LDC (String) "java.vm.info"
LDC (String) "mixed mode"
// Method descriptor: (Ljava/lang/Object;Ljava/lang/Object;)Ljava/lang/Object;
INVOKEINTERFACE java/util/Map#put
POP
ALOAD 4
CHECKCAST java/util/Map
LDC (String) "java.version"
LDC (String) "1.8.0_212-3-redhat"
// Method descriptor: (Ljava/lang/Object;Ljava/lang/Object;)Ljava/lang/Object;
INVOKEINTERFACE java/util/Map#put
POP
ALOAD 4
CHECKCAST java/util/Map
LDC (String) "java.ext.dirs"
LDC (String) "D:\java-1.8.0-openjdk-1.8.0\jre\lib\ext;C:\WINDOWS\Sun\Java\lib\ext"
// Method descriptor: (Ljava/lang/Object;Ljava/lang/Object;)Ljava/lang/Object;
INVOKEINTERFACE java/util/Map#put
POP
ALOAD 4
CHECKCAST java/util/Map
LDC (String) "sun.boot.class.path"
LDC (String) "D:\java-1.8.0-openjdk-1.8.0\jre\lib\resources.jar;D:\java-1.8.0-openjdk-1.8.0\jre\lib\rt.jar;D:\java-1.8.0-openjdk-1.8.0\jre\lib\sunrsasign.jar;D:\java-1.8.0-openjdk-1.8.0\jre\lib\jsse.jar;D:\java-1.8.0-openjdk-1.8.0\jre\lib\jce.jar;D:\java-1.8.0-openjdk-1.8.0\jre\lib\charsets.jar;D:\java-1.8.0-openjdk-1.8.0\jre\lib\jfr.jar;D:\java-1.8.0-openjdk-1.8.0\jre\classes"
// Method descriptor: (Ljava/lang/Object;Ljava/lang/Object;)Ljava/lang/Object;
INVOKEINTERFACE java/util/Map#put
POP
ALOAD 4
CHECKCAST java/util/Map
LDC (String) "java.vendor"
LDC (String) "Oracle Corporation"
// Method descriptor: (Ljava/lang/Object;Ljava/lang/Object;)Ljava/lang/Object;
INVOKEINTERFACE java/util/Map#put
POP
ALOAD 4
CHECKCAST java/util/Map
LDC (String) "sun.stderr.encoding"
LDC (String) "cp437"
// Method descriptor: (Ljava/lang/Object;Ljava/lang/Object;)Ljava/lang/Object;
INVOKEINTERFACE java/util/Map#put
POP
ALOAD 4
CHECKCAST java/util/Map
LDC (String) "maven.home"
LDC (String) "D:\apache-maven-3.6.1\bin\.."
// Method descriptor: (Ljava/lang/Object;Ljava/lang/Object;)Ljava/lang/Object;
INVOKEINTERFACE java/util/Map#put
POP
ALOAD 4
CHECKCAST java/util/Map
LDC (String) "file.separator"
LDC (String) "\"
// Method descriptor: (Ljava/lang/Object;Ljava/lang/Object;)Ljava/lang/Object;
INVOKEINTERFACE java/util/Map#put
POP
ALOAD 4
CHECKCAST java/util/Map
LDC (String) "java.vendor.url.bug"
LDC (String) "http://bugreport.sun.com/bugreport/"
// Method descriptor: (Ljava/lang/Object;Ljava/lang/Object;)Ljava/lang/Object;
INVOKEINTERFACE java/util/Map#put
POP
ALOAD 4
CHECKCAST java/util/Map
LDC (String) "sun.io.unicode.encoding"
LDC (String) "UnicodeLittle"
// Method descriptor: (Ljava/lang/Object;Ljava/lang/Object;)Ljava/lang/Object;
INVOKEINTERFACE java/util/Map#put
POP
ALOAD 4
CHECKCAST java/util/Map
LDC (String) "sun.cpu.endian"
LDC (String) "little"
// Method descriptor: (Ljava/lang/Object;Ljava/lang/Object;)Ljava/lang/Object;
INVOKEINTERFACE java/util/Map#put
POP
ALOAD 4
CHECKCAST java/util/Map
LDC (String) "sun.stdout.encoding"
LDC (String) "cp437"
// Method descriptor: (Ljava/lang/Object;Ljava/lang/Object;)Ljava/lang/Object;
INVOKEINTERFACE java/util/Map#put
POP
ALOAD 4
CHECKCAST java/util/Map
LDC (String) "sun.desktop"
LDC (String) "windows"
// Method descriptor: (Ljava/lang/Object;Ljava/lang/Object;)Ljava/lang/Object;
INVOKEINTERFACE java/util/Map#put
POP
ALOAD 4
CHECKCAST java/util/Map
LDC (String) "sun.cpu.isalist"
LDC (String) "amd64"
// Method descriptor: (Ljava/lang/Object;Ljava/lang/Object;)Ljava/lang/Object;
INVOKEINTERFACE java/util/Map#put
POP
ALOAD 2
LDC (Integer) 2
ALOAD 4
AASTORE
NEW io/quarkus/narayana/jta/runtime/NarayanaJtaRecorder
DUP
// Method descriptor: ()V
INVOKESPECIAL io/quarkus/narayana/jta/runtime/NarayanaJtaRecorder#<init>
ASTORE 5
ALOAD 2
LDC (Integer) 0
ALOAD 5
AASTORE
ALOAD 2
LDC (Integer) 2
AALOAD
ASTORE 6
ALOAD 2
LDC (Integer) 0
AALOAD
ASTORE 9
ALOAD 9
CHECKCAST io/quarkus/narayana/jta/runtime/NarayanaJtaRecorder
ALOAD 6
CHECKCAST java/util/Properties
// Method descriptor: (Ljava/util/Properties;)V
INVOKEVIRTUAL io/quarkus/narayana/jta/runtime/NarayanaJtaRecorder#setDefaultProperties
// Field descriptor: Lio/quarkus/runtime/generated/RunTimeConfigRoot;
GETSTATIC io/quarkus/runtime/generated/RunTimeConfig#runConfig
// Field descriptor: Ljava/lang/Object;
GETFIELD io/quarkus/runtime/generated/RunTimeConfigRoot#transactionManager
ASTORE 7
ALOAD 2
LDC (Integer) 3
ALOAD 7
AASTORE
ALOAD 2
LDC (Integer) 3
AALOAD
ASTORE 8
ALOAD 9
CHECKCAST io/quarkus/narayana/jta/runtime/NarayanaJtaRecorder
ALOAD 8
CHECKCAST io/quarkus/narayana/jta/runtime/TransactionManagerConfiguration
// Method descriptor: (Lio/quarkus/narayana/jta/runtime/TransactionManagerConfiguration;)V
INVOKEVIRTUAL io/quarkus/narayana/jta/runtime/NarayanaJtaRecorder#setNodeName
ALOAD 9
CHECKCAST io/quarkus/narayana/jta/runtime/NarayanaJtaRecorder
ALOAD 8
CHECKCAST io/quarkus/narayana/jta/runtime/TransactionManagerConfiguration
// Method descriptor: (Lio/quarkus/narayana/jta/runtime/TransactionManagerConfiguration;)V
INVOKEVIRTUAL io/quarkus/narayana/jta/runtime/NarayanaJtaRecorder#setDefaultTimeout
RETURN
** label2
}
// Access: public
Method deploy : V
(
arg 1 = Lio/quarkus/runtime/StartupContext;
) {
** label1
LDC (Integer) 4
ANEWARRAY java/lang/Object
ASTORE 2
ALOAD 0
ALOAD 1
ALOAD 2
// Method descriptor: (Lio/quarkus/runtime/StartupContext;[Ljava/lang/Object;)V
INVOKEVIRTUAL io/quarkus/deployment/steps/NarayanaJtaProcessor$build2#deploy_0
RETURN
** label2
}
|
target/generated-sources/gizmo/io/quarkus/deployment/steps/NarayanaJtaProcessor$build2.zig
|
const std = @import("std");
const c = @import("c.zig");
const glsl = @cImport({
@cInclude("sokol/sokol_gfx.h");
@cInclude("shaders/cube.glsl.h");
});
pub const ViewportState = struct {
pipeline: c.sg_pipeline = std.mem.zeroes(c.sg_pipeline),
bindings: c.sg_bindings = std.mem.zeroes(c.sg_bindings),
shader: c.sg_shader = std.mem.zeroes(c.sg_shader),
pass : c.sg_pass = std.mem.zeroes(c.sg_pass),
pass_action : c.sg_pass_action = std.mem.zeroes(c.sg_pass_action),
color_img : c.sg_image = std.mem.zeroes(c.sg_image),
depth_img : c.sg_image = std.mem.zeroes(c.sg_image),
min : c.ImVec2 = c.ImVec2 { .x = 0, .y = 0 },
max : c.ImVec2 = c.ImVec2 { .x = 0, .y = 0 },
size : c.ImVec2 = c.ImVec2 { .x = 0, .y = 0 },
camera_rot : c.vec3 = undefined,
mesh_idx : u8 = 0,
prev_mesh_idx : u8 = 0,
};
fn to_radians(degrees : f32) f32 {
return degrees * std.math.pi / 180.0;
}
pub fn compute_mvp(rotate : c.vec3, aspect : f32, eye_dist : f32) c.mat4 {
var proj : c.mat4 = undefined;
c.glm_perspective(45.0, aspect, 0.01, 10.0, &proj);
var view : c.mat4 = undefined;
var eye : c.vec3 = c.vec3 {2.0, 3.5, eye_dist};
var centre : c.vec3 = c.vec3 {0, 0, 0};
var up : c.vec3 = c.vec3 {0, 1, 0};
c.glm_lookat(&eye,
¢re,
&up,
&view);
var view_proj : c.mat4 = undefined;
c.glm_mat4_mul(&proj, &view, &view_proj);
var rxm : c.mat4 = undefined;
var rym : c.mat4 = undefined;
var rzm : c.mat4 = undefined;
c.glm_mat4_identity(&rxm);
c.glm_mat4_identity(&rym);
c.glm_mat4_identity(&rzm);
var r_vec = c.vec3 {1, 0, 0};
c.glm_rotate(&rxm, to_radians(rotate[0]), &r_vec);
r_vec = c.vec3 {0, 1, 0};
c.glm_rotate(&rym, to_radians(rotate[1]), &r_vec);
r_vec = c.vec3 {0, 0, 1};
c.glm_rotate(&rzm, to_radians(rotate[2]), &r_vec);
var temp1 : c.mat4 = undefined;
c.glm_mat4_mul(&rym, &rxm, &temp1);
var temp2 : c.mat4 = undefined;
c.glm_mat4_mul(&rzm, &temp1, &temp2);
var mvp : c.mat4 = undefined;
c.glm_mat4_mul(&view_proj, &temp2, &mvp);
return mvp;
}
fn init_viewport(viewport : *ViewportState, x : i32, y : i32) void {
c.sg_destroy_pass(viewport.pass);
c.sg_destroy_image(viewport.depth_img);
c.sg_destroy_image(viewport.color_img);
c.sg_destroy_buffer(viewport.bindings.vertex_buffers[0]);
c.sg_destroy_buffer(viewport.bindings.index_buffer);
c.sg_destroy_shader(viewport.shader);
c.sg_destroy_pipeline(viewport.pipeline);
// Init pass.
var img_desc : c.sg_image_desc = std.mem.zeroes(c.sg_image_desc);
img_desc.render_target = true;
img_desc.width = x;
img_desc.height = y;
img_desc.pixel_format = .SG_PIXELFORMAT_RGBA8;
img_desc.min_filter = .SG_FILTER_LINEAR;
img_desc.mag_filter = .SG_FILTER_LINEAR;
img_desc.wrap_u = .SG_WRAP_REPEAT;
img_desc.wrap_v = .SG_WRAP_REPEAT;
img_desc.label = "color-image";
viewport.color_img = c.sg_make_image(&img_desc);
img_desc.pixel_format = .SG_PIXELFORMAT_DEPTH;
img_desc.label = "depth-image";
viewport.depth_img = c.sg_make_image(&img_desc);
var pass_desc : c.sg_pass_desc = std.mem.zeroes(c.sg_pass_desc);
pass_desc.label = "offscreen-pass";
pass_desc.depth_stencil_attachment.image = viewport.depth_img;
pass_desc.color_attachments[0].image = viewport.color_img;
viewport.pass = c.sg_make_pass(&pass_desc);
// Init pass action.
viewport.pass_action.colors[0].action = .SG_ACTION_CLEAR;
viewport.pass_action.colors[0].value = c.struct_sg_color {
.r = 0.25, .g = 0.45, .b = 0.65, .a = 1.0
};
//
// CUBE:
//
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,
};
load_viewport_mesh(viewport, vertices[0..], indices[0..]);
const shader_desc = @ptrCast([*]const c.sg_shader_desc, glsl.cube_shader_desc(glsl.sg_query_backend()));
viewport.shader = c.sg_make_shader(shader_desc);
var pipeline_desc = std.mem.zeroes(c.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 = viewport.shader;
pipeline_desc.index_type = .SG_INDEXTYPE_UINT16;
pipeline_desc.depth.compare = .SG_COMPAREFUNC_LESS_EQUAL;
pipeline_desc.depth.write_enabled = true;
pipeline_desc.depth.pixel_format = .SG_PIXELFORMAT_DEPTH;
pipeline_desc.cull_mode = .SG_CULLMODE_BACK;
viewport.pipeline = c.sg_make_pipeline(&pipeline_desc);
}
fn load_viewport_mesh(viewport : *ViewportState, vertices : [] const f32, indices : [] const u16) void {
var buffer_desc = std.mem.zeroes(c.sg_buffer_desc);
buffer_desc.size = vertices.len * @sizeOf(f32);
buffer_desc.data = .{ .ptr = &vertices[0], .size = buffer_desc.size };
viewport.bindings.vertex_buffers[0] = c.sg_make_buffer(&buffer_desc);
buffer_desc = std.mem.zeroes(c.sg_buffer_desc);
buffer_desc.type = .SG_BUFFERTYPE_INDEXBUFFER;
buffer_desc.size = indices.len * @sizeOf(u16);
buffer_desc.data = .{ .ptr = &indices[0], .size = buffer_desc.size };
viewport.bindings.index_buffer = c.sg_make_buffer(&buffer_desc);
}
fn load_gltf_mesh_into_viewport(viewport : *ViewportState) void {
var options : c.cgltf_options = std.mem.zeroes(c.cgltf_options);
var data : [*c]c.cgltf_data = undefined;
var result : c.cgltf_result = c.cgltf_parse_file(&options, "../assets/suzanne.glb", &data);
if (@enumToInt(result) == c.cgltf_result_success) {
// TODO: use data
c.cgltf_free(data);
}
}
pub fn do_3d_viewport(viewport : *ViewportState) void {
if (viewport.mesh_idx == 1 and viewport.prev_mesh_idx != 1) {
load_gltf_mesh_into_viewport(viewport);
viewport.prev_mesh_idx = viewport.mesh_idx;
}
var vMin = c.ImVec2 { .x = 0, .y = 0 };
var vMax = c.ImVec2 { .x = 0, .y = 0 };
var vPos = c.ImVec2 { .x = 0, .y = 0 };
c.igGetWindowContentRegionMin(&vMin);
c.igGetWindowContentRegionMax(&vMax);
c.igGetWindowPos(&vPos);
vMin.x += vPos.x;
vMin.y += vPos.y;
vMax.x += vPos.x;
vMax.y += vPos.y;
if (viewport.min.x != vMin.x or
viewport.min.y != vMin.y or
viewport.max.x != vMax.x or
viewport.max.y != vMax.y - 2)
{
viewport.min = vMin;
viewport.max = vMax;
// This is necessary so we don't get a scroll bar on the viewport window.
// Not sure how we'd turn off the border on the image.
viewport.max.y -= 2;
viewport.size = c.ImVec2 { .x = viewport.max.x - viewport.min.x,
.y = viewport.max.y - viewport.min.y };
init_viewport(viewport,
@floatToInt(i32, viewport.size.x),
@floatToInt(i32, viewport.size.y));
}
const w: f32 = viewport.size.x;
const h: f32 = viewport.size.y;
var mvp = compute_mvp(viewport.camera_rot, w / h, 2.0);
var vs_params = glsl.vs_params_t {
.mvp = @ptrCast(*[16]f32, &mvp[0][0]).*,
};
c.sg_begin_pass(viewport.pass, &viewport.pass_action);
c.sg_apply_pipeline(viewport.pipeline);
c.sg_apply_bindings(&viewport.bindings);
c.sg_apply_uniforms(.SG_SHADERSTAGE_VS, 0, &.{ .ptr = &vs_params, .size = @sizeOf(glsl.vs_params_t) });
c.sg_draw(0, 36, 1);
c.sg_end_pass();
c.igImage(@intToPtr(c.ImTextureID, @intCast(usize, viewport.color_img.id)),
viewport.size,
c.ImVec2{ .x = 0, .y = 0 },
c.ImVec2{ .x = 1, .y = 1 },
c.ImVec4{ .x = 1, .y = 1, .z = 1, .w = 1 },
c.ImVec4{ .x = 1, .y = 1, .z = 1, .w = 1 });
}
|
src/3d_viewport.zig
|
const std = @import("std");
const Allocator = std.mem.Allocator;
const StringHashMap = std.StringHashMap;
const ArrayList = std.ArrayList;
const TailQueue = std.TailQueue;
pub fn DepsGraph(comptime T: type) type {
return struct {
allocator: *Allocator,
// All the pointers to symbols inside this struct are owned by this struct
// More specifically, they sould be freed when removed from the symbols
// hash map. And they should only be removed from there when there are
// no references to them in the dependants_of hash map
symbols: StringHashMap(*Symbol),
// *Symbol owned by self.symbols
dependants_of: StringHashMap(ArrayList(*Symbol)),
// ?*Symbol owned by self.symbols
current_symbol: ?*Symbol,
// Queue containing symbols ready to be emitted
// Can be updated each time after calling endSymbol()
emitted: TailQueue(EmittedSymbol),
const Self = @This();
pub fn init(allocator: *Allocator) Self {
return .{
.allocator = allocator,
.symbols = StringHashMap(*Symbol).init(allocator),
.dependants_of = StringHashMap(ArrayList(*Symbol)).init(allocator),
.current_symbol = null,
.emitted = TailQueue(EmittedSymbol){},
};
}
pub fn deinit(self: *Self) void {
var s_iter = self.symbols.iterator();
while (s_iter.next()) |entry| {
// Here entry.value is a *Symbol, so we deinit the symbol
entry.value_ptr.*.deinit(self.allocator);
// And free the pointer
self.allocator.destroy(entry.value_ptr.*);
}
self.symbols.deinit();
var d_iter = self.dependants_of.iterator();
while (d_iter.next()) |entry| {
// Here entry.value is an ArrayList(*Symbol), so we simply
// deinit the array list (since the pointers were freed already)
entry.value_ptr.*.deinit();
}
self.dependants_of.deinit();
while (self.emitted.popFirst()) |node| {
self.allocator.destroy(node);
}
self.current_symbol = null;
}
pub fn isBlocking(self: *Self, symbol_name: []const u8) bool {
// A symbol_name can be blocking if either:
// 1. There is no symbol declared with that name yet
// 2. There is a symbol, but it is blocked by some dependencies too
const symbol = self.symbols.get(symbol_name) orelse return true;
// TODO Should a symbol be able to depend on itself?
// If so, what to do in that case? For now, it blocks itself
// if (symbol == self.current_symbol) return false;
return symbol.hasDependenciesOfType(.Linear);
}
pub const BeginSymbolError = error{ DuplicateSymbol, OutOfMemory };
pub fn beginSymbol(self: *Self, name: []const u8, payload: T) BeginSymbolError!void {
var result = try self.symbols.getOrPut(name);
if (result.found_existing) {
return error.DuplicateSymbol;
}
// Since the allocation can fail, we do not want to leave the state
// inconsistent (with a KV whose value is empty)
errdefer std.debug.assert(self.symbols.remove(name));
result.value_ptr.* = try self.allocator.create(Symbol);
result.value_ptr.*.* = Symbol.init(self.allocator, name, payload);
self.current_symbol = result.value_ptr.*;
}
pub const AddDependencyError = error{ NoSymbol, OutOfMemory };
pub fn addDependency(self: *Self, dependency_name: []const u8) AddDependencyError!void {
// If the dependency is not blocking, then there's no need to add it
if (!self.isBlocking(dependency_name)) return;
var current_symbol = self.current_symbol orelse return error.NoSymbol;
// If a symbol depends on itself, whatever, not our business
if (std.mem.eql(u8, dependency_name, current_symbol.name)) return;
var already_added: bool = false;
var is_circular: bool = false;
// Checks if there are other symbols that depend on dependency_name
var result = try self.dependants_of.getOrPut(dependency_name);
// Creates or retrieves the array list that contains what symbols
// depend on dependency_name. Also checks if this symbol is already there
if (result.found_existing) {
for (result.value_ptr.items) |symbol| {
if (symbol == current_symbol) {
already_added = true;
}
}
} else {
result.value_ptr.* = ArrayList(*Symbol).init(self.allocator);
}
if (!already_added) {
try result.value_ptr.append(current_symbol);
if (self.dependants_of.getEntry(current_symbol.name)) |dependants| {
for (dependants.value_ptr.items) |dep| {
if (std.mem.eql(u8, dep.name, dependency_name)) {
try dep.addDependency(.{ .Circular = current_symbol.name });
is_circular = true;
break;
}
}
}
if (is_circular) {
try current_symbol.addDependency(.{ .Circular = dependency_name });
} else {
try current_symbol.addDependency(.{ .Linear = dependency_name });
}
}
}
pub const EndSymbolError = error{OutOfMemory};
pub fn createNode(comptime V: type, data: V, allocator: *Allocator) !*TailQueue(V).Node {
var node = try allocator.create(TailQueue(V).Node);
node.* = .{ .data = data };
return node;
}
pub fn endSymbol(self: *Self) EndSymbolError!void {
var current_symbol = self.current_symbol orelse return;
var unblock_queue = std.TailQueue(EmittedSymbol){};
if (!self.isBlocking(current_symbol.name)) {
const node = try createNode(EmittedSymbol, .{
.symbol = current_symbol,
.partial = current_symbol.hasDependencies(),
}, self.allocator);
unblock_queue.append(node);
}
// All items in unblock_queue have already been unblocked, and so
// should be emitted. Also, any dependants of them should be checked
// if they themselves can be unblocked as well
while (unblock_queue.popFirst()) |symbol_node| {
self.emitted.append(symbol_node);
const symbol = symbol_node.data.symbol;
if (self.dependants_of.getEntry(symbol.name)) |kv| {
for (kv.value_ptr.items) |dependant| {
if (dependant.removeDependency(symbol.name)) |dep| {
const unblock_dep = (!dependant.emitted and !dependant.hasDependenciesOfType(.Linear)) or !dependant.hasDependencies();
if (!unblock_dep) continue;
dependant.emitted = true;
const node = try createNode(EmittedSymbol, .{
.symbol = dependant,
.partial = dependant.hasDependencies(),
}, self.allocator);
unblock_queue.append(node);
}
}
}
}
self.current_symbol = null;
}
pub fn readEmitted(self: *Self) ?EmittedSymbol {
var symbol_node = self.emitted.popFirst() orelse return null;
var symbol = symbol_node.data;
self.allocator.destroy(symbol_node);
return symbol;
}
pub fn blockedIterator(self: *Self) BlockedSymbolsIterator {
return BlockedSymbolsIterator.init(self);
}
const Dependency = union(enum) {
Linear: []const u8,
Circular: []const u8,
pub fn getName(self: Dependency) []const u8 {
return switch (self) {
.Linear => |n| n,
.Circular => |n| n,
};
}
pub fn eql(self: Dependency, other: Dependency) bool {
switch (self) {
.Linear => |n| return other == .Linear and std.mem.eql(u8, other.Linear, n),
.Circular => |n| return other == .Circular and std.mem.eql(u8, other.Circular, n),
}
}
pub fn eqlName(self: Dependency, other: Dependency) bool {
return std.mem.eql(u8, self.getName(), other.getName());
}
};
const EmittedSymbol = struct {
symbol: *Symbol,
partial: bool,
};
const Symbol = struct {
// Not owned
name: []const u8,
// Slices not owned
dependencies: ArrayList(Dependency),
emitted: bool = false,
payload: T,
pub fn init(allocator: *Allocator, name: []const u8, payload: T) Symbol {
return .{
.name = name,
.dependencies = ArrayList(Dependency).init(allocator),
.payload = payload,
};
}
pub fn deinit(self: *Symbol, allocator: *Allocator) void {
self.dependencies.deinit();
}
pub fn addDependency(self: *Symbol, dependency: Dependency) !void {
for (self.dependencies.items) |*existing| {
if (dependency.eqlName(existing.*)) {
existing.* = dependency;
return;
}
}
try self.dependencies.append(dependency);
}
pub fn removeDependency(self: *Symbol, dependency_name: []const u8) ?Dependency {
var maybe_dep_index: ?usize = null;
for (self.dependencies.items) |dependency, i| {
if (dependency.eqlName(dependency)) {
maybe_dep_index = i;
break;
}
}
if (maybe_dep_index) |dep_index| {
// Since dependencies are not stored in any particurarly
// important order, we can use swapRemove which is more
// efficient than orderedRemove
return self.dependencies.swapRemove(dep_index);
}
return null;
}
pub fn getDependency(self: *Symbol, dependency_name: []const u8) ?Dependency {
for (self.dependencies.items) |dependency| {
if (dependency.eqlName(dependency)) {
return dependency;
}
}
return null;
}
pub fn hasDependencies(self: *Symbol) bool {
return self.dependencies.items.len > 0;
}
pub fn hasDependenciesOfType(self: *Symbol, tag: std.meta.TagType(Dependency)) bool {
for (self.dependencies.items) |dep| {
if (dep == tag) return true;
}
return false;
}
};
pub const BlockedSymbolsIterator = struct {
graph: *Self,
hash_iter: StringHashMap(*Symbol).Iterator,
pub fn init(graph: *Self) BlockedSymbolsIterator {
return .{
.graph = graph,
.hash_iter = graph.symbols.iterator(),
};
}
pub fn next(self: *BlockedSymbolsIterator) ?*Symbol {
while (self.hash_iter.next()) |symbol| {
if (symbol.value_ptr.*.hasDependenciesOfType(.Linear)) {
return symbol.value_ptr.*;
}
}
return null;
}
};
};
}
const expect = std.testing.expect;
const expectEqual = std.testing.expectEqual;
const expectEqualStrings = std.testing.expectEqualStrings;
fn expectSymbol(emitted: ?DepsGraph(void).EmittedSymbol, expected_name: []const u8, expected_partial: bool) !void {
try expect(emitted != null);
try expectEqualStrings(expected_name, emitted.?.symbol.name);
try expectEqual(expected_partial, emitted.?.partial);
}
test "Simple dependency graph with circular dependencies" {
const allocator = std.testing.allocator;
var deps = DepsGraph(void).init(allocator);
try deps.beginSymbol("SourceMap", {});
try deps.addDependency("TextSpan");
try deps.endSymbol();
try expect(deps.readEmitted() == null);
try deps.beginSymbol("TextSpan", {});
try deps.addDependency("TextPosition");
try deps.endSymbol();
try expect(deps.readEmitted() == null);
try deps.beginSymbol("TextPosition", {});
try deps.addDependency("TextSpan");
try deps.endSymbol();
try expect(deps.emitted.first != null);
if (deps.readEmitted()) |s| {
try expectEqualStrings(s.symbol.name, "TextPosition");
try expectEqual(s.partial, true);
}
try expect(deps.emitted.first != null);
if (deps.readEmitted()) |s| {
try expectEqualStrings(s.symbol.name, "TextSpan");
try expectEqual(s.partial, false);
}
try expect(deps.emitted.first != null);
if (deps.readEmitted()) |s| {
try expectEqualStrings(s.symbol.name, "SourceMap");
try expectEqual(s.partial, false);
}
try expect(deps.emitted.first != null);
if (deps.readEmitted()) |s| {
try expectEqualStrings(s.symbol.name, "TextPosition");
try expectEqual(s.partial, false);
}
try expect(deps.readEmitted() == null);
deps.deinit();
}
test "Blocked symbols iterator" {
const allocator = std.testing.allocator;
var deps = DepsGraph(void).init(allocator);
try deps.beginSymbol("SourceMap", {});
try deps.addDependency("TextSpan");
try deps.endSymbol();
try expect(deps.readEmitted() == null);
try deps.beginSymbol("TextSpan", {});
try deps.endSymbol();
try expect(deps.emitted.first != null);
if (deps.readEmitted()) |s| {
try expectEqualStrings(s.symbol.name, "TextSpan");
try expectEqual(s.partial, false);
}
try expect(deps.emitted.first != null);
if (deps.readEmitted()) |s| {
try expectEqualStrings(s.symbol.name, "SourceMap");
try expectEqual(s.partial, false);
}
try expect(deps.readEmitted() == null);
try deps.beginSymbol("TextPosition", {});
try deps.addDependency("Cursor");
try deps.endSymbol();
try expect(deps.readEmitted() == null);
var iter = deps.blockedIterator();
var symbol = iter.next();
try expect(symbol != null);
try expectEqualStrings(symbol.?.name, "TextPosition");
try expect(iter.next() == null);
deps.deinit();
}
test "Three tier circular dependencies" {
const allocator = std.testing.allocator;
var deps = DepsGraph(void).init(allocator);
try deps.beginSymbol("LookMaAnEnum", {});
try deps.endSymbol();
try deps.beginSymbol("WackType", {});
try deps.addDependency("LameType");
try deps.endSymbol();
try deps.beginSymbol("LameType", {});
try deps.addDependency("WackType");
try deps.addDependency("WhatsAUnion");
try deps.endSymbol();
try deps.beginSymbol("WhatsAUnion", {});
try deps.addDependency("LameType");
try deps.endSymbol();
try expectSymbol(deps.readEmitted(), "LookMaAnEnum", false);
try expectSymbol(deps.readEmitted(), "WhatsAUnion", true);
try expectSymbol(deps.readEmitted(), "LameType", true);
try expectSymbol(deps.readEmitted(), "WackType", false);
try expectSymbol(deps.readEmitted(), "WhatsAUnion", false);
try expectSymbol(deps.readEmitted(), "LameType", false);
try expect(deps.readEmitted() == null);
deps.deinit();
}
|
src/deps_graph.zig
|
const std = @import("std");
const testing = std.testing;
const input_file = "input02.txt";
const PasswordPolicy = struct {
min: u32,
max: u32,
char: u8,
};
fn parsePasswordPolicy(policy: []const u8) !PasswordPolicy {
var iter = std.mem.split(policy, " ");
const min_max = iter.next() orelse return error.FormatError;
const char = iter.next() orelse return error.FormatError;
var iter_min_max = std.mem.split(min_max, "-");
const min = iter_min_max.next() orelse return error.FormatError;
const max = iter_min_max.next() orelse return error.FormatError;
return PasswordPolicy{
.min = try std.fmt.parseInt(u32, min, 10),
.max = try std.fmt.parseInt(u32, max, 10),
.char = if (char.len == 1) char[0] else return error.CharacterTooLong,
};
}
test "parsePasswordPolicy" {
const policy = "1-3 a";
const parsed = try parsePasswordPolicy(policy);
try testing.expectEqual(parsed.min, 1);
try testing.expectEqual(parsed.max, 3);
try testing.expectEqual(parsed.char, 'a');
}
const Line = struct {
policy: PasswordPolicy,
password: []const u8,
pub fn isValid(self: Line) bool {
var count: u32 = 0;
for (self.password) |x| {
if (x == self.policy.char) count += 1;
}
return count >= self.policy.min and count <= self.policy.max;
}
};
fn parseLine(line: []const u8) !Line {
var iter = std.mem.split(line, ":");
const policy = iter.next() orelse return error.FormatError;
const password = iter.next() orelse return error.FormatError;
return Line{
.policy = try parsePasswordPolicy(policy),
.password = password[1..],
};
}
test "parseLine" {
const line = "1-3 a: abcde";
const parsed = try parseLine(line);
try testing.expectEqualSlices(u8, parsed.password, "<PASSWORD>");
try testing.expectEqual(parsed.policy.min, 1);
try testing.expectEqual(parsed.policy.max, 3);
try testing.expectEqual(parsed.policy.char, 'a');
}
pub fn main() !void {
var file = try std.fs.cwd().openFile(input_file, .{});
defer file.close();
var valid_passwords: u32 = 0;
const reader = file.reader();
var buf: [1024]u8 = undefined;
while (try reader.readUntilDelimiterOrEof(&buf, '\n')) |line| {
const parsed = try parseLine(line);
if (parsed.isValid()) valid_passwords += 1;
}
std.debug.print("valid passwords: {}\n", .{valid_passwords});
}
|
src/02.zig
|
const std = @import("std");
const ArrayList = std.ArrayList;
const walkdir = @import("walkdir");
const Entry = walkdir.Entry;
const regex = @import("regex");
const Regex = regex.Regex;
pub const TypeFilter = struct {
file: bool = false,
directory: bool = false,
symlink: bool = false,
executable: bool = false,
empty: bool = false,
const Self = @This();
pub fn matches(self: Self, entry: Entry) bool {
return switch (entry.kind) {
.BlockDevice => false,
.CharacterDevice => false,
.Directory => self.directory,
.NamedPipe => false,
.SymLink => self.symlink,
.File => self.file,
.UnixDomainSocket => false,
.Whiteout => false,
.Door => false,
.EventPort => false,
.Unknown => false,
};
}
};
fn hasExtension(name: []const u8, ext: []const u8) bool {
return std.mem.endsWith(u8, name, ext) and name.len > ext.len and name[name.len - ext.len - 1] == '.';
}
pub const Filter = struct {
pattern: ?Regex = null,
full_path: bool = false,
extensions: ?ArrayList([]const u8) = null,
types: ?TypeFilter = null,
const Self = @This();
pub fn deinit(self: *Self) void {
if (self.pattern) |*r| r.deinit();
if (self.extensions) |ext| {
for (ext.items) |x| ext.allocator.free(x);
ext.deinit();
}
}
pub fn matches(self: Self, entry: Entry) !bool {
const text = if (self.full_path) entry.relative_path else entry.name;
if (self.pattern) |re| {
var r = re;
if (!(try r.partialMatch(text))) {
return false;
}
}
if (self.extensions) |ext| {
for (ext.items) |x| {
if (hasExtension(text, x)) {
break;
}
} else return false;
}
if (self.types) |types| {
if (!types.matches(entry)) return false;
}
return true;
}
};
|
src/filter.zig
|
const types = @import("types.zig");
usingnamespace @import("method.zig");
const email = struct {
const Record = struct {
// meta
id: types.Id,
blob_id: types.Id,
thread_id: types.Id,
mailbox_ids: JsonStringMap(bool),
keywords: JsonStringMap(bool),
size: types.UnsignedInt,
received_at: types.UTCDate,
// convenience headers
message_id: ?[]const []const u8, // header:Message-ID:asMessageIds
in_reply_to: ?[]const []const u8, // header:In-Reply-To:asMessageIds
references: ?[]const []const u8, // header:References:asMessageIds
sender: ?[]const EmailAddress, // header:Sender:asAddresses
from: ?[]const EmailAddress, // header:From:asAddresses
to: ?[]const EmailAddress, // header:To:asAddresses
cc: ?[]const EmailAddress, // header:Cc:asAddresses
bcc: ?[]const EmailAddress, // header:Bcc:asAddresses
reply_to: ?[]const EmailAddress, // header:Reply-To:asAddresses
subject: ?[]const u8, // header:Subject:asText
sent_at: ?types.Date, // header:Date:asDate
// body parts
body_structure: EmailBodyPart,
body_values: JsonStringMap(EmailBodyValue),
text_body: []const EmailBodyPart,
html_body: []const EmailBodyPart,
attachments: []const EmailBodyPart,
has_attachment: bool,
preview: []const u8,
};
// standard methods
const Get = Method(GetRequest, standard.GetResponse(Record));
const Changes = Method(standard.ChangesRequest, standard.ChangesResponse);
const Query = Method(QueryRequest, standard.QueryResponse);
const QueryChanges = Method(QueryChangesRequest, standard.QueryChangesResponse);
const Set = Method(standard.SetRequest(Record), standard.SetResponse(Record));
const Copy = Method(standard.CopyRequest(Record), standard.CopyResponse(Record));
// non-standard methods
const Import = Method(ImportRequest, ImportResponse);
const Parse = Method(ParseRequest, ParseResponse);
const EmailHeader = struct {
name: []const u8,
value: []const u8,
};
const EmailBodyPart = struct {
part_id: ?[]const u8,
blob_id: ?types.Id,
size: types.UnsignedInt,
headers: []const EmailHeader,
name: ?[]const u8,
type: []const u8,
charset: ?[]const u8,
disposition: ?[]const u8,
cid: ?[]const u8,
language: ?[]const []const u8,
location: ?[]const u8,
sub_parts: ?[]const EmailBodyPart,
};
const EmailBodyValue = struct {
value: []const u8,
is_encoding_problem: bool = false,
is_truncated: bool = false,
};
pub const GetRequest = struct {
account_id: types.Id,
ids: ?[]const types.Id,
// changed fields
properties: []const []const u8 = .{"id", "blobId", "threadId", "mailboxIds", "keywords", "size",
"receivedAt", "messageId", "inReplyTo", "references", "sender", "from",
"to", "cc", "bcc", "replyTo", "subject", "sentAt", "hasAttachment",
"preview", "bodyValues", "textBody", "htmlBody", "attachments"},
// extra fields
body_properties: []const []const u8 = .{"partId", "blobId", "size", "name", "type", "charset",
"disposition", "cid", "language", "location"},
fetch_text_body_values: bool = false,
fetch_html_body_values: bool = false,
fetch_all_body_values: bool = false,
max_body_values_bytes: types.UnsignedInt = 0,
};
pub const FilterCondition = struct {
in_mailbox: ?types.Id,
in_mailbox_other_than: ?[]const types.Id,
before: ?types.UTCDate,
after: ?types.UTCDate,
min_size: ?types.UnsignedInt,
max_size: ?types.UnsignedInt,
all_in_thread_have_keyword: ?[]const u8,
some_in_thread_have_keyword: ?[]const u8,
none_in_thread_have_keyword: ?[]const u8,
has_keyword: ?[]const u8,
not_keyword: ?[]const u8,
has_attachment: ?bool,
text: ?[]const u8,
from: ?[]const u8,
to: ?[]const u8,
cc: ?[]const u8,
bcc: ?[]const u8,
subject: ?[]const u8,
body: ?[]const u8,
header: ?[]const []const u8,
};
pub const QueryRequest = struct {
account_id: types.Id,
filter: ?custom_filter(FilterCondition).Filter,
sort: ?[]const Comparator,
// extra fields
collapse_threads: bool = false,
};
pub const QueryChangesRequest = struct {
account_id: types.Id,
filter: ?Filter,
sort: ?[]const Comparator,
since_query_state: []const u8,
max_changes: ?types.UnsignedInt,
up_to_id: ?types.Id,
calculate_total: bool = false,
// extra fields
collapse_threads: bool = false,
};
pub const EmailImport = struct {
blob_id: types.Id,
mailbox_ids: JsonStringMap(bool),
keywords: JsonStringMap(bool),
received_at: types.UTCDate,
};
pub const ImportResponse = struct {
account_id: types.Id,
old_state: ?[]const u8,
new_state: []const u8,
created: ?JsonStringMap(Record),
not_created: ?JsonStringMap(SetError),
};
pub const ImportRequest = struct {
account_id: types.Id,
if_in_state: ?[]const u8,
emails: JsonStringMap(EmailImport),
};
pub const ParseRequest = struct {
account_id: types.Id,
blob_ids: []const types.Id,
properties: []const []const u8 = .{"messageId", "inReplyTo", "references", "sender", "from", "to",
"cc", "bcc", "replyTo", "subject", "sentAt", "hasAttachment",
"preview", "bodyValues", "textBody", "htmlBody", "attachments"},
body_properties: []const []const u8,
fetch_text_body_values: bool = false,
fetch_html_body_values: bool = false,
fetch_all_body_values: bool = false,
max_body_value_bytes: types.UnsignedInt = 0,
};
pub const ParseResponse = struct {
account_id: types.Id,
parsed: ?JsonStringMap(Record),
not_parsable: ?[]const types.Id,
not_found: ?[]const types.Id,
};
};
|
mail/email.zig
|
const std = @import("std");
const builtin = @import("builtin");
/// This is the TinyVG magic number which recognizes the icon format.
/// Magic numbers might seem unnecessary, but they will be the first
/// guard in line against bad input and prevent unnecessary cycles
/// to detect those.
pub const magic_number = [2]u8{ 0x72, 0x56 };
/// This is the latest TinyVG version supported by this library.
pub const current_version = 1;
// submodules
/// This module provides a runtime usable builder
pub const builder = @import("builder.zig");
/// Module that provides a generic purpose TinyVG parser. This parser exports all data as
/// pre-scaled `f32` values.
pub const parsing = @import("parsing.zig");
/// A TinyVG software renderer based on the parsing module. Takes a parser stream as input.
pub const rendering = @import("rendering.zig");
/// This module provides means to render SVG files from TinyVG.
pub const svg = @import("svg.zig");
/// This module provides means to render and parse TinyVG text.
pub const text = @import("text.zig");
/// Returns a stream of TinyVG commands as well as the document header.
/// - `allocator` is used to allocate temporary data like the current set of vertices for *FillPolygon*. This can be a fixed-buffer allocator.
/// - `reader` is a generic stream that provides the TinyVG byte data.
pub fn parse(allocator: std.mem.Allocator, reader: anytype) !parsing.Parser(@TypeOf(reader)) {
return try parsing.Parser(@TypeOf(reader)).init(allocator, reader);
}
pub fn renderStream(
/// Allocator for temporary allocations
allocator: std.mem.Allocator,
/// A struct that exports a single function `setPixel(x: isize, y: isize, color: [4]u8) void` as well as two fields width and height
framebuffer: anytype,
/// The icon data
reader: anytype,
) !void {
var parser = try parse(allocator, reader);
defer parser.deinit();
while (try parser.next()) |cmd| {
try rendering.render(
framebuffer,
parser.header,
parser.color_table,
cmd,
);
}
}
pub fn render(
/// Allocator for temporary allocations
allocator: std.mem.Allocator,
/// A struct that exports a single function `setPixel(x: isize, y: isize, color: [4]u8) void` as well as two fields width and height
framebuffer: anytype,
/// The icon data
icon: []const u8,
) !void {
var stream = std.io.fixedBufferStream(icon);
return try renderStream(allocator, framebuffer, stream.reader());
}
comptime {
if (builtin.is_test) {
_ = @import("builder.zig"); // import file for tests
_ = parsing;
_ = rendering;
}
}
/// The value range used in the encoding.
pub const Range = enum(u2) {
/// unit uses 16 bit,
default = 0,
/// unit takes only 8 bit
reduced = 1,
// unit uses 32 bit,
enhanced = 2,
};
/// The color encoding used in a TinyVG file. This enum describes how the data in the color table section of the format looks like.
pub const ColorEncoding = enum(u2) {
/// A classic 4-tuple with 8 bit unsigned channels.
/// Encodes red, green, blue and alpha. If not specified otherwise (via external means) the color channels encode sRGB color data
/// and the alpha stores linear transparency.
u8888 = 0,
/// A 16 bit color format with 5 bit for red and blue, and 6 bit color depth for green channel.
/// This format is typically used in embedded devices or cheaper displays. If not specified otherwise (via external means) the color channels encode sRGB color data.
u565 = 1,
/// A format with 16 byte per color and 4 channels. Each channel is encoded as a `binary32` IEEE 754 value.
/// The first three channels encode color data, the fourth channel encodes linear alpha.
/// If not specified otherwise (via external means) the color channels encode sRGB color data and the alpha stores linear transparency.
f32 = 2,
/// This format is specified by external means and is meant to signal that these files are *valid*, but it's not possible
/// to decode them without external knowledge about the color encoding. This is meant for special cases where huge savings
/// might be possible by not encoding any color information in the files itself or special device dependent color formats are required.
///
/// Possible uses cases are:
///
/// - External fixed or shared color palettes
/// - CMYK format for printing
/// - High precision 16 bit color formats
/// - Using non-sRGB color spaces
/// - Using RAL numbers for painting
/// - ...
///
/// **NOTE:** A conforming parser is allowed to reject any file with a custom color encoding, as these are meant to be parsed with a specific use case.
custom = 3,
};
/// A TinyVG scale value. Defines the scale for all units inside a graphic.
/// The scale is defined by the number of decimal bits in a `i32`, thus scaling
/// can be trivially implemented by shifting the integers right by the scale bits.
pub const Scale = enum(u4) {
const Self = @This();
@"1/1" = 0,
@"1/2" = 1,
@"1/4" = 2,
@"1/8" = 3,
@"1/16" = 4,
@"1/32" = 5,
@"1/64" = 6,
@"1/128" = 7,
@"1/256" = 8,
@"1/512" = 9,
@"1/1024" = 10,
@"1/2048" = 11,
@"1/4096" = 12,
@"1/8192" = 13,
@"1/16384" = 14,
@"1/32768" = 15,
pub fn map(self: Self, value: f32) Unit {
return Unit.init(self, value);
}
pub fn getShiftBits(self: Self) u4 {
return @enumToInt(self);
}
pub fn getScaleFactor(self: Self) u15 {
return @as(u15, 1) << self.getShiftBits();
}
};
/// A scalable fixed-point number.
pub const Unit = enum(i32) {
const Self = @This();
_,
pub fn init(scale: Scale, value: f32) Self {
return @intToEnum(Self, @floatToInt(i32, value * @intToFloat(f32, scale.getScaleFactor()) + 0.5));
}
pub fn raw(self: Self) i32 {
return @enumToInt(self);
}
pub fn toFloat(self: Self, scale: Scale) f32 {
return @intToFloat(f32, @enumToInt(self)) / @intToFloat(f32, scale.getScaleFactor());
}
pub fn toInt(self: Self, scale: Scale) i32 {
const factor = scale.getScaleFactor();
return @divFloor(@enumToInt(self) + (@divExact(factor, 2)), factor);
}
pub fn toUnsignedInt(self: Self, scale: Scale) !u31 {
const i = toInt(self, scale);
if (i < 0)
return error.InvalidData;
return @intCast(u31, i);
}
};
pub const Color = extern struct {
const Self = @This();
r: f32,
g: f32,
b: f32,
a: f32,
pub fn toRgba8(self: Self) [4]u8 {
return [4]u8{
@floatToInt(u8, std.math.clamp(255.0 * self.r, 0.0, 255.0)),
@floatToInt(u8, std.math.clamp(255.0 * self.g, 0.0, 255.0)),
@floatToInt(u8, std.math.clamp(255.0 * self.b, 0.0, 255.0)),
@floatToInt(u8, std.math.clamp(255.0 * self.a, 0.0, 255.0)),
};
}
pub fn lerp(lhs: Self, rhs: Self, factor: f32) Self {
const l = struct {
fn l(a: f32, b: f32, c: f32) u8 {
return @floatToInt(u8, @intToFloat(f32, a) + (@intToFloat(f32, b) - @intToFloat(f32, a)) * std.math.clamp(c, 0, 1));
}
}.l;
return Self{
.r = l(lhs.r, rhs.r, factor),
.g = l(lhs.g, rhs.g, factor),
.b = l(lhs.b, rhs.b, factor),
.a = l(lhs.a, rhs.a, factor),
};
}
pub fn fromString(str: []const u8) !Self {
return switch (str.len) {
6 => Self{
.r = @intToFloat(f32, try std.fmt.parseInt(u8, str[0..2], 16)) / 255.0,
.g = @intToFloat(f32, try std.fmt.parseInt(u8, str[2..4], 16)) / 255.0,
.b = @intToFloat(f32, try std.fmt.parseInt(u8, str[4..6], 16)) / 255.0,
.a = 1.0,
},
else => error.InvalidFormat,
};
}
};
pub const Command = enum(u6) {
end_of_document = 0,
fill_polygon = 1,
fill_rectangles = 2,
fill_path = 3,
draw_lines = 4,
draw_line_loop = 5,
draw_line_strip = 6,
draw_line_path = 7,
outline_fill_polygon = 8,
outline_fill_rectangles = 9,
outline_fill_path = 10,
_,
};
/// Constructs a new point
pub fn point(x: f32, y: f32) Point {
return .{ .x = x, .y = y };
}
pub const Point = struct {
x: f32,
y: f32,
};
pub fn rectangle(x: f32, y: f32, width: f32, height: f32) Rectangle {
return .{ .x = x, .y = y, .width = width, .height = height };
}
pub const Rectangle = struct {
x: f32,
y: f32,
width: f32,
height: f32,
};
pub fn line(start: Point, end: Point) Line {
return Line{ .start = start, .end = end };
}
pub const Line = struct {
start: Point,
end: Point,
};
pub const Path = struct {
segments: []Segment,
pub const Segment = struct {
start: Point,
commands: []const Node,
};
pub const Node = union(Type) {
const Self = @This();
line: NodeData(Point),
horiz: NodeData(f32),
vert: NodeData(f32),
bezier: NodeData(Bezier),
arc_circle: NodeData(ArcCircle),
arc_ellipse: NodeData(ArcEllipse),
close: NodeData(void),
quadratic_bezier: NodeData(QuadraticBezier),
pub fn NodeData(comptime Payload: type) type {
return struct {
line_width: ?f32 = null,
data: Payload,
pub fn init(line_width: ?f32, data: Payload) @This() {
return .{ .line_width = line_width, .data = data };
}
};
}
pub const ArcCircle = struct {
radius: f32,
large_arc: bool,
sweep: bool,
target: Point,
};
pub const ArcEllipse = struct {
radius_x: f32,
radius_y: f32,
rotation: f32,
large_arc: bool,
sweep: bool,
target: Point,
};
pub const Bezier = struct {
c0: Point,
c1: Point,
p1: Point,
};
pub const QuadraticBezier = struct {
c: Point,
p1: Point,
};
};
pub const Type = enum(u3) {
line = 0, // x,y
horiz = 1, // x
vert = 2, // y
bezier = 3, // c0x,c0y,c1x,c1y,x,y
arc_circle = 4, //r,x,y
arc_ellipse = 5, // rx,ry,x,y
close = 6,
quadratic_bezier = 7,
};
};
pub const StyleType = enum(u2) {
flat = 0,
linear = 1,
radial = 2,
};
pub const Style = union(StyleType) {
const Self = @This();
flat: u32, // color index
linear: Gradient,
radial: Gradient,
};
pub const Gradient = struct {
point_0: Point,
point_1: Point,
color_0: u32,
color_1: u32,
};
test {
_ = builder;
_ = parsing;
_ = rendering;
}
|
src/lib/tinyvg.zig
|
const std = @import("std");
const aws = @import("aws.zig");
const json = @import("json.zig");
var verbose = false;
pub fn log(
comptime level: std.log.Level,
comptime scope: @TypeOf(.EnumLiteral),
comptime format: []const u8,
args: anytype,
) void {
// Ignore awshttp messages
if (!verbose and scope == .awshttp and @enumToInt(level) >= @enumToInt(std.log.Level.debug))
return;
const scope_prefix = "(" ++ @tagName(scope) ++ "): ";
const prefix = "[" ++ @tagName(level) ++ "] " ++ scope_prefix;
// Print the message to stderr, silently ignoring any errors
std.debug.getStderrMutex().lock();
defer std.debug.getStderrMutex().unlock();
const stderr = std.io.getStdErr().writer();
nosuspend stderr.print(prefix ++ format ++ "\n", args) catch return;
}
const Tests = enum {
query_no_input,
query_with_input,
ec2_query_no_input,
json_1_0_query_with_input,
json_1_0_query_no_input,
json_1_1_query_with_input,
json_1_1_query_no_input,
rest_json_1_query_no_input,
rest_json_1_query_with_input,
rest_json_1_work_with_lambda,
};
pub fn main() anyerror!void {
const c_allocator = std.heap.c_allocator;
var gpa = std.heap.GeneralPurposeAllocator(.{}){
.backing_allocator = c_allocator,
};
defer _ = gpa.deinit();
const allocator = gpa.allocator();
var tests = std.ArrayList(Tests).init(allocator);
defer tests.deinit();
var args = std.process.args();
while (args.next(allocator)) |arg_or_error| {
const arg = try arg_or_error;
defer allocator.free(arg);
if (std.mem.eql(u8, "-v", arg)) {
verbose = true;
continue;
}
inline for (@typeInfo(Tests).Enum.fields) |f| {
if (std.mem.eql(u8, f.name, arg)) {
try tests.append(@field(Tests, f.name));
break;
}
}
}
if (tests.items.len == 0) {
inline for (@typeInfo(Tests).Enum.fields) |f|
try tests.append(@field(Tests, f.name));
}
std.log.info("Start\n", .{});
var client = aws.Client.init(allocator);
const options = aws.Options{
.region = "us-west-2",
.client = client,
};
defer client.deinit();
const services = aws.Services(.{ .sts, .ec2, .dynamo_db, .ecs, .lambda }){};
for (tests.items) |t| {
std.log.info("===== Start Test: {s} =====", .{@tagName(t)});
switch (t) {
.query_no_input => {
const call = try aws.Request(services.sts.get_caller_identity).call(.{}, options);
// const call = try client.call(services.sts.get_caller_identity.Request{}, options);
defer call.deinit();
std.log.info("arn: {s}", .{call.response.arn});
std.log.info("id: {s}", .{call.response.user_id});
std.log.info("account: {s}", .{call.response.account});
std.log.info("requestId: {s}", .{call.response_metadata.request_id});
},
.query_with_input => {
// TODO: Find test without sensitive info
const call = try client.call(services.sts.get_session_token.Request{
.duration_seconds = 900,
}, options);
defer call.deinit();
std.log.info("access key: {s}", .{call.response.credentials.?.access_key_id});
},
.json_1_0_query_with_input => {
const call = try client.call(services.dynamo_db.list_tables.Request{
.limit = 1,
}, options);
defer call.deinit();
std.log.info("request id: {s}", .{call.response_metadata.request_id});
std.log.info("account has tables: {b}", .{call.response.table_names.?.len > 0});
},
.json_1_0_query_no_input => {
const call = try client.call(services.dynamo_db.describe_limits.Request{}, options);
defer call.deinit();
std.log.info("account read capacity limit: {d}", .{call.response.account_max_read_capacity_units});
},
.json_1_1_query_with_input => {
const call = try client.call(services.ecs.list_clusters.Request{
.max_results = 1,
}, options);
defer call.deinit();
std.log.info("request id: {s}", .{call.response_metadata.request_id});
std.log.info("account has clusters: {b}", .{call.response.cluster_arns.?.len > 0});
},
.json_1_1_query_no_input => {
const call = try client.call(services.ecs.list_clusters.Request{}, options);
defer call.deinit();
std.log.info("request id: {s}", .{call.response_metadata.request_id});
std.log.info("account has clusters: {b}", .{call.response.cluster_arns.?.len > 0});
},
.rest_json_1_query_with_input => {
const call = try client.call(services.lambda.list_functions.Request{
.max_items = 1,
}, options);
defer call.deinit();
std.log.info("request id: {s}", .{call.response_metadata.request_id});
std.log.info("account has functions: {b}", .{call.response.functions.?.len > 0});
},
.rest_json_1_query_no_input => {
const call = try client.call(services.lambda.list_functions.Request{}, options);
defer call.deinit();
std.log.info("request id: {s}", .{call.response_metadata.request_id});
std.log.info("account has functions: {b}", .{call.response.functions.?.len > 0});
},
.rest_json_1_work_with_lambda => {
const call = try client.call(services.lambda.list_functions.Request{}, options);
defer call.deinit();
std.log.info("list request id: {s}", .{call.response_metadata.request_id});
if (call.response.functions) |fns| {
if (fns.len > 0) {
const func = fns[0];
const arn = func.function_arn.?;
// This is a bit ugly. Maybe a helper function in the library would help?
var tags = try std.ArrayList(@typeInfo(try typeForField(services.lambda.tag_resource.Request, "tags")).Pointer.child).initCapacity(allocator, 1);
defer tags.deinit();
tags.appendAssumeCapacity(.{ .key = "Foo", .value = "Bar" });
const req = services.lambda.tag_resource.Request{ .resource = arn, .tags = tags.items };
const addtag = try aws.Request(services.lambda.tag_resource).call(req, options);
defer addtag.deinit();
// const addtag = try client.call(services.lambda.tag_resource.Request{ .resource = arn, .tags = &.{.{ .key = "Foo", .value = "Bar" }} }, options);
std.log.info("add tag request id: {s}", .{addtag.response_metadata.request_id});
var keys = [_][]const u8{"Foo"}; // Would love to have a way to express this without burning a var here
const deletetag = try aws.Request(services.lambda.untag_resource).call(.{ .tag_keys = keys[0..], .resource = arn }, options);
defer deletetag.deinit();
std.log.info("delete tag request id: {s}", .{deletetag.response_metadata.request_id});
} else {
std.log.err("no functions to work with", .{});
}
} else {
std.log.err("no functions to work with", .{});
}
},
.ec2_query_no_input => {
std.log.err("EC2 Test disabled due to compiler bug", .{});
// const instances = try client.call(services.ec2.describe_instances.Request{}, options);
// defer instances.deinit();
// std.log.info("reservation count: {d}", .{instances.response.reservations.len});
},
}
std.log.info("===== End Test: {s} =====\n", .{@tagName(t)});
}
// if (test_twice) {
// std.time.sleep(1000 * std.time.ns_per_ms);
// std.log.info("second request", .{});
//
// var client2 = aws.Aws.init(allocator);
// defer client2.deinit();
// const resp2 = try client2.call(services.sts.get_caller_identity.Request{}, options); // catch here and try alloc?
// defer resp2.deinit();
// }
std.log.info("===== Tests complete =====", .{});
}
fn typeForField(comptime T: type, field_name: []const u8) !type {
const ti = @typeInfo(T);
switch (ti) {
.Struct => {
inline for (ti.Struct.fields) |field| {
if (std.mem.eql(u8, field.name, field_name))
return field.field_type;
}
},
else => return error.TypeIsNotAStruct, // should not hit this
}
return error.FieldNotFound;
}
// TODO: Move into json.zig
pub fn jsonFun() !void {
// Standard behavior
const payload =
\\{"GetCallerIdentityResponse":{"GetCallerIdentityResult":{"Account":"0123456789","Arn":"arn:aws:iam::0123456789:user/test","UserId":"MYUSERID"},"ResponseMetadata":{"RequestId":"3b80a99b-7df8-4bcb-96ee-b2759878a5f2"}}}
;
const Ret3 = struct {
getCallerIdentityResponse: struct { getCallerIdentityResult: struct { account: []u8, arn: []u8, user_id: []u8 }, responseMetadata: struct { requestId: []u8 } },
};
var stream3 = json.TokenStream.init(payload);
const res3 = json.parse(Ret3, &stream3, .{
.allocator = std.heap.c_allocator,
.allow_camel_case_conversion = true, // new option
.allow_snake_case_conversion = true, // new option
.allow_unknown_fields = true, // new option
}) catch unreachable;
std.log.info("{}", .{res3});
std.log.info("{s}", .{res3.getCallerIdentityResponse.getCallerIdentityResult.user_id});
}
|
src/main.zig
|
const c = @import("c.zig");
const std = @import("std");
const panic = std.debug.panic;
const debug_gl = @import("debug_gl.zig");
const glfw_impl = @import("glfw_impl.zig");
const gl3_impl = @import("gl3_impl.zig");
export fn errorCallback(err: c_int, description: [*c]const u8) void {
panic("Error: {}\n", .{description});
}
var rand: std.rand.DefaultPrng = undefined;
fn initRandom() !void {
var buf: [8]u8 = undefined;
try std.crypto.randomBytes(buf[0..]);
const seed = std.mem.readIntLittle(u64, buf[0..8]);
rand = std.rand.DefaultPrng.init(seed);
}
fn rgbColor(col: u32) u32 {
return rgbaColor(((col << 8) | 255));
}
fn rgbaColor(col: u32) u32 {
const a = ((col & 255) << 24);
const b = ((col & 65280) << 8);
const g = ((col & 16711680) >> 8);
const r = ((col & 4278190080) >> 24);
return (r | g | b | a);
}
const Dice = struct {
sides: u32,
color: u32,
color_hovered: u32,
};
const Roll = struct {
roll: u32,
dice: usize,
};
const dice = [_]Dice{ makeDice(2, 13226279), makeDice(4, 2400582), makeDice(6, 2604241), makeDice(8, 9647334), makeDice(10, 14758548), makeDice(12, 14233637), makeDice(20, 15953152), makeDice(100, 8882055) };
fn makeDice(sides: u32, color: u32) Dice {
return .{
.sides = sides,
.color = rgbaColor(((color << 8) | 204)),
.color_hovered = rgbColor(color),
};
}
const max_rolls: usize = 20;
var rolls: [max_rolls]Roll = undefined;
var rolls_len: usize = 0;
fn doRoll() void {
var i: usize = 0;
while ((i < rolls_len)) {
var roll = (&rolls[i]);
const d = dice[roll.dice];
roll.roll = (rand.random.uintLessThan(u32, d.sides) + 1);
i += 1;
}
}
fn render() !void {
c.igSetNextWindowSizeXY(500, 300, c.ImGuiCond_Once);
var p_open = false;
_ = c.igBegin("Dice Roller", (&p_open), c.ImGuiWindowFlags_None);
c.igText("Rolls");
c.igPushIDStr("Rolls buttons");
{
var i: usize = 0;
while ((i < rolls_len)) {
const roll = rolls[i];
const d = dice[roll.dice];
c.igPushIDInt(@intCast(c_int, i));
c.igPushStyleColorU32(c.ImGuiCol_Button, d.color);
c.igPushStyleColorU32(c.ImGuiCol_ButtonHovered, d.color_hovered);
c.igPushStyleColorU32(c.ImGuiCol_ButtonActive, d.color);
var buf: [32]u8 = undefined;
_ = try std.fmt.bufPrint((&buf), "{}", .{roll.roll});
if ((c.igButtonXY((&buf), 50, 50) and (rolls_len > 1))) {
var j: usize = i;
while ((j < (rolls_len - 1))) {
rolls[j] = rolls[(j + 1)];
j += 1;
}
rolls_len -= 1;
}
c.igPopStyleColor(3);
if (((i + 1) < rolls_len)) {
c.igSameLine(0, -1);
}
c.igPopID();
i += 1;
}
}
c.igPopID();
c.igText("Add dice");
c.igPushIDStr("Dice buttons");
for (dice) |d, i| {
c.igPushIDInt(@intCast(c_int, i));
c.igPushStyleColorU32(c.ImGuiCol_Button, d.color);
c.igPushStyleColorU32(c.ImGuiCol_ButtonHovered, d.color_hovered);
c.igPushStyleColorU32(c.ImGuiCol_ButtonActive, d.color);
var buf: [32]u8 = undefined;
_ = try std.fmt.bufPrint((&buf), "{}", .{d.sides});
if (c.igButtonXY((&buf), 50, 50)) {
std.debug.warn("Adding {}: #{}, {}\n", .{ rolls_len, i, d });
if ((rolls_len < max_rolls)) {
rolls[rolls_len] = .{
.roll = (rand.random.uintLessThan(u32, d.sides) + 1),
.dice = i,
};
rolls_len += 1;
}
}
c.igPopStyleColor(3);
if ((i < (dice.len - 1))) {
c.igSameLine(0, -1);
}
c.igPopID();
}
c.igPopID();
{
var total: u32 = 0;
var i: usize = 0;
while ((i < rolls_len)) {
total += rolls[i].roll;
i += 1;
}
var buf: [32]u8 = undefined;
_ = try std.fmt.bufPrint((&buf), "{}", .{total});
c.igText(buf[0..]);
}
if (c.igButtonXY("Roll", 0, 0)) doRoll();
c.igEnd();
}
pub fn main() !void {
try initRandom();
rolls[0] = .{
.roll = 0,
.dice = 2,
};
rolls_len = 1;
doRoll();
_ = c.glfwSetErrorCallback(errorCallback);
if ((c.glfwInit() == c.GL_FALSE)) panic("GLFW init failure\n", .{});
defer c.glfwTerminate();
c.glfwWindowHint(c.GLFW_CONTEXT_VERSION_MAJOR, 3);
c.glfwWindowHint(c.GLFW_CONTEXT_VERSION_MINOR, 2);
c.glfwWindowHint(c.GLFW_OPENGL_FORWARD_COMPAT, c.GL_TRUE);
c.glfwWindowHint(c.GLFW_OPENGL_DEBUG_CONTEXT, debug_gl.is_on);
c.glfwWindowHint(c.GLFW_OPENGL_PROFILE, c.GLFW_OPENGL_CORE_PROFILE);
c.glfwWindowHint(c.GLFW_RESIZABLE, c.GL_TRUE);
const window_width = 640;
const window_height = 480;
const window = (c.glfwCreateWindow(window_width, window_height, "ImGUI Test", null, null) orelse panic("unable to create window \n", .{}));
defer c.glfwDestroyWindow(window);
c.glfwMakeContextCurrent(window);
c.glfwSwapInterval(1);
const context = c.igCreateContext(null);
defer c.igDestroyContext(context);
const io = c.igGetIO();
io.*.ConfigFlags |= c.ImGuiConfigFlags_NavEnableKeyboard;
const style = c.igGetStyle();
c.igStyleColorsDark(style);
glfw_impl.Init(window, true, glfw_impl.ClientApi.OpenGL);
defer glfw_impl.Shutdown();
gl3_impl.Init();
defer gl3_impl.Shutdown();
const start_time = c.glfwGetTime();
var prev_time = start_time;
while ((c.glfwWindowShouldClose(window) == c.GL_FALSE)) {
c.glfwPollEvents();
try gl3_impl.NewFrame();
glfw_impl.NewFrame();
c.igNewFrame();
try render();
c.igRender();
var w: c_int = undefined;
var h: c_int = undefined;
c.glfwGetFramebufferSize(window, (&w), (&h));
c.glViewport(0, 0, w, h);
c.glClearColor(0.0, 0.0, 0.0, 0.0);
c.glClear(c.GL_COLOR_BUFFER_BIT);
gl3_impl.RenderDrawData(c.igGetDrawData());
c.glfwSwapBuffers(window);
}
}
|
examples/imgui-dice-roller/src/main.zig
|
const std = @import("../std.zig");
const builtin = @import("builtin");
const assert = std.debug.assert;
const maxInt = std.math.maxInt;
const elf = std.elf;
const vdso = @import("linux/vdso.zig");
const dl = @import("../dynamic_library.zig");
pub usingnamespace switch (builtin.arch) {
.i386 => @import("linux/i386.zig"),
.x86_64 => @import("linux/x86_64.zig"),
.aarch64 => @import("linux/arm64.zig"),
.arm => @import("linux/arm-eabi.zig"),
.riscv64 => @import("linux/riscv64.zig"),
.mipsel => @import("linux/mipsel.zig"),
else => struct {},
};
pub usingnamespace @import("bits.zig");
pub const tls = @import("linux/tls.zig");
/// Set by startup code, used by `getauxval`.
pub var elf_aux_maybe: ?[*]std.elf.Auxv = null;
/// See `std.elf` for the constants.
pub fn getauxval(index: usize) usize {
const auxv = elf_aux_maybe orelse return 0;
var i: usize = 0;
while (auxv[i].a_type != std.elf.AT_NULL) : (i += 1) {
if (auxv[i].a_type == index)
return auxv[i].a_un.a_val;
}
return 0;
}
/// Get the errno from a syscall return value, or 0 for no error.
pub fn getErrno(r: usize) u12 {
const signed_r = @bitCast(isize, r);
return if (signed_r > -4096 and signed_r < 0) @intCast(u12, -signed_r) else 0;
}
pub fn dup2(old: i32, new: i32) usize {
if (@hasDecl(@This(), "SYS_dup2")) {
return syscall2(SYS_dup2, @bitCast(usize, @as(isize, old)), @bitCast(usize, @as(isize, new)));
} else {
if (old == new) {
if (std.debug.runtime_safety) {
const rc = syscall2(SYS_fcntl, @bitCast(usize, @as(isize, old)), F_GETFD);
if (@bitCast(isize, rc) < 0) return rc;
}
return @intCast(usize, old);
} else {
return syscall3(SYS_dup3, @bitCast(usize, @as(isize, old)), @bitCast(usize, @as(isize, new)), 0);
}
}
}
pub fn dup3(old: i32, new: i32, flags: u32) usize {
return syscall3(SYS_dup3, @bitCast(usize, @as(isize, old)), @bitCast(usize, @as(isize, new)), flags);
}
// TODO https://github.com/ziglang/zig/issues/265
pub fn chdir(path: [*]const u8) usize {
return syscall1(SYS_chdir, @ptrToInt(path));
}
// TODO https://github.com/ziglang/zig/issues/265
pub fn chroot(path: [*]const u8) usize {
return syscall1(SYS_chroot, @ptrToInt(path));
}
// TODO https://github.com/ziglang/zig/issues/265
pub fn execve(path: [*]const u8, argv: [*]const ?[*]const u8, envp: [*]const ?[*]const u8) usize {
return syscall3(SYS_execve, @ptrToInt(path), @ptrToInt(argv), @ptrToInt(envp));
}
pub fn fork() usize {
if (@hasDecl(@This(), "SYS_fork")) {
return syscall0(SYS_fork);
} else {
return syscall2(SYS_clone, SIGCHLD, 0);
}
}
/// This must be inline, and inline call the syscall function, because if the
/// child does a return it will clobber the parent's stack.
/// It is advised to avoid this function and use clone instead, because
/// the compiler is not aware of how vfork affects control flow and you may
/// see different results in optimized builds.
pub inline fn vfork() usize {
return @call(.{ .modifier = .always_inline }, syscall0, .{SYS_vfork});
}
pub fn futimens(fd: i32, times: *const [2]timespec) usize {
return utimensat(fd, null, times, 0);
}
// TODO https://github.com/ziglang/zig/issues/265
pub fn utimensat(dirfd: i32, path: ?[*]const u8, times: *const [2]timespec, flags: u32) usize {
return syscall4(SYS_utimensat, @bitCast(usize, @as(isize, dirfd)), @ptrToInt(path), @ptrToInt(times), flags);
}
pub fn futex_wait(uaddr: *const i32, futex_op: u32, val: i32, timeout: ?*timespec) usize {
return syscall4(SYS_futex, @ptrToInt(uaddr), futex_op, @bitCast(u32, val), @ptrToInt(timeout));
}
pub fn futex_wake(uaddr: *const i32, futex_op: u32, val: i32) usize {
return syscall3(SYS_futex, @ptrToInt(uaddr), futex_op, @bitCast(u32, val));
}
pub fn getcwd(buf: [*]u8, size: usize) usize {
return syscall2(SYS_getcwd, @ptrToInt(buf), size);
}
pub fn getdents(fd: i32, dirp: [*]u8, len: usize) usize {
return syscall3(
SYS_getdents,
@bitCast(usize, @as(isize, fd)),
@ptrToInt(dirp),
std.math.min(len, maxInt(c_int)),
);
}
pub fn getdents64(fd: i32, dirp: [*]u8, len: usize) usize {
return syscall3(
SYS_getdents64,
@bitCast(usize, @as(isize, fd)),
@ptrToInt(dirp),
std.math.min(len, maxInt(c_int)),
);
}
pub fn inotify_init1(flags: u32) usize {
return syscall1(SYS_inotify_init1, flags);
}
pub fn inotify_add_watch(fd: i32, pathname: [*]const u8, mask: u32) usize {
return syscall3(SYS_inotify_add_watch, @bitCast(usize, @as(isize, fd)), @ptrToInt(pathname), mask);
}
pub fn inotify_rm_watch(fd: i32, wd: i32) usize {
return syscall2(SYS_inotify_rm_watch, @bitCast(usize, @as(isize, fd)), @bitCast(usize, @as(isize, wd)));
}
// TODO https://github.com/ziglang/zig/issues/265
pub fn readlink(noalias path: [*]const u8, noalias buf_ptr: [*]u8, buf_len: usize) usize {
if (@hasDecl(@This(), "SYS_readlink")) {
return syscall3(SYS_readlink, @ptrToInt(path), @ptrToInt(buf_ptr), buf_len);
} else {
return syscall4(SYS_readlinkat, @bitCast(usize, @as(isize, AT_FDCWD)), @ptrToInt(path), @ptrToInt(buf_ptr), buf_len);
}
}
// TODO https://github.com/ziglang/zig/issues/265
pub fn readlinkat(dirfd: i32, noalias path: [*]const u8, noalias buf_ptr: [*]u8, buf_len: usize) usize {
return syscall4(SYS_readlinkat, @bitCast(usize, @as(isize, dirfd)), @ptrToInt(path), @ptrToInt(buf_ptr), buf_len);
}
// TODO https://github.com/ziglang/zig/issues/265
pub fn mkdir(path: [*]const u8, mode: u32) usize {
if (@hasDecl(@This(), "SYS_mkdir")) {
return syscall2(SYS_mkdir, @ptrToInt(path), mode);
} else {
return syscall3(SYS_mkdirat, @bitCast(usize, @as(isize, AT_FDCWD)), @ptrToInt(path), mode);
}
}
// TODO https://github.com/ziglang/zig/issues/265
pub fn mkdirat(dirfd: i32, path: [*]const u8, mode: u32) usize {
return syscall3(SYS_mkdirat, @bitCast(usize, @as(isize, dirfd)), @ptrToInt(path), mode);
}
// TODO https://github.com/ziglang/zig/issues/265
pub fn mount(special: [*]const u8, dir: [*]const u8, fstype: [*]const u8, flags: u32, data: usize) usize {
return syscall5(SYS_mount, @ptrToInt(special), @ptrToInt(dir), @ptrToInt(fstype), flags, data);
}
// TODO https://github.com/ziglang/zig/issues/265
pub fn umount(special: [*]const u8) usize {
return syscall2(SYS_umount2, @ptrToInt(special), 0);
}
// TODO https://github.com/ziglang/zig/issues/265
pub fn umount2(special: [*]const u8, flags: u32) usize {
return syscall2(SYS_umount2, @ptrToInt(special), flags);
}
pub fn mmap(address: ?[*]u8, length: usize, prot: usize, flags: u32, fd: i32, offset: u64) usize {
if (@hasDecl(@This(), "SYS_mmap2")) {
// Make sure the offset is also specified in multiples of page size
if ((offset & (MMAP2_UNIT - 1)) != 0)
return @bitCast(usize, @as(isize, -EINVAL));
return syscall6(
SYS_mmap2,
@ptrToInt(address),
length,
prot,
flags,
@bitCast(usize, @as(isize, fd)),
@truncate(usize, offset / MMAP2_UNIT),
);
} else {
return syscall6(
SYS_mmap,
@ptrToInt(address),
length,
prot,
flags,
@bitCast(usize, @as(isize, fd)),
offset,
);
}
}
pub fn mprotect(address: [*]const u8, length: usize, protection: usize) usize {
return syscall3(SYS_mprotect, @ptrToInt(address), length, protection);
}
pub fn munmap(address: [*]const u8, length: usize) usize {
return syscall2(SYS_munmap, @ptrToInt(address), length);
}
pub fn poll(fds: [*]pollfd, n: nfds_t, timeout: i32) usize {
if (@hasDecl(@This(), "SYS_poll")) {
return syscall3(SYS_poll, @ptrToInt(fds), n, @bitCast(u32, timeout));
} else {
return syscall6(
SYS_ppoll,
@ptrToInt(fds),
n,
@ptrToInt(if (timeout >= 0)
×pec{
.tv_sec = @divTrunc(timeout, 1000),
.tv_nsec = @rem(timeout, 1000) * 1000000,
}
else
null),
0,
0,
NSIG / 8,
);
}
}
pub fn read(fd: i32, buf: [*]u8, count: usize) usize {
return syscall3(SYS_read, @bitCast(usize, @as(isize, fd)), @ptrToInt(buf), count);
}
pub fn preadv(fd: i32, iov: [*]const iovec, count: usize, offset: u64) usize {
return syscall5(
SYS_preadv,
@bitCast(usize, @as(isize, fd)),
@ptrToInt(iov),
count,
@truncate(usize, offset),
@truncate(usize, offset >> 32),
);
}
pub fn preadv2(fd: i32, iov: [*]const iovec, count: usize, offset: u64, flags: kernel_rwf) usize {
return syscall6(
SYS_preadv2,
@bitCast(usize, @as(isize, fd)),
@ptrToInt(iov),
count,
@truncate(usize, offset),
@truncate(usize, offset >> 32),
flags,
);
}
pub fn readv(fd: i32, iov: [*]const iovec, count: usize) usize {
return syscall3(SYS_readv, @bitCast(usize, @as(isize, fd)), @ptrToInt(iov), count);
}
pub fn writev(fd: i32, iov: [*]const iovec_const, count: usize) usize {
return syscall3(SYS_writev, @bitCast(usize, @as(isize, fd)), @ptrToInt(iov), count);
}
pub fn pwritev(fd: i32, iov: [*]const iovec_const, count: usize, offset: u64) usize {
return syscall5(
SYS_pwritev,
@bitCast(usize, @as(isize, fd)),
@ptrToInt(iov),
count,
@truncate(usize, offset),
@truncate(usize, offset >> 32),
);
}
pub fn pwritev2(fd: i32, iov: [*]const iovec_const, count: usize, offset: u64, flags: kernel_rwf) usize {
return syscall6(
SYS_pwritev2,
@bitCast(usize, @as(isize, fd)),
@ptrToInt(iov),
count,
@truncate(usize, offset),
@truncate(usize, offset >> 32),
flags,
);
}
// TODO https://github.com/ziglang/zig/issues/265
pub fn rmdir(path: [*]const u8) usize {
if (@hasDecl(@This(), "SYS_rmdir")) {
return syscall1(SYS_rmdir, @ptrToInt(path));
} else {
return syscall3(SYS_unlinkat, @bitCast(usize, @as(isize, AT_FDCWD)), @ptrToInt(path), AT_REMOVEDIR);
}
}
// TODO https://github.com/ziglang/zig/issues/265
pub fn symlink(existing: [*]const u8, new: [*]const u8) usize {
if (@hasDecl(@This(), "SYS_symlink")) {
return syscall2(SYS_symlink, @ptrToInt(existing), @ptrToInt(new));
} else {
return syscall3(SYS_symlinkat, @ptrToInt(existing), @bitCast(usize, @as(isize, AT_FDCWD)), @ptrToInt(new));
}
}
// TODO https://github.com/ziglang/zig/issues/265
pub fn symlinkat(existing: [*]const u8, newfd: i32, newpath: [*]const u8) usize {
return syscall3(SYS_symlinkat, @ptrToInt(existing), @bitCast(usize, @as(isize, newfd)), @ptrToInt(newpath));
}
// TODO https://github.com/ziglang/zig/issues/265
pub fn pread(fd: i32, buf: [*]u8, count: usize, offset: usize) usize {
return syscall4(SYS_pread, @bitCast(usize, @as(isize, fd)), @ptrToInt(buf), count, offset);
}
// TODO https://github.com/ziglang/zig/issues/265
pub fn access(path: [*]const u8, mode: u32) usize {
if (@hasDecl(@This(), "SYS_access")) {
return syscall2(SYS_access, @ptrToInt(path), mode);
} else {
return syscall4(SYS_faccessat, @bitCast(usize, @as(isize, AT_FDCWD)), @ptrToInt(path), mode, 0);
}
}
// TODO https://github.com/ziglang/zig/issues/265
pub fn faccessat(dirfd: i32, path: [*]const u8, mode: u32, flags: u32) usize {
return syscall4(SYS_faccessat, @bitCast(usize, @as(isize, dirfd)), @ptrToInt(path), mode, flags);
}
pub fn pipe(fd: *[2]i32) usize {
if (builtin.arch == .mipsel) {
return syscall_pipe(fd);
} else if (@hasDecl(@This(), "SYS_pipe")) {
return syscall1(SYS_pipe, @ptrToInt(fd));
} else {
return syscall2(SYS_pipe2, @ptrToInt(fd), 0);
}
}
pub fn pipe2(fd: *[2]i32, flags: u32) usize {
return syscall2(SYS_pipe2, @ptrToInt(fd), flags);
}
pub fn write(fd: i32, buf: [*]const u8, count: usize) usize {
return syscall3(SYS_write, @bitCast(usize, @as(isize, fd)), @ptrToInt(buf), count);
}
pub fn pwrite(fd: i32, buf: [*]const u8, count: usize, offset: usize) usize {
return syscall4(SYS_pwrite, @bitCast(usize, @as(isize, fd)), @ptrToInt(buf), count, offset);
}
// TODO https://github.com/ziglang/zig/issues/265
pub fn rename(old: [*]const u8, new: [*]const u8) usize {
if (@hasDecl(@This(), "SYS_rename")) {
return syscall2(SYS_rename, @ptrToInt(old), @ptrToInt(new));
} else if (@hasDecl(@This(), "SYS_renameat")) {
return syscall4(SYS_renameat, @bitCast(usize, @as(isize, AT_FDCWD)), @ptrToInt(old), @bitCast(usize, @as(isize, AT_FDCWD)), @ptrToInt(new));
} else {
return syscall5(SYS_renameat2, @bitCast(usize, @as(isize, AT_FDCWD)), @ptrToInt(old), @bitCast(usize, @as(isize, AT_FDCWD)), @ptrToInt(new), 0);
}
}
pub fn renameat(oldfd: i32, oldpath: [*]const u8, newfd: i32, newpath: [*]const u8) usize {
if (@hasDecl(@This(), "SYS_renameat")) {
return syscall4(
SYS_renameat,
@bitCast(usize, @as(isize, oldfd)),
@ptrToInt(old),
@bitCast(usize, @as(isize, newfd)),
@ptrToInt(new),
);
} else {
return syscall5(
SYS_renameat2,
@bitCast(usize, @as(isize, oldfd)),
@ptrToInt(old),
@bitCast(usize, @as(isize, newfd)),
@ptrToInt(new),
0,
);
}
}
// TODO https://github.com/ziglang/zig/issues/265
pub fn renameat2(oldfd: i32, oldpath: [*]const u8, newfd: i32, newpath: [*]const u8, flags: u32) usize {
return syscall5(
SYS_renameat2,
@bitCast(usize, @as(isize, oldfd)),
@ptrToInt(oldpath),
@bitCast(usize, @as(isize, newfd)),
@ptrToInt(newpath),
flags,
);
}
// TODO https://github.com/ziglang/zig/issues/265
pub fn open(path: [*]const u8, flags: u32, perm: usize) usize {
if (@hasDecl(@This(), "SYS_open")) {
return syscall3(SYS_open, @ptrToInt(path), flags, perm);
} else {
return syscall4(
SYS_openat,
@bitCast(usize, @as(isize, AT_FDCWD)),
@ptrToInt(path),
flags,
perm,
);
}
}
// TODO https://github.com/ziglang/zig/issues/265
pub fn create(path: [*]const u8, perm: usize) usize {
return syscall2(SYS_creat, @ptrToInt(path), perm);
}
// TODO https://github.com/ziglang/zig/issues/265
pub fn openat(dirfd: i32, path: [*]const u8, flags: u32, mode: usize) usize {
// dirfd could be negative, for example AT_FDCWD is -100
return syscall4(SYS_openat, @bitCast(usize, @as(isize, dirfd)), @ptrToInt(path), flags, mode);
}
/// See also `clone` (from the arch-specific include)
pub fn clone5(flags: usize, child_stack_ptr: usize, parent_tid: *i32, child_tid: *i32, newtls: usize) usize {
return syscall5(SYS_clone, flags, child_stack_ptr, @ptrToInt(parent_tid), @ptrToInt(child_tid), newtls);
}
/// See also `clone` (from the arch-specific include)
pub fn clone2(flags: u32, child_stack_ptr: usize) usize {
return syscall2(SYS_clone, flags, child_stack_ptr);
}
pub fn close(fd: i32) usize {
return syscall1(SYS_close, @bitCast(usize, @as(isize, fd)));
}
/// Can only be called on 32 bit systems. For 64 bit see `lseek`.
pub fn llseek(fd: i32, offset: u64, result: ?*u64, whence: usize) usize {
return syscall5(
SYS__llseek,
@bitCast(usize, @as(isize, fd)),
@truncate(usize, offset >> 32),
@truncate(usize, offset),
@ptrToInt(result),
whence,
);
}
/// Can only be called on 64 bit systems. For 32 bit see `llseek`.
pub fn lseek(fd: i32, offset: i64, whence: usize) usize {
return syscall3(SYS_lseek, @bitCast(usize, @as(isize, fd)), @bitCast(usize, offset), whence);
}
pub fn exit(status: i32) noreturn {
_ = syscall1(SYS_exit, @bitCast(usize, @as(isize, status)));
unreachable;
}
pub fn exit_group(status: i32) noreturn {
_ = syscall1(SYS_exit_group, @bitCast(usize, @as(isize, status)));
unreachable;
}
pub fn getrandom(buf: [*]u8, count: usize, flags: u32) usize {
return syscall3(SYS_getrandom, @ptrToInt(buf), count, flags);
}
pub fn kill(pid: i32, sig: i32) usize {
return syscall2(SYS_kill, @bitCast(usize, @as(isize, pid)), @bitCast(usize, @as(isize, sig)));
}
// TODO https://github.com/ziglang/zig/issues/265
pub fn unlink(path: [*]const u8) usize {
if (@hasDecl(@This(), "SYS_unlink")) {
return syscall1(SYS_unlink, @ptrToInt(path));
} else {
return syscall3(SYS_unlinkat, @bitCast(usize, @as(isize, AT_FDCWD)), @ptrToInt(path), 0);
}
}
// TODO https://github.com/ziglang/zig/issues/265
pub fn unlinkat(dirfd: i32, path: [*]const u8, flags: u32) usize {
return syscall3(SYS_unlinkat, @bitCast(usize, @as(isize, dirfd)), @ptrToInt(path), flags);
}
pub fn waitpid(pid: i32, status: *u32, flags: u32) usize {
return syscall4(SYS_wait4, @bitCast(usize, @as(isize, pid)), @ptrToInt(status), flags, 0);
}
var vdso_clock_gettime = @ptrCast(?*const c_void, init_vdso_clock_gettime);
// We must follow the C calling convention when we call into the VDSO
const vdso_clock_gettime_ty = extern fn (i32, *timespec) usize;
pub fn clock_gettime(clk_id: i32, tp: *timespec) usize {
if (@hasDecl(@This(), "VDSO_CGT_SYM")) {
const ptr = @atomicLoad(?*const c_void, &vdso_clock_gettime, .Unordered);
if (ptr) |fn_ptr| {
const f = @ptrCast(vdso_clock_gettime_ty, fn_ptr);
const rc = f(clk_id, tp);
switch (rc) {
0, @bitCast(usize, @as(isize, -EINVAL)) => return rc,
else => {},
}
}
}
return syscall2(SYS_clock_gettime, @bitCast(usize, @as(isize, clk_id)), @ptrToInt(tp));
}
extern fn init_vdso_clock_gettime(clk: i32, ts: *timespec) usize {
const ptr = @intToPtr(?*const c_void, vdso.lookup(VDSO_CGT_VER, VDSO_CGT_SYM));
// Note that we may not have a VDSO at all, update the stub address anyway
// so that clock_gettime will fall back on the good old (and slow) syscall
@atomicStore(?*const c_void, &vdso_clock_gettime, ptr, .Monotonic);
// Call into the VDSO if available
if (ptr) |fn_ptr| {
const f = @ptrCast(vdso_clock_gettime_ty, fn_ptr);
return f(clk, ts);
}
return @bitCast(usize, @as(isize, -ENOSYS));
}
pub fn clock_getres(clk_id: i32, tp: *timespec) usize {
return syscall2(SYS_clock_getres, @bitCast(usize, @as(isize, clk_id)), @ptrToInt(tp));
}
pub fn clock_settime(clk_id: i32, tp: *const timespec) usize {
return syscall2(SYS_clock_settime, @bitCast(usize, @as(isize, clk_id)), @ptrToInt(tp));
}
pub fn gettimeofday(tv: *timeval, tz: *timezone) usize {
return syscall2(SYS_gettimeofday, @ptrToInt(tv), @ptrToInt(tz));
}
pub fn settimeofday(tv: *const timeval, tz: *const timezone) usize {
return syscall2(SYS_settimeofday, @ptrToInt(tv), @ptrToInt(tz));
}
pub fn nanosleep(req: *const timespec, rem: ?*timespec) usize {
return syscall2(SYS_nanosleep, @ptrToInt(req), @ptrToInt(rem));
}
pub fn setuid(uid: u32) usize {
if (@hasDecl(@This(), "SYS_setuid32")) {
return syscall1(SYS_setuid32, uid);
} else {
return syscall1(SYS_setuid, uid);
}
}
pub fn setgid(gid: u32) usize {
if (@hasDecl(@This(), "SYS_setgid32")) {
return syscall1(SYS_setgid32, gid);
} else {
return syscall1(SYS_setgid, gid);
}
}
pub fn setreuid(ruid: u32, euid: u32) usize {
if (@hasDecl(@This(), "SYS_setreuid32")) {
return syscall2(SYS_setreuid32, ruid, euid);
} else {
return syscall2(SYS_setreuid, ruid, euid);
}
}
pub fn setregid(rgid: u32, egid: u32) usize {
if (@hasDecl(@This(), "SYS_setregid32")) {
return syscall2(SYS_setregid32, rgid, egid);
} else {
return syscall2(SYS_setregid, rgid, egid);
}
}
pub fn getuid() u32 {
if (@hasDecl(@This(), "SYS_getuid32")) {
return @as(u32, syscall0(SYS_getuid32));
} else {
return @as(u32, syscall0(SYS_getuid));
}
}
pub fn getgid() u32 {
if (@hasDecl(@This(), "SYS_getgid32")) {
return @as(u32, syscall0(SYS_getgid32));
} else {
return @as(u32, syscall0(SYS_getgid));
}
}
pub fn geteuid() u32 {
if (@hasDecl(@This(), "SYS_geteuid32")) {
return @as(u32, syscall0(SYS_geteuid32));
} else {
return @as(u32, syscall0(SYS_geteuid));
}
}
pub fn getegid() u32 {
if (@hasDecl(@This(), "SYS_getegid32")) {
return @as(u32, syscall0(SYS_getegid32));
} else {
return @as(u32, syscall0(SYS_getegid));
}
}
pub fn seteuid(euid: u32) usize {
return setreuid(std.math.maxInt(u32), euid);
}
pub fn setegid(egid: u32) usize {
return setregid(std.math.maxInt(u32), egid);
}
pub fn getresuid(ruid: *u32, euid: *u32, suid: *u32) usize {
if (@hasDecl(@This(), "SYS_getresuid32")) {
return syscall3(SYS_getresuid32, @ptrToInt(ruid), @ptrToInt(euid), @ptrToInt(suid));
} else {
return syscall3(SYS_getresuid, @ptrToInt(ruid), @ptrToInt(euid), @ptrToInt(suid));
}
}
pub fn getresgid(rgid: *u32, egid: *u32, sgid: *u32) usize {
if (@hasDecl(@This(), "SYS_getresgid32")) {
return syscall3(SYS_getresgid32, @ptrToInt(rgid), @ptrToInt(egid), @ptrToInt(sgid));
} else {
return syscall3(SYS_getresgid, @ptrToInt(rgid), @ptrToInt(egid), @ptrToInt(sgid));
}
}
pub fn setresuid(ruid: u32, euid: u32, suid: u32) usize {
if (@hasDecl(@This(), "SYS_setresuid32")) {
return syscall3(SYS_setresuid32, ruid, euid, suid);
} else {
return syscall3(SYS_setresuid, ruid, euid, suid);
}
}
pub fn setresgid(rgid: u32, egid: u32, sgid: u32) usize {
if (@hasDecl(@This(), "SYS_setresgid32")) {
return syscall3(SYS_setresgid32, rgid, egid, sgid);
} else {
return syscall3(SYS_setresgid, rgid, egid, sgid);
}
}
pub fn getgroups(size: usize, list: *u32) usize {
if (@hasDecl(@This(), "SYS_getgroups32")) {
return syscall2(SYS_getgroups32, size, @ptrToInt(list));
} else {
return syscall2(SYS_getgroups, size, @ptrToInt(list));
}
}
pub fn setgroups(size: usize, list: *const u32) usize {
if (@hasDecl(@This(), "SYS_setgroups32")) {
return syscall2(SYS_setgroups32, size, @ptrToInt(list));
} else {
return syscall2(SYS_setgroups, size, @ptrToInt(list));
}
}
pub fn getpid() i32 {
return @bitCast(i32, @truncate(u32, syscall0(SYS_getpid)));
}
pub fn gettid() i32 {
return @bitCast(i32, @truncate(u32, syscall0(SYS_gettid)));
}
pub fn sigprocmask(flags: u32, noalias set: *const sigset_t, noalias oldset: ?*sigset_t) usize {
return syscall4(SYS_rt_sigprocmask, flags, @ptrToInt(set), @ptrToInt(oldset), NSIG / 8);
}
pub fn sigaction(sig: u6, noalias act: *const Sigaction, noalias oact: ?*Sigaction) usize {
assert(sig >= 1);
assert(sig != SIGKILL);
assert(sig != SIGSTOP);
const restorer_fn = if ((act.flags & SA_SIGINFO) != 0) restore_rt else restore;
var ksa = k_sigaction{
.sigaction = act.sigaction,
.flags = act.flags | SA_RESTORER,
.mask = undefined,
.restorer = @ptrCast(extern fn () void, restorer_fn),
};
var ksa_old: k_sigaction = undefined;
const ksa_mask_size = @sizeOf(@TypeOf(ksa_old.mask));
@memcpy(@ptrCast([*]u8, &ksa.mask), @ptrCast([*]const u8, &act.mask), ksa_mask_size);
const result = syscall4(SYS_rt_sigaction, sig, @ptrToInt(&ksa), @ptrToInt(&ksa_old), ksa_mask_size);
const err = getErrno(result);
if (err != 0) {
return result;
}
if (oact) |old| {
old.sigaction = ksa_old.sigaction;
old.flags = @truncate(u32, ksa_old.flags);
@memcpy(@ptrCast([*]u8, &old.mask), @ptrCast([*]const u8, &ksa_old.mask), ksa_mask_size);
}
return 0;
}
pub fn blockAllSignals(set: *sigset_t) void {
_ = syscall4(SYS_rt_sigprocmask, SIG_BLOCK, @ptrToInt(&all_mask), @ptrToInt(set), NSIG / 8);
}
pub fn blockAppSignals(set: *sigset_t) void {
_ = syscall4(SYS_rt_sigprocmask, SIG_BLOCK, @ptrToInt(&app_mask), @ptrToInt(set), NSIG / 8);
}
pub fn restoreSignals(set: *sigset_t) void {
_ = syscall4(SYS_rt_sigprocmask, SIG_SETMASK, @ptrToInt(set), 0, NSIG / 8);
}
pub fn sigaddset(set: *sigset_t, sig: u6) void {
const s = sig - 1;
(set.*)[@intCast(usize, s) / usize.bit_count] |= @intCast(usize, 1) << (s & (usize.bit_count - 1));
}
pub fn sigismember(set: *const sigset_t, sig: u6) bool {
const s = sig - 1;
return ((set.*)[@intCast(usize, s) / usize.bit_count] & (@intCast(usize, 1) << (s & (usize.bit_count - 1)))) != 0;
}
pub fn getsockname(fd: i32, noalias addr: *sockaddr, noalias len: *socklen_t) usize {
if (builtin.arch == .i386) {
return socketcall(SC_getsockname, &[3]usize{ @bitCast(usize, @as(isize, fd)), @ptrToInt(addr), @ptrToInt(len) });
}
return syscall3(SYS_getsockname, @bitCast(usize, @as(isize, fd)), @ptrToInt(addr), @ptrToInt(len));
}
pub fn getpeername(fd: i32, noalias addr: *sockaddr, noalias len: *socklen_t) usize {
if (builtin.arch == .i386) {
return socketcall(SC_getpeername, &[3]usize{ @bitCast(usize, @as(isize, fd)), @ptrToInt(addr), @ptrToInt(len) });
}
return syscall3(SYS_getpeername, @bitCast(usize, @as(isize, fd)), @ptrToInt(addr), @ptrToInt(len));
}
pub fn socket(domain: u32, socket_type: u32, protocol: u32) usize {
if (builtin.arch == .i386) {
return socketcall(SC_socket, &[3]usize{ domain, socket_type, protocol });
}
return syscall3(SYS_socket, domain, socket_type, protocol);
}
pub fn setsockopt(fd: i32, level: u32, optname: u32, optval: [*]const u8, optlen: socklen_t) usize {
if (builtin.arch == .i386) {
return socketcall(SC_setsockopt, &[5]usize{ @bitCast(usize, @as(isize, fd)), level, optname, @ptrToInt(optval), @intCast(usize, optlen) });
}
return syscall5(SYS_setsockopt, @bitCast(usize, @as(isize, fd)), level, optname, @ptrToInt(optval), @intCast(usize, optlen));
}
pub fn getsockopt(fd: i32, level: u32, optname: u32, noalias optval: [*]u8, noalias optlen: *socklen_t) usize {
if (builtin.arch == .i386) {
return socketcall(SC_getsockopt, &[5]usize{ @bitCast(usize, @as(isize, fd)), level, optname, @ptrToInt(optval), @ptrToInt(optlen) });
}
return syscall5(SYS_getsockopt, @bitCast(usize, @as(isize, fd)), level, optname, @ptrToInt(optval), @ptrToInt(optlen));
}
pub fn sendmsg(fd: i32, msg: *msghdr_const, flags: u32) usize {
if (builtin.arch == .i386) {
return socketcall(SC_sendmsg, &[3]usize{ @bitCast(usize, @as(isize, fd)), @ptrToInt(msg), flags });
}
return syscall3(SYS_sendmsg, @bitCast(usize, @as(isize, fd)), @ptrToInt(msg), flags);
}
pub fn sendmmsg(fd: i32, msgvec: [*]mmsghdr_const, vlen: u32, flags: u32) usize {
if (@typeInfo(usize).Int.bits > @typeInfo(@TypeOf(mmsghdr(undefined).msg_len)).Int.bits) {
// workaround kernel brokenness:
// if adding up all iov_len overflows a i32 then split into multiple calls
// see https://www.openwall.com/lists/musl/2014/06/07/5
const kvlen = if (vlen > IOV_MAX) IOV_MAX else vlen; // matches kernel
var next_unsent: usize = 0;
for (msgvec[0..kvlen]) |*msg, i| {
var size: i32 = 0;
const msg_iovlen = @intCast(usize, msg.msg_hdr.msg_iovlen); // kernel side this is treated as unsigned
for (msg.msg_hdr.msg_iov[0..msg_iovlen]) |iov, j| {
if (iov.iov_len > std.math.maxInt(i32) or @addWithOverflow(i32, size, @intCast(i32, iov.iov_len), &size)) {
// batch-send all messages up to the current message
if (next_unsent < i) {
const batch_size = i - next_unsent;
const r = syscall4(SYS_sendmmsg, @bitCast(usize, @as(isize, fd)), @ptrToInt(&msgvec[next_unsent]), batch_size, flags);
if (getErrno(r) != 0) return next_unsent;
if (r < batch_size) return next_unsent + r;
}
// send current message as own packet
const r = sendmsg(fd, &msg.msg_hdr, flags);
if (getErrno(r) != 0) return r;
// Linux limits the total bytes sent by sendmsg to INT_MAX, so this cast is safe.
msg.msg_len = @intCast(u32, r);
next_unsent = i + 1;
break;
}
}
}
if (next_unsent < kvlen or next_unsent == 0) { // want to make sure at least one syscall occurs (e.g. to trigger MSG_EOR)
const batch_size = kvlen - next_unsent;
const r = syscall4(SYS_sendmmsg, @bitCast(usize, @as(isize, fd)), @ptrToInt(&msgvec[next_unsent]), batch_size, flags);
if (getErrno(r) != 0) return r;
return next_unsent + r;
}
return kvlen;
}
return syscall4(SYS_sendmmsg, @bitCast(usize, @as(isize, fd)), @ptrToInt(msgvec), vlen, flags);
}
pub fn connect(fd: i32, addr: *const c_void, len: socklen_t) usize {
if (builtin.arch == .i386) {
return socketcall(SC_connect, &[3]usize{ @bitCast(usize, @as(isize, fd)), @ptrToInt(addr), len });
}
return syscall3(SYS_connect, @bitCast(usize, @as(isize, fd)), @ptrToInt(addr), len);
}
pub fn recvmsg(fd: i32, msg: *msghdr, flags: u32) usize {
if (builtin.arch == .i386) {
return socketcall(SC_recvmsg, &[3]usize{ @bitCast(usize, @as(isize, fd)), @ptrToInt(msg), flags });
}
return syscall3(SYS_recvmsg, @bitCast(usize, @as(isize, fd)), @ptrToInt(msg), flags);
}
pub fn recvfrom(fd: i32, noalias buf: [*]u8, len: usize, flags: u32, noalias addr: ?*sockaddr, noalias alen: ?*socklen_t) usize {
if (builtin.arch == .i386) {
return socketcall(SC_recvfrom, &[6]usize{ @bitCast(usize, @as(isize, fd)), @ptrToInt(buf), len, flags, @ptrToInt(addr), @ptrToInt(alen) });
}
return syscall6(SYS_recvfrom, @bitCast(usize, @as(isize, fd)), @ptrToInt(buf), len, flags, @ptrToInt(addr), @ptrToInt(alen));
}
pub fn shutdown(fd: i32, how: i32) usize {
if (builtin.arch == .i386) {
return socketcall(SC_shutdown, &[2]usize{ @bitCast(usize, @as(isize, fd)), @bitCast(usize, @as(isize, how)) });
}
return syscall2(SYS_shutdown, @bitCast(usize, @as(isize, fd)), @bitCast(usize, @as(isize, how)));
}
pub fn bind(fd: i32, addr: *const sockaddr, len: socklen_t) usize {
if (builtin.arch == .i386) {
return socketcall(SC_bind, &[3]usize{ @bitCast(usize, @as(isize, fd)), @ptrToInt(addr), @intCast(usize, len) });
}
return syscall3(SYS_bind, @bitCast(usize, @as(isize, fd)), @ptrToInt(addr), @intCast(usize, len));
}
pub fn listen(fd: i32, backlog: u32) usize {
if (builtin.arch == .i386) {
return socketcall(SC_listen, &[2]usize{ @bitCast(usize, @as(isize, fd)), backlog });
}
return syscall2(SYS_listen, @bitCast(usize, @as(isize, fd)), backlog);
}
pub fn sendto(fd: i32, buf: [*]const u8, len: usize, flags: u32, addr: ?*const sockaddr, alen: socklen_t) usize {
if (builtin.arch == .i386) {
return socketcall(SC_sendto, &[6]usize{ @bitCast(usize, @as(isize, fd)), @ptrToInt(buf), len, flags, @ptrToInt(addr), @intCast(usize, alen) });
}
return syscall6(SYS_sendto, @bitCast(usize, @as(isize, fd)), @ptrToInt(buf), len, flags, @ptrToInt(addr), @intCast(usize, alen));
}
pub fn socketpair(domain: i32, socket_type: i32, protocol: i32, fd: [2]i32) usize {
if (builtin.arch == .i386) {
return socketcall(SC_socketpair, &[4]usize{ @intCast(usize, domain), @intCast(usize, socket_type), @intCast(usize, protocol), @ptrToInt(&fd[0]) });
}
return syscall4(SYS_socketpair, @intCast(usize, domain), @intCast(usize, socket_type), @intCast(usize, protocol), @ptrToInt(&fd[0]));
}
pub fn accept(fd: i32, noalias addr: *sockaddr, noalias len: *socklen_t) usize {
if (builtin.arch == .i386) {
return socketcall(SC_accept, &[4]usize{ fd, addr, len, 0 });
}
return accept4(fd, addr, len, 0);
}
pub fn accept4(fd: i32, noalias addr: *sockaddr, noalias len: *socklen_t, flags: u32) usize {
if (builtin.arch == .i386) {
return socketcall(SC_accept4, &[4]usize{ @bitCast(usize, @as(isize, fd)), @ptrToInt(addr), @ptrToInt(len), flags });
}
return syscall4(SYS_accept4, @bitCast(usize, @as(isize, fd)), @ptrToInt(addr), @ptrToInt(len), flags);
}
pub fn fstat(fd: i32, stat_buf: *Stat) usize {
if (@hasDecl(@This(), "SYS_fstat64")) {
return syscall2(SYS_fstat64, @bitCast(usize, @as(isize, fd)), @ptrToInt(stat_buf));
} else {
return syscall2(SYS_fstat, @bitCast(usize, @as(isize, fd)), @ptrToInt(stat_buf));
}
}
// TODO https://github.com/ziglang/zig/issues/265
pub fn stat(pathname: [*]const u8, statbuf: *Stat) usize {
if (@hasDecl(@This(), "SYS_stat64")) {
return syscall2(SYS_stat64, @ptrToInt(pathname), @ptrToInt(statbuf));
} else {
return syscall2(SYS_stat, @ptrToInt(pathname), @ptrToInt(statbuf));
}
}
// TODO https://github.com/ziglang/zig/issues/265
pub fn lstat(pathname: [*]const u8, statbuf: *Stat) usize {
if (@hasDecl(@This(), "SYS_lstat64")) {
return syscall2(SYS_lstat64, @ptrToInt(pathname), @ptrToInt(statbuf));
} else {
return syscall2(SYS_lstat, @ptrToInt(pathname), @ptrToInt(statbuf));
}
}
// TODO https://github.com/ziglang/zig/issues/265
pub fn fstatat(dirfd: i32, path: [*]const u8, stat_buf: *Stat, flags: u32) usize {
if (@hasDecl(@This(), "SYS_fstatat64")) {
return syscall4(SYS_fstatat64, @bitCast(usize, @as(isize, dirfd)), @ptrToInt(path), @ptrToInt(stat_buf), flags);
} else {
return syscall4(SYS_fstatat, @bitCast(usize, @as(isize, dirfd)), @ptrToInt(path), @ptrToInt(stat_buf), flags);
}
}
pub fn statx(dirfd: i32, path: [*]const u8, flags: u32, mask: u32, statx_buf: *Statx) usize {
if (@hasDecl(@This(), "SYS_statx")) {
return syscall5(
SYS_statx,
@bitCast(usize, @as(isize, dirfd)),
@ptrToInt(path),
flags,
mask,
@ptrToInt(statx_buf),
);
}
return @bitCast(usize, @as(isize, -ENOSYS));
}
// TODO https://github.com/ziglang/zig/issues/265
pub fn listxattr(path: [*]const u8, list: [*]u8, size: usize) usize {
return syscall3(SYS_listxattr, @ptrToInt(path), @ptrToInt(list), size);
}
// TODO https://github.com/ziglang/zig/issues/265
pub fn llistxattr(path: [*]const u8, list: [*]u8, size: usize) usize {
return syscall3(SYS_llistxattr, @ptrToInt(path), @ptrToInt(list), size);
}
pub fn flistxattr(fd: usize, list: [*]u8, size: usize) usize {
return syscall3(SYS_flistxattr, fd, @ptrToInt(list), size);
}
// TODO https://github.com/ziglang/zig/issues/265
pub fn getxattr(path: [*]const u8, name: [*]const u8, value: [*]u8, size: usize) usize {
return syscall4(SYS_getxattr, @ptrToInt(path), @ptrToInt(name), @ptrToInt(value), size);
}
// TODO https://github.com/ziglang/zig/issues/265
pub fn lgetxattr(path: [*]const u8, name: [*]const u8, value: [*]u8, size: usize) usize {
return syscall4(SYS_lgetxattr, @ptrToInt(path), @ptrToInt(name), @ptrToInt(value), size);
}
// TODO https://github.com/ziglang/zig/issues/265
pub fn fgetxattr(fd: usize, name: [*]const u8, value: [*]u8, size: usize) usize {
return syscall4(SYS_lgetxattr, fd, @ptrToInt(name), @ptrToInt(value), size);
}
// TODO https://github.com/ziglang/zig/issues/265
pub fn setxattr(path: [*]const u8, name: [*]const u8, value: *const void, size: usize, flags: usize) usize {
return syscall5(SYS_setxattr, @ptrToInt(path), @ptrToInt(name), @ptrToInt(value), size, flags);
}
// TODO https://github.com/ziglang/zig/issues/265
pub fn lsetxattr(path: [*]const u8, name: [*]const u8, value: *const void, size: usize, flags: usize) usize {
return syscall5(SYS_lsetxattr, @ptrToInt(path), @ptrToInt(name), @ptrToInt(value), size, flags);
}
// TODO https://github.com/ziglang/zig/issues/265
pub fn fsetxattr(fd: usize, name: [*]const u8, value: *const void, size: usize, flags: usize) usize {
return syscall5(SYS_fsetxattr, fd, @ptrToInt(name), @ptrToInt(value), size, flags);
}
// TODO https://github.com/ziglang/zig/issues/265
pub fn removexattr(path: [*]const u8, name: [*]const u8) usize {
return syscall2(SYS_removexattr, @ptrToInt(path), @ptrToInt(name));
}
// TODO https://github.com/ziglang/zig/issues/265
pub fn lremovexattr(path: [*]const u8, name: [*]const u8) usize {
return syscall2(SYS_lremovexattr, @ptrToInt(path), @ptrToInt(name));
}
// TODO https://github.com/ziglang/zig/issues/265
pub fn fremovexattr(fd: usize, name: [*]const u8) usize {
return syscall2(SYS_fremovexattr, fd, @ptrToInt(name));
}
pub fn sched_yield() usize {
return syscall0(SYS_sched_yield);
}
pub fn sched_getaffinity(pid: i32, size: usize, set: *cpu_set_t) usize {
const rc = syscall3(SYS_sched_getaffinity, @bitCast(usize, @as(isize, pid)), size, @ptrToInt(set));
if (@bitCast(isize, rc) < 0) return rc;
if (rc < size) @memset(@ptrCast([*]u8, set) + rc, 0, size - rc);
return 0;
}
pub fn epoll_create() usize {
return epoll_create1(0);
}
pub fn epoll_create1(flags: usize) usize {
return syscall1(SYS_epoll_create1, flags);
}
pub fn epoll_ctl(epoll_fd: i32, op: u32, fd: i32, ev: ?*epoll_event) usize {
return syscall4(SYS_epoll_ctl, @bitCast(usize, @as(isize, epoll_fd)), @intCast(usize, op), @bitCast(usize, @as(isize, fd)), @ptrToInt(ev));
}
pub fn epoll_wait(epoll_fd: i32, events: [*]epoll_event, maxevents: u32, timeout: i32) usize {
return epoll_pwait(epoll_fd, events, maxevents, timeout, null);
}
pub fn epoll_pwait(epoll_fd: i32, events: [*]epoll_event, maxevents: u32, timeout: i32, sigmask: ?*sigset_t) usize {
return syscall6(
SYS_epoll_pwait,
@bitCast(usize, @as(isize, epoll_fd)),
@ptrToInt(events),
@intCast(usize, maxevents),
@bitCast(usize, @as(isize, timeout)),
@ptrToInt(sigmask),
@sizeOf(sigset_t),
);
}
pub fn eventfd(count: u32, flags: u32) usize {
return syscall2(SYS_eventfd2, count, flags);
}
pub fn timerfd_create(clockid: i32, flags: u32) usize {
return syscall2(SYS_timerfd_create, @bitCast(usize, @as(isize, clockid)), flags);
}
pub const itimerspec = extern struct {
it_interval: timespec,
it_value: timespec,
};
pub fn timerfd_gettime(fd: i32, curr_value: *itimerspec) usize {
return syscall2(SYS_timerfd_gettime, @bitCast(usize, @as(isize, fd)), @ptrToInt(curr_value));
}
pub fn timerfd_settime(fd: i32, flags: u32, new_value: *const itimerspec, old_value: ?*itimerspec) usize {
return syscall4(SYS_timerfd_settime, @bitCast(usize, @as(isize, fd)), flags, @ptrToInt(new_value), @ptrToInt(old_value));
}
pub fn unshare(flags: usize) usize {
return syscall1(SYS_unshare, flags);
}
pub fn capget(hdrp: *cap_user_header_t, datap: *cap_user_data_t) usize {
return syscall2(SYS_capget, @ptrToInt(hdrp), @ptrToInt(datap));
}
pub fn capset(hdrp: *cap_user_header_t, datap: *const cap_user_data_t) usize {
return syscall2(SYS_capset, @ptrToInt(hdrp), @ptrToInt(datap));
}
pub fn sigaltstack(ss: ?*stack_t, old_ss: ?*stack_t) usize {
return syscall2(SYS_sigaltstack, @ptrToInt(ss), @ptrToInt(old_ss));
}
pub fn uname(uts: *utsname) usize {
return syscall1(SYS_uname, @ptrToInt(uts));
}
// XXX: This should be weak
extern const __ehdr_start: elf.Ehdr = undefined;
pub fn dl_iterate_phdr(comptime T: type, callback: extern fn (info: *dl_phdr_info, size: usize, data: ?*T) i32, data: ?*T) isize {
if (builtin.link_libc) {
return std.c.dl_iterate_phdr(@ptrCast(std.c.dl_iterate_phdr_callback, callback), @ptrCast(?*c_void, data));
}
const elf_base = @ptrToInt(&__ehdr_start);
const n_phdr = __ehdr_start.e_phnum;
const phdrs = (@intToPtr([*]elf.Phdr, elf_base + __ehdr_start.e_phoff))[0..n_phdr];
var it = dl.linkmap_iterator(phdrs) catch return 0;
// The executable has no dynamic link segment, create a single entry for
// the whole ELF image
if (it.end()) {
var info = dl_phdr_info{
.dlpi_addr = elf_base,
.dlpi_name = "/proc/self/exe",
.dlpi_phdr = @intToPtr([*]elf.Phdr, elf_base + __ehdr_start.e_phoff),
.dlpi_phnum = __ehdr_start.e_phnum,
};
return callback(&info, @sizeOf(dl_phdr_info), data);
}
// Last return value from the callback function
var last_r: isize = 0;
while (it.next()) |entry| {
var dlpi_phdr: usize = undefined;
var dlpi_phnum: u16 = undefined;
if (entry.l_addr != 0) {
const elf_header = @intToPtr(*elf.Ehdr, entry.l_addr);
dlpi_phdr = entry.l_addr + elf_header.e_phoff;
dlpi_phnum = elf_header.e_phnum;
} else {
// This is the running ELF image
dlpi_phdr = elf_base + __ehdr_start.e_phoff;
dlpi_phnum = __ehdr_start.e_phnum;
}
var info = dl_phdr_info{
.dlpi_addr = entry.l_addr,
.dlpi_name = entry.l_name,
.dlpi_phdr = @intToPtr([*]elf.Phdr, dlpi_phdr),
.dlpi_phnum = dlpi_phnum,
};
last_r = callback(&info, @sizeOf(dl_phdr_info), data);
if (last_r != 0) break;
}
return last_r;
}
pub fn io_uring_setup(entries: u32, p: *io_uring_params) usize {
return syscall2(SYS_io_uring_setup, entries, @ptrToInt(p));
}
pub fn io_uring_enter(fd: i32, to_submit: u32, min_complete: u32, flags: u32, sig: ?*sigset_t) usize {
return syscall6(SYS_io_uring_enter, @bitCast(usize, @as(isize, fd)), to_submit, min_complete, flags, @ptrToInt(sig), NSIG / 8);
}
pub fn io_uring_register(fd: i32, opcode: u32, arg: ?*const c_void, nr_args: u32) usize {
return syscall4(SYS_io_uring_register, @bitCast(usize, @as(isize, fd)), opcode, @ptrToInt(arg), nr_args);
}
test "" {
if (builtin.os == .linux) {
_ = @import("linux/test.zig");
}
}
|
lib/std/os/linux.zig
|
const std = @import("std.zig");
const builtin = @import("builtin");
const time = std.time;
const testing = std.testing;
const assert = std.debug.assert;
const SpinLock = std.SpinLock;
const linux = std.os.linux;
const windows = std.os.windows;
pub const ThreadParker = switch (builtin.os) {
.linux => if (builtin.link_libc) PosixParker else LinuxParker,
.windows => WindowsParker,
else => if (builtin.link_libc) PosixParker else SpinParker,
};
const SpinParker = struct {
pub fn init() SpinParker {
return SpinParker{};
}
pub fn deinit(self: *SpinParker) void {}
pub fn unpark(self: *SpinParker, ptr: *const u32) void {}
pub fn park(self: *SpinParker, ptr: *const u32, expected: u32) void {
var backoff = SpinLock.Backoff.init();
while (@atomicLoad(u32, ptr, .Acquire) == expected)
backoff.yield();
}
};
const LinuxParker = struct {
pub fn init() LinuxParker {
return LinuxParker{};
}
pub fn deinit(self: *LinuxParker) void {}
pub fn unpark(self: *LinuxParker, ptr: *const u32) void {
const rc = linux.futex_wake(@ptrCast(*const i32, ptr), linux.FUTEX_WAKE | linux.FUTEX_PRIVATE_FLAG, 1);
assert(linux.getErrno(rc) == 0);
}
pub fn park(self: *LinuxParker, ptr: *const u32, expected: u32) void {
const value = @intCast(i32, expected);
while (@atomicLoad(u32, ptr, .Acquire) == expected) {
const rc = linux.futex_wait(@ptrCast(*const i32, ptr), linux.FUTEX_WAIT | linux.FUTEX_PRIVATE_FLAG, value, null);
switch (linux.getErrno(rc)) {
0, linux.EAGAIN => return,
linux.EINTR => continue,
linux.EINVAL => unreachable,
else => continue,
}
}
}
};
const WindowsParker = struct {
waiters: u32,
pub fn init() WindowsParker {
return WindowsParker{ .waiters = 0 };
}
pub fn deinit(self: *WindowsParker) void {}
pub fn unpark(self: *WindowsParker, ptr: *const u32) void {
const key = @ptrCast(*const c_void, ptr);
const handle = getEventHandle() orelse return;
var waiting = @atomicLoad(u32, &self.waiters, .Monotonic);
while (waiting != 0) {
waiting = @cmpxchgWeak(u32, &self.waiters, waiting, waiting - 1, .Acquire, .Monotonic) orelse {
const rc = windows.ntdll.NtReleaseKeyedEvent(handle, key, windows.FALSE, null);
assert(rc == 0);
return;
};
}
}
pub fn park(self: *WindowsParker, ptr: *const u32, expected: u32) void {
var spin = SpinLock.Backoff.init();
const ev_handle = getEventHandle();
const key = @ptrCast(*const c_void, ptr);
while (@atomicLoad(u32, ptr, .Monotonic) == expected) {
if (ev_handle) |handle| {
_ = @atomicRmw(u32, &self.waiters, .Add, 1, .Release);
const rc = windows.ntdll.NtWaitForKeyedEvent(handle, key, windows.FALSE, null);
assert(rc == 0);
} else {
spin.yield();
}
}
}
var event_handle = std.lazyInit(windows.HANDLE);
fn getEventHandle() ?windows.HANDLE {
if (event_handle.get()) |handle_ptr|
return handle_ptr.*;
defer event_handle.resolve();
const access_mask = windows.GENERIC_READ | windows.GENERIC_WRITE;
if (windows.ntdll.NtCreateKeyedEvent(&event_handle.data, access_mask, null, 0) != 0)
return null;
return event_handle.data;
}
};
const PosixParker = struct {
cond: c.pthread_cond_t,
mutex: c.pthread_mutex_t,
const c = std.c;
pub fn init() PosixParker {
return PosixParker{
.cond = c.PTHREAD_COND_INITIALIZER,
.mutex = c.PTHREAD_MUTEX_INITIALIZER,
};
}
pub fn deinit(self: *PosixParker) void {
// On dragonfly, the destroy functions return EINVAL if they were initialized statically.
const retm = c.pthread_mutex_destroy(&self.mutex);
assert(retm == 0 or retm == (if (builtin.os == .dragonfly) os.EINVAL else 0));
const retc = c.pthread_cond_destroy(&self.cond);
assert(retc == 0 or retc == (if (builtin.os == .dragonfly) os.EINVAL else 0));
}
pub fn unpark(self: *PosixParker, ptr: *const u32) void {
assert(c.pthread_mutex_lock(&self.mutex) == 0);
defer assert(c.pthread_mutex_unlock(&self.mutex) == 0);
assert(c.pthread_cond_signal(&self.cond) == 0);
}
pub fn park(self: *PosixParker, ptr: *const u32, expected: u32) void {
assert(c.pthread_mutex_lock(&self.mutex) == 0);
defer assert(c.pthread_mutex_unlock(&self.mutex) == 0);
while (@atomicLoad(u32, ptr, .Acquire) == expected)
assert(c.pthread_cond_wait(&self.cond, &self.mutex) == 0);
}
};
test "std.ThreadParker" {
if (builtin.single_threaded)
return error.SkipZigTest;
const Context = struct {
parker: ThreadParker,
data: u32,
fn receiver(self: *@This()) void {
self.parker.park(&self.data, 0); // receives 1
assert(@atomicRmw(u32, &self.data, .Xchg, 2, .SeqCst) == 1); // sends 2
self.parker.unpark(&self.data); // wakes up waiters on 2
self.parker.park(&self.data, 2); // receives 3
assert(@atomicRmw(u32, &self.data, .Xchg, 4, .SeqCst) == 3); // sends 4
self.parker.unpark(&self.data); // wakes up waiters on 4
}
fn sender(self: *@This()) void {
assert(@atomicRmw(u32, &self.data, .Xchg, 1, .SeqCst) == 0); // sends 1
self.parker.unpark(&self.data); // wakes up waiters on 1
self.parker.park(&self.data, 1); // receives 2
assert(@atomicRmw(u32, &self.data, .Xchg, 3, .SeqCst) == 2); // sends 3
self.parker.unpark(&self.data); // wakes up waiters on 3
self.parker.park(&self.data, 3); // receives 4
}
};
var context = Context{
.parker = ThreadParker.init(),
.data = 0,
};
defer context.parker.deinit();
var receiver = try std.Thread.spawn(&context, Context.receiver);
defer receiver.wait();
context.sender();
}
|
lib/std/parker.zig
|
//! A thread-safe resource which supports blocking until signaled.
//! This API is for kernel threads, not evented I/O.
//! This API requires being initialized at runtime, and initialization
//! can fail. Once initialized, the core operations cannot fail.
//! If you need an abstraction that cannot fail to be initialized, see
//! `std.StaticResetEvent`. However if you can handle initialization failure,
//! it is preferred to use `ResetEvent`.
const ResetEvent = @This();
const std = @import("std.zig");
const builtin = std.builtin;
const testing = std.testing;
const assert = std.debug.assert;
const c = std.c;
const os = std.os;
const time = std.time;
impl: Impl,
pub const Impl = if (builtin.single_threaded)
std.StaticResetEvent.DebugEvent
else if (std.Target.current.isDarwin())
DarwinEvent
else if (std.Thread.use_pthreads)
PosixEvent
else
std.StaticResetEvent.AtomicEvent;
pub const InitError = error{SystemResources};
/// After `init`, it is legal to call any other function.
pub fn init(ev: *ResetEvent) InitError!void {
return ev.impl.init();
}
/// This function is not thread-safe.
/// After `deinit`, the only legal function to call is `init`.
pub fn deinit(ev: *ResetEvent) void {
return ev.impl.deinit();
}
/// Sets the event if not already set and wakes up all the threads waiting on
/// the event. It is safe to call `set` multiple times before calling `wait`.
/// However it is illegal to call `set` after `wait` is called until the event
/// is `reset`. This function is thread-safe.
pub fn set(ev: *ResetEvent) void {
return ev.impl.set();
}
/// Resets the event to its original, unset state.
/// This function is *not* thread-safe. It is equivalent to calling
/// `deinit` followed by `init` but without the possibility of failure.
pub fn reset(ev: *ResetEvent) void {
return ev.impl.reset();
}
/// Wait for the event to be set by blocking the current thread.
/// Thread-safe. No spurious wakeups.
/// Upon return from `wait`, the only functions available to be called
/// in `ResetEvent` are `reset` and `deinit`.
pub fn wait(ev: *ResetEvent) void {
return ev.impl.wait();
}
pub const TimedWaitResult = enum { event_set, timed_out };
/// Wait for the event to be set by blocking the current thread.
/// A timeout in nanoseconds can be provided as a hint for how
/// long the thread should block on the unset event before returning
/// `TimedWaitResult.timed_out`.
/// Thread-safe. No precision of timing is guaranteed.
/// Upon return from `wait`, the only functions available to be called
/// in `ResetEvent` are `reset` and `deinit`.
pub fn timedWait(ev: *ResetEvent, timeout_ns: u64) TimedWaitResult {
return ev.impl.timedWait(timeout_ns);
}
/// Apple has decided to not support POSIX semaphores, so we go with a
/// different approach using Grand Central Dispatch. This API is exposed
/// by libSystem so it is guaranteed to be available on all Darwin platforms.
pub const DarwinEvent = struct {
sem: c.dispatch_semaphore_t = undefined,
pub fn init(ev: *DarwinEvent) !void {
ev.* = .{
.sem = c.dispatch_semaphore_create(0) orelse return error.SystemResources,
};
}
pub fn deinit(ev: *DarwinEvent) void {
c.dispatch_release(ev.sem);
ev.* = undefined;
}
pub fn set(ev: *DarwinEvent) void {
// Empirically this returns the numerical value of the semaphore.
_ = c.dispatch_semaphore_signal(ev.sem);
}
pub fn wait(ev: *DarwinEvent) void {
assert(c.dispatch_semaphore_wait(ev.sem, c.DISPATCH_TIME_FOREVER) == 0);
}
pub fn timedWait(ev: *DarwinEvent, timeout_ns: u64) TimedWaitResult {
const t = c.dispatch_time(c.DISPATCH_TIME_NOW, @intCast(i64, timeout_ns));
if (c.dispatch_semaphore_wait(ev.sem, t) != 0) {
return .timed_out;
} else {
return .event_set;
}
}
pub fn reset(ev: *DarwinEvent) void {
// Keep calling until the semaphore goes back down to 0.
while (c.dispatch_semaphore_wait(ev.sem, c.DISPATCH_TIME_NOW) == 0) {}
}
};
/// POSIX semaphores must be initialized at runtime because they are allowed to
/// be implemented as file descriptors, in which case initialization would require
/// a syscall to open the fd.
pub const PosixEvent = struct {
sem: c.sem_t = undefined,
pub fn init(ev: *PosixEvent) !void {
switch (c.getErrno(c.sem_init(&ev.sem, 0, 0))) {
0 => return,
else => return error.SystemResources,
}
}
pub fn deinit(ev: *PosixEvent) void {
assert(c.sem_destroy(&ev.sem) == 0);
ev.* = undefined;
}
pub fn set(ev: *PosixEvent) void {
assert(c.sem_post(&ev.sem) == 0);
}
pub fn wait(ev: *PosixEvent) void {
while (true) {
switch (c.getErrno(c.sem_wait(&ev.sem))) {
0 => return,
c.EINTR => continue,
c.EINVAL => unreachable,
else => unreachable,
}
}
}
pub fn timedWait(ev: *PosixEvent, timeout_ns: u64) TimedWaitResult {
var ts: os.timespec = undefined;
var timeout_abs = timeout_ns;
os.clock_gettime(os.CLOCK_REALTIME, &ts) catch return .timed_out;
timeout_abs += @intCast(u64, ts.tv_sec) * time.ns_per_s;
timeout_abs += @intCast(u64, ts.tv_nsec);
ts.tv_sec = @intCast(@TypeOf(ts.tv_sec), @divFloor(timeout_abs, time.ns_per_s));
ts.tv_nsec = @intCast(@TypeOf(ts.tv_nsec), @mod(timeout_abs, time.ns_per_s));
while (true) {
switch (c.getErrno(c.sem_timedwait(&ev.sem, &ts))) {
0 => return .event_set,
c.EINTR => continue,
c.EINVAL => unreachable,
c.ETIMEDOUT => return .timed_out,
else => unreachable,
}
}
}
pub fn reset(ev: *PosixEvent) void {
while (true) {
switch (c.getErrno(c.sem_trywait(&ev.sem))) {
0 => continue, // Need to make it go to zero.
c.EINTR => continue,
c.EINVAL => unreachable,
c.EAGAIN => return, // The semaphore currently has the value zero.
else => unreachable,
}
}
}
};
test "basic usage" {
var event: ResetEvent = undefined;
try event.init();
defer event.deinit();
// test event setting
event.set();
// test event resetting
event.reset();
// test event waiting (non-blocking)
event.set();
event.wait();
event.reset();
event.set();
testing.expectEqual(TimedWaitResult.event_set, event.timedWait(1));
// test cross-thread signaling
if (builtin.single_threaded)
return;
const Context = struct {
const Self = @This();
value: u128,
in: ResetEvent,
out: ResetEvent,
fn init(self: *Self) !void {
self.* = .{
.value = 0,
.in = undefined,
.out = undefined,
};
try self.in.init();
try self.out.init();
}
fn deinit(self: *Self) void {
self.in.deinit();
self.out.deinit();
self.* = undefined;
}
fn sender(self: *Self) void {
// update value and signal input
testing.expect(self.value == 0);
self.value = 1;
self.in.set();
// wait for receiver to update value and signal output
self.out.wait();
testing.expect(self.value == 2);
// update value and signal final input
self.value = 3;
self.in.set();
}
fn receiver(self: *Self) void {
// wait for sender to update value and signal input
self.in.wait();
assert(self.value == 1);
// update value and signal output
self.in.reset();
self.value = 2;
self.out.set();
// wait for sender to update value and signal final input
self.in.wait();
assert(self.value == 3);
}
fn sleeper(self: *Self) void {
self.in.set();
time.sleep(time.ns_per_ms * 2);
self.value = 5;
self.out.set();
}
fn timedWaiter(self: *Self) !void {
self.in.wait();
testing.expectEqual(TimedWaitResult.timed_out, self.out.timedWait(time.ns_per_us));
try self.out.timedWait(time.ns_per_ms * 100);
testing.expect(self.value == 5);
}
};
var context: Context = undefined;
try context.init();
defer context.deinit();
const receiver = try std.Thread.spawn(&context, Context.receiver);
defer receiver.wait();
context.sender();
if (false) {
// I have now observed this fail on macOS, Windows, and Linux.
// https://github.com/ziglang/zig/issues/7009
var timed = Context.init();
defer timed.deinit();
const sleeper = try std.Thread.spawn(&timed, Context.sleeper);
defer sleeper.wait();
try timed.timedWaiter();
}
}
|
lib/std/ResetEvent.zig
|
const std = @import("std.zig");
const builtin = @import("builtin");
const assert = std.debug.assert;
const testing = std.testing;
const os = std.os;
const math = std.math;
pub const epoch = @import("time/epoch.zig");
/// Spurious wakeups are possible and no precision of timing is guaranteed.
pub fn sleep(nanoseconds: u64) void {
// TODO: opting out of async sleeping?
if (std.io.is_async) {
return std.event.Loop.instance.?.sleep(nanoseconds);
}
if (builtin.os.tag == .windows) {
const big_ms_from_ns = nanoseconds / ns_per_ms;
const ms = math.cast(os.windows.DWORD, big_ms_from_ns) catch math.maxInt(os.windows.DWORD);
os.windows.kernel32.Sleep(ms);
return;
}
if (builtin.os.tag == .wasi) {
const w = std.os.wasi;
const userdata: w.userdata_t = 0x0123_45678;
const clock = w.subscription_clock_t{
.id = w.CLOCK.MONOTONIC,
.timeout = nanoseconds,
.precision = 0,
.flags = 0,
};
const in = w.subscription_t{
.userdata = userdata,
.u = w.subscription_u_t{
.tag = w.EVENTTYPE_CLOCK,
.u = w.subscription_u_u_t{
.clock = clock,
},
},
};
var event: w.event_t = undefined;
var nevents: usize = undefined;
_ = w.poll_oneoff(&in, &event, 1, &nevents);
return;
}
const s = nanoseconds / ns_per_s;
const ns = nanoseconds % ns_per_s;
std.os.nanosleep(s, ns);
}
test "sleep" {
sleep(1);
}
/// Get a calendar timestamp, in seconds, relative to UTC 1970-01-01.
/// Precision of timing depends on the hardware and operating system.
/// The return value is signed because it is possible to have a date that is
/// before the epoch.
/// See `std.os.clock_gettime` for a POSIX timestamp.
pub fn timestamp() i64 {
return @divFloor(milliTimestamp(), ms_per_s);
}
/// Get a calendar timestamp, in milliseconds, relative to UTC 1970-01-01.
/// Precision of timing depends on the hardware and operating system.
/// The return value is signed because it is possible to have a date that is
/// before the epoch.
/// See `std.os.clock_gettime` for a POSIX timestamp.
pub fn milliTimestamp() i64 {
return @intCast(i64, @divFloor(nanoTimestamp(), ns_per_ms));
}
/// Get a calendar timestamp, in nanoseconds, relative to UTC 1970-01-01.
/// Precision of timing depends on the hardware and operating system.
/// On Windows this has a maximum granularity of 100 nanoseconds.
/// The return value is signed because it is possible to have a date that is
/// before the epoch.
/// See `std.os.clock_gettime` for a POSIX timestamp.
pub fn nanoTimestamp() i128 {
if (builtin.os.tag == .windows) {
// FileTime has a granularity of 100 nanoseconds and uses the NTFS/Windows epoch,
// which is 1601-01-01.
const epoch_adj = epoch.windows * (ns_per_s / 100);
var ft: os.windows.FILETIME = undefined;
os.windows.kernel32.GetSystemTimeAsFileTime(&ft);
const ft64 = (@as(u64, ft.dwHighDateTime) << 32) | ft.dwLowDateTime;
return @as(i128, @bitCast(i64, ft64) + epoch_adj) * 100;
}
if (builtin.os.tag == .wasi and !builtin.link_libc) {
var ns: os.wasi.timestamp_t = undefined;
const err = os.wasi.clock_time_get(os.wasi.CLOCK.REALTIME, 1, &ns);
assert(err == .SUCCESS);
return ns;
}
var ts: os.timespec = undefined;
os.clock_gettime(os.CLOCK.REALTIME, &ts) catch |err| switch (err) {
error.UnsupportedClock, error.Unexpected => return 0, // "Precision of timing depends on hardware and OS".
};
return (@as(i128, ts.tv_sec) * ns_per_s) + ts.tv_nsec;
}
test "timestamp" {
const margin = ns_per_ms * 50;
const time_0 = milliTimestamp();
sleep(ns_per_ms);
const time_1 = milliTimestamp();
const interval = time_1 - time_0;
try testing.expect(interval > 0);
// Tests should not depend on timings: skip test if outside margin.
if (!(interval < margin)) return error.SkipZigTest;
}
// Divisions of a nanosecond.
pub const ns_per_us = 1000;
pub const ns_per_ms = 1000 * ns_per_us;
pub const ns_per_s = 1000 * ns_per_ms;
pub const ns_per_min = 60 * ns_per_s;
pub const ns_per_hour = 60 * ns_per_min;
pub const ns_per_day = 24 * ns_per_hour;
pub const ns_per_week = 7 * ns_per_day;
// Divisions of a microsecond.
pub const us_per_ms = 1000;
pub const us_per_s = 1000 * us_per_ms;
pub const us_per_min = 60 * us_per_s;
pub const us_per_hour = 60 * us_per_min;
pub const us_per_day = 24 * us_per_hour;
pub const us_per_week = 7 * us_per_day;
// Divisions of a millisecond.
pub const ms_per_s = 1000;
pub const ms_per_min = 60 * ms_per_s;
pub const ms_per_hour = 60 * ms_per_min;
pub const ms_per_day = 24 * ms_per_hour;
pub const ms_per_week = 7 * ms_per_day;
// Divisions of a second.
pub const s_per_min = 60;
pub const s_per_hour = s_per_min * 60;
pub const s_per_day = s_per_hour * 24;
pub const s_per_week = s_per_day * 7;
/// An Instant represents a timestamp with respect to the currently
/// executing program that ticks during suspend and can be used to
/// record elapsed time unlike `nanoTimestamp`.
///
/// It tries to sample the system's fastest and most precise timer available.
/// It also tries to be monotonic, but this is not a guarantee due to OS/hardware bugs.
/// If you need monotonic readings for elapsed time, consider `Timer` instead.
pub const Instant = struct {
timestamp: if (is_posix) os.timespec else u64,
// true if we should use clock_gettime()
const is_posix = switch (builtin.os.tag) {
.wasi => builtin.link_libc,
.windows => false,
else => true,
};
/// Queries the system for the current moment of time as an Instant.
/// This is not guaranteed to be monotonic or steadily increasing, but for most implementations it is.
/// Returns `error.Unsupported` when a suitable clock is not detected.
pub fn now() error{Unsupported}!Instant {
// QPC on windows doesn't fail on >= XP/2000 and includes time suspended.
if (builtin.os.tag == .windows) {
return Instant{ .timestamp = os.windows.QueryPerformanceCounter() };
}
// On WASI without libc, use clock_time_get directly.
if (builtin.os.tag == .wasi and !builtin.link_libc) {
var ns: os.wasi.timestamp_t = undefined;
const rc = os.wasi.clock_time_get(os.wasi.CLOCK.MONOTONIC, 1, &ns);
if (rc != .SUCCESS) return error.Unsupported;
return Instant{ .timestamp = ns };
}
// On darwin, use UPTIME_RAW instead of MONOTONIC as it ticks while suspended.
// On linux, use BOOTTIME instead of MONOTONIC as it ticks while suspended.
// On freebsd derivatives, use MONOTONIC_FAST as currently there's no precision tradeoff.
// On other posix systems, MONOTONIC is generally the fastest and ticks while suspended.
const clock_id = switch (builtin.os.tag) {
.macos, .ios, .tvos, .watchos => os.CLOCK.UPTIME_RAW,
.freebsd, .dragonfly => os.CLOCK.MONOTONIC_FAST,
.linux => os.CLOCK.BOOTTIME,
else => os.CLOCK.MONOTONIC,
};
var ts: os.timespec = undefined;
os.clock_gettime(clock_id, &ts) catch return error.Unsupported;
return Instant{ .timestamp = ts };
}
/// Quickly compares two instances between each other.
pub fn order(self: Instant, other: Instant) std.math.Order {
// windows and wasi timestamps are in u64 which is easily comparible
if (!is_posix) {
return std.math.order(self.timestamp, other.timestamp);
}
var ord = std.math.order(self.timestamp.tv_sec, other.timestamp.tv_sec);
if (ord == .eq) {
ord = std.math.order(self.timestamp.tv_nsec, other.timestamp.tv_nsec);
}
return ord;
}
/// Returns elapsed time in nanoseconds since the `earlier` Instant.
/// This assumes that the `earlier` Instant represents a moment in time before or equal to `self`.
/// This also assumes that the time that has passed between both Instants fits inside a u64 (~585 yrs).
pub fn since(self: Instant, earlier: Instant) u64 {
if (builtin.os.tag == .windows) {
// We don't need to cache QPF as it's internally just a memory read to KUSER_SHARED_DATA
// (a read-only page of info updated and mapped by the kernel to all processes):
// https://docs.microsoft.com/en-us/windows-hardware/drivers/ddi/ntddk/ns-ntddk-kuser_shared_data
// https://www.geoffchappell.com/studies/windows/km/ntoskrnl/inc/api/ntexapi_x/kuser_shared_data/index.htm
const qpc = self.timestamp - earlier.timestamp;
const qpf = os.windows.QueryPerformanceFrequency();
// 10Mhz (1 qpc tick every 100ns) is a common enough QPF value that we can optimize on it.
// https://github.com/microsoft/STL/blob/785143a0c73f030238ef618890fd4d6ae2b3a3a0/stl/inc/chrono#L694-L701
const common_qpf = 10_000_000;
if (qpf == common_qpf) {
return qpc * (ns_per_s / common_qpf);
}
// Convert to ns using fixed point.
const scale = @as(u64, std.time.ns_per_s << 32) / @intCast(u32, qpf);
const result = (@as(u96, qpc) * scale) >> 32;
return @truncate(u64, result);
}
// WASI timestamps are directly in nanoseconds
if (builtin.os.tag == .wasi and !builtin.link_libc) {
return self.timestamp - earlier.timestamp;
}
// Convert timespec diff to ns
const seconds = @intCast(u64, self.timestamp.tv_sec - earlier.timestamp.tv_sec);
const elapsed = (seconds * ns_per_s) + @intCast(u32, self.timestamp.tv_nsec);
return elapsed - @intCast(u32, earlier.timestamp.tv_nsec);
}
};
/// A monotonic, high performance timer.
///
/// Timer.start() is used to initalize the timer
/// and gives the caller an opportunity to check for the existence of a supported clock.
/// Once a supported clock is discovered,
/// it is assumed that it will be available for the duration of the Timer's use.
///
/// Monotonicity is ensured by saturating on the most previous sample.
/// This means that while timings reported are monotonic,
/// they're not guaranteed to tick at a steady rate as this is up to the underlying system.
pub const Timer = struct {
started: Instant,
previous: Instant,
pub const Error = error{TimerUnsupported};
/// Initialize the timer by querying for a supported clock.
/// Returns `error.TimerUnsupported` when such a clock is unavailable.
/// This should only fail in hostile environments such as linux seccomp misuse.
pub fn start() Error!Timer {
const current = Instant.now() catch return error.TimerUnsupported;
return Timer{ .started = current, .previous = current };
}
/// Reads the timer value since start or the last reset in nanoseconds.
pub fn read(self: *Timer) u64 {
const current = self.sample();
return current.since(self.started);
}
/// Resets the timer value to 0/now.
pub fn reset(self: *Timer) void {
const current = self.sample();
self.started = current;
}
/// Returns the current value of the timer in nanoseconds, then resets it.
pub fn lap(self: *Timer) u64 {
const current = self.sample();
defer self.started = current;
return current.since(self.started);
}
/// Returns an Instant sampled at the callsite that is
/// guaranteed to be monotonic with respect to the timer's starting point.
fn sample(self: *Timer) Instant {
const current = Instant.now() catch unreachable;
if (current.order(self.previous) == .gt) {
self.previous = current;
}
return self.previous;
}
};
test "Timer + Instant" {
const margin = ns_per_ms * 150;
var timer = try Timer.start();
sleep(10 * ns_per_ms);
const time_0 = timer.read();
try testing.expect(time_0 > 0);
// Tests should not depend on timings: skip test if outside margin.
if (!(time_0 < margin)) return error.SkipZigTest;
const time_1 = timer.lap();
try testing.expect(time_1 >= time_0);
timer.reset();
try testing.expect(timer.read() < time_1);
}
test {
_ = epoch;
}
|
lib/std/time.zig
|
const Seat = @This();
const std = @import("std");
const log = std.log;
const os = std.os;
const wayland = @import("wayland");
const wl = wayland.client.wl;
const ext = wayland.client.ext;
const xkb = @import("xkbcommon");
const Lock = @import("Lock.zig");
const gpa = std.heap.c_allocator;
lock: *Lock,
name: u32,
wl_seat: *wl.Seat,
wl_pointer: ?*wl.Pointer = null,
wl_keyboard: ?*wl.Keyboard = null,
xkb_state: ?*xkb.State = null,
pub fn init(seat: *Seat, lock: *Lock, name: u32, wl_seat: *wl.Seat) void {
seat.* = .{
.lock = lock,
.name = name,
.wl_seat = wl_seat,
};
wl_seat.setListener(*Seat, seat_listener, seat);
}
pub fn destroy(seat: *Seat) void {
seat.wl_seat.release();
if (seat.wl_pointer) |wl_pointer| wl_pointer.release();
if (seat.wl_keyboard) |wl_keyboard| wl_keyboard.release();
if (seat.xkb_state) |xkb_state| xkb_state.unref();
const node = @fieldParentPtr(std.SinglyLinkedList(Seat).Node, "data", seat);
seat.lock.seats.remove(node);
gpa.destroy(node);
}
fn seat_listener(wl_seat: *wl.Seat, event: wl.Seat.Event, seat: *Seat) void {
switch (event) {
.name => {},
.capabilities => |ev| {
if (ev.capabilities.pointer and seat.wl_pointer == null) {
seat.wl_pointer = wl_seat.getPointer() catch {
log.err("failed to allocate memory for wl_pointer object", .{});
return;
};
seat.wl_pointer.?.setListener(?*anyopaque, pointer_listener, null);
} else if (!ev.capabilities.pointer and seat.wl_pointer != null) {
seat.wl_pointer.?.release();
seat.wl_pointer = null;
}
if (ev.capabilities.keyboard and seat.wl_keyboard == null) {
seat.wl_keyboard = wl_seat.getKeyboard() catch {
log.err("failed to allocate memory for wl_keyboard object", .{});
return;
};
seat.wl_keyboard.?.setListener(*Seat, keyboard_listener, seat);
} else if (!ev.capabilities.keyboard and seat.wl_keyboard != null) {
seat.wl_keyboard.?.release();
seat.wl_keyboard = null;
}
},
}
}
fn pointer_listener(wl_pointer: *wl.Pointer, event: wl.Pointer.Event, _: ?*anyopaque) void {
switch (event) {
.enter => |ev| {
// Hide the cursor when it enters any surface of this client.
wl_pointer.setCursor(ev.serial, null, 0, 0);
},
else => {},
}
}
fn keyboard_listener(_: *wl.Keyboard, event: wl.Keyboard.Event, seat: *Seat) void {
switch (event) {
.enter => {
// It doesn't matter which surface gains keyboard focus or what keys are
// currently pressed. We don't implement key repeat for simiplicity.
},
.leave => {
// There's nothing to do as we don't implement key repeat and
// only care about press events, not release.
},
.keymap => |ev| {
defer os.close(ev.fd);
if (ev.format != .xkb_v1) {
log.err("unsupported keymap format {d}", .{@enumToInt(ev.format)});
return;
}
const keymap_string = os.mmap(null, ev.size, os.PROT.READ, os.MAP.PRIVATE, ev.fd, 0) catch |err| {
log.err("failed to mmap() keymap fd: {s}", .{@errorName(err)});
return;
};
defer os.munmap(keymap_string);
const keymap = xkb.Keymap.newFromBuffer(
seat.lock.xkb_context,
keymap_string.ptr,
// The string is 0 terminated
keymap_string.len - 1,
.text_v1,
.no_flags,
) orelse {
log.err("failed to parse xkb keymap", .{});
return;
};
defer keymap.unref();
const state = xkb.State.new(keymap) orelse {
log.err("failed to create xkb state", .{});
return;
};
defer state.unref();
if (seat.xkb_state) |s| s.unref();
seat.xkb_state = state.ref();
},
.modifiers => |ev| {
if (seat.xkb_state) |xkb_state| {
_ = xkb_state.updateMask(
ev.mods_depressed,
ev.mods_latched,
ev.mods_locked,
0,
0,
ev.group,
);
}
},
.key => |ev| {
if (ev.state != .pressed) return;
if (seat.lock.state == .exiting) return;
const xkb_state = seat.xkb_state orelse return;
const lock = seat.lock;
lock.set_color(.input);
// The wayland protocol gives us an input event code. To convert this to an xkb
// keycode we must add 8.
const keycode = ev.key + 8;
const keysym = xkb_state.keyGetOneSym(keycode);
if (keysym == .NoSymbol) return;
switch (@enumToInt(keysym)) {
xkb.Keysym.Return => {
lock.submit_password();
return;
},
xkb.Keysym.Escape => {
lock.clear_password();
lock.set_color(.init);
return;
},
xkb.Keysym.u => {
const Component = xkb.State.Component;
const ctrl_active = xkb_state.modNameIsActive(
xkb.names.mod.ctrl,
@intToEnum(Component, Component.mods_depressed | Component.mods_latched),
) == 1;
if (ctrl_active) {
lock.clear_password();
lock.set_color(.init);
return;
}
},
else => {},
}
// If key was not handled, write to password buffer
const used = xkb_state.keyGetUtf8(keycode, lock.password.unusedCapacitySlice());
lock.password.resize(lock.password.len + used) catch {
log.err("password exceeds {} byte limit", .{lock.password.capacity()});
};
},
.repeat_info => {},
}
}
|
src/Seat.zig
|
const std = @import("../std.zig");
const utils = std.crypto.utils;
const mem = std.mem;
pub const Poly1305 = struct {
pub const block_length: usize = 16;
pub const mac_length = 16;
pub const key_length = 32;
// constant multiplier (from the secret key)
r: [3]u64,
// accumulated hash
h: [3]u64 = [_]u64{ 0, 0, 0 },
// random number added at the end (from the secret key)
pad: [2]u64,
// how many bytes are waiting to be processed in a partial block
leftover: usize = 0,
// partial block buffer
buf: [block_length]u8 align(16) = undefined,
pub fn init(key: *const [key_length]u8) Poly1305 {
const t0 = mem.readIntLittle(u64, key[0..8]);
const t1 = mem.readIntLittle(u64, key[8..16]);
return Poly1305{
.r = [_]u64{
t0 & 0xffc0fffffff,
((t0 >> 44) | (t1 << 20)) & 0xfffffc0ffff,
((t1 >> 24)) & 0x00ffffffc0f,
},
.pad = [_]u64{
mem.readIntLittle(u64, key[16..24]),
mem.readIntLittle(u64, key[24..32]),
},
};
}
fn blocks(st: *Poly1305, m: []const u8, comptime last: bool) void {
const hibit: u64 = if (last) 0 else 1 << 40;
const r0 = st.r[0];
const r1 = st.r[1];
const r2 = st.r[2];
var h0 = st.h[0];
var h1 = st.h[1];
var h2 = st.h[2];
const s1 = r1 * (5 << 2);
const s2 = r2 * (5 << 2);
var i: usize = 0;
while (i + block_length <= m.len) : (i += block_length) {
// h += m[i]
const t0 = mem.readIntLittle(u64, m[i..][0..8]);
const t1 = mem.readIntLittle(u64, m[i + 8 ..][0..8]);
h0 += @truncate(u44, t0);
h1 += @truncate(u44, (t0 >> 44) | (t1 << 20));
h2 += @truncate(u42, t1 >> 24) | hibit;
// h *= r
const d0 = @as(u128, h0) * r0 + @as(u128, h1) * s2 + @as(u128, h2) * s1;
var d1 = @as(u128, h0) * r1 + @as(u128, h1) * r0 + @as(u128, h2) * s2;
var d2 = @as(u128, h0) * r2 + @as(u128, h1) * r1 + @as(u128, h2) * r0;
// partial reduction
var carry = @intCast(u64, d0 >> 44);
h0 = @truncate(u44, d0);
d1 += carry;
carry = @intCast(u64, d1 >> 44);
h1 = @truncate(u44, d1);
d2 += carry;
carry = @intCast(u64, d2 >> 42);
h2 = @truncate(u42, d2);
h0 += @truncate(u64, carry) * 5;
carry = h0 >> 44;
h0 = @truncate(u44, h0);
h1 += carry;
}
st.h = [_]u64{ h0, h1, h2 };
}
pub fn update(st: *Poly1305, m: []const u8) void {
var mb = m;
// handle leftover
if (st.leftover > 0) {
const want = std.math.min(block_length - st.leftover, mb.len);
const mc = mb[0..want];
for (mc) |x, i| {
st.buf[st.leftover + i] = x;
}
mb = mb[want..];
st.leftover += want;
if (st.leftover < block_length) {
return;
}
st.blocks(&st.buf, false);
st.leftover = 0;
}
// process full blocks
if (mb.len >= block_length) {
const want = mb.len & ~(block_length - 1);
st.blocks(mb[0..want], false);
mb = mb[want..];
}
// store leftover
if (mb.len > 0) {
for (mb) |x, i| {
st.buf[st.leftover + i] = x;
}
st.leftover += mb.len;
}
}
/// Zero-pad to align the next input to the first byte of a block
pub fn pad(st: *Poly1305) void {
if (st.leftover == 0) {
return;
}
var i = st.leftover;
while (i < block_length) : (i += 1) {
st.buf[i] = 0;
}
st.blocks(&st.buf);
st.leftover = 0;
}
pub fn final(st: *Poly1305, out: *[mac_length]u8) void {
if (st.leftover > 0) {
var i = st.leftover;
st.buf[i] = 1;
i += 1;
while (i < block_length) : (i += 1) {
st.buf[i] = 0;
}
st.blocks(&st.buf, true);
}
// fully carry h
var carry = st.h[1] >> 44;
st.h[1] = @truncate(u44, st.h[1]);
st.h[2] += carry;
carry = st.h[2] >> 42;
st.h[2] = @truncate(u42, st.h[2]);
st.h[0] += carry * 5;
carry = st.h[0] >> 44;
st.h[0] = @truncate(u44, st.h[0]);
st.h[1] += carry;
carry = st.h[1] >> 44;
st.h[1] = @truncate(u44, st.h[1]);
st.h[2] += carry;
carry = st.h[2] >> 42;
st.h[2] = @truncate(u42, st.h[2]);
st.h[0] += carry * 5;
carry = st.h[0] >> 44;
st.h[0] = @truncate(u44, st.h[0]);
st.h[1] += carry;
// compute h + -p
var g0 = st.h[0] + 5;
carry = g0 >> 44;
g0 = @truncate(u44, g0);
var g1 = st.h[1] + carry;
carry = g1 >> 44;
g1 = @truncate(u44, g1);
var g2 = st.h[2] + carry -% (1 << 42);
// (hopefully) constant-time select h if h < p, or h + -p if h >= p
const mask = (g2 >> 63) -% 1;
g0 &= mask;
g1 &= mask;
g2 &= mask;
const nmask = ~mask;
st.h[0] = (st.h[0] & nmask) | g0;
st.h[1] = (st.h[1] & nmask) | g1;
st.h[2] = (st.h[2] & nmask) | g2;
// h = (h + pad)
const t0 = st.pad[0];
const t1 = st.pad[1];
st.h[0] += @truncate(u44, t0);
carry = st.h[0] >> 44;
st.h[0] = @truncate(u44, st.h[0]);
st.h[1] += @truncate(u44, (t0 >> 44) | (t1 << 20)) + carry;
carry = st.h[1] >> 44;
st.h[1] = @truncate(u44, st.h[1]);
st.h[2] += @truncate(u42, t1 >> 24) + carry;
st.h[2] = @truncate(u42, st.h[2]);
// mac = h % (2^128)
st.h[0] |= st.h[1] << 44;
st.h[1] = (st.h[1] >> 20) | (st.h[2] << 24);
mem.writeIntLittle(u64, out[0..8], st.h[0]);
mem.writeIntLittle(u64, out[8..16], st.h[1]);
utils.secureZero(u8, @ptrCast([*]u8, st)[0..@sizeOf(Poly1305)]);
}
pub fn create(out: *[mac_length]u8, msg: []const u8, key: *const [key_length]u8) void {
var st = Poly1305.init(key);
st.update(msg);
st.final(out);
}
};
test "poly1305 rfc7439 vector1" {
const expected_mac = "\xa8\x06\x1d\xc1\x30\x51\x36\xc6\xc2\x2b\x8b\xaf\x0c\x01\x27\xa9";
const msg = "Cryptographic Forum Research Group";
const key = <KEY>" ++
"\x01\x03\x80\x8a\xfb\x0d\xb2\xfd\x4a\xbf\xf6\xaf\x41\x49\xf5\x1b";
var mac: [16]u8 = undefined;
Poly1305.create(mac[0..], msg, key);
std.testing.expectEqualSlices(u8, expected_mac, &mac);
}
|
lib/std/crypto/poly1305.zig
|
const std = @import("std");
const mem = std.mem;
const ascii = @import("../../ascii.zig");
const Context = @import("../../Context.zig");
const Self = @This();
context: *Context,
pub fn new(ctx: *Context) Self {
return Self{ .context = ctx };
}
// isDecimal detects all Unicode digits.
pub fn isDecimal(self: Self, cp: u21) !bool {
const decimal = try self.context.getDecimal();
return decimal.isDecimalNumber(cp);
}
// isDigit detects all Unicode digits, which don't include the ASCII digits..
pub fn isDigit(self: Self, cp: u21) !bool {
const digit = try self.context.getDigit();
return digit.isDigit(cp) or (try self.isDecimal(cp));
}
/// isAsciiAlphabetic detects ASCII only letters.
pub fn isAsciiDigit(cp: u21) bool {
return if (cp < 128) ascii.isDigit(@intCast(u8, cp)) else false;
}
// isHex detects the 16 ASCII characters 0-9 A-F, and a-f.
pub fn isHexDigit(self: Self, cp: u21) !bool {
const hex = try self.context.getHex();
return hex.isHexDigit(cp);
}
/// isAsciiHexDigit detects ASCII only hexadecimal digits.
pub fn isAsciiHexDigit(cp: u21) bool {
return if (cp < 128) ascii.isXDigit(@intCast(u8, cp)) else false;
}
/// isNumber covers all Unicode numbers, not just ASII.
pub fn isNumber(self: Self, cp: u21) !bool {
const decimal = try self.context.getDecimal();
const letter_number = try self.context.getLetterNumber();
const other_number = try self.context.getOtherNumber();
return decimal.isDecimalNumber(cp) or letter_number.isLetterNumber(cp) or other_number.isOtherNumber(cp);
}
/// isAsciiNumber detects ASCII only numbers.
pub fn isAsciiNumber(cp: u21) bool {
return if (cp < 128) ascii.isDigit(@intCast(u8, cp)) else false;
}
const expect = std.testing.expect;
test "Component isDecimal" {
var ctx = Context.init(std.testing.allocator);
defer ctx.deinit();
var number = new(&ctx);
var cp: u21 = '0';
while (cp <= '9') : (cp += 1) {
expect(try number.isDecimal(cp));
}
expect(!try number.isDecimal('\u{0003}'));
expect(!try number.isDecimal('A'));
}
test "Component isHexDigit" {
var ctx = Context.init(std.testing.allocator);
defer ctx.deinit();
var number = new(&ctx);
var cp: u21 = '0';
while (cp <= '9') : (cp += 1) {
expect(try number.isHexDigit(cp));
}
expect(!try number.isHexDigit('\u{0003}'));
expect(!try number.isHexDigit('Z'));
}
test "Component isNumber" {
var ctx = Context.init(std.testing.allocator);
defer ctx.deinit();
var number = new(&ctx);
var cp: u21 = '0';
while (cp <= '9') : (cp += 1) {
expect(try number.isNumber(cp));
}
expect(!try number.isNumber('\u{0003}'));
expect(!try number.isNumber('A'));
}
|
src/components/aggregate/Number.zig
|
const std = @import("std");
const builtin = @import("builtin");
const assert = std.debug.assert;
const utils = @import("utils.zig");
const Handles = @import("handles.zig").Handles;
const SparseSet = @import("sparse_set.zig").SparseSet;
const ComponentStorage = @import("component_storage.zig").ComponentStorage;
const Sink = @import("../signals/sink.zig").Sink;
const TypeStore = @import("type_store.zig").TypeStore;
// allow overriding EntityTraits by setting in root via: EntityTraits = EntityTraitsType(.medium);
const root = @import("root");
pub const entity_traits = if (@hasDecl(root, "EntityTraits")) root.EntityTraits.init() else @import("entity.zig").EntityTraits.init();
// setup the Handles type based on the type set in EntityTraits
const EntityHandles = Handles(entity_traits.entity_type, entity_traits.index_type, entity_traits.version_type);
pub const Entity = entity_traits.entity_type;
const BasicView = @import("views.zig").BasicView;
const MultiView = @import("views.zig").MultiView;
const BasicGroup = @import("groups.zig").BasicGroup;
const OwningGroup = @import("groups.zig").OwningGroup;
/// Stores an ArrayList of components. The max amount that can be stored is based on the type below
pub fn Storage(comptime CompT: type) type {
return ComponentStorage(CompT, Entity);
}
/// the registry is the main gateway to all ecs functionality. It assumes all internal allocations will succeed and returns
/// no errors to keep the API clean and because if a component array cant be allocated you've got bigger problems.
pub const Registry = struct {
handles: EntityHandles,
components: std.AutoHashMap(u32, usize),
contexts: std.AutoHashMap(u32, usize),
groups: std.ArrayList(*GroupData),
singletons: TypeStore,
allocator: std.mem.Allocator,
/// internal, persistant data structure to manage the entities in a group
pub const GroupData = struct {
hash: u64,
size: u8,
/// optional. there will be an entity_set for non-owning groups and current for owning
entity_set: SparseSet(Entity) = undefined,
owned: []u32,
include: []u32,
exclude: []u32,
registry: *Registry,
current: usize,
pub fn initPtr(allocator: std.mem.Allocator, registry: *Registry, hash: u64, owned: []u32, include: []u32, exclude: []u32) *GroupData {
// std.debug.assert(std.mem.indexOfAny(u32, owned, include) == null);
// std.debug.assert(std.mem.indexOfAny(u32, owned, exclude) == null);
// std.debug.assert(std.mem.indexOfAny(u32, include, exclude) == null);
var group_data = allocator.create(GroupData) catch unreachable;
group_data.hash = hash;
group_data.size = @intCast(u8, owned.len + include.len + exclude.len);
if (owned.len == 0) {
group_data.entity_set = SparseSet(Entity).init(allocator);
}
group_data.owned = allocator.dupe(u32, owned) catch unreachable;
group_data.include = allocator.dupe(u32, include) catch unreachable;
group_data.exclude = allocator.dupe(u32, exclude) catch unreachable;
group_data.registry = registry;
group_data.current = 0;
return group_data;
}
pub fn deinit(self: *GroupData, allocator: std.mem.Allocator) void {
// only deinit th SparseSet for non-owning groups
if (self.owned.len == 0) {
self.entity_set.deinit();
}
allocator.free(self.owned);
allocator.free(self.include);
allocator.free(self.exclude);
allocator.destroy(self);
}
pub fn maybeValidIf(self: *GroupData, entity: Entity) void {
const isValid: bool = blk: {
for (self.owned) |tid| {
const ptr = self.registry.components.get(tid).?;
if (!@intToPtr(*Storage(u1), ptr).contains(entity))
break :blk false;
}
for (self.include) |tid| {
const ptr = self.registry.components.get(tid).?;
if (!@intToPtr(*Storage(u1), ptr).contains(entity))
break :blk false;
}
for (self.exclude) |tid| {
const ptr = self.registry.components.get(tid).?;
if (@intToPtr(*Storage(u1), ptr).contains(entity))
break :blk false;
}
break :blk true;
};
if (self.owned.len == 0) {
if (isValid and !self.entity_set.contains(entity)) {
self.entity_set.add(entity);
}
} else {
if (isValid) {
const ptr = self.registry.components.get(self.owned[0]).?;
if (!(@intToPtr(*Storage(u1), ptr).set.index(entity) < self.current)) {
for (self.owned) |tid| {
// store.swap hides a safe version that types it correctly
const store_ptr = self.registry.components.get(tid).?;
var store = @intToPtr(*Storage(u1), store_ptr);
store.swap(store.data()[self.current], entity);
}
self.current += 1;
}
}
std.debug.assert(self.owned.len >= 0);
}
}
pub fn discardIf(self: *GroupData, entity: Entity) void {
if (self.owned.len == 0) {
if (self.entity_set.contains(entity)) {
self.entity_set.remove(entity);
}
} else {
const ptr = self.registry.components.get(self.owned[0]).?;
var store = @intToPtr(*Storage(u1), ptr);
if (store.contains(entity) and store.set.index(entity) < self.current) {
self.current -= 1;
for (self.owned) |tid| {
const store_ptr = self.registry.components.get(tid).?;
store = @intToPtr(*Storage(u1), store_ptr);
store.swap(store.data()[self.current], entity);
}
}
}
}
/// finds the insertion point for this group by finding anything in the group family (overlapping owned)
/// and finds the least specialized (based on size). This allows the least specialized to update first
/// which ensures more specialized (ie less matches) will always be swapping inside the bounds of
/// the less specialized groups.
fn findInsertionIndex(self: GroupData, groups: []*GroupData) ?usize {
for (groups) |grp, i| {
var overlapping: u8 = 0;
for (grp.owned) |grp_owned| {
if (std.mem.indexOfScalar(u32, self.owned, grp_owned)) |_| overlapping += 1;
}
if (overlapping > 0 and self.size <= grp.size) return i;
}
return null;
}
// TODO: is this the right logic? Should this return just the previous item in the family or be more specific about
// the group size for the index it returns?
/// for discards, the most specialized group in the family needs to do its discard and swap first. This will ensure
/// as each more specialized group does their discards the entity will always remain outside of the "current" index
/// for all groups in the family.
fn findPreviousIndex(self: GroupData, groups: []*GroupData, index: ?usize) ?usize {
if (groups.len == 0) return null;
// we iterate backwards and either index or groups.len is one tick passed where we want to start
var i = if (index) |ind| ind else groups.len;
if (i > 0) i -= 1;
while (i >= 0) : (i -= 1) {
var overlapping: u8 = 0;
for (groups[i].owned) |grp_owned| {
if (std.mem.indexOfScalar(u32, self.owned, grp_owned)) |_| overlapping += 1;
}
if (overlapping > 0) return i;
if (i == 0) return null;
}
return null;
}
};
pub fn init(allocator: std.mem.Allocator) Registry {
return Registry{
.handles = EntityHandles.init(allocator),
.components = std.AutoHashMap(u32, usize).init(allocator),
.contexts = std.AutoHashMap(u32, usize).init(allocator),
.groups = std.ArrayList(*GroupData).init(allocator),
.singletons = TypeStore.init(allocator),
.allocator = allocator,
};
}
pub fn deinit(self: *Registry) void {
var iter = self.components.valueIterator();
while (iter.next()) |ptr| {
// HACK: we dont know the Type here but we need to call deinit
var storage = @intToPtr(*Storage(u1), ptr.*);
storage.deinit();
}
for (self.groups.items) |grp| {
grp.deinit(self.allocator);
}
self.components.deinit();
self.contexts.deinit();
self.groups.deinit();
self.singletons.deinit();
self.handles.deinit();
}
pub fn assure(self: *Registry, comptime T: type) *Storage(T) {
var type_id = utils.typeId(T);
if (self.components.getEntry(type_id)) |kv| {
return @intToPtr(*Storage(T), kv.value_ptr.*);
}
var comp_set = Storage(T).initPtr(self.allocator);
var comp_set_ptr = @ptrToInt(comp_set);
_ = self.components.put(type_id, comp_set_ptr) catch unreachable;
return comp_set;
}
/// Prepares a pool for the given type if required
pub fn prepare(self: *Registry, comptime T: type) void {
_ = self.assure(T);
}
/// Returns the number of existing components of the given type
pub fn len(self: *Registry, comptime T: type) usize {
return self.assure(T).len();
}
/// Increases the capacity of the registry or of the pools for the given component
pub fn reserve(self: *Registry, comptime T: type, cap: usize) void {
self.assure(T).reserve(cap);
}
/// Direct access to the list of components of a given pool
pub fn raw(self: Registry, comptime T: type) []T {
return self.assure(T).raw();
}
/// Direct access to the list of entities of a given pool
pub fn data(self: Registry, comptime T: type) []Entity {
return self.assure(T).data().*;
}
pub fn valid(self: *Registry, entity: Entity) bool {
return self.handles.alive(entity);
}
/// Returns the entity identifier without the version
pub fn entityId(_: Registry, entity: Entity) Entity {
return entity & entity_traits.entity_mask;
}
/// Returns the version stored along with an entity identifier
pub fn version(_: *Registry, entity: Entity) entity_traits.version_type {
return @truncate(entity_traits.version_type, entity >> entity_traits.entity_shift);
}
/// Creates a new entity and returns it
pub fn create(self: *Registry) Entity {
return self.handles.create();
}
/// Destroys an entity
pub fn destroy(self: *Registry, entity: Entity) void {
assert(self.valid(entity));
self.removeAll(entity);
self.handles.remove(entity) catch unreachable;
}
/// returns an interator that iterates all live entities
pub fn entities(self: Registry) EntityHandles.Iterator {
return self.handles.iterator();
}
pub fn add(self: *Registry, entity: Entity, value: anytype) void {
assert(self.valid(entity));
self.assure(@TypeOf(value)).add(entity, value);
}
/// shortcut for adding raw comptime_int/float without having to @as cast
pub fn addTyped(self: *Registry, comptime T: type, entity: Entity, value: T) void {
self.add(entity, value);
}
/// adds all the component types passed in as zero-initialized values
pub fn addTypes(self: *Registry, entity: Entity, comptime types: anytype) void {
inline for (types) |t| {
self.assure(t).add(entity, std.mem.zeroes(t));
}
}
/// Replaces the given component for an entity
pub fn replace(self: *Registry, entity: Entity, value: anytype) void {
assert(self.valid(entity));
self.assure(@TypeOf(value)).replace(entity, value);
}
/// shortcut for replacing raw comptime_int/float without having to @as cast
pub fn replaceTyped(self: *Registry, comptime T: type, entity: Entity, value: T) void {
self.replace(entity, value);
}
pub fn addOrReplace(self: *Registry, entity: Entity, value: anytype) void {
assert(self.valid(entity));
const store = self.assure(@TypeOf(value));
if (store.tryGet(entity)) |found| {
found.* = value;
} else {
store.add(entity, value);
}
}
/// shortcut for add-or-replace raw comptime_int/float without having to @as cast
pub fn addOrReplaceTyped(self: *Registry, T: type, entity: Entity, value: T) void {
self.addOrReplace(entity, value);
}
/// Removes the given component from an entity
pub fn remove(self: *Registry, comptime T: type, entity: Entity) void {
assert(self.valid(entity));
self.assure(T).remove(entity);
}
pub fn removeIfExists(self: *Registry, comptime T: type, entity: Entity) void {
assert(self.valid(entity));
var store = self.assure(T);
if (store.contains(entity)) {
store.remove(entity);
}
}
/// Removes all the components from an entity and makes it orphaned
pub fn removeAll(self: *Registry, entity: Entity) void {
assert(self.valid(entity));
var iter = self.components.valueIterator();
while (iter.next()) |value| {
// HACK: we dont know the Type here but we need to be able to call methods on the Storage(T)
var store = @intToPtr(*Storage(u1), value.*);
store.removeIfContains(entity);
}
}
pub fn has(self: *Registry, comptime T: type, entity: Entity) bool {
assert(self.valid(entity));
return self.assure(T).set.contains(entity);
}
pub fn get(self: *Registry, comptime T: type, entity: Entity) *T {
assert(self.valid(entity));
return self.assure(T).get(entity);
}
pub fn getConst(self: *Registry, comptime T: type, entity: Entity) T {
assert(self.valid(entity));
return self.assure(T).getConst(entity);
}
/// Returns a reference to the given component for an entity creating it if necessary
pub fn getOrAdd(self: *Registry, comptime T: type, entity: Entity) *T {
if (self.has(T, entity)) return self.get(T, entity);
self.add(T, entity, std.mem.zeros(T));
return self.get(T, type);
}
pub fn tryGet(self: *Registry, comptime T: type, entity: Entity) ?*T {
return self.assure(T).tryGet(entity);
}
/// Returns a Sink object for the given component to add/remove listeners with
pub fn onConstruct(self: *Registry, comptime T: type) Sink(Entity) {
return self.assure(T).onConstruct();
}
/// Returns a Sink object for the given component to add/remove listeners with
pub fn onUpdate(self: *Registry, comptime T: type) Sink(Entity) {
return self.assure(T).onUpdate();
}
/// Returns a Sink object for the given component to add/remove listeners with
pub fn onDestruct(self: *Registry, comptime T: type) Sink(Entity) {
return self.assure(T).onDestruct();
}
/// Binds an object to the context of the registry
pub fn setContext(self: *Registry, context: anytype) void {
std.debug.assert(@typeInfo(@TypeOf(context)) == .Pointer);
var type_id = utils.typeId(@typeInfo(@TypeOf(context)).Pointer.child);
_ = self.contexts.put(type_id, @ptrToInt(context)) catch unreachable;
}
/// Unsets a context variable if it exists
pub fn unsetContext(self: *Registry, comptime T: type) void {
std.debug.assert(@typeInfo(T) != .Pointer);
_ = self.contexts.put(utils.typeId(T), 0) catch unreachable;
}
/// Returns a pointer to an object in the context of the registry
pub fn getContext(self: *Registry, comptime T: type) ?*T {
std.debug.assert(@typeInfo(T) != .Pointer);
return if (self.contexts.get(utils.typeId(T))) |ptr|
return if (ptr > 0) @intToPtr(*T, ptr) else null
else
null;
}
/// provides access to a TypeStore letting you add singleton components to the registry
pub fn singletons(self: Registry) TypeStore {
return self.singletons;
}
pub fn sort(self: *Registry, comptime T: type, comptime lessThan: fn (void, T, T) bool) void {
const comp = self.assure(T);
std.debug.assert(comp.super == 0);
comp.sort(T, lessThan);
}
/// Checks whether the given component belongs to any group. If so, it is not sortable directly.
pub fn sortable(self: *Registry, comptime T: type) bool {
return self.assure(T).super == 0;
}
pub fn view(self: *Registry, comptime includes: anytype, comptime excludes: anytype) ViewType(includes, excludes) {
std.debug.assert(@typeInfo(@TypeOf(includes)) == .Struct);
std.debug.assert(@typeInfo(@TypeOf(excludes)) == .Struct);
std.debug.assert(includes.len > 0);
// just one include so use the optimized BasicView
if (includes.len == 1 and excludes.len == 0)
return BasicView(includes[0]).init(self.assure(includes[0]));
var includes_arr: [includes.len]u32 = undefined;
inline for (includes) |t, i| {
_ = self.assure(t);
includes_arr[i] = utils.typeId(t);
}
var excludes_arr: [excludes.len]u32 = undefined;
inline for (excludes) |t, i| {
_ = self.assure(t);
excludes_arr[i] = utils.typeId(t);
}
return MultiView(includes.len, excludes.len).init(self, includes_arr, excludes_arr);
}
/// returns the Type that a view will be based on the includes and excludes
fn ViewType(comptime includes: anytype, comptime excludes: anytype) type {
if (includes.len == 1 and excludes.len == 0) return BasicView(includes[0]);
return MultiView(includes.len, excludes.len);
}
/// creates an optimized group for iterating components
pub fn group(self: *Registry, comptime owned: anytype, comptime includes: anytype, comptime excludes: anytype) (if (owned.len == 0) BasicGroup else OwningGroup) {
std.debug.assert(@typeInfo(@TypeOf(owned)) == .Struct);
std.debug.assert(@typeInfo(@TypeOf(includes)) == .Struct);
std.debug.assert(@typeInfo(@TypeOf(excludes)) == .Struct);
std.debug.assert(owned.len + includes.len > 0);
std.debug.assert(owned.len + includes.len + excludes.len > 1);
// create a unique hash to identify the group so that we can look it up
const hash = comptime hashGroupTypes(owned, includes, excludes);
for (self.groups.items) |grp| {
if (grp.hash == hash) {
if (owned.len == 0) {
return BasicGroup.init(self, grp);
}
var first_owned = self.assure(owned[0]);
return OwningGroup.init(self, grp, &first_owned.super);
}
}
// gather up all our Types as typeIds
var includes_arr: [includes.len]u32 = undefined;
inline for (includes) |t, i| {
_ = self.assure(t);
includes_arr[i] = utils.typeId(t);
}
var excludes_arr: [excludes.len]u32 = undefined;
inline for (excludes) |t, i| {
_ = self.assure(t);
excludes_arr[i] = utils.typeId(t);
}
var owned_arr: [owned.len]u32 = undefined;
inline for (owned) |t, i| {
_ = self.assure(t);
owned_arr[i] = utils.typeId(t);
}
// we need to create a new GroupData
var new_group_data = GroupData.initPtr(self.allocator, self, hash, owned_arr[0..], includes_arr[0..], excludes_arr[0..]);
// before adding the group we need to do some checks to make sure there arent other owning groups with the same types
if (builtin.mode == .Debug and owned.len > 0) {
for (self.groups.items) |grp| {
if (grp.owned.len == 0) continue;
var overlapping: u8 = 0;
for (grp.owned) |grp_owned| {
if (std.mem.indexOfScalar(u32, &owned_arr, grp_owned)) |_| overlapping += 1;
}
var sz: u8 = overlapping;
for (grp.include) |grp_include| {
if (std.mem.indexOfScalar(u32, &includes_arr, grp_include)) |_| sz += 1;
}
for (grp.exclude) |grp_exclude| {
if (std.mem.indexOfScalar(u32, &excludes_arr, grp_exclude)) |_| sz += 1;
}
const check = overlapping == 0 or ((sz == new_group_data.size) or (sz == grp.size));
std.debug.assert(check);
}
}
var maybe_valid_if: ?*GroupData = null;
var discard_if: ?*GroupData = null;
if (owned.len == 0) {
self.groups.append(new_group_data) catch unreachable;
} else {
// if this is a group in a family, we may need to do an insert so get the insertion index first
const maybe_index = new_group_data.findInsertionIndex(self.groups.items);
// if there is a previous group in this family, we use it for inserting our discardIf calls
if (new_group_data.findPreviousIndex(self.groups.items, maybe_index)) |prev| {
discard_if = self.groups.items[prev];
}
if (maybe_index) |index| {
maybe_valid_if = self.groups.items[index];
self.groups.insert(index, new_group_data) catch unreachable;
} else {
self.groups.append(new_group_data) catch unreachable;
}
// update super on all owned Storages to be the max of size and their current super value
inline for (owned) |t| {
var storage = self.assure(t);
storage.super = std.math.max(storage.super, new_group_data.size);
}
}
// wire up our listeners
inline for (owned) |t| self.onConstruct(t).beforeBound(maybe_valid_if).connectBound(new_group_data, "maybeValidIf");
inline for (includes) |t| self.onConstruct(t).beforeBound(maybe_valid_if).connectBound(new_group_data, "maybeValidIf");
inline for (excludes) |t| self.onDestruct(t).beforeBound(maybe_valid_if).connectBound(new_group_data, "maybeValidIf");
inline for (owned) |t| self.onDestruct(t).beforeBound(discard_if).connectBound(new_group_data, "discardIf");
inline for (includes) |t| self.onDestruct(t).beforeBound(discard_if).connectBound(new_group_data, "discardIf");
inline for (excludes) |t| self.onConstruct(t).beforeBound(discard_if).connectBound(new_group_data, "discardIf");
// pre-fill the GroupData with any existing entitites that match
if (owned.len == 0) {
var view_iter = self.view(owned ++ includes, excludes).iterator();
while (view_iter.next()) |entity| {
new_group_data.entity_set.add(entity);
}
} else {
// we cannot iterate backwards because we want to leave behind valid entities in case of owned types
// ??? why not?
var first_owned_storage = self.assure(owned[0]);
for (first_owned_storage.data()) |entity| {
new_group_data.maybeValidIf(entity);
}
// for(auto *first = std::get<0>(cpools).data(), *last = first + std::get<0>(cpools).size(); first != last; ++first) {
// handler->template maybe_valid_if<std::tuple_element_t<0, std::tuple<std::decay_t<Owned>...>>>(*this, *first);
// }
}
if (owned.len == 0) {
return BasicGroup.init(self, new_group_data);
} else {
var first_owned_storage = self.assure(owned[0]);
return OwningGroup.init(self, new_group_data, &first_owned_storage.super);
}
}
/// given the 3 group Types arrays, generates a (mostly) unique u64 hash. Simultaneously ensures there are no duped types between
/// the 3 groups.
inline fn hashGroupTypes(comptime owned: anytype, comptime includes: anytype, comptime excludes: anytype) u64 {
comptime {
for (owned) |t1| {
for (includes) |t2| {
std.debug.assert(t1 != t2);
for (excludes) |t3| {
std.debug.assert(t1 != t3);
std.debug.assert(t2 != t3);
}
}
}
const owned_str = concatTypes(owned);
const includes_str = concatTypes(includes);
const excludes_str = concatTypes(excludes);
return utils.hashStringFnv(u64, owned_str ++ includes_str ++ excludes_str);
}
}
/// expects a tuple of types. Convertes them to type names, sorts them then concatenates and returns the string.
inline fn concatTypes(comptime types: anytype) []const u8 {
comptime {
if (types.len == 0) return "_";
const impl = struct {
fn asc(_: void, lhs: []const u8, rhs: []const u8) bool {
return std.mem.lessThan(u8, lhs, rhs);
}
};
var names: [types.len][]const u8 = undefined;
for (names) |*name, i| {
name.* = @typeName(types[i]);
}
std.sort.sort([]const u8, &names, {}, impl.asc);
comptime var res: []const u8 = "";
inline for (names) |name| res = res ++ name;
return res;
}
}
};
|
src/ecs/registry.zig
|
const builtin = @import("builtin");
const std = @import("std");
const Builder = std.build.Builder;
const Pkg = std.build.Pkg;
const sokol_build = @import("deps/sokol/build.zig");
const stb_build = @import("deps/stb/build.zig");
const imgui_build = @import("deps/imgui/build.zig");
const filebrowser_build = @import("deps/filebrowser/build.zig");
pub fn build(b: *Builder) void {}
pub fn linkArtifact(b: *Builder, artifact: *std.build.LibExeObjStep, target: std.build.Target, comptime prefix_path: []const u8) void {
sokol_build.linkArtifact(b, artifact, target, prefix_path);
stb_build.linkArtifact(b, artifact, target, prefix_path);
imgui_build.linkArtifact(b, artifact, target, prefix_path);
filebrowser_build.linkArtifact(b, artifact, target, prefix_path);
const sokol = Pkg{
.name = "sokol",
.path = prefix_path ++ "src/deps/sokol/sokol.zig",
};
const stb = Pkg{
.name = "stb",
.path = prefix_path ++ "src/deps/stb/stb.zig",
};
const imgui = Pkg{
.name = "imgui",
.path = prefix_path ++ "src/deps/imgui/imgui.zig",
};
const filebrowser = Pkg{
.name = "filebrowser",
.path = prefix_path ++ "src/deps/filebrowser/filebrowser.zig",
};
const upaya = Pkg{
.name = "upaya",
.path = prefix_path ++ "src/upaya.zig",
.dependencies = &[_]Pkg{ stb, filebrowser, sokol, imgui },
};
// packages exported to userland
artifact.addPackage(upaya);
artifact.addPackage(sokol);
artifact.addPackage(stb);
artifact.addPackage(imgui);
artifact.addPackage(filebrowser);
}
pub fn linkCommandLineArtifact(b: *Builder, artifact: *std.build.LibExeObjStep, target: std.build.Target, comptime prefix_path: []const u8) void {
stb_build.linkArtifact(b, artifact, target, prefix_path);
const stb = Pkg{
.name = "stb",
.path = prefix_path ++ "src/deps/stb/stb.zig",
};
const upaya = Pkg{
.name = "upaya",
.path = prefix_path ++ "src/upaya_cli.zig",
.dependencies = &[_]Pkg{stb},
};
// packages exported to userland
artifact.addPackage(upaya);
artifact.addPackage(stb);
}
// add tests.zig file runnable via "zig build test"
pub fn addTests(b: *Builder, target: std.build.Target) void {
var tst = b.addTest("src/tests.zig");
linkArtifact(b, tst, target, "");
const test_step = b.step("test", "Run tests in tests.zig");
test_step.dependOn(&tst.step);
}
|
src/build.zig
|
//--------------------------------------------------------------------------------
// Section: Types (2)
//--------------------------------------------------------------------------------
pub const CONDITION_TYPE = enum(i32) {
AND_CONDITION = 0,
OR_CONDITION = 1,
NOT_CONDITION = 2,
LEAF_CONDITION = 3,
};
pub const CT_AND_CONDITION = CONDITION_TYPE.AND_CONDITION;
pub const CT_OR_CONDITION = CONDITION_TYPE.OR_CONDITION;
pub const CT_NOT_CONDITION = CONDITION_TYPE.NOT_CONDITION;
pub const CT_LEAF_CONDITION = CONDITION_TYPE.LEAF_CONDITION;
pub const CONDITION_OPERATION = enum(i32) {
IMPLICIT = 0,
EQUAL = 1,
NOTEQUAL = 2,
LESSTHAN = 3,
GREATERTHAN = 4,
LESSTHANOREQUAL = 5,
GREATERTHANOREQUAL = 6,
VALUE_STARTSWITH = 7,
VALUE_ENDSWITH = 8,
VALUE_CONTAINS = 9,
VALUE_NOTCONTAINS = 10,
DOSWILDCARDS = 11,
WORD_EQUAL = 12,
WORD_STARTSWITH = 13,
APPLICATION_SPECIFIC = 14,
};
pub const COP_IMPLICIT = CONDITION_OPERATION.IMPLICIT;
pub const COP_EQUAL = CONDITION_OPERATION.EQUAL;
pub const COP_NOTEQUAL = CONDITION_OPERATION.NOTEQUAL;
pub const COP_LESSTHAN = CONDITION_OPERATION.LESSTHAN;
pub const COP_GREATERTHAN = CONDITION_OPERATION.GREATERTHAN;
pub const COP_LESSTHANOREQUAL = CONDITION_OPERATION.LESSTHANOREQUAL;
pub const COP_GREATERTHANOREQUAL = CONDITION_OPERATION.GREATERTHANOREQUAL;
pub const COP_VALUE_STARTSWITH = CONDITION_OPERATION.VALUE_STARTSWITH;
pub const COP_VALUE_ENDSWITH = CONDITION_OPERATION.VALUE_ENDSWITH;
pub const COP_VALUE_CONTAINS = CONDITION_OPERATION.VALUE_CONTAINS;
pub const COP_VALUE_NOTCONTAINS = CONDITION_OPERATION.VALUE_NOTCONTAINS;
pub const COP_DOSWILDCARDS = CONDITION_OPERATION.DOSWILDCARDS;
pub const COP_WORD_EQUAL = CONDITION_OPERATION.WORD_EQUAL;
pub const COP_WORD_STARTSWITH = CONDITION_OPERATION.WORD_STARTSWITH;
pub const COP_APPLICATION_SPECIFIC = CONDITION_OPERATION.APPLICATION_SPECIFIC;
//--------------------------------------------------------------------------------
// 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 (0)
//--------------------------------------------------------------------------------
test {
@setEvalBranchQuota(
@import("std").meta.declarations(@This()).len * 3
);
// reference all the pub declarations
if (!@import("builtin").is_test) return;
inline for (@import("std").meta.declarations(@This())) |decl| {
if (decl.is_pub) {
_ = decl;
}
}
}
|
win32/system/search/common.zig
|
const std = @import("std");
const assert = std.debug.assert;
const StringTable = @import("./strtab.zig").StringTable;
const allocator = std.testing.allocator;
pub const Map = struct {
bodies: StringTable,
parent: [4096]?usize,
pub fn init() Map {
var self = Map{
.bodies = StringTable.init(allocator),
.parent = undefined,
};
return self;
}
pub fn deinit(self: *Map) void {
self.bodies.deinit();
}
pub fn add_orbit(self: *Map, str: []const u8) void {
var it = std.mem.split(u8, str, ")");
var parent: ?usize = null;
while (it.next()) |what| {
var pos: usize = 0;
if (self.bodies.contains(what)) {
pos = self.bodies.get_pos(what).?;
} else {
pos = self.bodies.add(what);
self.parent[pos] = null;
}
if (parent == null) {
parent = pos;
} else {
const child = pos;
self.parent[child] = parent.?;
// std.debug.warn("PARENT {s} => {s}\n", .{ self.bodies.get_str(child), self.bodies.get_str(parent.?) });
}
}
}
fn inc_orbit(self: *Map, pos: ?usize, distance: usize) usize {
if (pos == null) return 0;
const child = pos.?;
// std.debug.warn("ORBITS {s} {}: +1\n", .{ self.bodies.get_str(child), distance });
const parent = self.parent[child];
return 1 + self.inc_orbit(parent, distance + 1);
}
pub fn count_orbits(self: *Map) usize {
var count: usize = 0;
var j: usize = 0;
while (j < self.bodies.size()) : (j += 1) {
const parent = self.parent[j];
count += self.inc_orbit(parent, 0);
}
return count;
}
pub fn count_hops(self: *Map, a: []const u8, b: []const u8) usize {
var current: usize = self.bodies.get_pos(a).?;
var ha = std.AutoHashMap(usize, usize).init(allocator);
defer ha.deinit();
var count: usize = 0;
while (true) {
const parent = self.parent[current];
if (parent == null) break;
count += 1;
current = parent.?;
// std.debug.warn("HOP A {s} {}\n", .{ self.bodies.get_str(current), count });
_ = ha.put(current, count) catch unreachable;
}
current = self.bodies.get_pos(b).?;
count = 0;
while (true) {
const parent = self.parent[current];
if (parent == null) break;
count += 1;
current = parent.?;
// std.debug.warn("HOP B {s} {}\n", .{ self.bodies.get_str(current), count });
if (ha.contains(current)) {
count += ha.getEntry(current).?.value_ptr.*;
break;
}
}
return count - 2;
}
};
test "total orbit count" {
const data: []const u8 =
\\COM)B
\\B)C
\\C)D
\\D)E
\\E)F
\\B)G
\\G)H
\\D)I
\\E)J
\\J)K
\\K)L
;
var map = Map.init();
defer map.deinit();
var it = std.mem.split(u8, data, "\n");
while (it.next()) |what| {
map.add_orbit(what);
}
const count = map.count_orbits();
assert(count == 42);
}
test "hop count" {
const data: []const u8 =
\\COM)B
\\B)C
\\C)D
\\D)E
\\E)F
\\B)G
\\G)H
\\D)I
\\E)J
\\J)K
\\K)L
\\K)YOU
\\I)SAN
;
var map = Map.init();
defer map.deinit();
var it = std.mem.split(u8, data, "\n");
while (it.next()) |what| {
map.add_orbit(what);
}
const count = map.count_hops("YOU", "SAN");
assert(count == 4);
}
|
2019/p06/map.zig
|
const std = @import("std");
const hasEnv = std.process.hasEnvVarConstant;
pub const CI = enum {
gerrit,
azure_pipelines,
bitrise,
buddy,
buildkite,
cirrus,
gitlab,
appveyor,
circle_ci,
semaphore,
drone,
dsari,
github_actions,
tddium,
strider,
taskcluster,
jenkins,
bamboo,
gocd,
hudson,
wercker,
netlify,
now_github,
now_gitlab,
now_bitbucket,
bitbucket_pipelines,
now,
vercel_github,
vercel_gitlab,
vercel_bitbucket,
vercel,
magnum,
nevercode,
render,
sail,
shippable,
teamcity,
custom,
heroku,
travis_ci,
aws_codebuild,
google_cloud_build,
};
pub fn detect() ?CI {
if (hasEnv("GERRIT_PROJECT")) return .gerrit;
if (hasEnv("SYSTEM_TEAMFOUNDATIONCOLLECTIONURI")) return .azure_pipelines;
if (hasEnv("BITRISE_IO")) return .bitrise;
if (hasEnv("BUDDY_WORKSPACE_ID")) return .buddy;
if (hasEnv("BUILDKITE")) return .buildkite;
if (hasEnv("CIRRUS_CI")) return .cirrus;
if (hasEnv("GITLAB_CI")) return .gitlab;
if (hasEnv("APPVEYOR")) return .appveyor;
if (hasEnv("CIRCLECI")) return .circle_ci;
if (hasEnv("SEMAPHORE")) return .semaphore;
if (hasEnv("DRONE")) return .drone;
if (hasEnv("DSARI")) return .dsari;
if (hasEnv("GITHUB_ACTION")) return .github_actions;
if (hasEnv("TDDIUM")) return .tddium;
if (hasEnv("STRIDER")) return .strider;
if (hasEnv("TASKCLUSTER_ROOT_URL")) return .taskcluster;
if (hasEnv("JENKINS_URL")) return .jenkins;
if (hasEnv("bamboo.buildKey")) return .bamboo;
if (hasEnv("GO_PIPELINE_NAME")) return .gocd;
if (hasEnv("HUDSON_URL")) return .hudson;
if (hasEnv("WERCKER")) return .wercker;
if (hasEnv("NETLIFY")) return .netlify;
if (hasEnv("NOW_GITHUB_DEPLOYMENT")) return .now_github;
if (hasEnv("GITLAB_DEPLOYMENT")) return .now_gitlab; // TODO should this prefixed with NOW_ ?
if (hasEnv("BITBUCKET_DEPLOYMENT")) return .now_bitbucket; // TODO should this be prefixed with NOW_ ?
if (hasEnv("BITBUCKET_BUILD_NUMBER")) return .bitbucket_pipelines;
if (hasEnv("NOW_BUILDER")) return .now;
if (hasEnv("VERCEL_GITHUB_DEPLOYMENT")) return .vercel_github;
if (hasEnv("VERCEL_GITLAB_DEPLOYMENT")) return .vercel_gitlab;
if (hasEnv("VERCEL_BITBUCKET_DEPLOYMENT")) return .vercel_bitbucket;
if (hasEnv("VERCEL")) return .vercel;
if (hasEnv("MAGNUM")) return .magnum;
if (hasEnv("NEVERCODE")) return .nevercode;
if (hasEnv("RENDER")) return .render;
if (hasEnv("SAIL_CI")) return .sail;
if (hasEnv("SHIPPABLE")) return .shippable;
if (hasEnv("TEAMCITY_VERSION")) return .teamcity;
if (hasEnv("CI_NAME")) return .custom;
// TODO this would likely mean we need an allocator in the method :/
// heroku doesn't set envs other than node in a heroku_specific location
// : /\/\.heroku\/node\/bin\/node$/.test(process.env.NODE || '') ? 'heroku'
if (hasEnv("TRAVIS")) return .travis_ci;
if (hasEnv("CODEBUILD_SRC_DIR")) return .aws_codebuild;
if (hasEnv("CI")) return .custom;
if (hasEnv("BUILDER_OUTPUT")) return .google_cloud_build;
return null;
}
|
src/lib.zig
|
/// A set of (micro-) benchmarks for the zig programming language
const std = @import("std");
//const format = std.fmt.format;
//const warn = std.debug.warn;
const print = std.debug.print;
var gpa = std.heap.GeneralPurposeAllocator(.{}){};
const fib = @import("fib.zig");
const perfect = @import("perfect.zig");
const mandel = @import("mandelbrot.zig");
const mc = @import("montecarlo.zig");
/// main entry point
pub fn main() !void {
var timer = try std.time.Timer.start();
const ns_per_ms = std.time.ns_per_s / std.time.ms_per_s;
print("Fibonacci numbers\n", .{});
print("=================\n", .{});
timer.reset();
var res = fib.fib_naive(35);
var elap = timer.read();
print("fib_naive(35) = {} (Elapsed: {d:.3}ms).\n", .{ res, @intToFloat(f32, elap / ns_per_ms) });
timer.reset();
res = try fib.fib(u64, 35);
elap = timer.read();
print("fib(35) = {} (Elapsed: {d:.3}ms).\n", .{ res, @intToFloat(f32, elap / ns_per_ms) });
timer.reset();
res = try fib.fib_iter(u64, 35);
elap = timer.read();
print("fib_iter(35) = {} (Elapsed: {d:.3}ms).\n", .{ res, @intToFloat(f32, elap / ns_per_ms) });
timer.reset();
const res_2 = try fib.fib_iter(u1024, 1000);
elap = timer.read();
print("fib_iter(1000) = {} (Elapsed: {d:.3}ms).\n", .{ 0, @intToFloat(f32, elap / ns_per_ms) });
print("\n", .{});
print("Perfect numbers\n", .{});
print("===============\n", .{});
timer.reset();
const pn_u16 = try perfect.perfect_numbers(u16, &gpa.allocator, 10000);
defer pn_u16.deinit();
elap = timer.read();
const pn_u16_str = try perfect.to_str(u16, &gpa.allocator, pn_u16);
defer pn_u16_str.deinit();
print("perfect_numbers(u16, 10000) = {s} (Elapsed: {d:.3}ms).\n", .{
pn_u16_str.items,
@intToFloat(f32, elap / ns_per_ms),
});
timer.reset();
const pn_u32 = try perfect.perfect_numbers(u32, &gpa.allocator, 10000);
defer pn_u32.deinit();
elap = timer.read();
const pn_u32_str = try perfect.to_str(u32, &gpa.allocator, pn_u32);
defer pn_u32_str.deinit();
print("perfect_numbers(u32, 10000) = {s} (Elapsed: {d:.3}ms).\n", .{
pn_u32_str.items,
@intToFloat(f32, elap / ns_per_ms),
});
timer.reset();
const pn_u64 = try perfect.perfect_numbers(u64, &gpa.allocator, 10000);
defer pn_u64.deinit();
elap = timer.read();
const pn_u64_str = try perfect.to_str(u64, &gpa.allocator, pn_u64);
defer pn_u64_str.deinit();
print("perfect_numbers(u64, 10000) = {s} (Elapsed: {d:.3}ms).\n", .{
pn_u64_str.items,
@intToFloat(f32, elap / ns_per_ms),
});
print("\n", .{});
print("Mandelbrot set\n", .{});
print("==============\n", .{});
timer.reset();
const width = 1920;
const height = 1600;
const img = try mandel.create(&gpa.allocator, width, height, -0.5, 0.0, 4.0 / @intToFloat(f32, width));
defer img.deinit();
elap = timer.read();
print("mandelbrot({}, {}) (Elapsed: {d:.3}ms).\n", .{
width,
height,
@intToFloat(f32, elap / ns_per_ms),
});
timer.reset();
try img.writePPM(&gpa.allocator, "mandelbrot.ppm");
elap = timer.read();
print("mandelbrot({}, {}) written as PPM (Elapsed: {d:.3}ms).\n", .{
width,
height,
@intToFloat(f32, elap / ns_per_ms),
});
timer.reset();
try img.write(&gpa.allocator, "mandelbrot.png");
elap = timer.read();
print("mandelbrot({}, {}) written as PNG (Elapsed: {d:.3}ms).\n", .{
width,
height,
@intToFloat(f32, elap / ns_per_ms),
});
print("\n", .{});
print("Monte-Carlo simulations\n", .{});
print("=======================\n", .{});
const count = 100_000_000;
timer.reset();
const pi_value = mc.simulatePi(count);
elap = timer.read();
print("mc_pi({}) = {} Error: {e:.3} (Elapsed: {d:.3}ms.)\n", .{
count,
pi_value,
std.math.absFloat(pi_value - std.math.pi),
@intToFloat(f32, elap / ns_per_ms),
});
}
test "benchmark" {
_ = @import("fib.zig");
_ = @import("perfect.zig");
_ = @import("image.zig");
_ = @import("mandelbrot.zig");
_ = @import("montecarlo.zig");
}
|
Zig/benchmark/src/main.zig
|
const std = @import("std");
const zs = @import("zstack.zig");
const Coord = zs.Coord;
const Piece = zs.Piece;
const Engine = zs.Engine;
/// Represents a relative rotation that can be applied to a piece.
pub const Rotation = enum(i8) {
Clockwise = 1,
AntiClockwise = -1,
Half = 2,
};
const Wallkick = Coord(i8);
fn wk(comptime x: comptime_int, comptime y: comptime_int) Wallkick {
return Wallkick{ .x = x, .y = y };
}
/// A RotationSystem details the set of blocks that make up each piece per rotation. And, the
/// wallkicks that are applied when a rotation is performed on a piece.
pub const RotationSystem = struct {
id: Id,
pub const Id = enum {
srs,
sega,
dtet,
nes,
ars,
tgm,
tgm3,
};
pub fn init(id: Id) RotationSystem {
return RotationSystem{ .id = id };
}
/// Returns the set of blocks for a piece in the RotationSystem at a given theta.
/// These are always 0-offset, so the caller needs to add any x,y offsets if required.
pub fn blocks(self: RotationSystem, id: Piece.Id, theta: Piece.Theta) Piece.Blocks {
return switch (self.id) {
.srs => SrsRotationSystem.blocks(id, theta),
.sega => SegaRotationSystem.blocks(id, theta),
.dtet => DtetRotationSystem.blocks(id, theta),
.nes => NintendoRotationSystem.blocks(id, theta),
.ars => ArikaSrsRotationSystem.blocks(id, theta),
.tgm => TgmRotationSystem.blocks(id, theta),
.tgm3 => Tgm3RotationSystem.blocks(id, theta),
};
}
/// Attempts to rotation a piece in its current position in the well, applying any number
/// of wallkicks as needed. If successful, true is returned and the pieces position is
/// modified to match.
pub fn rotate(self: RotationSystem, engine: Engine, piece: *Piece, rotation: Rotation) bool {
return switch (self.id) {
.srs => SrsRotationSystem.rotate(engine, piece, rotation),
.sega => SegaRotationSystem.rotate(engine, piece, rotation),
.dtet => DtetRotationSystem.rotate(engine, piece, rotation),
.nes => NintendoRotationSystem.rotate(engine, piece, rotation),
.ars => ArikaSrsRotationSystem.rotate(engine, piece, rotation),
.tgm => TgmRotationSystem.rotate(engine, piece, rotation),
.tgm3 => Tgm3RotationSystem.rotate(engine, piece, rotation),
};
}
};
/// Parse an offset specification, defining how a piece is to be rotated in a given system.
fn parseOffsetSpec(
comptime spec: [Piece.Id.count][]const u8,
) [Piece.Id.count][Piece.Theta.count]Piece.Blocks {
var result: [Piece.Id.count][Piece.Theta.count]Piece.Blocks = undefined;
@setEvalBranchQuota(5000);
for (spec) |piece_spec, id| {
const line_length = 20;
var offset: usize = 0;
var rotation: usize = 0;
while (rotation < Piece.Theta.count) : ({
rotation += 1;
offset += 5;
}) {
var x: usize = 0;
var i: usize = 0;
while (x < 4) : (x += 1) {
var y: usize = 0;
while (y < 4) : (y += 1) {
switch (piece_spec[offset + y * line_length + x]) {
'@' => {
result[id][rotation][i] = Coord(u8){
.x = x,
.y = y,
};
i += 1;
},
'.' => {},
else => unreachable,
}
}
}
std.debug.assert(i == 4);
}
}
return result;
}
fn rotateWithWallkicks(engine: Engine, piece: *Piece, rotation: Rotation, kicks: []const Wallkick) bool {
const new_theta = piece.theta.rotate(rotation);
for (kicks) |kick| {
if (!engine.isCollision(piece.id, piece.x + kick.x, piece.y + kick.y, new_theta)) {
// A floorkick is indicated by a negative y-movement wallkick. If we exceed
// our floorkick limit then immediately request a lock on this frame by setting the
// lock_timer to exceed the lock delay.
piece.handleFloorkick(engine, kick.y < 0);
piece.move(engine, piece.x + kick.x, piece.y + kick.y, new_theta);
return true;
}
}
return false;
}
const no_wallkicks = [_]Wallkick{wk(0, 0)};
/// Super Rotation System. Current Tetris Guideline standard.
/// https://tetris.wiki/SRS.
pub const SrsRotationSystem = struct {
// TODO: ziglang/zig:#2456.
const offsets = parseOffsetSpec([_][]const u8{
\\.... ..@. .... .@..
\\@@@@ ..@. .... .@..
\\.... ..@. @@@@ .@..
\\.... ..@. .... .@..
,
\\@... .@@. .... .@..
\\@@@. .@.. @@@. .@..
\\.... .@.. ..@. @@..
\\.... .... .... ....
,
\\..@. .@.. .... @@..
\\@@@. .@.. @@@. .@..
\\.... .@@. @... .@..
\\.... .... .... ....
,
\\.@@. .@@. .@@. .@@.
\\.@@. .@@. .@@. .@@.
\\.... .... .... ....
\\.... .... .... ....
,
\\.@@. .@.. .... @...
\\@@.. .@@. .@@. @@..
\\.... ..@. @@.. .@..
\\.... .... .... ....
,
\\.@.. .@.. .... .@..
\\@@@. .@@. @@@. @@..
\\.... .@.. .@.. .@..
\\.... .... .... ....
,
\\@@.. ..@. .... .@..
\\.@@. .@@. @@.. @@..
\\.... .@.. .@@. @...
\\.... .... .... ....
});
const jlstz_wallkicks_clockwise = [4][5]Wallkick{
// 0 -> R
[_]Wallkick{ wk(0, 0), wk(-1, 0), wk(-1, 1), wk(0, -2), wk(-1, -2) },
// R -> 2
[_]Wallkick{ wk(0, 0), wk(1, 0), wk(1, -1), wk(0, 2), wk(1, 2) },
// 2 -> L
[_]Wallkick{ wk(0, 0), wk(1, 0), wk(1, 1), wk(0, -2), wk(1, -2) },
// L -> 0
[_]Wallkick{ wk(0, 0), wk(-1, 0), wk(-1, -1), wk(0, 2), wk(-1, 2) },
};
const jlstz_wallkicks_anticlockwise = [4][5]Wallkick{
// 0 -> L
[_]Wallkick{ wk(0, 0), wk(1, 0), wk(1, 1), wk(0, -2), wk(1, -2) },
// L -> 2
[_]Wallkick{ wk(0, 0), wk(-1, 0), wk(-1, -1), wk(0, 2), wk(-1, 2) },
// 2 -> R
[_]Wallkick{ wk(0, 0), wk(-1, 0), wk(-1, 1), wk(0, -2), wk(-1, -2) },
// R -> 0
[_]Wallkick{ wk(0, 0), wk(1, 0), wk(1, -1), wk(0, 2), wk(1, 2) },
};
const i_wallkicks_clockwise = [4][5]Wallkick{
// 0 -> R
[_]Wallkick{ wk(0, 0), wk(-2, 0), wk(1, 0), wk(-2, -1), wk(1, 2) },
// R -> 2
[_]Wallkick{ wk(0, 0), wk(-1, 0), wk(2, 0), wk(-1, 2), wk(2, -1) },
// 2 -> L
[_]Wallkick{ wk(0, 0), wk(2, 0), wk(-1, 0), wk(2, 1), wk(-1, -2) },
// L -> 0
[_]Wallkick{ wk(0, 0), wk(1, 0), wk(-2, 0), wk(1, -2), wk(-2, 1) },
};
const i_wallkicks_anticlockwise = [4][5]Wallkick{
// 0 -> L
[_]Wallkick{ wk(0, 0), wk(-1, 0), wk(2, 0), wk(-1, 2), wk(2, -1) },
// L -> 2
[_]Wallkick{ wk(0, 0), wk(-2, 0), wk(1, 0), wk(-2, -1), wk(1, 2) },
// 2 -> R
[_]Wallkick{ wk(0, 0), wk(1, 0), wk(-2, 0), wk(1, -2), wk(-2, 1) },
// R -> 0
[_]Wallkick{ wk(0, 0), wk(2, 0), wk(-1, 0), wk(2, 1), wk(-1, -2) },
};
pub fn blocks(id: Piece.Id, theta: Piece.Theta) Piece.Blocks {
return offsets[@enumToInt(id)][@enumToInt(theta)];
}
pub fn rotate(engine: Engine, piece: *Piece, rotation: Rotation) bool {
const wallkicks = switch (rotation) {
.Clockwise => (if (piece.id == .I) i_wallkicks_clockwise else jlstz_wallkicks_clockwise)[@enumToInt(piece.theta)],
.AntiClockwise => (if (piece.id == .I) i_wallkicks_anticlockwise else jlstz_wallkicks_anticlockwise)[@enumToInt(piece.theta)],
.Half => no_wallkicks,
};
return rotateWithWallkicks(engine, piece, rotation, wallkicks);
}
};
/// As found on the Sega arcade version of Tetris.
/// https://tetris.wiki/Sega_Rotation
pub const SegaRotationSystem = struct {
const offsets = parseOffsetSpec([_][]const u8{
\\.... ..@. .... ..@.
\\@@@@ ..@. @@@@ ..@.
\\.... ..@. .... ..@.
\\.... ..@. .... ..@.
,
\\.... .@.. .... .@@.
\\@@@. .@.. @... .@..
\\..@. @@.. @@@. .@..
\\.... .... .... ....
,
\\.... @@.. .... .@..
\\@@@. .@.. ..@. .@..
\\@... .@.. @@@. .@@.
\\.... .... .... ....
,
\\.... .... .... ....
\\.@@. .@@. .@@. .@@.
\\.@@. .@@. .@@. .@@.
\\.... .... .... ....
,
\\.... @... .... @...
\\.@@. @@.. .@@. @@..
\\@@.. .@.. @@.. .@..
\\.... .... .... ....
,
\\.... .@.. .... .@..
\\@@@. @@.. .@.. .@@.
\\.@.. .@.. @@@. .@..
\\.... .... .... ....
,
\\.... ..@. .... ..@.
\\@@.. .@@. @@.. .@@.
\\.@@. .@.. .@@. .@..
\\.... .... .... ....
});
pub fn blocks(id: Piece.Id, theta: Piece.Theta) Piece.Blocks {
return offsets[@enumToInt(id)][@enumToInt(theta)];
}
pub fn rotate(engine: Engine, piece: *Piece, rotation: Rotation) bool {
return rotateWithWallkicks(engine, piece, rotation, no_wallkicks);
}
};
/// As found on the original NES tetris games. Right-handed I variant.
/// https://tetris.wiki/Nintendo_Rotation_System
pub const NintendoRotationSystem = struct {
const offsets = parseOffsetSpec([_][]const u8{
\\.... ..@. .... ..@.
\\.... ..@. .... ..@.
\\@@@@ ..@. @@@@ ..@.
\\.... ..@. .... ..@.
,
\\.... .@.. @... .@@.
\\@@@. .@.. @@@. .@..
\\..@. @@.. .... .@..
\\.... .... .... ....
,
\\.... @@.. ..@. .@..
\\@@@. .@.. @@@. .@..
\\@... .@.. .... .@@.
\\.... .... .... ....
,
\\.... .... .... ....
\\.@@. .@@. .@@. .@@.
\\.@@. .@@. .@@. .@@.
\\.... .... .... ....
,
\\.... .@.. .... .@..
\\.@@. .@@. .@@. .@@.
\\@@.. ..@. @@.. ..@.
\\.... .... .... ....
,
\\.... .@.. .@.. .@..
\\@@@. @@.. @@@. .@@.
\\.@.. .@.. .... .@..
\\.... .... .... ....
,
\\.... ..@. .... ..@.
\\@@.. .@@. @@.. .@@.
\\.@@. .@.. .@@. .@..
\\.... .... .... ....
});
pub fn blocks(id: Piece.Id, theta: Piece.Theta) Piece.Blocks {
return offsets[@enumToInt(id)][@enumToInt(theta)];
}
pub fn rotate(engine: Engine, piece: *Piece, rotation: Rotation) bool {
return rotateWithWallkicks(engine, piece, rotation, no_wallkicks);
}
};
/// Used in the fan-game DTET. Similar to Sega Rotation with a few changes and symmetric wallkicks.
/// https://tetris.wiki/DTET_Rotation_System
pub const DtetRotationSystem = struct {
const offsets = parseOffsetSpec([_][]const u8{
\\.... .@.. .... .@..
\\.... .@.. .... .@..
\\@@@@ .@.. @@@@ .@..
\\.... .@.. .... .@..
,
\\.... .@.. .... .@@.
\\@@@. .@.. @... .@..
\\..@. @@.. @@@. .@..
\\.... .... .... ....
,
\\.... @@.. .... .@..
\\@@@. .@.. ..@. .@..
\\@... .@.. @@@. .@@.
\\.... .... .... ....
,
\\.... .... .... ....
\\.@@. .@@. .@@. .@@.
\\.@@. .@@. .@@. .@@.
\\.... .... .... ....
,
\\.... .@.. .... @...
\\.@@. .@@. .@@. @@..
\\@@.. ..@. @@.. .@..
\\.... .... .... ....
,
\\.... .@.. .... .@..
\\@@@. @@.. .@.. .@@.
\\.@.. .@.. @@@. .@..
\\.... .... .... ....
,
\\.... ..@. .... .@..
\\@@.. .@@. @@.. @@..
\\.@@. .@.. .@@. @...
\\.... .... .... ....
});
const clockwise_wallkicks = [_]Wallkick{
wk(0, 0), wk(1, 0), wk(-1, 0), wk(0, 1), wk(1, 1), wk(-1, 1),
};
const anticlockwise_wallkicks = [_]Wallkick{
wk(0, 0), wk(-1, 0), wk(1, 0), wk(0, 1), wk(-1, 1), wk(1, 1),
};
pub fn blocks(id: Piece.Id, theta: Piece.Theta) Piece.Blocks {
return offsets[@enumToInt(id)][@enumToInt(theta)];
}
pub fn rotate(engine: Engine, piece: *Piece, rotation: Rotation) bool {
const wallkicks = switch (rotation) {
.Clockwise => clockwise_wallkicks,
.AntiClockwise => anticlockwise_wallkicks,
.Half => no_wallkicks,
};
return rotateWithWallkicks(engine, piece, rotation, wallkicks);
}
};
/// Arika SRS as implemented in TGM3 and TGM:Ace. This is listed in TGM under 'World Rule'.
/// Uses the same offsets/kick-data as SRS, except for a modified I wallkick.
/// https://tetris.wiki/SRS#Arika_SRS.
pub const ArikaSrsRotationSystem = struct {
const i_wallkicks_clockwise = [4][5]Wallkick{
// 0 -> R
[_]Wallkick{ wk(0, 0), wk(-2, 0), wk(1, 0), wk(1, 2), wk(-2, 1) },
// R -> 2
[_]Wallkick{ wk(0, 0), wk(-1, 0), wk(2, 0), wk(-1, 2), wk(2, -1) },
// 2 -> L
[_]Wallkick{ wk(0, 0), wk(2, 0), wk(-1, 0), wk(2, 1), wk(-1, -1) },
// L -> 0
[_]Wallkick{ wk(0, 0), wk(-2, 0), wk(1, 0), wk(-2, 1), wk(1, -2) },
};
const i_wallkicks_anticlockwise = [4][5]Wallkick{
// 0 -> L
[_]Wallkick{ wk(0, 0), wk(2, 0), wk(-1, 0), wk(-1, 2), wk(2, -1) },
// L -> 2
[_]Wallkick{ wk(0, 0), wk(1, 0), wk(-2, 0), wk(1, 2), wk(-2, -1) },
// 2 -> R
[_]Wallkick{ wk(0, 0), wk(-2, 0), wk(1, 0), wk(-2, 1), wk(1, -1) },
// R -> 0
[_]Wallkick{ wk(0, 0), wk(2, 0), wk(-1, 0), wk(2, 1), wk(-1, -2) },
};
pub fn blocks(id: Piece.Id, theta: Piece.Theta) Piece.Blocks {
return SrsRotationSystem.offsets[@enumToInt(id)][@enumToInt(theta)];
}
pub fn rotate(engine: Engine, piece: *Piece, rotation: Rotation) bool {
const kicks = switch (rotation) {
.Clockwise => (if (piece.id == .I) i_wallkicks_clockwise else SrsRotationSystem.jlstz_wallkicks_clockwise)[@enumToInt(piece.theta)],
.AntiClockwise => (if (piece.id == .I) i_wallkicks_anticlockwise else SrsRotationSystem.jlstz_wallkicks_anticlockwise)[@enumToInt(piece.theta)],
.Half => no_wallkicks,
};
return rotateWithWallkicks(engine, piece, rotation, kicks);
}
};
/// As found in TGM1 and TGM2. Similar to Sega Rotation with a few changes and wallkicks.
/// https://tetris.wiki/TGM_Rotation
pub const TgmRotationSystem = struct {
const offsets = parseOffsetSpec([_][]const u8{
\\.... ..@. .... ..@.
\\@@@@ ..@. @@@@ ..@.
\\.... ..@. .... ..@.
\\.... ..@. .... ..@.
,
\\.... .@.. .... .@@.
\\@@@. .@.. @... .@..
\\..@. @@.. @@@. .@..
\\.... .... .... ....
,
\\.... @@.. .... .@..
\\@@@. .@.. ..@. .@..
\\@... .@.. @@@. .@@.
\\.... .... .... ....
,
\\.... .... .... ....
\\.@@. .@@. .@@. .@@.
\\.@@. .@@. .@@. .@@.
\\.... .... .... ....
,
\\.... @... .... @...
\\.@@. @@.. .@@. @@..
\\@@.. .@.. @@.. .@..
\\.... .... .... ....
,
\\.... .@.. .... .@..
\\@@@. .@@. @@@. @@..
\\.@.. .@.. .@.. .@..
\\.... .... .... ....
,
\\.... .@.. .... .@..
\\@@.. @@.. @@.. @@..
\\.@@. @... .@@. @...
\\.... .... .... ....
});
const wallkicks = [_]Wallkick{
wk(0, 0), wk(1, 0), wk(-1, 1),
};
const i_wallkicks = [_]Wallkick{wk(0, 0)};
pub fn blocks(id: Piece.Id, theta: Piece.Theta) Piece.Blocks {
return offsets[@enumToInt(id)][@enumToInt(theta)];
}
// Wallkicks will not occur if a block fills the x slot AND a block does not fill
// the `c` spot when rotating clockwise, or `a` when rotating anti-clockwise.
fn wallkickException(engine: Engine, piece: Piece, rotation: Rotation) bool {
switch (piece.id) {
.L => {
// c x
// @@@ @@@
// @x @
if (piece.theta == .R0) {
if (engine.well[piece.uy() + 2][piece.ux() + 1] != null and
!(rotation == .Clockwise and engine.well[piece.uy()][piece.ux()] != null))
{
return true;
}
if (engine.well[piece.uy()][piece.ux() + 1] != null) {
return true;
}
}
// x a
// @ x@
// @@@ @@@
else if (piece.theta == .R180) {
if (engine.well[piece.uy()][piece.ux() + 1] != null) {
return true;
}
if (engine.well[piece.uy() + 1][piece.ux() + 1] != null and
!(rotation == .AntiClockwise and engine.well[piece.uy()][piece.ux()] != null))
{
return true;
}
}
},
.J => {
// a x
// @@@ @@@
// x@ @
if (piece.theta == .R0) {
if (engine.well[piece.uy() + 2][piece.ux() + 1] != null and
!(rotation == .AntiClockwise and engine.well[piece.uy()][piece.ux() + 2] != null))
{
return true;
}
if (engine.well[piece.uy()][piece.ux() + 1] != null) {
return true;
}
}
// x c
// @ @x
// @@@ @@@
else if (piece.theta == .R180) {
if (engine.well[piece.uy()][piece.ux() + 1] != null) {
return true;
}
if (engine.well[piece.uy() + 1][piece.ux() + 1] != null and
!(rotation == .Clockwise and engine.well[piece.uy()][piece.ux() + 2] != null))
{
return true;
}
}
},
.T => {
// x x
// @ @@@
// @@@ @
if ((piece.theta == .R0 or piece.theta == .R180) and
engine.well[piece.uy()][piece.ux() + 1] != null)
{
return false;
}
},
else => {},
}
return false;
}
pub fn rotate(engine: Engine, piece: *Piece, rotation: Rotation) bool {
const new_theta = piece.theta.rotate(rotation);
const kicks = switch (rotation) {
.Clockwise, .AntiClockwise => if (piece.id == .I) i_wallkicks else wallkicks,
.Half => no_wallkicks,
};
for (kicks) |kick| {
if (!engine.isCollision(piece.id, piece.x + kick.x, piece.y + kick.y, new_theta) and
!wallkickException(engine, piece.*, rotation))
{
piece.handleFloorkick(engine, kick.y < 0);
piece.move(engine, piece.x + kick.x, piece.y + kick.y, new_theta);
return true;
}
}
return false;
}
};
/// As found in TGM3. This is the same as TGM1/2 Rotation however with extra wallkicks/floorkicks.
/// https://tetris.wiki/TGM_Rotation#New_wall_kicks_in_TGM3
pub const Tgm3RotationSystem = struct {
const wallkicks = [_]Wallkick{
wk(0, 0), wk(1, 0), wk(-1, 1),
};
const i_wallkicks = [_]Wallkick{
wk(0, 0), wk(1, 0), wk(2, 0), wk(-1, 0),
wk(-1, 0), wk(-2, 0), // Floorkicks: TODO: Check we cannot rotate into a floating position.
};
const t_wallkicks = [_]Wallkick{
wk(0, 0), wk(1, 0), wk(-1, 1),
wk(-1, 0), // Floorkicks: TODO: Check we cannot rotate into a floating position.
};
pub fn blocks(id: Piece.Id, theta: Piece.Theta) Piece.Blocks {
return TgmRotationSystem.offsets[@enumToInt(id)][@enumToInt(theta)];
}
pub fn rotate(engine: Engine, piece: *Piece, rotation: Rotation) bool {
const new_theta = piece.theta.rotate(rotation);
const kicks = switch (rotation) {
.Clockwise, .AntiClockwise => if (piece.id == .I) i_wallkicks else if (piece.id == .T) t_wallkicks else wallkicks,
.Half => no_wallkicks,
};
for (kicks) |kick| {
if (!engine.isCollision(piece.id, piece.x + kick.x, piece.y + kick.y, new_theta) and
!TgmRotationSystem.wallkickException(engine, piece.*, rotation))
{
// TODO: Implement floorkick limit. 2 for T, 1 for I.
piece.handleFloorkick(engine, kick.y < 0);
piece.move(engine, piece.x + kick.x, piece.y + kick.y, new_theta);
return true;
}
}
return false;
}
};
test "rotation" {
std.debug.warn("\n");
for (DtetRotationSystem.offsets) |rotations, id| {
std.debug.warn("{}\n", @intToEnum(Piece.Id, @intCast(u3, id)));
for (rotations) |rotation, i| {
std.debug.warn(" {}: ", i);
for (rotation) |s| {
std.debug.warn("({} {}) ", s.x, s.y);
}
std.debug.warn("\n");
}
}
}
|
src/rotation.zig
|
const std = @import("std");
const warn = std.debug.warn;
const assert = std.debug.assert;
const types = @import("types.zig");
/// Instructions in byte-code as described in
/// https://docs.oracle.com/javase/specs/jvms/se14/html/jvms-6.html#jvms-6.5
const Inst = enum(u8) {
iload_0 = 26,
iload_1 = 27,
iadd = 96,
ireturn = 172,
};
/// Runtime values in VM
const Obj = union {
int: i32
};
const Frame = struct {
class: types.Class,
code: []u8,
locals: []Obj,
stack: []Obj,
pub fn init(c: types.Class, method: []const u8, args: []const Obj) !Frame {
// TODO: make these available as struct fields or hashmaps.
for (c.methods) |m| if (std.mem.eql(u8, m.name, method)) {
for (m.attributes) |a| if (std.mem.eql(u8, a.name, "Code")) {
// Code layout
// https://docs.oracle.com/javase/specs/jvms/se14/html/jvms-4.html#jvms-4.7.3
const ns = std.mem.bigToNative(u16, @bitCast(u16, a.data[0..2].*));
const nl = std.mem.bigToNative(u16, @bitCast(u16, a.data[2..4].*));
var ret = Frame{
.class = c,
.code = a.data[8..],
.locals = try types.allocator.alloc(Obj, nl),
// TODO: remove + 1
.stack = try types.allocator.alloc(Obj, ns + 1),
};
for (args) |arg, i| {
ret.locals[i] = arg;
}
return ret;
};
};
return error.InvalidParam;
}
pub fn exec(self: Frame) Obj {
var code_ptr: usize = 0;
var stack_ptr: usize = 0;
while (true) {
const inst = @intToEnum(Inst, self.code[code_ptr]);
code_ptr += 1;
switch (inst) {
Inst.iload_0 => {
stack_ptr += 1;
self.stack[stack_ptr] = self.locals[0];
},
Inst.iload_1 => {
stack_ptr += 1;
self.stack[stack_ptr] = self.locals[1];
},
Inst.iadd => {
const a = self.stack[stack_ptr].int;
stack_ptr -= 1;
const b = self.stack[stack_ptr].int;
stack_ptr -= 1;
stack_ptr += 1;
self.stack[stack_ptr] = Obj{ .int = a + b };
},
Inst.ireturn => {
stack_ptr -= 1;
return self.stack[stack_ptr + 1];
},
// else => {
// warn("NOT IMPLEMENTED: {}", .{inst});
// assert(false);
// },
}
}
}
};
test "vm.Frame" {
const loader = @import("loader.zig");
const file = try std.fs.cwd().openFile("test/Add.class", .{});
defer file.close();
const l = loader.Loader{ .file = file };
const c = try l.class();
defer c.deinit();
const args = [_]Obj{ Obj{ .int = 1 }, Obj{ .int = 2 } };
const f = try Frame.init(c, "add", args[0..2]);
assert(f.locals[0].int == 1);
assert(f.locals[1].int == 2);
assert(f.exec().int == 1 + 2);
}
|
src/vm.zig
|
const std = @import("std");
const sdl = @cImport({
@cDefine("SDL_MAIN_HANDLED", "");
@cInclude("SDL.h");
});
const SCREEN_WIDTH = 480;
const SCREEN_HEIGHT = 640;
pub fn main() anyerror!void {
std.log.info("starting app\n", .{});
if (sdl.SDL_Init(sdl.SDL_INIT_VIDEO | sdl.SDL_INIT_AUDIO | sdl.SDL_INIT_EVENTS) != 0) {
std.log.err("could not initialize SDL", .{});
return;
}
defer sdl.SDL_Quit();
var window = sdl.SDL_CreateWindow(
"My Game",
sdl.SDL_WINDOWPOS_UNDEFINED,
sdl.SDL_WINDOWPOS_UNDEFINED,
SCREEN_WIDTH,
SCREEN_HEIGHT,
0,
) orelse {
std.log.err("could not create window", .{});
return;
};
defer sdl.SDL_DestroyWindow(window);
var windowSurface = sdl.SDL_GetWindowSurface(window);
if (sdl.SDL_FillRect(windowSurface, null, sdl.SDL_MapRGB(windowSurface.*.format, 0xaa, 0xaa, 0xaa)) < 0) {
std.log.err("could not fill rect", .{});
return;
}
var rw = sdl.SDL_RWFromFile("images/gato.bmp", "rb");
var imageSurface = sdl.SDL_LoadBMP_RW(rw, @boolToInt(true)) orelse {
std.log.err("could not load image\n", .{});
return;
};
defer sdl.SDL_FreeSurface(imageSurface);
main_loop: while (true) {
var event: sdl.SDL_Event = undefined;
while (sdl.SDL_PollEvent(&event) != 0) {
switch (event.type) {
sdl.SDL_QUIT => break :main_loop,
sdl.SDL_MOUSEBUTTONDOWN => {
std.log.info("mouse down", .{});
},
sdl.SDL_MOUSEBUTTONUP => {
std.log.info("mouse up", .{});
},
else => {},
}
}
var destRect = sdl.SDL_Rect{
.x = 10,
.y = 10,
.w = 0,
.h = 0,
};
if (sdl.SDL_BlitSurface(imageSurface, null, windowSurface, &destRect) < 0) {
std.log.err("could not blit image", .{});
return;
}
if (sdl.SDL_UpdateWindowSurface(window) < 0) {
std.log.err("could not update window surface", .{});
return;
}
}
}
|
src/main.zig
|
const std = @import("std");
const CrossTarget = std.zig.CrossTarget;
const TestContext = @import("../src/test.zig").TestContext;
const linux_x86_64 = CrossTarget{
.cpu_arch = .x86_64,
.os_tag = .linux,
.abi = .musl,
};
const macos_x86_64 = CrossTarget{
.cpu_arch = .x86_64,
.os_tag = .macos,
.abi = .gnu,
};
const macos_aarch64 = CrossTarget{
.cpu_arch = .aarch64,
.os_tag = .macos,
.abi = .gnu,
};
const macos_targets: []const CrossTarget = &.{
macos_x86_64,
macos_aarch64,
};
const all_targets: []const CrossTarget = &.{
linux_x86_64,
macos_x86_64,
macos_aarch64,
};
pub fn addCases(ctx: *TestContext) !void {
// macOS/Mach-O tests
for (macos_targets) |target| {
{
var case = try ctx.addCase("hello world in Zig", target);
try case.addInput("hello.zig",
\\const std = @import("std");
\\
\\pub fn main() anyerror!void {
\\ const stdout = std.io.getStdOut().writer();
\\ try stdout.print("Hello, World!\n", .{});
\\}
);
case.expectedStdout("Hello, World!\n");
}
{
var case = try ctx.addCase("stack traces in Zig", target);
try case.addInput("panic.zig",
\\const std = @import("std");
\\
\\pub fn main() void {
\\ unreachable;
\\}
);
case.expectedStdout("");
// TODO figure out if we can test the resultant stack trace info
// case.expectedStderr(
// \\thread 5731434 panic: reached unreachable code
// \\/Users/kubkon/dev/zld/zig-cache/tmp/ObL4MD7CSJolhrZC/panic.zig:4:5: 0x104d4bef3 in main (panic)
// \\ unreachable;
// \\ ^
// \\/opt/zig/lib/zig/std/start.zig:335:22: 0x104d4c03f in std.start.main (panic)
// \\ root.main();
// \\ ^
// \\???:?:?: 0x190c74f33 in ??? (???)
// \\Panicked during a panic. Aborting.
// );
}
{
var case = try ctx.addCase("tlv in Zig", target);
try case.addInput("tlv.zig",
\\const std = @import("std");
\\
\\threadlocal var globl: usize = 0;
\\
\\pub fn main() void {
\\ std.log.info("Before: {}", .{globl});
\\ globl += 1;
\\ std.log.info("After: {}", .{globl});
\\}
);
case.expectedStdout("");
case.expectedStderr("info: Before: 0\ninfo: After: 1\n");
}
}
// All targets
for (all_targets) |target| {
{
var case = try ctx.addCase("hello world in C", target);
try case.addInput("main.c",
\\#include <stdio.h>
\\
\\int main() {
\\ fprintf(stdout, "Hello, World!\n");
\\ return 0;
\\}
);
case.expectedStdout("Hello, World!\n");
}
{
var case = try ctx.addCase("simple multi object in C", target);
try case.addInput("add.h",
\\#ifndef ADD_H
\\#define ADD_H
\\
\\int add(int a, int b);
\\
\\#endif
);
try case.addInput("add.c",
\\#include "add.h"
\\
\\int add(int a, int b) {
\\ return a + b;
\\}
);
try case.addInput("main.c",
\\#include <stdio.h>
\\#include "add.h"
\\
\\int main() {
\\ int a = 1;
\\ int b = 2;
\\ int res = add(1, 2);
\\ printf("%d + %d = %d\n", a, b, res);
\\ return 0;
\\}
);
case.expectedStdout("1 + 2 = 3\n");
}
{
var case = try ctx.addCase("multiple imports in C", target);
try case.addInput("main.c",
\\#include <stdio.h>
\\#include <stdlib.h>
\\
\\int main() {
\\ fprintf(stdout, "Hello, World!\n");
\\ exit(0);
\\ return 0;
\\}
);
case.expectedStdout("Hello, World!\n");
}
{
var case = try ctx.addCase("zero-init statics in C", target);
try case.addInput("main.c",
\\#include <stdio.h>
\\
\\static int aGlobal = 1;
\\
\\int main() {
\\ printf("aGlobal=%d\n", aGlobal);
\\ aGlobal -= 1;
\\ return aGlobal;
\\}
);
case.expectedStdout("aGlobal=1\n");
}
}
}
|
test/test.zig
|
const std = @import("std");
const interop = @import("../interop.zig");
const iup = @import("../iup.zig");
const Impl = @import("../impl.zig").Impl;
const CallbackHandler = @import("../callback_handler.zig").CallbackHandler;
const debug = std.debug;
const trait = std.meta.trait;
const Element = iup.Element;
const Handle = iup.Handle;
const Error = iup.Error;
const ChildrenIterator = iup.ChildrenIterator;
const Size = iup.Size;
const Margin = iup.Margin;
///
/// Creates an interface element that is a button with a drop down arrow.
/// It can function as a button and as a dropdown.
/// Its visual presentation can contain a text and/or an image.
/// When dropped displays a child inside a dialog with no decorations, so it
/// can simulate the initial function of a dropdown list, but it can display
/// any layout of IUP elements inside the dropped dialog.
/// When the user click outside the dialog, it is automatically closed.
/// It inherits from IupCanvas.
pub const DropButton = opaque {
pub const CLASS_NAME = "dropbutton";
pub const NATIVE_TYPE = iup.NativeType.Canvas;
const Self = @This();
///
/// SCROLL_CB SCROLL_CB Called when some manipulation is made to the scrollbar.
/// The canvas is automatically redrawn only if this callback is NOT defined.
/// (GTK 2.8) Also the POSX and POSY values will not be correctly updated for
/// older GTK versions.
/// In Ubuntu, when liboverlay-scrollbar is enabled (the new tiny auto-hide
/// scrollbar) only the IUP_SBPOSV and IUP_SBPOSH codes are used.
/// Callback int function(Ihandle *ih, int op, float posx, float posy); [in C]
/// ih:scroll_cb(op, posx, posy: number) -> (ret: number) [in Lua] ih:
/// identifier of the element that activated the event.
/// op: indicates the operation performed on the scrollbar.
/// If the manipulation was made on the vertical scrollbar, it can have the
/// following values: IUP_SBUP - line up IUP_SBDN - line down IUP_SBPGUP - page
/// up IUP_SBPGDN - page down IUP_SBPOSV - vertical positioning IUP_SBDRAGV -
/// vertical drag If it was on the horizontal scrollbar, the following values
/// are valid: IUP_SBLEFT - column left IUP_SBRIGHT - column right IUP_SBPGLEFT
/// - page left IUP_SBPGRIGHT - page right IUP_SBPOSH - horizontal positioning
/// IUP_SBDRAGH - horizontal drag posx, posy: the same as the ACTION canvas
/// callback (corresponding to the values of attributes POSX and POSY).
/// Notes IUP_SBDRAGH and IUP_SBDRAGV are not supported in GTK.
/// During drag IUP_SBPOSH and IUP_SBPOSV are used.
/// In Windows, after a drag when mouse is released IUP_SBPOSH or IUP_SBPOSV
/// are called.
/// Affects IupCanvas, IupGLCanvas, SCROLLBAR
pub const OnScrollFn = fn (self: *Self, arg0: i32, arg1: f32, arg2: f32) anyerror!void;
///
/// The drop dialog is configured with no decorations and it is not resizable,
/// only the FOCUS_CB and K_ESC callbacks are set.
/// But this can be changed by the application.
/// It is a regular IupDialog.
/// To obtain the drop button handle from the handle of the dialog get the
/// "DROPBUTTON" attribute handle from the dialog, using IupGetAttributeHandle.
/// After performing some operation on the drop child, use SHOWDROPDOWN=NO on
/// the drop button, you may also update its TITLE, just like a regular IupList
/// with DROPDOWN=Yes, but this will not be performed automatically by the drop button.
/// For example, set the ACTION callback on the IupList used as drop child:
/// static int list_cb(Ihandle* list, char *text, int item, int state) { if
/// (state == 1) { Ihandle* ih = IupGetAttributeHandle(IupGetDialog(list),
/// "DROPBUTTON"); IupSetAttribute(ih, "SHOWDROPDOWN", "No");
/// IupSetStrAttribute(ih, "TITLE", text); } return IUP_DEFAULT; }
pub const OnFocusFn = fn (self: *Self, arg0: i32) anyerror!void;
///
/// WOM_CB WOM_CB Action generated when an audio device receives an event.
/// [Windows Only] Callback int function(Ihandle *ih, int state); [in C]
/// ih:wom_cb(state: number) -> (ret: number) [in Lua] ih: identifies the
/// element that activated the event.
/// state: can be opening=1, done=0, or closing=-1.
/// Notes This callback is used to syncronize video playback with audio.
/// It is sent when the audio device: Message Description opening is opened by
/// using the waveOutOpen function.
/// done is finished with a data block sent by using the waveOutWrite function.
/// closing is closed by using the waveOutClose function.
/// You must use the HWND attribute when calling waveOutOpen in the dwCallback
/// parameter and set fdwOpen to CALLBACK_WINDOW.
/// Affects IupDialog, IupCanvas, IupGLCanvas
pub const OnWomFn = fn (self: *Self, arg0: i32) anyerror!void;
///
/// K_ANY K_ANY Action generated when a keyboard event occurs.
/// Callback int function(Ihandle *ih, int c); [in C] ih:k_any(c: number) ->
/// (ret: number) [in Lua] ih: identifier of the element that activated the event.
/// c: identifier of typed key.
/// Please refer to the Keyboard Codes table for a list of possible values.
/// Returns: If IUP_IGNORE is returned the key is ignored and not processed by
/// the control and not propagated.
/// If returns IUP_CONTINUE, the key will be processed and the event will be
/// propagated to the parent of the element receiving it, this is the default behavior.
/// If returns IUP_DEFAULT the key is processed but it is not propagated.
/// IUP_CLOSE will be processed.
/// Notes Keyboard callbacks depend on the keyboard usage of the control with
/// the focus.
/// So if you return IUP_IGNORE the control will usually not process the key.
/// But be aware that sometimes the control process the key in another event so
/// even returning IUP_IGNORE the key can get processed.
/// Although it will not be propagated.
/// IMPORTANT: The callbacks "K_*" of the dialog or native containers depend on
/// the IUP_CONTINUE return value to work while the control is in focus.
/// If the callback does not exists it is automatically propagated to the
/// parent of the element.
/// K_* callbacks All defined keys are also callbacks of any element, called
/// when the respective key is activated.
/// For example: "K_cC" is also a callback activated when the user press
/// Ctrl+C, when the focus is at the element or at a children with focus.
/// This is the way an application can create shortcut keys, also called hot keys.
/// These callbacks are not available in IupLua.
/// Affects All elements with keyboard interaction.
pub const OnKAnyFn = fn (self: *Self, arg0: i32) anyerror!void;
pub const OnFlatFocusFn = fn (self: *Self, arg0: i32) anyerror!void;
///
/// HELP_CB HELP_CB Action generated when the user press F1 at a control.
/// In Motif is also activated by the Help button in some workstations keyboard.
/// Callback void function(Ihandle *ih); [in C] ih:help_cb() -> (ret: number)
/// [in Lua] ih: identifier of the element that activated the event.
/// Returns: IUP_CLOSE will be processed.
/// Affects All elements with user interaction.
pub const OnHelpFn = fn (self: *Self) anyerror!void;
pub const OnDropMotionFn = fn (self: *Self, arg0: i32, arg1: i32, arg2: [:0]const u8) anyerror!void;
pub const OnFlatLeaveWindowFn = fn (self: *Self) anyerror!void;
///
/// KEYPRESS_CB KEYPRESS_CB Action generated when a key is pressed or released.
/// If the key is pressed and held several calls will occur.
/// It is called after the callback K_ANY is processed.
/// Callback int function(Ihandle *ih, int c, int press); [in C]
/// ih:keypress_cb(c, press: number) -> (ret: number) [in Lua] ih: identifier
/// of the element that activated the event.
/// c: identifier of typed key.
/// Please refer to the Keyboard Codes table for a list of possible values.
/// press: 1 is the user pressed the key or 0 otherwise.
/// Returns: If IUP_IGNORE is returned the key is ignored by the system.
/// IUP_CLOSE will be processed.
/// Affects IupCanvas
pub const OnKeyPressFn = fn (self: *Self, arg0: i32, arg1: i32) anyerror!void;
pub const OnDragEndFn = fn (self: *Self, arg0: i32) anyerror!void;
pub const OnDragBeginFn = fn (self: *Self, arg0: i32, arg1: i32) anyerror!void;
///
/// ACTION ACTION Action generated when the element is activated.
/// Affects each element differently.
/// Callback int function(Ihandle *ih); [in C] ih:action() -> (ret: number) [in
/// Lua] ih: identifier of the element that activated the event.
/// In some elements, this callback may receive more parameters, apart from ih.
/// Please refer to each element's documentation.
/// Affects IupButton, IupItem, IupList, IupText, IupCanvas, IupMultiline,
/// IupToggle
pub const OnActionFn = fn (self: *Self, arg0: f32, arg1: f32) anyerror!void;
///
/// MOTION_CB MOTION_CB Action generated when the mouse moves.
/// Callback int function(Ihandle *ih, int x, int y, char *status); [in C]
/// ih:motion_cb(x, y: number, status: string) -> (ret: number) [in Lua] ih:
/// identifier of the element that activated the event.
/// x, y: position in the canvas where the event has occurred, in pixels.
/// status: status of mouse buttons and certain keyboard keys at the moment the
/// event was generated.
/// The same macros used for BUTTON_CB can be used for this status.
/// Notes Between press and release all mouse events are redirected only to
/// this control, even if the cursor moves outside the element.
/// So the BUTTON_CB callback when released and the MOTION_CB callback can be
/// called with coordinates outside the element rectangle.
/// Affects IupCanvas, IupGLCanvas
pub const OnMotionFn = fn (self: *Self, arg0: i32, arg1: i32, arg2: [:0]const u8) anyerror!void;
pub const OnFlatEnterWindowFn = fn (self: *Self, arg0: i32, arg1: i32) anyerror!void;
///
/// WHEEL_CB WHEEL_CB Action generated when the mouse wheel is rotated.
/// If this callback is not defined the wheel will automatically scroll the
/// canvas in the vertical direction by some lines, the SCROLL_CB callback if
/// defined will be called with the IUP_SBDRAGV operation.
/// Callback int function(Ihandle *ih, float delta, int x, int y, char
/// *status); [in C] ih:wheel_cb(delta, x, y: number, status: string) -> (ret:
/// number) [in Lua] ih: identifier of the element that activated the event.
/// delta: the amount the wheel was rotated in notches.
/// x, y: position in the canvas where the event has occurred, in pixels.
/// status: status of mouse buttons and certain keyboard keys at the moment the
/// event was generated.
/// The same macros used for BUTTON_CB can be used for this status.
/// Notes In Motif and GTK delta is always 1 or -1.
/// In Windows is some situations delta can reach the value of two.
/// In the future with more precise wheels this increment can be changed.
/// Affects IupCanvas, IupGLCanvas
pub const OnWheelFn = fn (self: *Self, arg0: f32, arg1: i32, arg2: i32, arg3: [:0]const u8) anyerror!void;
///
/// MAP_CB MAP_CB Called right after an element is mapped and its attributes
/// updated in IupMap.
/// When the element is a dialog, it is called after the layout is updated.
/// For all other elements is called before the layout is updated, so the
/// element current size will still be 0x0 during MAP_CB (since 3.14).
/// Callback int function(Ihandle *ih); [in C] ih:map_cb() -> (ret: number) [in
/// Lua] ih: identifier of the element that activated the event.
/// Affects All that have a native representation.
pub const OnMapFn = fn (self: *Self) anyerror!void;
pub const OnFlatButtonFn = fn (self: *Self, arg0: i32, arg1: i32, arg2: i32, arg3: i32, arg4: [:0]const u8) anyerror!void;
///
/// ENTERWINDOW_CB ENTERWINDOW_CB Action generated when the mouse enters the
/// native element.
/// Callback int function(Ihandle *ih); [in C] ih:enterwindow_cb() -> (ret:
/// number) [in Lua] ih: identifier of the element that activated the event.
/// Notes When the cursor is moved from one element to another, the call order
/// in all platforms will be first the LEAVEWINDOW_CB callback of the old
/// control followed by the ENTERWINDOW_CB callback of the new control.
/// (since 3.14) If the mouse button is hold pressed and the cursor moves
/// outside the element the behavior is system dependent.
/// In Windows the LEAVEWINDOW_CB/ENTERWINDOW_CB callbacks are NOT called, in
/// GTK the callbacks are called.
/// Affects All controls with user interaction.
/// See Also LEAVEWINDOW_CB
pub const OnEnterWindowFn = fn (self: *Self) anyerror!void;
///
/// DESTROY_CB DESTROY_CB Called right before an element is destroyed.
/// Callback int function(Ihandle *ih); [in C] ih:destroy_cb() -> (ret: number)
/// [in Lua] ih: identifier of the element that activated the event.
/// Notes If the dialog is visible then it is hidden before it is destroyed.
/// The callback will be called right after it is hidden.
/// The callback will be called before all other destroy procedures.
/// For instance, if the element has children then it is called before the
/// children are destroyed.
/// For language binding implementations use the callback name "LDESTROY_CB" to
/// release memory allocated by the binding for the element.
/// Also the callback will be called before the language callback.
/// Affects All.
pub const OnDestroyFn = fn (self: *Self) anyerror!void;
pub const OnDropDataFn = fn (self: *Self, arg0: [:0]const u8, arg1: *iup.Unknow, arg2: i32, arg3: i32, arg4: i32) anyerror!void;
///
/// KILLFOCUS_CB KILLFOCUS_CB Action generated when an element loses keyboard focus.
/// This callback is called before the GETFOCUS_CB of the element that gets the focus.
/// Callback int function(Ihandle *ih); [in C] ih:killfocus_cb() -> (ret:
/// number) [in Lua] ih: identifier of the element that activated the event.
/// Affects All elements with user interaction, except menus.
/// In Windows, there are restrictions when using this callback.
/// From MSDN on WM_KILLFOCUS: "While processing this message, do not make any
/// function calls that display or activate a window.
/// This causes the thread to yield control and can cause the application to
/// stop responding to messages.
/// See Also GETFOCUS_CB, IupGetFocus, IupSetFocus
pub const OnKillFocusFn = fn (self: *Self) anyerror!void;
///
/// DROPSHOW_CB: Action generated right after the drop child is shown or hidden.
/// This callback is also called when SHOWDROPDOWN is set.
/// int function (Ihandle *ih, int state); [in C]ih:dropdown_cb(state: boolean)
/// -> (ret: number) [in Lua]
pub const OnDropShowFn = fn (self: *Self, arg0: i32) anyerror!void;
pub const OnDragDataFn = fn (self: *Self, arg0: [:0]const u8, arg1: *iup.Unknow, arg2: i32) anyerror!void;
pub const OnDragDataSizeFn = fn (self: *Self, arg0: [:0]const u8) anyerror!void;
///
/// DROPFILES_CB DROPFILES_CB Action called when a file is "dropped" into the control.
/// When several files are dropped at once, the callback is called several
/// times, once for each file.
/// If defined after the element is mapped then the attribute DROPFILESTARGET
/// must be set to YES.
/// [Windows and GTK Only] (GTK 2.6) Callback int function(Ihandle *ih, const
/// char* filename, int num, int x, int y); [in C] ih:dropfiles_cb(filename:
/// string; num, x, y: number) -> (ret: number) [in Lua] ih: identifier of the
/// element that activated the event.
/// filename: Name of the dropped file.
/// num: Number index of the dropped file.
/// If several files are dropped, num is the index of the dropped file starting
/// from "total-1" to "0".
/// x: X coordinate of the point where the user released the mouse button.
/// y: Y coordinate of the point where the user released the mouse button.
/// Returns: If IUP_IGNORE is returned the callback will NOT be called for the
/// next dropped files, and the processing of dropped files will be interrupted.
/// Affects IupDialog, IupCanvas, IupGLCanvas, IupText, IupList
pub const OnDropFilesFn = fn (self: *Self, arg0: [:0]const u8, arg1: i32, arg2: i32, arg3: i32) anyerror!void;
///
/// RESIZE_CB RESIZE_CB Action generated when the canvas or dialog size is changed.
/// Callback int function(Ihandle *ih, int width, int height); [in C]
/// ih:resize_cb(width, height: number) -> (ret: number) [in Lua] ih:
/// identifier of the element that activated the event.
/// width: the width of the internal element size in pixels not considering the
/// decorations (client size) height: the height of the internal element size
/// in pixels not considering the decorations (client size) Notes For the
/// dialog, this action is also generated when the dialog is mapped, after the
/// map and before the show.
/// When XAUTOHIDE=Yes or YAUTOHIDE=Yes, if the canvas scrollbar is
/// hidden/shown after changing the DX or DY attributes from inside the
/// callback, the size of the drawing area will immediately change, so the
/// parameters with and height will be invalid.
/// To update the parameters consult the DRAWSIZE attribute.
/// Also activate the drawing toolkit only after updating the DX or DY attributes.
/// Affects IupCanvas, IupGLCanvas, IupDialog
pub const OnResizeFn = fn (self: *Self, arg0: i32, arg1: i32) anyerror!void;
///
/// UNMAP_CB UNMAP_CB Called right before an element is unmapped.
/// Callback int function(Ihandle *ih); [in C] ih:unmap_cb() -> (ret: number)
/// [in Lua] ih: identifier of the element that activated the event.
/// Affects All that have a native representation.
pub const OnUnmapFn = fn (self: *Self) anyerror!void;
///
/// FLAT_ACTION: Action generated when the button 1 (usually left) is selected.
/// This callback is called only after the mouse is released and when it is
/// released inside the button area.
/// Called only when DROPONARROW=Yes.
/// int function(Ihandle* ih); [in C]ih:action() -> (ret: number) [in Lua]
pub const OnFlatActionFn = fn (self: *Self) anyerror!void;
///
/// GETFOCUS_CB GETFOCUS_CB Action generated when an element is given keyboard focus.
/// This callback is called after the KILLFOCUS_CB of the element that loosed
/// the focus.
/// The IupGetFocus function during the callback returns the element that
/// loosed the focus.
/// Callback int function(Ihandle *ih); [in C] ih:getfocus_cb() -> (ret:
/// number) [in Lua] ih: identifier of the element that received keyboard focus.
/// Affects All elements with user interaction, except menus.
/// See Also KILLFOCUS_CB, IupGetFocus, IupSetFocus
pub const OnGetFocusFn = fn (self: *Self) anyerror!void;
///
/// BUTTON_CB BUTTON_CB Action generated when a mouse button is pressed or released.
/// Callback int function(Ihandle* ih, int button, int pressed, int x, int y,
/// char* status); [in C] ih:button_cb(button, pressed, x, y: number, status:
/// string) -> (ret: number) [in Lua] ih: identifies the element that activated
/// the event.
/// button: identifies the activated mouse button: IUP_BUTTON1 - left mouse
/// button (button 1); IUP_BUTTON2 - middle mouse button (button 2);
/// IUP_BUTTON3 - right mouse button (button 3).
/// pressed: indicates the state of the button: 0 - mouse button was released;
/// 1 - mouse button was pressed.
/// x, y: position in the canvas where the event has occurred, in pixels.
/// status: status of the mouse buttons and some keyboard keys at the moment
/// the event is generated.
/// The following macros must be used for verification: iup_isshift(status)
/// iup_iscontrol(status) iup_isbutton1(status) iup_isbutton2(status)
/// iup_isbutton3(status) iup_isbutton4(status) iup_isbutton5(status)
/// iup_isdouble(status) iup_isalt(status) iup_issys(status) They return 1 if
/// the respective key or button is pressed, and 0 otherwise.
/// These macros are also available in Lua, returning a boolean.
/// Returns: IUP_CLOSE will be processed.
/// On some controls if IUP_IGNORE is returned the action is ignored (this is
/// system dependent).
/// Notes This callback can be used to customize a button behavior.
/// For a standard button behavior use the ACTION callback of the IupButton.
/// For a single click the callback is called twice, one for pressed=1 and one
/// for pressed=0.
/// Only after both calls the ACTION callback is called.
/// In Windows, if a dialog is shown or popup in any situation there could be
/// unpredictable results because the native system still has processing to be
/// done even after the callback is called.
/// A double click is preceded by two single clicks, one for pressed=1 and one
/// for pressed=0, and followed by a press=0, all three without the double
/// click flag set.
/// In GTK, it is preceded by an additional two single clicks sequence.
/// For example, for one double click all the following calls are made:
/// BUTTON_CB(but=1 (1), x=154, y=83 [ 1 ]) BUTTON_CB(but=1 (0), x=154, y=83 [
/// 1 ]) BUTTON_CB(but=1 (1), x=154, y=83 [ 1 ]) (in GTK only) BUTTON_CB(but=1
/// (0), x=154, y=83 [ 1 ]) (in GTK only) BUTTON_CB(but=1 (1), x=154, y=83 [ 1
/// D ]) BUTTON_CB(but=1 (0), x=154, y=83 [ 1 ]) Between press and release all
/// mouse events are redirected only to this control, even if the cursor moves
/// outside the element.
/// So the BUTTON_CB callback when released and the MOTION_CB callback can be
/// called with coordinates outside the element rectangle.
/// Affects IupCanvas, IupButton, IupText, IupList, IupGLCanvas
pub const OnButtonFn = fn (self: *Self, arg0: i32, arg1: i32, arg2: i32, arg3: i32, arg4: [:0]const u8) anyerror!void;
pub const OnFlatMotionFn = fn (self: *Self, arg0: i32, arg1: i32, arg2: [:0]const u8) anyerror!void;
///
/// DROPDOWN_CB: Action generated right before the drop child is shown or hidden.
/// This callback is also called when SHOWDROPDOWN is set.
/// int function (Ihandle *ih, int state); [in C]ih:dropdown_cb(state: boolean)
/// -> (ret: number) [in Lua]
pub const OnDropDownFn = fn (self: *Self, arg0: i32) anyerror!void;
pub const OnLDestroyFn = fn (self: *Self) anyerror!void;
///
/// LEAVEWINDOW_CB LEAVEWINDOW_CB Action generated when the mouse leaves the
/// native element.
/// Callback int function(Ihandle *ih); [in C] ih:leavewindow_cb() -> (ret:
/// number) [in Lua] ih: identifier of the element that activated the event.
/// Notes When the cursor is moved from one element to another, the call order
/// in all platforms will be first the LEAVEWINDOW_CB callback of the old
/// control followed by the ENTERWINDOW_CB callback of the new control.
/// (since 3.14) If the mouse button is hold pressed and the cursor moves
/// outside the element the behavior is system dependent.
/// In Windows the LEAVEWINDOW_CB/ENTERWINDOW_CB callbacks are NOT called, in
/// GTK the callbacks are called.
/// Affects All controls with user interaction.
/// See Also ENTERWINDOW_CB
pub const OnLeaveWindowFn = fn (self: *Self) anyerror!void;
pub const OnPostMessageFn = fn (self: *Self, arg0: [:0]const u8, arg1: i32, arg2: f64, arg3: *iup.Unknow) anyerror!void;
pub const DrawTextAlignment = enum {
ACenter,
ARight,
ALeft,
};
pub const ZOrder = enum {
Top,
Bottom,
};
///
/// EXPAND (non inheritable): The default value is "NO".
pub const Expand = enum {
Yes,
Horizontal,
Vertical,
HorizontalFree,
VerticalFree,
No,
};
pub const Floating = enum {
Yes,
Ignore,
No,
};
pub const DrawStyle = enum {
Fill,
StrokeDash,
StrokeDot,
StrokeDashDot,
StrokeDashDotdot,
DrawStroke,
};
///
/// IMAGEPOSITION (non inheritable): Position of the image relative to the text
/// when both are displayed.
/// Can be: LEFT, RIGHT, TOP, BOTTOM.
/// Default: LEFT.
pub const ImagePosition = enum {
Left,
Right,
Bottom,
Top,
};
///
/// TEXTALIGNMENT (non inheritable): Horizontal text alignment for multiple lines.
/// Can be: ALEFT, ARIGHT or ACENTER.
/// Default: ALEFT.
pub const TextAlignment = enum {
ARight,
ALeft,
ACenter,
};
pub const Initializer = struct {
last_error: ?anyerror = null,
ref: *Self,
///
/// Returns a pointer to IUP element or an error.
/// Only top-level or detached elements needs to be unwraped,
pub fn unwrap(self: Initializer) !*Self {
if (self.last_error) |e| {
return e;
} else {
return self.ref;
}
}
///
/// Captures a reference into a external variable
/// Allows to capture some references even using full declarative API
pub fn capture(self: *Initializer, ref: **Self) Initializer {
ref.* = self.ref;
return self.*;
}
pub fn setStrAttribute(self: *Initializer, attributeName: [:0]const u8, arg: [:0]const u8) Initializer {
if (self.last_error) |_| return self.*;
Self.setStrAttribute(self.ref, attributeName, arg);
return self.*;
}
pub fn setIntAttribute(self: *Initializer, attributeName: [:0]const u8, arg: i32) Initializer {
if (self.last_error) |_| return self.*;
Self.setIntAttribute(self.ref, attributeName, arg);
return self.*;
}
pub fn setBoolAttribute(self: *Initializer, attributeName: [:0]const u8, arg: bool) Initializer {
if (self.last_error) |_| return self.*;
Self.setBoolAttribute(self.ref, attributeName, arg);
return self.*;
}
pub fn setPtrAttribute(self: *Initializer, comptime T: type, attributeName: [:0]const u8, value: ?*T) Initializer {
if (self.last_error) |_| return self.*;
Self.setPtrAttribute(self.ref, T, attributeName, value);
return self.*;
}
pub fn setHandle(self: *Initializer, arg: [:0]const u8) Initializer {
if (self.last_error) |_| return self.*;
interop.setHandle(self.ref, arg);
return self.*;
}
///
/// FGCOLOR: Text color.
/// Default: the global attribute DLGFGCOLOR.
pub fn setFgColor(self: *Initializer, rgb: iup.Rgb) Initializer {
if (self.last_error) |_| return self.*;
interop.setRgb(self.ref, "FGCOLOR", .{}, rgb);
return self.*;
}
pub fn setHandleName(self: *Initializer, arg: [:0]const u8) Initializer {
if (self.last_error) |_| return self.*;
interop.setStrAttribute(self.ref, "HANDLENAME", .{}, arg);
return self.*;
}
pub fn setTipBgColor(self: *Initializer, rgb: iup.Rgb) Initializer {
if (self.last_error) |_| return self.*;
interop.setRgb(self.ref, "TIPBGCOLOR", .{}, rgb);
return self.*;
}
///
/// FRONTIMAGEHIGHLIGHT (non inheritable): foreground image name of the element
/// in highlight state.
/// If it is not defined then the FRONTIMAGE is used.
pub fn setFrontImageHighlight(self: *Initializer, arg: anytype) Initializer {
if (self.last_error) |_| return self.*;
if (interop.validateHandle(.Image, arg)) {
interop.setHandleAttribute(self.ref, "FRONTIMAGEHIGHLIGHT", .{}, arg);
} else |err| {
self.last_error = err;
}
return self.*;
}
pub fn setFrontImageHighlightHandleName(self: *Initializer, arg: [:0]const u8) Initializer {
if (self.last_error) |_| return self.*;
interop.setStrAttribute(self.ref, "FRONTIMAGEHIGHLIGHT", .{}, arg);
return self.*;
}
pub fn setXMin(self: *Initializer, arg: i32) Initializer {
if (self.last_error) |_| return self.*;
interop.setIntAttribute(self.ref, "XMIN", .{}, arg);
return self.*;
}
pub fn setTipIcon(self: *Initializer, arg: [:0]const u8) Initializer {
if (self.last_error) |_| return self.*;
interop.setStrAttribute(self.ref, "TIPICON", .{}, arg);
return self.*;
}
pub fn setMaxSize(self: *Initializer, width: ?i32, height: ?i32) Initializer {
if (self.last_error) |_| return self.*;
var buffer: [128]u8 = undefined;
var value = Size.intIntToString(&buffer, width, height);
interop.setStrAttribute(self.ref, "MAXSIZE", .{}, value);
return self.*;
}
///
/// ARROWIMAGEPRESS (non inheritable): Arrow image name of the element in
/// pressed state.
/// If it is not defined then the ARROWIMAGE is used.
pub fn setArrowImagePress(self: *Initializer, arg: anytype) Initializer {
if (self.last_error) |_| return self.*;
if (interop.validateHandle(.Image, arg)) {
interop.setHandleAttribute(self.ref, "ARROWIMAGEPRESS", .{}, arg);
} else |err| {
self.last_error = err;
}
return self.*;
}
pub fn setArrowImagePressHandleName(self: *Initializer, arg: [:0]const u8) Initializer {
if (self.last_error) |_| return self.*;
interop.setStrAttribute(self.ref, "ARROWIMAGEPRESS", .{}, arg);
return self.*;
}
pub fn setDrawTextWrap(self: *Initializer, arg: bool) Initializer {
if (self.last_error) |_| return self.*;
interop.setBoolAttribute(self.ref, "DRAWTEXTWRAP", .{}, arg);
return self.*;
}
///
/// FOCUSFEEDBACK (non inheritable): draw the focus feedback.
/// Can be Yes or No.
/// Default: Yes.
/// (since 3.26)
pub fn setFocusFeedback(self: *Initializer, arg: bool) Initializer {
if (self.last_error) |_| return self.*;
interop.setBoolAttribute(self.ref, "FOCUSFEEDBACK", .{}, arg);
return self.*;
}
pub fn setPosition(self: *Initializer, x: i32, y: i32) Initializer {
if (self.last_error) |_| return self.*;
var buffer: [128]u8 = undefined;
var value = iup.XYPos.intIntToString(&buffer, x, y, ',');
interop.setStrAttribute(self.ref, "POSITION", .{}, value);
return self.*;
}
pub fn setDropFilesTarget(self: *Initializer, arg: bool) Initializer {
if (self.last_error) |_| return self.*;
interop.setBoolAttribute(self.ref, "DROPFILESTARGET", .{}, arg);
return self.*;
}
pub fn setDrawTextAlignment(self: *Initializer, arg: ?DrawTextAlignment) Initializer {
if (self.last_error) |_| return self.*;
if (arg) |value| switch (value) {
.ACenter => interop.setStrAttribute(self.ref, "DRAWTEXTALIGNMENT", .{}, "ACENTER"),
.ARight => interop.setStrAttribute(self.ref, "DRAWTEXTALIGNMENT", .{}, "ARIGHT"),
.ALeft => interop.setStrAttribute(self.ref, "DRAWTEXTALIGNMENT", .{}, "ALEFT"),
} else {
interop.clearAttribute(self.ref, "DRAWTEXTALIGNMENT", .{});
}
return self.*;
}
pub fn setTip(self: *Initializer, arg: [:0]const u8) Initializer {
if (self.last_error) |_| return self.*;
interop.setStrAttribute(self.ref, "TIP", .{}, arg);
return self.*;
}
pub fn setDrawTextLayoutCenter(self: *Initializer, arg: bool) Initializer {
if (self.last_error) |_| return self.*;
interop.setBoolAttribute(self.ref, "DRAWTEXTLAYOUTCENTER", .{}, arg);
return self.*;
}
///
/// CANFOCUS (creation only) (non inheritable): enables the focus traversal of
/// the control.
/// In Windows the button will respect CANFOCUS in opposite to the other controls.
/// Default: YES.
pub fn setCanFocus(self: *Initializer, arg: bool) Initializer {
if (self.last_error) |_| return self.*;
interop.setBoolAttribute(self.ref, "CANFOCUS", .{}, arg);
return self.*;
}
pub fn setDragSourceMove(self: *Initializer, arg: bool) Initializer {
if (self.last_error) |_| return self.*;
interop.setBoolAttribute(self.ref, "DRAGSOURCEMOVE", .{}, arg);
return self.*;
}
///
/// PSCOLOR: background color used to indicate a press state.
/// Pre-defined to "150 200 235".
/// Can be set to NULL.
/// If NULL BGCOLOR will be used instead.
pub fn setPsColor(self: *Initializer, rgb: iup.Rgb) Initializer {
if (self.last_error) |_| return self.*;
interop.setRgb(self.ref, "PSCOLOR", .{}, rgb);
return self.*;
}
pub fn setVisible(self: *Initializer, arg: bool) Initializer {
if (self.last_error) |_| return self.*;
interop.setBoolAttribute(self.ref, "VISIBLE", .{}, arg);
return self.*;
}
///
/// IMAGE (non inheritable): Image name.
/// Use IupSetHandle or IupSetAttributeHandle to associate an image to a name.
/// See also IupImage.
pub fn setImage(self: *Initializer, arg: anytype) Initializer {
if (self.last_error) |_| return self.*;
if (interop.validateHandle(.Image, arg)) {
interop.setHandleAttribute(self.ref, "IMAGE", .{}, arg);
} else |err| {
self.last_error = err;
}
return self.*;
}
pub fn setImageHandleName(self: *Initializer, arg: [:0]const u8) Initializer {
if (self.last_error) |_| return self.*;
interop.setStrAttribute(self.ref, "IMAGE", .{}, arg);
return self.*;
}
pub fn setLineX(self: *Initializer, arg: f64) Initializer {
if (self.last_error) |_| return self.*;
interop.setDoubleAttribute(self.ref, "LINEX", .{}, arg);
return self.*;
}
pub fn setCursor(self: *Initializer, arg: anytype) Initializer {
if (self.last_error) |_| return self.*;
if (interop.validateHandle(.Image, arg)) {
interop.setHandleAttribute(self.ref, "CURSOR", .{}, arg);
} else |err| {
self.last_error = err;
}
return self.*;
}
pub fn setCursorHandleName(self: *Initializer, arg: [:0]const u8) Initializer {
if (self.last_error) |_| return self.*;
interop.setStrAttribute(self.ref, "CURSOR", .{}, arg);
return self.*;
}
pub fn setLineY(self: *Initializer, arg: f64) Initializer {
if (self.last_error) |_| return self.*;
interop.setDoubleAttribute(self.ref, "LINEY", .{}, arg);
return self.*;
}
pub fn zOrder(self: *Initializer, arg: ?ZOrder) Initializer {
if (self.last_error) |_| return self.*;
if (arg) |value| switch (value) {
.Top => interop.setStrAttribute(self.ref, "ZORDER", .{}, "TOP"),
.Bottom => interop.setStrAttribute(self.ref, "ZORDER", .{}, "BOTTOM"),
} else {
interop.clearAttribute(self.ref, "ZORDER", .{});
}
return self.*;
}
pub fn setDrawLineWidth(self: *Initializer, arg: i32) Initializer {
if (self.last_error) |_| return self.*;
interop.setIntAttribute(self.ref, "DRAWLINEWIDTH", .{}, arg);
return self.*;
}
pub fn setDragDrop(self: *Initializer, arg: bool) Initializer {
if (self.last_error) |_| return self.*;
interop.setBoolAttribute(self.ref, "DRAGDROP", .{}, arg);
return self.*;
}
pub fn setTheme(self: *Initializer, arg: [:0]const u8) Initializer {
if (self.last_error) |_| return self.*;
interop.setStrAttribute(self.ref, "THEME", .{}, arg);
return self.*;
}
///
/// EXPAND (non inheritable): The default value is "NO".
pub fn setExpand(self: *Initializer, arg: ?Expand) Initializer {
if (self.last_error) |_| return self.*;
if (arg) |value| switch (value) {
.Yes => interop.setStrAttribute(self.ref, "EXPAND", .{}, "YES"),
.Horizontal => interop.setStrAttribute(self.ref, "EXPAND", .{}, "HORIZONTAL"),
.Vertical => interop.setStrAttribute(self.ref, "EXPAND", .{}, "VERTICAL"),
.HorizontalFree => interop.setStrAttribute(self.ref, "EXPAND", .{}, "HORIZONTALFREE"),
.VerticalFree => interop.setStrAttribute(self.ref, "EXPAND", .{}, "VERTICALFREE"),
.No => interop.setStrAttribute(self.ref, "EXPAND", .{}, "NO"),
} else {
interop.clearAttribute(self.ref, "EXPAND", .{});
}
return self.*;
}
pub fn setDrawFont(self: *Initializer, arg: [:0]const u8) Initializer {
if (self.last_error) |_| return self.*;
interop.setStrAttribute(self.ref, "DRAWFONT", .{}, arg);
return self.*;
}
pub fn setSize(self: *Initializer, width: ?i32, height: ?i32) Initializer {
if (self.last_error) |_| return self.*;
var buffer: [128]u8 = undefined;
var value = Size.intIntToString(&buffer, width, height);
interop.setStrAttribute(self.ref, "SIZE", .{}, value);
return self.*;
}
///
/// PADDING: internal margin.
/// Works just like the MARGIN attribute of the IupHbox and IupVbox containers,
/// but uses a different name to avoid inheritance problems.
/// Alignment does not includes the padding area.
/// Default value: "3x3".
/// Value can be DEFAULTBUTTONPADDING, so the global attribute of this name
/// will be used instead (since 3.29).
/// The natural size will be a combination of the size of the image and the
/// title, if any, plus PADDING and SPACING (if both image and title are
/// present), and plus the horizontal space occupied by the arrow.
pub fn setPadding(self: *Initializer, width: ?i32, height: ?i32) Initializer {
if (self.last_error) |_| return self.*;
var buffer: [128]u8 = undefined;
var value = Size.intIntToString(&buffer, width, height);
interop.setStrAttribute(self.ref, "PADDING", .{}, value);
return self.*;
}
pub fn setPosX(self: *Initializer, arg: f64) Initializer {
if (self.last_error) |_| return self.*;
interop.setDoubleAttribute(self.ref, "POSX", .{}, arg);
return self.*;
}
pub fn setPosY(self: *Initializer, arg: f64) Initializer {
if (self.last_error) |_| return self.*;
interop.setDoubleAttribute(self.ref, "POSY", .{}, arg);
return self.*;
}
///
/// BORDERHLCOLOR: color used for borders when highlighted.
/// Default use BORDERCOLOR.
pub fn setBorderHlColor(self: *Initializer, rgb: iup.Rgb) Initializer {
if (self.last_error) |_| return self.*;
interop.setRgb(self.ref, "BORDERHLCOLOR", .{}, rgb);
return self.*;
}
///
/// TEXTHLCOLOR: text color used to indicate a highlight state.
/// If not defined FGCOLOR will be used instead.
/// (since 3.26)
pub fn setTextHlColor(self: *Initializer, rgb: iup.Rgb) Initializer {
if (self.last_error) |_| return self.*;
interop.setRgb(self.ref, "TEXTHLCOLOR", .{}, rgb);
return self.*;
}
pub fn setTipMarkup(self: *Initializer, arg: [:0]const u8) Initializer {
if (self.last_error) |_| return self.*;
interop.setStrAttribute(self.ref, "TIPMARKUP", .{}, arg);
return self.*;
}
pub fn setYMin(self: *Initializer, arg: i32) Initializer {
if (self.last_error) |_| return self.*;
interop.setIntAttribute(self.ref, "YMIN", .{}, arg);
return self.*;
}
///
/// TEXTELLIPSIS (non inheritable): If the text is larger that its box, an
/// ellipsis ("...") will be placed near the last visible part of the text and
/// replace the invisible part.
/// It will be ignored when TEXTWRAP=Yes.
/// (since 3.25)
pub fn setTextEllipsis(self: *Initializer, arg: bool) Initializer {
if (self.last_error) |_| return self.*;
interop.setBoolAttribute(self.ref, "TEXTELLIPSIS", .{}, arg);
return self.*;
}
pub fn setDrawMakeInactive(self: *Initializer, arg: bool) Initializer {
if (self.last_error) |_| return self.*;
interop.setBoolAttribute(self.ref, "DRAWMAKEINACTIVE", .{}, arg);
return self.*;
}
pub fn setFontSize(self: *Initializer, arg: i32) Initializer {
if (self.last_error) |_| return self.*;
interop.setIntAttribute(self.ref, "FONTSIZE", .{}, arg);
return self.*;
}
pub fn setDropTypes(self: *Initializer, arg: [:0]const u8) Initializer {
if (self.last_error) |_| return self.*;
interop.setStrAttribute(self.ref, "DROPTYPES", .{}, arg);
return self.*;
}
pub fn setUserSize(self: *Initializer, width: ?i32, height: ?i32) Initializer {
if (self.last_error) |_| return self.*;
var buffer: [128]u8 = undefined;
var value = Size.intIntToString(&buffer, width, height);
interop.setStrAttribute(self.ref, "USERSIZE", .{}, value);
return self.*;
}
pub fn setTipDelay(self: *Initializer, arg: i32) Initializer {
if (self.last_error) |_| return self.*;
interop.setIntAttribute(self.ref, "TIPDELAY", .{}, arg);
return self.*;
}
///
/// BACKIMAGEINACTIVE (non inheritable): background image name of the element
/// when inactive.
/// If it is not defined then the BACKIMAGE is used and its colors will be
/// replaced by a modified version creating the disabled effect.
pub fn setBackImageInactive(self: *Initializer, arg: anytype) Initializer {
if (self.last_error) |_| return self.*;
if (interop.validateHandle(.Image, arg)) {
interop.setHandleAttribute(self.ref, "BACKIMAGEINACTIVE", .{}, arg);
} else |err| {
self.last_error = err;
}
return self.*;
}
pub fn setBackImageInactiveHandleName(self: *Initializer, arg: [:0]const u8) Initializer {
if (self.last_error) |_| return self.*;
interop.setStrAttribute(self.ref, "BACKIMAGEINACTIVE", .{}, arg);
return self.*;
}
pub fn setScrollBar(self: *Initializer, arg: bool) Initializer {
if (self.last_error) |_| return self.*;
interop.setBoolAttribute(self.ref, "SCROLLBAR", .{}, arg);
return self.*;
}
///
/// TITLE (non inheritable): Label's text.
/// The '\n' character is accepted for line change.
pub fn setTitle(self: *Initializer, arg: [:0]const u8) Initializer {
if (self.last_error) |_| return self.*;
interop.setStrAttribute(self.ref, "TITLE", .{}, arg);
return self.*;
}
pub fn setXAutoHide(self: *Initializer, arg: bool) Initializer {
if (self.last_error) |_| return self.*;
interop.setBoolAttribute(self.ref, "XAUTOHIDE", .{}, arg);
return self.*;
}
///
/// PROPAGATEFOCUS (non inheritable): enables the focus callback forwarding to
/// the next native parent with FOCUS_CB defined.
/// Default: NO.
pub fn setPropagateFocus(self: *Initializer, arg: bool) Initializer {
if (self.last_error) |_| return self.*;
interop.setBoolAttribute(self.ref, "PROPAGATEFOCUS", .{}, arg);
return self.*;
}
pub fn setXMax(self: *Initializer, arg: i32) Initializer {
if (self.last_error) |_| return self.*;
interop.setIntAttribute(self.ref, "XMAX", .{}, arg);
return self.*;
}
///
/// BGCOLOR: Background color.
/// If text and image are not defined, the button is configured to simply show
/// a color, in this case set the button size because the natural size will be
/// very small.
/// If not defined it will use the background color of the native parent.
pub fn setBgColor(self: *Initializer, rgb: iup.Rgb) Initializer {
if (self.last_error) |_| return self.*;
interop.setRgb(self.ref, "BGCOLOR", .{}, rgb);
return self.*;
}
pub fn setDropTarget(self: *Initializer, arg: bool) Initializer {
if (self.last_error) |_| return self.*;
interop.setBoolAttribute(self.ref, "DROPTARGET", .{}, arg);
return self.*;
}
pub fn setDX(self: *Initializer, arg: f64) Initializer {
if (self.last_error) |_| return self.*;
interop.setDoubleAttribute(self.ref, "DX", .{}, arg);
return self.*;
}
pub fn setDY(self: *Initializer, arg: f64) Initializer {
if (self.last_error) |_| return self.*;
interop.setDoubleAttribute(self.ref, "DY", .{}, arg);
return self.*;
}
pub fn setDrawTextEllipsis(self: *Initializer, arg: bool) Initializer {
if (self.last_error) |_| return self.*;
interop.setBoolAttribute(self.ref, "DRAWTEXTELLIPSIS", .{}, arg);
return self.*;
}
pub fn setDragSource(self: *Initializer, arg: bool) Initializer {
if (self.last_error) |_| return self.*;
interop.setBoolAttribute(self.ref, "DRAGSOURCE", .{}, arg);
return self.*;
}
pub fn setDrawTextClip(self: *Initializer, arg: bool) Initializer {
if (self.last_error) |_| return self.*;
interop.setBoolAttribute(self.ref, "DRAWTEXTCLIP", .{}, arg);
return self.*;
}
pub fn setFloating(self: *Initializer, arg: ?Floating) Initializer {
if (self.last_error) |_| return self.*;
if (arg) |value| switch (value) {
.Yes => interop.setStrAttribute(self.ref, "FLOATING", .{}, "YES"),
.Ignore => interop.setStrAttribute(self.ref, "FLOATING", .{}, "IGNORE"),
.No => interop.setStrAttribute(self.ref, "FLOATING", .{}, "NO"),
} else {
interop.clearAttribute(self.ref, "FLOATING", .{});
}
return self.*;
}
pub fn setNormalizerGroup(self: *Initializer, arg: [:0]const u8) Initializer {
if (self.last_error) |_| return self.*;
interop.setStrAttribute(self.ref, "NORMALIZERGROUP", .{}, arg);
return self.*;
}
///
/// SPACING (non inheritable): spacing between the image and the text.
/// Default: "2".
/// The natural size will be a combination of the size of the image and the
/// title, if any, plus PADDING and SPACING (if both image and title are
/// present), and plus the horizontal space occupied by the arrow.
pub fn setSpacing(self: *Initializer, arg: i32) Initializer {
if (self.last_error) |_| return self.*;
interop.setIntAttribute(self.ref, "SPACING", .{}, arg);
return self.*;
}
///
/// BORDERPSCOLOR: color used for borders when pressed or selected.
/// Default use BORDERCOLOR.
pub fn setBorderPsColor(self: *Initializer, rgb: iup.Rgb) Initializer {
if (self.last_error) |_| return self.*;
interop.setRgb(self.ref, "BORDERPSCOLOR", .{}, rgb);
return self.*;
}
pub fn setRasterSize(self: *Initializer, width: ?i32, height: ?i32) Initializer {
if (self.last_error) |_| return self.*;
var buffer: [128]u8 = undefined;
var value = Size.intIntToString(&buffer, width, height);
interop.setStrAttribute(self.ref, "RASTERSIZE", .{}, value);
return self.*;
}
///
/// TEXTPSCOLOR: text color used to indicate a press state.
/// If not defined FGCOLOR will be used instead.
/// (since 3.26)
pub fn setTextPsColor(self: *Initializer, rgb: iup.Rgb) Initializer {
if (self.last_error) |_| return self.*;
interop.setRgb(self.ref, "TEXTPSCOLOR", .{}, rgb);
return self.*;
}
///
/// BORDERCOLOR: color used for borders.
/// Default: "50 150 255".
/// This is for the IupDropButton drawn border.
pub fn setBorderColor(self: *Initializer, rgb: iup.Rgb) Initializer {
if (self.last_error) |_| return self.*;
interop.setRgb(self.ref, "BORDERCOLOR", .{}, rgb);
return self.*;
}
pub fn setTipFgColor(self: *Initializer, rgb: iup.Rgb) Initializer {
if (self.last_error) |_| return self.*;
interop.setRgb(self.ref, "TIPFGCOLOR", .{}, rgb);
return self.*;
}
///
/// ARROWIMAGEHIGHLIGHT (non inheritable): Arrow image name of the element in
/// highlight state.
/// If it is not defined then the ARROWIMAGE is used.
pub fn setArrowImageHighlight(self: *Initializer, arg: anytype) Initializer {
if (self.last_error) |_| return self.*;
if (interop.validateHandle(.Image, arg)) {
interop.setHandleAttribute(self.ref, "ARROWIMAGEHIGHLIGHT", .{}, arg);
} else |err| {
self.last_error = err;
}
return self.*;
}
pub fn setArrowImageHighlightHandleName(self: *Initializer, arg: [:0]const u8) Initializer {
if (self.last_error) |_| return self.*;
interop.setStrAttribute(self.ref, "ARROWIMAGEHIGHLIGHT", .{}, arg);
return self.*;
}
///
/// FRONTIMAGEINACTIVE (non inheritable): foreground image name of the element
/// when inactive.
/// If it is not defined then the FRONTIMAGE is used and its colors will be
/// replaced by a modified version creating the disabled effect.
pub fn setFrontImageInactive(self: *Initializer, arg: anytype) Initializer {
if (self.last_error) |_| return self.*;
if (interop.validateHandle(.Image, arg)) {
interop.setHandleAttribute(self.ref, "FRONTIMAGEINACTIVE", .{}, arg);
} else |err| {
self.last_error = err;
}
return self.*;
}
pub fn setFrontImageInactiveHandleName(self: *Initializer, arg: [:0]const u8) Initializer {
if (self.last_error) |_| return self.*;
interop.setStrAttribute(self.ref, "FRONTIMAGEINACTIVE", .{}, arg);
return self.*;
}
///
/// ARROWIMAGEINACTIVE (non inheritable): Arrow image name of the element when inactive.
/// If it is not defined then the ARROWIMAGE is used and its colors will be
/// replaced by a modified version creating the disabled effect.
pub fn setArrowImageInactive(self: *Initializer, arg: anytype) Initializer {
if (self.last_error) |_| return self.*;
if (interop.validateHandle(.Image, arg)) {
interop.setHandleAttribute(self.ref, "ARROWIMAGEINACTIVE", .{}, arg);
} else |err| {
self.last_error = err;
}
return self.*;
}
pub fn setArrowImageInactiveHandleName(self: *Initializer, arg: [:0]const u8) Initializer {
if (self.last_error) |_| return self.*;
interop.setStrAttribute(self.ref, "ARROWIMAGEINACTIVE", .{}, arg);
return self.*;
}
///
/// BACKIMAGEHIGHLIGHT (non inheritable): background image name of the element
/// in highlight state.
/// If it is not defined then the BACKIMAGE is used.
pub fn setBackImageHighlight(self: *Initializer, arg: anytype) Initializer {
if (self.last_error) |_| return self.*;
if (interop.validateHandle(.Image, arg)) {
interop.setHandleAttribute(self.ref, "BACKIMAGEHIGHLIGHT", .{}, arg);
} else |err| {
self.last_error = err;
}
return self.*;
}
pub fn setBackImageHighlightHandleName(self: *Initializer, arg: [:0]const u8) Initializer {
if (self.last_error) |_| return self.*;
interop.setStrAttribute(self.ref, "BACKIMAGEHIGHLIGHT", .{}, arg);
return self.*;
}
///
/// FRONTIMAGEPRESS (non inheritable): foreground image name of the element in
/// pressed state.
/// If it is not defined then the FRONTIMAGE is used.
pub fn setFrontImagePress(self: *Initializer, arg: anytype) Initializer {
if (self.last_error) |_| return self.*;
if (interop.validateHandle(.Image, arg)) {
interop.setHandleAttribute(self.ref, "FRONTIMAGEPRESS", .{}, arg);
} else |err| {
self.last_error = err;
}
return self.*;
}
pub fn setFrontImagePressHandleName(self: *Initializer, arg: [:0]const u8) Initializer {
if (self.last_error) |_| return self.*;
interop.setStrAttribute(self.ref, "FRONTIMAGEPRESS", .{}, arg);
return self.*;
}
///
/// CSPACING: same as SPACING but using the units of the vertical part of the
/// SIZE attribute.
/// It will actually set the SPACING attribute.
/// (since 3.29)
pub fn setCSpacing(self: *Initializer, arg: i32) Initializer {
if (self.last_error) |_| return self.*;
interop.setIntAttribute(self.ref, "CSPACING", .{}, arg);
return self.*;
}
///
/// HLCOLOR: background color used to indicate a highlight state.
/// Pre-defined to "200 225 245".
/// Can be set to NULL.
/// If NULL BGCOLOR will be used instead.
pub fn setHlColor(self: *Initializer, rgb: iup.Rgb) Initializer {
if (self.last_error) |_| return self.*;
interop.setRgb(self.ref, "HLCOLOR", .{}, rgb);
return self.*;
}
///
/// FRONTIMAGE (non inheritable): image name to be used as foreground.
/// The foreground image is drawn in the same position as the background, but
/// it is drawn at last.
/// Use IupSetHandle or IupSetAttributeHandle to associate an image to a name.
/// See also IupImage.
pub fn setFrontImage(self: *Initializer, arg: anytype) Initializer {
if (self.last_error) |_| return self.*;
if (interop.validateHandle(.Image, arg)) {
interop.setHandleAttribute(self.ref, "FRONTIMAGE", .{}, arg);
} else |err| {
self.last_error = err;
}
return self.*;
}
pub fn setFrontImageHandleName(self: *Initializer, arg: [:0]const u8) Initializer {
if (self.last_error) |_| return self.*;
interop.setStrAttribute(self.ref, "FRONTIMAGE", .{}, arg);
return self.*;
}
pub fn setFontFace(self: *Initializer, arg: [:0]const u8) Initializer {
if (self.last_error) |_| return self.*;
interop.setStrAttribute(self.ref, "FONTFACE", .{}, arg);
return self.*;
}
pub fn setDrawColor(self: *Initializer, rgb: iup.Rgb) Initializer {
if (self.last_error) |_| return self.*;
interop.setRgb(self.ref, "DRAWCOLOR", .{}, rgb);
return self.*;
}
pub fn setDrawTextOrientation(self: *Initializer, arg: f64) Initializer {
if (self.last_error) |_| return self.*;
interop.setDoubleAttribute(self.ref, "DRAWTEXTORIENTATION", .{}, arg);
return self.*;
}
pub fn setDrawBgColor(self: *Initializer, rgb: iup.Rgb) Initializer {
if (self.last_error) |_| return self.*;
interop.setRgb(self.ref, "DRAWBGCOLOR", .{}, rgb);
return self.*;
}
///
/// VISIBLECOLUMNS: Defines the number of visible columns for the Natural Size,
/// this means that will act also as minimum number of visible columns.
/// It uses a wider character size then the one used for the SIZE attribute so
/// strings will fit better without the need of extra columns.
/// Padding will be around the visible columns.
pub fn setVisibleColumns(self: *Initializer, arg: i32) Initializer {
if (self.last_error) |_| return self.*;
interop.setIntAttribute(self.ref, "VISIBLECOLUMNS", .{}, arg);
return self.*;
}
///
/// IMAGEPRESS (non inheritable): Image name of the element in pressed state.
/// If it is not defined then the IMAGE is used.
pub fn setImagePress(self: *Initializer, arg: anytype) Initializer {
if (self.last_error) |_| return self.*;
if (interop.validateHandle(.Image, arg)) {
interop.setHandleAttribute(self.ref, "IMAGEPRESS", .{}, arg);
} else |err| {
self.last_error = err;
}
return self.*;
}
pub fn setImagePressHandleName(self: *Initializer, arg: [:0]const u8) Initializer {
if (self.last_error) |_| return self.*;
interop.setStrAttribute(self.ref, "IMAGEPRESS", .{}, arg);
return self.*;
}
pub fn setName(self: *Initializer, arg: [:0]const u8) Initializer {
if (self.last_error) |_| return self.*;
interop.setStrAttribute(self.ref, "NAME", .{}, arg);
return self.*;
}
///
/// ARROWIMAGE (non inheritable): Arrow image name.
/// Use IupSetHandle or IupSetAttributeHandle to associate an image to a name.
/// See also IupImage.
pub fn setArrowImage(self: *Initializer, arg: anytype) Initializer {
if (self.last_error) |_| return self.*;
if (interop.validateHandle(.Image, arg)) {
interop.setHandleAttribute(self.ref, "ARROWIMAGE", .{}, arg);
} else |err| {
self.last_error = err;
}
return self.*;
}
pub fn setArrowImageHandleName(self: *Initializer, arg: [:0]const u8) Initializer {
if (self.last_error) |_| return self.*;
interop.setStrAttribute(self.ref, "ARROWIMAGE", .{}, arg);
return self.*;
}
pub fn setBackingStore(self: *Initializer, arg: bool) Initializer {
if (self.last_error) |_| return self.*;
interop.setBoolAttribute(self.ref, "BACKINGSTORE", .{}, arg);
return self.*;
}
pub fn setYAutoHide(self: *Initializer, arg: bool) Initializer {
if (self.last_error) |_| return self.*;
interop.setBoolAttribute(self.ref, "YAUTOHIDE", .{}, arg);
return self.*;
}
pub fn setDrawStyle(self: *Initializer, arg: ?DrawStyle) Initializer {
if (self.last_error) |_| return self.*;
if (arg) |value| switch (value) {
.Fill => interop.setStrAttribute(self.ref, "DRAWSTYLE", .{}, "FILL"),
.StrokeDash => interop.setStrAttribute(self.ref, "DRAWSTYLE", .{}, "STROKE_DASH"),
.StrokeDot => interop.setStrAttribute(self.ref, "DRAWSTYLE", .{}, "STROKE_DOT"),
.StrokeDashDot => interop.setStrAttribute(self.ref, "DRAWSTYLE", .{}, "STROKE_DASH_DOT"),
.StrokeDashDotdot => interop.setStrAttribute(self.ref, "DRAWSTYLE", .{}, "STROKE_DASH_DOT_DOT"),
.DrawStroke => interop.setStrAttribute(self.ref, "DRAWSTYLE", .{}, "DRAW_STROKE"),
} else {
interop.clearAttribute(self.ref, "DRAWSTYLE", .{});
}
return self.*;
}
///
/// DROPCHILD_HANDLE: same as DROPCHILD but directly using the Ihandle* of the element.
pub fn setDropChildHandle(self: *Initializer, arg: anytype) !Initializer {
if (self.last_error) |_| return self.*;
interop.setHandleAttribute(self.ref, "DROPCHILD_HANDLE", .{}, arg);
return self.*;
}
pub fn setDropChildHandleHandleName(self: *Initializer, arg: [:0]const u8) Initializer {
if (self.last_error) |_| return self.*;
interop.setStrAttribute(self.ref, "DROPCHILD_HANDLE", .{}, arg);
return self.*;
}
///
/// BACKIMAGEZOOM (non inheritable): if set the back image will be zoomed to
/// occupy the full background.
/// Aspect ratio is NOT preserved.
/// Can be Yes or No.
/// Default: No.
/// (since 3.25)
pub fn setBackImageZoom(self: *Initializer, arg: bool) Initializer {
if (self.last_error) |_| return self.*;
interop.setBoolAttribute(self.ref, "BACKIMAGEZOOM", .{}, arg);
return self.*;
}
///
/// CPADDING: same as PADDING but using the units of the SIZE attribute.
/// It will actually set the PADDING attribute.
/// (since 3.29)
pub fn setCPadding(self: *Initializer, width: ?i32, height: ?i32) Initializer {
if (self.last_error) |_| return self.*;
var buffer: [128]u8 = undefined;
var value = Size.intIntToString(&buffer, width, height);
interop.setStrAttribute(self.ref, "CPADDING", .{}, value);
return self.*;
}
///
/// TEXTORIENTATION (non inheritable): text angle in degrees and counterclockwise.
/// The text size will adapt to include the rotated space.
/// (since 3.25)
pub fn setTextOrientation(self: *Initializer, arg: f64) Initializer {
if (self.last_error) |_| return self.*;
interop.setDoubleAttribute(self.ref, "TEXTORIENTATION", .{}, arg);
return self.*;
}
///
/// FITTOBACKIMAGE (non inheritable): enable the natural size to be computed
/// from the BACKIMAGE.
/// If BACKIMAGE is not defined will be ignored.
/// Can be Yes or No.
/// Default: No.
pub fn setFitToBackImage(self: *Initializer, arg: bool) Initializer {
if (self.last_error) |_| return self.*;
interop.setBoolAttribute(self.ref, "FITTOBACKIMAGE", .{}, arg);
return self.*;
}
///
/// ACTIVE, FONT, EXPAND, SCREENPOSITION, POSITION, MINSIZE, MAXSIZE, WID, TIP,
/// SIZE, RASTERSIZE, ZORDER, VISIBLE, THEME: also accepted.
pub fn setActive(self: *Initializer, arg: bool) Initializer {
if (self.last_error) |_| return self.*;
interop.setBoolAttribute(self.ref, "ACTIVE", .{}, arg);
return self.*;
}
pub fn setTipVisible(self: *Initializer, arg: bool) Initializer {
if (self.last_error) |_| return self.*;
interop.setBoolAttribute(self.ref, "TIPVISIBLE", .{}, arg);
return self.*;
}
///
/// IMAGEHIGHLIGHT (non inheritable): Image name of the element in highlight state.
/// If it is not defined then the IMAGE is used.
pub fn setImageHighlight(self: *Initializer, arg: anytype) Initializer {
if (self.last_error) |_| return self.*;
if (interop.validateHandle(.Image, arg)) {
interop.setHandleAttribute(self.ref, "IMAGEHIGHLIGHT", .{}, arg);
} else |err| {
self.last_error = err;
}
return self.*;
}
pub fn setImageHighlightHandleName(self: *Initializer, arg: [:0]const u8) Initializer {
if (self.last_error) |_| return self.*;
interop.setStrAttribute(self.ref, "IMAGEHIGHLIGHT", .{}, arg);
return self.*;
}
pub fn setYMax(self: *Initializer, arg: i32) Initializer {
if (self.last_error) |_| return self.*;
interop.setIntAttribute(self.ref, "YMAX", .{}, arg);
return self.*;
}
///
/// BACKIMAGE (non inheritable): image name to be used as background.
/// Use IupSetHandle or IupSetAttributeHandle to associate an image to a name.
/// See also IupImage.
pub fn setBackImage(self: *Initializer, arg: anytype) Initializer {
if (self.last_error) |_| return self.*;
if (interop.validateHandle(.Image, arg)) {
interop.setHandleAttribute(self.ref, "BACKIMAGE", .{}, arg);
} else |err| {
self.last_error = err;
}
return self.*;
}
pub fn setBackImageHandleName(self: *Initializer, arg: [:0]const u8) Initializer {
if (self.last_error) |_| return self.*;
interop.setStrAttribute(self.ref, "BACKIMAGE", .{}, arg);
return self.*;
}
///
/// IMAGEINACTIVE (non inheritable): Image name of the element when inactive.
/// If it is not defined then the IMAGE is used and its colors will be replaced
/// by a modified version creating the disabled effect.
pub fn setImageInactive(self: *Initializer, arg: anytype) Initializer {
if (self.last_error) |_| return self.*;
if (interop.validateHandle(.Image, arg)) {
interop.setHandleAttribute(self.ref, "IMAGEINACTIVE", .{}, arg);
} else |err| {
self.last_error = err;
}
return self.*;
}
pub fn setImageInactiveHandleName(self: *Initializer, arg: [:0]const u8) Initializer {
if (self.last_error) |_| return self.*;
interop.setStrAttribute(self.ref, "IMAGEINACTIVE", .{}, arg);
return self.*;
}
///
/// SHOWDROPDOWN (write-only): opens or closes the dropdown child.
/// Can be "YES" or "NO".
/// Ignored if set before map.
pub fn showDropDown(self: *Initializer, arg: bool) Initializer {
if (self.last_error) |_| return self.*;
interop.setBoolAttribute(self.ref, "SHOWDROPDOWN", .{}, arg);
return self.*;
}
pub fn setExpandWeight(self: *Initializer, arg: f64) Initializer {
if (self.last_error) |_| return self.*;
interop.setDoubleAttribute(self.ref, "EXPANDWEIGHT", .{}, arg);
return self.*;
}
pub fn setMinSize(self: *Initializer, width: ?i32, height: ?i32) Initializer {
if (self.last_error) |_| return self.*;
var buffer: [128]u8 = undefined;
var value = Size.intIntToString(&buffer, width, height);
interop.setStrAttribute(self.ref, "MINSIZE", .{}, value);
return self.*;
}
///
/// SHOWBORDER: by default borders are drawn only when the button is
/// highlighted, if SHOWBORDER=Yes borders are always show.
/// When SHOWBORDER=Yes and BGCOLOR is not defined, the actual BGCOLOR will be
/// a darker version of the background color of the native parent.
pub fn setShowBorder(self: *Initializer, arg: bool) Initializer {
if (self.last_error) |_| return self.*;
interop.setBoolAttribute(self.ref, "SHOWBORDER", .{}, arg);
return self.*;
}
///
/// ARROWIMAGES (non inheritable): replace the drawn arrows by the following images.
/// Make sure their sizes are equal or smaller than ARROWSIZE.
/// Default: No.
pub fn setArrowImages(self: *Initializer, arg: i32) Initializer {
if (self.last_error) |_| return self.*;
interop.setIntAttribute(self.ref, "ARROWIMAGES", .{}, arg);
return self.*;
}
pub fn setNTheme(self: *Initializer, arg: [:0]const u8) Initializer {
if (self.last_error) |_| return self.*;
interop.setStrAttribute(self.ref, "NTHEME", .{}, arg);
return self.*;
}
///
/// BORDER (creation only): the default value is "NO".
/// This is the IupCanvas border.
pub fn setBorder(self: *Initializer, arg: bool) Initializer {
if (self.last_error) |_| return self.*;
interop.setBoolAttribute(self.ref, "BORDER", .{}, arg);
return self.*;
}
///
/// IMAGEPOSITION (non inheritable): Position of the image relative to the text
/// when both are displayed.
/// Can be: LEFT, RIGHT, TOP, BOTTOM.
/// Default: LEFT.
pub fn setImagePosition(self: *Initializer, arg: ?ImagePosition) Initializer {
if (self.last_error) |_| return self.*;
if (arg) |value| switch (value) {
.Left => interop.setStrAttribute(self.ref, "IMAGEPOSITION", .{}, "LEFT"),
.Right => interop.setStrAttribute(self.ref, "IMAGEPOSITION", .{}, "RIGHT"),
.Bottom => interop.setStrAttribute(self.ref, "IMAGEPOSITION", .{}, "BOTTOM"),
.Top => interop.setStrAttribute(self.ref, "IMAGEPOSITION", .{}, "TOP"),
} else {
interop.clearAttribute(self.ref, "IMAGEPOSITION", .{});
}
return self.*;
}
pub fn setDragTypes(self: *Initializer, arg: [:0]const u8) Initializer {
if (self.last_error) |_| return self.*;
interop.setStrAttribute(self.ref, "DRAGTYPES", .{}, arg);
return self.*;
}
pub fn setWheelDropFocus(self: *Initializer, arg: bool) Initializer {
if (self.last_error) |_| return self.*;
interop.setBoolAttribute(self.ref, "WHEELDROPFOCUS", .{}, arg);
return self.*;
}
///
/// BORDERWIDTH: line width used for borders.
/// Default: "1".
/// Any borders can be hidden by simply setting this value to 0.
/// This is for the IupDropButton drawn border.
pub fn setBorderWidth(self: *Initializer, arg: i32) Initializer {
if (self.last_error) |_| return self.*;
interop.setIntAttribute(self.ref, "BORDERWIDTH", .{}, arg);
return self.*;
}
pub fn setFontStyle(self: *Initializer, arg: [:0]const u8) Initializer {
if (self.last_error) |_| return self.*;
interop.setStrAttribute(self.ref, "FONTSTYLE", .{}, arg);
return self.*;
}
///
/// TEXTALIGNMENT (non inheritable): Horizontal text alignment for multiple lines.
/// Can be: ALEFT, ARIGHT or ACENTER.
/// Default: ALEFT.
pub fn setTextAlignment(self: *Initializer, arg: ?TextAlignment) Initializer {
if (self.last_error) |_| return self.*;
if (arg) |value| switch (value) {
.ARight => interop.setStrAttribute(self.ref, "TEXTALIGNMENT", .{}, "ARIGHT"),
.ALeft => interop.setStrAttribute(self.ref, "TEXTALIGNMENT", .{}, "ALEFT"),
.ACenter => interop.setStrAttribute(self.ref, "TEXTALIGNMENT", .{}, "ACENTER"),
} else {
interop.clearAttribute(self.ref, "TEXTALIGNMENT", .{});
}
return self.*;
}
pub fn setTouch(self: *Initializer, arg: bool) Initializer {
if (self.last_error) |_| return self.*;
interop.setBoolAttribute(self.ref, "TOUCH", .{}, arg);
return self.*;
}
///
/// TEXTWRAP (non inheritable): For single line texts if the text is larger
/// than its box the line will be automatically broken in multiple lines.
/// Notice that this is done internally by the system, the element natural size
/// will still use only a single line.
/// For the remaining lines to be visible the element should use
/// EXPAND=VERTICAL or set a SIZE/RASTERSIZE with enough height for the wrapped lines.
/// (since 3.25)
pub fn setTextWrap(self: *Initializer, arg: bool) Initializer {
if (self.last_error) |_| return self.*;
interop.setBoolAttribute(self.ref, "TEXTWRAP", .{}, arg);
return self.*;
}
///
/// BACKIMAGEPRESS (non inheritable): background image name of the element in
/// pressed state.
/// If it is not defined then the BACKIMAGE is used.
pub fn setBackImagePress(self: *Initializer, arg: anytype) Initializer {
if (self.last_error) |_| return self.*;
if (interop.validateHandle(.Image, arg)) {
interop.setHandleAttribute(self.ref, "BACKIMAGEPRESS", .{}, arg);
} else |err| {
self.last_error = err;
}
return self.*;
}
pub fn setBackImagePressHandleName(self: *Initializer, arg: [:0]const u8) Initializer {
if (self.last_error) |_| return self.*;
interop.setStrAttribute(self.ref, "BACKIMAGEPRESS", .{}, arg);
return self.*;
}
pub fn setFont(self: *Initializer, arg: [:0]const u8) Initializer {
if (self.last_error) |_| return self.*;
interop.setStrAttribute(self.ref, "FONT", .{}, arg);
return self.*;
}
pub fn setMdiClient(self: *Initializer, arg: bool) Initializer {
if (self.last_error) |_| return self.*;
interop.setBoolAttribute(self.ref, "MDICLIENT", .{}, arg);
return self.*;
}
pub fn setMdiMenu(self: *Initializer, arg: *iup.Menu) Initializer {
if (self.last_error) |_| return self.*;
interop.setHandleAttribute(self.ref, "MDIMENU", .{}, arg);
return self.*;
}
pub fn setMdiMenuHandleName(self: *Initializer, arg: [:0]const u8) Initializer {
if (self.last_error) |_| return self.*;
interop.setStrAttribute(self.ref, "MDIMENU", .{}, arg);
return self.*;
}
///
/// TABIMAGEn (non inheritable): image name to be used in the respective tab.
/// Use IupSetHandle or IupSetAttributeHandle to associate an image to a name.
/// n starts at 0.
/// See also IupImage.
/// In Motif, the image is shown only if TABTITLEn is NULL.
/// In Windows and Motif set the BGCOLOR attribute before setting the image.
/// When set after map will update the TABIMAGE attribute on the respective
/// child (since 3.10).
/// (since 3.0).
/// TABIMAGE (non inheritable) (at children only): Same as TABIMAGEn but set in
/// each child.
/// Works only if set before the child is added to the tabs.
pub fn setTabImage(self: *Initializer, index: i32, arg: anytype) Initializer {
if (self.last_error) |_| return self.*;
if (interop.validateHandle(.Image, arg)) {
interop.setHandleAttribute(self.ref, "TABIMAGE", .{index}, arg);
} else |err| {
self.last_error = err;
}
return self.*;
}
pub fn setTabImageHandleName(self: *Initializer, index: i32, arg: [:0]const u8) Initializer {
if (self.last_error) |_| return self.*;
interop.setStrAttribute(self.ref, "TABIMAGE", .{index}, arg);
return self.*;
}
///
/// TABTITLEn (non inheritable): Contains the text to be shown in the
/// respective tab title.
/// n starts at 0.
/// If this value is NULL, it will remain empty.
/// The "&" character can be used to define a mnemonic, the next character will
/// be used as key.
/// Use "&&" to show the "&" character instead on defining a mnemonic.
/// The button can be activated from any control in the dialog using the
/// "Alt+key" combination.
/// (mnemonic support since 3.3).
/// When set after map will update the TABTITLE attribute on the respective
/// child (since 3.10).
/// (since 3.0).
/// TABTITLE (non inheritable) (at children only): Same as TABTITLEn but set in
/// each child.
/// Works only if set before the child is added to the tabs.
pub fn setTabTitle(self: *Initializer, index: i32, arg: [:0]const u8) Initializer {
if (self.last_error) |_| return self.*;
interop.setStrAttribute(self.ref, "TABTITLE", .{index}, arg);
return self.*;
}
///
/// SCROLL_CB SCROLL_CB Called when some manipulation is made to the scrollbar.
/// The canvas is automatically redrawn only if this callback is NOT defined.
/// (GTK 2.8) Also the POSX and POSY values will not be correctly updated for
/// older GTK versions.
/// In Ubuntu, when liboverlay-scrollbar is enabled (the new tiny auto-hide
/// scrollbar) only the IUP_SBPOSV and IUP_SBPOSH codes are used.
/// Callback int function(Ihandle *ih, int op, float posx, float posy); [in C]
/// ih:scroll_cb(op, posx, posy: number) -> (ret: number) [in Lua] ih:
/// identifier of the element that activated the event.
/// op: indicates the operation performed on the scrollbar.
/// If the manipulation was made on the vertical scrollbar, it can have the
/// following values: IUP_SBUP - line up IUP_SBDN - line down IUP_SBPGUP - page
/// up IUP_SBPGDN - page down IUP_SBPOSV - vertical positioning IUP_SBDRAGV -
/// vertical drag If it was on the horizontal scrollbar, the following values
/// are valid: IUP_SBLEFT - column left IUP_SBRIGHT - column right IUP_SBPGLEFT
/// - page left IUP_SBPGRIGHT - page right IUP_SBPOSH - horizontal positioning
/// IUP_SBDRAGH - horizontal drag posx, posy: the same as the ACTION canvas
/// callback (corresponding to the values of attributes POSX and POSY).
/// Notes IUP_SBDRAGH and IUP_SBDRAGV are not supported in GTK.
/// During drag IUP_SBPOSH and IUP_SBPOSV are used.
/// In Windows, after a drag when mouse is released IUP_SBPOSH or IUP_SBPOSV
/// are called.
/// Affects IupCanvas, IupGLCanvas, SCROLLBAR
pub fn setScrollCallback(self: *Initializer, callback: ?OnScrollFn) Initializer {
const Handler = CallbackHandler(Self, OnScrollFn, "SCROLL_CB");
Handler.setCallback(self.ref, callback);
return self.*;
}
///
/// The drop dialog is configured with no decorations and it is not resizable,
/// only the FOCUS_CB and K_ESC callbacks are set.
/// But this can be changed by the application.
/// It is a regular IupDialog.
/// To obtain the drop button handle from the handle of the dialog get the
/// "DROPBUTTON" attribute handle from the dialog, using IupGetAttributeHandle.
/// After performing some operation on the drop child, use SHOWDROPDOWN=NO on
/// the drop button, you may also update its TITLE, just like a regular IupList
/// with DROPDOWN=Yes, but this will not be performed automatically by the drop button.
/// For example, set the ACTION callback on the IupList used as drop child:
/// static int list_cb(Ihandle* list, char *text, int item, int state) { if
/// (state == 1) { Ihandle* ih = IupGetAttributeHandle(IupGetDialog(list),
/// "DROPBUTTON"); IupSetAttribute(ih, "SHOWDROPDOWN", "No");
/// IupSetStrAttribute(ih, "TITLE", text); } return IUP_DEFAULT; }
pub fn setFocusCallback(self: *Initializer, callback: ?OnFocusFn) Initializer {
const Handler = CallbackHandler(Self, OnFocusFn, "FOCUS_CB");
Handler.setCallback(self.ref, callback);
return self.*;
}
///
/// WOM_CB WOM_CB Action generated when an audio device receives an event.
/// [Windows Only] Callback int function(Ihandle *ih, int state); [in C]
/// ih:wom_cb(state: number) -> (ret: number) [in Lua] ih: identifies the
/// element that activated the event.
/// state: can be opening=1, done=0, or closing=-1.
/// Notes This callback is used to syncronize video playback with audio.
/// It is sent when the audio device: Message Description opening is opened by
/// using the waveOutOpen function.
/// done is finished with a data block sent by using the waveOutWrite function.
/// closing is closed by using the waveOutClose function.
/// You must use the HWND attribute when calling waveOutOpen in the dwCallback
/// parameter and set fdwOpen to CALLBACK_WINDOW.
/// Affects IupDialog, IupCanvas, IupGLCanvas
pub fn setWomCallback(self: *Initializer, callback: ?OnWomFn) Initializer {
const Handler = CallbackHandler(Self, OnWomFn, "WOM_CB");
Handler.setCallback(self.ref, callback);
return self.*;
}
///
/// K_ANY K_ANY Action generated when a keyboard event occurs.
/// Callback int function(Ihandle *ih, int c); [in C] ih:k_any(c: number) ->
/// (ret: number) [in Lua] ih: identifier of the element that activated the event.
/// c: identifier of typed key.
/// Please refer to the Keyboard Codes table for a list of possible values.
/// Returns: If IUP_IGNORE is returned the key is ignored and not processed by
/// the control and not propagated.
/// If returns IUP_CONTINUE, the key will be processed and the event will be
/// propagated to the parent of the element receiving it, this is the default behavior.
/// If returns IUP_DEFAULT the key is processed but it is not propagated.
/// IUP_CLOSE will be processed.
/// Notes Keyboard callbacks depend on the keyboard usage of the control with
/// the focus.
/// So if you return IUP_IGNORE the control will usually not process the key.
/// But be aware that sometimes the control process the key in another event so
/// even returning IUP_IGNORE the key can get processed.
/// Although it will not be propagated.
/// IMPORTANT: The callbacks "K_*" of the dialog or native containers depend on
/// the IUP_CONTINUE return value to work while the control is in focus.
/// If the callback does not exists it is automatically propagated to the
/// parent of the element.
/// K_* callbacks All defined keys are also callbacks of any element, called
/// when the respective key is activated.
/// For example: "K_cC" is also a callback activated when the user press
/// Ctrl+C, when the focus is at the element or at a children with focus.
/// This is the way an application can create shortcut keys, also called hot keys.
/// These callbacks are not available in IupLua.
/// Affects All elements with keyboard interaction.
pub fn setKAnyCallback(self: *Initializer, callback: ?OnKAnyFn) Initializer {
const Handler = CallbackHandler(Self, OnKAnyFn, "K_ANY");
Handler.setCallback(self.ref, callback);
return self.*;
}
pub fn setFlatFocusCallback(self: *Initializer, callback: ?OnFlatFocusFn) Initializer {
const Handler = CallbackHandler(Self, OnFlatFocusFn, "FLAT_FOCUS_CB");
Handler.setCallback(self.ref, callback);
return self.*;
}
///
/// HELP_CB HELP_CB Action generated when the user press F1 at a control.
/// In Motif is also activated by the Help button in some workstations keyboard.
/// Callback void function(Ihandle *ih); [in C] ih:help_cb() -> (ret: number)
/// [in Lua] ih: identifier of the element that activated the event.
/// Returns: IUP_CLOSE will be processed.
/// Affects All elements with user interaction.
pub fn setHelpCallback(self: *Initializer, callback: ?OnHelpFn) Initializer {
const Handler = CallbackHandler(Self, OnHelpFn, "HELP_CB");
Handler.setCallback(self.ref, callback);
return self.*;
}
pub fn setDropMotionCallback(self: *Initializer, callback: ?OnDropMotionFn) Initializer {
const Handler = CallbackHandler(Self, OnDropMotionFn, "DROPMOTION_CB");
Handler.setCallback(self.ref, callback);
return self.*;
}
pub fn setFlatLeaveWindowCallback(self: *Initializer, callback: ?OnFlatLeaveWindowFn) Initializer {
const Handler = CallbackHandler(Self, OnFlatLeaveWindowFn, "FLAT_LEAVEWINDOW_CB");
Handler.setCallback(self.ref, callback);
return self.*;
}
///
/// KEYPRESS_CB KEYPRESS_CB Action generated when a key is pressed or released.
/// If the key is pressed and held several calls will occur.
/// It is called after the callback K_ANY is processed.
/// Callback int function(Ihandle *ih, int c, int press); [in C]
/// ih:keypress_cb(c, press: number) -> (ret: number) [in Lua] ih: identifier
/// of the element that activated the event.
/// c: identifier of typed key.
/// Please refer to the Keyboard Codes table for a list of possible values.
/// press: 1 is the user pressed the key or 0 otherwise.
/// Returns: If IUP_IGNORE is returned the key is ignored by the system.
/// IUP_CLOSE will be processed.
/// Affects IupCanvas
pub fn setKeyPressCallback(self: *Initializer, callback: ?OnKeyPressFn) Initializer {
const Handler = CallbackHandler(Self, OnKeyPressFn, "KEYPRESS_CB");
Handler.setCallback(self.ref, callback);
return self.*;
}
pub fn setDragEndCallback(self: *Initializer, callback: ?OnDragEndFn) Initializer {
const Handler = CallbackHandler(Self, OnDragEndFn, "DRAGEND_CB");
Handler.setCallback(self.ref, callback);
return self.*;
}
pub fn setDragBeginCallback(self: *Initializer, callback: ?OnDragBeginFn) Initializer {
const Handler = CallbackHandler(Self, OnDragBeginFn, "DRAGBEGIN_CB");
Handler.setCallback(self.ref, callback);
return self.*;
}
///
/// ACTION ACTION Action generated when the element is activated.
/// Affects each element differently.
/// Callback int function(Ihandle *ih); [in C] ih:action() -> (ret: number) [in
/// Lua] ih: identifier of the element that activated the event.
/// In some elements, this callback may receive more parameters, apart from ih.
/// Please refer to each element's documentation.
/// Affects IupButton, IupItem, IupList, IupText, IupCanvas, IupMultiline,
/// IupToggle
pub fn setActionCallback(self: *Initializer, callback: ?OnActionFn) Initializer {
const Handler = CallbackHandler(Self, OnActionFn, "ACTION");
Handler.setCallback(self.ref, callback);
return self.*;
}
///
/// MOTION_CB MOTION_CB Action generated when the mouse moves.
/// Callback int function(Ihandle *ih, int x, int y, char *status); [in C]
/// ih:motion_cb(x, y: number, status: string) -> (ret: number) [in Lua] ih:
/// identifier of the element that activated the event.
/// x, y: position in the canvas where the event has occurred, in pixels.
/// status: status of mouse buttons and certain keyboard keys at the moment the
/// event was generated.
/// The same macros used for BUTTON_CB can be used for this status.
/// Notes Between press and release all mouse events are redirected only to
/// this control, even if the cursor moves outside the element.
/// So the BUTTON_CB callback when released and the MOTION_CB callback can be
/// called with coordinates outside the element rectangle.
/// Affects IupCanvas, IupGLCanvas
pub fn setMotionCallback(self: *Initializer, callback: ?OnMotionFn) Initializer {
const Handler = CallbackHandler(Self, OnMotionFn, "MOTION_CB");
Handler.setCallback(self.ref, callback);
return self.*;
}
pub fn setFlatEnterWindowCallback(self: *Initializer, callback: ?OnFlatEnterWindowFn) Initializer {
const Handler = CallbackHandler(Self, OnFlatEnterWindowFn, "FLAT_ENTERWINDOW_CB");
Handler.setCallback(self.ref, callback);
return self.*;
}
///
/// WHEEL_CB WHEEL_CB Action generated when the mouse wheel is rotated.
/// If this callback is not defined the wheel will automatically scroll the
/// canvas in the vertical direction by some lines, the SCROLL_CB callback if
/// defined will be called with the IUP_SBDRAGV operation.
/// Callback int function(Ihandle *ih, float delta, int x, int y, char
/// *status); [in C] ih:wheel_cb(delta, x, y: number, status: string) -> (ret:
/// number) [in Lua] ih: identifier of the element that activated the event.
/// delta: the amount the wheel was rotated in notches.
/// x, y: position in the canvas where the event has occurred, in pixels.
/// status: status of mouse buttons and certain keyboard keys at the moment the
/// event was generated.
/// The same macros used for BUTTON_CB can be used for this status.
/// Notes In Motif and GTK delta is always 1 or -1.
/// In Windows is some situations delta can reach the value of two.
/// In the future with more precise wheels this increment can be changed.
/// Affects IupCanvas, IupGLCanvas
pub fn setWheelCallback(self: *Initializer, callback: ?OnWheelFn) Initializer {
const Handler = CallbackHandler(Self, OnWheelFn, "WHEEL_CB");
Handler.setCallback(self.ref, callback);
return self.*;
}
///
/// MAP_CB MAP_CB Called right after an element is mapped and its attributes
/// updated in IupMap.
/// When the element is a dialog, it is called after the layout is updated.
/// For all other elements is called before the layout is updated, so the
/// element current size will still be 0x0 during MAP_CB (since 3.14).
/// Callback int function(Ihandle *ih); [in C] ih:map_cb() -> (ret: number) [in
/// Lua] ih: identifier of the element that activated the event.
/// Affects All that have a native representation.
pub fn setMapCallback(self: *Initializer, callback: ?OnMapFn) Initializer {
const Handler = CallbackHandler(Self, OnMapFn, "MAP_CB");
Handler.setCallback(self.ref, callback);
return self.*;
}
pub fn setFlatButtonCallback(self: *Initializer, callback: ?OnFlatButtonFn) Initializer {
const Handler = CallbackHandler(Self, OnFlatButtonFn, "FLAT_BUTTON_CB");
Handler.setCallback(self.ref, callback);
return self.*;
}
///
/// ENTERWINDOW_CB ENTERWINDOW_CB Action generated when the mouse enters the
/// native element.
/// Callback int function(Ihandle *ih); [in C] ih:enterwindow_cb() -> (ret:
/// number) [in Lua] ih: identifier of the element that activated the event.
/// Notes When the cursor is moved from one element to another, the call order
/// in all platforms will be first the LEAVEWINDOW_CB callback of the old
/// control followed by the ENTERWINDOW_CB callback of the new control.
/// (since 3.14) If the mouse button is hold pressed and the cursor moves
/// outside the element the behavior is system dependent.
/// In Windows the LEAVEWINDOW_CB/ENTERWINDOW_CB callbacks are NOT called, in
/// GTK the callbacks are called.
/// Affects All controls with user interaction.
/// See Also LEAVEWINDOW_CB
pub fn setEnterWindowCallback(self: *Initializer, callback: ?OnEnterWindowFn) Initializer {
const Handler = CallbackHandler(Self, OnEnterWindowFn, "ENTERWINDOW_CB");
Handler.setCallback(self.ref, callback);
return self.*;
}
///
/// DESTROY_CB DESTROY_CB Called right before an element is destroyed.
/// Callback int function(Ihandle *ih); [in C] ih:destroy_cb() -> (ret: number)
/// [in Lua] ih: identifier of the element that activated the event.
/// Notes If the dialog is visible then it is hidden before it is destroyed.
/// The callback will be called right after it is hidden.
/// The callback will be called before all other destroy procedures.
/// For instance, if the element has children then it is called before the
/// children are destroyed.
/// For language binding implementations use the callback name "LDESTROY_CB" to
/// release memory allocated by the binding for the element.
/// Also the callback will be called before the language callback.
/// Affects All.
pub fn setDestroyCallback(self: *Initializer, callback: ?OnDestroyFn) Initializer {
const Handler = CallbackHandler(Self, OnDestroyFn, "DESTROY_CB");
Handler.setCallback(self.ref, callback);
return self.*;
}
pub fn setDropDataCallback(self: *Initializer, callback: ?OnDropDataFn) Initializer {
const Handler = CallbackHandler(Self, OnDropDataFn, "DROPDATA_CB");
Handler.setCallback(self.ref, callback);
return self.*;
}
///
/// KILLFOCUS_CB KILLFOCUS_CB Action generated when an element loses keyboard focus.
/// This callback is called before the GETFOCUS_CB of the element that gets the focus.
/// Callback int function(Ihandle *ih); [in C] ih:killfocus_cb() -> (ret:
/// number) [in Lua] ih: identifier of the element that activated the event.
/// Affects All elements with user interaction, except menus.
/// In Windows, there are restrictions when using this callback.
/// From MSDN on WM_KILLFOCUS: "While processing this message, do not make any
/// function calls that display or activate a window.
/// This causes the thread to yield control and can cause the application to
/// stop responding to messages.
/// See Also GETFOCUS_CB, IupGetFocus, IupSetFocus
pub fn setKillFocusCallback(self: *Initializer, callback: ?OnKillFocusFn) Initializer {
const Handler = CallbackHandler(Self, OnKillFocusFn, "KILLFOCUS_CB");
Handler.setCallback(self.ref, callback);
return self.*;
}
///
/// DROPSHOW_CB: Action generated right after the drop child is shown or hidden.
/// This callback is also called when SHOWDROPDOWN is set.
/// int function (Ihandle *ih, int state); [in C]ih:dropdown_cb(state: boolean)
/// -> (ret: number) [in Lua]
pub fn setDropShowCallback(self: *Initializer, callback: ?OnDropShowFn) Initializer {
const Handler = CallbackHandler(Self, OnDropShowFn, "DROPSHOW_CB");
Handler.setCallback(self.ref, callback);
return self.*;
}
pub fn setDragDataCallback(self: *Initializer, callback: ?OnDragDataFn) Initializer {
const Handler = CallbackHandler(Self, OnDragDataFn, "DRAGDATA_CB");
Handler.setCallback(self.ref, callback);
return self.*;
}
pub fn setDragDataSizeCallback(self: *Initializer, callback: ?OnDragDataSizeFn) Initializer {
const Handler = CallbackHandler(Self, OnDragDataSizeFn, "DRAGDATASIZE_CB");
Handler.setCallback(self.ref, callback);
return self.*;
}
///
/// DROPFILES_CB DROPFILES_CB Action called when a file is "dropped" into the control.
/// When several files are dropped at once, the callback is called several
/// times, once for each file.
/// If defined after the element is mapped then the attribute DROPFILESTARGET
/// must be set to YES.
/// [Windows and GTK Only] (GTK 2.6) Callback int function(Ihandle *ih, const
/// char* filename, int num, int x, int y); [in C] ih:dropfiles_cb(filename:
/// string; num, x, y: number) -> (ret: number) [in Lua] ih: identifier of the
/// element that activated the event.
/// filename: Name of the dropped file.
/// num: Number index of the dropped file.
/// If several files are dropped, num is the index of the dropped file starting
/// from "total-1" to "0".
/// x: X coordinate of the point where the user released the mouse button.
/// y: Y coordinate of the point where the user released the mouse button.
/// Returns: If IUP_IGNORE is returned the callback will NOT be called for the
/// next dropped files, and the processing of dropped files will be interrupted.
/// Affects IupDialog, IupCanvas, IupGLCanvas, IupText, IupList
pub fn setDropFilesCallback(self: *Initializer, callback: ?OnDropFilesFn) Initializer {
const Handler = CallbackHandler(Self, OnDropFilesFn, "DROPFILES_CB");
Handler.setCallback(self.ref, callback);
return self.*;
}
///
/// RESIZE_CB RESIZE_CB Action generated when the canvas or dialog size is changed.
/// Callback int function(Ihandle *ih, int width, int height); [in C]
/// ih:resize_cb(width, height: number) -> (ret: number) [in Lua] ih:
/// identifier of the element that activated the event.
/// width: the width of the internal element size in pixels not considering the
/// decorations (client size) height: the height of the internal element size
/// in pixels not considering the decorations (client size) Notes For the
/// dialog, this action is also generated when the dialog is mapped, after the
/// map and before the show.
/// When XAUTOHIDE=Yes or YAUTOHIDE=Yes, if the canvas scrollbar is
/// hidden/shown after changing the DX or DY attributes from inside the
/// callback, the size of the drawing area will immediately change, so the
/// parameters with and height will be invalid.
/// To update the parameters consult the DRAWSIZE attribute.
/// Also activate the drawing toolkit only after updating the DX or DY attributes.
/// Affects IupCanvas, IupGLCanvas, IupDialog
pub fn setResizeCallback(self: *Initializer, callback: ?OnResizeFn) Initializer {
const Handler = CallbackHandler(Self, OnResizeFn, "RESIZE_CB");
Handler.setCallback(self.ref, callback);
return self.*;
}
///
/// UNMAP_CB UNMAP_CB Called right before an element is unmapped.
/// Callback int function(Ihandle *ih); [in C] ih:unmap_cb() -> (ret: number)
/// [in Lua] ih: identifier of the element that activated the event.
/// Affects All that have a native representation.
pub fn setUnmapCallback(self: *Initializer, callback: ?OnUnmapFn) Initializer {
const Handler = CallbackHandler(Self, OnUnmapFn, "UNMAP_CB");
Handler.setCallback(self.ref, callback);
return self.*;
}
///
/// FLAT_ACTION: Action generated when the button 1 (usually left) is selected.
/// This callback is called only after the mouse is released and when it is
/// released inside the button area.
/// Called only when DROPONARROW=Yes.
/// int function(Ihandle* ih); [in C]ih:action() -> (ret: number) [in Lua]
pub fn setFlatActionCallback(self: *Initializer, callback: ?OnFlatActionFn) Initializer {
const Handler = CallbackHandler(Self, OnFlatActionFn, "FLAT_ACTION");
Handler.setCallback(self.ref, callback);
return self.*;
}
///
/// GETFOCUS_CB GETFOCUS_CB Action generated when an element is given keyboard focus.
/// This callback is called after the KILLFOCUS_CB of the element that loosed
/// the focus.
/// The IupGetFocus function during the callback returns the element that
/// loosed the focus.
/// Callback int function(Ihandle *ih); [in C] ih:getfocus_cb() -> (ret:
/// number) [in Lua] ih: identifier of the element that received keyboard focus.
/// Affects All elements with user interaction, except menus.
/// See Also KILLFOCUS_CB, IupGetFocus, IupSetFocus
pub fn setGetFocusCallback(self: *Initializer, callback: ?OnGetFocusFn) Initializer {
const Handler = CallbackHandler(Self, OnGetFocusFn, "GETFOCUS_CB");
Handler.setCallback(self.ref, callback);
return self.*;
}
///
/// BUTTON_CB BUTTON_CB Action generated when a mouse button is pressed or released.
/// Callback int function(Ihandle* ih, int button, int pressed, int x, int y,
/// char* status); [in C] ih:button_cb(button, pressed, x, y: number, status:
/// string) -> (ret: number) [in Lua] ih: identifies the element that activated
/// the event.
/// button: identifies the activated mouse button: IUP_BUTTON1 - left mouse
/// button (button 1); IUP_BUTTON2 - middle mouse button (button 2);
/// IUP_BUTTON3 - right mouse button (button 3).
/// pressed: indicates the state of the button: 0 - mouse button was released;
/// 1 - mouse button was pressed.
/// x, y: position in the canvas where the event has occurred, in pixels.
/// status: status of the mouse buttons and some keyboard keys at the moment
/// the event is generated.
/// The following macros must be used for verification: iup_isshift(status)
/// iup_iscontrol(status) iup_isbutton1(status) iup_isbutton2(status)
/// iup_isbutton3(status) iup_isbutton4(status) iup_isbutton5(status)
/// iup_isdouble(status) iup_isalt(status) iup_issys(status) They return 1 if
/// the respective key or button is pressed, and 0 otherwise.
/// These macros are also available in Lua, returning a boolean.
/// Returns: IUP_CLOSE will be processed.
/// On some controls if IUP_IGNORE is returned the action is ignored (this is
/// system dependent).
/// Notes This callback can be used to customize a button behavior.
/// For a standard button behavior use the ACTION callback of the IupButton.
/// For a single click the callback is called twice, one for pressed=1 and one
/// for pressed=0.
/// Only after both calls the ACTION callback is called.
/// In Windows, if a dialog is shown or popup in any situation there could be
/// unpredictable results because the native system still has processing to be
/// done even after the callback is called.
/// A double click is preceded by two single clicks, one for pressed=1 and one
/// for pressed=0, and followed by a press=0, all three without the double
/// click flag set.
/// In GTK, it is preceded by an additional two single clicks sequence.
/// For example, for one double click all the following calls are made:
/// BUTTON_CB(but=1 (1), x=154, y=83 [ 1 ]) BUTTON_CB(but=1 (0), x=154, y=83 [
/// 1 ]) BUTTON_CB(but=1 (1), x=154, y=83 [ 1 ]) (in GTK only) BUTTON_CB(but=1
/// (0), x=154, y=83 [ 1 ]) (in GTK only) BUTTON_CB(but=1 (1), x=154, y=83 [ 1
/// D ]) BUTTON_CB(but=1 (0), x=154, y=83 [ 1 ]) Between press and release all
/// mouse events are redirected only to this control, even if the cursor moves
/// outside the element.
/// So the BUTTON_CB callback when released and the MOTION_CB callback can be
/// called with coordinates outside the element rectangle.
/// Affects IupCanvas, IupButton, IupText, IupList, IupGLCanvas
pub fn setButtonCallback(self: *Initializer, callback: ?OnButtonFn) Initializer {
const Handler = CallbackHandler(Self, OnButtonFn, "BUTTON_CB");
Handler.setCallback(self.ref, callback);
return self.*;
}
pub fn setFlatMotionCallback(self: *Initializer, callback: ?OnFlatMotionFn) Initializer {
const Handler = CallbackHandler(Self, OnFlatMotionFn, "FLAT_MOTION_CB");
Handler.setCallback(self.ref, callback);
return self.*;
}
///
/// DROPDOWN_CB: Action generated right before the drop child is shown or hidden.
/// This callback is also called when SHOWDROPDOWN is set.
/// int function (Ihandle *ih, int state); [in C]ih:dropdown_cb(state: boolean)
/// -> (ret: number) [in Lua]
pub fn setDropDownCallback(self: *Initializer, callback: ?OnDropDownFn) Initializer {
const Handler = CallbackHandler(Self, OnDropDownFn, "DROPDOWN_CB");
Handler.setCallback(self.ref, callback);
return self.*;
}
pub fn setLDestroyCallback(self: *Initializer, callback: ?OnLDestroyFn) Initializer {
const Handler = CallbackHandler(Self, OnLDestroyFn, "LDESTROY_CB");
Handler.setCallback(self.ref, callback);
return self.*;
}
///
/// LEAVEWINDOW_CB LEAVEWINDOW_CB Action generated when the mouse leaves the
/// native element.
/// Callback int function(Ihandle *ih); [in C] ih:leavewindow_cb() -> (ret:
/// number) [in Lua] ih: identifier of the element that activated the event.
/// Notes When the cursor is moved from one element to another, the call order
/// in all platforms will be first the LEAVEWINDOW_CB callback of the old
/// control followed by the ENTERWINDOW_CB callback of the new control.
/// (since 3.14) If the mouse button is hold pressed and the cursor moves
/// outside the element the behavior is system dependent.
/// In Windows the LEAVEWINDOW_CB/ENTERWINDOW_CB callbacks are NOT called, in
/// GTK the callbacks are called.
/// Affects All controls with user interaction.
/// See Also ENTERWINDOW_CB
pub fn setLeaveWindowCallback(self: *Initializer, callback: ?OnLeaveWindowFn) Initializer {
const Handler = CallbackHandler(Self, OnLeaveWindowFn, "LEAVEWINDOW_CB");
Handler.setCallback(self.ref, callback);
return self.*;
}
pub fn setPostMessageCallback(self: *Initializer, callback: ?OnPostMessageFn) Initializer {
const Handler = CallbackHandler(Self, OnPostMessageFn, "POSTMESSAGE_CB");
Handler.setCallback(self.ref, callback);
return self.*;
}
};
pub fn setStrAttribute(self: *Self, attribute: [:0]const u8, arg: [:0]const u8) void {
interop.setStrAttribute(self, attribute, .{}, arg);
}
pub fn getStrAttribute(self: *Self, attribute: [:0]const u8) [:0]const u8 {
return interop.getStrAttribute(self, attribute, .{});
}
pub fn setIntAttribute(self: *Self, attribute: [:0]const u8, arg: i32) void {
interop.setIntAttribute(self, attribute, .{}, arg);
}
pub fn getIntAttribute(self: *Self, attribute: [:0]const u8) i32 {
return interop.getIntAttribute(self, attribute, .{});
}
pub fn setBoolAttribute(self: *Self, attribute: [:0]const u8, arg: bool) void {
interop.setBoolAttribute(self, attribute, .{}, arg);
}
pub fn getBoolAttribute(self: *Self, attribute: [:0]const u8) bool {
return interop.getBoolAttribute(self, attribute, .{});
}
pub fn getPtrAttribute(self: *Self, comptime T: type, attribute: [:0]const u8) ?*T {
return interop.getPtrAttribute(T, self, attribute, .{});
}
pub fn setPtrAttribute(self: *Self, comptime T: type, attribute: [:0]const u8, value: ?*T) void {
interop.setPtrAttribute(T, self, attribute, .{}, value);
}
pub fn setHandle(self: *Self, arg: [:0]const u8) void {
interop.setHandle(self, arg);
}
pub fn fromHandleName(handle_name: [:0]const u8) ?*Self {
return interop.fromHandleName(Self, handle_name);
}
///
/// Creates an interface element given its class name and parameters.
/// After creation the element still needs to be attached to a container and mapped to the native system so it can be visible.
pub fn init() Initializer {
var handle = interop.create(Self);
if (handle) |valid| {
return .{
.ref = @ptrCast(*Self, valid),
};
} else {
return .{ .ref = undefined, .last_error = Error.NotInitialized };
}
}
///
/// Destroys an interface element and all its children.
/// Only dialogs, timers, popup menus and images should be normally destroyed, but detached elements can also be destroyed.
pub fn deinit(self: *Self) void {
interop.destroy(self);
}
///
/// Creates (maps) the native interface objects corresponding to the given IUP interface elements.
/// It will also called recursively to create the native element of all the children in the element's tree.
/// The element must be already attached to a mapped container, except the dialog. A child can only be mapped if its parent is already mapped.
/// This function is automatically called before the dialog is shown in IupShow, IupShowXY or IupPopup.
/// If the element is a dialog then the abstract layout will be updated even if the dialog is already mapped. If the dialog is visible the elements will be immediately repositioned. Calling IupMap for an already mapped dialog is the same as only calling IupRefresh for the dialog.
/// Calling IupMap for an already mapped element that is not a dialog does nothing.
/// If you add new elements to an already mapped dialog you must call IupMap for that elements. And then call IupRefresh to update the dialog layout.
/// If the WID attribute of an element is NULL, it means the element was not already mapped. Some containers do not have a native element associated, like VBOX and HBOX. In this case their WID is a fake value (void*)(-1).
/// It is useful for the application to call IupMap when the value of the WID attribute must be known, i.e. the native element must exist, before a dialog is made visible.
/// The MAP_CB callback is called at the end of the IupMap function, after all processing, so it can also be used to create other things that depend on the WID attribute. But notice that for non dialog elements it will be called before the dialog layout has been updated, so the element current size will still be 0x0 (since 3.14).
pub fn map(self: *Self) !void {
try interop.map(self);
}
///
///
pub fn getDialog(self: *Self) ?*iup.Dialog {
return interop.getDialog(self);
}
///
/// Returns the the child element that has the NAME attribute equals to the given value on the same dialog hierarchy.
/// Works also for children of a menu that is associated with a dialog.
pub fn getDialogChild(self: *Self, byName: [:0]const u8) ?Element {
return interop.getDialogChild(self, byName);
}
///
/// Updates the size and layout of all controls in the same dialog.
/// To be used after changing size attributes, or attributes that affect the size of the control. Can be used for any element inside a dialog, but the layout of the dialog and all controls will be updated. It can change the layout of all the controls inside the dialog because of the dynamic layout positioning.
pub fn refresh(self: *Self) void {
Impl(Self).refresh(self);
}
///
/// FGCOLOR: Text color.
/// Default: the global attribute DLGFGCOLOR.
pub fn getFgColor(self: *Self) ?iup.Rgb {
return interop.getRgb(self, "FGCOLOR", .{});
}
///
/// FGCOLOR: Text color.
/// Default: the global attribute DLGFGCOLOR.
pub fn setFgColor(self: *Self, rgb: iup.Rgb) void {
interop.setRgb(self, "FGCOLOR", .{}, rgb);
}
pub fn getHandleName(self: *Self) [:0]const u8 {
return interop.getStrAttribute(self, "HANDLENAME", .{});
}
pub fn setHandleName(self: *Self, arg: [:0]const u8) void {
interop.setStrAttribute(self, "HANDLENAME", .{}, arg);
}
pub fn getTipBgColor(self: *Self) ?iup.Rgb {
return interop.getRgb(self, "TIPBGCOLOR", .{});
}
pub fn setTipBgColor(self: *Self, rgb: iup.Rgb) void {
interop.setRgb(self, "TIPBGCOLOR", .{}, rgb);
}
///
/// HASFOCUS (read-only): returns the button state if has focus.
/// Can be Yes or No.
pub fn getHasFocus(self: *Self) bool {
return interop.getBoolAttribute(self, "HASFOCUS", .{});
}
///
/// FRONTIMAGEHIGHLIGHT (non inheritable): foreground image name of the element
/// in highlight state.
/// If it is not defined then the FRONTIMAGE is used.
pub fn getFrontImageHighlight(self: *Self) ?iup.Element {
if (interop.getHandleAttribute(self, "FRONTIMAGEHIGHLIGHT", .{})) |handle| {
return iup.Element.fromHandle(handle);
} else {
return null;
}
}
///
/// FRONTIMAGEHIGHLIGHT (non inheritable): foreground image name of the element
/// in highlight state.
/// If it is not defined then the FRONTIMAGE is used.
pub fn setFrontImageHighlight(self: *Self, arg: anytype) !void {
try interop.validateHandle(.Image, arg);
interop.setHandleAttribute(self, "FRONTIMAGEHIGHLIGHT", .{}, arg);
}
pub fn setFrontImageHighlightHandleName(self: *Self, arg: [:0]const u8) void {
interop.setStrAttribute(self, "FRONTIMAGEHIGHLIGHT", .{}, arg);
}
pub fn getXMin(self: *Self) i32 {
return interop.getIntAttribute(self, "XMIN", .{});
}
pub fn setXMin(self: *Self, arg: i32) void {
interop.setIntAttribute(self, "XMIN", .{}, arg);
}
pub fn getTipIcon(self: *Self) [:0]const u8 {
return interop.getStrAttribute(self, "TIPICON", .{});
}
pub fn setTipIcon(self: *Self, arg: [:0]const u8) void {
interop.setStrAttribute(self, "TIPICON", .{}, arg);
}
pub fn getMaxSize(self: *Self) Size {
var str = interop.getStrAttribute(self, "MAXSIZE", .{});
return Size.parse(str);
}
pub fn setMaxSize(self: *Self, width: ?i32, height: ?i32) void {
var buffer: [128]u8 = undefined;
var value = Size.intIntToString(&buffer, width, height);
interop.setStrAttribute(self, "MAXSIZE", .{}, value);
}
///
/// ARROWIMAGEPRESS (non inheritable): Arrow image name of the element in
/// pressed state.
/// If it is not defined then the ARROWIMAGE is used.
pub fn getArrowImagePress(self: *Self) ?iup.Element {
if (interop.getHandleAttribute(self, "ARROWIMAGEPRESS", .{})) |handle| {
return iup.Element.fromHandle(handle);
} else {
return null;
}
}
///
/// ARROWIMAGEPRESS (non inheritable): Arrow image name of the element in
/// pressed state.
/// If it is not defined then the ARROWIMAGE is used.
pub fn setArrowImagePress(self: *Self, arg: anytype) !void {
try interop.validateHandle(.Image, arg);
interop.setHandleAttribute(self, "ARROWIMAGEPRESS", .{}, arg);
}
pub fn setArrowImagePressHandleName(self: *Self, arg: [:0]const u8) void {
interop.setStrAttribute(self, "ARROWIMAGEPRESS", .{}, arg);
}
pub fn getDrawTextWrap(self: *Self) bool {
return interop.getBoolAttribute(self, "DRAWTEXTWRAP", .{});
}
pub fn setDrawTextWrap(self: *Self, arg: bool) void {
interop.setBoolAttribute(self, "DRAWTEXTWRAP", .{}, arg);
}
pub fn getScreenPosition(self: *Self) iup.XYPos {
var str = interop.getStrAttribute(self, "SCREENPOSITION", .{});
return iup.XYPos.parse(str, ',');
}
///
/// FOCUSFEEDBACK (non inheritable): draw the focus feedback.
/// Can be Yes or No.
/// Default: Yes.
/// (since 3.26)
pub fn getFocusFeedback(self: *Self) bool {
return interop.getBoolAttribute(self, "FOCUSFEEDBACK", .{});
}
///
/// FOCUSFEEDBACK (non inheritable): draw the focus feedback.
/// Can be Yes or No.
/// Default: Yes.
/// (since 3.26)
pub fn setFocusFeedback(self: *Self, arg: bool) void {
interop.setBoolAttribute(self, "FOCUSFEEDBACK", .{}, arg);
}
pub fn getPosition(self: *Self) iup.XYPos {
var str = interop.getStrAttribute(self, "POSITION", .{});
return iup.XYPos.parse(str, ',');
}
pub fn setPosition(self: *Self, x: i32, y: i32) void {
var buffer: [128]u8 = undefined;
var value = iup.XYPos.intIntToString(&buffer, x, y, ',');
interop.setStrAttribute(self, "POSITION", .{}, value);
}
pub fn getDropFilesTarget(self: *Self) bool {
return interop.getBoolAttribute(self, "DROPFILESTARGET", .{});
}
pub fn setDropFilesTarget(self: *Self, arg: bool) void {
interop.setBoolAttribute(self, "DROPFILESTARGET", .{}, arg);
}
pub fn getDrawTextAlignment(self: *Self) ?DrawTextAlignment {
var ret = interop.getStrAttribute(self, "DRAWTEXTALIGNMENT", .{});
if (std.ascii.eqlIgnoreCase("ACENTER", ret)) return .ACenter;
if (std.ascii.eqlIgnoreCase("ARIGHT", ret)) return .ARight;
if (std.ascii.eqlIgnoreCase("ALEFT", ret)) return .ALeft;
return null;
}
pub fn setDrawTextAlignment(self: *Self, arg: ?DrawTextAlignment) void {
if (arg) |value| switch (value) {
.ACenter => interop.setStrAttribute(self, "DRAWTEXTALIGNMENT", .{}, "ACENTER"),
.ARight => interop.setStrAttribute(self, "DRAWTEXTALIGNMENT", .{}, "ARIGHT"),
.ALeft => interop.setStrAttribute(self, "DRAWTEXTALIGNMENT", .{}, "ALEFT"),
} else {
interop.clearAttribute(self, "DRAWTEXTALIGNMENT", .{});
}
}
pub fn getTip(self: *Self) [:0]const u8 {
return interop.getStrAttribute(self, "TIP", .{});
}
pub fn setTip(self: *Self, arg: [:0]const u8) void {
interop.setStrAttribute(self, "TIP", .{}, arg);
}
pub fn getDrawTextLayoutCenter(self: *Self) bool {
return interop.getBoolAttribute(self, "DRAWTEXTLAYOUTCENTER", .{});
}
pub fn setDrawTextLayoutCenter(self: *Self, arg: bool) void {
interop.setBoolAttribute(self, "DRAWTEXTLAYOUTCENTER", .{}, arg);
}
pub fn getDragSourceMove(self: *Self) bool {
return interop.getBoolAttribute(self, "DRAGSOURCEMOVE", .{});
}
pub fn setDragSourceMove(self: *Self, arg: bool) void {
interop.setBoolAttribute(self, "DRAGSOURCEMOVE", .{}, arg);
}
///
/// PSCOLOR: background color used to indicate a press state.
/// Pre-defined to "150 200 235".
/// Can be set to NULL.
/// If NULL BGCOLOR will be used instead.
pub fn getPsColor(self: *Self) ?iup.Rgb {
return interop.getRgb(self, "PSCOLOR", .{});
}
///
/// PSCOLOR: background color used to indicate a press state.
/// Pre-defined to "150 200 235".
/// Can be set to NULL.
/// If NULL BGCOLOR will be used instead.
pub fn setPsColor(self: *Self, rgb: iup.Rgb) void {
interop.setRgb(self, "PSCOLOR", .{}, rgb);
}
pub fn getVisible(self: *Self) bool {
return interop.getBoolAttribute(self, "VISIBLE", .{});
}
pub fn setVisible(self: *Self, arg: bool) void {
interop.setBoolAttribute(self, "VISIBLE", .{}, arg);
}
///
/// IMAGE (non inheritable): Image name.
/// Use IupSetHandle or IupSetAttributeHandle to associate an image to a name.
/// See also IupImage.
pub fn getImage(self: *Self) ?iup.Element {
if (interop.getHandleAttribute(self, "IMAGE", .{})) |handle| {
return iup.Element.fromHandle(handle);
} else {
return null;
}
}
///
/// IMAGE (non inheritable): Image name.
/// Use IupSetHandle or IupSetAttributeHandle to associate an image to a name.
/// See also IupImage.
pub fn setImage(self: *Self, arg: anytype) !void {
try interop.validateHandle(.Image, arg);
interop.setHandleAttribute(self, "IMAGE", .{}, arg);
}
pub fn setImageHandleName(self: *Self, arg: [:0]const u8) void {
interop.setStrAttribute(self, "IMAGE", .{}, arg);
}
pub fn getLineX(self: *Self) f64 {
return interop.getDoubleAttribute(self, "LINEX", .{});
}
pub fn setLineX(self: *Self, arg: f64) void {
interop.setDoubleAttribute(self, "LINEX", .{}, arg);
}
pub fn getCursor(self: *Self) ?iup.Element {
if (interop.getHandleAttribute(self, "CURSOR", .{})) |handle| {
return iup.Element.fromHandle(handle);
} else {
return null;
}
}
pub fn setCursor(self: *Self, arg: anytype) !void {
try interop.validateHandle(.Image, arg);
interop.setHandleAttribute(self, "CURSOR", .{}, arg);
}
pub fn setCursorHandleName(self: *Self, arg: [:0]const u8) void {
interop.setStrAttribute(self, "CURSOR", .{}, arg);
}
pub fn getLineY(self: *Self) f64 {
return interop.getDoubleAttribute(self, "LINEY", .{});
}
pub fn setLineY(self: *Self, arg: f64) void {
interop.setDoubleAttribute(self, "LINEY", .{}, arg);
}
pub fn zOrder(self: *Self, arg: ?ZOrder) void {
if (arg) |value| switch (value) {
.Top => interop.setStrAttribute(self, "ZORDER", .{}, "TOP"),
.Bottom => interop.setStrAttribute(self, "ZORDER", .{}, "BOTTOM"),
} else {
interop.clearAttribute(self, "ZORDER", .{});
}
}
pub fn getDrawLineWidth(self: *Self) i32 {
return interop.getIntAttribute(self, "DRAWLINEWIDTH", .{});
}
pub fn setDrawLineWidth(self: *Self, arg: i32) void {
interop.setIntAttribute(self, "DRAWLINEWIDTH", .{}, arg);
}
pub fn getX(self: *Self) i32 {
return interop.getIntAttribute(self, "X", .{});
}
pub fn getY(self: *Self) i32 {
return interop.getIntAttribute(self, "Y", .{});
}
pub fn getDragDrop(self: *Self) bool {
return interop.getBoolAttribute(self, "DRAGDROP", .{});
}
pub fn setDragDrop(self: *Self, arg: bool) void {
interop.setBoolAttribute(self, "DRAGDROP", .{}, arg);
}
pub fn getTheme(self: *Self) [:0]const u8 {
return interop.getStrAttribute(self, "THEME", .{});
}
pub fn setTheme(self: *Self, arg: [:0]const u8) void {
interop.setStrAttribute(self, "THEME", .{}, arg);
}
///
/// EXPAND (non inheritable): The default value is "NO".
pub fn getExpand(self: *Self) ?Expand {
var ret = interop.getStrAttribute(self, "EXPAND", .{});
if (std.ascii.eqlIgnoreCase("YES", ret)) return .Yes;
if (std.ascii.eqlIgnoreCase("HORIZONTAL", ret)) return .Horizontal;
if (std.ascii.eqlIgnoreCase("VERTICAL", ret)) return .Vertical;
if (std.ascii.eqlIgnoreCase("HORIZONTALFREE", ret)) return .HorizontalFree;
if (std.ascii.eqlIgnoreCase("VERTICALFREE", ret)) return .VerticalFree;
if (std.ascii.eqlIgnoreCase("NO", ret)) return .No;
return null;
}
///
/// EXPAND (non inheritable): The default value is "NO".
pub fn setExpand(self: *Self, arg: ?Expand) void {
if (arg) |value| switch (value) {
.Yes => interop.setStrAttribute(self, "EXPAND", .{}, "YES"),
.Horizontal => interop.setStrAttribute(self, "EXPAND", .{}, "HORIZONTAL"),
.Vertical => interop.setStrAttribute(self, "EXPAND", .{}, "VERTICAL"),
.HorizontalFree => interop.setStrAttribute(self, "EXPAND", .{}, "HORIZONTALFREE"),
.VerticalFree => interop.setStrAttribute(self, "EXPAND", .{}, "VERTICALFREE"),
.No => interop.setStrAttribute(self, "EXPAND", .{}, "NO"),
} else {
interop.clearAttribute(self, "EXPAND", .{});
}
}
pub fn getDrawFont(self: *Self) [:0]const u8 {
return interop.getStrAttribute(self, "DRAWFONT", .{});
}
pub fn setDrawFont(self: *Self, arg: [:0]const u8) void {
interop.setStrAttribute(self, "DRAWFONT", .{}, arg);
}
pub fn getSize(self: *Self) Size {
var str = interop.getStrAttribute(self, "SIZE", .{});
return Size.parse(str);
}
pub fn setSize(self: *Self, width: ?i32, height: ?i32) void {
var buffer: [128]u8 = undefined;
var value = Size.intIntToString(&buffer, width, height);
interop.setStrAttribute(self, "SIZE", .{}, value);
}
///
/// PADDING: internal margin.
/// Works just like the MARGIN attribute of the IupHbox and IupVbox containers,
/// but uses a different name to avoid inheritance problems.
/// Alignment does not includes the padding area.
/// Default value: "3x3".
/// Value can be DEFAULTBUTTONPADDING, so the global attribute of this name
/// will be used instead (since 3.29).
/// The natural size will be a combination of the size of the image and the
/// title, if any, plus PADDING and SPACING (if both image and title are
/// present), and plus the horizontal space occupied by the arrow.
pub fn getPadding(self: *Self) Size {
var str = interop.getStrAttribute(self, "PADDING", .{});
return Size.parse(str);
}
///
/// PADDING: internal margin.
/// Works just like the MARGIN attribute of the IupHbox and IupVbox containers,
/// but uses a different name to avoid inheritance problems.
/// Alignment does not includes the padding area.
/// Default value: "3x3".
/// Value can be DEFAULTBUTTONPADDING, so the global attribute of this name
/// will be used instead (since 3.29).
/// The natural size will be a combination of the size of the image and the
/// title, if any, plus PADDING and SPACING (if both image and title are
/// present), and plus the horizontal space occupied by the arrow.
pub fn setPadding(self: *Self, width: ?i32, height: ?i32) void {
var buffer: [128]u8 = undefined;
var value = Size.intIntToString(&buffer, width, height);
interop.setStrAttribute(self, "PADDING", .{}, value);
}
pub fn getPosX(self: *Self) f64 {
return interop.getDoubleAttribute(self, "POSX", .{});
}
pub fn setPosX(self: *Self, arg: f64) void {
interop.setDoubleAttribute(self, "POSX", .{}, arg);
}
pub fn getPosY(self: *Self) f64 {
return interop.getDoubleAttribute(self, "POSY", .{});
}
pub fn setPosY(self: *Self, arg: f64) void {
interop.setDoubleAttribute(self, "POSY", .{}, arg);
}
pub fn getWId(self: *Self) i32 {
return interop.getIntAttribute(self, "WID", .{});
}
///
/// BORDERHLCOLOR: color used for borders when highlighted.
/// Default use BORDERCOLOR.
pub fn getBorderHlColor(self: *Self) ?iup.Rgb {
return interop.getRgb(self, "BORDERHLCOLOR", .{});
}
///
/// BORDERHLCOLOR: color used for borders when highlighted.
/// Default use BORDERCOLOR.
pub fn setBorderHlColor(self: *Self, rgb: iup.Rgb) void {
interop.setRgb(self, "BORDERHLCOLOR", .{}, rgb);
}
///
/// TEXTHLCOLOR: text color used to indicate a highlight state.
/// If not defined FGCOLOR will be used instead.
/// (since 3.26)
pub fn getTextHlColor(self: *Self) ?iup.Rgb {
return interop.getRgb(self, "TEXTHLCOLOR", .{});
}
///
/// TEXTHLCOLOR: text color used to indicate a highlight state.
/// If not defined FGCOLOR will be used instead.
/// (since 3.26)
pub fn setTextHlColor(self: *Self, rgb: iup.Rgb) void {
interop.setRgb(self, "TEXTHLCOLOR", .{}, rgb);
}
pub fn getTipMarkup(self: *Self) [:0]const u8 {
return interop.getStrAttribute(self, "TIPMARKUP", .{});
}
pub fn setTipMarkup(self: *Self, arg: [:0]const u8) void {
interop.setStrAttribute(self, "TIPMARKUP", .{}, arg);
}
pub fn getYMin(self: *Self) i32 {
return interop.getIntAttribute(self, "YMIN", .{});
}
pub fn setYMin(self: *Self, arg: i32) void {
interop.setIntAttribute(self, "YMIN", .{}, arg);
}
///
/// TEXTELLIPSIS (non inheritable): If the text is larger that its box, an
/// ellipsis ("...") will be placed near the last visible part of the text and
/// replace the invisible part.
/// It will be ignored when TEXTWRAP=Yes.
/// (since 3.25)
pub fn getTextEllipsis(self: *Self) bool {
return interop.getBoolAttribute(self, "TEXTELLIPSIS", .{});
}
///
/// TEXTELLIPSIS (non inheritable): If the text is larger that its box, an
/// ellipsis ("...") will be placed near the last visible part of the text and
/// replace the invisible part.
/// It will be ignored when TEXTWRAP=Yes.
/// (since 3.25)
pub fn setTextEllipsis(self: *Self, arg: bool) void {
interop.setBoolAttribute(self, "TEXTELLIPSIS", .{}, arg);
}
pub fn getDrawMakeInactive(self: *Self) bool {
return interop.getBoolAttribute(self, "DRAWMAKEINACTIVE", .{});
}
pub fn setDrawMakeInactive(self: *Self, arg: bool) void {
interop.setBoolAttribute(self, "DRAWMAKEINACTIVE", .{}, arg);
}
pub fn getFontSize(self: *Self) i32 {
return interop.getIntAttribute(self, "FONTSIZE", .{});
}
pub fn setFontSize(self: *Self, arg: i32) void {
interop.setIntAttribute(self, "FONTSIZE", .{}, arg);
}
pub fn getNaturalSize(self: *Self) Size {
var str = interop.getStrAttribute(self, "NATURALSIZE", .{});
return Size.parse(str);
}
pub fn getDropTypes(self: *Self) [:0]const u8 {
return interop.getStrAttribute(self, "DROPTYPES", .{});
}
pub fn setDropTypes(self: *Self, arg: [:0]const u8) void {
interop.setStrAttribute(self, "DROPTYPES", .{}, arg);
}
pub fn getUserSize(self: *Self) Size {
var str = interop.getStrAttribute(self, "USERSIZE", .{});
return Size.parse(str);
}
pub fn setUserSize(self: *Self, width: ?i32, height: ?i32) void {
var buffer: [128]u8 = undefined;
var value = Size.intIntToString(&buffer, width, height);
interop.setStrAttribute(self, "USERSIZE", .{}, value);
}
pub fn getTipDelay(self: *Self) i32 {
return interop.getIntAttribute(self, "TIPDELAY", .{});
}
pub fn setTipDelay(self: *Self, arg: i32) void {
interop.setIntAttribute(self, "TIPDELAY", .{}, arg);
}
///
/// BACKIMAGEINACTIVE (non inheritable): background image name of the element
/// when inactive.
/// If it is not defined then the BACKIMAGE is used and its colors will be
/// replaced by a modified version creating the disabled effect.
pub fn getBackImageInactive(self: *Self) ?iup.Element {
if (interop.getHandleAttribute(self, "BACKIMAGEINACTIVE", .{})) |handle| {
return iup.Element.fromHandle(handle);
} else {
return null;
}
}
///
/// BACKIMAGEINACTIVE (non inheritable): background image name of the element
/// when inactive.
/// If it is not defined then the BACKIMAGE is used and its colors will be
/// replaced by a modified version creating the disabled effect.
pub fn setBackImageInactive(self: *Self, arg: anytype) !void {
try interop.validateHandle(.Image, arg);
interop.setHandleAttribute(self, "BACKIMAGEINACTIVE", .{}, arg);
}
pub fn setBackImageInactiveHandleName(self: *Self, arg: [:0]const u8) void {
interop.setStrAttribute(self, "BACKIMAGEINACTIVE", .{}, arg);
}
pub fn getScrollBar(self: *Self) bool {
return interop.getBoolAttribute(self, "SCROLLBAR", .{});
}
pub fn setScrollBar(self: *Self, arg: bool) void {
interop.setBoolAttribute(self, "SCROLLBAR", .{}, arg);
}
pub fn getXHidden(self: *Self) bool {
return interop.getBoolAttribute(self, "XHIDDEN", .{});
}
///
/// TITLE (non inheritable): Label's text.
/// The '\n' character is accepted for line change.
pub fn getTitle(self: *Self) [:0]const u8 {
return interop.getStrAttribute(self, "TITLE", .{});
}
///
/// TITLE (non inheritable): Label's text.
/// The '\n' character is accepted for line change.
pub fn setTitle(self: *Self, arg: [:0]const u8) void {
interop.setStrAttribute(self, "TITLE", .{}, arg);
}
pub fn getXAutoHide(self: *Self) bool {
return interop.getBoolAttribute(self, "XAUTOHIDE", .{});
}
pub fn setXAutoHide(self: *Self, arg: bool) void {
interop.setBoolAttribute(self, "XAUTOHIDE", .{}, arg);
}
///
/// PROPAGATEFOCUS (non inheritable): enables the focus callback forwarding to
/// the next native parent with FOCUS_CB defined.
/// Default: NO.
pub fn getPropagateFocus(self: *Self) bool {
return interop.getBoolAttribute(self, "PROPAGATEFOCUS", .{});
}
///
/// PROPAGATEFOCUS (non inheritable): enables the focus callback forwarding to
/// the next native parent with FOCUS_CB defined.
/// Default: NO.
pub fn setPropagateFocus(self: *Self, arg: bool) void {
interop.setBoolAttribute(self, "PROPAGATEFOCUS", .{}, arg);
}
pub fn getXMax(self: *Self) i32 {
return interop.getIntAttribute(self, "XMAX", .{});
}
pub fn setXMax(self: *Self, arg: i32) void {
interop.setIntAttribute(self, "XMAX", .{}, arg);
}
///
/// BGCOLOR: Background color.
/// If text and image are not defined, the button is configured to simply show
/// a color, in this case set the button size because the natural size will be
/// very small.
/// If not defined it will use the background color of the native parent.
pub fn getBgColor(self: *Self) ?iup.Rgb {
return interop.getRgb(self, "BGCOLOR", .{});
}
///
/// BGCOLOR: Background color.
/// If text and image are not defined, the button is configured to simply show
/// a color, in this case set the button size because the natural size will be
/// very small.
/// If not defined it will use the background color of the native parent.
pub fn setBgColor(self: *Self, rgb: iup.Rgb) void {
interop.setRgb(self, "BGCOLOR", .{}, rgb);
}
pub fn getDropTarget(self: *Self) bool {
return interop.getBoolAttribute(self, "DROPTARGET", .{});
}
pub fn setDropTarget(self: *Self, arg: bool) void {
interop.setBoolAttribute(self, "DROPTARGET", .{}, arg);
}
///
/// HIGHLIGHTED (read-only): returns the button state if highlighted.
/// Can be Yes or No.
pub fn getHighlightEd(self: *Self) bool {
return interop.getBoolAttribute(self, "HIGHLIGHTED", .{});
}
pub fn getDX(self: *Self) f64 {
return interop.getDoubleAttribute(self, "DX", .{});
}
pub fn setDX(self: *Self, arg: f64) void {
interop.setDoubleAttribute(self, "DX", .{}, arg);
}
pub fn getDY(self: *Self) f64 {
return interop.getDoubleAttribute(self, "DY", .{});
}
pub fn setDY(self: *Self, arg: f64) void {
interop.setDoubleAttribute(self, "DY", .{}, arg);
}
pub fn getDrawTextEllipsis(self: *Self) bool {
return interop.getBoolAttribute(self, "DRAWTEXTELLIPSIS", .{});
}
pub fn setDrawTextEllipsis(self: *Self, arg: bool) void {
interop.setBoolAttribute(self, "DRAWTEXTELLIPSIS", .{}, arg);
}
pub fn getDragSource(self: *Self) bool {
return interop.getBoolAttribute(self, "DRAGSOURCE", .{});
}
pub fn setDragSource(self: *Self, arg: bool) void {
interop.setBoolAttribute(self, "DRAGSOURCE", .{}, arg);
}
pub fn getDrawTextClip(self: *Self) bool {
return interop.getBoolAttribute(self, "DRAWTEXTCLIP", .{});
}
pub fn setDrawTextClip(self: *Self, arg: bool) void {
interop.setBoolAttribute(self, "DRAWTEXTCLIP", .{}, arg);
}
pub fn getFloating(self: *Self) ?Floating {
var ret = interop.getStrAttribute(self, "FLOATING", .{});
if (std.ascii.eqlIgnoreCase("YES", ret)) return .Yes;
if (std.ascii.eqlIgnoreCase("IGNORE", ret)) return .Ignore;
if (std.ascii.eqlIgnoreCase("NO", ret)) return .No;
return null;
}
pub fn setFloating(self: *Self, arg: ?Floating) void {
if (arg) |value| switch (value) {
.Yes => interop.setStrAttribute(self, "FLOATING", .{}, "YES"),
.Ignore => interop.setStrAttribute(self, "FLOATING", .{}, "IGNORE"),
.No => interop.setStrAttribute(self, "FLOATING", .{}, "NO"),
} else {
interop.clearAttribute(self, "FLOATING", .{});
}
}
pub fn getNormalizerGroup(self: *Self) [:0]const u8 {
return interop.getStrAttribute(self, "NORMALIZERGROUP", .{});
}
pub fn setNormalizerGroup(self: *Self, arg: [:0]const u8) void {
interop.setStrAttribute(self, "NORMALIZERGROUP", .{}, arg);
}
///
/// SPACING (non inheritable): spacing between the image and the text.
/// Default: "2".
/// The natural size will be a combination of the size of the image and the
/// title, if any, plus PADDING and SPACING (if both image and title are
/// present), and plus the horizontal space occupied by the arrow.
pub fn getSpacing(self: *Self) i32 {
return interop.getIntAttribute(self, "SPACING", .{});
}
///
/// SPACING (non inheritable): spacing between the image and the text.
/// Default: "2".
/// The natural size will be a combination of the size of the image and the
/// title, if any, plus PADDING and SPACING (if both image and title are
/// present), and plus the horizontal space occupied by the arrow.
pub fn setSpacing(self: *Self, arg: i32) void {
interop.setIntAttribute(self, "SPACING", .{}, arg);
}
///
/// BORDERPSCOLOR: color used for borders when pressed or selected.
/// Default use BORDERCOLOR.
pub fn getBorderPsColor(self: *Self) ?iup.Rgb {
return interop.getRgb(self, "BORDERPSCOLOR", .{});
}
///
/// BORDERPSCOLOR: color used for borders when pressed or selected.
/// Default use BORDERCOLOR.
pub fn setBorderPsColor(self: *Self, rgb: iup.Rgb) void {
interop.setRgb(self, "BORDERPSCOLOR", .{}, rgb);
}
pub fn getRasterSize(self: *Self) Size {
var str = interop.getStrAttribute(self, "RASTERSIZE", .{});
return Size.parse(str);
}
pub fn setRasterSize(self: *Self, width: ?i32, height: ?i32) void {
var buffer: [128]u8 = undefined;
var value = Size.intIntToString(&buffer, width, height);
interop.setStrAttribute(self, "RASTERSIZE", .{}, value);
}
///
/// TEXTPSCOLOR: text color used to indicate a press state.
/// If not defined FGCOLOR will be used instead.
/// (since 3.26)
pub fn getTextPsColor(self: *Self) ?iup.Rgb {
return interop.getRgb(self, "TEXTPSCOLOR", .{});
}
///
/// TEXTPSCOLOR: text color used to indicate a press state.
/// If not defined FGCOLOR will be used instead.
/// (since 3.26)
pub fn setTextPsColor(self: *Self, rgb: iup.Rgb) void {
interop.setRgb(self, "TEXTPSCOLOR", .{}, rgb);
}
///
/// BORDERCOLOR: color used for borders.
/// Default: "50 150 255".
/// This is for the IupDropButton drawn border.
pub fn getBorderColor(self: *Self) ?iup.Rgb {
return interop.getRgb(self, "BORDERCOLOR", .{});
}
///
/// BORDERCOLOR: color used for borders.
/// Default: "50 150 255".
/// This is for the IupDropButton drawn border.
pub fn setBorderColor(self: *Self, rgb: iup.Rgb) void {
interop.setRgb(self, "BORDERCOLOR", .{}, rgb);
}
pub fn getTipFgColor(self: *Self) ?iup.Rgb {
return interop.getRgb(self, "TIPFGCOLOR", .{});
}
pub fn setTipFgColor(self: *Self, rgb: iup.Rgb) void {
interop.setRgb(self, "TIPFGCOLOR", .{}, rgb);
}
pub fn getYHidden(self: *Self) bool {
return interop.getBoolAttribute(self, "YHIDDEN", .{});
}
///
/// ARROWIMAGEHIGHLIGHT (non inheritable): Arrow image name of the element in
/// highlight state.
/// If it is not defined then the ARROWIMAGE is used.
pub fn getArrowImageHighlight(self: *Self) ?iup.Element {
if (interop.getHandleAttribute(self, "ARROWIMAGEHIGHLIGHT", .{})) |handle| {
return iup.Element.fromHandle(handle);
} else {
return null;
}
}
///
/// ARROWIMAGEHIGHLIGHT (non inheritable): Arrow image name of the element in
/// highlight state.
/// If it is not defined then the ARROWIMAGE is used.
pub fn setArrowImageHighlight(self: *Self, arg: anytype) !void {
try interop.validateHandle(.Image, arg);
interop.setHandleAttribute(self, "ARROWIMAGEHIGHLIGHT", .{}, arg);
}
pub fn setArrowImageHighlightHandleName(self: *Self, arg: [:0]const u8) void {
interop.setStrAttribute(self, "ARROWIMAGEHIGHLIGHT", .{}, arg);
}
///
/// FRONTIMAGEINACTIVE (non inheritable): foreground image name of the element
/// when inactive.
/// If it is not defined then the FRONTIMAGE is used and its colors will be
/// replaced by a modified version creating the disabled effect.
pub fn getFrontImageInactive(self: *Self) ?iup.Element {
if (interop.getHandleAttribute(self, "FRONTIMAGEINACTIVE", .{})) |handle| {
return iup.Element.fromHandle(handle);
} else {
return null;
}
}
///
/// FRONTIMAGEINACTIVE (non inheritable): foreground image name of the element
/// when inactive.
/// If it is not defined then the FRONTIMAGE is used and its colors will be
/// replaced by a modified version creating the disabled effect.
pub fn setFrontImageInactive(self: *Self, arg: anytype) !void {
try interop.validateHandle(.Image, arg);
interop.setHandleAttribute(self, "FRONTIMAGEINACTIVE", .{}, arg);
}
pub fn setFrontImageInactiveHandleName(self: *Self, arg: [:0]const u8) void {
interop.setStrAttribute(self, "FRONTIMAGEINACTIVE", .{}, arg);
}
///
/// ARROWIMAGEINACTIVE (non inheritable): Arrow image name of the element when inactive.
/// If it is not defined then the ARROWIMAGE is used and its colors will be
/// replaced by a modified version creating the disabled effect.
pub fn getArrowImageInactive(self: *Self) ?iup.Element {
if (interop.getHandleAttribute(self, "ARROWIMAGEINACTIVE", .{})) |handle| {
return iup.Element.fromHandle(handle);
} else {
return null;
}
}
///
/// ARROWIMAGEINACTIVE (non inheritable): Arrow image name of the element when inactive.
/// If it is not defined then the ARROWIMAGE is used and its colors will be
/// replaced by a modified version creating the disabled effect.
pub fn setArrowImageInactive(self: *Self, arg: anytype) !void {
try interop.validateHandle(.Image, arg);
interop.setHandleAttribute(self, "ARROWIMAGEINACTIVE", .{}, arg);
}
pub fn setArrowImageInactiveHandleName(self: *Self, arg: [:0]const u8) void {
interop.setStrAttribute(self, "ARROWIMAGEINACTIVE", .{}, arg);
}
///
/// BACKIMAGEHIGHLIGHT (non inheritable): background image name of the element
/// in highlight state.
/// If it is not defined then the BACKIMAGE is used.
pub fn getBackImageHighlight(self: *Self) ?iup.Element {
if (interop.getHandleAttribute(self, "BACKIMAGEHIGHLIGHT", .{})) |handle| {
return iup.Element.fromHandle(handle);
} else {
return null;
}
}
///
/// BACKIMAGEHIGHLIGHT (non inheritable): background image name of the element
/// in highlight state.
/// If it is not defined then the BACKIMAGE is used.
pub fn setBackImageHighlight(self: *Self, arg: anytype) !void {
try interop.validateHandle(.Image, arg);
interop.setHandleAttribute(self, "BACKIMAGEHIGHLIGHT", .{}, arg);
}
pub fn setBackImageHighlightHandleName(self: *Self, arg: [:0]const u8) void {
interop.setStrAttribute(self, "BACKIMAGEHIGHLIGHT", .{}, arg);
}
///
/// FRONTIMAGEPRESS (non inheritable): foreground image name of the element in
/// pressed state.
/// If it is not defined then the FRONTIMAGE is used.
pub fn getFrontImagePress(self: *Self) ?iup.Element {
if (interop.getHandleAttribute(self, "FRONTIMAGEPRESS", .{})) |handle| {
return iup.Element.fromHandle(handle);
} else {
return null;
}
}
///
/// FRONTIMAGEPRESS (non inheritable): foreground image name of the element in
/// pressed state.
/// If it is not defined then the FRONTIMAGE is used.
pub fn setFrontImagePress(self: *Self, arg: anytype) !void {
try interop.validateHandle(.Image, arg);
interop.setHandleAttribute(self, "FRONTIMAGEPRESS", .{}, arg);
}
pub fn setFrontImagePressHandleName(self: *Self, arg: [:0]const u8) void {
interop.setStrAttribute(self, "FRONTIMAGEPRESS", .{}, arg);
}
///
/// CSPACING: same as SPACING but using the units of the vertical part of the
/// SIZE attribute.
/// It will actually set the SPACING attribute.
/// (since 3.29)
pub fn getCSpacing(self: *Self) i32 {
return interop.getIntAttribute(self, "CSPACING", .{});
}
///
/// CSPACING: same as SPACING but using the units of the vertical part of the
/// SIZE attribute.
/// It will actually set the SPACING attribute.
/// (since 3.29)
pub fn setCSpacing(self: *Self, arg: i32) void {
interop.setIntAttribute(self, "CSPACING", .{}, arg);
}
pub fn getDrawSize(self: *Self) Size {
var str = interop.getStrAttribute(self, "DRAWSIZE", .{});
return Size.parse(str);
}
///
/// HLCOLOR: background color used to indicate a highlight state.
/// Pre-defined to "200 225 245".
/// Can be set to NULL.
/// If NULL BGCOLOR will be used instead.
pub fn getHlColor(self: *Self) ?iup.Rgb {
return interop.getRgb(self, "HLCOLOR", .{});
}
///
/// HLCOLOR: background color used to indicate a highlight state.
/// Pre-defined to "200 225 245".
/// Can be set to NULL.
/// If NULL BGCOLOR will be used instead.
pub fn setHlColor(self: *Self, rgb: iup.Rgb) void {
interop.setRgb(self, "HLCOLOR", .{}, rgb);
}
///
/// FRONTIMAGE (non inheritable): image name to be used as foreground.
/// The foreground image is drawn in the same position as the background, but
/// it is drawn at last.
/// Use IupSetHandle or IupSetAttributeHandle to associate an image to a name.
/// See also IupImage.
pub fn getFrontImage(self: *Self) ?iup.Element {
if (interop.getHandleAttribute(self, "FRONTIMAGE", .{})) |handle| {
return iup.Element.fromHandle(handle);
} else {
return null;
}
}
///
/// FRONTIMAGE (non inheritable): image name to be used as foreground.
/// The foreground image is drawn in the same position as the background, but
/// it is drawn at last.
/// Use IupSetHandle or IupSetAttributeHandle to associate an image to a name.
/// See also IupImage.
pub fn setFrontImage(self: *Self, arg: anytype) !void {
try interop.validateHandle(.Image, arg);
interop.setHandleAttribute(self, "FRONTIMAGE", .{}, arg);
}
pub fn setFrontImageHandleName(self: *Self, arg: [:0]const u8) void {
interop.setStrAttribute(self, "FRONTIMAGE", .{}, arg);
}
pub fn getFirstControlHandle(self: *Self) ?iup.Element {
if (interop.getHandleAttribute(self, "FIRST_CONTROL_HANDLE", .{})) |handle| {
return iup.Element.fromHandle(handle);
} else {
return null;
}
}
pub fn getFontFace(self: *Self) [:0]const u8 {
return interop.getStrAttribute(self, "FONTFACE", .{});
}
pub fn setFontFace(self: *Self, arg: [:0]const u8) void {
interop.setStrAttribute(self, "FONTFACE", .{}, arg);
}
pub fn getDrawColor(self: *Self) ?iup.Rgb {
return interop.getRgb(self, "DRAWCOLOR", .{});
}
pub fn setDrawColor(self: *Self, rgb: iup.Rgb) void {
interop.setRgb(self, "DRAWCOLOR", .{}, rgb);
}
pub fn getDrawTextOrientation(self: *Self) f64 {
return interop.getDoubleAttribute(self, "DRAWTEXTORIENTATION", .{});
}
pub fn setDrawTextOrientation(self: *Self, arg: f64) void {
interop.setDoubleAttribute(self, "DRAWTEXTORIENTATION", .{}, arg);
}
pub fn getDrawBgColor(self: *Self) ?iup.Rgb {
return interop.getRgb(self, "DRAWBGCOLOR", .{});
}
pub fn setDrawBgColor(self: *Self, rgb: iup.Rgb) void {
interop.setRgb(self, "DRAWBGCOLOR", .{}, rgb);
}
///
/// VISIBLECOLUMNS: Defines the number of visible columns for the Natural Size,
/// this means that will act also as minimum number of visible columns.
/// It uses a wider character size then the one used for the SIZE attribute so
/// strings will fit better without the need of extra columns.
/// Padding will be around the visible columns.
pub fn getVisibleColumns(self: *Self) i32 {
return interop.getIntAttribute(self, "VISIBLECOLUMNS", .{});
}
///
/// VISIBLECOLUMNS: Defines the number of visible columns for the Natural Size,
/// this means that will act also as minimum number of visible columns.
/// It uses a wider character size then the one used for the SIZE attribute so
/// strings will fit better without the need of extra columns.
/// Padding will be around the visible columns.
pub fn setVisibleColumns(self: *Self, arg: i32) void {
interop.setIntAttribute(self, "VISIBLECOLUMNS", .{}, arg);
}
///
/// IMAGEPRESS (non inheritable): Image name of the element in pressed state.
/// If it is not defined then the IMAGE is used.
pub fn getImagePress(self: *Self) ?iup.Element {
if (interop.getHandleAttribute(self, "IMAGEPRESS", .{})) |handle| {
return iup.Element.fromHandle(handle);
} else {
return null;
}
}
///
/// IMAGEPRESS (non inheritable): Image name of the element in pressed state.
/// If it is not defined then the IMAGE is used.
pub fn setImagePress(self: *Self, arg: anytype) !void {
try interop.validateHandle(.Image, arg);
interop.setHandleAttribute(self, "IMAGEPRESS", .{}, arg);
}
pub fn setImagePressHandleName(self: *Self, arg: [:0]const u8) void {
interop.setStrAttribute(self, "IMAGEPRESS", .{}, arg);
}
pub fn getName(self: *Self) [:0]const u8 {
return interop.getStrAttribute(self, "NAME", .{});
}
pub fn setName(self: *Self, arg: [:0]const u8) void {
interop.setStrAttribute(self, "NAME", .{}, arg);
}
///
/// ARROWIMAGE (non inheritable): Arrow image name.
/// Use IupSetHandle or IupSetAttributeHandle to associate an image to a name.
/// See also IupImage.
pub fn getArrowImage(self: *Self) ?iup.Element {
if (interop.getHandleAttribute(self, "ARROWIMAGE", .{})) |handle| {
return iup.Element.fromHandle(handle);
} else {
return null;
}
}
///
/// ARROWIMAGE (non inheritable): Arrow image name.
/// Use IupSetHandle or IupSetAttributeHandle to associate an image to a name.
/// See also IupImage.
pub fn setArrowImage(self: *Self, arg: anytype) !void {
try interop.validateHandle(.Image, arg);
interop.setHandleAttribute(self, "ARROWIMAGE", .{}, arg);
}
pub fn setArrowImageHandleName(self: *Self, arg: [:0]const u8) void {
interop.setStrAttribute(self, "ARROWIMAGE", .{}, arg);
}
pub fn getBackingStore(self: *Self) bool {
return interop.getBoolAttribute(self, "BACKINGSTORE", .{});
}
pub fn setBackingStore(self: *Self, arg: bool) void {
interop.setBoolAttribute(self, "BACKINGSTORE", .{}, arg);
}
pub fn getDrawDriver(self: *Self) [:0]const u8 {
return interop.getStrAttribute(self, "DRAWDRIVER", .{});
}
pub fn getYAutoHide(self: *Self) bool {
return interop.getBoolAttribute(self, "YAUTOHIDE", .{});
}
pub fn setYAutoHide(self: *Self, arg: bool) void {
interop.setBoolAttribute(self, "YAUTOHIDE", .{}, arg);
}
pub fn getDrawStyle(self: *Self) ?DrawStyle {
var ret = interop.getStrAttribute(self, "DRAWSTYLE", .{});
if (std.ascii.eqlIgnoreCase("FILL", ret)) return .Fill;
if (std.ascii.eqlIgnoreCase("STROKE_DASH", ret)) return .StrokeDash;
if (std.ascii.eqlIgnoreCase("STROKE_DOT", ret)) return .StrokeDot;
if (std.ascii.eqlIgnoreCase("STROKE_DASH_DOT", ret)) return .StrokeDashDot;
if (std.ascii.eqlIgnoreCase("STROKE_DASH_DOT_DOT", ret)) return .StrokeDashDotdot;
if (std.ascii.eqlIgnoreCase("DRAW_STROKE", ret)) return .DrawStroke;
return null;
}
pub fn setDrawStyle(self: *Self, arg: ?DrawStyle) void {
if (arg) |value| switch (value) {
.Fill => interop.setStrAttribute(self, "DRAWSTYLE", .{}, "FILL"),
.StrokeDash => interop.setStrAttribute(self, "DRAWSTYLE", .{}, "STROKE_DASH"),
.StrokeDot => interop.setStrAttribute(self, "DRAWSTYLE", .{}, "STROKE_DOT"),
.StrokeDashDot => interop.setStrAttribute(self, "DRAWSTYLE", .{}, "STROKE_DASH_DOT"),
.StrokeDashDotdot => interop.setStrAttribute(self, "DRAWSTYLE", .{}, "STROKE_DASH_DOT_DOT"),
.DrawStroke => interop.setStrAttribute(self, "DRAWSTYLE", .{}, "DRAW_STROKE"),
} else {
interop.clearAttribute(self, "DRAWSTYLE", .{});
}
}
///
/// DROPCHILD_HANDLE: same as DROPCHILD but directly using the Ihandle* of the element.
pub fn getDropChildHandle(self: *Self) ?iup.Element {
if (interop.getHandleAttribute(self, "DROPCHILD_HANDLE", .{})) |handle| {
return iup.Element.fromHandle(handle);
} else {
return null;
}
}
///
/// DROPCHILD_HANDLE: same as DROPCHILD but directly using the Ihandle* of the element.
pub fn setDropChildHandle(self: *Self, arg: anytype) !void {
interop.setHandleAttribute(self, "DROPCHILD_HANDLE", .{}, arg);
}
pub fn setDropChildHandleHandleName(self: *Self, arg: [:0]const u8) void {
interop.setStrAttribute(self, "DROPCHILD_HANDLE", .{}, arg);
}
///
/// BACKIMAGEZOOM (non inheritable): if set the back image will be zoomed to
/// occupy the full background.
/// Aspect ratio is NOT preserved.
/// Can be Yes or No.
/// Default: No.
/// (since 3.25)
pub fn getBackImageZoom(self: *Self) bool {
return interop.getBoolAttribute(self, "BACKIMAGEZOOM", .{});
}
///
/// BACKIMAGEZOOM (non inheritable): if set the back image will be zoomed to
/// occupy the full background.
/// Aspect ratio is NOT preserved.
/// Can be Yes or No.
/// Default: No.
/// (since 3.25)
pub fn setBackImageZoom(self: *Self, arg: bool) void {
interop.setBoolAttribute(self, "BACKIMAGEZOOM", .{}, arg);
}
pub fn getNextControlHandle(self: *Self) ?iup.Element {
if (interop.getHandleAttribute(self, "NEXT_CONTROL_HANDLE", .{})) |handle| {
return iup.Element.fromHandle(handle);
} else {
return null;
}
}
///
/// CPADDING: same as PADDING but using the units of the SIZE attribute.
/// It will actually set the PADDING attribute.
/// (since 3.29)
pub fn getCPadding(self: *Self) Size {
var str = interop.getStrAttribute(self, "CPADDING", .{});
return Size.parse(str);
}
///
/// CPADDING: same as PADDING but using the units of the SIZE attribute.
/// It will actually set the PADDING attribute.
/// (since 3.29)
pub fn setCPadding(self: *Self, width: ?i32, height: ?i32) void {
var buffer: [128]u8 = undefined;
var value = Size.intIntToString(&buffer, width, height);
interop.setStrAttribute(self, "CPADDING", .{}, value);
}
///
/// TEXTORIENTATION (non inheritable): text angle in degrees and counterclockwise.
/// The text size will adapt to include the rotated space.
/// (since 3.25)
pub fn getTextOrientation(self: *Self) f64 {
return interop.getDoubleAttribute(self, "TEXTORIENTATION", .{});
}
///
/// TEXTORIENTATION (non inheritable): text angle in degrees and counterclockwise.
/// The text size will adapt to include the rotated space.
/// (since 3.25)
pub fn setTextOrientation(self: *Self, arg: f64) void {
interop.setDoubleAttribute(self, "TEXTORIENTATION", .{}, arg);
}
///
/// FITTOBACKIMAGE (non inheritable): enable the natural size to be computed
/// from the BACKIMAGE.
/// If BACKIMAGE is not defined will be ignored.
/// Can be Yes or No.
/// Default: No.
pub fn getFitToBackImage(self: *Self) bool {
return interop.getBoolAttribute(self, "FITTOBACKIMAGE", .{});
}
///
/// FITTOBACKIMAGE (non inheritable): enable the natural size to be computed
/// from the BACKIMAGE.
/// If BACKIMAGE is not defined will be ignored.
/// Can be Yes or No.
/// Default: No.
pub fn setFitToBackImage(self: *Self, arg: bool) void {
interop.setBoolAttribute(self, "FITTOBACKIMAGE", .{}, arg);
}
///
/// ACTIVE, FONT, EXPAND, SCREENPOSITION, POSITION, MINSIZE, MAXSIZE, WID, TIP,
/// SIZE, RASTERSIZE, ZORDER, VISIBLE, THEME: also accepted.
pub fn getActive(self: *Self) bool {
return interop.getBoolAttribute(self, "ACTIVE", .{});
}
///
/// ACTIVE, FONT, EXPAND, SCREENPOSITION, POSITION, MINSIZE, MAXSIZE, WID, TIP,
/// SIZE, RASTERSIZE, ZORDER, VISIBLE, THEME: also accepted.
pub fn setActive(self: *Self, arg: bool) void {
interop.setBoolAttribute(self, "ACTIVE", .{}, arg);
}
pub fn getTipVisible(self: *Self) bool {
return interop.getBoolAttribute(self, "TIPVISIBLE", .{});
}
pub fn setTipVisible(self: *Self, arg: bool) void {
interop.setBoolAttribute(self, "TIPVISIBLE", .{}, arg);
}
///
/// IMAGEHIGHLIGHT (non inheritable): Image name of the element in highlight state.
/// If it is not defined then the IMAGE is used.
pub fn getImageHighlight(self: *Self) ?iup.Element {
if (interop.getHandleAttribute(self, "IMAGEHIGHLIGHT", .{})) |handle| {
return iup.Element.fromHandle(handle);
} else {
return null;
}
}
///
/// IMAGEHIGHLIGHT (non inheritable): Image name of the element in highlight state.
/// If it is not defined then the IMAGE is used.
pub fn setImageHighlight(self: *Self, arg: anytype) !void {
try interop.validateHandle(.Image, arg);
interop.setHandleAttribute(self, "IMAGEHIGHLIGHT", .{}, arg);
}
pub fn setImageHighlightHandleName(self: *Self, arg: [:0]const u8) void {
interop.setStrAttribute(self, "IMAGEHIGHLIGHT", .{}, arg);
}
pub fn getYMax(self: *Self) i32 {
return interop.getIntAttribute(self, "YMAX", .{});
}
pub fn setYMax(self: *Self, arg: i32) void {
interop.setIntAttribute(self, "YMAX", .{}, arg);
}
///
/// BACKIMAGE (non inheritable): image name to be used as background.
/// Use IupSetHandle or IupSetAttributeHandle to associate an image to a name.
/// See also IupImage.
pub fn getBackImage(self: *Self) ?iup.Element {
if (interop.getHandleAttribute(self, "BACKIMAGE", .{})) |handle| {
return iup.Element.fromHandle(handle);
} else {
return null;
}
}
///
/// BACKIMAGE (non inheritable): image name to be used as background.
/// Use IupSetHandle or IupSetAttributeHandle to associate an image to a name.
/// See also IupImage.
pub fn setBackImage(self: *Self, arg: anytype) !void {
try interop.validateHandle(.Image, arg);
interop.setHandleAttribute(self, "BACKIMAGE", .{}, arg);
}
pub fn setBackImageHandleName(self: *Self, arg: [:0]const u8) void {
interop.setStrAttribute(self, "BACKIMAGE", .{}, arg);
}
///
/// IMAGEINACTIVE (non inheritable): Image name of the element when inactive.
/// If it is not defined then the IMAGE is used and its colors will be replaced
/// by a modified version creating the disabled effect.
pub fn getImageInactive(self: *Self) ?iup.Element {
if (interop.getHandleAttribute(self, "IMAGEINACTIVE", .{})) |handle| {
return iup.Element.fromHandle(handle);
} else {
return null;
}
}
///
/// IMAGEINACTIVE (non inheritable): Image name of the element when inactive.
/// If it is not defined then the IMAGE is used and its colors will be replaced
/// by a modified version creating the disabled effect.
pub fn setImageInactive(self: *Self, arg: anytype) !void {
try interop.validateHandle(.Image, arg);
interop.setHandleAttribute(self, "IMAGEINACTIVE", .{}, arg);
}
pub fn setImageInactiveHandleName(self: *Self, arg: [:0]const u8) void {
interop.setStrAttribute(self, "IMAGEINACTIVE", .{}, arg);
}
///
/// SHOWDROPDOWN (write-only): opens or closes the dropdown child.
/// Can be "YES" or "NO".
/// Ignored if set before map.
pub fn showDropDown(self: *Self, arg: bool) void {
interop.setBoolAttribute(self, "SHOWDROPDOWN", .{}, arg);
}
pub fn getExpandWeight(self: *Self) f64 {
return interop.getDoubleAttribute(self, "EXPANDWEIGHT", .{});
}
pub fn setExpandWeight(self: *Self, arg: f64) void {
interop.setDoubleAttribute(self, "EXPANDWEIGHT", .{}, arg);
}
pub fn getMinSize(self: *Self) Size {
var str = interop.getStrAttribute(self, "MINSIZE", .{});
return Size.parse(str);
}
pub fn setMinSize(self: *Self, width: ?i32, height: ?i32) void {
var buffer: [128]u8 = undefined;
var value = Size.intIntToString(&buffer, width, height);
interop.setStrAttribute(self, "MINSIZE", .{}, value);
}
///
/// SHOWBORDER: by default borders are drawn only when the button is
/// highlighted, if SHOWBORDER=Yes borders are always show.
/// When SHOWBORDER=Yes and BGCOLOR is not defined, the actual BGCOLOR will be
/// a darker version of the background color of the native parent.
pub fn getShowBorder(self: *Self) bool {
return interop.getBoolAttribute(self, "SHOWBORDER", .{});
}
///
/// SHOWBORDER: by default borders are drawn only when the button is
/// highlighted, if SHOWBORDER=Yes borders are always show.
/// When SHOWBORDER=Yes and BGCOLOR is not defined, the actual BGCOLOR will be
/// a darker version of the background color of the native parent.
pub fn setShowBorder(self: *Self, arg: bool) void {
interop.setBoolAttribute(self, "SHOWBORDER", .{}, arg);
}
///
/// ARROWIMAGES (non inheritable): replace the drawn arrows by the following images.
/// Make sure their sizes are equal or smaller than ARROWSIZE.
/// Default: No.
pub fn getArrowImages(self: *Self) i32 {
return interop.getIntAttribute(self, "ARROWIMAGES", .{});
}
///
/// ARROWIMAGES (non inheritable): replace the drawn arrows by the following images.
/// Make sure their sizes are equal or smaller than ARROWSIZE.
/// Default: No.
pub fn setArrowImages(self: *Self, arg: i32) void {
interop.setIntAttribute(self, "ARROWIMAGES", .{}, arg);
}
pub fn getNTheme(self: *Self) [:0]const u8 {
return interop.getStrAttribute(self, "NTHEME", .{});
}
pub fn setNTheme(self: *Self, arg: [:0]const u8) void {
interop.setStrAttribute(self, "NTHEME", .{}, arg);
}
pub fn getCharSize(self: *Self) Size {
var str = interop.getStrAttribute(self, "CHARSIZE", .{});
return Size.parse(str);
}
///
/// IMAGEPOSITION (non inheritable): Position of the image relative to the text
/// when both are displayed.
/// Can be: LEFT, RIGHT, TOP, BOTTOM.
/// Default: LEFT.
pub fn getImagePosition(self: *Self) ?ImagePosition {
var ret = interop.getStrAttribute(self, "IMAGEPOSITION", .{});
if (std.ascii.eqlIgnoreCase("LEFT", ret)) return .Left;
if (std.ascii.eqlIgnoreCase("RIGHT", ret)) return .Right;
if (std.ascii.eqlIgnoreCase("BOTTOM", ret)) return .Bottom;
if (std.ascii.eqlIgnoreCase("TOP", ret)) return .Top;
return null;
}
///
/// IMAGEPOSITION (non inheritable): Position of the image relative to the text
/// when both are displayed.
/// Can be: LEFT, RIGHT, TOP, BOTTOM.
/// Default: LEFT.
pub fn setImagePosition(self: *Self, arg: ?ImagePosition) void {
if (arg) |value| switch (value) {
.Left => interop.setStrAttribute(self, "IMAGEPOSITION", .{}, "LEFT"),
.Right => interop.setStrAttribute(self, "IMAGEPOSITION", .{}, "RIGHT"),
.Bottom => interop.setStrAttribute(self, "IMAGEPOSITION", .{}, "BOTTOM"),
.Top => interop.setStrAttribute(self, "IMAGEPOSITION", .{}, "TOP"),
} else {
interop.clearAttribute(self, "IMAGEPOSITION", .{});
}
}
pub fn getDragTypes(self: *Self) [:0]const u8 {
return interop.getStrAttribute(self, "DRAGTYPES", .{});
}
pub fn setDragTypes(self: *Self, arg: [:0]const u8) void {
interop.setStrAttribute(self, "DRAGTYPES", .{}, arg);
}
pub fn getWheelDropFocus(self: *Self) bool {
return interop.getBoolAttribute(self, "WHEELDROPFOCUS", .{});
}
pub fn setWheelDropFocus(self: *Self, arg: bool) void {
interop.setBoolAttribute(self, "WHEELDROPFOCUS", .{}, arg);
}
///
/// BORDERWIDTH: line width used for borders.
/// Default: "1".
/// Any borders can be hidden by simply setting this value to 0.
/// This is for the IupDropButton drawn border.
pub fn getBorderWidth(self: *Self) i32 {
return interop.getIntAttribute(self, "BORDERWIDTH", .{});
}
///
/// BORDERWIDTH: line width used for borders.
/// Default: "1".
/// Any borders can be hidden by simply setting this value to 0.
/// This is for the IupDropButton drawn border.
pub fn setBorderWidth(self: *Self, arg: i32) void {
interop.setIntAttribute(self, "BORDERWIDTH", .{}, arg);
}
pub fn getFontStyle(self: *Self) [:0]const u8 {
return interop.getStrAttribute(self, "FONTSTYLE", .{});
}
pub fn setFontStyle(self: *Self, arg: [:0]const u8) void {
interop.setStrAttribute(self, "FONTSTYLE", .{}, arg);
}
///
/// TEXTALIGNMENT (non inheritable): Horizontal text alignment for multiple lines.
/// Can be: ALEFT, ARIGHT or ACENTER.
/// Default: ALEFT.
pub fn getTextAlignment(self: *Self) ?TextAlignment {
var ret = interop.getStrAttribute(self, "TEXTALIGNMENT", .{});
if (std.ascii.eqlIgnoreCase("ARIGHT", ret)) return .ARight;
if (std.ascii.eqlIgnoreCase("ALEFT", ret)) return .ALeft;
if (std.ascii.eqlIgnoreCase("ACENTER", ret)) return .ACenter;
return null;
}
///
/// TEXTALIGNMENT (non inheritable): Horizontal text alignment for multiple lines.
/// Can be: ALEFT, ARIGHT or ACENTER.
/// Default: ALEFT.
pub fn setTextAlignment(self: *Self, arg: ?TextAlignment) void {
if (arg) |value| switch (value) {
.ARight => interop.setStrAttribute(self, "TEXTALIGNMENT", .{}, "ARIGHT"),
.ALeft => interop.setStrAttribute(self, "TEXTALIGNMENT", .{}, "ALEFT"),
.ACenter => interop.setStrAttribute(self, "TEXTALIGNMENT", .{}, "ACENTER"),
} else {
interop.clearAttribute(self, "TEXTALIGNMENT", .{});
}
}
pub fn getTouch(self: *Self) bool {
return interop.getBoolAttribute(self, "TOUCH", .{});
}
pub fn setTouch(self: *Self, arg: bool) void {
interop.setBoolAttribute(self, "TOUCH", .{}, arg);
}
///
/// TEXTWRAP (non inheritable): For single line texts if the text is larger
/// than its box the line will be automatically broken in multiple lines.
/// Notice that this is done internally by the system, the element natural size
/// will still use only a single line.
/// For the remaining lines to be visible the element should use
/// EXPAND=VERTICAL or set a SIZE/RASTERSIZE with enough height for the wrapped lines.
/// (since 3.25)
pub fn getTextWrap(self: *Self) bool {
return interop.getBoolAttribute(self, "TEXTWRAP", .{});
}
///
/// TEXTWRAP (non inheritable): For single line texts if the text is larger
/// than its box the line will be automatically broken in multiple lines.
/// Notice that this is done internally by the system, the element natural size
/// will still use only a single line.
/// For the remaining lines to be visible the element should use
/// EXPAND=VERTICAL or set a SIZE/RASTERSIZE with enough height for the wrapped lines.
/// (since 3.25)
pub fn setTextWrap(self: *Self, arg: bool) void {
interop.setBoolAttribute(self, "TEXTWRAP", .{}, arg);
}
///
/// BACKIMAGEPRESS (non inheritable): background image name of the element in
/// pressed state.
/// If it is not defined then the BACKIMAGE is used.
pub fn getBackImagePress(self: *Self) ?iup.Element {
if (interop.getHandleAttribute(self, "BACKIMAGEPRESS", .{})) |handle| {
return iup.Element.fromHandle(handle);
} else {
return null;
}
}
///
/// BACKIMAGEPRESS (non inheritable): background image name of the element in
/// pressed state.
/// If it is not defined then the BACKIMAGE is used.
pub fn setBackImagePress(self: *Self, arg: anytype) !void {
try interop.validateHandle(.Image, arg);
interop.setHandleAttribute(self, "BACKIMAGEPRESS", .{}, arg);
}
pub fn setBackImagePressHandleName(self: *Self, arg: [:0]const u8) void {
interop.setStrAttribute(self, "BACKIMAGEPRESS", .{}, arg);
}
pub fn getFont(self: *Self) [:0]const u8 {
return interop.getStrAttribute(self, "FONT", .{});
}
pub fn setFont(self: *Self, arg: [:0]const u8) void {
interop.setStrAttribute(self, "FONT", .{}, arg);
}
///
/// PRESSED (read-only): returns the button state if pressed.
/// Can be Yes or No.
pub fn getPressed(self: *Self) bool {
return interop.getBoolAttribute(self, "PRESSED", .{});
}
pub fn getMdiClient(self: *Self) bool {
return interop.getBoolAttribute(self, "MDICLIENT", .{});
}
pub fn setMdiClient(self: *Self, arg: bool) void {
interop.setBoolAttribute(self, "MDICLIENT", .{}, arg);
}
pub fn getMdiMenu(self: *Self) ?*iup.Menu {
if (interop.getHandleAttribute(self, "MDIMENU", .{})) |handle| {
return @ptrCast(*iup.Menu, handle);
} else {
return null;
}
}
pub fn setMdiMenu(self: *Self, arg: *iup.Menu) void {
interop.setHandleAttribute(self, "MDIMENU", .{}, arg);
}
pub fn setMdiMenuHandleName(self: *Self, arg: [:0]const u8) void {
interop.setStrAttribute(self, "MDIMENU", .{}, arg);
}
///
/// TABIMAGEn (non inheritable): image name to be used in the respective tab.
/// Use IupSetHandle or IupSetAttributeHandle to associate an image to a name.
/// n starts at 0.
/// See also IupImage.
/// In Motif, the image is shown only if TABTITLEn is NULL.
/// In Windows and Motif set the BGCOLOR attribute before setting the image.
/// When set after map will update the TABIMAGE attribute on the respective
/// child (since 3.10).
/// (since 3.0).
/// TABIMAGE (non inheritable) (at children only): Same as TABIMAGEn but set in
/// each child.
/// Works only if set before the child is added to the tabs.
pub fn getTabImage(self: *Self, index: i32) ?iup.Element {
if (interop.getHandleAttribute(self, "TABIMAGE", .{index})) |handle| {
return iup.Element.fromHandle(handle);
} else {
return null;
}
}
///
/// TABIMAGEn (non inheritable): image name to be used in the respective tab.
/// Use IupSetHandle or IupSetAttributeHandle to associate an image to a name.
/// n starts at 0.
/// See also IupImage.
/// In Motif, the image is shown only if TABTITLEn is NULL.
/// In Windows and Motif set the BGCOLOR attribute before setting the image.
/// When set after map will update the TABIMAGE attribute on the respective
/// child (since 3.10).
/// (since 3.0).
/// TABIMAGE (non inheritable) (at children only): Same as TABIMAGEn but set in
/// each child.
/// Works only if set before the child is added to the tabs.
pub fn setTabImage(self: *Self, index: i32, arg: anytype) !void {
try interop.validateHandle(.Image, arg);
interop.setHandleAttribute(self, "TABIMAGE", .{index}, arg);
}
pub fn setTabImageHandleName(self: *Self, index: i32, arg: [:0]const u8) void {
interop.setStrAttribute(self, "TABIMAGE", .{index}, arg);
}
///
/// TABTITLEn (non inheritable): Contains the text to be shown in the
/// respective tab title.
/// n starts at 0.
/// If this value is NULL, it will remain empty.
/// The "&" character can be used to define a mnemonic, the next character will
/// be used as key.
/// Use "&&" to show the "&" character instead on defining a mnemonic.
/// The button can be activated from any control in the dialog using the
/// "Alt+key" combination.
/// (mnemonic support since 3.3).
/// When set after map will update the TABTITLE attribute on the respective
/// child (since 3.10).
/// (since 3.0).
/// TABTITLE (non inheritable) (at children only): Same as TABTITLEn but set in
/// each child.
/// Works only if set before the child is added to the tabs.
pub fn getTabTitle(self: *Self, index: i32) [:0]const u8 {
return interop.getStrAttribute(self, "TABTITLE", .{index});
}
///
/// TABTITLEn (non inheritable): Contains the text to be shown in the
/// respective tab title.
/// n starts at 0.
/// If this value is NULL, it will remain empty.
/// The "&" character can be used to define a mnemonic, the next character will
/// be used as key.
/// Use "&&" to show the "&" character instead on defining a mnemonic.
/// The button can be activated from any control in the dialog using the
/// "Alt+key" combination.
/// (mnemonic support since 3.3).
/// When set after map will update the TABTITLE attribute on the respective
/// child (since 3.10).
/// (since 3.0).
/// TABTITLE (non inheritable) (at children only): Same as TABTITLEn but set in
/// each child.
/// Works only if set before the child is added to the tabs.
pub fn setTabTitle(self: *Self, index: i32, arg: [:0]const u8) void {
interop.setStrAttribute(self, "TABTITLE", .{index}, arg);
}
///
/// SCROLL_CB SCROLL_CB Called when some manipulation is made to the scrollbar.
/// The canvas is automatically redrawn only if this callback is NOT defined.
/// (GTK 2.8) Also the POSX and POSY values will not be correctly updated for
/// older GTK versions.
/// In Ubuntu, when liboverlay-scrollbar is enabled (the new tiny auto-hide
/// scrollbar) only the IUP_SBPOSV and IUP_SBPOSH codes are used.
/// Callback int function(Ihandle *ih, int op, float posx, float posy); [in C]
/// ih:scroll_cb(op, posx, posy: number) -> (ret: number) [in Lua] ih:
/// identifier of the element that activated the event.
/// op: indicates the operation performed on the scrollbar.
/// If the manipulation was made on the vertical scrollbar, it can have the
/// following values: IUP_SBUP - line up IUP_SBDN - line down IUP_SBPGUP - page
/// up IUP_SBPGDN - page down IUP_SBPOSV - vertical positioning IUP_SBDRAGV -
/// vertical drag If it was on the horizontal scrollbar, the following values
/// are valid: IUP_SBLEFT - column left IUP_SBRIGHT - column right IUP_SBPGLEFT
/// - page left IUP_SBPGRIGHT - page right IUP_SBPOSH - horizontal positioning
/// IUP_SBDRAGH - horizontal drag posx, posy: the same as the ACTION canvas
/// callback (corresponding to the values of attributes POSX and POSY).
/// Notes IUP_SBDRAGH and IUP_SBDRAGV are not supported in GTK.
/// During drag IUP_SBPOSH and IUP_SBPOSV are used.
/// In Windows, after a drag when mouse is released IUP_SBPOSH or IUP_SBPOSV
/// are called.
/// Affects IupCanvas, IupGLCanvas, SCROLLBAR
pub fn setScrollCallback(self: *Self, callback: ?OnScrollFn) void {
const Handler = CallbackHandler(Self, OnScrollFn, "SCROLL_CB");
Handler.setCallback(self, callback);
}
///
/// The drop dialog is configured with no decorations and it is not resizable,
/// only the FOCUS_CB and K_ESC callbacks are set.
/// But this can be changed by the application.
/// It is a regular IupDialog.
/// To obtain the drop button handle from the handle of the dialog get the
/// "DROPBUTTON" attribute handle from the dialog, using IupGetAttributeHandle.
/// After performing some operation on the drop child, use SHOWDROPDOWN=NO on
/// the drop button, you may also update its TITLE, just like a regular IupList
/// with DROPDOWN=Yes, but this will not be performed automatically by the drop button.
/// For example, set the ACTION callback on the IupList used as drop child:
/// static int list_cb(Ihandle* list, char *text, int item, int state) { if
/// (state == 1) { Ihandle* ih = IupGetAttributeHandle(IupGetDialog(list),
/// "DROPBUTTON"); IupSetAttribute(ih, "SHOWDROPDOWN", "No");
/// IupSetStrAttribute(ih, "TITLE", text); } return IUP_DEFAULT; }
pub fn setFocusCallback(self: *Self, callback: ?OnFocusFn) void {
const Handler = CallbackHandler(Self, OnFocusFn, "FOCUS_CB");
Handler.setCallback(self, callback);
}
///
/// WOM_CB WOM_CB Action generated when an audio device receives an event.
/// [Windows Only] Callback int function(Ihandle *ih, int state); [in C]
/// ih:wom_cb(state: number) -> (ret: number) [in Lua] ih: identifies the
/// element that activated the event.
/// state: can be opening=1, done=0, or closing=-1.
/// Notes This callback is used to syncronize video playback with audio.
/// It is sent when the audio device: Message Description opening is opened by
/// using the waveOutOpen function.
/// done is finished with a data block sent by using the waveOutWrite function.
/// closing is closed by using the waveOutClose function.
/// You must use the HWND attribute when calling waveOutOpen in the dwCallback
/// parameter and set fdwOpen to CALLBACK_WINDOW.
/// Affects IupDialog, IupCanvas, IupGLCanvas
pub fn setWomCallback(self: *Self, callback: ?OnWomFn) void {
const Handler = CallbackHandler(Self, OnWomFn, "WOM_CB");
Handler.setCallback(self, callback);
}
///
/// K_ANY K_ANY Action generated when a keyboard event occurs.
/// Callback int function(Ihandle *ih, int c); [in C] ih:k_any(c: number) ->
/// (ret: number) [in Lua] ih: identifier of the element that activated the event.
/// c: identifier of typed key.
/// Please refer to the Keyboard Codes table for a list of possible values.
/// Returns: If IUP_IGNORE is returned the key is ignored and not processed by
/// the control and not propagated.
/// If returns IUP_CONTINUE, the key will be processed and the event will be
/// propagated to the parent of the element receiving it, this is the default behavior.
/// If returns IUP_DEFAULT the key is processed but it is not propagated.
/// IUP_CLOSE will be processed.
/// Notes Keyboard callbacks depend on the keyboard usage of the control with
/// the focus.
/// So if you return IUP_IGNORE the control will usually not process the key.
/// But be aware that sometimes the control process the key in another event so
/// even returning IUP_IGNORE the key can get processed.
/// Although it will not be propagated.
/// IMPORTANT: The callbacks "K_*" of the dialog or native containers depend on
/// the IUP_CONTINUE return value to work while the control is in focus.
/// If the callback does not exists it is automatically propagated to the
/// parent of the element.
/// K_* callbacks All defined keys are also callbacks of any element, called
/// when the respective key is activated.
/// For example: "K_cC" is also a callback activated when the user press
/// Ctrl+C, when the focus is at the element or at a children with focus.
/// This is the way an application can create shortcut keys, also called hot keys.
/// These callbacks are not available in IupLua.
/// Affects All elements with keyboard interaction.
pub fn setKAnyCallback(self: *Self, callback: ?OnKAnyFn) void {
const Handler = CallbackHandler(Self, OnKAnyFn, "K_ANY");
Handler.setCallback(self, callback);
}
pub fn setFlatFocusCallback(self: *Self, callback: ?OnFlatFocusFn) void {
const Handler = CallbackHandler(Self, OnFlatFocusFn, "FLAT_FOCUS_CB");
Handler.setCallback(self, callback);
}
///
/// HELP_CB HELP_CB Action generated when the user press F1 at a control.
/// In Motif is also activated by the Help button in some workstations keyboard.
/// Callback void function(Ihandle *ih); [in C] ih:help_cb() -> (ret: number)
/// [in Lua] ih: identifier of the element that activated the event.
/// Returns: IUP_CLOSE will be processed.
/// Affects All elements with user interaction.
pub fn setHelpCallback(self: *Self, callback: ?OnHelpFn) void {
const Handler = CallbackHandler(Self, OnHelpFn, "HELP_CB");
Handler.setCallback(self, callback);
}
pub fn setDropMotionCallback(self: *Self, callback: ?OnDropMotionFn) void {
const Handler = CallbackHandler(Self, OnDropMotionFn, "DROPMOTION_CB");
Handler.setCallback(self, callback);
}
pub fn setFlatLeaveWindowCallback(self: *Self, callback: ?OnFlatLeaveWindowFn) void {
const Handler = CallbackHandler(Self, OnFlatLeaveWindowFn, "FLAT_LEAVEWINDOW_CB");
Handler.setCallback(self, callback);
}
///
/// KEYPRESS_CB KEYPRESS_CB Action generated when a key is pressed or released.
/// If the key is pressed and held several calls will occur.
/// It is called after the callback K_ANY is processed.
/// Callback int function(Ihandle *ih, int c, int press); [in C]
/// ih:keypress_cb(c, press: number) -> (ret: number) [in Lua] ih: identifier
/// of the element that activated the event.
/// c: identifier of typed key.
/// Please refer to the Keyboard Codes table for a list of possible values.
/// press: 1 is the user pressed the key or 0 otherwise.
/// Returns: If IUP_IGNORE is returned the key is ignored by the system.
/// IUP_CLOSE will be processed.
/// Affects IupCanvas
pub fn setKeyPressCallback(self: *Self, callback: ?OnKeyPressFn) void {
const Handler = CallbackHandler(Self, OnKeyPressFn, "KEYPRESS_CB");
Handler.setCallback(self, callback);
}
pub fn setDragEndCallback(self: *Self, callback: ?OnDragEndFn) void {
const Handler = CallbackHandler(Self, OnDragEndFn, "DRAGEND_CB");
Handler.setCallback(self, callback);
}
pub fn setDragBeginCallback(self: *Self, callback: ?OnDragBeginFn) void {
const Handler = CallbackHandler(Self, OnDragBeginFn, "DRAGBEGIN_CB");
Handler.setCallback(self, callback);
}
///
/// ACTION ACTION Action generated when the element is activated.
/// Affects each element differently.
/// Callback int function(Ihandle *ih); [in C] ih:action() -> (ret: number) [in
/// Lua] ih: identifier of the element that activated the event.
/// In some elements, this callback may receive more parameters, apart from ih.
/// Please refer to each element's documentation.
/// Affects IupButton, IupItem, IupList, IupText, IupCanvas, IupMultiline,
/// IupToggle
pub fn setActionCallback(self: *Self, callback: ?OnActionFn) void {
const Handler = CallbackHandler(Self, OnActionFn, "ACTION");
Handler.setCallback(self, callback);
}
///
/// MOTION_CB MOTION_CB Action generated when the mouse moves.
/// Callback int function(Ihandle *ih, int x, int y, char *status); [in C]
/// ih:motion_cb(x, y: number, status: string) -> (ret: number) [in Lua] ih:
/// identifier of the element that activated the event.
/// x, y: position in the canvas where the event has occurred, in pixels.
/// status: status of mouse buttons and certain keyboard keys at the moment the
/// event was generated.
/// The same macros used for BUTTON_CB can be used for this status.
/// Notes Between press and release all mouse events are redirected only to
/// this control, even if the cursor moves outside the element.
/// So the BUTTON_CB callback when released and the MOTION_CB callback can be
/// called with coordinates outside the element rectangle.
/// Affects IupCanvas, IupGLCanvas
pub fn setMotionCallback(self: *Self, callback: ?OnMotionFn) void {
const Handler = CallbackHandler(Self, OnMotionFn, "MOTION_CB");
Handler.setCallback(self, callback);
}
pub fn setFlatEnterWindowCallback(self: *Self, callback: ?OnFlatEnterWindowFn) void {
const Handler = CallbackHandler(Self, OnFlatEnterWindowFn, "FLAT_ENTERWINDOW_CB");
Handler.setCallback(self, callback);
}
///
/// WHEEL_CB WHEEL_CB Action generated when the mouse wheel is rotated.
/// If this callback is not defined the wheel will automatically scroll the
/// canvas in the vertical direction by some lines, the SCROLL_CB callback if
/// defined will be called with the IUP_SBDRAGV operation.
/// Callback int function(Ihandle *ih, float delta, int x, int y, char
/// *status); [in C] ih:wheel_cb(delta, x, y: number, status: string) -> (ret:
/// number) [in Lua] ih: identifier of the element that activated the event.
/// delta: the amount the wheel was rotated in notches.
/// x, y: position in the canvas where the event has occurred, in pixels.
/// status: status of mouse buttons and certain keyboard keys at the moment the
/// event was generated.
/// The same macros used for BUTTON_CB can be used for this status.
/// Notes In Motif and GTK delta is always 1 or -1.
/// In Windows is some situations delta can reach the value of two.
/// In the future with more precise wheels this increment can be changed.
/// Affects IupCanvas, IupGLCanvas
pub fn setWheelCallback(self: *Self, callback: ?OnWheelFn) void {
const Handler = CallbackHandler(Self, OnWheelFn, "WHEEL_CB");
Handler.setCallback(self, callback);
}
///
/// MAP_CB MAP_CB Called right after an element is mapped and its attributes
/// updated in IupMap.
/// When the element is a dialog, it is called after the layout is updated.
/// For all other elements is called before the layout is updated, so the
/// element current size will still be 0x0 during MAP_CB (since 3.14).
/// Callback int function(Ihandle *ih); [in C] ih:map_cb() -> (ret: number) [in
/// Lua] ih: identifier of the element that activated the event.
/// Affects All that have a native representation.
pub fn setMapCallback(self: *Self, callback: ?OnMapFn) void {
const Handler = CallbackHandler(Self, OnMapFn, "MAP_CB");
Handler.setCallback(self, callback);
}
pub fn setFlatButtonCallback(self: *Self, callback: ?OnFlatButtonFn) void {
const Handler = CallbackHandler(Self, OnFlatButtonFn, "FLAT_BUTTON_CB");
Handler.setCallback(self, callback);
}
///
/// ENTERWINDOW_CB ENTERWINDOW_CB Action generated when the mouse enters the
/// native element.
/// Callback int function(Ihandle *ih); [in C] ih:enterwindow_cb() -> (ret:
/// number) [in Lua] ih: identifier of the element that activated the event.
/// Notes When the cursor is moved from one element to another, the call order
/// in all platforms will be first the LEAVEWINDOW_CB callback of the old
/// control followed by the ENTERWINDOW_CB callback of the new control.
/// (since 3.14) If the mouse button is hold pressed and the cursor moves
/// outside the element the behavior is system dependent.
/// In Windows the LEAVEWINDOW_CB/ENTERWINDOW_CB callbacks are NOT called, in
/// GTK the callbacks are called.
/// Affects All controls with user interaction.
/// See Also LEAVEWINDOW_CB
pub fn setEnterWindowCallback(self: *Self, callback: ?OnEnterWindowFn) void {
const Handler = CallbackHandler(Self, OnEnterWindowFn, "ENTERWINDOW_CB");
Handler.setCallback(self, callback);
}
///
/// DESTROY_CB DESTROY_CB Called right before an element is destroyed.
/// Callback int function(Ihandle *ih); [in C] ih:destroy_cb() -> (ret: number)
/// [in Lua] ih: identifier of the element that activated the event.
/// Notes If the dialog is visible then it is hidden before it is destroyed.
/// The callback will be called right after it is hidden.
/// The callback will be called before all other destroy procedures.
/// For instance, if the element has children then it is called before the
/// children are destroyed.
/// For language binding implementations use the callback name "LDESTROY_CB" to
/// release memory allocated by the binding for the element.
/// Also the callback will be called before the language callback.
/// Affects All.
pub fn setDestroyCallback(self: *Self, callback: ?OnDestroyFn) void {
const Handler = CallbackHandler(Self, OnDestroyFn, "DESTROY_CB");
Handler.setCallback(self, callback);
}
pub fn setDropDataCallback(self: *Self, callback: ?OnDropDataFn) void {
const Handler = CallbackHandler(Self, OnDropDataFn, "DROPDATA_CB");
Handler.setCallback(self, callback);
}
///
/// KILLFOCUS_CB KILLFOCUS_CB Action generated when an element loses keyboard focus.
/// This callback is called before the GETFOCUS_CB of the element that gets the focus.
/// Callback int function(Ihandle *ih); [in C] ih:killfocus_cb() -> (ret:
/// number) [in Lua] ih: identifier of the element that activated the event.
/// Affects All elements with user interaction, except menus.
/// In Windows, there are restrictions when using this callback.
/// From MSDN on WM_KILLFOCUS: "While processing this message, do not make any
/// function calls that display or activate a window.
/// This causes the thread to yield control and can cause the application to
/// stop responding to messages.
/// See Also GETFOCUS_CB, IupGetFocus, IupSetFocus
pub fn setKillFocusCallback(self: *Self, callback: ?OnKillFocusFn) void {
const Handler = CallbackHandler(Self, OnKillFocusFn, "KILLFOCUS_CB");
Handler.setCallback(self, callback);
}
///
/// DROPSHOW_CB: Action generated right after the drop child is shown or hidden.
/// This callback is also called when SHOWDROPDOWN is set.
/// int function (Ihandle *ih, int state); [in C]ih:dropdown_cb(state: boolean)
/// -> (ret: number) [in Lua]
pub fn setDropShowCallback(self: *Self, callback: ?OnDropShowFn) void {
const Handler = CallbackHandler(Self, OnDropShowFn, "DROPSHOW_CB");
Handler.setCallback(self, callback);
}
pub fn setDragDataCallback(self: *Self, callback: ?OnDragDataFn) void {
const Handler = CallbackHandler(Self, OnDragDataFn, "DRAGDATA_CB");
Handler.setCallback(self, callback);
}
pub fn setDragDataSizeCallback(self: *Self, callback: ?OnDragDataSizeFn) void {
const Handler = CallbackHandler(Self, OnDragDataSizeFn, "DRAGDATASIZE_CB");
Handler.setCallback(self, callback);
}
///
/// DROPFILES_CB DROPFILES_CB Action called when a file is "dropped" into the control.
/// When several files are dropped at once, the callback is called several
/// times, once for each file.
/// If defined after the element is mapped then the attribute DROPFILESTARGET
/// must be set to YES.
/// [Windows and GTK Only] (GTK 2.6) Callback int function(Ihandle *ih, const
/// char* filename, int num, int x, int y); [in C] ih:dropfiles_cb(filename:
/// string; num, x, y: number) -> (ret: number) [in Lua] ih: identifier of the
/// element that activated the event.
/// filename: Name of the dropped file.
/// num: Number index of the dropped file.
/// If several files are dropped, num is the index of the dropped file starting
/// from "total-1" to "0".
/// x: X coordinate of the point where the user released the mouse button.
/// y: Y coordinate of the point where the user released the mouse button.
/// Returns: If IUP_IGNORE is returned the callback will NOT be called for the
/// next dropped files, and the processing of dropped files will be interrupted.
/// Affects IupDialog, IupCanvas, IupGLCanvas, IupText, IupList
pub fn setDropFilesCallback(self: *Self, callback: ?OnDropFilesFn) void {
const Handler = CallbackHandler(Self, OnDropFilesFn, "DROPFILES_CB");
Handler.setCallback(self, callback);
}
///
/// RESIZE_CB RESIZE_CB Action generated when the canvas or dialog size is changed.
/// Callback int function(Ihandle *ih, int width, int height); [in C]
/// ih:resize_cb(width, height: number) -> (ret: number) [in Lua] ih:
/// identifier of the element that activated the event.
/// width: the width of the internal element size in pixels not considering the
/// decorations (client size) height: the height of the internal element size
/// in pixels not considering the decorations (client size) Notes For the
/// dialog, this action is also generated when the dialog is mapped, after the
/// map and before the show.
/// When XAUTOHIDE=Yes or YAUTOHIDE=Yes, if the canvas scrollbar is
/// hidden/shown after changing the DX or DY attributes from inside the
/// callback, the size of the drawing area will immediately change, so the
/// parameters with and height will be invalid.
/// To update the parameters consult the DRAWSIZE attribute.
/// Also activate the drawing toolkit only after updating the DX or DY attributes.
/// Affects IupCanvas, IupGLCanvas, IupDialog
pub fn setResizeCallback(self: *Self, callback: ?OnResizeFn) void {
const Handler = CallbackHandler(Self, OnResizeFn, "RESIZE_CB");
Handler.setCallback(self, callback);
}
///
/// UNMAP_CB UNMAP_CB Called right before an element is unmapped.
/// Callback int function(Ihandle *ih); [in C] ih:unmap_cb() -> (ret: number)
/// [in Lua] ih: identifier of the element that activated the event.
/// Affects All that have a native representation.
pub fn setUnmapCallback(self: *Self, callback: ?OnUnmapFn) void {
const Handler = CallbackHandler(Self, OnUnmapFn, "UNMAP_CB");
Handler.setCallback(self, callback);
}
///
/// FLAT_ACTION: Action generated when the button 1 (usually left) is selected.
/// This callback is called only after the mouse is released and when it is
/// released inside the button area.
/// Called only when DROPONARROW=Yes.
/// int function(Ihandle* ih); [in C]ih:action() -> (ret: number) [in Lua]
pub fn setFlatActionCallback(self: *Self, callback: ?OnFlatActionFn) void {
const Handler = CallbackHandler(Self, OnFlatActionFn, "FLAT_ACTION");
Handler.setCallback(self, callback);
}
///
/// GETFOCUS_CB GETFOCUS_CB Action generated when an element is given keyboard focus.
/// This callback is called after the KILLFOCUS_CB of the element that loosed
/// the focus.
/// The IupGetFocus function during the callback returns the element that
/// loosed the focus.
/// Callback int function(Ihandle *ih); [in C] ih:getfocus_cb() -> (ret:
/// number) [in Lua] ih: identifier of the element that received keyboard focus.
/// Affects All elements with user interaction, except menus.
/// See Also KILLFOCUS_CB, IupGetFocus, IupSetFocus
pub fn setGetFocusCallback(self: *Self, callback: ?OnGetFocusFn) void {
const Handler = CallbackHandler(Self, OnGetFocusFn, "GETFOCUS_CB");
Handler.setCallback(self, callback);
}
///
/// BUTTON_CB BUTTON_CB Action generated when a mouse button is pressed or released.
/// Callback int function(Ihandle* ih, int button, int pressed, int x, int y,
/// char* status); [in C] ih:button_cb(button, pressed, x, y: number, status:
/// string) -> (ret: number) [in Lua] ih: identifies the element that activated
/// the event.
/// button: identifies the activated mouse button: IUP_BUTTON1 - left mouse
/// button (button 1); IUP_BUTTON2 - middle mouse button (button 2);
/// IUP_BUTTON3 - right mouse button (button 3).
/// pressed: indicates the state of the button: 0 - mouse button was released;
/// 1 - mouse button was pressed.
/// x, y: position in the canvas where the event has occurred, in pixels.
/// status: status of the mouse buttons and some keyboard keys at the moment
/// the event is generated.
/// The following macros must be used for verification: iup_isshift(status)
/// iup_iscontrol(status) iup_isbutton1(status) iup_isbutton2(status)
/// iup_isbutton3(status) iup_isbutton4(status) iup_isbutton5(status)
/// iup_isdouble(status) iup_isalt(status) iup_issys(status) They return 1 if
/// the respective key or button is pressed, and 0 otherwise.
/// These macros are also available in Lua, returning a boolean.
/// Returns: IUP_CLOSE will be processed.
/// On some controls if IUP_IGNORE is returned the action is ignored (this is
/// system dependent).
/// Notes This callback can be used to customize a button behavior.
/// For a standard button behavior use the ACTION callback of the IupButton.
/// For a single click the callback is called twice, one for pressed=1 and one
/// for pressed=0.
/// Only after both calls the ACTION callback is called.
/// In Windows, if a dialog is shown or popup in any situation there could be
/// unpredictable results because the native system still has processing to be
/// done even after the callback is called.
/// A double click is preceded by two single clicks, one for pressed=1 and one
/// for pressed=0, and followed by a press=0, all three without the double
/// click flag set.
/// In GTK, it is preceded by an additional two single clicks sequence.
/// For example, for one double click all the following calls are made:
/// BUTTON_CB(but=1 (1), x=154, y=83 [ 1 ]) BUTTON_CB(but=1 (0), x=154, y=83 [
/// 1 ]) BUTTON_CB(but=1 (1), x=154, y=83 [ 1 ]) (in GTK only) BUTTON_CB(but=1
/// (0), x=154, y=83 [ 1 ]) (in GTK only) BUTTON_CB(but=1 (1), x=154, y=83 [ 1
/// D ]) BUTTON_CB(but=1 (0), x=154, y=83 [ 1 ]) Between press and release all
/// mouse events are redirected only to this control, even if the cursor moves
/// outside the element.
/// So the BUTTON_CB callback when released and the MOTION_CB callback can be
/// called with coordinates outside the element rectangle.
/// Affects IupCanvas, IupButton, IupText, IupList, IupGLCanvas
pub fn setButtonCallback(self: *Self, callback: ?OnButtonFn) void {
const Handler = CallbackHandler(Self, OnButtonFn, "BUTTON_CB");
Handler.setCallback(self, callback);
}
pub fn setFlatMotionCallback(self: *Self, callback: ?OnFlatMotionFn) void {
const Handler = CallbackHandler(Self, OnFlatMotionFn, "FLAT_MOTION_CB");
Handler.setCallback(self, callback);
}
///
/// DROPDOWN_CB: Action generated right before the drop child is shown or hidden.
/// This callback is also called when SHOWDROPDOWN is set.
/// int function (Ihandle *ih, int state); [in C]ih:dropdown_cb(state: boolean)
/// -> (ret: number) [in Lua]
pub fn setDropDownCallback(self: *Self, callback: ?OnDropDownFn) void {
const Handler = CallbackHandler(Self, OnDropDownFn, "DROPDOWN_CB");
Handler.setCallback(self, callback);
}
pub fn setLDestroyCallback(self: *Self, callback: ?OnLDestroyFn) void {
const Handler = CallbackHandler(Self, OnLDestroyFn, "LDESTROY_CB");
Handler.setCallback(self, callback);
}
///
/// LEAVEWINDOW_CB LEAVEWINDOW_CB Action generated when the mouse leaves the
/// native element.
/// Callback int function(Ihandle *ih); [in C] ih:leavewindow_cb() -> (ret:
/// number) [in Lua] ih: identifier of the element that activated the event.
/// Notes When the cursor is moved from one element to another, the call order
/// in all platforms will be first the LEAVEWINDOW_CB callback of the old
/// control followed by the ENTERWINDOW_CB callback of the new control.
/// (since 3.14) If the mouse button is hold pressed and the cursor moves
/// outside the element the behavior is system dependent.
/// In Windows the LEAVEWINDOW_CB/ENTERWINDOW_CB callbacks are NOT called, in
/// GTK the callbacks are called.
/// Affects All controls with user interaction.
/// See Also ENTERWINDOW_CB
pub fn setLeaveWindowCallback(self: *Self, callback: ?OnLeaveWindowFn) void {
const Handler = CallbackHandler(Self, OnLeaveWindowFn, "LEAVEWINDOW_CB");
Handler.setCallback(self, callback);
}
pub fn setPostMessageCallback(self: *Self, callback: ?OnPostMessageFn) void {
const Handler = CallbackHandler(Self, OnPostMessageFn, "POSTMESSAGE_CB");
Handler.setCallback(self, callback);
}
};
test "DropButton FgColor" {
try iup.MainLoop.open();
defer iup.MainLoop.close();
var item = try (iup.DropButton.init().setFgColor(.{ .r = 9, .g = 10, .b = 11 }).unwrap());
defer item.deinit();
var ret = item.getFgColor();
try std.testing.expect(ret != null and ret.?.r == 9 and ret.?.g == 10 and ret.?.b == 11);
}
test "DropButton HandleName" {
try iup.MainLoop.open();
defer iup.MainLoop.close();
var item = try (iup.DropButton.init().setHandleName("Hello").unwrap());
defer item.deinit();
var ret = item.getHandleName();
try std.testing.expect(std.mem.eql(u8, ret, "Hello"));
}
test "DropButton TipBgColor" {
try iup.MainLoop.open();
defer iup.MainLoop.close();
var item = try (iup.DropButton.init().setTipBgColor(.{ .r = 9, .g = 10, .b = 11 }).unwrap());
defer item.deinit();
var ret = item.getTipBgColor();
try std.testing.expect(ret != null and ret.?.r == 9 and ret.?.g == 10 and ret.?.b == 11);
}
test "DropButton XMin" {
try iup.MainLoop.open();
defer iup.MainLoop.close();
var item = try (iup.DropButton.init().setXMin(42).unwrap());
defer item.deinit();
var ret = item.getXMin();
try std.testing.expect(ret == 42);
}
test "DropButton TipIcon" {
try iup.MainLoop.open();
defer iup.MainLoop.close();
var item = try (iup.DropButton.init().setTipIcon("Hello").unwrap());
defer item.deinit();
var ret = item.getTipIcon();
try std.testing.expect(std.mem.eql(u8, ret, "Hello"));
}
test "DropButton MaxSize" {
try iup.MainLoop.open();
defer iup.MainLoop.close();
var item = try (iup.DropButton.init().setMaxSize(9, 10).unwrap());
defer item.deinit();
var ret = item.getMaxSize();
try std.testing.expect(ret.width != null and ret.width.? == 9 and ret.height != null and ret.height.? == 10);
}
test "DropButton DrawTextWrap" {
try iup.MainLoop.open();
defer iup.MainLoop.close();
var item = try (iup.DropButton.init().setDrawTextWrap(true).unwrap());
defer item.deinit();
var ret = item.getDrawTextWrap();
try std.testing.expect(ret == true);
}
test "DropButton FocusFeedback" {
try iup.MainLoop.open();
defer iup.MainLoop.close();
var item = try (iup.DropButton.init().setFocusFeedback(true).unwrap());
defer item.deinit();
var ret = item.getFocusFeedback();
try std.testing.expect(ret == true);
}
test "DropButton Position" {
try iup.MainLoop.open();
defer iup.MainLoop.close();
var item = try (iup.DropButton.init().setPosition(9, 10).unwrap());
defer item.deinit();
var ret = item.getPosition();
try std.testing.expect(ret.x == 9 and ret.y == 10);
}
test "DropButton DropFilesTarget" {
try iup.MainLoop.open();
defer iup.MainLoop.close();
var item = try (iup.DropButton.init().setDropFilesTarget(true).unwrap());
defer item.deinit();
var ret = item.getDropFilesTarget();
try std.testing.expect(ret == true);
}
test "DropButton DrawTextAlignment" {
try iup.MainLoop.open();
defer iup.MainLoop.close();
var item = try (iup.DropButton.init().setDrawTextAlignment(.ACenter).unwrap());
defer item.deinit();
var ret = item.getDrawTextAlignment();
try std.testing.expect(ret != null and ret.? == .ACenter);
}
test "DropButton Tip" {
try iup.MainLoop.open();
defer iup.MainLoop.close();
var item = try (iup.DropButton.init().setTip("Hello").unwrap());
defer item.deinit();
var ret = item.getTip();
try std.testing.expect(std.mem.eql(u8, ret, "Hello"));
}
test "DropButton DrawTextLayoutCenter" {
try iup.MainLoop.open();
defer iup.MainLoop.close();
var item = try (iup.DropButton.init().setDrawTextLayoutCenter(true).unwrap());
defer item.deinit();
var ret = item.getDrawTextLayoutCenter();
try std.testing.expect(ret == true);
}
test "DropButton DragSourceMove" {
try iup.MainLoop.open();
defer iup.MainLoop.close();
var item = try (iup.DropButton.init().setDragSourceMove(true).unwrap());
defer item.deinit();
var ret = item.getDragSourceMove();
try std.testing.expect(ret == true);
}
test "DropButton PsColor" {
try iup.MainLoop.open();
defer iup.MainLoop.close();
var item = try (iup.DropButton.init().setPsColor(.{ .r = 9, .g = 10, .b = 11 }).unwrap());
defer item.deinit();
var ret = item.getPsColor();
try std.testing.expect(ret != null and ret.?.r == 9 and ret.?.g == 10 and ret.?.b == 11);
}
test "DropButton Visible" {
try iup.MainLoop.open();
defer iup.MainLoop.close();
var item = try (iup.DropButton.init().setVisible(true).unwrap());
defer item.deinit();
var ret = item.getVisible();
try std.testing.expect(ret == true);
}
test "DropButton LineX" {
try iup.MainLoop.open();
defer iup.MainLoop.close();
var item = try (iup.DropButton.init().setLineX(3.14).unwrap());
defer item.deinit();
var ret = item.getLineX();
try std.testing.expect(ret == @as(f64, 3.14));
}
test "DropButton LineY" {
try iup.MainLoop.open();
defer iup.MainLoop.close();
var item = try (iup.DropButton.init().setLineY(3.14).unwrap());
defer item.deinit();
var ret = item.getLineY();
try std.testing.expect(ret == @as(f64, 3.14));
}
test "DropButton DrawLineWidth" {
try iup.MainLoop.open();
defer iup.MainLoop.close();
var item = try (iup.DropButton.init().setDrawLineWidth(42).unwrap());
defer item.deinit();
var ret = item.getDrawLineWidth();
try std.testing.expect(ret == 42);
}
test "DropButton DragDrop" {
try iup.MainLoop.open();
defer iup.MainLoop.close();
var item = try (iup.DropButton.init().setDragDrop(true).unwrap());
defer item.deinit();
var ret = item.getDragDrop();
try std.testing.expect(ret == true);
}
test "DropButton Theme" {
try iup.MainLoop.open();
defer iup.MainLoop.close();
var item = try (iup.DropButton.init().setTheme("Hello").unwrap());
defer item.deinit();
var ret = item.getTheme();
try std.testing.expect(std.mem.eql(u8, ret, "Hello"));
}
test "DropButton Expand" {
try iup.MainLoop.open();
defer iup.MainLoop.close();
var item = try (iup.DropButton.init().setExpand(.Yes).unwrap());
defer item.deinit();
var ret = item.getExpand();
try std.testing.expect(ret != null and ret.? == .Yes);
}
test "DropButton DrawFont" {
try iup.MainLoop.open();
defer iup.MainLoop.close();
var item = try (iup.DropButton.init().setDrawFont("Hello").unwrap());
defer item.deinit();
var ret = item.getDrawFont();
try std.testing.expect(std.mem.eql(u8, ret, "Hello"));
}
test "DropButton Size" {
try iup.MainLoop.open();
defer iup.MainLoop.close();
var item = try (iup.DropButton.init().setSize(9, 10).unwrap());
defer item.deinit();
var ret = item.getSize();
try std.testing.expect(ret.width != null and ret.width.? == 9 and ret.height != null and ret.height.? == 10);
}
test "DropButton Padding" {
try iup.MainLoop.open();
defer iup.MainLoop.close();
var item = try (iup.DropButton.init().setPadding(9, 10).unwrap());
defer item.deinit();
var ret = item.getPadding();
try std.testing.expect(ret.width != null and ret.width.? == 9 and ret.height != null and ret.height.? == 10);
}
test "DropButton PosX" {
try iup.MainLoop.open();
defer iup.MainLoop.close();
var item = try (iup.DropButton.init().setPosX(3.14).unwrap());
defer item.deinit();
var ret = item.getPosX();
try std.testing.expect(ret == @as(f64, 3.14));
}
test "DropButton PosY" {
try iup.MainLoop.open();
defer iup.MainLoop.close();
var item = try (iup.DropButton.init().setPosY(3.14).unwrap());
defer item.deinit();
var ret = item.getPosY();
try std.testing.expect(ret == @as(f64, 3.14));
}
test "DropButton BorderHlColor" {
try iup.MainLoop.open();
defer iup.MainLoop.close();
var item = try (iup.DropButton.init().setBorderHlColor(.{ .r = 9, .g = 10, .b = 11 }).unwrap());
defer item.deinit();
var ret = item.getBorderHlColor();
try std.testing.expect(ret != null and ret.?.r == 9 and ret.?.g == 10 and ret.?.b == 11);
}
test "DropButton TextHlColor" {
try iup.MainLoop.open();
defer iup.MainLoop.close();
var item = try (iup.DropButton.init().setTextHlColor(.{ .r = 9, .g = 10, .b = 11 }).unwrap());
defer item.deinit();
var ret = item.getTextHlColor();
try std.testing.expect(ret != null and ret.?.r == 9 and ret.?.g == 10 and ret.?.b == 11);
}
test "DropButton TipMarkup" {
try iup.MainLoop.open();
defer iup.MainLoop.close();
var item = try (iup.DropButton.init().setTipMarkup("Hello").unwrap());
defer item.deinit();
var ret = item.getTipMarkup();
try std.testing.expect(std.mem.eql(u8, ret, "Hello"));
}
test "DropButton YMin" {
try iup.MainLoop.open();
defer iup.MainLoop.close();
var item = try (iup.DropButton.init().setYMin(42).unwrap());
defer item.deinit();
var ret = item.getYMin();
try std.testing.expect(ret == 42);
}
test "DropButton TextEllipsis" {
try iup.MainLoop.open();
defer iup.MainLoop.close();
var item = try (iup.DropButton.init().setTextEllipsis(true).unwrap());
defer item.deinit();
var ret = item.getTextEllipsis();
try std.testing.expect(ret == true);
}
test "DropButton DrawMakeInactive" {
try iup.MainLoop.open();
defer iup.MainLoop.close();
var item = try (iup.DropButton.init().setDrawMakeInactive(true).unwrap());
defer item.deinit();
var ret = item.getDrawMakeInactive();
try std.testing.expect(ret == true);
}
test "DropButton FontSize" {
try iup.MainLoop.open();
defer iup.MainLoop.close();
var item = try (iup.DropButton.init().setFontSize(42).unwrap());
defer item.deinit();
var ret = item.getFontSize();
try std.testing.expect(ret == 42);
}
test "DropButton DropTypes" {
try iup.MainLoop.open();
defer iup.MainLoop.close();
var item = try (iup.DropButton.init().setDropTypes("Hello").unwrap());
defer item.deinit();
var ret = item.getDropTypes();
try std.testing.expect(std.mem.eql(u8, ret, "Hello"));
}
test "DropButton UserSize" {
try iup.MainLoop.open();
defer iup.MainLoop.close();
var item = try (iup.DropButton.init().setUserSize(9, 10).unwrap());
defer item.deinit();
var ret = item.getUserSize();
try std.testing.expect(ret.width != null and ret.width.? == 9 and ret.height != null and ret.height.? == 10);
}
test "DropButton TipDelay" {
try iup.MainLoop.open();
defer iup.MainLoop.close();
var item = try (iup.DropButton.init().setTipDelay(42).unwrap());
defer item.deinit();
var ret = item.getTipDelay();
try std.testing.expect(ret == 42);
}
test "DropButton ScrollBar" {
try iup.MainLoop.open();
defer iup.MainLoop.close();
var item = try (iup.DropButton.init().setScrollBar(true).unwrap());
defer item.deinit();
var ret = item.getScrollBar();
try std.testing.expect(ret == true);
}
test "DropButton Title" {
try iup.MainLoop.open();
defer iup.MainLoop.close();
var item = try (iup.DropButton.init().setTitle("Hello").unwrap());
defer item.deinit();
var ret = item.getTitle();
try std.testing.expect(std.mem.eql(u8, ret, "Hello"));
}
test "DropButton XAutoHide" {
try iup.MainLoop.open();
defer iup.MainLoop.close();
var item = try (iup.DropButton.init().setXAutoHide(true).unwrap());
defer item.deinit();
var ret = item.getXAutoHide();
try std.testing.expect(ret == true);
}
test "DropButton PropagateFocus" {
try iup.MainLoop.open();
defer iup.MainLoop.close();
var item = try (iup.DropButton.init().setPropagateFocus(true).unwrap());
defer item.deinit();
var ret = item.getPropagateFocus();
try std.testing.expect(ret == true);
}
test "DropButton XMax" {
try iup.MainLoop.open();
defer iup.MainLoop.close();
var item = try (iup.DropButton.init().setXMax(42).unwrap());
defer item.deinit();
var ret = item.getXMax();
try std.testing.expect(ret == 42);
}
test "DropButton BgColor" {
try iup.MainLoop.open();
defer iup.MainLoop.close();
var item = try (iup.DropButton.init().setBgColor(.{ .r = 9, .g = 10, .b = 11 }).unwrap());
defer item.deinit();
var ret = item.getBgColor();
try std.testing.expect(ret != null and ret.?.r == 9 and ret.?.g == 10 and ret.?.b == 11);
}
test "DropButton DropTarget" {
try iup.MainLoop.open();
defer iup.MainLoop.close();
var item = try (iup.DropButton.init().setDropTarget(true).unwrap());
defer item.deinit();
var ret = item.getDropTarget();
try std.testing.expect(ret == true);
}
test "DropButton DX" {
try iup.MainLoop.open();
defer iup.MainLoop.close();
var item = try (iup.DropButton.init().setDX(3.14).unwrap());
defer item.deinit();
var ret = item.getDX();
try std.testing.expect(ret == @as(f64, 3.14));
}
test "DropButton DY" {
try iup.MainLoop.open();
defer iup.MainLoop.close();
var item = try (iup.DropButton.init().setDY(3.14).unwrap());
defer item.deinit();
var ret = item.getDY();
try std.testing.expect(ret == @as(f64, 3.14));
}
test "DropButton DrawTextEllipsis" {
try iup.MainLoop.open();
defer iup.MainLoop.close();
var item = try (iup.DropButton.init().setDrawTextEllipsis(true).unwrap());
defer item.deinit();
var ret = item.getDrawTextEllipsis();
try std.testing.expect(ret == true);
}
test "DropButton DragSource" {
try iup.MainLoop.open();
defer iup.MainLoop.close();
var item = try (iup.DropButton.init().setDragSource(true).unwrap());
defer item.deinit();
var ret = item.getDragSource();
try std.testing.expect(ret == true);
}
test "DropButton DrawTextClip" {
try iup.MainLoop.open();
defer iup.MainLoop.close();
var item = try (iup.DropButton.init().setDrawTextClip(true).unwrap());
defer item.deinit();
var ret = item.getDrawTextClip();
try std.testing.expect(ret == true);
}
test "DropButton Floating" {
try iup.MainLoop.open();
defer iup.MainLoop.close();
var item = try (iup.DropButton.init().setFloating(.Yes).unwrap());
defer item.deinit();
var ret = item.getFloating();
try std.testing.expect(ret != null and ret.? == .Yes);
}
test "DropButton NormalizerGroup" {
try iup.MainLoop.open();
defer iup.MainLoop.close();
var item = try (iup.DropButton.init().setNormalizerGroup("Hello").unwrap());
defer item.deinit();
var ret = item.getNormalizerGroup();
try std.testing.expect(std.mem.eql(u8, ret, "Hello"));
}
test "DropButton Spacing" {
try iup.MainLoop.open();
defer iup.MainLoop.close();
var item = try (iup.DropButton.init().setSpacing(42).unwrap());
defer item.deinit();
var ret = item.getSpacing();
try std.testing.expect(ret == 42);
}
test "DropButton BorderPsColor" {
try iup.MainLoop.open();
defer iup.MainLoop.close();
var item = try (iup.DropButton.init().setBorderPsColor(.{ .r = 9, .g = 10, .b = 11 }).unwrap());
defer item.deinit();
var ret = item.getBorderPsColor();
try std.testing.expect(ret != null and ret.?.r == 9 and ret.?.g == 10 and ret.?.b == 11);
}
test "DropButton RasterSize" {
try iup.MainLoop.open();
defer iup.MainLoop.close();
var item = try (iup.DropButton.init().setRasterSize(9, 10).unwrap());
defer item.deinit();
var ret = item.getRasterSize();
try std.testing.expect(ret.width != null and ret.width.? == 9 and ret.height != null and ret.height.? == 10);
}
test "DropButton TextPsColor" {
try iup.MainLoop.open();
defer iup.MainLoop.close();
var item = try (iup.DropButton.init().setTextPsColor(.{ .r = 9, .g = 10, .b = 11 }).unwrap());
defer item.deinit();
var ret = item.getTextPsColor();
try std.testing.expect(ret != null and ret.?.r == 9 and ret.?.g == 10 and ret.?.b == 11);
}
test "DropButton BorderColor" {
try iup.MainLoop.open();
defer iup.MainLoop.close();
var item = try (iup.DropButton.init().setBorderColor(.{ .r = 9, .g = 10, .b = 11 }).unwrap());
defer item.deinit();
var ret = item.getBorderColor();
try std.testing.expect(ret != null and ret.?.r == 9 and ret.?.g == 10 and ret.?.b == 11);
}
test "DropButton TipFgColor" {
try iup.MainLoop.open();
defer iup.MainLoop.close();
var item = try (iup.DropButton.init().setTipFgColor(.{ .r = 9, .g = 10, .b = 11 }).unwrap());
defer item.deinit();
var ret = item.getTipFgColor();
try std.testing.expect(ret != null and ret.?.r == 9 and ret.?.g == 10 and ret.?.b == 11);
}
test "DropButton CSpacing" {
try iup.MainLoop.open();
defer iup.MainLoop.close();
var item = try (iup.DropButton.init().setCSpacing(42).unwrap());
defer item.deinit();
var ret = item.getCSpacing();
try std.testing.expect(ret == 42);
}
test "DropButton HlColor" {
try iup.MainLoop.open();
defer iup.MainLoop.close();
var item = try (iup.DropButton.init().setHlColor(.{ .r = 9, .g = 10, .b = 11 }).unwrap());
defer item.deinit();
var ret = item.getHlColor();
try std.testing.expect(ret != null and ret.?.r == 9 and ret.?.g == 10 and ret.?.b == 11);
}
test "DropButton FontFace" {
try iup.MainLoop.open();
defer iup.MainLoop.close();
var item = try (iup.DropButton.init().setFontFace("Hello").unwrap());
defer item.deinit();
var ret = item.getFontFace();
try std.testing.expect(std.mem.eql(u8, ret, "Hello"));
}
test "DropButton DrawColor" {
try iup.MainLoop.open();
defer iup.MainLoop.close();
var item = try (iup.DropButton.init().setDrawColor(.{ .r = 9, .g = 10, .b = 11 }).unwrap());
defer item.deinit();
var ret = item.getDrawColor();
try std.testing.expect(ret != null and ret.?.r == 9 and ret.?.g == 10 and ret.?.b == 11);
}
test "DropButton DrawTextOrientation" {
try iup.MainLoop.open();
defer iup.MainLoop.close();
var item = try (iup.DropButton.init().setDrawTextOrientation(3.14).unwrap());
defer item.deinit();
var ret = item.getDrawTextOrientation();
try std.testing.expect(ret == @as(f64, 3.14));
}
test "DropButton DrawBgColor" {
try iup.MainLoop.open();
defer iup.MainLoop.close();
var item = try (iup.DropButton.init().setDrawBgColor(.{ .r = 9, .g = 10, .b = 11 }).unwrap());
defer item.deinit();
var ret = item.getDrawBgColor();
try std.testing.expect(ret != null and ret.?.r == 9 and ret.?.g == 10 and ret.?.b == 11);
}
test "DropButton VisibleColumns" {
try iup.MainLoop.open();
defer iup.MainLoop.close();
var item = try (iup.DropButton.init().setVisibleColumns(42).unwrap());
defer item.deinit();
var ret = item.getVisibleColumns();
try std.testing.expect(ret == 42);
}
test "DropButton Name" {
try iup.MainLoop.open();
defer iup.MainLoop.close();
var item = try (iup.DropButton.init().setName("Hello").unwrap());
defer item.deinit();
var ret = item.getName();
try std.testing.expect(std.mem.eql(u8, ret, "Hello"));
}
test "DropButton BackingStore" {
try iup.MainLoop.open();
defer iup.MainLoop.close();
var item = try (iup.DropButton.init().setBackingStore(true).unwrap());
defer item.deinit();
var ret = item.getBackingStore();
try std.testing.expect(ret == true);
}
test "DropButton YAutoHide" {
try iup.MainLoop.open();
defer iup.MainLoop.close();
var item = try (iup.DropButton.init().setYAutoHide(true).unwrap());
defer item.deinit();
var ret = item.getYAutoHide();
try std.testing.expect(ret == true);
}
test "DropButton DrawStyle" {
try iup.MainLoop.open();
defer iup.MainLoop.close();
var item = try (iup.DropButton.init().setDrawStyle(.Fill).unwrap());
defer item.deinit();
var ret = item.getDrawStyle();
try std.testing.expect(ret != null and ret.? == .Fill);
}
test "DropButton BackImageZoom" {
try iup.MainLoop.open();
defer iup.MainLoop.close();
var item = try (iup.DropButton.init().setBackImageZoom(true).unwrap());
defer item.deinit();
var ret = item.getBackImageZoom();
try std.testing.expect(ret == true);
}
test "DropButton CPadding" {
try iup.MainLoop.open();
defer iup.MainLoop.close();
var item = try (iup.DropButton.init().setCPadding(9, 10).unwrap());
defer item.deinit();
var ret = item.getCPadding();
try std.testing.expect(ret.width != null and ret.width.? == 9 and ret.height != null and ret.height.? == 10);
}
test "DropButton TextOrientation" {
try iup.MainLoop.open();
defer iup.MainLoop.close();
var item = try (iup.DropButton.init().setTextOrientation(3.14).unwrap());
defer item.deinit();
var ret = item.getTextOrientation();
try std.testing.expect(ret == @as(f64, 3.14));
}
test "DropButton FitToBackImage" {
try iup.MainLoop.open();
defer iup.MainLoop.close();
var item = try (iup.DropButton.init().setFitToBackImage(true).unwrap());
defer item.deinit();
var ret = item.getFitToBackImage();
try std.testing.expect(ret == true);
}
test "DropButton Active" {
try iup.MainLoop.open();
defer iup.MainLoop.close();
var item = try (iup.DropButton.init().setActive(true).unwrap());
defer item.deinit();
var ret = item.getActive();
try std.testing.expect(ret == true);
}
test "DropButton TipVisible" {
try iup.MainLoop.open();
defer iup.MainLoop.close();
var item = try (iup.DropButton.init().setTipVisible(true).unwrap());
defer item.deinit();
var ret = item.getTipVisible();
try std.testing.expect(ret == true);
}
test "DropButton YMax" {
try iup.MainLoop.open();
defer iup.MainLoop.close();
var item = try (iup.DropButton.init().setYMax(42).unwrap());
defer item.deinit();
var ret = item.getYMax();
try std.testing.expect(ret == 42);
}
test "DropButton ExpandWeight" {
try iup.MainLoop.open();
defer iup.MainLoop.close();
var item = try (iup.DropButton.init().setExpandWeight(3.14).unwrap());
defer item.deinit();
var ret = item.getExpandWeight();
try std.testing.expect(ret == @as(f64, 3.14));
}
test "DropButton MinSize" {
try iup.MainLoop.open();
defer iup.MainLoop.close();
var item = try (iup.DropButton.init().setMinSize(9, 10).unwrap());
defer item.deinit();
var ret = item.getMinSize();
try std.testing.expect(ret.width != null and ret.width.? == 9 and ret.height != null and ret.height.? == 10);
}
test "DropButton ShowBorder" {
try iup.MainLoop.open();
defer iup.MainLoop.close();
var item = try (iup.DropButton.init().setShowBorder(true).unwrap());
defer item.deinit();
var ret = item.getShowBorder();
try std.testing.expect(ret == true);
}
test "DropButton ArrowImages" {
try iup.MainLoop.open();
defer iup.MainLoop.close();
var item = try (iup.DropButton.init().setArrowImages(42).unwrap());
defer item.deinit();
var ret = item.getArrowImages();
try std.testing.expect(ret == 42);
}
test "DropButton NTheme" {
try iup.MainLoop.open();
defer iup.MainLoop.close();
var item = try (iup.DropButton.init().setNTheme("Hello").unwrap());
defer item.deinit();
var ret = item.getNTheme();
try std.testing.expect(std.mem.eql(u8, ret, "Hello"));
}
test "DropButton ImagePosition" {
try iup.MainLoop.open();
defer iup.MainLoop.close();
var item = try (iup.DropButton.init().setImagePosition(.Left).unwrap());
defer item.deinit();
var ret = item.getImagePosition();
try std.testing.expect(ret != null and ret.? == .Left);
}
test "DropButton DragTypes" {
try iup.MainLoop.open();
defer iup.MainLoop.close();
var item = try (iup.DropButton.init().setDragTypes("Hello").unwrap());
defer item.deinit();
var ret = item.getDragTypes();
try std.testing.expect(std.mem.eql(u8, ret, "Hello"));
}
test "DropButton WheelDropFocus" {
try iup.MainLoop.open();
defer iup.MainLoop.close();
var item = try (iup.DropButton.init().setWheelDropFocus(true).unwrap());
defer item.deinit();
var ret = item.getWheelDropFocus();
try std.testing.expect(ret == true);
}
test "DropButton BorderWidth" {
try iup.MainLoop.open();
defer iup.MainLoop.close();
var item = try (iup.DropButton.init().setBorderWidth(42).unwrap());
defer item.deinit();
var ret = item.getBorderWidth();
try std.testing.expect(ret == 42);
}
test "DropButton FontStyle" {
try iup.MainLoop.open();
defer iup.MainLoop.close();
var item = try (iup.DropButton.init().setFontStyle("Hello").unwrap());
defer item.deinit();
var ret = item.getFontStyle();
try std.testing.expect(std.mem.eql(u8, ret, "Hello"));
}
test "DropButton TextAlignment" {
try iup.MainLoop.open();
defer iup.MainLoop.close();
var item = try (iup.DropButton.init().setTextAlignment(.ARight).unwrap());
defer item.deinit();
var ret = item.getTextAlignment();
try std.testing.expect(ret != null and ret.? == .ARight);
}
test "DropButton Touch" {
try iup.MainLoop.open();
defer iup.MainLoop.close();
var item = try (iup.DropButton.init().setTouch(true).unwrap());
defer item.deinit();
var ret = item.getTouch();
try std.testing.expect(ret == true);
}
test "DropButton TextWrap" {
try iup.MainLoop.open();
defer iup.MainLoop.close();
var item = try (iup.DropButton.init().setTextWrap(true).unwrap());
defer item.deinit();
var ret = item.getTextWrap();
try std.testing.expect(ret == true);
}
test "DropButton Font" {
try iup.MainLoop.open();
defer iup.MainLoop.close();
var item = try (iup.DropButton.init().setFont("Hello").unwrap());
defer item.deinit();
var ret = item.getFont();
try std.testing.expect(std.mem.eql(u8, ret, "Hello"));
}
|
src/elements/drop_button.zig
|
const std = @import("std");
const chipz = @import("chipz");
const Key = chipz.Key;
const c = @cImport({
@cInclude("SDL.h");
});
const DISPLAY_EVENT : u32 = 0;
fn manage_timer_callback(interval : u32, params : ?*c_void) callconv(.C) u32 {
if(params) |ptr| {
var timer = @ptrCast(*u8, ptr);
if(timer.* != 0) {
if(@subWithOverflow(u8, timer.*, @intCast(u8, 1), timer)) {
timer.* = 0;
}
}
}
return interval;
}
fn manage_cycle_callback(interval : u32, params : ?*c_void) callconv(.C) u32 {
if(params) |ptr| {
var emu = @ptrCast(*chipz.ChipZ, @alignCast(@alignOf(**chipz.ChipZ), ptr));
if(emu.cycle()) {} else |err| {
@panic("Faulting instruction");
}
if(emu.flags.display_update) {
publish_event_display();
}
}
return interval;
}
fn publish_event_display() void {
var userevent = c.SDL_UserEvent{
.type = c.SDL_USEREVENT,
.code = DISPLAY_EVENT,
.data1 = null,
.data2 = null,
.timestamp = 0,
.windowID = 0,
};
var event = c.SDL_Event{
.user = userevent,
};
_ = c.SDL_PushEvent(&event);
}
pub fn main() anyerror!void {
_ = c.SDL_Init(c.SDL_INIT_VIDEO);
defer c.SDL_Quit();
var window = c.SDL_CreateWindow("chipz", c.SDL_WINDOWPOS_CENTERED, c.SDL_WINDOWPOS_CENTERED, 64, 32, 0);
defer c.SDL_DestroyWindow(window);
var renderer = c.SDL_CreateRenderer(window, 0, c.SDL_RENDERER_PRESENTVSYNC);
defer c.SDL_DestroyRenderer(renderer);
var frame: usize = 0;
var general_purpose_allocator = std.heap.GeneralPurposeAllocator(.{}){};
const gpa = &general_purpose_allocator.allocator;
const args = try std.process.argsAlloc(gpa);
defer std.process.argsFree(gpa, args);
const file_path = args[1];
var file_handle = try std.fs.openFileAbsolute(file_path, .{.read = true, .write = false});
defer file_handle.close();
var buffer = try file_handle.readToEndAlloc(gpa, 4096-0x200);
defer gpa.free(buffer);
var emu = chipz.ChipZ.init(gpa);
emu.load_program(buffer);
var x : usize = 0;
var y : usize = 0;
var size_mult : c_int = 10;
var rect = c.SDL_Rect{ .x = 0, .y = 0, .w = size_mult, .h = size_mult };
var current_window_h : c_int = size_mult*32;
var current_window_w : c_int = size_mult*64;
c.SDL_SetWindowSize(window, current_window_w, current_window_h);
var timer_callback = c.SDL_AddTimer(16, manage_timer_callback, &emu.timer_delay);
var sound_timer_callback = c.SDL_AddTimer(16, manage_timer_callback, &emu.timer_sound);
var cycle_callback = c.SDL_AddTimer(1, manage_cycle_callback, &emu);
mainloop: while(true) {
var sdl_event: c.SDL_Event = undefined;
var force_redraw: bool = false;
defer force_redraw = false;
while (c.SDL_PollEvent(&sdl_event) != 0) {
switch (sdl_event.type) {
c.SDL_QUIT => break :mainloop,
c.SDL_KEYDOWN => {
switch(sdl_event.key.keysym.sym){
c.SDLK_UP, c.SDLK_DOWN => {
const mult : c_int = if(sdl_event.key.keysym.sym == c.SDLK_UP) 1 else -1;
size_mult += mult;
current_window_h = size_mult*32;
current_window_w = size_mult*64;
c.SDL_SetWindowSize(window, current_window_w, current_window_h);
c.SDL_RenderPresent(renderer);
rect.w = size_mult;
rect.h = size_mult;
publish_event_display();
},
// inputs
c.SDLK_1 => emu.flags.current_key_pressed = Key.One,
c.SDLK_2 => emu.flags.current_key_pressed = Key.Two,
c.SDLK_3 => emu.flags.current_key_pressed = Key.Three,
c.SDLK_4 => emu.flags.current_key_pressed = Key.C,
c.SDLK_q => emu.flags.current_key_pressed = Key.Four,
c.SDLK_w => emu.flags.current_key_pressed = Key.Five,
c.SDLK_e => emu.flags.current_key_pressed = Key.Six,
c.SDLK_r => emu.flags.current_key_pressed = Key.D,
c.SDLK_a => emu.flags.current_key_pressed = Key.Seven,
c.SDLK_s => emu.flags.current_key_pressed = Key.Eight,
c.SDLK_d => emu.flags.current_key_pressed = Key.Nine,
c.SDLK_f => emu.flags.current_key_pressed = Key.E,
c.SDLK_z => emu.flags.current_key_pressed = Key.A,
c.SDLK_x => emu.flags.current_key_pressed = Key.Zero,
c.SDLK_c => emu.flags.current_key_pressed = Key.B,
c.SDLK_v => emu.flags.current_key_pressed = Key.F,
else => {},
}
},
c.SDL_KEYUP => emu.flags.current_key_pressed = null,
c.SDL_USEREVENT => {
switch(sdl_event.user.code){
DISPLAY_EVENT => {
x = 0;
y = 0;
_ = c.SDL_SetRenderDrawColor(renderer, 0xff, 0xff, 0xff, 0xff);
_ = c.SDL_RenderClear(renderer);
while(x < 32) : (x += 1) {
y = 0;
while (y < 64) : (y += 1) {
rect.x = size_mult * @intCast(c_int, y);
rect.y = size_mult * @intCast(c_int, x);
if(emu.display[y][x]) {
_ = c.SDL_SetRenderDrawColor(renderer, 0xff, 0xff, 0xff, 0xff);
_ = c.SDL_RenderFillRect(renderer, &rect);
}
else
{
_ = c.SDL_SetRenderDrawColor(renderer, 0x00, 0x00, 0x00, 0xff);
_ = c.SDL_RenderFillRect(renderer, &rect);
}
}
}
c.SDL_RenderPresent(renderer);
},
else => {},
}
},
else => {},
}
}
}
}
|
src/main.zig
|
const std = @import("std");
const zigimg = @import("zigimg");
const helpers = @import("../helpers.zig");
const jpeg = zigimg.jpeg;
const errors = zigimg.errors;
const color = zigimg.color;
const testing = std.testing;
test "Should error on non JPEG images" {
const file = try helpers.testOpenFile(helpers.zigimg_test_allocator, "tests/fixtures/bmp/simple_v4.bmp");
defer file.close();
var stream_source = std.io.StreamSource{ .file = file };
var jpeg_file = jpeg.JPEG.init(helpers.zigimg_test_allocator);
defer jpeg_file.deinit();
var pixelsOpt: ?color.ColorStorage = null;
const invalidFile = jpeg_file.read(stream_source.reader(), stream_source.seekableStream(), &pixelsOpt);
defer {
if (pixelsOpt) |pixels| {
pixels.deinit(helpers.zigimg_test_allocator);
}
}
try helpers.expectError(invalidFile, errors.ImageError.InvalidMagicHeader);
}
test "Read JFIF header properly and decode simple Huffman stream" {
const file = try helpers.testOpenFile(helpers.zigimg_test_allocator, "tests/fixtures/jpeg/huff_simple0.jpg");
defer file.close();
var stream_source = std.io.StreamSource{ .file = file };
var jpeg_file = jpeg.JPEG.init(helpers.zigimg_test_allocator);
defer jpeg_file.deinit();
var pixelsOpt: ?color.ColorStorage = null;
const frame = try jpeg_file.read(stream_source.reader(), stream_source.seekableStream(), &pixelsOpt);
defer {
if (pixelsOpt) |pixels| {
pixels.deinit(helpers.zigimg_test_allocator);
}
}
try helpers.expectEq(frame.frame_header.row_count, 8);
try helpers.expectEq(frame.frame_header.samples_per_row, 16);
try helpers.expectEq(frame.frame_header.sample_precision, 8);
try helpers.expectEq(frame.frame_header.components.len, 3);
try testing.expect(pixelsOpt != null);
if (pixelsOpt) |pixels| {
try testing.expect(pixels == .Rgb24);
}
}
test "Read the tuba properly" {
const file = try helpers.testOpenFile(helpers.zigimg_test_allocator, "tests/fixtures/jpeg/tuba.jpg");
defer file.close();
var stream_source = std.io.StreamSource{ .file = file };
var jpeg_file = jpeg.JPEG.init(helpers.zigimg_test_allocator);
defer jpeg_file.deinit();
var pixelsOpt: ?color.ColorStorage = null;
const frame = try jpeg_file.read(stream_source.reader(), stream_source.seekableStream(), &pixelsOpt);
defer {
if (pixelsOpt) |pixels| {
pixels.deinit(helpers.zigimg_test_allocator);
}
}
try helpers.expectEq(frame.frame_header.row_count, 512);
try helpers.expectEq(frame.frame_header.samples_per_row, 512);
try helpers.expectEq(frame.frame_header.sample_precision, 8);
try helpers.expectEq(frame.frame_header.components.len, 3);
try testing.expect(pixelsOpt != null);
if (pixelsOpt) |pixels| {
try testing.expect(pixels == .Rgb24);
// Just for fun, let's sample a few pixels. :^)
try helpers.expectEq(pixels.Rgb24[(126 * 512 + 163)], color.Rgb24.initRGB(0xAC, 0x78, 0x54));
try helpers.expectEq(pixels.Rgb24[(265 * 512 + 284)], color.Rgb24.initRGB(0x37, 0x30, 0x33));
try helpers.expectEq(pixels.Rgb24[(431 * 512 + 300)], color.Rgb24.initRGB(0xFE, 0xE7, 0xC9));
}
}
|
tests/formats/jpeg_test.zig
|
const uefi = @import("std").os.uefi;
const fmt = @import("std").fmt;
const Writer = @import("std").io.Writer;
pub var con_out: *uefi.protocols.SimpleTextOutputProtocol = undefined;
pub const ConsoleColors = enum(u8) {
Black = uefi.protocols.SimpleTextOutputProtocol.black,
Blue = uefi.protocols.SimpleTextOutputProtocol.blue,
Green = uefi.protocols.SimpleTextOutputProtocol.green,
Cyan = uefi.protocols.SimpleTextOutputProtocol.cyan,
Red = uefi.protocols.SimpleTextOutputProtocol.red,
Magenta = uefi.protocols.SimpleTextOutputProtocol.magenta,
Brown = uefi.protocols.SimpleTextOutputProtocol.brown,
LightGray = uefi.protocols.SimpleTextOutputProtocol.lightgray,
DarkGray = uefi.protocols.SimpleTextOutputProtocol.darkgray,
LightBlue = uefi.protocols.SimpleTextOutputProtocol.lightblue,
LightGreen = uefi.protocols.SimpleTextOutputProtocol.lightgreen,
LightCyan = uefi.protocols.SimpleTextOutputProtocol.lightcyan,
LightRed = uefi.protocols.SimpleTextOutputProtocol.lightred,
LightMagenta = uefi.protocols.SimpleTextOutputProtocol.lightmagenta,
LightBrown = uefi.protocols.SimpleTextOutputProtocol.yellow,
White = uefi.protocols.SimpleTextOutputProtocol.white,
};
var row: usize = undefined;
var column: usize = undefined;
pub fn initialize() void {
_ = con_out.reset(false);
_ = con_out.queryMode(undefined, &column, &row);
clear();
}
pub fn enableCursor() void {
_ = con_out.enableCursor(true);
}
pub fn disableCursor() void {
_ = con_out.enableCursor(false);
}
pub fn setColor(comptime fg: ?ConsoleColors, comptime bg: ?ConsoleColors) void {
if (fg) |fg_| {
_ = con_out.setAttribute(@enumToInt(fg_));
}
if (bg) |bg_| {
_ = con_out.setAttribute(@enumToInt(bg_));
}
}
pub fn clear() void {
_ = con_out.clearScreen();
}
pub fn putCharAt(c: u8, x_: usize, y_: usize) void {
var backup_x = @intCast(usize, con_out.mode.cursor_row);
var backup_y = @intCast(usize, con_out.mode.cursor_column);
var x = x_;
var y = y_;
if (&x_ == undefined)
x = backup_x;
if (&y_ == undefined)
y = backup_y;
_ = con_out.setCursorPosition(y, x);
putChar(c);
_ = con_out.setCursorPosition(backup_y, backup_x);
}
pub fn putChar(c: u8) void {
const c_ = [2]u16{ c, 0 }; // work around https://github.com/ziglang/zig/issues/4372
if (c == '\n') {
_ = con_out.outputString(&[_:0]u16{ '\r', '\n' });
} else {
_ = con_out.outputString(@ptrCast(*const [1:0]u16, &c_));
}
}
pub fn puts(data: []const u8) void {
for (data) |c|
putChar(c);
}
pub const writer = Writer(void, error{}, callback){ .context = {} };
fn callback(_: void, string: []const u8) error{}!usize {
puts(string);
return string.len;
}
pub fn printf(comptime format: []const u8, args: anytype) void {
fmt.format(writer, format, args) catch unreachable;
}
|
stage1/uefi/console.zig
|
const clap = @import("clap");
const std = @import("std");
const util = @import("util.zig");
const debug = std.debug;
const fmt = std.fmt;
const heap = std.heap;
const io = std.io;
const math = std.math;
const mem = std.mem;
const testing = std.testing;
pub const test_case = @embedFile("test_file.tm35");
pub const TestProgramOptions = struct {
args: []const []const u8 = &[_][]const u8{},
in: []const u8 = test_case,
out: []const u8,
};
pub fn testProgram(
comptime Program: type,
args: []const []const u8,
in: []const u8,
out: []const u8,
) !void {
const res = try runProgram(Program, .{ .args = args, .in = in });
defer testing.allocator.free(res);
try testing.expectEqualStrings(out, res);
}
pub const RunProgramOptions = struct {
args: []const []const u8,
in: []const u8 = test_case,
};
pub fn runProgram(comptime Program: type, opt: RunProgramOptions) ![:0]const u8 {
var arena_state = std.heap.ArenaAllocator.init(testing.allocator);
defer arena_state.deinit();
var stdout = std.ArrayList(u8).init(testing.allocator);
var stdin = io.fixedBufferStream(opt.in);
var arg_iter = clap.args.SliceIterator{ .args = opt.args };
const clap_args = try clap.parseEx(clap.Help, Program.params, &arg_iter, .{});
defer clap_args.deinit();
const StdIo = util.CustomStdIoStreams(
std.io.FixedBufferStream([]const u8).Reader,
std.ArrayList(u8).Writer,
);
var program = try Program.init(arena_state.allocator(), clap_args);
try program.run(
StdIo.Reader,
StdIo.Writer,
.{ .in = stdin.reader(), .out = stdout.writer() },
);
return stdout.toOwnedSliceSentinel(0);
}
pub const Context = struct {
handle: *const anyopaque,
len: usize,
pub fn fromSlice(slice: anytype) Context {
return .{
.handle = @ptrCast(*const anyopaque, slice.ptr),
.len = slice.len,
};
}
pub fn toSlice(ctx: Context, comptime T: type) []const T {
const ptr = @ptrCast([*]const T, ctx.handle);
return ptr[0..ctx.len];
}
};
pub const Pattern = struct {
min: usize,
max: usize,
ctx: Context,
find: fn (Context, []const u8, usize) ?usize,
pub fn string(min: usize, max: usize, str: []const u8) Pattern {
return .{
.min = min,
.max = max,
.ctx = Context.fromSlice(str),
.find = findString,
};
}
fn findString(ctx: Context, haystack: []const u8, pos: usize) ?usize {
const slice = ctx.toSlice(u8);
const index = mem.indexOfPos(u8, haystack, pos, slice) orelse return null;
return index + slice.len;
}
pub fn glob(min: usize, max: usize, str: []const u8) Pattern {
return .{
.min = min,
.max = max,
.ctx = Context.fromSlice(str),
.find = findGlob,
};
}
fn findGlob(ctx: Context, haystack: []const u8, pos: usize) ?usize {
const glob_str = ctx.toSlice(u8);
var it = mem.split(u8, haystack, "\n");
it.index = pos;
while (it.next()) |line| {
if (util.glob.match(glob_str, line))
return it.index;
}
return null;
}
};
pub const FindMatchesOptions = struct {
args: []const []const u8 = &[_][]const u8{},
in: []const u8 = test_case,
patterns: []const Pattern,
};
/// Runs `Program` and checks that the output contains a number of patterns. A pattern is just
/// something that can be found in a string, and a pattern also specifies how many of that
/// pattern is expected to be found in the output.
pub fn runProgramFindPatterns(comptime Program: type, opt: FindMatchesOptions) !void {
const res = try runProgram(Program, .{ .args = opt.args, .in = opt.in });
defer testing.allocator.free(res);
var fail: bool = false;
for (opt.patterns) |pattern| {
var i: usize = 0;
var matches: usize = 0;
while (pattern.find(pattern.ctx, res, i)) |end| : (i = end)
matches += 1;
if (matches < pattern.min or pattern.max < matches) {
std.debug.print("\nexpected between {} and {} matches, found {}", .{
pattern.min,
pattern.max,
matches,
});
fail = true;
}
}
if (fail) {
std.debug.print("\n", .{});
return error.TestExpectedEqual;
}
}
pub fn filter(in: []const u8, globs: []const []const u8) ![:0]u8 {
var res = std.ArrayList(u8).init(testing.allocator);
errdefer res.deinit();
var it = mem.split(u8, in, "\n");
while (it.next()) |line| {
if (util.glob.matchesOneOf(line, globs) == null)
continue;
try res.appendSlice(line);
try res.append('\n');
}
return res.toOwnedSliceSentinel(0);
}
pub fn boundPrint(
comptime bound: usize,
comptime format: []const u8,
args: anytype,
) !std.BoundedArray(u8, bound) {
var res: std.BoundedArray(u8, bound) = undefined;
res.len = (try fmt.bufPrint(&res.buffer, format, args)).len;
return res;
}
|
src/common/testing.zig
|
const std = @import("std");
const warn = std.debug.warn;
const Allocator = std.mem.Allocator;
const TreeNode = struct {
l: ?*TreeNode,
r: ?*TreeNode,
pub fn new(a: *Allocator, l: ?*TreeNode, r: ?*TreeNode) !*TreeNode {
var node = try a.create(TreeNode);
node.l = l;
node.r = r;
return node;
}
pub fn free(self: *TreeNode, a: &Allocator) void {
a.free(self);
}
};
fn itemCheck(node: *TreeNode) usize {
if (node.l) |left| {
// either have both nodes or none
return 1 + itemCheck(left) + itemCheck(??node.r);
} else {
return 1;
}
}
fn bottomUpTree(a: *Allocator, depth: usize) Allocator.Error!*TreeNode {
if (depth > 0) {
return try TreeNode.new(a, try bottomUpTree(a, depth - 1), try bottomUpTree(a, depth - 1));
} else {
return try TreeNode.new(a, null, null);
}
}
fn deleteTree(a: *Allocator, node: *TreeNode) void {
if (node.l) |left| {
// either have both nodes or none
deleteTree(a, left);
deleteTree(a, ??node.r);
}
a.destroy(node);
}
pub fn testAllocator(comptime n: usize, allocator: *Allocator) !void {
const min_depth: usize = 4;
const max_depth: usize = n;
const stretch_depth = max_depth + 1;
const stretch_tree = try bottomUpTree(allocator, stretch_depth);
warn(" depth {}, check {}\n", stretch_depth, itemCheck(stretch_tree));
deleteTree(allocator, stretch_tree);
const long_lived_tree = try bottomUpTree(allocator, max_depth);
var depth = min_depth;
while (depth <= max_depth) : (depth += 2) {
var iterations = usize(std.math.pow(f32, 2, f32(max_depth - depth + min_depth)));
var check: usize = 0;
var i: usize = 1;
while (i <= iterations) : (i += 1) {
const temp_tree = try bottomUpTree(allocator, depth);
check += itemCheck(temp_tree);
deleteTree(allocator, temp_tree);
}
warn(" {} trees of depth {}, check {}\n", iterations, depth, check);
}
warn(" long lived tree of depth {}, check {}\n", max_depth, itemCheck(long_lived_tree));
deleteTree(allocator, long_lived_tree);
}
|
test/binary_trees.zig
|
const std = @import("std");
const util = @import("util.zig");
const File = @This();
id: Id,
ref_count: u16,
var all: std.AutoHashMap(Id, File) = undefined;
var incr: util.AutoIncr(Id, 3) = .{};
pub fn open(path: []const u8, flags: Flags, perm: Mode) !*File {
const fid = incr.next(all);
if (true) {
unreachable;
}
first_available = fid;
try self.all.putNoClobber(fid, .{
.id = fid,
.ref_count = 1,
});
return fid.file();
}
pub fn retain(file: *File) void {
switch (file.id) {
.stdin, .stdout, .stderr => return,
else => {},
}
file.ref_count += 1;
}
pub fn release(file: *File) void {
switch (file.id) {
.stdin, .stdout, .stderr => return,
else => {},
}
file.ref_count -= 1;
if (file.ref_count == 0) {
file.close();
}
}
const _keep_descriptors_low = false;
fn close(file: *File) void {
std.debug.assert(file.ref_count == 0);
// I don't think this matters
if (_keep_descriptors_low) {
if (@enumToInt(file.id) < @enumToInt(incr.prev)) {
incr.reset(file.id);
}
}
@panic("TODO");
}
pub fn read(file: File, buf: []u8) !usize {
return 0;
}
pub fn write(file: File, bytes: []const u8) !usize {
return 0;
}
pub const Id = enum(u32) {
stdin = 0,
stdout = 1,
stderr = 2,
_,
pub fn file(fid: Id) *File {
return &all.getEntry(fid).?.value;
}
};
pub const Flags = EndianOrdered(packed struct {
access: u3,
_pad1: u3,
creat: bool,
excl: bool,
noctty: bool,
trunc: bool,
append: bool,
nonblock: bool,
dsync: bool,
@"async": bool,
directory: bool,
nofollow: bool,
largefile: bool,
direct: bool,
noatime: bool,
cloexec: bool,
sync: bool, // sync + dsync == O_SYNC
path: bool,
tmpfile: bool, // tmpfile + directory == O_TMPFILE
_pad2: u1,
_pad3: u8,
});
pub const Access = enum(u2) {
read = 0o0,
write = 0o1,
read_write = 0o2,
_,
pub fn raw(self: Format) u4 {
return @enumToInt(self);
}
};
test "Flags" {
std.testing.expectEqual(@as(usize, 4), @sizeOf(Flags));
std.testing.expectEqual(@as(usize, 32), @bitSizeOf(Flags));
}
pub const Mode = EndianOrdered(packed struct {
other_execute: bool,
other_write: bool,
other_read: bool,
group_execute: bool,
group_write: bool,
group_read: bool,
owner_execute: bool,
owner_write: bool,
owner_read: bool,
restricted_delete: bool,
set_gid: bool,
set_uid: bool,
// TODO: make this type Format, compiler currently crashes with "buf_read_value_bytes enum packed"
format: u4,
_pad: u16 = 0,
});
pub const Format = enum(u4) {
fifo = 0o1,
char = 0o2,
dir = 0o4,
block = 0o6,
reg = 0o10,
symlink = 0o12,
socket = 0o14,
_,
pub fn raw(self: Format) u4 {
return @enumToInt(self);
}
};
test "Mode" {
std.testing.expectEqual(@as(usize, 4), @sizeOf(Mode));
std.testing.expectEqual(@as(usize, 32), @bitSizeOf(Mode));
const S_IFMT: u32 = 0o170000;
const S_IFDIR: u32 = 0o040000;
const S_IFCHR: u32 = 0o020000;
const S_IFBLK: u32 = 0o060000;
const S_IFREG: u32 = 0o100000;
const S_IFIFO: u32 = 0o010000;
const S_IFLNK: u32 = 0o120000;
const S_IFSOCK: u32 = 0o140000;
var mode = @bitCast(Mode, @as(u32, 0));
mode.format = Format.fifo.raw();
std.testing.expectEqual(S_IFIFO, S_IFMT & @bitCast(u32, mode));
mode.format = Format.block.raw();
std.testing.expectEqual(S_IFBLK, S_IFMT & @bitCast(u32, mode));
const S_ISUID: u32 = 0o4000;
const S_ISGID: u32 = 0o2000;
const S_ISVTX: u32 = 0o1000;
std.testing.expectEqual(@as(u32, 0), S_ISVTX & @bitCast(u32, mode));
mode.restricted_delete = true;
std.testing.expectEqual(S_ISVTX, S_ISVTX & @bitCast(u32, mode));
std.testing.expectEqual(@as(u32, 0), S_ISUID & @bitCast(u32, mode));
mode.set_uid = true;
std.testing.expectEqual(S_ISUID, S_ISUID & @bitCast(u32, mode));
const S_IRUSR: u32 = 0o400;
const S_IWUSR: u32 = 0o200;
const S_IXUSR: u32 = 0o100;
const S_IRGRP: u32 = 0o040;
const S_IWGRP: u32 = 0o020;
const S_IXGRP: u32 = 0o010;
const S_IROTH: u32 = 0o004;
const S_IWOTH: u32 = 0o002;
const S_IXOTH: u32 = 0o001;
}
fn EndianOrdered(comptime T: type) type {
if (std.builtin.endian == .Little) {
return T;
} else {
var info = @typeInfo(T);
const len = info.Struct.fields.len;
var reversed_fields: [len]std.builtin.TypeInfo.StructField = undefined;
for (info.Struct.fields) |field, i| {
reversed_fields[len - 1 - i] = field;
}
info.Struct.fields = &reversed_fields;
return @Type(info);
}
}
|
src/File.zig
|
extern fn glBlendColor(_: f32, _: f32, _: f32, _: f32) void;
extern fn glBlendEquation(_: c_uint) void;
extern fn glBlendEquationSeparate(_: c_uint, _: c_uint) void;
extern fn glBlendFunc(_: c_uint, _: c_uint) void;
extern fn glBlendFuncSeparate(_: c_uint, _: c_uint, _: c_uint, _: c_uint) void;
extern fn glDepthFunc(_: c_uint) void;
extern fn glSampleCoverage(_: f32, _: c_uint) void;
extern fn glStencilFunc(_: c_uint, _: c_int, _: c_uint) void;
extern fn glStencilFuncSeparate(_: c_uint, _: c_uint, _: c_int, _: c_uint) void;
extern fn glStencilOp(_: c_uint, _: c_uint, _: c_uint) void;
extern fn glStencilOpSeparate(_: c_uint, _: c_uint, _: c_uint, _: c_uint) void;
// Buffer Objects
extern fn glCreateBuffer() c_uint;
extern fn glDeleteBuffer(_: c_uint) void;
extern fn glBindBuffer(_: c_uint, _: c_uint) void;
extern fn glBufferData(_: c_uint, _: c_uint, _: [*]const u8, _: c_uint) void;
extern fn glBufferSubData(_: c_uint, _: c_uint, _: c_uint, [*]const u8) void;
// Programs and Shaders
extern fn glAttachShader(_: c_uint, _: c_uint) void;
extern fn glCompileShader(_: c_uint) void;
extern fn glCreateProgram() c_uint;
extern fn glCreateShader(_: c_uint) c_uint;
extern fn glDeleteProgram(_: c_uint) void;
extern fn glDeleteShader(_: c_uint) void;
extern fn glDetachShader(_: c_uint, _: c_uint) void;
extern fn glLinkProgram(_: c_uint) void;
extern fn glShaderSource(_: c_uint, _: [*]const u8, _: c_uint) void;
extern fn glUseProgram(_: c_uint) void;
extern fn glValidateProgram(_: c_uint) void;
// Special Functions
// TODO: This
// Rasterization
extern fn glCullFace(_: c_uint) void;
extern fn glFrontFace(_: c_uint) void;
extern fn glLineWidth(_: f32) void;
extern fn glPolygonOffset(_: f32, _: f32) void;
// View and Clip
extern fn glDepthRange(_: f32, _: f32) void;
extern fn glScissor(_: c_int, _: c_int, _: c_long, _: c_long) void;
extern fn glViewport(_: c_int, _: c_int, _: c_long, _: c_long) void;
// Writing to the Draw Buffer
extern fn glDrawArrays(_: c_uint, _: c_uint, _: c_uint) void;
extern fn glDrawElements(_: c_uint, _: c_uint, _: c_uint, _: c_uint) void;
extern fn glVertexAttribDivisor(_: c_uint, _: c_uint) void;
extern fn glDrawArraysInstanced(_: c_uint, _: c_uint, _: c_uint, _: c_uint) void;
extern fn glDrawElementsInstanced(_: c_uint, _: c_uint, _: c_uint, _: c_uint, _: c_uint) void;
extern fn glDrawRangeElements(_: c_uint, _: c_uint, _: c_uint, _: c_uint, _: c_uint, _: c_uint) void;
// Uniforms and Attributes
extern fn glDisableVertexAttribArray(_: c_uint) void;
extern fn glEnableVertexAttribArray(_: c_uint) void;
extern fn glGetUniformLocation(_: c_uint, _: [*]const u8, _: c_int) c_uint;
extern fn glUniform1f(_: c_uint, _: f32) void;
extern fn glUniform2fv(_: c_int, _: f32, _: f32) void;
extern fn glUniform3fv(_: c_int, _: f32, _: f32, _: f32) void;
extern fn glUniform4fv(_: c_int, _: f32, _: f32, _: f32, _: f32) void;
extern fn glUniform1i(_: c_int, _: c_int) void;
extern fn glUniform2iv(_: c_int, _: c_int, _: c_int) void;
extern fn glUniform3iv(_: c_int, _: c_int, _: c_int, _: c_int) void;
extern fn glUniform4iv(_: c_int, _: c_int, _: c_int, _: c_int, _: c_int) void;
extern fn glUniform1ui(_: c_int, _: c_uint) void;
extern fn glUniform2uiv(_: c_int, _: c_uint, _: c_uint) void;
extern fn glUniform3uiv(_: c_int, _: c_uint, _: c_uint, _: c_uint) void;
extern fn glUniform4uiv(_: c_int, _: c_uint, _: c_uint, _: c_uint, _: c_uint) void;
extern fn glUniformMatrix2fv(_: c_int, _: c_uint, [*]const f32) void;
extern fn glUniformMatrix3fv(_: c_int, _: c_uint, [*]const f32) void;
extern fn glUniformMatrix4fv(_: c_int, _: c_uint, [*]const f32) void;
extern fn glVertexAttribPointer(_: c_uint, _: c_uint, _: c_uint, _: c_uint, _: c_uint, _: [*c]const c_uint) void;
extern fn glVertexAttribIPointer(_: c_uint, _: c_uint, _: c_uint, _: c_uint, _: [*c]const c_uint) void;
// Vertex Array Objects
extern fn glBindVertexArray(_: c_uint) void;
extern fn glCreateVertexArray() c_uint;
extern fn glDeleteVertexArray(_: c_uint) void;
// Texture Objects
extern fn glActiveTexture(_: c_uint) void;
extern fn bindTexture(_: c_uint, _: c_uint) void;
// TODO: The rest
// Framebuffer Objects
// TODO: This
// Renderbuffer Objects
// TODO: This
// Whole Framebuffer Operations
extern fn glClear(_: c_uint) void;
extern fn glClearColor(_: f32, _: f32, _: f32, _: f32) void;
extern fn glClearDepth(_: f32) void;
extern fn glClearStencil(s: c_int) void;
extern fn glColorMask(_: c_uint, _: c_uint, _: c_uint, _: c_uint) void;
extern fn glDepthMask(_: c_uint) void;
extern fn glStencilMask(_: c_uint) void;
extern fn glStencilMaskSeparate(_: c_uint, _: c_uint) void;
// Multiple Render Targets
// TODO: This
// Sampler Objects
// TODO: This
// Query Objects
// TODO: This
// Transform Feedback
// TODO: This
// Sync Objects
// TODO: This
// Uniform Buffer Objects
// TODO: This
// Types
pub const GLuint = c_uint;
pub const GLenum = c_uint;
pub const GLint = c_int;
pub const GLfloat = f32;
// Identifier constants pulled from WebGLRenderingContext
const GL_VERTEX_SHADER: c_uint = 35633;
const GL_FRAGMENT_SHADER: c_uint = 35632;
const GL_ARRAY_BUFFER: c_uint = 34962;
const GL_TRIANGLES: c_uint = 4;
const GL_TRIANGLE_STRIP = 5;
const GL_STATIC_DRAW: c_uint = 35044;
const GL_FLOAT: c_uint = 5126;
const GL_DEPTH_TEST: c_uint = 2929;
const GL_LEQUAL: c_uint = 515;
const GL_COLOR_BUFFER_BIT: c_uint = 16384;
const GL_DEPTH_BUFFER_BIT: c_uint = 256;
const GL_STENCIL_BUFFER_BIT = 1024;
const GL_TEXTURE_2D: c_uint = 3553;
const GL_RGBA: c_uint = 6408;
const GL_UNSIGNED_BYTE: c_uint = 5121;
const GL_TEXTURE_MAG_FILTER: c_uint = 10240;
const GL_TEXTURE_MIN_FILTER: c_uint = 10241;
const GL_NEAREST: c_uint = 9728;
const GL_TEXTURE0: c_uint = 33984;
const GL_BLEND: c_uint = 3042;
const GL_SRC_ALPHA: c_uint = 770;
const GL_ONE_MINUS_SRC_ALPHA: c_uint = 771;
const GL_ONE: c_uint = 1;
const GL_NO_ERROR = 0;
const GL_FALSE = 0;
const GL_TRUE = 1;
const GL_UNPACK_ALIGNMENT = 3317;
const GL_TEXTURE_WRAP_S = 10242;
const GL_CLAMP_TO_EDGE = 33071;
const GL_TEXTURE_WRAP_T = 10243;
const GL_PACK_ALIGNMENT = 3333;
pub const blendColor = glBlendColor;
pub const blendEquation = glBlendEquation;
pub const blendEquationSeparate = glBlendEquationSeparate;
pub const blendFunc = glBlendFunc;
pub const blendFuncSeparate = glBlendFuncSeparate;
pub const depthFunc = glDepthFunc;
pub const sampleCoverage = glSampleCoverage;
pub const stencilFunc = glStencilFunc;
pub const stencilFuncSeparate = glStencilFuncSeparate;
pub const stencilOp = glStencilOp;
pub const stencilOpSeparate = glStencilOpSeparate;
pub const createBuffer = glCreateBuffer;
pub const deleteBuffer = glDeleteBuffer;
pub const bindBuffer = glBindBuffer;
pub const bufferData = glBufferData;
pub const bufferSubData = glBufferSubData;
pub const attachShader = glAttachShader;
pub const compileShader = glCompileShader;
pub const createProgram = glCreateProgram;
pub const createShader = glCreateShader;
pub const deleteProgram = glDeleteProgram;
pub const deleteShader = glDeleteShader;
pub const detachShader = glDetachShader;
pub const linkProgram = glLinkProgram;
pub const shaderSource = glShaderSource;
pub const useProgram = glUseProgram;
pub const validateProgram = glValidateProgram;
pub const cullFace = glCullFace;
pub const frontFace = glFrontFace;
pub const lineWidth = glLineWidth;
pub const polygonOffset = glPolygonOffset;
pub const depthRange = glDepthRange;
pub const scissor = glScissor;
pub const viewport = glViewport;
pub const drawArrays = glDrawArrays;
pub const drawElements = glDrawElements;
pub const vertexAttribDivisor = glVertexAttribDivisor;
pub const drawArraysInstanced = glDrawArraysInstanced;
pub const drawElementsInstanced = glDrawElementsInstanced;
pub const drawRangeElements = glDrawRangeElements;
pub const disableVertexAttribArray = glDisableVertexAttribArray;
pub const enableVertexAttribArray = glEnableVertexAttribArray;
pub const getUniformLocation = glGetUniformLocation;
pub const uniform1f = glUniform1f;
pub const uniform2fv = glUniform2fv;
pub const uniform3fv = glUniform3fv;
pub const uniform4fv = glUniform4fv;
pub const uniform1i = glUniform1i;
pub const uniform2iv = glUniform2iv;
pub const uniform3iv = glUniform3iv;
pub const uniform4iv = glUniform4iv;
pub const uniform1ui = glUniform1ui;
pub const uniform2uiv = glUniform2uiv;
pub const uniform3uiv = glUniform3uiv;
pub const uniform4uiv = glUniform4uiv;
pub const uniformMatrix2fv = glUniformMatrix2fv;
pub const uniformMatrix3fv = glUniformMatrix3fv;
pub const uniformMatrix4fv = glUniformMatrix4fv;
pub const vertexAttribPointer = glVertexAttribPointer;
pub const vertexAttribIPointer = glVertexAttribIPointer;
pub const bindVertexArray = glBindVertexArray;
pub const createVertexArray = glCreateVertexArray;
pub const deleteVertexArray = glDeleteVertexArray;
pub const activeTexture = glActiveTexture;
pub const ndTexture = bindTexture;
pub const clear = glClear;
pub const clearColor = glClearColor;
pub const clearDepth = glClearDepth;
pub const clearStencil = glClearStencil;
pub const colorMask = glColorMask;
pub const depthMask = glDepthMask;
pub const stencilMask = glStencilMask;
pub const stencilMaskSeparate = glStencilMaskSeparate;
pub const VERTEX_SHADER = GL_VERTEX_SHADER;
pub const FRAGMENT_SHADER = GL_FRAGMENT_SHADER;
pub const ARRAY_BUFFER = GL_ARRAY_BUFFER;
pub const TRIANGLES = GL_TRIANGLES;
pub const TRIANGLE_STRIP = GL_TRIANGLE_STRIP;
pub const STATIC_DRAW = GL_STATIC_DRAW;
pub const FLOAT = GL_FLOAT;
pub const DEPTH_TEST = GL_DEPTH_TEST;
pub const LEQUAL = GL_LEQUAL;
pub const COLOR_BUFFER_BIT = GL_COLOR_BUFFER_BIT;
pub const DEPTH_BUFFER_BIT = GL_DEPTH_BUFFER_BIT;
pub const STENCIL_BUFFER_BIT = GL_STENCIL_BUFFER_BIT;
pub const TEXTURE_2D = GL_TEXTURE_2D;
pub const RGBA = GL_RGBA;
pub const UNSIGNED_BYTE = GL_UNSIGNED_BYTE;
pub const TEXTURE_MAG_FILTER = GL_TEXTURE_MAG_FILTER;
pub const TEXTURE_MIN_FILTER = GL_TEXTURE_MIN_FILTER;
pub const NEAREST = GL_NEAREST;
pub const TEXTURE0 = GL_TEXTURE0;
pub const BLEND = GL_BLEND;
pub const SRC_ALPHA = GL_SRC_ALPHA;
pub const ONE_MINUS_SRC_ALPHA = GL_ONE_MINUS_SRC_ALPHA;
pub const ONE = GL_ONE;
pub const NO_ERROR = GL_NO_ERROR;
pub const FALSE = GL_FALSE;
pub const TRUE = GL_TRUE;
pub const UNPACK_ALIGNMENT = GL_UNPACK_ALIGNMENT;
pub const TEXTURE_WRAP_S = GL_TEXTURE_WRAP_S;
pub const CLAMP_TO_EDGE = GL_CLAMP_TO_EDGE;
pub const TEXTURE_WRAP_T = GL_TEXTURE_WRAP_T;
pub const PACK_ALIGNMENT = GL_PACK_ALIGNMENT;
|
src/webgl.zig
|
const std = @import("std");
pub const Key = struct {
const Self = @This();
index: u32,
version: u32,
pub fn equals(lhs: Self, rhs: Self) bool {
return lhs.index == rhs.index and lhs.version == rhs.version;
}
};
fn Slot(comptime T: type) type {
return struct {
const Self = @This();
version: u32,
next_free: u32,
value: T,
fn new(version: u32, next_free: u32, value: T) Self {
return Self{
.version = version,
.next_free = next_free,
.value = value,
};
}
fn occupied(self: Self) bool {
return self.version % 2 > 0;
}
};
}
pub fn SlotMap(comptime T: type) type {
return struct {
const Self = @This();
const SlotType = Slot(T);
pub const Error = error{
OverflowError,
InvalidKey,
};
pub const Iterator = struct {
map: *const Self,
index: usize,
pub fn next_key(self: *Iterator) ?Key {
if (self.map.len == 0 or self.index > self.map.len) {
self.reset();
return null;
}
while (!self.map.slots.at(self.index).occupied()) : (self.index += 1) {}
self.index += 1;
return Key{
.index = @intCast(u32, self.index - 1),
.version = self.map.slots.at(self.index - 1).version,
};
}
pub fn next_value(self: *Iterator) ?T {
if (self.map.len == 0 or self.index > self.map.len) {
self.reset();
return null;
}
while (!self.map.slots.at(self.index).occupied()) : (self.index += 1) {}
self.index += 1;
return self.map.slots.at(self.index - 1).value;
}
fn reset(self: *Iterator) void {
self.index = 0;
}
};
slots: std.ArrayList(SlotType),
free_head: usize,
len: usize,
pub fn init(allocator: *std.mem.Allocator, size: u32) !Self {
var result = Self{
.slots = std.ArrayList(SlotType).init(allocator),
.free_head = 0,
.len = 0,
};
try result.set_capacity(size);
return result;
}
pub fn deinit(self: Self) void {
self.slots.deinit();
}
pub fn count(self: Self) usize {
return self.len;
}
pub fn capacity(self: Self) usize {
return self.slots.capacity();
}
pub fn set_capacity(self: *Self, new_capacity: usize) !void {
try self.slots.ensureCapacity(new_capacity);
}
pub fn has_key(self: Self, key: Key) bool {
if (key.index < self.slots.count()) {
const slot = self.slots.at(key.index);
return slot.version == key.version;
} else {
return false;
}
}
pub fn insert(self: *Self, value: T) !Key {
const new_len = self.len + 1;
if (new_len == std.math.maxInt(u32)) {
return error.OverflowError;
}
const idx = self.free_head;
if (idx < self.slots.count()) {
const slots = self.slots.toSlice();
const occupied_version = slots[idx].version | 1;
const result = Key{
.index = @intCast(u32, idx),
.version = occupied_version,
};
slots[idx].value = value;
slots[idx].version = occupied_version;
self.free_head = slots[idx].next_free;
self.len = new_len;
return result;
} else {
const result = Key{
.index = @intCast(u32, idx),
.version = 1,
};
try self.slots.append(SlotType.new(1, 0, value));
self.free_head = self.slots.count();
self.len = new_len;
return result;
}
}
// TODO: find out how to do this correctly
fn reserve(self: *Self) !Key {
const default: T = undefined;
return try self.insert(default);
}
fn remove_from_slot(self: *Self, idx: usize) T {
const slots = self.slots.toSlice();
slots[idx].next_free = @intCast(u32, self.free_head);
slots[idx].version += 1;
self.free_head = idx;
self.len -= 1;
return slots[idx].value;
}
pub fn remove(self: *Self, key: Key) !T {
if (self.has_key(key)) {
return self.remove_from_slot(key.index);
} else {
return error.InvalidKey;
}
}
pub fn delete(self: *Self, key: Key) !void {
if (self.has_key(key)) {
_ = self.remove_from_slot(key.index);
} else {
return error.InvalidKey;
}
}
// TODO: zig closures
fn retain(self: *Self, filter: fn (key: Key, value: T) bool) void {
const len = self.slots.len;
var idx = 0;
while (idx < len) : (idx += 1) {
const slot = self.slots.at(idx);
const key = Key{ .index = idx, .version = slot.version };
if (slot.occupied and !filter(key, value)) {
_ = self.remove_from_slot(idx);
}
}
}
pub fn clear(self: *Self) void {
while (self.len > 0) {
_ = self.remove_from_slot(self.len);
}
self.slots.shrink(0);
self.free_head = 0;
}
pub fn get(self: *const Self, key: Key) !T {
if (self.has_key(key)) {
return self.slots.at(key.index).value;
} else {
return error.InvalidKey;
}
}
pub fn get_ptr(self: *const Self, key: Key) !*T {
if (self.has_key(key)) {
const slots = self.slots.toSlice();
return &slots[key.index].value;
} else {
return error.InvalidKey;
}
}
pub fn set(self: *Self, key: Key, value: T) !void {
if (self.has_key(key)) {
const slots = self.slots.toSlice();
slots[key.index].value = value;
} else {
return error.InvalidKey;
}
}
pub fn iterator(self: *const Self) Iterator {
return Iterator{
.map = self,
.index = 0,
};
}
};
}
test "slotmap" {
const debug = std.debug;
const mem = std.mem;
const assert = debug.assert;
const assertError = debug.assertError;
const data = [][]const u8{
"foo",
"bar",
"cat",
"zag",
};
var map = try SlotMap([]const u8).init(std.debug.global_allocator, 3);
var keys = []Key{Key{ .index = 0, .version = 0 }} ** 3;
var iter = map.iterator();
var idx: usize = 0;
defer map.deinit();
for (data[0..3]) |word, i| {
keys[i] = try map.insert(word);
}
assert(mem.eql(u8, try map.get(keys[0]), data[0]));
assert(mem.eql(u8, try map.get(keys[1]), data[1]));
assert(mem.eql(u8, try map.get(keys[2]), data[2]));
try map.set(keys[0], data[3]);
assert(mem.eql(u8, try map.get(keys[0]), data[3]));
try map.delete(keys[0]);
assertError(map.get(keys[0]), error.InvalidKey);
while (iter.next_value()) |value| : (idx += 1) {
assert(mem.eql(u8, value, data[idx + 1]));
}
idx = 0;
while (iter.next_key()) |key| : (idx += 1) {
assert(mem.eql(u8, try map.get(key), data[idx + 1]));
}
map.clear();
std.debug.warn("\n");
for (keys) |key| {
assertError(map.get(key), error.InvalidKey);
}
while (iter.next_value()) |value| {
assert(iter.index == 0);
}
}
|
src/lib/slotmap.zig
|
const std = @import("std");
const Date = @import("date.zig");
const Arguments = @import("args.zig");
const util = @import("util.zig");
const config = @import("config.zig");
const testing = std.testing;
args: *Arguments,
next_token: ?Token = null,
const Self = @This();
const Token = union(enum) {
month_name: Date.Month,
week_day_name: Date.DayOfWeek,
number: u32,
// Constants
this,
next,
week,
month,
year,
today,
tomorrow,
// If it's a type void, it's a constant
pub const constants = util.unionCreateFieldsWithType(Token, void, {});
};
// Tokens which are the same name as written in input
pub const TokenError = Date.DateError || std.fmt.ParseIntError;
/// Parses what comes after the content
pub fn peek(self: *Self) TokenError!?Token {
var buffer: [config.MAX_LINE]u8 = undefined;
if (self.args.peek()) |arg| {
if (util.isAlpha(arg[0])) {
std.mem.copy(u8, buffer[0..], arg);
util.toLowerStr(buffer[0..arg.len]);
inline for (Token.constants) |c| {
if (util.eqlNoCase(u8, @tagName(c), arg)) {
self.next_token = c;
}
}
if (self.next_token == null) {
if (try Date.nameToMonth(arg)) |m| {
self.next_token = Token { .month_name = m };
} else if (try Date.nameToDayOfWeek(arg)) |d| {
self.next_token = Token { .week_day_name = d };
} else {
return TokenError.InvalidDate;
}
}
} else {
if (arg[arg.len - 1] == ',') {
self.next_token = Token { .number = try std.fmt.parseInt(u32, arg[0..arg.len-1], 10) };
}
else {
self.next_token = Token { .number = try std.fmt.parseInt(u32, arg, 10) };
}
}
} else self.next_token = null;
return self.next_token;
}
/// Parses what comes after the content
pub fn next(self: *Self) TokenError!?Token {
const token = self.next_token orelse try self.peek();
_ = self.args.next();
self.next_token = null;
return token;
}
test "tokenizer.next" {
const raw_arguments = [_][:0]const u8{"jan", "02"};
var args = Arguments {
.args = raw_arguments[0..],
};
var lexer = Self {
.args = &args,
};
const month = try lexer.next();
const number = try lexer.next();
testing.expectEqual(Date.Month.January, month.?.month_name);
testing.expectEqual(@as(u32, 02), number.?.number);
}
|
src/lexer.zig
|
const x86_64 = @import("../index.zig");
const bitjuggle = @import("bitjuggle");
const std = @import("std");
const formatWithoutFields = @import("../common.zig").formatWithoutFields;
/// Extended feature enable mask register
pub const XCr0 = packed struct {
/// Enables x87 FPU
x87: bool,
/// Enables 128-bit (legacy) SSE
/// Must be set to enable AVX and YMM
sse: bool,
/// Enables 256-bit SSE
/// Must be set to enable AVX
avx: bool,
/// When set, MPX instructions are enabled and the bound registers BND0-BND3 can be managed by XSAVE.
bndreg: bool,
/// When set, MPX instructions can be executed and XSAVE can manage the BNDCFGU and BNDSTATUS registers.
bndcsr: bool,
/// If set, AVX-512 instructions can be executed and XSAVE can manage the K0-K7 mask registers.
opmask: bool,
/// If set, AVX-512 instructions can be executed and XSAVE can be used to manage the upper halves of the lower ZMM registers.
zmm_hi256: bool,
/// If set, AVX-512 instructions can be executed and XSAVE can manage the upper ZMM registers.
hi16_zmm: bool,
z_reserved8: bool,
/// When set, PKRU state management is supported by XSAVE/XRSTOR
mpk: bool,
z_reserved10_15: u6,
z_reserved16_47: u32,
z_reserved48_55: u8,
z_reserved56_61: u6,
/// When set the Lightweight Profiling extensions are enabled
lwp: bool,
z_reserved63: bool,
/// Read the current set of XCr0 flags.
pub fn read() XCr0 {
return XCr0.fromU64(readRaw());
}
/// Read the current raw XCr0 value.
fn readRaw() u64 {
var high: u32 = undefined;
var low: u32 = undefined;
asm ("xor %%rcx, %%rcx; xgetbv"
: [low] "={rax}" (low),
[high] "={rdx}" (high),
:
: "rcx"
);
return (@as(u64, high) << 32) | @as(u64, low);
}
/// Write XCr0 flags.
///
/// Preserves the value of reserved fields.
pub fn write(self: XCr0) void {
writeRaw(self.toU64() | (readRaw() & ALL_RESERVED));
}
/// Write raw XCr0 flags.
///
/// Does _not_ preserve any values, including reserved fields.
fn writeRaw(value: u64) void {
var high: u32 = @truncate(u32, value >> 32);
var low: u32 = @truncate(u32, value);
asm volatile ("xor %%ecx, %%ecx; xsetbv"
:
: [low] "{eax}" (low),
[high] "{edx}" (high),
: "ecx"
);
}
const ALL_RESERVED: u64 = blk: {
var flags = std.mem.zeroes(XCr0);
flags.z_reserved8 = true;
flags.z_reserved10_15 = std.math.maxInt(u6);
flags.z_reserved16_47 = std.math.maxInt(u32);
flags.z_reserved48_55 = std.math.maxInt(u8);
flags.z_reserved56_61 = std.math.maxInt(u6);
flags.z_reserved63 = true;
break :blk @bitCast(u64, flags);
};
const ALL_NOT_RESERVED: u64 = ~ALL_RESERVED;
pub fn fromU64(value: u64) XCr0 {
return @bitCast(XCr0, value & ALL_NOT_RESERVED);
}
pub fn toU64(self: XCr0) u64 {
return @bitCast(u64, self) & ALL_NOT_RESERVED;
}
pub fn format(value: XCr0, comptime fmt: []const u8, options: std.fmt.FormatOptions, writer: anytype) !void {
_ = fmt;
return formatWithoutFields(
value,
options,
writer,
&.{ "z_reserved8", "z_reserved10_15", "z_reserved16_47", "z_reserved48_55", "z_reserved56_61", "z_reserved63" },
);
}
test {
try std.testing.expectEqual(@as(usize, 64), @bitSizeOf(XCr0));
try std.testing.expectEqual(@as(usize, 8), @sizeOf(XCr0));
}
comptime {
std.testing.refAllDecls(@This());
}
};
comptime {
std.testing.refAllDecls(@This());
}
|
src/registers/xcontrol.zig
|
// SPDX-License-Identifier: MIT
// This file is part of the Termelot project under the MIT license.
const c = @cImport({
@cInclude("sys/ioctl.h");
@cInclude("sys/time.h");
@cInclude("termios.h");
});
const builtin = @import("builtin");
const std = @import("std");
const Allocator = std.mem.Allocator;
const ArrayList = std.ArrayList;
const stdin = std.io.getStdIn();
const stdout = std.io.getStdOut();
const termelot = @import("../termelot.zig");
usingnamespace termelot.style;
usingnamespace termelot.event;
const BackendName = termelot.backend.BackendName;
const Config = termelot.Config;
const Position = termelot.Position;
const Rune = termelot.Rune;
const Size = termelot.Size;
const SupportedFeatures = termelot.SupportedFeatures;
fn ioctl(fd: std.os.fd_t, request: u32, comptime ResT: type) !ResT {
var res: ResT = undefined;
while (true) {
switch (std.os.errno(std.os.system.ioctl(
fd,
request,
@ptrToInt(&res),
))) {
0 => break,
std.os.EBADF => return error.BadFileDescriptor,
std.os.EFAULT => unreachable, // Bad pointer param
std.os.EINVAL => unreachable, // Bad params
std.os.ENOTTY => return error.RequestDoesNotApply,
std.os.EINTR => continue,
else => |err| return std.os.unexpectedErrno(err),
}
}
return res;
}
fn tcflags(comptime itms: anytype) std.os.tcflag_t {
comptime {
var res: std.os.tcflag_t = 0;
for (itms) |itm| res |= @as(
std.os.tcflag_t,
@field(std.os, @tagName(itm)),
);
return res;
}
}
const VMIN: usize = switch (std.builtin.os.tag) {
.linux => switch (std.builtin.cpu.arch) {
.x86_64 => 6,
.aarch64 => 6,
.mipsel => 4,
else => c.VMIN,
},
else => c.VMIN,
};
const VTIME = switch (std.builtin.os.tag) {
.linux => switch (std.builtin.cpu.arch) {
.x86_64 => 5,
.aarch64 => 5,
.mipsel => 5,
else => c.VMIN,
},
else => c.VMIN,
};
const TermiosType = switch (std.builtin.os.tag) {
.linux => std.os.termios,
else => c.termios,
};
fn makeRaw(current_termios: TermiosType) TermiosType {
switch (std.builtin.os.tag) {
.linux => {
var new_termios = current_termios;
new_termios.iflag &= ~tcflags(.{
.IGNBRK,
.BRKINT,
.PARMRK,
.ISTRIP,
.INLCR,
.IGNCR,
.ICRNL,
.IXON,
});
new_termios.oflag &= ~tcflags(.{.OPOST});
new_termios.lflag &= ~tcflags(.{
.ECHO,
.ECHONL,
.ICANON,
.ISIG,
.IEXTEN,
});
new_termios.cflag &= ~tcflags(.{ .CSIZE, .PARENB });
new_termios.cflag |= @as(std.os.tcflag_t, std.os.CS8);
new_termios.cc[VMIN] = 0;
new_termios.cc[VTIME] = 1;
return new_termios;
},
else => {
var new_termios = current_termios;
c.cfmakeraw(&new_termios);
new_termios.c_cc[c.VMIN] = 0;
new_termios.c_cc[c.VTIME] = 1;
return new_termios;
},
}
}
fn tcgetattr(fd: std.os.fd_t) !TermiosType {
switch (std.builtin.os.tag) {
.linux => return std.os.tcgetattr(fd) catch
return error.BackendError,
else => {
var current_termios: TermiosType = undefined;
if (c.tcgetattr(fd, ¤t_termios) < 0) {
return error.BackendError;
}
return current_termios;
},
}
}
fn tcsetattr(fd: std.os.fd_t, termios: TermiosType) !void {
switch (std.builtin.os.tag) {
.linux => std.os.tcsetattr(fd, std.os.TCSA.NOW, termios) catch
return error.BackendError,
else => if (c.tcsetattr(stdin.handle, c.TCSANOW, &termios) < 0) {
return error.BackendError;
},
}
}
// TODO: Use "/dev/tty" if possible, instead of stdout/stdin
pub const Backend = struct {
orig_termios: switch (std.builtin.os.tag) {
.linux => std.os.termios,
else => c.termios,
},
allocator: *Allocator,
alternate: bool,
cursor_visible: bool,
cursor_position: Position,
input_buffer: ArrayList(u8),
const Self = @This();
/// The tag of a backend is like its identifier. It is used in the build system, and by users
/// for comptime code.
pub const tag = BackendName.termios;
/// Initialize backend
pub fn init(
allocator: *std.mem.Allocator,
config: Config,
) !Backend {
const orig_termios = try tcgetattr(stdin.handle);
_ = config;
var result = Backend{
.orig_termios = orig_termios,
.allocator = allocator,
.alternate = false,
.cursor_visible = false,
.cursor_position = undefined,
.input_buffer = try ArrayList(u8).initCapacity(allocator, 128),
};
try result.setCursorPosition(Position{ .row = 0, .col = 0 });
return result;
}
/// Deinitialize backend
pub fn deinit(self: *Self) void {
tcsetattr(stdin.handle, self.orig_termios) catch {};
self.input_buffer.deinit();
}
/// Retrieve supported features for this backend.
pub fn getSupportedFeatures(self: *Self) !SupportedFeatures {
_ = self;
return SupportedFeatures{
.color_types = .{
.Named16 = true,
.Bit8 = true,
.Bit24 = true,
},
.decorations = Decorations{
.bold = true,
.italic = true,
.underline = true,
.blinking = true,
},
};
}
/// Retrieve raw mode status.
pub fn getRawMode() !bool {
const current_termios = try tcgetattr(stdin.handle);
const new_termios = makeRaw(current_termios);
return std.meta.eql(new_termios, current_termios);
}
/// Enter/exit raw mode.
pub fn setRawMode(self: *Self, enabled: bool) !void {
var current_termios = try tcgetattr(stdin.handle);
if (enabled) {
const new_termios = makeRaw(current_termios);
try tcsetattr(stdin.handle, new_termios);
} else {
// TODO: Check if there is a way to always disable raw mode, even
// if original was in raw mode
try tcsetattr(stdin.handle, self.orig_termios);
}
}
/// Retrieve alternate screen status.
pub fn getAlternateScreen(self: *Self) !bool {
return self.alternate;
}
/// Enter/exit alternate screen.
pub fn setAlternateScreen(self: *Self, enabled: bool) !void {
if (enabled and self.alternate) return;
if (!enabled and !self.alternate) return;
if (enabled) {
_ = try stdout.writer().write("\x1b[?1049h");
self.alternate = true;
} else {
_ = try stdout.writer().write("\x1b[?1049l");
self.alternate = false;
}
}
/// Read `n` bytes from terminal.
pub fn read_up_to(self: *Self, n: i32) !isize {
const prev_len = self.input_buffer.items.len;
self.input_buffer.ensureCapacity(self.input_buffer.capacity + n);
var read_n = 0;
while (read_n <= n) {
var r: isize = 0;
if (read_n < n) {
r = c.read(inout, self.input_buffer.items.ptr + prev_len + read_n, n - read_n);
}
if (r < 0) {
std.debug.assert(c.errno != c.EAGAIN and c.errno != c.EWOULDBLOCK);
return error.Idk; // TODO check man pages
} else if (r > 0) {
read_n += r;
} else {
// TODO: maybe???
self.input_buffer.ensureCapacity(prev_len + read_n);
return read_n;
}
}
unreachable;
}
/// If timeout is less than or equal to zero:
/// Blocking; return next available Event if one is present, and null otherwise.
/// If timeout is greater than zero:
/// Non-blocking; return next available Event if one arises within `timeout` ms.
pub fn pollEvent(self: *Self, timeout: i32) !?Event {
// Describe the timeout with a timeval in seconds and microseconds.
const tv = c.timeval{
.tv_sec = timeout / 1000,
.tv_usec = (timeout - (tv.tv_sec * 1000)) * 1000,
};
var events: c.fd_set = undefined;
_ = events;
_ = tv;
_ = self;
// Attempt to read an event from the input buffer
return null; // TODO: replace
}
/// Set terminal title.
pub fn setTitle(self: *Self, runes: []const Rune) !void {
_ = self;
_ = try stdout.writer().print("\x1b]0;{s}\x07", .{runes});
}
/// Get screen size.
pub fn getScreenSize(self: *Self) !Size {
_ = self;
switch (std.builtin.os.tag) {
.linux => {
const ws = ioctl(
stdout.handle,
std.os.linux.TIOCGWINSZ,
std.os.linux.winsize,
) catch return error.BackendError;
return Size{ .rows = ws.ws_row, .cols = ws.ws_col };
},
.freebsd => {
const ws = ioctl(
stdout.handle,
std.os.freebsd.TIOCGWINSZ,
std.os.freebsd.winsize,
) catch return error.BackendError;
return Size{ .rows = ws.ws_row, .cols = ws.ws_col };
},
.netbsd => {
const ws = ioctl(
stdout.handle,
std.os.netbsd.TIOCGWINSZ,
std.os.netbsd.winsize,
) catch return error.BackendError;
return Size{ .rows = ws.ws_row, .cols = ws.ws_col };
},
else => {
var ws: c.winsize = undefined;
if (c.ioctl(stdout.handle, c.TIOCGWINSZ, &ws) < 0 or
ws.ws_col == 0 or ws.ws_row == 0)
{
return error.BackendError;
}
return Size{
.rows = ws.ws_row,
.cols = ws.ws_col,
};
},
}
}
/// Get cursor position.
pub fn getCursorPosition(self: *Self) !Position {
// Querying for cursor position is unfortunately not supported on
// *many* terminals. Instead, we should keep track of our own
// representation; sadly, this is not robust against external
// (outside of Termelot) interactions with the terminal.
return self.cursor_position;
}
/// Set cursor position.
pub fn setCursorPosition(self: *Self, position: Position) !void {
_ = try stdout.writer().print(
"\x1b[{};{}H",
.{ position.row + 1, position.col + 1 },
);
self.cursor_position = position;
}
/// Get cursor visibility.
pub fn getCursorVisibility(self: *Self) !bool {
return self.cursor_visible;
}
/// Set cursor visibility.
pub fn setCursorVisibility(self: *Self, visible: bool) !void {
if (visible) {
_ = try stdout.writer().write("\x1b[?25h");
self.cursor_visible = true;
} else {
_ = try stdout.writer().write("\x1b[?25l");
self.cursor_visible = false;
}
}
fn writeStyle(style: Style) !void {
const writer = stdout.writer();
_ = try writer.write("\x1b[0m");
if (style.decorations.bold) {
_ = try writer.write("\x1b[1m");
}
if (style.decorations.italic) {
_ = try writer.write("\x1b[3m");
}
if (style.decorations.underline) {
_ = try writer.write("\x1b[4m");
}
if (style.decorations.blinking) {
_ = try writer.write("\x1b[5m");
}
switch (style.fg_color) {
ColorType.Default => {
_ = try writer.write("\x1b[39m");
},
ColorType.Named16 => |v| _ = try writer.write(switch (v) {
ColorNamed16.Black => "\x1b[30m",
ColorNamed16.Red => "\x1b[31m",
ColorNamed16.Green => "\x1b[32m",
ColorNamed16.Yellow => "\x1b[33m",
ColorNamed16.Blue => "\x1b[34m",
ColorNamed16.Magenta => "\x1b[35m",
ColorNamed16.Cyan => "\x1b[36m",
ColorNamed16.White => "\x1b[37m",
ColorNamed16.BrightBlack => "\x1b[90m",
ColorNamed16.BrightRed => "\x1b[91m",
ColorNamed16.BrightGreen => "\x1b[92m",
ColorNamed16.BrightYellow => "\x1b[93m",
ColorNamed16.BrightBlue => "\x1b[94m",
ColorNamed16.BrightMagenta => "\x1b[95m",
ColorNamed16.BrightCyan => "\x1b[96m",
ColorNamed16.BrightWhite => "\x1b[97m",
}),
ColorType.Bit8 => |v| {
_ = try writer.print("\x1b[38;5;{}m", .{v.code});
},
ColorType.Bit24 => |v| {
_ = try writer.print("\x1b[38;2;{};{};{}m", .{
v.red(),
v.green(),
v.blue(),
});
},
}
switch (style.bg_color) {
ColorType.Default => {
_ = try writer.write("\x1b[49m");
},
ColorType.Named16 => |v| _ = try writer.write(switch (v) {
ColorNamed16.Black => "\x1b[40m",
ColorNamed16.Red => "\x1b[41m",
ColorNamed16.Green => "\x1b[42m",
ColorNamed16.Yellow => "\x1b[43m",
ColorNamed16.Blue => "\x1b[44m",
ColorNamed16.Magenta => "\x1b[45m",
ColorNamed16.Cyan => "\x1b[46m",
ColorNamed16.White => "\x1b[47m",
ColorNamed16.BrightBlack => "\x1b[100m",
ColorNamed16.BrightRed => "\x1b[101m",
ColorNamed16.BrightGreen => "\x1b[102m",
ColorNamed16.BrightYellow => "\x1b[103m",
ColorNamed16.BrightBlue => "\x1b[104m",
ColorNamed16.BrightMagenta => "\x1b[105m",
ColorNamed16.BrightCyan => "\x1b[106m",
ColorNamed16.BrightWhite => "\x1b[107m",
}),
ColorType.Bit8 => |v| {
_ = try writer.print("\x1b[48;5;{}m", .{v.code});
},
ColorType.Bit24 => |v| {
_ = try writer.print("\x1b[48;2;{};{};{}m", .{
v.red(),
v.green(),
v.blue(),
});
},
}
}
/// Write styled output to screen at position. Assumed that no newline
/// or carriage return runes are provided.
pub fn write(
self: *Self,
position: Position,
runes: []Rune,
styles: []Style,
) !void {
if (runes.len != styles.len) {
return error.BackendError;
}
if (runes.len == 0) {
return;
}
try self.setCursorPosition(position);
var orig_style_index: usize = 0;
try writeStyle(styles[0]);
for (styles) |style, index| {
if (!std.meta.eql(styles[orig_style_index], style)) {
_ = try stdout.writer().write(runes[orig_style_index..index]);
orig_style_index = index;
try writeStyle(style);
}
}
_ = try stdout.writer().write(runes[orig_style_index..]);
_ = try stdout.writer().write("\x1b[0m");
}
};
|
src/backend/termios.zig
|
const std = @import("std");
const crypto = std.crypto;
const debug = std.debug;
const fmt = std.fmt;
const mem = std.mem;
const c = @import("c.zig");
const global = @import("global.zig");
// Big thank-you to Electronic Frontier Foundation (EFF) for the improved
// wordlist.
//
// https://www.eff.org/deeplinks/2016/07/new-wordlists-random-passphrases
//
// archive page: https://archive.is/1kFCn
// txt file: https://archive.is/gjXfJ
const wordlist = @embedFile("../lib/eff_large_wordlist.txt");
pub const Param = struct {
user_name: []const u8,
site_name: []const u8,
counter: u8,
word_count: u4,
};
const GeneratePassphraseError = error{
SaltNotAllocated,
KeyNotAllocated,
SeedNotAllocated,
OutOfMemory,
};
pub fn generatePassword(allocator: *mem.Allocator, param: Param, password: []const u8, output: []u8) GeneratePassphraseError!void {
const salt = block: {
const salt_length = 64;
var salt = [_]u8{0} ** salt_length;
crypto.Blake3.hash(
fmt.allocPrint(allocator, "{}{}{}", .{
global.id,
global.utf8Length(param.user_name) catch unreachable,
param.user_name,
}) catch return error.SaltNotAllocated,
&salt,
);
break :block salt;
};
var key = block: {
const iterations: u32 = 64;
const memory_usage: u32 = 4096; // 4096 KiB == 4194304 bytes
const parallelism: u32 = 1;
// BLAKE3's keyed hash function can only accept an array the size of
// 32 bytes.
const key_length = 32;
var key = [_]u8{0} ** key_length;
switch (c.argon2id_hash_raw(
iterations,
memory_usage,
parallelism,
password.ptr,
password.len,
&salt,
salt.len,
&key,
key.len,
)) {
c.ARGON2_MEMORY_ALLOCATION_ERROR => return error.KeyNotAllocated,
c.ARGON2_OK => break :block key,
else => unreachable,
}
};
defer mem.secureZero(u8, &key);
var seed = block0: {
const seed_length = 64;
var seed = [_]u8{0} ** seed_length;
const input_hash = block1: {
var input_hash = [_]u8{0} ** seed_length;
crypto.Blake3.hash(
fmt.allocPrint(allocator, "{}{}{}{}", .{
global.id,
global.utf8Length(param.site_name) catch unreachable,
param.site_name,
param.counter,
}) catch return error.SeedNotAllocated,
&input_hash,
);
break :block1 input_hash;
};
var keyed_hash = crypto.Blake3.init_keyed(key);
keyed_hash.update(&input_hash);
keyed_hash.final(&seed);
break :block0 seed;
};
defer mem.secureZero(u8, &seed);
var istanbul = allocator.alloc(u8, param.word_count) catch return error.OutOfMemory;
{
mem.set(u8, istanbul, 5);
var para: usize = seed.len - istanbul.len * 5;
var i: usize = 0;
while (para > 0) : ({
para -= 1;
i += 1;
})
istanbul[i % istanbul.len] += 1;
}
var romania = allocator.alloc([]u8, param.word_count) catch return error.OutOfMemory;
{
var para: usize = 0;
var mexer: usize = 0;
for (romania) |*roman, index| {
mexer += istanbul[index % istanbul.len];
roman.* = seed[para..mexer];
para = mexer;
}
}
var neverland = allocator.alloc([5]u16, param.word_count) catch return error.OutOfMemory;
{
for (neverland) |*never|
mem.set(u16, &never.*, 1);
for (romania) |roman, index| {
var para: usize = roman.len - 5;
var i: usize = 0;
while (para > 0) : ({
para -= 1;
i += 1;
})
neverland[index][i % neverland[index].len] += 1;
}
}
{
for (neverland) |*never, index| {
var para: usize = 0;
var mexer: usize = 0;
for (never) |*ever| {
var javier: u16 = 0;
mexer += ever.*;
for (romania[index][para..mexer]) |roman|
javier += roman;
ever.* = javier;
para = mexer;
}
}
}
{
const number_of_faces_on_a_traditional_die = 6;
for (neverland) |*never| {
for (never) |*ever| {
ever.* %= number_of_faces_on_a_traditional_die;
// Change from 0-5 to 1-6.
ever.* += 1;
// Turn the number into an ASCII representation of said number.
ever.* += 0x30;
}
}
}
{
var output_indicator: usize = 0;
for (neverland) |never, index0| {
var indicator: usize = 0;
for (never) |ever, index1| {
while (true) {
if (wordlist[indicator] != ever) {
while (wordlist[indicator] != '\n') : (indicator += 1) {}
indicator += 1 + index1;
} else {
indicator += 1;
break;
}
}
}
indicator += 1;
while (wordlist[indicator] != '\n') : ({
indicator += 1;
output_indicator += 1;
})
output[output_indicator] = wordlist[indicator];
// If it's processing the final word, avoid putting the space
// character at the end of the string array.
if (index0 == neverland.len - 1) break;
output[output_indicator] = ' ';
output_indicator += 1;
}
}
}
|
src/algorithm.zig
|
impl: Impl = .{},
const std = @import("../std.zig");
const builtin = @import("builtin");
const Condition = @This();
const windows = std.os.windows;
const linux = std.os.linux;
const Mutex = std.Thread.Mutex;
const assert = std.debug.assert;
const testing = std.testing;
pub fn wait(cond: *Condition, mutex: *Mutex) void {
cond.impl.wait(mutex);
}
pub fn timedWait(cond: *Condition, mutex: *Mutex, timeout_ns: u64) error{TimedOut}!void {
try cond.impl.timedWait(mutex, timeout_ns);
}
pub fn signal(cond: *Condition) void {
cond.impl.signal();
}
pub fn broadcast(cond: *Condition) void {
cond.impl.broadcast();
}
const Impl = if (builtin.single_threaded)
SingleThreadedCondition
else if (builtin.os.tag == .windows)
WindowsCondition
else if (std.Thread.use_pthreads)
PthreadCondition
else
AtomicCondition;
pub const SingleThreadedCondition = struct {
pub fn wait(cond: *SingleThreadedCondition, mutex: *Mutex) void {
_ = cond;
_ = mutex;
unreachable; // deadlock detected
}
pub fn timedWait(cond: *SingleThreadedCondition, mutex: *Mutex, timeout_ns: u64) error{TimedOut}!void {
_ = cond;
_ = mutex;
_ = timeout_ns;
std.time.sleep(timeout_ns);
return error.TimedOut;
}
pub fn signal(cond: *SingleThreadedCondition) void {
_ = cond;
}
pub fn broadcast(cond: *SingleThreadedCondition) void {
_ = cond;
}
};
pub const WindowsCondition = struct {
cond: windows.CONDITION_VARIABLE = windows.CONDITION_VARIABLE_INIT,
pub fn wait(cond: *WindowsCondition, mutex: *Mutex) void {
const rc = windows.kernel32.SleepConditionVariableSRW(
&cond.cond,
&mutex.impl.srwlock,
windows.INFINITE,
@as(windows.ULONG, 0),
);
assert(rc != windows.FALSE);
}
pub fn timedWait(cond: *WindowsCondition, mutex: *Mutex, timeout_ns: u64) error{TimedOut}!void {
var timeout_checked = std.math.cast(windows.DWORD, timeout_ns / std.time.ns_per_ms) catch overflow: {
break :overflow std.math.maxInt(windows.DWORD);
};
// Handle the case where timeout is INFINITE, otherwise SleepConditionVariableSRW's time-out never elapses
const timeout_overflowed = timeout_checked == windows.INFINITE;
timeout_checked -= @boolToInt(timeout_overflowed);
const rc = windows.kernel32.SleepConditionVariableSRW(
&cond.cond,
&mutex.impl.srwlock,
timeout_checked,
@as(windows.ULONG, 0),
);
if (rc == windows.FALSE and windows.kernel32.GetLastError() == windows.Win32Error.TIMEOUT) return error.TimedOut;
assert(rc != windows.FALSE);
}
pub fn signal(cond: *WindowsCondition) void {
windows.kernel32.WakeConditionVariable(&cond.cond);
}
pub fn broadcast(cond: *WindowsCondition) void {
windows.kernel32.WakeAllConditionVariable(&cond.cond);
}
};
pub const PthreadCondition = struct {
cond: std.c.pthread_cond_t = .{},
pub fn wait(cond: *PthreadCondition, mutex: *Mutex) void {
const rc = std.c.pthread_cond_wait(&cond.cond, &mutex.impl.pthread_mutex);
assert(rc == .SUCCESS);
}
pub fn timedWait(cond: *PthreadCondition, mutex: *Mutex, timeout_ns: u64) error{TimedOut}!void {
var ts: std.os.timespec = undefined;
std.os.clock_gettime(std.os.CLOCK.REALTIME, &ts) catch unreachable;
ts.tv_sec += @intCast(@TypeOf(ts.tv_sec), timeout_ns / std.time.ns_per_s);
ts.tv_nsec += @intCast(@TypeOf(ts.tv_nsec), timeout_ns % std.time.ns_per_s);
if (ts.tv_nsec >= std.time.ns_per_s) {
ts.tv_sec += 1;
ts.tv_nsec -= std.time.ns_per_s;
}
const rc = std.c.pthread_cond_timedwait(&cond.cond, &mutex.impl.pthread_mutex, &ts);
return switch (rc) {
.SUCCESS => {},
.TIMEDOUT => error.TimedOut,
else => unreachable,
};
}
pub fn signal(cond: *PthreadCondition) void {
const rc = std.c.pthread_cond_signal(&cond.cond);
assert(rc == .SUCCESS);
}
pub fn broadcast(cond: *PthreadCondition) void {
const rc = std.c.pthread_cond_broadcast(&cond.cond);
assert(rc == .SUCCESS);
}
};
pub const AtomicCondition = struct {
pending: bool = false,
queue_mutex: Mutex = .{},
queue_list: QueueList = .{},
pub const QueueList = std.SinglyLinkedList(QueueItem);
pub const QueueItem = struct {
futex: i32 = 0,
dequeued: bool = false,
fn wait(cond: *@This()) void {
while (@atomicLoad(i32, &cond.futex, .Acquire) == 0) {
switch (builtin.os.tag) {
.linux => {
switch (linux.getErrno(linux.futex_wait(
&cond.futex,
linux.FUTEX.PRIVATE_FLAG | linux.FUTEX.WAIT,
0,
null,
))) {
.SUCCESS => {},
.INTR => {},
.AGAIN => {},
else => unreachable,
}
},
else => std.atomic.spinLoopHint(),
}
}
}
pub fn timedWait(cond: *@This(), timeout_ns: u64) error{TimedOut}!void {
const start_time = std.time.nanoTimestamp();
while (@atomicLoad(i32, &cond.futex, .Acquire) == 0) {
switch (builtin.os.tag) {
.linux => {
var ts: std.os.timespec = undefined;
ts.tv_sec = @intCast(@TypeOf(ts.tv_sec), timeout_ns / std.time.ns_per_s);
ts.tv_nsec = @intCast(@TypeOf(ts.tv_nsec), timeout_ns % std.time.ns_per_s);
switch (linux.getErrno(linux.futex_wait(
&cond.futex,
linux.FUTEX.PRIVATE_FLAG | linux.FUTEX.WAIT,
0,
&ts,
))) {
.SUCCESS => {},
.INTR => {},
.AGAIN => {},
.TIMEDOUT => return error.TimedOut,
.INVAL => {}, // possibly timeout overflow
.FAULT => unreachable,
else => unreachable,
}
},
else => {
if (std.time.nanoTimestamp() - start_time >= timeout_ns) {
return error.TimedOut;
}
std.atomic.spinLoopHint();
},
}
}
}
fn notify(cond: *@This()) void {
@atomicStore(i32, &cond.futex, 1, .Release);
switch (builtin.os.tag) {
.linux => {
switch (linux.getErrno(linux.futex_wake(
&cond.futex,
linux.FUTEX.PRIVATE_FLAG | linux.FUTEX.WAKE,
1,
))) {
.SUCCESS => {},
.FAULT => {},
else => unreachable,
}
},
else => {},
}
}
};
pub fn wait(cond: *AtomicCondition, mutex: *Mutex) void {
var waiter = QueueList.Node{ .data = .{} };
{
cond.queue_mutex.lock();
defer cond.queue_mutex.unlock();
cond.queue_list.prepend(&waiter);
@atomicStore(bool, &cond.pending, true, .SeqCst);
}
mutex.unlock();
waiter.data.wait();
mutex.lock();
}
pub fn timedWait(cond: *AtomicCondition, mutex: *Mutex, timeout_ns: u64) error{TimedOut}!void {
var waiter = QueueList.Node{ .data = .{} };
{
cond.queue_mutex.lock();
defer cond.queue_mutex.unlock();
cond.queue_list.prepend(&waiter);
@atomicStore(bool, &cond.pending, true, .SeqCst);
}
var timed_out = false;
mutex.unlock();
defer mutex.lock();
waiter.data.timedWait(timeout_ns) catch |err| switch (err) {
error.TimedOut => {
defer if (!timed_out) {
waiter.data.wait();
};
cond.queue_mutex.lock();
defer cond.queue_mutex.unlock();
if (!waiter.data.dequeued) {
timed_out = true;
cond.queue_list.remove(&waiter);
}
},
else => unreachable,
};
if (timed_out) {
return error.TimedOut;
}
}
pub fn signal(cond: *AtomicCondition) void {
if (@atomicLoad(bool, &cond.pending, .SeqCst) == false)
return;
const maybe_waiter = blk: {
cond.queue_mutex.lock();
defer cond.queue_mutex.unlock();
const maybe_waiter = cond.queue_list.popFirst();
if (maybe_waiter) |waiter| {
waiter.data.dequeued = true;
}
@atomicStore(bool, &cond.pending, cond.queue_list.first != null, .SeqCst);
break :blk maybe_waiter;
};
if (maybe_waiter) |waiter| {
waiter.data.notify();
}
}
pub fn broadcast(cond: *AtomicCondition) void {
if (@atomicLoad(bool, &cond.pending, .SeqCst) == false)
return;
@atomicStore(bool, &cond.pending, false, .SeqCst);
var waiters = blk: {
cond.queue_mutex.lock();
defer cond.queue_mutex.unlock();
const waiters = cond.queue_list;
var it = waiters.first;
while (it) |node| : (it = node.next) {
node.data.dequeued = true;
}
cond.queue_list = .{};
break :blk waiters;
};
while (waiters.popFirst()) |waiter| {
waiter.data.notify();
}
}
};
test "Thread.Condition" {
if (builtin.single_threaded) {
return error.SkipZigTest;
}
const TestContext = struct {
cond: *Condition,
cond_main: *Condition,
mutex: *Mutex,
n: *i32,
fn worker(ctx: *@This()) void {
ctx.mutex.lock();
ctx.n.* += 1;
ctx.cond_main.signal();
ctx.cond.wait(ctx.mutex);
ctx.n.* -= 1;
ctx.cond_main.signal();
ctx.mutex.unlock();
}
};
const num_threads = 3;
var threads: [num_threads]std.Thread = undefined;
var cond = Condition{};
var cond_main = Condition{};
var mut = Mutex{};
var n: i32 = 0;
var ctx = TestContext{ .cond = &cond, .cond_main = &cond_main, .mutex = &mut, .n = &n };
mut.lock();
for (threads) |*t| t.* = try std.Thread.spawn(.{}, TestContext.worker, .{&ctx});
cond_main.wait(&mut);
while (n < num_threads) cond_main.wait(&mut);
cond.signal();
cond_main.wait(&mut);
try testing.expect(n == (num_threads - 1));
cond.broadcast();
while (n > 0) cond_main.wait(&mut);
try testing.expect(n == 0);
for (threads) |t| t.join();
}
test "Thread.Condition.timedWait" {
if (builtin.single_threaded) {
return error.SkipZigTest;
}
var cond = Condition{};
var mut = Mutex{};
// Expect a timeout, as the condition variable is never signaled
{
mut.lock();
defer mut.unlock();
try testing.expectError(error.TimedOut, cond.timedWait(&mut, 10 * std.time.ns_per_ms));
}
// Expect a signal before timeout
{
const TestContext = struct {
cond: *Condition,
mutex: *Mutex,
n: *u32,
fn worker(ctx: *@This()) void {
ctx.mutex.lock();
defer ctx.mutex.unlock();
ctx.n.* = 1;
ctx.cond.signal();
}
};
var n: u32 = 0;
var ctx = TestContext{ .cond = &cond, .mutex = &mut, .n = &n };
mut.lock();
var thread = try std.Thread.spawn(.{}, TestContext.worker, .{&ctx});
// Looped check to handle spurious wakeups
while (n != 1) try cond.timedWait(&mut, 500 * std.time.ns_per_ms);
mut.unlock();
try testing.expect(n == 1);
thread.join();
}
}
|
lib/std/Thread/Condition.zig
|
const std = @import("std");
const File = std.fs.File;
pub const ESC = "\x1b";
pub const CSI = ESC ++ "[";
pub var stdout: File = undefined;
pub var stdout_buffer: std.io.BufferedWriter(2048, File.Writer) = undefined;
pub var stderr: File = undefined;
pub fn init() void {
stdout = std.io.getStdOut();
stdout_buffer = @TypeOf(stdout_buffer){ .unbuffered_writer = stdout.writer() };
stderr = std.io.getStdErr();
}
pub fn deinit() void {
flush();
}
pub fn print(comptime format: []const u8, args: anytype) void {
inline for (format) |c|
if (c == '\n')
flush();
stdout_buffer.writer().print(format, args) catch return;
}
pub fn println(comptime format: []const u8, args: anytype) void {
print(format ++ "\n", args);
}
pub fn flush() void {
stdout_buffer.flush() catch return;
}
pub fn eprint(comptime format: []const u8, args: anytype) void {
stderr.writer().print(format, args) catch return;
}
pub fn eprintln(comptime format: []const u8, args: anytype) void {
eprint(format ++ "\n", args);
}
pub fn clearLine() void {
print(CSI ++ "2K", .{});
}
pub fn printAttr(comptime format: []const u8, args: anytype, attr: Attr) void {
print("{}", .{attr});
print(format, args);
print("{}", .{Attr{ .reset = true }});
}
pub fn printlnAttr(comptime format: []const u8, args: anytype, attr: Attr) void {
printAttr(format, args, attr);
println("", .{});
}
/// Ansi text attributes
pub const Attr = struct {
col: ?Color = null,
bold: bool = false,
reset: bool = false,
pub const Color = enum(u3) {
black,
red,
green,
yellow,
blue,
magenta,
cyan,
white,
};
pub fn format(self: Attr, comptime fmt: []const u8, options: std.fmt.FormatOptions, writer: anytype) !void {
_ = options;
_ = fmt;
try writer.writeAll("\x1b[");
if (self.reset) {
try writer.writeAll("0m");
return;
}
if (self.col) |col| {
switch (col) {
.black => try writer.writeAll("30"),
.red => try writer.writeAll("31"),
.green => try writer.writeAll("32"),
.yellow => try writer.writeAll("33"),
.blue => try writer.writeAll("34"),
.magenta => try writer.writeAll("35"),
.cyan => try writer.writeAll("36"),
.white => try writer.writeAll("37"),
}
}
if (self.bold)
try writer.writeAll(";1");
try writer.writeAll("m");
}
};
|
fexc/src/term.zig
|
const std = @import("std");
const Allocator = std.mem.Allocator;
const assert = std.debug.assert;
const print = std.debug.print;
const parseInt = @import("parseInt.zig").parse;
const passports = @embedFile("input04.txt");
fn isSpace(string: []const u8) bool {
for (string) |c| {
if (!std.ascii.isSpace(c))
return false;
}
return true;
}
const Field = struct {
key: []const u8,
value: []const u8,
};
fn isBetween(n: u32, min: u32, max: u32) bool {
return n >= min and n <= max;
}
fn validateYear(string: []const u8, min: u32, max: u32) !bool {
if (string.len != 4)
return false;
for (string) |char|
if (!std.ascii.isDigit(char))
return false;
const n = try parseInt(u32, string, 10);
return isBetween(n, min, max);
}
const Passport = struct {
byr: ?[]const u8,
iyr: ?[]const u8,
eyr: ?[]const u8,
hgt: ?[]const u8,
hcl: ?[]const u8,
ecl: ?[]const u8,
pid: ?[]const u8,
cid: ?[]const u8,
pub fn hasAllRequiredFields(p: *const Passport) bool {
return p.byr != null and p.iyr != null and p.eyr != null and p.hgt != null and p.hcl != null and p.ecl != null and p.pid != null;
}
pub fn validateBirthdayYear(p: *const Passport) !bool {
return try validateYear(p.byr.?, 1920, 2002);
}
pub fn validateIssueYear(p: *const Passport) !bool {
return try validateYear(p.iyr.?, 2010, 2020);
}
pub fn validateExpirationYear(p: *const Passport) !bool {
return try validateYear(p.eyr.?, 2020, 2030);
}
pub fn validateHeight(p: *const Passport) !bool {
const height = p.hgt.?;
if (height.len > 5) //we support '\d\d\dcm' or '\d\din'
return false;
if (std.mem.endsWith(u8, height, "cm")) {
return (std.mem.order(u8, height, "149cm") == .gt) and (std.mem.order(u8, height, "194cm") == .lt);
} else if (std.mem.endsWith(u8, height, "in")) {
return (std.mem.order(u8, height, "58in") == .gt) and (std.mem.order(u8, height, "77in") == .lt);
} else return false;
return true;
}
pub fn validateHairColor(p: *const Passport) !bool {
const hairColor = p.hcl.?;
if (hairColor.len != 7)
return false;
for (hairColor[1..]) |char| {
switch (char) {
'0'...'9' => continue,
'a'...'f' => continue,
else => return false,
}
}
return true;
}
pub fn validateEyeColor(p: *const Passport) !bool {
const eyeColor = p.ecl.?;
const validColors = [_][]const u8{ "amb", "blu", "brn", "gry", "grn", "hzl", "oth" };
inline for (validColors) |color| {
if (std.mem.eql(u8, eyeColor, color))
return true;
}
return false;
}
pub fn validatePassportId(p: *const Passport) !bool {
const pid = p.pid.?;
if (pid.len != 9)
return false;
for (pid) |char| {
if (!std.ascii.isDigit(char))
return false;
}
return true;
}
pub fn isValid(p: *const Passport) !bool {
if (!p.hasAllRequiredFields()) {
return false;
}
if (!try p.validateBirthdayYear()) {
return false;
}
if (!try p.validateIssueYear()) {
return false;
}
if (!try p.validateExpirationYear()) {
return false;
}
if (!try p.validateHeight()) {
return false;
}
if (!try p.validateHairColor()) {
return false;
}
if (!try p.validateEyeColor()) {
return false;
}
if (!try p.validatePassportId()) {
return false;
}
return true;
}
};
fn stringEqual(stringA: []const u8, stringB: []const u8) bool {
return std.mem.eql(u8, stringA, stringB);
}
fn setField(passport: *Passport, field: Field) void {
if (stringEqual(field.key, "byr")) {
passport.byr = field.value;
} else if (stringEqual(field.key, "iyr")) {
passport.iyr = field.value;
} else if (stringEqual(field.key, "eyr")) {
passport.eyr = field.value;
} else if (stringEqual(field.key, "hgt")) {
passport.hgt = field.value;
} else if (stringEqual(field.key, "hcl")) {
passport.hcl = field.value;
} else if (stringEqual(field.key, "ecl")) {
passport.ecl = field.value;
} else if (stringEqual(field.key, "pid")) {
passport.pid = field.value;
} else if (stringEqual(field.key, "cid")) {
passport.cid = field.value;
}
}
fn parseField(field: []const u8) Field {
var tokens = std.mem.tokenize(field, ":");
var fieldKey = tokens.next().?;
var fieldValue = tokens.next().?;
return Field{ .key = fieldKey, .value = fieldValue };
}
fn parseLine(passport: *Passport, line: []const u8) void {
var fields = std.mem.tokenize(line, " \n\r");
while (fields.next()) |field| {
var parsedField = parseField(field);
setField(passport, parsedField);
}
}
fn parseAllPassports(allocator: *Allocator) !std.ArrayList(Passport) {
var passportList = std.ArrayList(Passport).init(allocator);
var iterator = std.mem.split(passports, "\n");
var passport: Passport = undefined;
while (iterator.next()) |line| {
if (isSpace(line)) {
try passportList.append(passport);
passport = undefined;
} else {
parseLine(&passport, line);
}
}
try passportList.append(passport);
return passportList;
}
fn part1() !void {
print("Part1:\n", .{});
var gpa = std.heap.GeneralPurposeAllocator(.{}){};
defer _ = gpa.deinit();
var passportList = try parseAllPassports(&gpa.allocator);
defer passportList.deinit();
var validPassports: u32 = 0;
for (passportList.items) |passport| {
if (passport.hasAllRequiredFields())
validPassports += 1;
}
print("Valid passports: {}\n", .{validPassports});
}
fn part2() !void {
print("\nPart2:\n", .{});
var gpa = std.heap.GeneralPurposeAllocator(.{}){};
defer _ = gpa.deinit();
var passportList = try parseAllPassports(&gpa.allocator);
defer passportList.deinit();
var validPassports: u32 = 0;
for (passportList.items) |passport| {
if (try passport.isValid()) {
validPassports += 1;
}
}
print("Valid passports: {}\n", .{validPassports});
}
pub fn main() !void {
try part1();
try part2();
}
|
src/day04.zig
|
const std = @import("std");
const Allocator = std.mem.Allocator;
const assert = std.debug.assert;
const fs = std.fs;
const math = std.math;
const draw = @import("pixel_draw.zig");
const Texture = draw.Texture;
usingnamespace draw.vector_math;
pub const Block = struct {
id: u16 = 0,
texture: draw.Texture,
};
pub const Chunk = struct {
block_data: [size * size * height]u16,
light_data: [size * size * height]u8,
pub const size = 16;
pub const height = 256;
pub inline fn setBlockData(chunk: *Chunk, x: u32, y: u32, z: u32, value: u16) void {
chunk.block_data[x + z * size + y * size * size] = value;
}
pub inline fn setLightData(chunk: *Chunk, x: u32, y: u32, z: u32, value: u8) void {
chunk.light_data[x + z * size + y * size * size] = value;
}
pub inline fn getBlockData(chunk: *Chunk, x: u32, y: u32, z: u32) u16 {
return chunk.block_data[x + z * size + y * size * size];
}
pub inline fn getLightData(chunk: *Chunk, x: u32, y: u32, z: u32) u8 {
return chunk.light_data[x + z * size + y * size * size];
}
pub inline fn posFromI(i: usize, x: *u32, y: *u32, z: *u32) void {
x.* = @intCast(u32, i % size);
z.* = @intCast(u32, (i / size) % size);
y.* = @intCast(u32, i / (size * size));
}
pub fn init() Chunk {
var result: Chunk = undefined;
for (result.block_data) |*it| {
it.* = 0;
}
for (result.light_data) |*it| {
it.* = 255;
}
var z: u32 = 0;
while (z < size) : (z += 1) {
var x: u32 = 0;
while (x < size) : (x += 1) {
var y: u32 = x / 8 + z / 4;
result.setBlockData(x, y, z, 1);
}
}
return result;
}
};
var block_list: [256]Block = undefined;
pub fn initBlockList(al: *Allocator) !void {
block_list[0].id = 0;
block_list[0].texture = try draw.textureFromTgaData(al, @embedFile("../assets/potato.tga"));
var i: u16 = 1;
while (i < block_list.len) : (i += 1) {
block_list[i].id = i;
block_list[i].texture = block_list[0].texture;
}
}
|
src/voxel.zig
|
pub const CONSOLE_TEXTMODE_BUFFER = @as(u32, 1);
pub const ATTACH_PARENT_PROCESS = @as(u32, 4294967295);
pub const CTRL_C_EVENT = @as(u32, 0);
pub const CTRL_BREAK_EVENT = @as(u32, 1);
pub const CTRL_CLOSE_EVENT = @as(u32, 2);
pub const CTRL_LOGOFF_EVENT = @as(u32, 5);
pub const CTRL_SHUTDOWN_EVENT = @as(u32, 6);
pub const PSEUDOCONSOLE_INHERIT_CURSOR = @as(u32, 1);
pub const FOREGROUND_BLUE = @as(u32, 1);
pub const FOREGROUND_GREEN = @as(u32, 2);
pub const FOREGROUND_RED = @as(u32, 4);
pub const FOREGROUND_INTENSITY = @as(u32, 8);
pub const BACKGROUND_BLUE = @as(u32, 16);
pub const BACKGROUND_GREEN = @as(u32, 32);
pub const BACKGROUND_RED = @as(u32, 64);
pub const BACKGROUND_INTENSITY = @as(u32, 128);
pub const COMMON_LVB_LEADING_BYTE = @as(u32, 256);
pub const COMMON_LVB_TRAILING_BYTE = @as(u32, 512);
pub const COMMON_LVB_GRID_HORIZONTAL = @as(u32, 1024);
pub const COMMON_LVB_GRID_LVERTICAL = @as(u32, 2048);
pub const COMMON_LVB_GRID_RVERTICAL = @as(u32, 4096);
pub const COMMON_LVB_REVERSE_VIDEO = @as(u32, 16384);
pub const COMMON_LVB_UNDERSCORE = @as(u32, 32768);
pub const COMMON_LVB_SBCSDBCS = @as(u32, 768);
pub const CONSOLE_NO_SELECTION = @as(u32, 0);
pub const CONSOLE_SELECTION_IN_PROGRESS = @as(u32, 1);
pub const CONSOLE_SELECTION_NOT_EMPTY = @as(u32, 2);
pub const CONSOLE_MOUSE_SELECTION = @as(u32, 4);
pub const CONSOLE_MOUSE_DOWN = @as(u32, 8);
pub const HISTORY_NO_DUP_FLAG = @as(u32, 1);
pub const CONSOLE_FULLSCREEN = @as(u32, 1);
pub const CONSOLE_FULLSCREEN_HARDWARE = @as(u32, 2);
pub const CONSOLE_FULLSCREEN_MODE = @as(u32, 1);
pub const CONSOLE_WINDOWED_MODE = @as(u32, 2);
pub const RIGHT_ALT_PRESSED = @as(u32, 1);
pub const LEFT_ALT_PRESSED = @as(u32, 2);
pub const RIGHT_CTRL_PRESSED = @as(u32, 4);
pub const LEFT_CTRL_PRESSED = @as(u32, 8);
pub const SHIFT_PRESSED = @as(u32, 16);
pub const NUMLOCK_ON = @as(u32, 32);
pub const SCROLLLOCK_ON = @as(u32, 64);
pub const CAPSLOCK_ON = @as(u32, 128);
pub const ENHANCED_KEY = @as(u32, 256);
pub const NLS_DBCSCHAR = @as(u32, 65536);
pub const NLS_ALPHANUMERIC = @as(u32, 0);
pub const NLS_KATAKANA = @as(u32, 131072);
pub const NLS_HIRAGANA = @as(u32, 262144);
pub const NLS_ROMAN = @as(u32, 4194304);
pub const NLS_IME_CONVERSION = @as(u32, 8388608);
pub const ALTNUMPAD_BIT = @as(u32, 67108864);
pub const NLS_IME_DISABLE = @as(u32, 536870912);
pub const FROM_LEFT_1ST_BUTTON_PRESSED = @as(u32, 1);
pub const RIGHTMOST_BUTTON_PRESSED = @as(u32, 2);
pub const FROM_LEFT_2ND_BUTTON_PRESSED = @as(u32, 4);
pub const FROM_LEFT_3RD_BUTTON_PRESSED = @as(u32, 8);
pub const FROM_LEFT_4TH_BUTTON_PRESSED = @as(u32, 16);
pub const MOUSE_MOVED = @as(u32, 1);
pub const DOUBLE_CLICK = @as(u32, 2);
pub const MOUSE_WHEELED = @as(u32, 4);
pub const MOUSE_HWHEELED = @as(u32, 8);
pub const KEY_EVENT = @as(u32, 1);
pub const MOUSE_EVENT = @as(u32, 2);
pub const WINDOW_BUFFER_SIZE_EVENT = @as(u32, 4);
pub const MENU_EVENT = @as(u32, 8);
pub const FOCUS_EVENT = @as(u32, 16);
//--------------------------------------------------------------------------------
// Section: Types (21)
//--------------------------------------------------------------------------------
pub const CONSOLE_MODE = enum(u32) {
ENABLE_PROCESSED_INPUT = 1,
ENABLE_LINE_INPUT = 2,
ENABLE_ECHO_INPUT = 4,
ENABLE_WINDOW_INPUT = 8,
ENABLE_MOUSE_INPUT = 16,
ENABLE_INSERT_MODE = 32,
ENABLE_QUICK_EDIT_MODE = 64,
ENABLE_EXTENDED_FLAGS = 128,
ENABLE_AUTO_POSITION = 256,
ENABLE_VIRTUAL_TERMINAL_INPUT = 512,
// ENABLE_PROCESSED_OUTPUT = 1, this enum value conflicts with ENABLE_PROCESSED_INPUT
// ENABLE_WRAP_AT_EOL_OUTPUT = 2, this enum value conflicts with ENABLE_LINE_INPUT
// ENABLE_VIRTUAL_TERMINAL_PROCESSING = 4, this enum value conflicts with ENABLE_ECHO_INPUT
// DISABLE_NEWLINE_AUTO_RETURN = 8, this enum value conflicts with ENABLE_WINDOW_INPUT
// ENABLE_LVB_GRID_WORLDWIDE = 16, this enum value conflicts with ENABLE_MOUSE_INPUT
_,
pub fn initFlags(o: struct {
ENABLE_PROCESSED_INPUT: u1 = 0,
ENABLE_LINE_INPUT: u1 = 0,
ENABLE_ECHO_INPUT: u1 = 0,
ENABLE_WINDOW_INPUT: u1 = 0,
ENABLE_MOUSE_INPUT: u1 = 0,
ENABLE_INSERT_MODE: u1 = 0,
ENABLE_QUICK_EDIT_MODE: u1 = 0,
ENABLE_EXTENDED_FLAGS: u1 = 0,
ENABLE_AUTO_POSITION: u1 = 0,
ENABLE_VIRTUAL_TERMINAL_INPUT: u1 = 0,
}) CONSOLE_MODE {
return @intToEnum(CONSOLE_MODE,
(if (o.ENABLE_PROCESSED_INPUT == 1) @enumToInt(CONSOLE_MODE.ENABLE_PROCESSED_INPUT) else 0)
| (if (o.ENABLE_LINE_INPUT == 1) @enumToInt(CONSOLE_MODE.ENABLE_LINE_INPUT) else 0)
| (if (o.ENABLE_ECHO_INPUT == 1) @enumToInt(CONSOLE_MODE.ENABLE_ECHO_INPUT) else 0)
| (if (o.ENABLE_WINDOW_INPUT == 1) @enumToInt(CONSOLE_MODE.ENABLE_WINDOW_INPUT) else 0)
| (if (o.ENABLE_MOUSE_INPUT == 1) @enumToInt(CONSOLE_MODE.ENABLE_MOUSE_INPUT) else 0)
| (if (o.ENABLE_INSERT_MODE == 1) @enumToInt(CONSOLE_MODE.ENABLE_INSERT_MODE) else 0)
| (if (o.ENABLE_QUICK_EDIT_MODE == 1) @enumToInt(CONSOLE_MODE.ENABLE_QUICK_EDIT_MODE) else 0)
| (if (o.ENABLE_EXTENDED_FLAGS == 1) @enumToInt(CONSOLE_MODE.ENABLE_EXTENDED_FLAGS) else 0)
| (if (o.ENABLE_AUTO_POSITION == 1) @enumToInt(CONSOLE_MODE.ENABLE_AUTO_POSITION) else 0)
| (if (o.ENABLE_VIRTUAL_TERMINAL_INPUT == 1) @enumToInt(CONSOLE_MODE.ENABLE_VIRTUAL_TERMINAL_INPUT) else 0)
);
}
};
pub const ENABLE_PROCESSED_INPUT = CONSOLE_MODE.ENABLE_PROCESSED_INPUT;
pub const ENABLE_LINE_INPUT = CONSOLE_MODE.ENABLE_LINE_INPUT;
pub const ENABLE_ECHO_INPUT = CONSOLE_MODE.ENABLE_ECHO_INPUT;
pub const ENABLE_WINDOW_INPUT = CONSOLE_MODE.ENABLE_WINDOW_INPUT;
pub const ENABLE_MOUSE_INPUT = CONSOLE_MODE.ENABLE_MOUSE_INPUT;
pub const ENABLE_INSERT_MODE = CONSOLE_MODE.ENABLE_INSERT_MODE;
pub const ENABLE_QUICK_EDIT_MODE = CONSOLE_MODE.ENABLE_QUICK_EDIT_MODE;
pub const ENABLE_EXTENDED_FLAGS = CONSOLE_MODE.ENABLE_EXTENDED_FLAGS;
pub const ENABLE_AUTO_POSITION = CONSOLE_MODE.ENABLE_AUTO_POSITION;
pub const ENABLE_VIRTUAL_TERMINAL_INPUT = CONSOLE_MODE.ENABLE_VIRTUAL_TERMINAL_INPUT;
pub const ENABLE_PROCESSED_OUTPUT = CONSOLE_MODE.ENABLE_PROCESSED_INPUT;
pub const ENABLE_WRAP_AT_EOL_OUTPUT = CONSOLE_MODE.ENABLE_LINE_INPUT;
pub const ENABLE_VIRTUAL_TERMINAL_PROCESSING = CONSOLE_MODE.ENABLE_ECHO_INPUT;
pub const DISABLE_NEWLINE_AUTO_RETURN = CONSOLE_MODE.ENABLE_WINDOW_INPUT;
pub const ENABLE_LVB_GRID_WORLDWIDE = CONSOLE_MODE.ENABLE_MOUSE_INPUT;
pub const STD_HANDLE = enum(u32) {
INPUT_HANDLE = 4294967286,
OUTPUT_HANDLE = 4294967285,
ERROR_HANDLE = 4294967284,
};
pub const STD_INPUT_HANDLE = STD_HANDLE.INPUT_HANDLE;
pub const STD_OUTPUT_HANDLE = STD_HANDLE.OUTPUT_HANDLE;
pub const STD_ERROR_HANDLE = STD_HANDLE.ERROR_HANDLE;
// TODO: this type has a FreeFunc 'ClosePseudoConsole', what can Zig do with this information?
pub const HPCON = *opaque{};
pub const COORD = extern struct {
X: i16,
Y: i16,
};
pub const SMALL_RECT = extern struct {
Left: i16,
Top: i16,
Right: i16,
Bottom: i16,
};
pub const KEY_EVENT_RECORD = extern struct {
bKeyDown: BOOL,
wRepeatCount: u16,
wVirtualKeyCode: u16,
wVirtualScanCode: u16,
uChar: extern union {
UnicodeChar: u16,
AsciiChar: CHAR,
},
dwControlKeyState: u32,
};
pub const MOUSE_EVENT_RECORD = extern struct {
dwMousePosition: COORD,
dwButtonState: u32,
dwControlKeyState: u32,
dwEventFlags: u32,
};
pub const WINDOW_BUFFER_SIZE_RECORD = extern struct {
dwSize: COORD,
};
pub const MENU_EVENT_RECORD = extern struct {
dwCommandId: u32,
};
pub const FOCUS_EVENT_RECORD = extern struct {
bSetFocus: BOOL,
};
pub const INPUT_RECORD = extern struct {
EventType: u16,
Event: extern union {
KeyEvent: KEY_EVENT_RECORD,
MouseEvent: MOUSE_EVENT_RECORD,
WindowBufferSizeEvent: WINDOW_BUFFER_SIZE_RECORD,
MenuEvent: MENU_EVENT_RECORD,
FocusEvent: FOCUS_EVENT_RECORD,
},
};
pub const CHAR_INFO = extern struct {
Char: extern union {
UnicodeChar: u16,
AsciiChar: CHAR,
},
Attributes: u16,
};
pub const CONSOLE_FONT_INFO = extern struct {
nFont: u32,
dwFontSize: COORD,
};
pub const CONSOLE_READCONSOLE_CONTROL = extern struct {
nLength: u32,
nInitialChars: u32,
dwCtrlWakeupMask: u32,
dwControlKeyState: u32,
};
pub const PHANDLER_ROUTINE = fn(
CtrlType: u32,
) callconv(@import("std").os.windows.WINAPI) BOOL;
pub const CONSOLE_CURSOR_INFO = extern struct {
dwSize: u32,
bVisible: BOOL,
};
pub const CONSOLE_SCREEN_BUFFER_INFO = extern struct {
dwSize: COORD,
dwCursorPosition: COORD,
wAttributes: u16,
srWindow: SMALL_RECT,
dwMaximumWindowSize: COORD,
};
pub const CONSOLE_SCREEN_BUFFER_INFOEX = extern struct {
cbSize: u32,
dwSize: COORD,
dwCursorPosition: COORD,
wAttributes: u16,
srWindow: SMALL_RECT,
dwMaximumWindowSize: COORD,
wPopupAttributes: u16,
bFullscreenSupported: BOOL,
ColorTable: [16]u32,
};
pub const CONSOLE_FONT_INFOEX = extern struct {
cbSize: u32,
nFont: u32,
dwFontSize: COORD,
FontFamily: u32,
FontWeight: u32,
FaceName: [32]u16,
};
pub const CONSOLE_SELECTION_INFO = extern struct {
dwFlags: u32,
dwSelectionAnchor: COORD,
srSelection: SMALL_RECT,
};
pub const CONSOLE_HISTORY_INFO = extern struct {
cbSize: u32,
HistoryBufferSize: u32,
NumberOfHistoryBuffers: u32,
dwFlags: u32,
};
//--------------------------------------------------------------------------------
// Section: Functions (94)
//--------------------------------------------------------------------------------
pub extern "KERNEL32" fn AllocConsole(
) callconv(@import("std").os.windows.WINAPI) BOOL;
pub extern "KERNEL32" fn FreeConsole(
) callconv(@import("std").os.windows.WINAPI) BOOL;
pub extern "KERNEL32" fn AttachConsole(
dwProcessId: u32,
) callconv(@import("std").os.windows.WINAPI) BOOL;
pub extern "KERNEL32" fn GetConsoleCP(
) callconv(@import("std").os.windows.WINAPI) u32;
pub extern "KERNEL32" fn GetConsoleOutputCP(
) callconv(@import("std").os.windows.WINAPI) u32;
pub extern "KERNEL32" fn GetConsoleMode(
hConsoleHandle: ?HANDLE,
lpMode: ?*CONSOLE_MODE,
) callconv(@import("std").os.windows.WINAPI) BOOL;
pub extern "KERNEL32" fn SetConsoleMode(
hConsoleHandle: ?HANDLE,
dwMode: CONSOLE_MODE,
) callconv(@import("std").os.windows.WINAPI) BOOL;
pub extern "KERNEL32" fn GetNumberOfConsoleInputEvents(
hConsoleInput: ?HANDLE,
lpNumberOfEvents: ?*u32,
) callconv(@import("std").os.windows.WINAPI) BOOL;
pub extern "KERNEL32" fn ReadConsoleInputA(
hConsoleInput: ?HANDLE,
lpBuffer: [*]INPUT_RECORD,
nLength: u32,
lpNumberOfEventsRead: ?*u32,
) callconv(@import("std").os.windows.WINAPI) BOOL;
pub extern "KERNEL32" fn ReadConsoleInputW(
hConsoleInput: ?HANDLE,
lpBuffer: [*]INPUT_RECORD,
nLength: u32,
lpNumberOfEventsRead: ?*u32,
) callconv(@import("std").os.windows.WINAPI) BOOL;
pub extern "KERNEL32" fn PeekConsoleInputA(
hConsoleInput: ?HANDLE,
lpBuffer: [*]INPUT_RECORD,
nLength: u32,
lpNumberOfEventsRead: ?*u32,
) callconv(@import("std").os.windows.WINAPI) BOOL;
pub extern "KERNEL32" fn PeekConsoleInputW(
hConsoleInput: ?HANDLE,
lpBuffer: [*]INPUT_RECORD,
nLength: u32,
lpNumberOfEventsRead: ?*u32,
) callconv(@import("std").os.windows.WINAPI) BOOL;
pub extern "KERNEL32" fn ReadConsoleA(
hConsoleInput: ?HANDLE,
lpBuffer: ?*anyopaque,
nNumberOfCharsToRead: u32,
lpNumberOfCharsRead: ?*u32,
pInputControl: ?*CONSOLE_READCONSOLE_CONTROL,
) callconv(@import("std").os.windows.WINAPI) BOOL;
pub extern "KERNEL32" fn ReadConsoleW(
hConsoleInput: ?HANDLE,
lpBuffer: ?*anyopaque,
nNumberOfCharsToRead: u32,
lpNumberOfCharsRead: ?*u32,
pInputControl: ?*CONSOLE_READCONSOLE_CONTROL,
) callconv(@import("std").os.windows.WINAPI) BOOL;
pub extern "KERNEL32" fn WriteConsoleA(
hConsoleOutput: ?HANDLE,
lpBuffer: [*]const u8,
nNumberOfCharsToWrite: u32,
lpNumberOfCharsWritten: ?*u32,
lpReserved: ?*anyopaque,
) callconv(@import("std").os.windows.WINAPI) BOOL;
pub extern "KERNEL32" fn WriteConsoleW(
hConsoleOutput: ?HANDLE,
lpBuffer: [*]const u8,
nNumberOfCharsToWrite: u32,
lpNumberOfCharsWritten: ?*u32,
lpReserved: ?*anyopaque,
) callconv(@import("std").os.windows.WINAPI) BOOL;
pub extern "KERNEL32" fn SetConsoleCtrlHandler(
HandlerRoutine: ?PHANDLER_ROUTINE,
Add: BOOL,
) callconv(@import("std").os.windows.WINAPI) BOOL;
pub extern "KERNEL32" fn CreatePseudoConsole(
size: COORD,
hInput: ?HANDLE,
hOutput: ?HANDLE,
dwFlags: u32,
phPC: ?*?HPCON,
) callconv(@import("std").os.windows.WINAPI) HRESULT;
pub extern "KERNEL32" fn ResizePseudoConsole(
hPC: ?HPCON,
size: COORD,
) callconv(@import("std").os.windows.WINAPI) HRESULT;
pub extern "KERNEL32" fn ClosePseudoConsole(
hPC: ?HPCON,
) callconv(@import("std").os.windows.WINAPI) void;
pub extern "KERNEL32" fn FillConsoleOutputCharacterA(
hConsoleOutput: ?HANDLE,
cCharacter: CHAR,
nLength: u32,
dwWriteCoord: COORD,
lpNumberOfCharsWritten: ?*u32,
) callconv(@import("std").os.windows.WINAPI) BOOL;
pub extern "KERNEL32" fn FillConsoleOutputCharacterW(
hConsoleOutput: ?HANDLE,
cCharacter: u16,
nLength: u32,
dwWriteCoord: COORD,
lpNumberOfCharsWritten: ?*u32,
) callconv(@import("std").os.windows.WINAPI) BOOL;
pub extern "KERNEL32" fn FillConsoleOutputAttribute(
hConsoleOutput: ?HANDLE,
wAttribute: u16,
nLength: u32,
dwWriteCoord: COORD,
lpNumberOfAttrsWritten: ?*u32,
) callconv(@import("std").os.windows.WINAPI) BOOL;
pub extern "KERNEL32" fn GenerateConsoleCtrlEvent(
dwCtrlEvent: u32,
dwProcessGroupId: u32,
) callconv(@import("std").os.windows.WINAPI) BOOL;
pub extern "KERNEL32" fn CreateConsoleScreenBuffer(
dwDesiredAccess: u32,
dwShareMode: u32,
lpSecurityAttributes: ?*const SECURITY_ATTRIBUTES,
dwFlags: u32,
lpScreenBufferData: ?*anyopaque,
) callconv(@import("std").os.windows.WINAPI) ?HANDLE;
pub extern "KERNEL32" fn SetConsoleActiveScreenBuffer(
hConsoleOutput: ?HANDLE,
) callconv(@import("std").os.windows.WINAPI) BOOL;
pub extern "KERNEL32" fn FlushConsoleInputBuffer(
hConsoleInput: ?HANDLE,
) callconv(@import("std").os.windows.WINAPI) BOOL;
pub extern "KERNEL32" fn SetConsoleCP(
wCodePageID: u32,
) callconv(@import("std").os.windows.WINAPI) BOOL;
pub extern "KERNEL32" fn SetConsoleOutputCP(
wCodePageID: u32,
) callconv(@import("std").os.windows.WINAPI) BOOL;
pub extern "KERNEL32" fn GetConsoleCursorInfo(
hConsoleOutput: ?HANDLE,
lpConsoleCursorInfo: ?*CONSOLE_CURSOR_INFO,
) callconv(@import("std").os.windows.WINAPI) BOOL;
pub extern "KERNEL32" fn SetConsoleCursorInfo(
hConsoleOutput: ?HANDLE,
lpConsoleCursorInfo: ?*const CONSOLE_CURSOR_INFO,
) callconv(@import("std").os.windows.WINAPI) BOOL;
pub extern "KERNEL32" fn GetConsoleScreenBufferInfo(
hConsoleOutput: ?HANDLE,
lpConsoleScreenBufferInfo: ?*CONSOLE_SCREEN_BUFFER_INFO,
) callconv(@import("std").os.windows.WINAPI) BOOL;
pub extern "KERNEL32" fn GetConsoleScreenBufferInfoEx(
hConsoleOutput: ?HANDLE,
lpConsoleScreenBufferInfoEx: ?*CONSOLE_SCREEN_BUFFER_INFOEX,
) callconv(@import("std").os.windows.WINAPI) BOOL;
pub extern "KERNEL32" fn SetConsoleScreenBufferInfoEx(
hConsoleOutput: ?HANDLE,
lpConsoleScreenBufferInfoEx: ?*CONSOLE_SCREEN_BUFFER_INFOEX,
) callconv(@import("std").os.windows.WINAPI) BOOL;
pub extern "KERNEL32" fn SetConsoleScreenBufferSize(
hConsoleOutput: ?HANDLE,
dwSize: COORD,
) callconv(@import("std").os.windows.WINAPI) BOOL;
pub extern "KERNEL32" fn SetConsoleCursorPosition(
hConsoleOutput: ?HANDLE,
dwCursorPosition: COORD,
) callconv(@import("std").os.windows.WINAPI) BOOL;
pub extern "KERNEL32" fn GetLargestConsoleWindowSize(
hConsoleOutput: ?HANDLE,
) callconv(@import("std").os.windows.WINAPI) COORD;
pub extern "KERNEL32" fn SetConsoleTextAttribute(
hConsoleOutput: ?HANDLE,
wAttributes: u16,
) callconv(@import("std").os.windows.WINAPI) BOOL;
pub extern "KERNEL32" fn SetConsoleWindowInfo(
hConsoleOutput: ?HANDLE,
bAbsolute: BOOL,
lpConsoleWindow: ?*const SMALL_RECT,
) callconv(@import("std").os.windows.WINAPI) BOOL;
pub extern "KERNEL32" fn WriteConsoleOutputCharacterA(
hConsoleOutput: ?HANDLE,
lpCharacter: [*:0]const u8,
nLength: u32,
dwWriteCoord: COORD,
lpNumberOfCharsWritten: ?*u32,
) callconv(@import("std").os.windows.WINAPI) BOOL;
pub extern "KERNEL32" fn WriteConsoleOutputCharacterW(
hConsoleOutput: ?HANDLE,
lpCharacter: [*:0]const u16,
nLength: u32,
dwWriteCoord: COORD,
lpNumberOfCharsWritten: ?*u32,
) callconv(@import("std").os.windows.WINAPI) BOOL;
pub extern "KERNEL32" fn WriteConsoleOutputAttribute(
hConsoleOutput: ?HANDLE,
lpAttribute: [*:0]const u16,
nLength: u32,
dwWriteCoord: COORD,
lpNumberOfAttrsWritten: ?*u32,
) callconv(@import("std").os.windows.WINAPI) BOOL;
pub extern "KERNEL32" fn ReadConsoleOutputCharacterA(
hConsoleOutput: ?HANDLE,
lpCharacter: [*:0]u8,
nLength: u32,
dwReadCoord: COORD,
lpNumberOfCharsRead: ?*u32,
) callconv(@import("std").os.windows.WINAPI) BOOL;
pub extern "KERNEL32" fn ReadConsoleOutputCharacterW(
hConsoleOutput: ?HANDLE,
lpCharacter: [*:0]u16,
nLength: u32,
dwReadCoord: COORD,
lpNumberOfCharsRead: ?*u32,
) callconv(@import("std").os.windows.WINAPI) BOOL;
pub extern "KERNEL32" fn ReadConsoleOutputAttribute(
hConsoleOutput: ?HANDLE,
lpAttribute: [*:0]u16,
nLength: u32,
dwReadCoord: COORD,
lpNumberOfAttrsRead: ?*u32,
) callconv(@import("std").os.windows.WINAPI) BOOL;
pub extern "KERNEL32" fn WriteConsoleInputA(
hConsoleInput: ?HANDLE,
lpBuffer: [*]const INPUT_RECORD,
nLength: u32,
lpNumberOfEventsWritten: ?*u32,
) callconv(@import("std").os.windows.WINAPI) BOOL;
pub extern "KERNEL32" fn WriteConsoleInputW(
hConsoleInput: ?HANDLE,
lpBuffer: [*]const INPUT_RECORD,
nLength: u32,
lpNumberOfEventsWritten: ?*u32,
) callconv(@import("std").os.windows.WINAPI) BOOL;
pub extern "KERNEL32" fn ScrollConsoleScreenBufferA(
hConsoleOutput: ?HANDLE,
lpScrollRectangle: ?*const SMALL_RECT,
lpClipRectangle: ?*const SMALL_RECT,
dwDestinationOrigin: COORD,
lpFill: ?*const CHAR_INFO,
) callconv(@import("std").os.windows.WINAPI) BOOL;
pub extern "KERNEL32" fn ScrollConsoleScreenBufferW(
hConsoleOutput: ?HANDLE,
lpScrollRectangle: ?*const SMALL_RECT,
lpClipRectangle: ?*const SMALL_RECT,
dwDestinationOrigin: COORD,
lpFill: ?*const CHAR_INFO,
) callconv(@import("std").os.windows.WINAPI) BOOL;
pub extern "KERNEL32" fn WriteConsoleOutputA(
hConsoleOutput: ?HANDLE,
lpBuffer: ?*const CHAR_INFO,
dwBufferSize: COORD,
dwBufferCoord: COORD,
lpWriteRegion: ?*SMALL_RECT,
) callconv(@import("std").os.windows.WINAPI) BOOL;
pub extern "KERNEL32" fn WriteConsoleOutputW(
hConsoleOutput: ?HANDLE,
lpBuffer: ?*const CHAR_INFO,
dwBufferSize: COORD,
dwBufferCoord: COORD,
lpWriteRegion: ?*SMALL_RECT,
) callconv(@import("std").os.windows.WINAPI) BOOL;
pub extern "KERNEL32" fn ReadConsoleOutputA(
hConsoleOutput: ?HANDLE,
lpBuffer: ?*CHAR_INFO,
dwBufferSize: COORD,
dwBufferCoord: COORD,
lpReadRegion: ?*SMALL_RECT,
) callconv(@import("std").os.windows.WINAPI) BOOL;
pub extern "KERNEL32" fn ReadConsoleOutputW(
hConsoleOutput: ?HANDLE,
lpBuffer: ?*CHAR_INFO,
dwBufferSize: COORD,
dwBufferCoord: COORD,
lpReadRegion: ?*SMALL_RECT,
) callconv(@import("std").os.windows.WINAPI) BOOL;
pub extern "KERNEL32" fn GetConsoleTitleA(
lpConsoleTitle: [*:0]u8,
nSize: u32,
) callconv(@import("std").os.windows.WINAPI) u32;
pub extern "KERNEL32" fn GetConsoleTitleW(
lpConsoleTitle: [*:0]u16,
nSize: u32,
) callconv(@import("std").os.windows.WINAPI) u32;
pub extern "KERNEL32" fn GetConsoleOriginalTitleA(
lpConsoleTitle: [*:0]u8,
nSize: u32,
) callconv(@import("std").os.windows.WINAPI) u32;
pub extern "KERNEL32" fn GetConsoleOriginalTitleW(
lpConsoleTitle: [*:0]u16,
nSize: u32,
) callconv(@import("std").os.windows.WINAPI) u32;
pub extern "KERNEL32" fn SetConsoleTitleA(
lpConsoleTitle: ?[*:0]const u8,
) callconv(@import("std").os.windows.WINAPI) BOOL;
pub extern "KERNEL32" fn SetConsoleTitleW(
lpConsoleTitle: ?[*:0]const u16,
) callconv(@import("std").os.windows.WINAPI) BOOL;
pub extern "KERNEL32" fn GetNumberOfConsoleMouseButtons(
lpNumberOfMouseButtons: ?*u32,
) callconv(@import("std").os.windows.WINAPI) BOOL;
pub extern "KERNEL32" fn GetConsoleFontSize(
hConsoleOutput: ?HANDLE,
nFont: u32,
) callconv(@import("std").os.windows.WINAPI) COORD;
pub extern "KERNEL32" fn GetCurrentConsoleFont(
hConsoleOutput: ?HANDLE,
bMaximumWindow: BOOL,
lpConsoleCurrentFont: ?*CONSOLE_FONT_INFO,
) callconv(@import("std").os.windows.WINAPI) BOOL;
pub extern "KERNEL32" fn GetCurrentConsoleFontEx(
hConsoleOutput: ?HANDLE,
bMaximumWindow: BOOL,
lpConsoleCurrentFontEx: ?*CONSOLE_FONT_INFOEX,
) callconv(@import("std").os.windows.WINAPI) BOOL;
pub extern "KERNEL32" fn SetCurrentConsoleFontEx(
hConsoleOutput: ?HANDLE,
bMaximumWindow: BOOL,
lpConsoleCurrentFontEx: ?*CONSOLE_FONT_INFOEX,
) callconv(@import("std").os.windows.WINAPI) BOOL;
pub extern "KERNEL32" fn GetConsoleSelectionInfo(
lpConsoleSelectionInfo: ?*CONSOLE_SELECTION_INFO,
) callconv(@import("std").os.windows.WINAPI) BOOL;
pub extern "KERNEL32" fn GetConsoleHistoryInfo(
lpConsoleHistoryInfo: ?*CONSOLE_HISTORY_INFO,
) callconv(@import("std").os.windows.WINAPI) BOOL;
pub extern "KERNEL32" fn SetConsoleHistoryInfo(
lpConsoleHistoryInfo: ?*CONSOLE_HISTORY_INFO,
) callconv(@import("std").os.windows.WINAPI) BOOL;
pub extern "KERNEL32" fn GetConsoleDisplayMode(
lpModeFlags: ?*u32,
) callconv(@import("std").os.windows.WINAPI) BOOL;
pub extern "KERNEL32" fn SetConsoleDisplayMode(
hConsoleOutput: ?HANDLE,
dwFlags: u32,
lpNewScreenBufferDimensions: ?*COORD,
) callconv(@import("std").os.windows.WINAPI) BOOL;
pub extern "KERNEL32" fn GetConsoleWindow(
) callconv(@import("std").os.windows.WINAPI) ?HWND;
pub extern "KERNEL32" fn AddConsoleAliasA(
Source: ?PSTR,
Target: ?PSTR,
ExeName: ?PSTR,
) callconv(@import("std").os.windows.WINAPI) BOOL;
pub extern "KERNEL32" fn AddConsoleAliasW(
Source: ?PWSTR,
Target: ?PWSTR,
ExeName: ?PWSTR,
) callconv(@import("std").os.windows.WINAPI) BOOL;
pub extern "KERNEL32" fn GetConsoleAliasA(
Source: ?PSTR,
TargetBuffer: [*:0]u8,
TargetBufferLength: u32,
ExeName: ?PSTR,
) callconv(@import("std").os.windows.WINAPI) u32;
pub extern "KERNEL32" fn GetConsoleAliasW(
Source: ?PWSTR,
TargetBuffer: [*:0]u16,
TargetBufferLength: u32,
ExeName: ?PWSTR,
) callconv(@import("std").os.windows.WINAPI) u32;
pub extern "KERNEL32" fn GetConsoleAliasesLengthA(
ExeName: ?PSTR,
) callconv(@import("std").os.windows.WINAPI) u32;
pub extern "KERNEL32" fn GetConsoleAliasesLengthW(
ExeName: ?PWSTR,
) callconv(@import("std").os.windows.WINAPI) u32;
pub extern "KERNEL32" fn GetConsoleAliasExesLengthA(
) callconv(@import("std").os.windows.WINAPI) u32;
pub extern "KERNEL32" fn GetConsoleAliasExesLengthW(
) callconv(@import("std").os.windows.WINAPI) u32;
pub extern "KERNEL32" fn GetConsoleAliasesA(
AliasBuffer: [*:0]u8,
AliasBufferLength: u32,
ExeName: ?PSTR,
) callconv(@import("std").os.windows.WINAPI) u32;
pub extern "KERNEL32" fn GetConsoleAliasesW(
AliasBuffer: [*:0]u16,
AliasBufferLength: u32,
ExeName: ?PWSTR,
) callconv(@import("std").os.windows.WINAPI) u32;
pub extern "KERNEL32" fn GetConsoleAliasExesA(
ExeNameBuffer: [*:0]u8,
ExeNameBufferLength: u32,
) callconv(@import("std").os.windows.WINAPI) u32;
pub extern "KERNEL32" fn GetConsoleAliasExesW(
ExeNameBuffer: [*:0]u16,
ExeNameBufferLength: u32,
) callconv(@import("std").os.windows.WINAPI) u32;
pub extern "KERNEL32" fn ExpungeConsoleCommandHistoryA(
ExeName: ?PSTR,
) callconv(@import("std").os.windows.WINAPI) void;
pub extern "KERNEL32" fn ExpungeConsoleCommandHistoryW(
ExeName: ?PWSTR,
) callconv(@import("std").os.windows.WINAPI) void;
pub extern "KERNEL32" fn SetConsoleNumberOfCommandsA(
Number: u32,
ExeName: ?PSTR,
) callconv(@import("std").os.windows.WINAPI) BOOL;
pub extern "KERNEL32" fn SetConsoleNumberOfCommandsW(
Number: u32,
ExeName: ?PWSTR,
) callconv(@import("std").os.windows.WINAPI) BOOL;
pub extern "KERNEL32" fn GetConsoleCommandHistoryLengthA(
ExeName: ?PSTR,
) callconv(@import("std").os.windows.WINAPI) u32;
pub extern "KERNEL32" fn GetConsoleCommandHistoryLengthW(
ExeName: ?PWSTR,
) callconv(@import("std").os.windows.WINAPI) u32;
pub extern "KERNEL32" fn GetConsoleCommandHistoryA(
// TODO: what to do with BytesParamIndex 1?
Commands: ?PSTR,
CommandBufferLength: u32,
ExeName: ?PSTR,
) callconv(@import("std").os.windows.WINAPI) u32;
pub extern "KERNEL32" fn GetConsoleCommandHistoryW(
// TODO: what to do with BytesParamIndex 1?
Commands: ?PWSTR,
CommandBufferLength: u32,
ExeName: ?PWSTR,
) callconv(@import("std").os.windows.WINAPI) u32;
pub extern "KERNEL32" fn GetConsoleProcessList(
lpdwProcessList: [*]u32,
dwProcessCount: u32,
) callconv(@import("std").os.windows.WINAPI) u32;
pub extern "KERNEL32" fn GetStdHandle(
nStdHandle: STD_HANDLE,
) callconv(@import("std").os.windows.WINAPI) HANDLE;
pub extern "KERNEL32" fn SetStdHandle(
nStdHandle: STD_HANDLE,
hHandle: ?HANDLE,
) callconv(@import("std").os.windows.WINAPI) BOOL;
pub extern "KERNEL32" fn SetStdHandleEx(
nStdHandle: STD_HANDLE,
hHandle: ?HANDLE,
phPrevValue: ?*?HANDLE,
) callconv(@import("std").os.windows.WINAPI) BOOL;
//--------------------------------------------------------------------------------
// Section: Unicode Aliases (24)
//--------------------------------------------------------------------------------
const thismodule = @This();
pub usingnamespace switch (@import("../zig.zig").unicode_mode) {
.ansi => struct {
pub const ReadConsoleInput = thismodule.ReadConsoleInputA;
pub const PeekConsoleInput = thismodule.PeekConsoleInputA;
pub const ReadConsole = thismodule.ReadConsoleA;
pub const WriteConsole = thismodule.WriteConsoleA;
pub const FillConsoleOutputCharacter = thismodule.FillConsoleOutputCharacterA;
pub const WriteConsoleOutputCharacter = thismodule.WriteConsoleOutputCharacterA;
pub const ReadConsoleOutputCharacter = thismodule.ReadConsoleOutputCharacterA;
pub const WriteConsoleInput = thismodule.WriteConsoleInputA;
pub const ScrollConsoleScreenBuffer = thismodule.ScrollConsoleScreenBufferA;
pub const WriteConsoleOutput = thismodule.WriteConsoleOutputA;
pub const ReadConsoleOutput = thismodule.ReadConsoleOutputA;
pub const GetConsoleTitle = thismodule.GetConsoleTitleA;
pub const GetConsoleOriginalTitle = thismodule.GetConsoleOriginalTitleA;
pub const SetConsoleTitle = thismodule.SetConsoleTitleA;
pub const AddConsoleAlias = thismodule.AddConsoleAliasA;
pub const GetConsoleAlias = thismodule.GetConsoleAliasA;
pub const GetConsoleAliasesLength = thismodule.GetConsoleAliasesLengthA;
pub const GetConsoleAliasExesLength = thismodule.GetConsoleAliasExesLengthA;
pub const GetConsoleAliases = thismodule.GetConsoleAliasesA;
pub const GetConsoleAliasExes = thismodule.GetConsoleAliasExesA;
pub const ExpungeConsoleCommandHistory = thismodule.ExpungeConsoleCommandHistoryA;
pub const SetConsoleNumberOfCommands = thismodule.SetConsoleNumberOfCommandsA;
pub const GetConsoleCommandHistoryLength = thismodule.GetConsoleCommandHistoryLengthA;
pub const GetConsoleCommandHistory = thismodule.GetConsoleCommandHistoryA;
},
.wide => struct {
pub const ReadConsoleInput = thismodule.ReadConsoleInputW;
pub const PeekConsoleInput = thismodule.PeekConsoleInputW;
pub const ReadConsole = thismodule.ReadConsoleW;
pub const WriteConsole = thismodule.WriteConsoleW;
pub const FillConsoleOutputCharacter = thismodule.FillConsoleOutputCharacterW;
pub const WriteConsoleOutputCharacter = thismodule.WriteConsoleOutputCharacterW;
pub const ReadConsoleOutputCharacter = thismodule.ReadConsoleOutputCharacterW;
pub const WriteConsoleInput = thismodule.WriteConsoleInputW;
pub const ScrollConsoleScreenBuffer = thismodule.ScrollConsoleScreenBufferW;
pub const WriteConsoleOutput = thismodule.WriteConsoleOutputW;
pub const ReadConsoleOutput = thismodule.ReadConsoleOutputW;
pub const GetConsoleTitle = thismodule.GetConsoleTitleW;
pub const GetConsoleOriginalTitle = thismodule.GetConsoleOriginalTitleW;
pub const SetConsoleTitle = thismodule.SetConsoleTitleW;
pub const AddConsoleAlias = thismodule.AddConsoleAliasW;
pub const GetConsoleAlias = thismodule.GetConsoleAliasW;
pub const GetConsoleAliasesLength = thismodule.GetConsoleAliasesLengthW;
pub const GetConsoleAliasExesLength = thismodule.GetConsoleAliasExesLengthW;
pub const GetConsoleAliases = thismodule.GetConsoleAliasesW;
pub const GetConsoleAliasExes = thismodule.GetConsoleAliasExesW;
pub const ExpungeConsoleCommandHistory = thismodule.ExpungeConsoleCommandHistoryW;
pub const SetConsoleNumberOfCommands = thismodule.SetConsoleNumberOfCommandsW;
pub const GetConsoleCommandHistoryLength = thismodule.GetConsoleCommandHistoryLengthW;
pub const GetConsoleCommandHistory = thismodule.GetConsoleCommandHistoryW;
},
.unspecified => if (@import("builtin").is_test) struct {
pub const ReadConsoleInput = *opaque{};
pub const PeekConsoleInput = *opaque{};
pub const ReadConsole = *opaque{};
pub const WriteConsole = *opaque{};
pub const FillConsoleOutputCharacter = *opaque{};
pub const WriteConsoleOutputCharacter = *opaque{};
pub const ReadConsoleOutputCharacter = *opaque{};
pub const WriteConsoleInput = *opaque{};
pub const ScrollConsoleScreenBuffer = *opaque{};
pub const WriteConsoleOutput = *opaque{};
pub const ReadConsoleOutput = *opaque{};
pub const GetConsoleTitle = *opaque{};
pub const GetConsoleOriginalTitle = *opaque{};
pub const SetConsoleTitle = *opaque{};
pub const AddConsoleAlias = *opaque{};
pub const GetConsoleAlias = *opaque{};
pub const GetConsoleAliasesLength = *opaque{};
pub const GetConsoleAliasExesLength = *opaque{};
pub const GetConsoleAliases = *opaque{};
pub const GetConsoleAliasExes = *opaque{};
pub const ExpungeConsoleCommandHistory = *opaque{};
pub const SetConsoleNumberOfCommands = *opaque{};
pub const GetConsoleCommandHistoryLength = *opaque{};
pub const GetConsoleCommandHistory = *opaque{};
} else struct {
pub const ReadConsoleInput = @compileError("'ReadConsoleInput' requires that UNICODE be set to true or false in the root module");
pub const PeekConsoleInput = @compileError("'PeekConsoleInput' requires that UNICODE be set to true or false in the root module");
pub const ReadConsole = @compileError("'ReadConsole' requires that UNICODE be set to true or false in the root module");
pub const WriteConsole = @compileError("'WriteConsole' requires that UNICODE be set to true or false in the root module");
pub const FillConsoleOutputCharacter = @compileError("'FillConsoleOutputCharacter' requires that UNICODE be set to true or false in the root module");
pub const WriteConsoleOutputCharacter = @compileError("'WriteConsoleOutputCharacter' requires that UNICODE be set to true or false in the root module");
pub const ReadConsoleOutputCharacter = @compileError("'ReadConsoleOutputCharacter' requires that UNICODE be set to true or false in the root module");
pub const WriteConsoleInput = @compileError("'WriteConsoleInput' requires that UNICODE be set to true or false in the root module");
pub const ScrollConsoleScreenBuffer = @compileError("'ScrollConsoleScreenBuffer' requires that UNICODE be set to true or false in the root module");
pub const WriteConsoleOutput = @compileError("'WriteConsoleOutput' requires that UNICODE be set to true or false in the root module");
pub const ReadConsoleOutput = @compileError("'ReadConsoleOutput' requires that UNICODE be set to true or false in the root module");
pub const GetConsoleTitle = @compileError("'GetConsoleTitle' requires that UNICODE be set to true or false in the root module");
pub const GetConsoleOriginalTitle = @compileError("'GetConsoleOriginalTitle' requires that UNICODE be set to true or false in the root module");
pub const SetConsoleTitle = @compileError("'SetConsoleTitle' requires that UNICODE be set to true or false in the root module");
pub const AddConsoleAlias = @compileError("'AddConsoleAlias' requires that UNICODE be set to true or false in the root module");
pub const GetConsoleAlias = @compileError("'GetConsoleAlias' requires that UNICODE be set to true or false in the root module");
pub const GetConsoleAliasesLength = @compileError("'GetConsoleAliasesLength' requires that UNICODE be set to true or false in the root module");
pub const GetConsoleAliasExesLength = @compileError("'GetConsoleAliasExesLength' requires that UNICODE be set to true or false in the root module");
pub const GetConsoleAliases = @compileError("'GetConsoleAliases' requires that UNICODE be set to true or false in the root module");
pub const GetConsoleAliasExes = @compileError("'GetConsoleAliasExes' requires that UNICODE be set to true or false in the root module");
pub const ExpungeConsoleCommandHistory = @compileError("'ExpungeConsoleCommandHistory' requires that UNICODE be set to true or false in the root module");
pub const SetConsoleNumberOfCommands = @compileError("'SetConsoleNumberOfCommands' requires that UNICODE be set to true or false in the root module");
pub const GetConsoleCommandHistoryLength = @compileError("'GetConsoleCommandHistoryLength' requires that UNICODE be set to true or false in the root module");
pub const GetConsoleCommandHistory = @compileError("'GetConsoleCommandHistory' requires that UNICODE be set to true or false in the root module");
},
};
//--------------------------------------------------------------------------------
// Section: Imports (8)
//--------------------------------------------------------------------------------
const BOOL = @import("../foundation.zig").BOOL;
const CHAR = @import("../foundation.zig").CHAR;
const HANDLE = @import("../foundation.zig").HANDLE;
const HRESULT = @import("../foundation.zig").HRESULT;
const HWND = @import("../foundation.zig").HWND;
const PSTR = @import("../foundation.zig").PSTR;
const PWSTR = @import("../foundation.zig").PWSTR;
const SECURITY_ATTRIBUTES = @import("../security.zig").SECURITY_ATTRIBUTES;
test {
// The following '_ = <FuncPtrType>' lines are a workaround for https://github.com/ziglang/zig/issues/4476
if (@hasDecl(@This(), "PHANDLER_ROUTINE")) { _ = PHANDLER_ROUTINE; }
@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/console.zig
|
const std = @import("std");
const gui = @import("./gui/ui.zig");
const cli = @import("./cli/ui.zig");
const args = @import("./args.zig");
const patternMatch = @import("./patterns.zig").patternMatch;
// const layout = @import("./gui/layout.zig");
//
// comptime {
// std.testing.refAllDecls(layout);
// }
pub const Player = struct {
name: []const u8 = undefined,
points: u32 = 0,
};
pub const State = struct {
player: Player = undefined,
alloc: *std.mem.Allocator = undefined,
dices: [5]u8 = .{0} ** 5,
reroll_buffer: [5]bool = [_]bool{true} ** 5,
reroll_count: usize = 0,
pub fn dicesToReroll(self: *State) usize {
var face_counter = [_]u8{0} ** 6;
// if dices is not 1 or 5 or not contribute to small straight or 3,4,5 of each\
for (self.dices) |elem, index| {
face_counter[elem - 1] += 1;
if ((elem == 1) or (elem == 5)) {
self.reroll_buffer[index] = false;
}
}
for (face_counter) |face_count, face_index| {
const face = face_index + 1;
if (face_count >= 3) {
for (self.dices) |elem, idx| {
if (elem == face) {
self.reroll_buffer[idx] = false;
}
}
}
}
// var points: usize = 0;
// const three_of = patternMatch(self.dices, "NNN??") or patternMatch(self.dices, "?NNN?") or patternMatch(dices, "??NNN"); // { value: u8, count: u8 }
// const four_of = patternMatch(self.dices, "NNNN?") or patternMatch(self.dices, "?NNNN");
// const five_of = patternMatch(self.dices, "NNNNN");
// const many = dices[2];
// if ( five_of ) { points = many * 100 * 4; } else if (four_of) { points = many * 100 * 2; } else if ( three_of ) { points = many * 100; }
// const has_straight = patternMatch(dices, "12345") or patternMatch(dices, "23456");
var has_straight: bool = true;
for (face_counter[0..4]) |face| {
if (face != 1) {
has_straight = false;
break;
}
}
if (has_straight) {
for (self.reroll_buffer) |*r| {
r.* = false;
}
return 0;
}
var count: u8 = 0;
for (self.reroll_buffer) |r| {
if (r) count += 1;
}
return count;
}
pub fn init(user: []const u8) State {
return .{
.player = .{ .name = user, .points = 0 },
};
}
pub fn computePoints(self: *State) u32 {
var points: u32 = 0;
const three_of = patternMatch(&self.dices, "NNN??") or patternMatch(&self.dices, "?NNN?") or patternMatch(&self.dices, "??NNN");
const four_of = patternMatch(&self.dices, "NNNN?") or patternMatch(&self.dices, "?NNNN");
const five_of = patternMatch(&self.dices, "NNNNN");
const ones = @intCast(u32, std.mem.count(u8, &self.dices, &.{1}));
const fives = @intCast(u32, std.mem.count(u8, &self.dices, &.{5}));
const multiple_factor: u32 = if (self.dices[3] == 1) 1000 else 100;
if ( five_of ) {
points += self.dices[3] * multiple_factor * 4;
} else if ( four_of ) {
points += self.dices[3] * multiple_factor * 2;
} else if ( three_of ) {
points += self.dices[3] * multiple_factor;
}
if ( ones < 3 ) {
points += ones * 100;
}
if ( fives < 3 ) {
points += fives * 50;
}
if ( patternMatch(&self.dices, "12345") or patternMatch(&self.dices, "23456")) {
points += 1250;
}
return points;
}
pub fn reroll(self: *State) void {
for (self.reroll_buffer) |dice_to_reroll, idx| {
if (dice_to_reroll) {
self.dices[idx] = global_rng.random.intRangeAtMost(u8, 1, 6);
}
}
const asc_u8 = comptime std.sort.asc(u8);
std.sort.sort(u8, &self.dices, {}, asc_u8);
self.reroll_count = self.dicesToReroll();
}
pub fn forceReroll(self: *State) void {
std.mem.set(bool, &self.reroll_buffer, true);
self.reroll();
}
pub fn newGame(self: *State, player_name: []const u8) void {
self.player = Player {
.name = player_name,
};
std.mem.set(bool, &self.reroll_buffer, true);
std.mem.set(u8, &self.dices, 1);
}
};
pub const AppError = error{BadInput};
const WINNING_CONDITION: usize = 10000;
const RandState = struct {
rng: std.rand.DefaultPrng = undefined,
random: *std.rand.Random = undefined,
};
pub var global_rng: RandState = .{};
pub var global_allocator : *std.mem.Allocator = undefined;
pub fn initRandomGenerator() void {
var seed_bytes: [@sizeOf(u64)]u8 = undefined;
std.crypto.random.bytes(&seed_bytes);
const seed: u64 = std.mem.readIntNative(u64, &seed_bytes);
global_rng.rng = std.rand.DefaultPrng.init(seed);
global_rng.random = &global_rng.rng.random;
}
pub fn main() anyerror!void {
std.debug.print("== Hello in this little dice roller == \n", .{});
std.debug.print("First things first.\n", .{});
initRandomGenerator();
var gpa = std.heap.GeneralPurposeAllocator(.{}){};
global_allocator = &gpa.allocator;
var state = State.init("User");
var options = try args.parseArgs(&gpa.allocator);
defer options.deinit(&gpa.allocator);
switch (options.gui_type) {
.Cli => {
try cli.start(options, &state);
},
.Gui => {
try gui.start(options, &state);
},
}
}
|
src/main.zig
|
const std = @import("std");
const tools = @import("tools");
const with_trace = false;
fn trace(comptime fmt: []const u8, args: anytype) void {
if (with_trace) std.debug.print(fmt, args);
}
const assert = std.debug.assert;
pub const main = tools.defaultMain("2021/day09.txt", run);
const Vec2 = tools.Vec2;
const Map = tools.Map(u8, 128, 128, false);
fn floodFill(map: *const Map, pos: Vec2) u32 {
const Bitmap = tools.Map(u1, 128, 128, false);
const Local = struct {
fn recurse(m: *const Map, filled: *Bitmap, p: Vec2) u32 {
if ((m.get(p) orelse 9) >= 9) return 0;
if ((filled.get(p) orelse 0) != 0) return 0;
filled.set(p, 1);
var count: u32 = 1;
for (tools.Vec.cardinal4_dirs) |d| count += @This().recurse(m, filled, p + d);
return count;
}
};
var filled = Bitmap{ .default_tile = 0 };
return Local.recurse(map, &filled, pos);
}
pub fn run(input: []const u8, gpa: std.mem.Allocator) tools.RunError![2][]const u8 {
var map = Map{ .default_tile = 0 };
{
var it = std.mem.tokenize(u8, input, "\n");
var y: u32 = 0;
while (it.next()) |line| : (y += 1) {
for (line) |c, x| {
switch (c) {
'0'...'9' => map.set(Vec2{ @intCast(i32, x), @intCast(i32, y) }, c - '0'),
else => {},
}
}
}
}
var lowpoints_storage: [500]Vec2 = undefined;
var lowpoints: []Vec2 = lowpoints_storage[0..0];
const ans1 = ans: {
var score: u32 = 0;
var it = map.iter(null);
while (it.nextEx()) |t| {
var count: i32 = 0;
for (t.neib4) |n| {
if (n) |t1| {
count += @boolToInt(t.t.* < t1);
} else {
count += 1;
}
}
if (count == 4) {
score += t.t.* + 1;
lowpoints_storage[lowpoints.len] = t.p;
lowpoints = lowpoints_storage[0 .. lowpoints.len + 1];
}
}
break :ans score;
};
const ans2 = ans: {
var largest_basins = [3]u32{ 0, 0, 0 };
for (lowpoints) |lp| {
const size = floodFill(&map, lp);
trace("bassin @{} = {}\n", .{ lp, size });
if (size > largest_basins[0]) {
largest_basins[2] = largest_basins[1];
largest_basins[1] = largest_basins[0];
largest_basins[0] = size;
} else if (size > largest_basins[1]) {
largest_basins[2] = largest_basins[1];
largest_basins[1] = size;
} else if (size > largest_basins[2]) {
largest_basins[2] = size;
}
}
break :ans largest_basins[0] * largest_basins[1] * largest_basins[2];
};
return [_][]const u8{
try std.fmt.allocPrint(gpa, "{}", .{ans1}),
try std.fmt.allocPrint(gpa, "{}", .{ans2}),
};
}
test {
const res = try run(
\\2199943210
\\3987894921
\\9856789892
\\8767896789
\\9899965678
, std.testing.allocator);
defer std.testing.allocator.free(res[0]);
defer std.testing.allocator.free(res[1]);
try std.testing.expectEqualStrings("15", res[0]);
try std.testing.expectEqualStrings("1134", res[1]);
}
|
2021/day09.zig
|
const std = @import("std");
const assert = std.debug.assert;
const tools = @import("tools");
pub fn run(input: []const u8, allocator: std.mem.Allocator) ![2][]const u8 {
var pots = [_]u1{0} ** 1000;
const pot_offset = pots.len / 2;
var pot_min: usize = 1000;
var pot_max: usize = 0;
var rules = [_]u1{0} ** 32;
const filled: u1 = 1;
const empty: u1 = 0;
{
var it = std.mem.tokenize(u8, input, "\n\r");
{
const fields = tools.match_pattern("initial state: {}", it.next().?) orelse unreachable;
const init = fields[0].lit;
for (init) |c, i| {
const pot_index = i + pot_offset;
pots[pot_index] = if (c == '#') filled else empty;
if (pots[pot_index] != 0) {
pot_min = if (pot_index < pot_min) pot_index else pot_min;
pot_max = if (pot_index > pot_max) pot_index else pot_max;
}
}
}
while (it.next()) |line| {
const fields = tools.match_pattern("{} => {}", line) orelse unreachable;
const out = if (fields[1].lit[0] == '#') filled else empty;
var in: u32 = 0;
for (fields[0].lit) |c| {
in = (in << 1) | (if (c == '#') filled else empty);
}
rules[in] = out;
}
}
// part1
const ans1 = ans: {
var prev = [_]u1{0} ** 1000;
var next = [_]u1{0} ** 1000;
std.mem.copy(u1, &prev, &pots);
var prev_min = pot_min;
var prev_max = pot_max;
var gen: u32 = 1;
while (gen <= 20) : (gen += 1) {
var next_min: usize = 10000;
var next_max: usize = 0;
for (next[prev_min - 2 .. prev_max + 2 + 1]) |*it, index| {
const i = index + (prev_min - 2);
const p: usize = @as(usize, prev[i - 2]) * 16 + @as(usize, prev[i - 1]) * 8 + @as(usize, prev[i + 0]) * 4 + @as(usize, prev[i + 1]) * 2 + @as(usize, prev[i + 2]) * 1;
it.* = rules[p];
if (rules[p] != 0) {
next_min = if (i < next_min) i else next_min;
next_max = if (i > next_max) i else next_max;
}
}
std.mem.copy(u1, &prev, &next);
prev_min = next_min;
prev_max = next_max;
}
var score: i32 = 0;
for (prev[prev_min .. prev_max + 1]) |p, i| {
if (p != 0)
score += (@intCast(i32, i + prev_min) - @intCast(i32, pot_offset));
}
break :ans score;
};
// part2
const ans2 = ans: {
var prev = [_]u1{0} ** 1000;
var next = [_]u1{0} ** 1000;
std.mem.copy(u1, &prev, &pots);
var prev_min = pot_min;
var prev_max = pot_max;
var prev_score: i32 = 0;
var a: i64 = 0;
var b: i64 = 0;
var gen: u32 = 1;
while (true) : (gen += 1) {
//std.debug.print("gen n°{}: [{}, {}] ", .{ gen, prev_min, prev_max });
//for (prev[prev_min .. prev_max + 1]) |p, i| {
// const c: u8 = if (p != 0) '#' else '.';
// std.debug.print("{c}", .{c});
//}
//std.debug.print("\n", .{});
var next_min: usize = 10000;
var next_max: usize = 0;
for (next[prev_min - 2 .. prev_max + 2 + 1]) |*it, index| {
const i = index + (prev_min - 2);
const p: usize = @as(usize, prev[i - 2]) * 16 + @as(usize, prev[i - 1]) * 8 + @as(usize, prev[i + 0]) * 4 + @as(usize, prev[i + 1]) * 2 + @as(usize, prev[i + 2]) * 1;
it.* = rules[p];
if (rules[p] != 0) {
next_min = if (i < next_min) i else next_min;
next_max = if (i > next_max) i else next_max;
}
}
std.mem.copy(u1, &prev, &next);
prev_min = next_min;
prev_max = next_max;
var score: i32 = 0;
for (prev[prev_min .. prev_max + 1]) |p, i| {
if (p != 0)
score += (@intCast(i32, i + prev_min) - @intCast(i32, pot_offset));
}
//std.debug.print("gen={}, score={}, min={}, recentre={}, moy={}\n", .{ gen, score, prev_min, score - @intCast(i32, prev_min), @divTrunc((score - @intCast(i32, (prev_min + prev_max) / 2)), @intCast(i32, prev_max - prev_min)) });
// on constate que le pattern devient fixe après quelques generations (152) et se decale a vitesse constante. -> on doit pouvoir extrapoler
{
const g = @intCast(i32, gen);
const na = (score - prev_score);
const nb = score - g * na;
// std.debug.print("gen={}, a={}, b={}, check={}\n", .{ gen, na, nb, na * g + nb });
if (na == a and nb == b) { // stabilized!
break :ans a * 50000000000 + b;
}
a = na;
b = nb;
}
prev_score = score;
}
unreachable;
};
return [_][]const u8{
try std.fmt.allocPrint(allocator, "{}", .{ans1}),
try std.fmt.allocPrint(allocator, "{}", .{ans2}),
};
}
pub const main = tools.defaultMain("2018/input_day12.txt", run);
|
2018/day12.zig
|
const std = @import("std");
const Atomic = std.atomic.Atomic;
const utils = @import("../utils.zig");
pub const Lock =
if (utils.is_windows)
WindowsLock
else if (utils.is_darwin)
DarwinLock
else if (utils.is_linux)
LinuxLock
else
void;
const DarwinLock = extern struct {
pub const name = "os_unfair_lock";
oul: std.os.darwin.os_unfair_lock,
pub fn init(self: *Lock) void {
self.oul = std.os.darwin.OS_UNFAIR_LOCK_INIT;
}
pub fn deinit(self: *Lock) void {
self.* = undefined;
}
pub fn acquire(self: *Lock) void {
std.os.darwin.os_unfair_lock_lock(&self.oul);
}
pub fn release(self: *Lock) void {
std.os.darwin.os_unfair_lock_unlock(&self.oul);
}
};
const WindowsLock = extern struct {
pub const name = "SRWLOCK";
srwlock: std.os.windows.SRWLOCK = std.os.windows.SRWLOCK_INIT,
pub fn init(self: *Lock) void {
self.* = Lock{};
}
pub fn deinit(self: *Lock) void {
self.* = undefined;
}
pub fn acquire(self: *Lock) void {
std.os.windows.kernel32.AcquireSRWLockExclusive(&self.srwlock);
}
pub fn release(self: *Lock) void {
std.os.windows.kernel32.ReleaseSRWLockExclusive(&self.srwlock);
}
};
const LinuxLock = extern struct {
pub const name = "FUTEX.LOCK_PI";
state: Atomic(u32) = Atomic(u32).init(UNLOCKED),
const UNLOCKED = 0;
const FUTEX_WAITERS = 0x80000000;
pub fn init(self: *Lock) void {
self.* = Lock{};
}
pub fn deinit(self: *Lock) void {
self.* = undefined;
}
threadlocal var tls_tid: u32 = 0;
pub fn acquire(self: *Lock) void {
if (!self.acquireFast()) {
self.acquireSlow();
}
}
inline fn acquireFast(self: *Lock) bool {
const tid = tls_tid;
return tid != 0 and self.state.tryCompareAndSwap(
UNLOCKED,
tid,
.Acquire,
.Monotonic,
) == null;
}
fn acquireSlow(self: *Lock) void {
@setCold(true);
var tid = tls_tid;
if (tid == 0) {
tid = @bitCast(u32, std.os.linux.gettid());
tls_tid = tid;
}
var spin: u8 = 10;
while (spin > 0) : (spin -= 1) {
const state = self.state.load(.Monotonic);
if (state & FUTEX_WAITERS != 0) break;
if (state != UNLOCKED) continue;
if (self.state.tryCompareAndSwap(UNLOCKED, tid, .Acquire, .Monotonic) == null) return;
}
while (true) {
if (self.state.load(.Monotonic) == 0) {
_ = self.state.compareAndSwap(
UNLOCKED,
tid,
.Acquire,
.Monotonic,
) orelse return;
}
const rc = std.os.linux.syscall4(
.futex,
@ptrToInt(&self.state),
std.os.linux.FUTEX.PRIVATE_FLAG | std.os.linux.FUTEX.LOCK_PI,
undefined,
@as(usize, 0),
);
switch (std.os.linux.getErrno(rc)) {
.SUCCESS => return,
.AGAIN => continue,
.NOSYS => unreachable,
.DEADLK => unreachable,
.FAULT => unreachable,
.INVAL => unreachable,
.PERM => unreachable,
.NOMEM => @panic("kernel OOM"),
else => unreachable,
}
}
}
pub fn release(self: *Lock) void {
const tid = tls_tid;
std.debug.assert(tid != 0);
_ = self.state.compareAndSwap(
tid,
UNLOCKED,
.Release,
.Monotonic,
) orelse return;
return self.releaseSlow();
}
fn releaseSlow(self: *Lock) void {
@setCold(true);
while (true) {
const rc = std.os.linux.syscall4(
.futex,
@ptrToInt(&self.state),
std.os.linux.FUTEX.PRIVATE_FLAG | std.os.linux.FUTEX.UNLOCK_PI,
undefined,
@as(usize, 0),
);
switch (std.os.linux.getErrno(rc)) {
.SUCCESS => return,
.INVAL => unreachable,
.PERM => unreachable,
else => unreachable,
}
}
}
};
|
locks/os_raw_lock.zig
|
const std = @import("std");
const builtin = @import("builtin");
const minInt = std.math.minInt;
const maxInt = std.math.maxInt;
const expect = std.testing.expect;
test "wrapping add" {
const S = struct {
fn doTheTest() !void {
try testWrapAdd(i8, -3, 10, 7);
try testWrapAdd(i8, -128, -128, 0);
try testWrapAdd(i2, 1, 1, -2);
try testWrapAdd(i64, maxInt(i64), 1, minInt(i64));
try testWrapAdd(i128, maxInt(i128), -maxInt(i128), 0);
try testWrapAdd(i128, minInt(i128), maxInt(i128), -1);
try testWrapAdd(i8, 127, 127, -2);
try testWrapAdd(u8, 3, 10, 13);
try testWrapAdd(u8, 255, 255, 254);
try testWrapAdd(u2, 3, 2, 1);
try testWrapAdd(u3, 7, 1, 0);
try testWrapAdd(u128, maxInt(u128), 1, minInt(u128));
}
fn testWrapAdd(comptime T: type, lhs: T, rhs: T, expected: T) !void {
try expect((lhs +% rhs) == expected);
var x = lhs;
x +%= rhs;
try expect(x == expected);
}
};
try S.doTheTest();
comptime try S.doTheTest();
comptime try S.testWrapAdd(comptime_int, 0, 0, 0);
comptime try S.testWrapAdd(comptime_int, 3, 2, 5);
comptime try S.testWrapAdd(comptime_int, 651075816498665588400716961808225370057, 468229432685078038144554201546849378455, 1119305249183743626545271163355074748512);
comptime try S.testWrapAdd(comptime_int, 7, -593423721213448152027139550640105366508, -593423721213448152027139550640105366501);
}
test "wrapping subtraction" {
const S = struct {
fn doTheTest() !void {
try testWrapSub(i8, -3, 10, -13);
try testWrapSub(i8, -128, -128, 0);
try testWrapSub(i8, -1, 127, -128);
try testWrapSub(i64, minInt(i64), 1, maxInt(i64));
try testWrapSub(i128, maxInt(i128), -1, minInt(i128));
try testWrapSub(i128, minInt(i128), -maxInt(i128), -1);
try testWrapSub(u8, 10, 3, 7);
try testWrapSub(u8, 0, 255, 1);
try testWrapSub(u5, 0, 31, 1);
try testWrapSub(u128, 0, maxInt(u128), 1);
}
fn testWrapSub(comptime T: type, lhs: T, rhs: T, expected: T) !void {
try expect((lhs -% rhs) == expected);
var x = lhs;
x -%= rhs;
try expect(x == expected);
}
};
try S.doTheTest();
comptime try S.doTheTest();
comptime try S.testWrapSub(comptime_int, 0, 0, 0);
comptime try S.testWrapSub(comptime_int, 3, 2, 1);
comptime try S.testWrapSub(comptime_int, 651075816498665588400716961808225370057, 468229432685078038144554201546849378455, 182846383813587550256162760261375991602);
comptime try S.testWrapSub(comptime_int, 7, -593423721213448152027139550640105366508, 593423721213448152027139550640105366515);
}
test "wrapping multiplication" {
// TODO: once #9660 has been solved, remove this line
if (builtin.cpu.arch == .wasm32) return error.SkipZigTest;
const S = struct {
fn doTheTest() !void {
try testWrapMul(i8, -3, 10, -30);
try testWrapMul(i4, 2, 4, -8);
try testWrapMul(i8, 2, 127, -2);
try testWrapMul(i8, -128, -128, 0);
try testWrapMul(i8, maxInt(i8), maxInt(i8), 1);
try testWrapMul(i16, maxInt(i16), -1, minInt(i16) + 1);
try testWrapMul(i128, maxInt(i128), -1, minInt(i128) + 1);
try testWrapMul(i128, minInt(i128), -1, minInt(i128));
try testWrapMul(u8, 10, 3, 30);
try testWrapMul(u8, 2, 255, 254);
try testWrapMul(u128, maxInt(u128), maxInt(u128), 1);
}
fn testWrapMul(comptime T: type, lhs: T, rhs: T, expected: T) !void {
try expect((lhs *% rhs) == expected);
var x = lhs;
x *%= rhs;
try expect(x == expected);
}
};
try S.doTheTest();
comptime try S.doTheTest();
comptime try S.testWrapMul(comptime_int, 0, 0, 0);
comptime try S.testWrapMul(comptime_int, 3, 2, 6);
comptime try S.testWrapMul(comptime_int, 651075816498665588400716961808225370057, 468229432685078038144554201546849378455, 304852860194144160265083087140337419215516305999637969803722975979232817921935);
comptime try S.testWrapMul(comptime_int, 7, -593423721213448152027139550640105366508, -4153966048494137064189976854480737565556);
}
|
test/behavior/wrapping_arithmetic.zig
|
pub usingnamespace @import("prompt.zig");
usingnamespace if (@import("root") == @This())
struct {
const std = @import("std");
const builtin = @import("builtin");
const mem = std.mem;
const ascii = std.ascii;
const Allocator = mem.Allocator;
const Stream = std.fs.File.OutStream.Stream;
fn flushCmds(stream: *Stream, cmds: []const Command) void {
for (cmds) |c|
stream.print("{}", c) catch return;
}
fn toUnixPath(path: []u8) []u8 {
path[1] = ascii.toLower(path[0]);
path[0] = '/';
for (path) |*c| {
switch (c.*) {
'\\' => c.* = '/',
else => {},
}
}
return mem.trimRight(u8, path, "/");
}
fn trimWhileLeft(slice: []u8, strip: []const u8) usize {
var idx: usize = 0;
while (idx < slice.len and slice[idx] == strip[idx]) : (idx += 1) {}
return idx;
}
fn truncatePath(allocator: *Allocator, path: []u8, home: []const u8) []const u8 {
if (mem.startsWith(u8, path, home)) {
path[home.len - 1] = '~';
path = path[home.len - 1 ..];
} else {
path = path[trimWhileLeft(path, home) - 1 ..];
path[0] = '/';
}
std.debug.warn("-> {}\n", path);
const end = mem.indexOf(u8, path, "/") orelse 0;
var start = mem.lastIndexOf(u8, path[0..], "/") orelse 0;
start = mem.lastIndexOf(u8, path[0..start], "/") orelse start;
if (end == 0) {
return mem.join(allocator, "...", [_][]const u8{ "", path[start..] }) catch path;
} else {
return mem.join(allocator, "...", [_][]const u8{ path[0..end + 1], path[start..] }) catch path;
}
// std.debug.warn("-> {}\n", path[start..]);
// if (path[start..].len > 1 and path[0..end].len > 0) {
// return mem.join(allocator, "..", [_][]u8{ path[0..end], path[start..] }) catch path;
// } else if (path[start..].len > 1) {
// return path[start..];
// } else {
// return path;
// }
}
pub fn main() void {
var buffer: [std.fs.MAX_PATH_BYTES]u8 = undefined;
var allocator = &std.heap.FixedBufferAllocator.init(buffer[0..]).allocator;
const user = mem.toSliceConst(u8, std.c.getenv(c"USER") orelse c"$USER");
const home = blk: {
var home = mem.toSlice(u8, std.c.getenv(c"HOME") orelse break :blk "");
if (builtin.os == .windows)
break :blk toUnixPath(home);
break :blk home;
};
const cwd = blk: {
var cwd = toUnixPath(std.process.getCwdAlloc(allocator) catch break :blk "$(pwd)"[0..]);
if (builtin.os == .windows)
break :blk truncatePath(allocator, cwd, home);
break :blk cwd;
};
// std.debug.warn("");
var stdout = std.io.getStdOut() catch return;
var stream = &stdout.outStream().stream;
flushCmds(stream, [_]Command{
Command.Bright,
Command{ .ForeGround = .Red },
Command{ .ReturnCode = ReturnCode{} },
Command{ .ForeGround = .Green },
Command{ .Text = user },
Command{ .ForeGround = .Blue },
Command{ .Text = " " },
Command{ .Text = cwd },
Command.Reset,
Command{ .Text = "\n%% " },
});
}
};
|
src/zomp.zig
|
const std = @import("std");
const Allocator = std.mem.Allocator;
const print = std.debug.print;
const data = @embedFile("../inputs/day13.txt");
pub fn main() anyerror!void {
var gpa_impl = std.heap.GeneralPurposeAllocator(.{}){};
defer _ = gpa_impl.deinit();
const gpa = gpa_impl.allocator();
return main_with_allocator(gpa);
}
pub fn main_with_allocator(allocator: Allocator) anyerror!void {
var instr = try Instr.parse(allocator, data[0..]);
defer instr.deinit();
print("Part 1: {d}\n", .{try part1(allocator, instr)});
print("Part 2:\n", .{});
try part2(allocator, instr);
}
const Point = struct {
const Self = @This();
x: isize,
y: isize,
fn parse(input: []const u8) !Self {
var it = std.mem.tokenize(u8, input, ",");
const x = try std.fmt.parseInt(isize, it.next().?, 10);
const y = try std.fmt.parseInt(isize, it.next().?, 10);
return Point{
.x = x,
.y = y,
};
}
};
const Fold = union(enum) {
const Self = @This();
x: isize,
y: isize,
fn parse(input: []const u8) !Self {
const fold_str = std.mem.trimLeft(u8, input, "fold along ");
switch (fold_str[0]) {
'x' => {
const x = try std.fmt.parseInt(isize, std.mem.trimLeft(u8, fold_str, "x="), 10);
return Fold{ .x = x };
},
'y' => {
const y = try std.fmt.parseInt(isize, std.mem.trimLeft(u8, fold_str, "y="), 10);
return Fold{ .y = y };
},
else => return error.UnexpectedFoldDim,
}
}
};
const Instr = struct {
const Self = @This();
points: std.AutoHashMap(Point, void),
folds: std.ArrayList(Fold),
fn deinit(self: *Self) void {
self.points.deinit();
self.folds.deinit();
self.* = undefined;
}
fn parse(allocator: Allocator, input: []const u8) !Self {
var lines = std.mem.split(u8, input, "\n");
var points = std.AutoHashMap(Point, void).init(allocator);
var folds = std.ArrayList(Fold).init(allocator);
var parsing_folds = false;
while (lines.next()) |line| {
if (line.len == 0) {
parsing_folds = true;
continue;
}
if (parsing_folds) {
const fold = try Fold.parse(line);
try folds.append(fold);
} else {
const point = try Point.parse(line);
try points.put(point, .{});
}
}
return Instr{
.points = points,
.folds = folds,
};
}
};
fn part1(allocator: Allocator, instr: Instr) !usize {
var points = std.AutoHashMap(Point, void).init(allocator);
defer points.deinit();
const fold = instr.folds.items[0];
var it = instr.points.keyIterator();
while (it.next()) |point| {
switch (fold) {
.x => |x| {
if (point.x > x) {
try points.put(Point{
.x = 2 * x - point.x,
.y = point.y,
}, .{});
} else {
try points.put(point.*, .{});
}
},
.y => |y| {
if (point.y > y) {
try points.put(Point{
.x = point.x,
.y = 2 * y - point.y,
}, .{});
} else {
try points.put(point.*, .{});
}
},
}
}
return points.count();
}
fn part2(allocator: Allocator, instr: Instr) !void {
var points = try instr.points.clone();
defer points.deinit();
var next_points = std.AutoHashMap(Point, void).init(allocator);
defer next_points.deinit();
var bound_x: isize = std.math.maxInt(isize);
var bound_y: isize = std.math.maxInt(isize);
for (instr.folds.items) |fold| {
next_points.clearRetainingCapacity();
var it = points.keyIterator();
while (it.next()) |point| {
switch (fold) {
.x => |x| {
bound_x = std.math.min(bound_x, x);
if (point.x > x) {
try next_points.put(Point{
.x = 2 * x - point.x,
.y = point.y,
}, .{});
} else {
try next_points.put(point.*, .{});
}
},
.y => |y| {
bound_y = std.math.min(bound_y, y);
if (point.y > y) {
try next_points.put(Point{
.x = point.x,
.y = 2 * y - point.y,
}, .{});
} else {
try next_points.put(point.*, .{});
}
},
}
}
std.mem.swap(std.AutoHashMap(Point, void), &points, &next_points);
}
draw_points(bound_x, bound_y, points);
}
fn draw_points(bound_x: isize, bound_y: isize, points: std.AutoHashMap(Point, void)) void {
var y: isize = 0;
while (y <= bound_y) : (y += 1) {
var x: isize = 0;
while (x <= bound_x) : (x += 1) {
if (points.contains(Point{ .x = x, .y = y })) {
print("#", .{});
} else {
print(".", .{});
}
}
print("\n", .{});
}
}
test "folding paper" {
const input =
\\6,10
\\0,14
\\9,10
\\0,3
\\10,4
\\4,11
\\6,0
\\6,12
\\4,1
\\0,13
\\10,12
\\3,4
\\3,0
\\8,4
\\1,10
\\2,14
\\8,10
\\9,0
\\
\\fold along y=7
\\fold along x=5
;
const allocator = std.testing.allocator;
var instr = try Instr.parse(allocator, input[0..]);
defer instr.deinit();
try std.testing.expectEqual(@as(usize, 17), try part1(allocator, instr));
}
|
src/day13.zig
|
const std = @import("std");
const Parser = @import("main.zig").Parser;
pub fn main() void {
const json =
\\{
\\ "type": "FeatureCollection",
\\ "features": [{
\\ "type": "Feature",
\\ "geometry": {
\\ "type": "Point",
\\ "coordinates": [102.0, 0.5]
\\ },
\\ "properties": {
\\ "prop0": "value0"
\\ }
\\ }, {
\\ "type": "Feature",
\\ "geometry": {
\\ "type": "LineString",
\\ "coordinates": [
\\ [102.0, 0.0],
\\ [103.0, 1.0],
\\ [104.0, 0.0],
\\ [105.0, 1.0]
\\ ]
\\ },
\\ "properties": {
\\ "prop0": "value0",
\\ "prop1": 0.0
\\ }
\\ }, {
\\ "type": "Feature",
\\ "geometry": {
\\ "type": "Polygon",
\\ "coordinates": [
\\ [
\\ [100.0, 0.0],
\\ [101.0, 0.0],
\\ [101.0, 1.0],
\\ [100.0, 1.0],
\\ [100.0, 0.0]
\\ ]
\\ ]
\\ },
\\ "properties": {
\\ "prop0": "value0",
\\ "prop1": {
\\ "this": "that"
\\ }
\\ }
\\ }]
\\}
;
var geojson = Parser.parse(json, std.testing.allocator) catch |err| {
std.debug.warn("Could not parse geojson! {}", .{err});
return;
};
defer geojson.deinit();
// switch on the content if you don't already know the type
switch (geojson.content) {
.feature => |feature| std.debug.warn("It's a Feature!\n", .{}),
.feature_collection => |features| std.debug.warn("It's a FeatureCollection!\n", .{}),
.geometry => |geometry| std.debug.warn("It's a Geometry!\n", .{}),
}
// there are helper methods `featureCollection()`, `feature()`, and `geometry()`, returning optionals
if (geojson.featureCollection()) |collection| {
std.debug.warn("FeatureCollection contains {} features\n", .{collection.len});
for (collection) |feature, idx| {
std.debug.warn("{}: It's a {s} => ", .{ idx, @tagName(feature.geometry) });
switch (feature.geometry) {
.point => |value| std.debug.warn("[{d}, {d}]\n", .{ value[0], value[1] }),
.multi_point => |value| std.debug.warn("containing {} points\n", .{value.len}),
.line_string => |value| std.debug.warn("containing {} points\n", .{value.len}),
.multi_line_string => |value| std.debug.warn("containing {} lineStrings\n", .{value.len}),
.polygon => |value| std.debug.warn("containing {} rings\n", .{value.len}),
.multi_polygon => |value| std.debug.warn("containing {} polygons\n", .{value.len}),
.geometry_collection => |value| std.debug.warn("containing {} geometries\n", .{value.len}),
.@"null" => continue,
}
}
// accessing properties (safe)
const feature = collection[0];
if (feature.properties) |properties| {
if (properties.get("prop0")) |value| {
std.debug.warn("Property: 'prop0' => {}\n", .{value});
}
}
// or unsafe
const value = collection[1].properties.?.get("prop1").?;
std.debug.warn("Property: 'prop1' => {}\n", .{value});
}
}
|
src/example.zig
|
const std = @import("std");
const token = @import("../token.zig");
const ast = @import("../ast.zig");
const fieldNames = std.meta.fieldNames;
const eq = std.mem.eql;
const TokenError = token.TokenError;
const Token = token.Token;
const Kind = Token.Kind;
const Op = Token.Kind.Op;
const Tty = @import("./type.zig").@"Type";
const Block = @import("./block.zig").Block;
const Ast = ast.Ast;
pub const Kw = enum(u16) {
// PREFI qualifier ops
all = 0,
some,
any,
once,
ever,
only,
always,
not,
never,
when,
who,
what,
where,
with,
set = 25, //DECLARATTIONS KW START
type,
be,
put,
@"for",
@"init",
get,
have,
use,
@"return",
print,
let,
loop,
@"if",
@"else",
@"while",
case,
def,
do,
@"and" = 50, // START OF CONDITIONAL KW
@"or",
will,
as,
like,
does,
of,
on,
by,
in,
has,
to,
is,
can,
@"error" = 75, // START OF TYPE KW
err,
none,
maybe,
int,
@"enum",
@"class",
num,
rule,
bool,
tuple,
seq,
map,
range,
proc,
str,
float,
// TYPE DESCRIPTOR START
prop = 100,
point,
ref,
qual,
actual,
abstr,
local,
global,
this,
state,
data,
that,
so = 200, // MISC/UNASSIGNED KW START
out,
start,
end,
tst,
tbd,
// KW extenders
until,
const Self = @This();
pub fn isKw(input: []const u8) ?Kw {
inline for (@typeInfo(Kw).Enum.fields) |kword| {
if (std.mem.eql(u8, input, kword.name)) {
return @field(Kw, kword.name);
}
}
return null;
// return std.meta.stringToEnum(Kw, input);
}
// Redundant to have keyword + value types for float, etc.kwOp
// should just consume the keyword and the value in one tuple?
pub fn isType(kw: Kw) bool {
const idx = @enumToInt(kw);
return idx > 75 and idx < 100;
}
/// If keyword kw i(o s a verb in its postfix form, return true
/// if keyword kw
pub fn isPrefix(kw: Kw) bool {
const idx = @enumToInt(kw);
return idx < 50;
}
pub fn isInfix(kw: Kw) bool {
const idx = @enumToInt(kw);
return idx >= 50 and idx < 75;
}
pub const Declaration = struct {
name: []const u8,
pub fn fromKw(kw: Kw) ?Declaration {
switch (kw) {
.rule,
.range,
.attribute,
=> {},
else => null,
}
}
};
pub fn tOp(kword: Kw) []const u8 {
return @tagName(kword);
}
pub fn toType(kw: Kw) Kw {
// const idx = @enumToInt(kw);
return kw;
}
pub fn kwOp(kw: Kw) ?Op {
return switch (kw) {
Kw.@"or" => Op.@"or",
Kw.@"and" => Op.@"and",
.use => Op.use,
else => null,
};
}
pub fn toStr(k: Kw) []const u8 {
return @tagName(k);
}
pub fn toNode(kw: Kw) Ast.Node {
return Ast.Node.init(Token.initKind(Kind{ .kw = kw }));
}
};
pub const KwAttrs = struct {
verb: bool,
aliases: [][]const u8,
};
|
src/lang/token/kw.zig
|
const std = @import("std");
const print = std.debug.print;
const input_file = @embedFile("input.txt");
const BagRule = struct {
count: u32, color: []const u8
};
fn parseInput(allocator: *std.mem.Allocator) !std.StringHashMap([]BagRule) {
var bag_map = std.StringHashMap([]BagRule).init(allocator);
errdefer bag_map.deinit();
var input = std.mem.tokenize(input_file, "\n");
while (input.next()) |line| {
const delim = " bags contain";
const color_end_index = std.mem.indexOf(u8, line, delim).?;
const parent_color = line[0..color_end_index];
var rules = std.ArrayList(BagRule).init(allocator);
errdefer rules.deinit();
var child_iter = std.mem.split(line[(color_end_index + delim.len)..], " bag");
while (child_iter.next()) |child| {
var word_iter = std.mem.split(child, " ");
_ = word_iter.next(); // leading "" or "s," or "s." or "," or "."
if (word_iter.next()) |count_str| {
const count = std.fmt.parseUnsigned(u32, count_str, 10) catch continue;
const child_color = child[(word_iter.index.?)..];
try rules.append(BagRule{
.count = count,
.color = child_color,
});
}
}
try bag_map.put(parent_color, rules.toOwnedSlice());
}
return bag_map;
}
fn contains(bag_map: std.StringHashMap([]BagRule), parent: []const u8, target: []const u8) bool {
for (bag_map.get(parent).?) |child| {
if (std.mem.eql(u8, child.color, target) or contains(bag_map, child.color, target)) {
return true;
}
}
return false;
}
fn countChildren(bag_map: std.StringHashMap([]BagRule), parent: []const u8) u32 {
var count: u32 = 0;
for (bag_map.get(parent).?) |child| {
count += child.count * (countChildren(bag_map, child.color) + 1);
}
return count;
}
fn part1(bag_map: std.StringHashMap([]BagRule)) u32 {
var answer: u32 = 0;
var iter = bag_map.iterator();
while (iter.next()) |key_value| {
if (contains(bag_map, key_value.key, "shiny gold")) answer += 1;
}
return answer;
}
fn part2(bag_map: std.StringHashMap([]BagRule)) u32 {
return countChildren(bag_map, "shiny gold");
}
pub fn main() !void {
var gpa = std.heap.GeneralPurposeAllocator(.{}){};
defer _ = gpa.deinit();
var arena = std.heap.ArenaAllocator.init(&gpa.allocator);
defer arena.deinit();
var bag_map = try parseInput(&arena.allocator);
print("part 1: {}\n", .{part1(bag_map)});
print("part 2: {}\n", .{part2(bag_map)});
}
|
2020/07/main.zig
|
const mecha = @import("mecha");
const std = @import("std");
const event = std.event;
const fs = std.fs;
const heap = std.heap;
const log = std.log;
const Message = @import("../message.zig").Message;
pub fn mem(channel: *event.Channel(Message)) void {
const loop = event.Loop.instance.?;
const cwd = fs.cwd();
// On my system, `cat /proc/meminfo | wc -c` gives 1419, so this buffer
// should be enough to hold all data read from meminfo.
var buf: [1024 * 10]u8 = undefined;
var fba = heap.FixedBufferAllocator.init("");
while (true) {
const content = cwd.readFile("/proc/meminfo", &buf) catch |err| {
log.warn("Failed to read /proc/meminfo: {}", .{err});
continue;
};
const result = parser(&fba.allocator, content) catch |_| {
log.warn("Error while parsing /proc/meminfo", .{});
continue;
};
channel.put(.{
.mem = .{
.total = result.value.mem_total,
.free = result.value.mem_free,
.available = result.value.mem_available,
},
});
loop.sleep(std.time.ns_per_s);
}
}
pub const Mem = struct {
mem_total: usize,
mem_free: usize,
mem_available: usize,
buffers: usize,
cached: usize,
swap_cached: usize,
active: usize,
inactive: usize,
active_anon: usize,
inactive_anon: usize,
active_file: usize,
inactive_file: usize,
unevictable: usize,
mlocked: usize,
swap_total: usize,
swap_free: usize,
dirty: usize,
writeback: usize,
anon_pages: usize,
mapped: usize,
shmem: usize,
kreclaimable: usize,
slab: usize,
sreclaimable: usize,
sunreclaim: usize,
kernel_stack: usize,
page_tables: usize,
nfs_unstable: usize,
bounce: usize,
writeback_tmp: usize,
commit_limit: usize,
committed_as: usize,
vmalloc_total: usize,
vmalloc_used: usize,
vmalloc_chunk: usize,
percpu: usize,
hardware_corrupted: usize,
anon_huge_pages: usize,
shmem_huge_pages: usize,
shmem_pmd_mapped: usize,
file_huge_pages: usize,
file_pmd_mapped: usize,
cma_total: usize,
cma_free: usize,
huge_pages_total: usize,
huge_pages_free: usize,
huge_pages_rsvd: usize,
huge_pages_surp: usize,
hugepagesize: usize,
hugetlb: usize,
direct_map4k: usize,
direct_map2m: usize,
direct_map1g: usize,
};
const parser = blk: {
@setEvalBranchQuota(1000000000);
break :blk mecha.map(Mem, mecha.toStruct(Mem), mecha.combine(.{
field("MemTotal"),
field("MemFree"),
field("MemAvailable"),
field("Buffers"),
field("Cached"),
field("SwapCached"),
field("Active"),
field("Inactive"),
field("Active(anon)"),
field("Inactive(anon)"),
field("Active(file)"),
field("Inactive(file)"),
field("Unevictable"),
field("Mlocked"),
field("SwapTotal"),
field("SwapFree"),
field("Dirty"),
field("Writeback"),
field("AnonPages"),
field("Mapped"),
field("Shmem"),
field("KReclaimable"),
field("Slab"),
field("SReclaimable"),
field("SUnreclaim"),
field("KernelStack"),
field("PageTables"),
field("NFS_Unstable"),
field("Bounce"),
field("WritebackTmp"),
field("CommitLimit"),
field("Committed_AS"),
field("VmallocTotal"),
field("VmallocUsed"),
field("VmallocChunk"),
field("Percpu"),
field("HardwareCorrupted"),
field("AnonHugePages"),
field("ShmemHugePages"),
field("ShmemPmdMapped"),
field("FileHugePages"),
field("FilePmdMapped"),
field("CmaTotal"),
field("CmaFree"),
field("HugePages_Total"),
field("HugePages_Free"),
field("HugePages_Rsvd"),
field("HugePages_Surp"),
field("Hugepagesize"),
field("Hugetlb"),
field("DirectMap4k"),
field("DirectMap2M"),
field("DirectMap1G"),
}));
};
fn field(comptime name: []const u8) mecha.Parser(usize) {
return mecha.combine(.{
mecha.string(name ++ ":"),
mecha.discard(mecha.many(mecha.ascii.char(' '), .{ .collect = false })),
mecha.int(usize, .{}),
mecha.discard(mecha.opt(mecha.string(" kB"))),
mecha.ascii.char('\n'),
});
}
|
src/producer/mem.zig
|
const std = @import("std");
const args_parser = @import("args");
const zigimg = @import("img");
const qoi = @import("qoi.zig");
const total_rounds = 8;
pub fn main() !u8 {
const allocator = std.heap.c_allocator; // for perf
var cli = args_parser.parseForCurrentProcess(struct {}, allocator, .print) catch return 1;
defer cli.deinit();
var total_raw_size: u64 = 0;
var total_png_size: u64 = 0;
var total_qoi_size: u64 = 0;
var total_decode_time: u64 = 0;
var total_encode_time: u64 = 0;
std.debug.print(
"File Name\tWidth\tHeight\tTotal Raw Bytes\tTotal PNG Bytes\tPNG Compression\tTotal QOI Bytes\tQOI Compression\tQOI to PNG\tDecode Time (ns)\tEncode Time (ns)\n",
.{},
);
for (cli.positionals) |folder_name| {
var folder = try std.fs.cwd().openDir(folder_name, .{ .iterate = true });
defer folder.close();
var iterator = folder.iterate();
while (try iterator.next()) |entry| {
if (entry.kind != .File) {
continue;
}
const ext = std.fs.path.extension(entry.name);
if (!std.mem.eql(u8, ext, ".png"))
continue;
var file = try folder.openFile(entry.name, .{});
defer file.close();
const png_size = (try file.stat()).size;
var raw_image = try zigimg.Image.fromFile(allocator, &file);
defer raw_image.deinit();
var image = qoi.Image{
.width = std.math.cast(u32, raw_image.width) catch continue,
.height = std.math.cast(u32, raw_image.height) catch continue,
.colorspace = .sRGB,
.pixels = try allocator.alloc(qoi.Color, raw_image.width * raw_image.height),
};
defer image.deinit(allocator);
{
var index: usize = 0;
var pixels = raw_image.iterator();
while (pixels.next()) |pix| {
const rgba8 = pix.toIntegerColor8();
image.pixels[index] = .{
.r = rgba8.R,
.g = rgba8.G,
.b = rgba8.B,
.a = rgba8.A,
};
index += 1;
}
std.debug.assert(image.pixels.len == index);
}
const reference_qoi = try qoi.encodeBuffer(allocator, image.asConst());
defer allocator.free(reference_qoi);
const decode_time = try performBenchmark(false, reference_qoi, image.asConst());
const encode_time = try performBenchmark(true, reference_qoi, image.asConst());
const raw_size = @sizeOf(qoi.Color) * image.pixels.len;
const qoi_size = reference_qoi.len;
total_raw_size += raw_size;
total_qoi_size += qoi_size;
total_png_size += png_size;
total_decode_time += decode_time;
total_encode_time += encode_time;
const png_rel_size = @intToFloat(f32, png_size) / @intToFloat(f32, raw_size);
const qoi_rel_size = @intToFloat(f32, qoi_size) / @intToFloat(f32, raw_size);
const png_to_qoi_diff = qoi_rel_size / png_rel_size;
std.debug.print("{s}/{s}\t{}\t{}\t{}\t{}\t{d:3.2}\t{}\t{d:3.2}\t{d}\t{}\t{}\n", .{
folder_name,
entry.name,
image.width,
image.height,
raw_size,
png_size,
png_rel_size,
qoi_size,
qoi_rel_size,
png_to_qoi_diff,
decode_time,
encode_time,
});
}
}
std.debug.print("total sum\t0\t0\t{}\t{}\t{d:3.2}\t{}\t{d:3.2}\t{d}\t{}\t{}\n", .{
total_raw_size,
total_png_size,
@intToFloat(f32, total_png_size) / @intToFloat(f32, total_raw_size),
total_qoi_size,
@intToFloat(f32, total_qoi_size) / @intToFloat(f32, total_raw_size),
@intToFloat(f32, total_qoi_size) / @intToFloat(f32, total_png_size),
total_decode_time,
total_encode_time,
});
return 0;
}
fn performBenchmark(comptime test_encoder: bool, qoi_data: []const u8, reference_image: qoi.ConstImage) !u64 {
const allocator = std.heap.c_allocator;
var total_time: u64 = 0;
var rounds: usize = total_rounds;
while (rounds > 0) {
rounds -= 1;
var start_point: i128 = undefined;
var end_point: i128 = undefined;
if (test_encoder) {
start_point = std.time.nanoTimestamp();
const memory = try qoi.encodeBuffer(allocator, reference_image);
defer allocator.free(memory);
end_point = std.time.nanoTimestamp();
if (!std.mem.eql(u8, qoi_data, memory))
return error.EncodingError;
} else {
start_point = std.time.nanoTimestamp();
var image = try qoi.decodeBuffer(allocator, qoi_data);
defer image.deinit(allocator);
end_point = std.time.nanoTimestamp();
if (image.width != reference_image.width or image.height != reference_image.height)
return error.DecodingError;
if (!std.mem.eql(u8, std.mem.sliceAsBytes(reference_image.pixels), std.mem.sliceAsBytes(image.pixels)))
return error.DecodingError;
}
total_time += @intCast(u64, end_point - start_point);
}
return total_time / total_rounds;
}
|
src/bench-files.zig
|
const std = @import("std");
const mem = std.mem;
const math = std.math;
const common = @import("common.zig");
const instruction = @import("instruction.zig");
const opcode = @import("opcode.zig");
const Function = @import("function.zig").Function;
const Module = @import("module.zig").Module;
const Store = @import("store.zig").ArrayListStore;
const Memory = @import("memory.zig").Memory;
const Table = @import("table.zig").Table;
const Global = @import("global.zig").Global;
const Interpreter = @import("interpreter.zig").Interpreter;
const ArrayList = std.ArrayList;
const Instruction = @import("function.zig").Instruction;
const InterpreterOptions = struct {
frame_stack_size: comptime_int = 1024,
label_stack_size: comptime_int = 1024,
operand_stack_size: comptime_int = 1024,
};
// Instance
//
// An Instance represents the runtime instantiation of a particular module.
//
// It contains:
// - a copy of the module it is an instance of
// - a pointer to the Store shared amongst modules
// - `memaddrs`: a set of addresses in the store to map a modules
// definitions to those in the store
// - `tableaddrs`: as per `memaddrs` but for tables
// - `globaladdrs`: as per `memaddrs` but for globals
pub const Instance = struct {
module: Module,
store: *Store,
funcaddrs: ArrayList(usize),
memaddrs: ArrayList(usize),
tableaddrs: ArrayList(usize),
globaladdrs: ArrayList(usize),
pub fn init(alloc: *mem.Allocator, store: *Store, module: Module) Instance {
return Instance{
.module = module,
.store = store,
.funcaddrs = ArrayList(usize).init(alloc),
.memaddrs = ArrayList(usize).init(alloc),
.tableaddrs = ArrayList(usize).init(alloc),
.globaladdrs = ArrayList(usize).init(alloc),
};
}
pub fn instantiate(self: *Instance, index: usize) !void {
if (self.module.decoded == false) return error.ModuleNotDecoded;
try self.instantiateImports();
try self.instantiateFunctions(index);
try self.instantiateGlobals();
try self.instantiateMemories();
try self.instantiateTables();
try self.checkData();
try self.checkElements();
try self.instantiateData();
try self.instantiateElements();
if (self.module.start) |start_function| {
try self.invokeStart(start_function, .{});
}
}
fn instantiateImports(self: *Instance) !void {
for (self.module.imports.list.items) |import| {
const import_handle = try self.store.import(import.module, import.name, import.desc_tag);
switch (import.desc_tag) {
.Func => try self.funcaddrs.append(import_handle),
.Mem => try self.memaddrs.append(import_handle),
.Table => try self.tableaddrs.append(import_handle),
.Global => try self.globaladdrs.append(import_handle),
}
}
}
fn instantiateFunctions(self: *Instance, index: usize) !void {
// Initialise (internal) functions
//
// We have two possibilities:
// 1. the function is imported
// 2. the function is defined in this module (i.e. there is an associatd code section)
//
// In the case of 1 we need to check that the type of import matches the type
// of the actual function in the store
//
// For 2, we need to add the function to the store
const imported_function_count = self.funcaddrs.items.len;
for (self.module.functions.list.items) |function_def, i| {
if (function_def.import) |_| {
// Check that the function defintion (which this module expects)
// is the same as the function in the store
const func_type = self.module.types.list.items[function_def.typeidx];
const external_function = try self.getFunc(i);
switch (external_function) {
.function => |ef| {
if (!Module.signaturesEqual(ef.params, ef.results, func_type)) {
return error.ImportedFunctionTypeSignatureDoesNotMatch;
}
},
.host_function => |hef| {
if (!Module.signaturesEqual(hef.params, hef.results, func_type)) {
return error.ImportedFunctionTypeSignatureDoesNotMatch;
}
},
}
} else {
// TODO: clean this up
const code = self.module.codes.list.items[i - imported_function_count];
const func = self.module.functions.list.items[i];
const func_type = self.module.types.list.items[func.typeidx];
const handle = try self.store.addFunction(Function{
.function = .{
.start = code.start,
.required_stack_space = code.required_stack_space,
.locals_count = code.locals_count,
.params = func_type.params,
.results = func_type.results,
.instance = index,
},
});
// Need to do this regardless of if import or internal
try self.funcaddrs.append(handle);
}
}
}
fn instantiateGlobals(self: *Instance) !void {
// 2. Initialise globals
for (self.module.globals.list.items) |global_def, i| {
if (global_def.import != null) {
const imported_global = try self.getGlobal(i);
if (imported_global.mutability != global_def.mutability) return error.MismatchedMutability;
} else {
const value = if (global_def.start) |start| try self.invokeExpression(start, u64, .{}) else 0;
const handle = try self.store.addGlobal(Global{
.value = value,
.mutability = global_def.mutability,
.value_type = global_def.value_type,
});
try self.globaladdrs.append(handle);
}
}
}
fn instantiateMemories(self: *Instance) !void {
// 3a. Initialise memories
for (self.module.memories.list.items) |mem_size, i| {
if (mem_size.import != null) {
const imported_mem = try self.getMemory(i);
if (!common.limitMatch(imported_mem.min, imported_mem.max, mem_size.min, mem_size.max)) return error.ImportedMemoryNotBigEnough;
} else {
const handle = try self.store.addMemory(mem_size.min, mem_size.max);
try self.memaddrs.append(handle);
}
}
}
fn instantiateTables(self: *Instance) !void {
// 3b. Initialise tables
for (self.module.tables.list.items) |table_size, i| {
if (table_size.import != null) {
const imported_table = try self.getTable(i);
if (!common.limitMatch(imported_table.min, imported_table.max, table_size.min, table_size.max)) return error.ImportedTableNotBigEnough;
} else {
const handle = try self.store.addTable(table_size.min, table_size.max);
try self.tableaddrs.append(handle);
}
}
}
fn checkData(self: *Instance) !void {
// 4a. Check all data
for (self.module.datas.list.items) |data| {
const handle = self.memaddrs.items[data.index];
const memory = try self.store.memory(handle);
const offset = try self.invokeExpression(data.start, u32, .{});
try memory.check(offset, data.data);
}
}
fn checkElements(self: *Instance) !void {
// 4b. Check all elements
for (self.module.elements.list.items) |segment| {
const table = try self.getTable(segment.index);
const offset = try self.invokeExpression(segment.start, u32, .{});
if ((try math.add(u32, offset, segment.count)) > table.size()) return error.OutOfBoundsMemoryAccess;
}
}
fn instantiateData(self: *Instance) !void {
// 5a. Mutate all data
for (self.module.datas.list.items) |data| {
const handle = self.memaddrs.items[data.index];
const memory = try self.store.memory(handle);
const offset = try self.invokeExpression(data.start, u32, .{});
try memory.copy(offset, data.data);
}
}
fn instantiateElements(self: *Instance) !void {
// 5b. If all our elements were good, initialise them
for (self.module.elements.list.items) |segment| {
const table = try self.getTable(segment.index);
const offset = try self.invokeExpression(segment.start, u32, .{});
var data = segment.data;
var j: usize = 0;
while (j < segment.count) : (j += 1) {
const value = try opcode.readULEB128Mem(u32, &data);
try table.set(@intCast(u32, offset + j), try self.funcHandle(value));
}
}
}
pub fn getFunc(self: *Instance, index: usize) !Function {
if (index >= self.funcaddrs.items.len) return error.FunctionIndexOutOfBounds;
const handle = self.funcaddrs.items[index];
return try self.store.function(handle);
}
pub fn funcHandle(self: *Instance, index: usize) !usize {
if (index >= self.funcaddrs.items.len) return error.FunctionIndexOutOfBounds;
return self.funcaddrs.items[index];
}
// Lookup a memory in store via the modules index
pub fn getMemory(self: *Instance, index: usize) !*Memory {
// TODO: with a verified program we shouldn't need to check this
if (index >= self.memaddrs.items.len) return error.MemoryIndexOutOfBounds;
const handle = self.memaddrs.items[index];
return try self.store.memory(handle);
}
pub fn getTable(self: *Instance, index: usize) !*Table {
// TODO: with a verified program we shouldn't need to check this
if (index >= self.tableaddrs.items.len) return error.TableIndexOutOfBounds;
const handle = self.tableaddrs.items[index];
return try self.store.table(handle);
}
pub fn getGlobal(self: *Instance, index: usize) !*Global {
if (index >= self.globaladdrs.items.len) return error.GlobalIndexOutOfBounds;
const handle = self.globaladdrs.items[index];
return try self.store.global(handle);
}
// invoke
//
// Similar to invoke, but without some type checking
pub fn invoke(self: *Instance, name: []const u8, in: []u64, out: []u64, comptime options: InterpreterOptions) !void {
// 1.
const index = try self.module.getExport(.Func, name);
if (index >= self.module.functions.list.items.len) return error.FuncIndexExceedsTypesLength;
const function = try self.getFunc(index);
var frame_stack: [options.frame_stack_size]Interpreter.Frame = [_]Interpreter.Frame{undefined} ** options.frame_stack_size;
var label_stack: [options.label_stack_size]Interpreter.Label = [_]Interpreter.Label{undefined} ** options.label_stack_size;
var op_stack: [options.operand_stack_size]u64 = [_]u64{0} ** options.operand_stack_size;
switch (function) {
.function => |f| {
const function_instance = try self.store.instance(f.instance);
if (f.params.len != in.len) return error.ParamCountMismatch;
if (f.results.len != out.len) return error.ResultCountMismatch;
// 6. set up our stacks
var interp = Interpreter.init(op_stack[0..], frame_stack[0..], label_stack[0..], try self.store.instance(f.instance));
const locals_start = interp.op_ptr;
// 7b. push params
for (in) |arg| {
try interp.pushOperand(u64, arg);
}
// 7c. push (i.e. make space for) locals
var i: usize = 0;
while (i < f.locals_count) : (i += 1) {
try interp.pushOperand(u64, 0);
}
// Check we have enough stack space
try interp.checkStackSpace(f.required_stack_space);
// 7a. push control frame
try interp.pushFrame(Interpreter.Frame{
.op_stack_len = locals_start,
.label_stack_len = interp.label_ptr,
.return_arity = f.results.len,
.inst = function_instance,
}, f.locals_count + f.params.len);
// 7a.2. push label for our implicit function block. We know we don't have
// any code to execute after calling invoke, but we will need to
// pop a Label
try interp.pushLabel(Interpreter.Label{
.return_arity = f.results.len,
.op_stack_len = locals_start,
.branch_target = 0,
});
// 8. Execute our function
try interp.invoke(f.start);
// 9.
for (out) |_, out_index| {
out[out_index] = interp.popOperand(u64);
}
},
.host_function => |host_func| {
var interp = Interpreter.init(op_stack[0..], frame_stack[0..], label_stack[0..], self);
try host_func.func(&interp);
},
}
}
pub fn invokeStart(self: *Instance, index: u32, comptime options: InterpreterOptions) !void {
const function = try self.getFunc(index);
var frame_stack: [options.frame_stack_size]Interpreter.Frame = [_]Interpreter.Frame{undefined} ** options.frame_stack_size;
var label_stack: [options.label_stack_size]Interpreter.Label = [_]Interpreter.Label{undefined} ** options.label_stack_size;
var op_stack: [options.operand_stack_size]u64 = [_]u64{0} ** options.operand_stack_size;
switch (function) {
.function => |f| {
const function_instance = try self.store.instance(f.instance);
var interp = Interpreter.init(op_stack[0..], frame_stack[0..], label_stack[0..], try self.store.instance(f.instance));
const locals_start = interp.op_ptr;
var i: usize = 0;
while (i < f.locals_count) : (i += 1) {
try interp.pushOperand(u64, 0);
}
// Check we have enough stack space
try interp.checkStackSpace(f.required_stack_space);
try interp.pushFrame(Interpreter.Frame{
.op_stack_len = locals_start,
.label_stack_len = interp.label_ptr,
.return_arity = 0,
.inst = function_instance,
}, f.locals_count);
try interp.pushLabel(Interpreter.Label{
.return_arity = 0,
.op_stack_len = locals_start,
.branch_target = 0,
});
try interp.invoke(f.start);
},
.host_function => |host_func| {
var interp = Interpreter.init(op_stack[0..], frame_stack[0..], label_stack[0..], self);
try host_func.func(&interp);
},
}
}
pub fn invokeExpression(self: *Instance, start: usize, comptime Result: type, comptime options: InterpreterOptions) !Result {
var frame_stack: [options.frame_stack_size]Interpreter.Frame = [_]Interpreter.Frame{undefined} ** options.frame_stack_size;
var label_stack: [options.label_stack_size]Interpreter.Label = [_]Interpreter.Label{undefined} ** options.label_stack_size;
var op_stack: [options.operand_stack_size]u64 = [_]u64{0} ** options.operand_stack_size;
var interp = Interpreter.init(op_stack[0..], frame_stack[0..], label_stack[0..], self);
const locals_start = interp.op_ptr;
try interp.pushFrame(Interpreter.Frame{
.op_stack_len = locals_start,
.label_stack_len = interp.label_ptr,
.return_arity = 1,
.inst = self,
}, 0);
try interp.pushLabel(Interpreter.Label{
.return_arity = 1,
.op_stack_len = locals_start,
});
try interp.invoke(start);
switch (Result) {
u64 => return interp.popAnyOperand(),
else => return interp.popOperand(Result),
}
}
};
|
src/instance.zig
|
const std = @import("std");
const upaya = @import("../upaya.zig");
pub const Tilemap = struct {
w: usize,
h: usize,
layers: []Layer,
current_layer: usize = 0,
pub const Layer = struct {
name: []const u8,
data: []u8,
pub fn init(name: []const u8, size: usize) Layer {
var layer = Layer{
.name = upaya.mem.allocator.dupeZ(u8, name) catch unreachable,
.data = upaya.mem.allocator.alloc(u8, size) catch unreachable,
};
layer.clear();
return layer;
}
pub fn deinit(self: Layer) void {
for (self.layers) |layer| {
upaya.mem.allocator.free(layer.data);
upaya.mem.allocator.free(layer.name);
}
}
pub fn clear(self: Layer) void {
std.mem.set(u8, self.data, 0);
}
};
pub fn init(width: usize, height: usize) Tilemap {
var map = Tilemap{
.w = width,
.h = height,
.layers = upaya.mem.allocator.alloc(Layer, 1) catch unreachable,
};
map.layers[0] = Layer.init("Layer 1", map.w * map.h);
return map;
}
pub fn initWithData(data: []const u8, width: usize, height: usize) Tilemap {
return .{
.w = width,
.h = height,
.data = std.mem.dupe(upaya.mem.allocator, u8, data) catch unreachable,
};
}
pub fn deinit(self: Tilemap) void {
upaya.mem.allocator.free(self.data);
}
pub fn addLayer(self: *Tilemap) void {
self.layers = upaya.mem.allocator.realloc(self.layers, self.layers.len + 1) catch unreachable;
self.layers[self.layers.len - 1] = Layer.init("Layer", self.w * self.h);
}
pub fn rotate(self: *Tilemap) void {
var rotated = upaya.mem.allocator.alloc(u8, self.data.len) catch unreachable;
var y: usize = 0;
while (y < self.h) : (y += 1) {
var x: usize = 0;
while (x < self.w) : (x += 1) {
rotated[y + x * self.h] = self.data[x + y * self.w];
}
}
std.testing.allocator.free(self.data);
self.data = rotated;
std.mem.swap(usize, &self.w, &self.h);
}
pub fn print(self: Tilemap) void {
var y: usize = 0;
while (y < self.h) : (y += 1) {
var x: usize = 0;
while (x < self.w) : (x += 1) {
std.debug.print("{}, ", .{self.data[x + y * self.w]});
}
std.debug.print("\n", .{});
}
std.debug.print("\n", .{});
}
pub fn getTile(self: Tilemap, x: usize, y: usize) u8 {
if (x > self.w or y > self.h) {
return 0;
}
return self.layers[self.current_layer].data[x + y * self.w];
}
pub fn setTile(self: Tilemap, x: usize, y: usize, value: u8) void {
self.layers[self.current_layer].data[x + y * self.w] = value;
}
};
|
src/tilemaps/tilemap.zig
|
const build_options = @import("build_options");
const std = @import("std");
const fs = std.fs;
const log = std.log;
const mem = std.mem;
const DotEnv = @import("dotenv.zig").DotEnv;
const utils = @import("utils.zig");
const fatal = utils.fatal;
pub const Release = struct {
boot_script: []const u8,
boot_script_clean: []const u8,
command: []const u8,
cookie: []const u8,
distribution: []const u8,
erts_vsn: []const u8,
extra: []const u8,
mode: []const u8,
name: []const u8,
node: []const u8,
prog: []const u8,
remote_vm_args: []const u8,
root: []const u8,
sys_config: []const u8,
tmp: []const u8,
vm_args: []const u8,
vsn: []const u8,
vsn_dir: []const u8,
};
// TODO: handle possibility of RUNTIME_CONFIG=true in `sys.config`
pub fn init(allocator: std.mem.Allocator, prog: []const u8, command: []const u8) !Release {
const release_root = try fs.path.resolve(allocator, &[_][]const u8{ try fs.selfExeDirPathAlloc(allocator), "../" });
// read erts and release versions from /releases/start_erl.data
const start_erl_data = try utils.read(allocator, &[_][]const u8{ release_root, "releases/start_erl.data" }, 128);
var split = mem.split(u8, start_erl_data, " ");
const erts_vsn = split.next() orelse fatal("failed to read erts version", .{});
const release_vsn = split.next() orelse fatal("failed to read release version", .{});
const release_vsn_dir = try fs.path.join(allocator, &[_][]const u8{ release_root, "releases", release_vsn });
// load values from .env.<command> or .env in release version directory
const dotenv_command = try std.fmt.allocPrint(allocator, ".env.{s}", .{command});
const dotenv_command_path = try fs.path.join(allocator, &[_][]const u8{ release_vsn_dir, dotenv_command });
const dotenv_path = try fs.path.join(allocator, &[_][]const u8{ release_vsn_dir, ".env" });
var dotenv: DotEnv = DotEnv.init(allocator);
defer dotenv.deinit();
if (fs.cwd().openFile(dotenv_command_path, .{})) |file| {
defer file.close();
const bytes_read = try file.reader().readAllAlloc(allocator, 1_000_000);
try dotenv.parse(bytes_read);
// TODO: print that the .env file is busted and provide some context
} else |_| {
if (fs.cwd().openFile(dotenv_path, .{})) |file| {
defer file.close();
const bytes_read = try file.reader().readAllAlloc(allocator, 1_000_000);
try dotenv.parse(bytes_read);
// TODO: print that the .env file is busted and provide some context
} else |_| {
log.debug(".env not found", .{});
}
}
// zig fmt: off
const default_release_cookie = try utils.read(allocator, &[_][]const u8{ release_root, "releases", "COOKIE" }, 128);
const default_release_tmp = try fs.path.join(allocator, &[_][]const u8{ release_root, "tmp" });
const default_release_vm_args = try fs.path.join(allocator, &[_][]const u8{ release_vsn_dir, "vm.args" });
const default_remote_vm_args = try fs.path.join(allocator, &[_][]const u8{ release_vsn_dir, "remote.vm.args" });
const default_sys_config = try fs.path.join(allocator, &[_][]const u8{ release_vsn_dir, "sys" });
return Release{
.boot_script = try allocator.dupe(u8, getEnv(allocator, &dotenv.map, "RELEASE_BOOT_SCRIPT", "start")),
.boot_script_clean = try allocator.dupe(u8, getEnv(allocator, &dotenv.map, "RELEASE_BOOT_SCRIPT_CLEAN", "start_clean")),
.command = command,
.cookie = try allocator.dupe(u8, getEnv(allocator, &dotenv.map, "RELEASE_COOKIE", default_release_cookie)),
.distribution = try allocator.dupe(u8, getEnv(allocator, &dotenv.map, "RELEASE_DISTRIBUTION", "sname")),
.erts_vsn = erts_vsn,
.extra = "",
.mode = try allocator.dupe(u8, getEnv(allocator, &dotenv.map, "RELEASE_MODE", "embedded")),
.name = try allocator.dupe(u8, getEnv(allocator, &dotenv.map, "RELEASE_NAME", build_options.RELEASE_NAME)),
.node = try allocator.dupe(u8, getEnv(allocator, &dotenv.map, "RELEASE_NODE", build_options.RELEASE_NAME)),
.prog = prog,
.remote_vm_args = try allocator.dupe(u8, getEnv(allocator, &dotenv.map, "RELEASE_REMOTE_VM_ARGS", default_remote_vm_args)),
.root = release_root,
.sys_config = try allocator.dupe(u8, getEnv(allocator, &dotenv.map, "RELEASE_SYS_CONFIG", default_sys_config)),
.tmp = try allocator.dupe(u8, getEnv(allocator, &dotenv.map, "RELEASE_TMP", default_release_tmp)),
.vm_args = try allocator.dupe(u8, getEnv(allocator, &dotenv.map, "RELEASE_VM_ARGS", default_release_vm_args)),
.vsn = release_vsn,
.vsn_dir = release_vsn_dir,
};
// zig fmt: on
}
// get the value from the map or the environment or the provided default
fn getEnv(allocator: std.mem.Allocator, map: *std.BufMap, key: []const u8, default: []const u8) []const u8 {
if (map.get(key)) |value| {
return value;
} else {
return std.process.getEnvVarOwned(allocator, key) catch default;
}
}
|
src/release.zig
|
const builtin = @import("builtin");
const std = @import("index.zig");
const io = std.io;
const mem = std.mem;
const MH_MAGIC_64 = 0xFEEDFACF;
const MH_PIE = 0x200000;
const LC_SYMTAB = 2;
const MachHeader64 = packed struct {
magic: u32,
cputype: u32,
cpusubtype: u32,
filetype: u32,
ncmds: u32,
sizeofcmds: u32,
flags: u32,
reserved: u32,
};
const LoadCommand = packed struct {
cmd: u32,
cmdsize: u32,
};
const SymtabCommand = packed struct {
symoff: u32,
nsyms: u32,
stroff: u32,
strsize: u32,
};
const Nlist64 = packed struct {
n_strx: u32,
n_type: u8,
n_sect: u8,
n_desc: u16,
n_value: u64,
};
pub const Symbol = struct {
name: []const u8,
address: u64,
fn addressLessThan(lhs: *const Symbol, rhs: *const Symbol) bool {
return lhs.address < rhs.address;
}
};
pub const SymbolTable = struct {
allocator: *mem.Allocator,
symbols: []const Symbol,
strings: []const u8,
// Doubles as an eyecatcher to calculate the PIE slide, see loadSymbols().
// Ideally we'd use _mh_execute_header because it's always at 0x100000000
// in the image but as it's located in a different section than executable
// code, its displacement is different.
pub fn deinit(self: *SymbolTable) void {
self.allocator.free(self.symbols);
self.symbols = []const Symbol{};
self.allocator.free(self.strings);
self.strings = []const u8{};
}
pub fn search(self: *const SymbolTable, address: usize) ?*const Symbol {
var min: usize = 0;
var max: usize = self.symbols.len - 1; // Exclude sentinel.
while (min < max) {
const mid = min + (max - min) / 2;
const curr = &self.symbols[mid];
const next = &self.symbols[mid + 1];
if (address >= next.address) {
min = mid + 1;
} else if (address < curr.address) {
max = mid;
} else {
return curr;
}
}
return null;
}
};
pub fn loadSymbols(allocator: *mem.Allocator, in: *io.FileInStream) !SymbolTable {
var file = in.file;
try file.seekTo(0);
var hdr: MachHeader64 = undefined;
try readOneNoEof(in, MachHeader64, &hdr);
if (hdr.magic != MH_MAGIC_64) return error.MissingDebugInfo;
const is_pie = MH_PIE == (hdr.flags & MH_PIE);
var pos: usize = @sizeOf(@typeOf(hdr));
var ncmd: u32 = hdr.ncmds;
while (ncmd != 0) : (ncmd -= 1) {
try file.seekTo(pos);
var lc: LoadCommand = undefined;
try readOneNoEof(in, LoadCommand, &lc);
if (lc.cmd == LC_SYMTAB) break;
pos += lc.cmdsize;
} else {
return error.MissingDebugInfo;
}
var cmd: SymtabCommand = undefined;
try readOneNoEof(in, SymtabCommand, &cmd);
try file.seekTo(cmd.symoff);
var syms = try allocator.alloc(Nlist64, cmd.nsyms);
defer allocator.free(syms);
try readNoEof(in, Nlist64, syms);
try file.seekTo(cmd.stroff);
var strings = try allocator.alloc(u8, cmd.strsize);
errdefer allocator.free(strings);
try in.stream.readNoEof(strings);
var nsyms: usize = 0;
for (syms) |sym|
if (isSymbol(sym)) nsyms += 1;
if (nsyms == 0) return error.MissingDebugInfo;
var symbols = try allocator.alloc(Symbol, nsyms + 1); // Room for sentinel.
errdefer allocator.free(symbols);
var pie_slide: usize = 0;
var nsym: usize = 0;
for (syms) |sym| {
if (!isSymbol(sym)) continue;
const start = sym.n_strx;
const end = mem.indexOfScalarPos(u8, strings, start, 0).?;
const name = strings[start..end];
const address = sym.n_value;
symbols[nsym] = Symbol{ .name = name, .address = address };
nsym += 1;
if (is_pie and mem.eql(u8, name, "_SymbolTable_deinit")) {
pie_slide = @ptrToInt(SymbolTable.deinit) - address;
}
}
// Effectively a no-op, lld emits symbols in ascending order.
std.sort.insertionSort(Symbol, symbols[0..nsyms], Symbol.addressLessThan);
// Insert the sentinel. Since we don't know where the last function ends,
// we arbitrarily limit it to the start address + 4 KB.
const top = symbols[nsyms - 1].address + 4096;
symbols[nsyms] = Symbol{ .name = "", .address = top };
if (pie_slide != 0) {
for (symbols) |*symbol|
symbol.address += pie_slide;
}
return SymbolTable{
.allocator = allocator,
.symbols = symbols,
.strings = strings,
};
}
fn readNoEof(in: *io.FileInStream, comptime T: type, result: []T) !void {
return in.stream.readNoEof(@sliceToBytes(result));
}
fn readOneNoEof(in: *io.FileInStream, comptime T: type, result: *T) !void {
return readNoEof(in, T, (*[1]T)(result)[0..]);
}
fn isSymbol(sym: *const Nlist64) bool {
return sym.n_value != 0 and sym.n_desc == 0;
}
|
std/macho.zig
|
const flags_ = @import("../flags.zig");
const CreateFlags = flags_.CreateFlags;
const FieldFlagsDef = flags_.FieldFlagsDef;
// https://wiki.nesdev.com/w/index.php?title=PPU_registers
// slightly diverges from nesdev, the last char of flags 0 and 1 are made lowercase
pub fn RegisterMasks(comptime T: type) type {
return CreateFlags(T, ([_]FieldFlagsDef{
.{ .field = "ppu_ctrl", .flags = "VPHBSINn" },
.{ .field = "ppu_mask", .flags = "BGRsbMmg" },
.{ .field = "ppu_status", .flags = "VSO?????" },
})[0..]);
}
pub const Address = struct {
value: u15,
pub fn coarseX(self: Address) u5 {
return @truncate(u5, self.value);
}
pub fn coarseY(self: Address) u5 {
return @truncate(u5, self.value >> 5);
}
pub fn nametableSelect(self: Address) u2 {
return @truncate(u2, self.value >> 10);
}
pub fn fineY(self: Address) u3 {
return @truncate(u3, self.value >> 12);
}
pub fn fullY(self: Address) u8 {
return (@as(u8, self.coarseY()) << 3) | self.fineY();
}
};
pub const palette = [_]u32{
0x666666ff,
0x002a88ff,
0x1412a7ff,
0x3b00a4ff,
0x5c007eff,
0x6e0040ff,
0x6c0600ff,
0x561d00ff,
0x333500ff,
0x0b4800ff,
0x005200ff,
0x004f08ff,
0x00404dff,
0x000000ff,
0x000000ff,
0x000000ff,
0xadadadff,
0x155fd9ff,
0x4240ffff,
0x7527feff,
0xa01accff,
0xb71e7bff,
0xb53120ff,
0x994e00ff,
0x6b6d00ff,
0x388700ff,
0x0c9300ff,
0x008f32ff,
0x007c8dff,
0x000000ff,
0x000000ff,
0x000000ff,
0xfffeffff,
0x64b0ffff,
0x9290ffff,
0xc676ffff,
0xf36affff,
0xfe6eccff,
0xfe8170ff,
0xea9e22ff,
0xbcbe00ff,
0x88d800ff,
0x5ce430ff,
0x45e082ff,
0x48cddeff,
0x4f4f4fff,
0x000000ff,
0x000000ff,
0xfffeffff,
0xc0dfffff,
0xd3d2ffff,
0xe8c8ffff,
0xfbc2ffff,
0xfec4eaff,
0xfeccc5ff,
0xf7d8a5ff,
0xe4e594ff,
0xcfef96ff,
0xbdf4abff,
0xb3f3ccff,
0xb5ebf2ff,
0xb8b8b8ff,
0x000000ff,
0x000000ff,
};
|
src/ppu/common.zig
|
const builtin = @import("builtin");
const Os = builtin.Os;
const os = @import("index.zig");
const io = @import("../io.zig");
pub const UserInfo = struct.{
uid: u32,
gid: u32,
};
/// POSIX function which gets a uid from username.
pub fn getUserInfo(name: []const u8) !UserInfo {
return switch (builtin.os) {
Os.linux, Os.macosx, Os.ios => posixGetUserInfo(name),
else => @compileError("Unsupported OS"),
};
}
const State = enum.{
Start,
WaitForNextLine,
SkipPassword,
ReadUserId,
ReadGroupId,
};
// TODO this reads /etc/passwd. But sometimes the user/id mapping is in something else
// like NIS, AD, etc. See `man nss` or look at an strace for `id myuser`.
pub fn posixGetUserInfo(name: []const u8) !UserInfo {
var in_stream = try io.InStream.open("/etc/passwd", null);
defer in_stream.close();
var buf: [os.page_size]u8 = undefined;
var name_index: usize = 0;
var state = State.Start;
var uid: u32 = 0;
var gid: u32 = 0;
while (true) {
const amt_read = try in_stream.read(buf[0..]);
for (buf[0..amt_read]) |byte| {
switch (state) {
State.Start => switch (byte) {
':' => {
state = if (name_index == name.len) State.SkipPassword else State.WaitForNextLine;
},
'\n' => return error.CorruptPasswordFile,
else => {
if (name_index == name.len or name[name_index] != byte) {
state = State.WaitForNextLine;
}
name_index += 1;
},
},
State.WaitForNextLine => switch (byte) {
'\n' => {
name_index = 0;
state = State.Start;
},
else => continue,
},
State.SkipPassword => switch (byte) {
'\n' => return error.CorruptPasswordFile,
':' => {
state = State.ReadUserId;
},
else => continue,
},
State.ReadUserId => switch (byte) {
':' => {
state = State.ReadGroupId;
},
'\n' => return error.CorruptPasswordFile,
else => {
const digit = switch (byte) {
'0'...'9' => byte - '0',
else => return error.CorruptPasswordFile,
};
if (@mulWithOverflow(u32, uid, 10, *uid)) return error.CorruptPasswordFile;
if (@addWithOverflow(u32, uid, digit, *uid)) return error.CorruptPasswordFile;
},
},
State.ReadGroupId => switch (byte) {
'\n', ':' => {
return UserInfo.{
.uid = uid,
.gid = gid,
};
},
else => {
const digit = switch (byte) {
'0'...'9' => byte - '0',
else => return error.CorruptPasswordFile,
};
if (@mulWithOverflow(u32, gid, 10, *gid)) return error.CorruptPasswordFile;
if (@addWithOverflow(u32, gid, digit, *gid)) return error.CorruptPasswordFile;
},
},
}
}
if (amt_read < buf.len) return error.UserNotFound;
}
}
|
std/os/get_user_id.zig
|
const std = @import("std");
const elf = std.elf;
const arch = @import("./arch.zig");
const table = @import("../table-helper/table-helper.zig");
const SectionHeader = @import("./SectionHeader.zig");
//usingnamespace @import("./arch.zig");
const elfErrors = error{
CannotTellIfBinaryIs32or64bit,
};
pub const ELF = struct {
file: std.fs.File,
is32: bool,
path: []const u8,
symbols: std.StringHashMap(arch.Syms),
// got: std.StringHashMap(usize),
// plt: std.StringHashMap(usize),
// functions: std.StringHashMap(usize),
address: usize = 0x400000,
ehdr: arch.Ehdr,
shdrs: []arch.Shdr,
phdrs: []arch.Phdr,
relas: []arch.Rela,
//linker: []const u8,
//fill_gaps: bool = true,
const Self = @This();
pub fn init(path: []const u8, alloc: *std.mem.Allocator) !ELF {
var f = try openElf(path);
var is = try is32(f);
var ehdr = try ehdrParse(f, is);
var phdrs = try phdrParse(f, ehdr, alloc, is);
var shdrs = try shdrParse(f, ehdr, alloc, is);
var syms2 = try getSyms(f, alloc, is, shdrs);
return ELF{
.file = f,
.is32 = is,
.path = path,
.symbols = syms2,
.ehdr = ehdr,
.shdrs = shdrs,
.phdrs = phdrs,
};
}
};
pub fn ehdrParse(parse_source: anytype, isit32: bool) !arch.Ehdr {
try parse_source.seekableStream().seekTo(0x00);
if (!isit32) {
var ehdr: std.elf.Elf64_arch.Ehdr = undefined;
const stream = parse_source.reader();
try stream.readNoEof(std.mem.asBytes(&ehdr));
// return try parse_source.reader().readstruct(std.elf.elf64_ehdr);
return arch.Ehdr{
.identity = ehdr.e_ident,
.etype = ehdr.e_type,
.machine = ehdr.e_machine,
.version = ehdr.e_version,
.entry = ehdr.e_entry,
.phoff = ehdr.e_phoff,
.shoff = ehdr.e_shoff,
.flags = ehdr.e_flags,
.ehsize = ehdr.e_ehsize,
.phentsize = ehdr.e_phentsize,
.phnum = ehdr.e_phnum,
.shentsize = ehdr.e_shentsize,
.shnum = ehdr.e_shnum,
.shstrndx = ehdr.e_shstrndx,
};
} else {
var ehdr: std.elf.Elf32_arch.Ehdr = undefined;
const stream = parse_source.reader();
try stream.readNoEof(std.mem.asBytes(&ehdr));
// return try parse_source.reader().readstruct(std.elf.elf64_ehdr);
return arch.Ehdr{
.identity = ehdr.e_ident,
.etype = ehdr.e_type,
.machine = ehdr.e_machine,
.version = ehdr.e_version,
.entry = ehdr.e_entry,
.phoff = ehdr.e_phoff,
.shoff = ehdr.e_shoff,
.flags = ehdr.e_flags,
.ehsize = ehdr.e_ehsize,
.phentsize = ehdr.e_phentsize,
.phnum = ehdr.e_phnum,
.shentsize = ehdr.e_shentsize,
.shnum = ehdr.e_shnum,
.shstrndx = ehdr.e_shstrndx,
};
}
}
fn is32(parse_source: std.fs.File) !bool {
var ident: [std.elf.EI_NIDENT]u8 = undefined;
_ = try parse_source.read(ident[0..]);
if (ident[0x04] == 1) {
return true;
} else if (ident[0x04] == 2) {
return false;
} else {
return elfErrors.CannotTellIfBinaryIs32or64bit;
}
}
pub fn openElf(file: []const u8) !std.fs.File {
return std.fs.cwd().openFile(file, .{});
}
pub fn phdrParse(parse_source: std.fs.File, ehdr: arch.Ehdr, alloc: *std.mem.Allocator, Is32: bool) ![]arch.Phdr {
var list = std.ArrayList(arch.Phdr).init(alloc);
defer list.deinit();
if (Is32 == false) {
var phdr: elf.Elf64_arch.Phdr = undefined;
const stream = parse_source.reader();
var i: usize = 0;
while (i <= ehdr.phnum) : (i = i + 1) {
const offset = ehdr.phoff + @sizeOf(@TypeOf(phdr)) * i;
try parse_source.seekableStream().seekTo(offset);
try stream.readNoEof(std.mem.asBytes(&phdr));
var phdr1: arch.Phdr = undefined;
phdr1.ptype = phdr.p_type;
phdr1.flags = phdr.p_flags;
phdr1.offset = phdr.p_offset;
phdr1.vaddr = phdr.p_vaddr;
phdr1.paddr = phdr.p_paddr;
phdr1.filesz = phdr.p_filesz;
phdr1.memsz = phdr.p_memsz;
phdr1.palign = phdr.p_align;
try list.append(phdr1);
}
const a = std.mem.dupe(alloc, arch.Phdr, list.items);
return a;
} else {
var i: usize = 0;
var phdr: elf.Elf32_arch.Phdr = undefined;
const stream = parse_source.reader();
while (i <= ehdr.phnum) : (i = i + 1) {
const offset = ehdr.phoff + @sizeOf(@TypeOf(phdr)) * i;
try parse_source.seekableStream().seekTo(offset);
try stream.readNoEof(std.mem.asBytes(&phdr));
var phdr1: arch.Phdr = undefined;
phdr1.ptype = phdr.p_type;
phdr1.flags = phdr.p_flags;
phdr1.offset = phdr.p_offset;
phdr1.vaddr = phdr.p_vaddr;
phdr1.paddr = phdr.p_paddr;
phdr1.filesz = phdr.p_filesz;
phdr1.memsz = phdr.p_memsz;
phdr1.palign = phdr.p_align;
try list.append(phdr1);
}
const a = std.mem.dupe(alloc, arch.Phdr, list.items);
return a;
}
}
fn shdr_get_name_init(parse_source: anytype, ehdr: arch.Ehdr, shstrndx: u64, alloc: *std.mem.Allocator, Is32: bool) ![]const u8 {
if (!Is32) {
var shdr: std.elf.Elf64_arch.Shdr = undefined;
const buf = std.mem.asBytes(&shdr);
_ = try parse_source.preadAll(buf, ehdr.shoff + @sizeOf(std.elf.Elf64_arch.Shdr) * shstrndx);
const buffer = try alloc.alloc(u8, shdr.sh_size);
_ = try parse_source.preadAll(buffer, shdr.sh_offset);
return buffer;
} else {
var shdr: std.elf.Elf32_arch.Shdr = undefined;
const buf = std.mem.asBytes(&shdr);
_ = try parse_source.preadAll(buf, ehdr.shoff + @sizeOf(std.elf.Elf32_arch.Shdr) * shstrndx);
const buffer = try alloc.alloc(u8, shdr.sh_size);
_ = try parse_source.preadAll(buffer, shdr.sh_offset);
return buffer;
}
}
fn shdr_get_name(list: []const u8, offset: u64) []const u8 {
if (offset < list.len) {
const slice = list[offset..];
const len = std.mem.indexOf(u8, slice, "\x00") orelse 0;
return slice[0..len];
} else {
return "";
}
}
pub fn shdrParse(parse_source: std.fs.File, ehdr: arch.Ehdr, alloc: *std.mem.Allocator, Is32: bool) ![]arch.Shdr {
var list = std.ArrayList(arch.Shdr).init(alloc);
defer list.deinit();
const stream = parse_source.reader();
var section_strtab = try shdr_get_name_init(parse_source, ehdr, ehdr.shstrndx, alloc, Is32);
//try std.io.getStdOut().writer().print("{x}\n", .{std.fmt.fmtSliceHexLower(section_strtab[0..])});
var i: usize = 0;
if (Is32 == false) {
var shdr: elf.Elf64_arch.Shdr = undefined;
while (i < ehdr.shnum) : (i = i + 1) {
const offset = ehdr.shoff + @sizeOf(@TypeOf(shdr)) * i;
try parse_source.seekableStream().seekTo(offset);
try stream.readNoEof(std.mem.asBytes(&shdr));
var shdr1: arch.Shdr = undefined;
shdr1.name = shdr_get_name(section_strtab, shdr.sh_name);
shdr1.shtype = shdr.sh_type;
shdr1.offset = shdr.sh_offset;
shdr1.entsize = shdr.sh_entsize;
shdr1.addralign = shdr.sh_addralign;
shdr1.info = shdr.sh_info;
shdr1.link = shdr.sh_link;
shdr1.size = shdr.sh_size;
shdr1.addr = shdr.sh_addr;
shdr1.flags = shdr.sh_flags;
//var data = try alloc.alloc(u8, shdr.sh_size); //[shdr.sh_size]u8 = undefined;
//try parse_source.seekableStream().seekTo(shdr.sh_offset);
//_ = try parse_source.reader().read(data[0..]);
try list.append(shdr1);
}
return try alloc.dupe(arch.Shdr, list.items);
} else {
var shdr: elf.Elf32_arch.Shdr = undefined;
while (i < ehdr.shnum) : (i = i + 1) {
const offset = ehdr.shoff + @sizeOf(@TypeOf(shdr)) * i;
try parse_source.seekableStream().seekTo(offset);
try stream.readNoEof(std.mem.asBytes(&shdr));
var shdr1: arch.Shdr = undefined;
shdr1.name = shdr_get_name(section_strtab, shdr.sh_name);
shdr1.shtype = shdr.sh_type;
shdr1.offset = shdr.sh_offset;
shdr1.entsize = shdr.sh_entsize;
shdr1.addralign = shdr.sh_addralign;
shdr1.info = shdr.sh_info;
shdr1.link = shdr.sh_link;
shdr1.size = shdr.sh_size;
shdr1.addr = shdr.sh_addr;
shdr1.flags = shdr.sh_flags;
//var data = try alloc.alloc(u8, shdr.sh_size); //[shdr.sh_size]u8 = undefined;
//try parse_source.seekableStream().seekTo(shdr.sh_offset);
//_ = try parse_source.reader().read(data[0..]);
try list.append(shdr1);
}
return try alloc.dupe(arch.Shdr, list.items);
}
}
pub fn getSyms(parse_source: std.fs.File, alloc: *std.mem.Allocator, Is32: bool, ShdrArray: []arch.Shdr) !std.StringHashMap(arch.Syms) {
var symtabList = std.ArrayList(*arch.Shdr).init(alloc);
var strtab: ?*arch.Shdr = null;
const stream = parse_source.reader();
var dynstr: ?*arch.Shdr = null;
for (ShdrArray) |*section| {
if (section.shtype == SectionHeader.sh_type.SYMTAB or section.shtype == SectionHeader.sh_type.DYNSYM) {
try symtabList.append(section);
}
if (section.shtype == SectionHeader.sh_type.STRTAB and (std.mem.eql(u8, section.name, ".strtab"))) {
strtab = section;
}
if (section.shtype == SectionHeader.sh_type.STRTAB and (std.mem.eql(u8, section.name, ".dynstr"))) {
dynstr = section;
}
}
var list = std.StringHashMap(arch.Syms).init(alloc);
if (!Is32) {
for (symtabList.items) |section| {
var total_syms = section.size / @sizeOf(elf.Elf64_Sym);
try parse_source.seekableStream().seekTo(section.offset);
var sym: elf.Elf64_Sym = undefined; //[total_syms]elf.Elf64_Sym = undefined;
var i: usize = 0;
while (i <= total_syms - 1) : (i = i + 1) {
var curr_offset = section.offset + (@sizeOf(elf.Elf64_Sym) * i);
try parse_source.seekableStream().seekTo(curr_offset);
try stream.readNoEof(std.mem.asBytes(&sym));
//const sym = std.mem.bytesToValue(elf.Elf64_Sym, §ion_data[curr_offset .. curr_offset + @sizeOf(elf.Elf64_Sym)]);
var syms2: arch.Syms = undefined;
syms2.num = i;
syms2.value = sym.st_value;
syms2.size = sym.st_size;
syms2.symtype = switch (ELF32_ST_TYPE(sym.st_info)) {
0 => "NOTYPE",
1 => "OBJECT",
2 => "FUNC",
3 => "SECTION",
4 => "FILE",
6 => "TLS",
7 => "NUM",
10 => "LOOS",
12 => "HIOS",
else => "UNKNOWN",
};
syms2.bind = switch (ELF32_ST_BIND(sym.st_info)) {
0 => "LOCAL",
1 => "GLOBAL",
2 => "WEAK",
3 => "NUM",
10 => "UNIQUE",
12 => "HIOS",
13 => "LOPROC",
else => "UNKNOWN",
};
syms2.visibility = switch (ELF32_ST_VISIBILITY(sym.st_other)) {
0 => "DEFAULT",
1 => "INTERNAL",
2 => "HIDDEN",
3 => "PROTECTED",
else => "UNKNOWN",
};
syms2.index = try std.fmt.allocPrint(alloc, "0x{x}", .{sym.st_shndx});
syms2.name = blk: {
if (std.mem.eql(u8, section.shtype, "SYMTAB")) {
try parse_source.seekableStream().seekTo(strtab.?.offset + sym.st_name);
const c = (try stream.readUntilDelimiterOrEofAlloc(alloc, '\x00', 9000000000000000)) orelse "no name";
break :blk c;
} else {
try parse_source.seekableStream().seekTo(dynstr.?.offset + sym.st_name);
const c = (try stream.readUntilDelimiterOrEofAlloc(alloc, '\x00', 9000000000000000)) orelse "no name";
break :blk c;
}
};
syms2.section = section.name;
try list.put(syms2.name, syms2);
//try std.io.getStdOut().writer().print("{s}\n", .{syms2});
}
}
return list;
} else {
for (symtabList.items) |section| {
var total_syms = section.size / @sizeOf(elf.Elf32_Sym);
try parse_source.seekableStream().seekTo(section.offset);
var sym: elf.Elf32_Sym = undefined; //[total_syms]elf.Elf64_Sym = undefined;
var i: usize = 0;
while (i <= total_syms - 1) : (i = i + 1) {
var curr_offset = section.offset + (@sizeOf(elf.Elf32_Sym) * i);
try parse_source.seekableStream().seekTo(curr_offset);
try stream.readNoEof(std.mem.asBytes(&sym));
//const sym = std.mem.bytesToValue(elf.Elf64_Sym, §ion_data[curr_offset .. curr_offset + @sizeOf(elf.Elf64_Sym)]);
var syms2: arch.Syms = undefined;
syms2.num = i;
syms2.value = sym.st_value;
syms2.size = sym.st_size;
syms2.symtype = switch (ELF32_ST_TYPE(sym.st_info)) {
0 => "NOTYPE",
1 => "OBJECT",
2 => "FUNC",
3 => "SECTION",
4 => "FILE",
6 => "TLS",
7 => "NUM",
10 => "LOOS",
12 => "HIOS",
else => "UNKNOWN",
};
syms2.bind = switch (ELF32_ST_BIND(sym.st_info)) {
0 => "LOCAL",
1 => "GLOBAL",
2 => "WEAK",
3 => "NUM",
10 => "UNIQUE",
12 => "HIOS",
13 => "LOPROC",
else => "UNKNOWN",
};
syms2.visibility = switch (ELF32_ST_VISIBILITY(sym.st_other)) {
0 => "DEFAULT",
1 => "INTERNAL",
2 => "HIDDEN",
3 => "PROTECTED",
else => "UNKNOWN",
};
syms2.index = try std.fmt.allocPrint(alloc, "0x{x}", .{sym.st_shndx});
syms2.name = blk: {
if (std.mem.eql(u8, section.shtype, "SYMTAB")) {
try parse_source.seekableStream().seekTo(strtab.?.offset + sym.st_name);
const c = (try stream.readUntilDelimiterOrEofAlloc(alloc, '\x00', 9000000000000000)) orelse "no name";
break :blk c;
} else {
try parse_source.seekableStream().seekTo(dynstr.?.offset + sym.st_name);
const c = (try stream.readUntilDelimiterOrEofAlloc(alloc, '\x00', 9000000000000000)) orelse "no name";
break :blk c;
}
};
syms2.section = section.name;
try list.put(syms2.name, syms2);
//try std.io.getStdOut().writer().print("{s}\n", .{syms2});
}
}
return list;
}
}
pub fn ELF32_ST_BIND(val: u8) u8 {
return val >> 4;
}
pub fn ELF32_ST_TYPE(val: anytype) c_int {
return (@as(c_int, val) & @as(c_int, 0xf));
}
pub fn ELF32_ST_INFO(bind: anytype, type_1: anytype) c_int {
return (bind << @as(c_int, 4)) + (type_1 & @as(c_int, 0xf));
}
pub fn ELF32_ST_VISIBILITY(o: anytype) c_int {
return @as(c_int, o) & @as(c_int, 0x03);
}
pub fn getRela(parse_source: std.fs.File, alloc: *std.mem.Allocator, Is32: bool, shdrList: *[]arch.Shdr, dynsymlist: []arch.Syms) []arch.Rela {
var list = std.ArrayList(arch.Rela).init(alloc);
//defer list.deinit();
const stream = parse_source.reader();
for (shdrList) |*section| {
if (std.mem.eql(u8, section.shtype, "SHT_RELA")) {
if (!Is32) {
try parse_source.seekableStream().seekTo(section.offset);
var total_rela = section.size / @sizeOf(elf.Elf64_Rela);
var i: usize = 0;
while (i <= total_rela - 1) : (i = i + 1) {
var curr_offset = section.offset + (@sizeOf(elf.Elf64_Rela) * i);
try parse_source.seekableStream().seekTo(curr_offset);
var rela: elf.Elf64_Rela = undefined;
try stream.readNoEof(std.mem.asBytes(&rela));
var rela2: arch.Rela = undefined;
rela2.offset = rela.r_offset;
rela2.info = rela.r_info;
rela2.reltype = switch (rela.r_type) {
0 => "R_X86_64_NONE",
1 => "R_X86_64_64",
2 => "R_X86_64_PC32",
3 => "R_X86_64_GOT32",
4 => "R_X86_64_PLT32",
5 => "R_X86_64_COPY",
6 => "R_X86_64_GLOB_DAT",
7 => "R_X86_64_JUMP_SLOT",
8 => "R_X86_64_RELATIVE",
9 => "R_X86_64_GOTPCREL",
10 => "R_X86_64_32",
11 => "R_X86_64_32S",
12 => "R_X86_64_16",
13 => "R_X86_64_PC16",
14 => "R_X86_64_8",
15 => "R_X86_64_PC8",
16 => "R_X86_64_DTPMOD64",
17 => "R_X86_64_DTPOFF64",
18 => "R_X86_64_TPOFF64",
19 => "R_X86_64_TLSGD",
20 => "R_X86_64_TLSLD",
21 => "R_X86_64_DTPOFF32",
22 => "R_X86_64_GOTTPOFF",
23 => "R_X86_64_TPOFF32",
24 => "R_X86_64_PC64",
25 => "R_X86_64_GOTOFF64",
26 => "R_X86_64_GOTPC32",
27 => "R_X86_64_GOT64",
28 => "R_X86_64_GOTPCREL64",
29 => "R_X86_64_GOTPC64",
30 => "R_X86_64_GOTPLT64",
31 => "R_X86_64_PLTOFF64",
32 => "R_X86_64_SIZE32",
33 => "R_X86_64_SIZE64",
34 => "R_X86_64_GOTPC32_TLSDESC",
35 => "R_X86_64_TLSDESC_CALL",
36 => "R_X86_64_TLSDESC",
37 => "R_X86_64_IRELATIVE",
38 => "R_X86_64_RELATIVE64",
41 => "R_X86_64_GOTPCRELX",
42 => "R_X86_64_REX_GOTPCRELX",
43 => "R_X86_64_NUM",
};
rela2.symbol_name = blk: {
var symvalue = rela.r_sym();
var symbol = dynsymlist[symvalue].name;
break :blk symbol;
};
rela2.symbol_value = rela.r_sym();
rela2.section_name = dynsymlist[rela2.symbol_value].section;
try list.append(rela2);
}
} else {
try parse_source.seekableStream().seekTo(section.offset);
var total_rela = section.size / @sizeOf(elf.Elf32_Rela);
var i: usize = 0;
while (i <= total_rela - 1) : (i = i + 1) {
var curr_offset = section.offset + (@sizeOf(elf.Elf32_Rela) * i);
try parse_source.seekableStream().seekTo(curr_offset);
var rela: elf.Elf32_Rela = undefined;
try stream.readNoEof(std.mem.asBytes(&rela));
var rela2: arch.Rela = undefined;
rela2.offset = rela.r_offset;
rela2.info = rela.r_info;
rela2.reltype = switch (rela.r_type) {
0 => "R_386_NONE",
1 => "R_386_32",
2 => "R_386_PC32",
3 => "R_386_GOT32",
4 => "R_386_PLT32",
5 => "R_386_COPY",
6 => "R_386_GLOB_DAT",
7 => "R_386_JMP_SLOT",
8 => "R_386_RELATIVE",
9 => "R_386_GOTOFF",
10 => "R_386_GOTPC",
11 => "R_386_32PLT",
12 => "R_386_TLS_TPOFF",
13 => "R_386_TLS_IE",
14 => "R_386_TLS_GOTIE",
15 => "R_386_TLS_LE",
16 => "R_386_TLS_GD",
17 => "R_386_TLS_LDM",
18 => "R_386_16",
19 => "R_386_PC16",
20 => "R_386_8",
21 => "R_386_PC8",
22 => "R_386_TLS_GD_32",
23 => "R_386_TLS_GD_PUSH",
24 => "R_386_TLS_GD_CALL",
25 => "R_386_TLS_GD_POP",
26 => "R_386_TLS_LDM_32",
27 => "R_386_TLS_LDM_PUSH",
28 => "R_386_TLS_LDM_CALL",
29 => "R_386_TLS_LDM_POP",
30 => "R_386_TLS_LDO_32",
31 => "R_386_TLS_IE_32",
32 => "R_386_TLS_LE_32",
33 => "R_386_TLS_DTPMOD32",
34 => "R_386_TLS_DTPOFF32",
35 => "R_386_TLS_TPOFF32",
36 => "R_386_SIZE32",
37 => "R_386_TLS_GOTDESC",
38 => "R_386_TLS_DESC_CALL",
41 => "R_386_TLS_DESC",
42 => "R_386_IRELATIVE",
43 => "R_386_GOT32X",
44 => "R_386_NUM",
};
rela2.symbol_name = blk: {
var symvalue = rela.r_sym();
var symbol = dynsymlist[symvalue].name;
break :blk symbol;
};
rela2.symbol_value = rela.r_sym();
rela2.section_name = dynsymlist[rela2.symbol_value].section;
try list.append(rela2);
}
}
}
}
return list;
}
|
src/elf.zig
|
const std = @import("std");
const testing = std.testing;
const Allocator = std.mem.Allocator;
/// QueryParameters is an alias for a String HashMap
pub const QueryParameters = std.StringHashMap([]const u8);
/// Possible errors when parsing query parameters
const QueryError = error{ MalformedUrl, OutOfMemory, InvalidCharacter };
pub const Url = struct {
path: []const u8,
raw_path: []const u8,
raw_query: []const u8,
/// Builds a new URL from a given path
pub fn init(path: []const u8) Url {
const query = blk: {
var raw_query: []const u8 = undefined;
if (std.mem.indexOf(u8, path, "?")) |index| {
raw_query = path[index..];
} else {
raw_query = "";
}
break :blk raw_query;
};
return Url{
.path = path[0 .. path.len - query.len],
.raw_path = path,
.raw_query = query,
};
}
/// Builds query parameters from url's `raw_query`
/// Memory is owned by caller
/// Note: For now, each key/value pair needs to be freed manually
pub fn queryParameters(self: Url, allocator: *Allocator) QueryError!QueryParameters {
var queries = QueryParameters.init(allocator);
errdefer queries.deinit();
var query = self.raw_query;
if (std.mem.startsWith(u8, query, "?")) {
query = query[1..];
}
while (query.len > 0) {
var key = query;
if (std.mem.indexOfAny(u8, key, "&")) |index| {
query = key[index + 1 ..];
key = key[0..index];
} else {
query = "";
}
if (key.len == 0) continue;
var value: []const u8 = undefined;
if (std.mem.indexOfAny(u8, key, "=")) |index| {
value = key[index + 1 ..];
key = key[0..index];
}
key = try unescape(allocator, key);
errdefer allocator.free(key);
value = try unescape(allocator, value);
errdefer allocator.free(value);
try queries.put(key, value);
}
return queries;
}
};
/// Unescapes the given string literal by decoding the %hex number into ascii
/// memory is owned & freed by caller
fn unescape(allocator: *Allocator, value: []const u8) QueryError![]const u8 {
var perc_counter: usize = 0;
var has_plus: bool = false;
// find % and + symbols to determine buffer size
var i: usize = 0;
while (i < value.len) : (i += 1) {
switch (value[i]) {
'%' => {
perc_counter += 1;
if (i + 2 > value.len or !isHex(value[i + 1]) or !isHex(value[i + 2])) {
return QueryError.MalformedUrl;
}
i += 2;
},
'+' => {
has_plus = true;
},
else => {},
}
}
if (perc_counter == 0 and !has_plus) return value;
// replace url encoded string
var buffer = try allocator.alloc(u8, value.len - 2 * perc_counter);
errdefer allocator.free(buffer);
i = 0;
while (i < buffer.len) : (i += 1) {
switch (value[i]) {
'%' => {
const a = try std.fmt.charToDigit(value[i + 1], 16);
const b = try std.fmt.charToDigit(value[i + 2], 16);
buffer[i] = a << 4 | b;
i += 2;
},
'+' => buffer[i] = ' ',
else => buffer[i] = value[i],
}
}
return buffer;
}
/// Escapes a string by encoding symbols so it can be safely used inside an URL
fn escape(value: []const u8) []const u8 {
@compileError("TODO: Implement escape()");
}
/// Returns true if the given byte is heximal
fn isHex(c: u8) bool {
return switch (c) {
'0'...'9', 'a'...'f', 'A'...'F' => true,
else => false,
};
}
test "Basic raw query" {
const path = "/example?name=value";
const url: Url = Url.init(path);
testing.expectEqualSlices(u8, "?name=value", url.raw_query);
}
test "Retrieve query parameters" {
const path = "/example?name=value";
const url: Url = Url.init(path);
var query_params = try url.queryParameters(testing.allocator);
defer query_params.deinit();
testing.expect(query_params.contains("name"));
testing.expectEqualStrings("value", query_params.get("name") orelse " ");
}
|
src/url.zig
|
const std = @import("std");
const assert = std.debug.assert;
const allocator = std.heap.page_allocator;
const Computer = @import("./computer.zig").Computer;
pub const Pos = struct {
const OFFSET: usize = 10000;
x: usize,
y: usize,
pub fn init(x: usize, y: usize) Pos {
return Pos{
.x = x,
.y = y,
};
}
pub fn equal(self: Pos, other: Pos) bool {
return self.x == other.x and self.y == other.y;
}
};
pub const Map = struct {
cells: std.AutoHashMap(Pos, Tile),
computer: Computer,
robot_dir: Dir,
robot_tumbling: bool,
pcur: Pos,
pmin: Pos,
pmax: Pos,
pub const Dir = enum(u8) {
N = 1,
S = 2,
W = 3,
E = 4,
pub fn reverse(d: Dir) Dir {
return switch (d) {
Dir.N => Dir.S,
Dir.S => Dir.N,
Dir.W => Dir.E,
Dir.E => Dir.W,
};
}
pub fn move(p: Pos, d: Dir) Pos {
var q = p;
switch (d) {
Dir.N => q.y -= 1,
Dir.S => q.y += 1,
Dir.W => q.x -= 1,
Dir.E => q.x += 1,
}
return q;
}
pub fn turn(c: Dir, w: Dir) ?Turn {
var t: ?Turn = null;
switch (c) {
Dir.N => {
switch (w) {
Dir.N => t = null,
Dir.S => t = null,
Dir.W => t = Turn.L,
Dir.E => t = Turn.R,
}
},
Dir.S => {
switch (w) {
Dir.N => t = null,
Dir.S => t = null,
Dir.W => t = Turn.R,
Dir.E => t = Turn.L,
}
},
Dir.W => {
switch (w) {
Dir.N => t = Turn.R,
Dir.S => t = Turn.L,
Dir.W => t = null,
Dir.E => t = null,
}
},
Dir.E => {
switch (w) {
Dir.N => t = Turn.L,
Dir.S => t = Turn.R,
Dir.W => t = null,
Dir.E => t = null,
}
},
}
return t;
}
};
pub const Turn = enum(u8) {
L = 'L',
R = 'R',
};
pub const Tile = enum(u8) {
Empty = '.',
Scaffold = '#',
Robot = '*',
};
pub fn init() Map {
var self = Map{
.cells = std.AutoHashMap(Pos, Tile).init(allocator),
.computer = Computer.init(true),
.robot_dir = undefined,
.robot_tumbling = false,
.pcur = undefined,
.pmin = Pos.init(std.math.maxInt(usize), std.math.maxInt(usize)),
.pmax = Pos.init(0, 0),
};
return self;
}
pub fn deinit(self: *Map) void {
self.computer.deinit();
self.cells.deinit();
}
pub fn run_to_get_map(self: *Map) void {
var y: usize = 0;
var x: usize = 0;
main: while (true) {
self.computer.run();
while (true) {
const output = self.computer.getOutput();
// std.debug.warn("COMPUTER output {}\n",.{ output});
if (output == null) break;
var c = @intCast(u8, output.?);
if (c == '\n') {
if (x == 0) break :main;
y += 1;
x = 0;
continue;
}
if (c == '^') {
self.robot_dir = Dir.N;
c = '*';
}
if (c == 'v') {
self.robot_dir = Dir.S;
c = '*';
}
if (c == '<') {
self.robot_dir = Dir.W;
c = '*';
}
if (c == '>') {
self.robot_dir = Dir.E;
c = '*';
}
if (c == 'X') {
self.robot_tumbling = true;
c = '*';
}
const t = @intToEnum(Tile, c);
const p = Pos.init(x + Pos.OFFSET / 2, y + Pos.OFFSET / 2);
self.set_pos(p, t);
x += 1;
}
if (self.computer.halted) break;
}
}
pub fn walk(self: *Map, route: *std.ArrayList(u8)) usize {
var sum: usize = 0;
var seen = std.AutoHashMap(Pos, void).init(allocator);
var p: Pos = self.pcur;
var d: Dir = undefined;
var r: ?Dir = null;
while (true) {
var found: bool = false;
var j: u8 = 1;
while (j <= 4) : (j += 1) {
d = @intToEnum(Dir, j);
if (r != null and d == r.?) continue;
const n = Dir.move(p, d);
if (self.get_pos(n) == Tile.Scaffold) {
found = true;
p = n;
r = Dir.reverse(d);
break;
}
}
if (!found) break;
const t = Dir.turn(self.robot_dir, d);
if (t != null) {
// std.debug.warn("TURN from {} to {} => {}\n",.{ self.robot_dir, d, t.?});
const c = @enumToInt(t.?);
route.append(c) catch unreachable;
route.append(',') catch unreachable;
self.robot_dir = d;
}
// std.debug.warn("WALK 1 {} {}\n",.{ p.x - Pos.OFFSET / 2, p.y - Pos.OFFSET / 2});
if (seen.contains(p)) {
// std.debug.warn("CROSSING {} {}\n",.{ p.x, p.y});
const alignment = (p.x - Pos.OFFSET / 2) * (p.y - Pos.OFFSET / 2);
sum += alignment;
} else {
_ = seen.put(p, {}) catch unreachable;
}
var steps: usize = 1;
while (true) {
const n = Dir.move(p, d);
if (self.get_pos(n) != Tile.Scaffold) {
break;
}
p = n;
steps += 1;
// std.debug.warn("WALK 2 {} {}\n",.{ p.x - Pos.OFFSET / 2, p.y - Pos.OFFSET / 2});
if (seen.contains(p)) {
// std.debug.warn("CROSSING {} {}\n",.{ p.x, p.y});
const alignment = (p.x - Pos.OFFSET / 2) * (p.y - Pos.OFFSET / 2);
sum += alignment;
} else {
_ = seen.put(p, {}) catch unreachable;
}
}
// std.debug.warn("MOVE {} steps\n",.{ steps});
var str: [30]u8 = undefined;
const len = usizeToStr(steps, str[0..]);
var k: usize = len;
while (true) {
k -= 1;
route.append(str[k]) catch unreachable;
if (k == 0) break;
}
route.append(',') catch unreachable;
}
return sum;
}
pub fn program_and_run(self: *Map) i64 {
// TODO: found these "by hand" -- shameful!
const program =
\\C,B,B,A,A,C,C,B,B,A
\\R,12,R,4,L,6,L,8,L,8
\\R,12,R,4,L,12
\\L,12,R,4,R,4
\\n
;
var it = std.mem.split(u8, program, "\n");
while (it.next()) |line| {
var j: usize = 0;
while (j < line.len) : (j += 1) {
self.computer.enqueueInput(line[j]);
}
self.computer.enqueueInput('\n');
}
while (!self.computer.halted)
self.computer.run();
std.debug.warn("== PROGRAM OUTPUT ==\n", .{});
var dust: i64 = 0;
while (true) {
const result = self.computer.getOutput();
if (result == null) break;
if (result.? >= 0 and result.? < 256) {
const c = @intCast(u8, result.?);
std.debug.warn("{c}", .{c});
} else {
dust = result.?;
}
}
return dust;
}
pub fn split_route(self: *Map, route: []const u8) usize {
_ = self;
std.debug.warn("SPLIT {} bytes: [{}]\n", .{ route.len, route });
// var seen = std.StringHashMap(usize).init(allocator);
var j: usize = 0;
while (j < route.len) {
var commas: usize = 0;
var k: usize = j + 1;
while (k < route.len) : (k += 1) {
if (route[k] == ',') commas += 1;
if (commas >= 6) break;
}
const slice = route[j..k];
const top = route.len - slice.len;
var count: usize = 0;
// std.debug.warn("SLICE [{}] with {} bytes, top byte {}\n",.{ slice, slice.len, top});
k += 1;
while (k < top) : (k += 1) {
// std.debug.warn("CMP pos {}\n",.{ k});
if (std.mem.eql(u8, slice, route[k .. k + slice.len])) {
count += 1;
if (count == 1) {
std.debug.warn("SLICE #0 {} bytes at {}-{}: [{}]\n", .{ slice.len, j, j + slice.len, slice });
}
std.debug.warn("MATCH #{} {} bytes at {}-{}: [{}]\n", .{ count, slice.len, k, k + slice.len, slice });
}
}
commas = 0;
while (j < route.len) : (j += 1) {
if (route[j] == ',') commas += 1;
if (commas >= 2) break;
}
j += 1;
}
return 0;
}
fn usizeToStr(n: usize, str: []u8) usize {
var m: usize = n;
var p: usize = 0;
while (true) {
const d = @intCast(u8, m % 10);
m /= 10;
str[p] = d + '0';
p += 1;
if (m == 0) break;
}
return p;
}
pub fn get_pos(self: *Map, pos: Pos) Tile {
if (!self.cells.contains(pos)) {
return Tile.Empty;
}
return self.cells.get(pos).?;
}
pub fn set_pos(self: *Map, pos: Pos, mark: Tile) void {
_ = self.cells.put(pos, mark) catch unreachable;
if (self.pmin.x > pos.x) self.pmin.x = pos.x;
if (self.pmin.y > pos.y) self.pmin.y = pos.y;
if (self.pmax.x < pos.x) self.pmax.x = pos.x;
if (self.pmax.y < pos.y) self.pmax.y = pos.y;
if (mark == Tile.Robot) {
self.pcur = pos;
}
}
pub fn show(self: Map) void {
const sx = self.pmax.x - self.pmin.x + 1;
const sy = self.pmax.y - self.pmin.y + 1;
std.debug.warn("MAP: {} x {} - {} {} - {} {}\n", .{ sx, sy, self.pmin.x, self.pmin.y, self.pmax.x, self.pmax.y });
std.debug.warn("ROBOT: {} {}\n", .{ self.pcur.x, self.pcur.y });
var y: usize = self.pmin.y;
while (y <= self.pmax.y) : (y += 1) {
std.debug.warn("{:4} | ", .{y});
var x: usize = self.pmin.x;
while (x <= self.pmax.x) : (x += 1) {
const p = Pos.init(x, y);
const g = self.cells.get(p);
var t: u8 = ' ';
if (g != null) {
const c = g.?.value;
t = @enumToInt(c);
}
if (p.equal(self.pcur)) {
t = switch (self.robot_dir) {
Dir.N => '^',
Dir.S => 'v',
Dir.W => '<',
Dir.E => '>',
};
if (self.robot_tumbling) {
t = 'X';
}
}
std.debug.warn("{c}", .{t});
}
std.debug.warn("\n", .{});
}
}
};
test "find intersections and alignments" {
const data =
\\..#..........
\\..#..........
\\#######...###
\\#.#...#...#.#
\\#############
\\..#...#...#..
\\..#####...^..
;
var map = Map.init();
defer map.deinit();
var y: usize = 0;
var itl = std.mem.split(u8, data, "\n");
while (itl.next()) |line| : (y += 1) {
var x: usize = 0;
while (x < line.len) : (x += 1) {
const p = Pos.init(x + Pos.OFFSET / 2, y + Pos.OFFSET / 2);
var t: Map.Tile = Map.Tile.Empty;
if (line[x] == '#') t = Map.Tile.Scaffold;
if (line[x] == '^') {
t = Map.Tile.Robot;
map.pcur = p;
map.robot_dir = Map.Dir.N;
}
if (line[x] == 'v') {
t = Map.Tile.Robot;
map.pcur = p;
map.robot_dir = Map.Dir.S;
}
if (line[x] == '<') {
t = Map.Tile.Robot;
map.pcur = p;
map.robot_dir = Map.Dir.W;
}
if (line[x] == '>') {
t = Map.Tile.Robot;
map.pcur = p;
map.robot_dir = Map.Dir.E;
}
if (line[x] == 'X') {
t = Map.Tile.Robot;
map.pcur = p;
map.robot_tumbling = true;
}
map.set_pos(p, t);
}
}
var route = std.ArrayList(u8).init(allocator);
defer route.deinit();
const result = map.walk(&route);
assert(result == 76);
}
test "find correct route" {
const data =
\\#######...#####
\\#.....#...#...#
\\#.....#...#...#
\\......#...#...#
\\......#...###.#
\\......#.....#.#
\\^########...#.#
\\......#.#...#.#
\\......#########
\\........#...#..
\\....#########..
\\....#...#......
\\....#...#......
\\....#...#......
\\....#####......
;
var map = Map.init();
defer map.deinit();
var y: usize = 0;
var itl = std.mem.split(u8, data, "\n");
while (itl.next()) |line| : (y += 1) {
var x: usize = 0;
while (x < line.len) : (x += 1) {
const p = Pos.init(x + Pos.OFFSET / 2, y + Pos.OFFSET / 2);
var t: Map.Tile = Map.Tile.Empty;
if (line[x] == '#') t = Map.Tile.Scaffold;
if (line[x] == '^') {
t = Map.Tile.Robot;
map.pcur = p;
map.robot_dir = Map.Dir.N;
}
if (line[x] == 'v') {
t = Map.Tile.Robot;
map.pcur = p;
map.robot_dir = Map.Dir.S;
}
if (line[x] == '<') {
t = Map.Tile.Robot;
map.pcur = p;
map.robot_dir = Map.Dir.W;
}
if (line[x] == '>') {
t = Map.Tile.Robot;
map.pcur = p;
map.robot_dir = Map.Dir.E;
}
if (line[x] == 'X') {
t = Map.Tile.Robot;
map.pcur = p;
map.robot_tumbling = true;
}
map.set_pos(p, t);
}
}
var route = std.ArrayList(u8).init(allocator);
defer route.deinit();
_ = map.walk(&route);
const slice = route.toOwnedSlice();
const wanted = "R,8,R,8,R,4,R,4,R,8,L,6,L,2,R,4,R,4,R,8,R,8,R,8,L,6,L,2";
const wanted_comma = wanted ++ ",";
assert(std.mem.eql(u8, slice, wanted) or std.mem.eql(u8, slice, wanted_comma));
}
test "split program matches" {
const original = "L,12,R,4,R,4,R,12,R,4,L,12,R,12,R,4,L,12,R,12,R,4,L,6,L,8,L,8,R,12,R,4,L,6,L,8,L,8,L,12,R,4,R,4,L,12,R,4,R,4,R,12,R,4,L,12,R,12,R,4,L,12,R,12,R,4,L,6,L,8,L,8";
const main = "C,B,B,A,A,C,C,B,B,A";
const routines =
\\R,12,R,4,L,6,L,8,L,8
\\R,12,R,4,L,12
\\L,12,R,4,R,4
;
var j: usize = 0;
var routine: [3][]const u8 = undefined;
var itr = std.mem.split(u8, routines, "\n");
while (itr.next()) |line| : (j += 1) {
routine[j] = line;
}
var output: [original.len * 2]u8 = undefined;
var pos: usize = 0;
var itm = std.mem.split(u8, main, ",");
while (itm.next()) |name| {
const index = name[0] - 'A';
std.mem.copy(u8, output[pos..], routine[index]);
pos += routine[index].len;
std.mem.copy(u8, output[pos..], ",");
pos += 1;
}
assert(std.mem.eql(u8, original, output[0..original.len]));
}
|
2019/p17/map.zig
|
const std = @import("std");
const glfw = @import("zglfw");
const gl = @import("zgl");
pub fn main() anyerror!void {
var gpa_state = std.heap.GeneralPurposeAllocator(.{}){};
const gpa = &gpa_state.allocator;
{
var maj: i32 = undefined;
var min: i32 = undefined;
var rev: i32 = undefined;
glfw.getVersion(&maj, &min, &rev);
std.log.info("GLFW v{}.{}.{}", .{ maj, min, rev });
}
glfw.initHint(.CocoaChdirResources, false);
try glfw.init();
defer glfw.terminate();
glfw.windowHint(.ContextVersionMajor, 3);
glfw.windowHint(.ContextVersionMinor, 3);
glfw.windowHint(.OpenGLForwardCompat, 1);
glfw.windowHint(.CocoaRetinaFramebuffer, 1);
glfw.windowHint(.Samples, 4);
glfw.windowHint(.OpenGLProfile, @enumToInt(glfw.GLProfileAttribute.OpenglCoreProfile));
glfw.windowHint(.Resizable, 1);
var window = try glfw.createWindow(800, 640, "Fractal Test", null, null);
defer glfw.destroyWindow(window);
glfw.makeContextCurrent(window);
// glfw.swapInterval(1);
var program = try SimpleProgram.init(gpa, vertex_shader, fragment_shader);
defer program.deinit();
const vao = gl.VertexArray.gen();
defer vao.delete();
const vbo = gl.Buffer.gen();
defer vbo.delete();
vao.bind();
vbo.bind(.array_buffer);
gl.bufferData(.array_buffer, [2]gl.Float, &vertices, .static_draw);
// x, y
gl.enableVertexAttribArray(0);
gl.vertexAttribPointer(0, 2, .float, false, @intCast(i32, @sizeOf([2]gl.Float)), 0);
const uni_centerOffset = program.prog_handle.uniformLocation("centerOffset");
const uni_scaleFactor = program.prog_handle.uniformLocation("scaleFactor");
const uni_iters = program.prog_handle.uniformLocation("iters");
gl.bindVertexArray(.invalid);
gl.bindBuffer(.invalid, .array_buffer);
program.attach();
gl.uniform2f(uni_centerOffset, 0.5, 0.0);
gl.uniform2f(uni_scaleFactor, 1.25, 1);
gl.uniform1ui(uni_iters, 220);
vao.bind();
var time: u64 = 0;
var lastTime = glfw.getTime();
while (!glfw.windowShouldClose(window)) : (time += 1) {
var curTime = glfw.getTime();
if (glfw.getKey(window, glfw.Key.Escape) == glfw.KeyState.Press) {
glfw.setWindowShouldClose(window, true);
}
var w: c_int = undefined;
var h: c_int = undefined;
glfw.getFramebufferSize(window, &w, &h);
const ratio = @intToFloat(f32, w)/@intToFloat(f32, h);
gl.viewport(0, 0, @intCast(usize, w), @intCast(usize, h));
gl.clear(.{ .color = true });
const zoom = 1 + @intToFloat(gl.Float, time)/200;
gl.uniform2f(uni_scaleFactor, ratio / zoom, 1.0 / zoom);
gl.uniform2f(uni_centerOffset, 0.5 * 1.1 * zoom, -0.25 * zoom);
gl.drawArrays(.triangle_fan, 0, vertices.len);
glfw.pollEvents();
glfw.swapBuffers(window);
if (curTime - lastTime >= 1.0) {
var title_buf: [1024]u8 = undefined;
const title = std.fmt.bufPrintZ(&title_buf, "Fractal Test : FPS={}", .{time/@floatToInt(u64, curTime)}) catch unreachable;
glfw.setWindowTitle(window, title.ptr);
lastTime = curTime;
}
}
}
pub const SimpleProgram = struct {
prog_handle: gl.Program,
fn compile(alloc: *std.mem.Allocator, source: []const u8, shader_type: gl.ShaderType) !gl.Shader {
var shader = gl.Shader.create(shader_type);
shader.source(1, &source);
shader.compile();
if (shader.get(.compile_status) == 0) {
defer shader.delete();
const msg = try shader.getCompileLog(alloc);
defer alloc.free(msg);
std.log.emerg("Failed to compile shader (type={s})!\nError: {s}\n", .{ @tagName(shader_type), msg });
return error.ShaderCompileError;
}
return shader;
}
pub fn init(
alloc: *std.mem.Allocator,
vertex_shader_src: []const u8,
fragment_shader_src: []const u8,
) !SimpleProgram {
const vert_shader = try SimpleProgram.compile(alloc, vertex_shader_src, .vertex);
defer vert_shader.delete();
const frag_shader = try SimpleProgram.compile(alloc, fragment_shader_src, .fragment);
defer frag_shader.delete();
const prog = gl.Program.create();
prog.attach(vert_shader);
prog.attach(frag_shader);
prog.link();
if (prog.get(.link_status) == 0) {
defer prog.delete();
const msg = try prog.getCompileLog(alloc);
defer alloc.free(msg);
std.log.emerg("Error occured while linking shader program: {s}\n", .{msg});
return error.ShaderLinkError;
}
// prog.validate();
// if (prog.get(.validate_status) == 0) {
// const msg = try prog.getCompileLog(alloc);
// defer alloc.free(msg);
// std.log.emerg("Shader program could not be validated: {s}\n", .{msg});
// return error.ShaderInvalid;
// }
return SimpleProgram{ .prog_handle = prog };
}
pub fn deinit(self: *SimpleProgram) void {
self.prog_handle.delete();
self.prog_handle = .invalid;
}
pub fn attach(self: *const SimpleProgram) void {
self.prog_handle.use();
}
};
// zig fmt: off
const vertices = [_][2]gl.Float{
.{ -1.0, -1.0, },
.{ 1.0, -1.0, },
.{ 1.0, 1.0, },
.{ -1.0, 1.0, },
};
// zig fmt: on
const vertex_shader = @embedFile("./shaders/vertex.glsl");
const fragment_shader = @embedFile("./shaders/fragment.glsl");
|
src/main.zig
|
const std = @import("std");
const zlm = @import("zlm");
pub const c = @cImport(@cInclude("GLES3/gl3.h"));
// add to this as needed, there's a lot and i'd rather not list them all
pub const Feature = enum(c.GLenum) {
depth_test = c.GL_DEPTH_TEST,
cull_face = c.GL_CULL_FACE,
};
pub fn enable(feature: Feature) void {
c.glEnable(@enumToInt(feature));
}
pub const BufferBit = enum(c.GLenum) {
color = c.GL_COLOR_BUFFER_BIT,
depth = c.GL_DEPTH_BUFFER_BIT,
stencil = c.GL_STENCIL_BUFFER_BIT,
};
pub fn clear(bits: []const BufferBit) void {
var b: c.GLbitfield = 0;
for (bits) |bit| b |= @enumToInt(bit);
c.glClear(b);
}
pub fn clearColor(r: f32, g: f32, b: f32, a: f32) void {
c.glClearColor(r, g, b, a);
}
pub fn viewport(x: c_int, y: c_int, w: c_int, h: c_int) void {
c.glViewport(x, y, w, h);
}
fn checkSuccess(
allocator: *std.mem.Allocator,
object: c_uint,
status: c.GLenum,
getStatus: fn (c_uint, c.GLenum, *c_int) callconv(.C) void,
getInfoLog: fn (c_uint, c_int, ?*c_int, [*]u8) callconv(.C) void,
) bool {
var success: c_int = undefined;
getStatus(object, status, &success);
if (success == 0) {
var len: c_int = undefined;
getStatus(object, c.GL_INFO_LOG_LENGTH, &len);
const log = allocator.alloc(u8, @intCast(usize, len)) catch {
std.debug.print("shaders have errors <no memory to allocate error log>", .{});
return false;
};
defer allocator.free(log);
getInfoLog(object, len, null, log.ptr);
std.debug.print("shaders have errors\n{s}", .{log});
return false;
}
return true;
}
pub const ShaderType = enum(c_uint) {
vertex = c.GL_VERTEX_SHADER,
fragment = c.GL_FRAGMENT_SHADER,
};
pub const Shader = struct {
handle: c_uint,
pub fn init(shader_type: ShaderType) !Shader {
const handle = c.glCreateShader(@enumToInt(shader_type));
if (handle == 0) {
return error.InternalGLError;
}
return Shader{ .handle = handle };
}
pub fn deinit(self: Shader) void {
c.glDeleteShader(self.handle);
}
pub fn source(self: Shader, src: []const u8) void {
self.sourcesComptime(1, .{src});
}
pub fn sourcesComptime(self: Shader, comptime n: comptime_int, srcs: [n][]const u8) void {
var src_ptrs: [n][*]const u8 = undefined;
var lengths: [n]c_int = undefined;
for (srcs) |p, i| {
src_ptrs[i] = p.ptr;
lengths[i] = @intCast(c_int, p.len);
}
self.sources(&src_ptrs, &lengths);
}
pub fn sources(self: Shader, srcs: []const [*]const u8, lengths: []const c_int) void {
std.debug.assert(srcs.len == lengths.len);
c.glShaderSource(self.handle, @intCast(c_int, srcs.len), srcs.ptr, lengths.ptr);
}
pub fn compile(self: Shader, temp_allocator: *std.mem.Allocator) !void {
c.glCompileShader(self.handle);
if (!checkSuccess(temp_allocator, self.handle, c.GL_COMPILE_STATUS, c.glGetShaderiv, c.glGetShaderInfoLog)) {
return error.CompileError;
}
}
};
pub const Program = struct {
handle: c_uint,
pub fn init() !Program {
const handle = c.glCreateProgram();
if (handle == 0) {
return error.InternalGLError;
}
return Program{ .handle = handle };
}
pub fn deinit(self: Program) void {
c.glDeleteProgram(self.handle);
}
pub fn attach(self: Program, shader: Shader) void {
c.glAttachShader(self.handle, shader.handle);
}
pub fn link(self: Program, temp_allocator: *std.mem.Allocator) !void {
c.glLinkProgram(self.handle);
if (!checkSuccess(temp_allocator, self.handle, c.GL_LINK_STATUS, c.glGetProgramiv, c.glGetProgramInfoLog)) {
return error.LinkError;
}
}
pub fn use(self: Program) void {
c.glUseProgram(self.handle);
}
pub fn getUniformLocation(self: Program, name: [*:0]const u8) !c_int {
const location = c.glGetUniformLocation(self.handle, name);
if (location == -1) {
return error.NoSuchLocation;
}
return location;
}
pub fn uniform(location: c_int, value: anytype) void {
switch (@typeInfo(@TypeOf(value))) {
.Float => |ti| if (ti.bits <= 32) {
c.glUniform1f(location, value);
return;
},
.ComptimeFloat => {
c.glUniform1f(location, value);
return;
},
.Int => |ti| if ((ti.signedness == .unsigned and ti.bits <= 31) or ti.bits <= 32) {
c.glUniform1i(location, value);
return;
},
.ComptimeInt => {
c.glUniform1i(location, value);
return;
},
.Pointer, .Array => {
const ti = @typeInfo(@TypeOf(value));
if ((ti == .Pointer and ti.Pointer.size != .One and ti.Pointer.size != .Slice) or ti == .Array) {
@compileError("convert this to a slice before passing");
}
// TODO add slices of ints or floats, luckily we don't need those rn
},
else => {},
}
inline for (.{ "2", "3", "4" }) |t| {
const Vec = @field(zlm, "Vec" ++ t);
const vecFunc = @field(c, "glUniform" ++ t ++ "fv");
if (@TypeOf(value) == Vec) {
vecFunc(location, 1, @ptrCast([*]const f32, &value));
return;
} else if (@TypeOf(value) == []const Vec) {
vecFunc(location, @intCast(c_int, value.len), @ptrCast([*]const f32, value.ptr));
return;
}
const Mat = @field(zlm, "Mat" ++ t);
const matFunc = @field(c, "glUniformMatrix" ++ t ++ "fv");
if (@TypeOf(value) == Mat) {
matFunc(location, 1, 0, @ptrCast([*]const f32, &value));
return;
} else if (@TypeOf(value) == []const Mat) {
matFunc(location, @intCast(c_int, value.len), 0, @ptrCast([*]const f32, value.ptr));
return;
}
}
@compileError("unsupported type");
}
};
pub const PrimitiveMode = enum(c.GLenum) {
points = c.GL_POINTS,
line_strip = c.GL_LINE_STRIP,
line_loop = c.GL_LINE_LOOP,
lines = c.GL_LINES,
triangle_strip = c.GL_TRIANGLE_STRIP,
triangle_fan = c.GL_TRIANGLE_FAN,
triangles = c.GL_TRIANGLES,
};
fn BatchManagement(comptime T: type, comptime ctor: anytype, comptime dtor: anytype) type {
if (@sizeOf(T) != @sizeOf(c_uint)) {
@compileError("cannot use this mixin due to size mismatch");
}
return struct {
pub fn init() T {
return initComptime(1)[0];
}
pub fn initSlice(slice: []T) void {
ctor(@intCast(c_int, slice.len), @ptrCast([*]c_uint, slice.ptr));
}
pub fn initComptime(comptime count: comptime_int) [count]T {
var arr: [count]T = undefined;
initSlice(&arr);
return arr;
}
pub fn deinit(self: T) void {
deinitSlice(&.{self});
}
pub fn deinitSlice(slice: []const T) void {
dtor(@intCast(c_int, slice.len), @ptrCast([*]const c_uint, slice.ptr));
}
};
}
pub const VertexArray = struct {
handle: c_uint,
pub usingnamespace BatchManagement(VertexArray, c.glGenVertexArrays, c.glDeleteVertexArrays);
pub fn bind(self: VertexArray) void {
c.glBindVertexArray(self.handle);
}
pub fn draw(mode: PrimitiveMode, first: c_int, count: c_int) void {
c.glDrawArrays(@enumToInt(mode), first, count);
}
fn toGLType(comptime T: type) c.GLenum {
return switch (T) {
bool => c.GL_UNSIGNED_BYTE,
f16 => c.GL_HALF_FLOAT,
f32 => c.GL_FLOAT,
else => {
comptime var bits = 1;
inline while (bits <= 8) : (bits += 1) {
if (T == std.meta.Int(.unsigned, bits)) return c.GL_UNSIGNED_BYTE;
if (T == std.meta.Int(.signed, bits)) return c.GL_BYTE;
}
inline while (bits <= 16) : (bits += 1) {
if (T == std.meta.Int(.unsigned, bits)) return c.GL_UNSIGNED_SHORT;
if (T == std.meta.Int(.signed, bits)) return c.GL_SHORT;
}
inline while (bits <= 32) : (bits += 1) {
if (T == std.meta.Int(.unsigned, bits)) return c.GL_UNSIGNED_INT;
if (T == std.meta.Int(.signed, bits)) return c.GL_INT;
}
@compileError("cannot get GL type for this type");
},
};
}
fn attributeScalar(index: c_uint, amt: u3, stride: c_int, comptime F: type, pointer: ?*const c_void) void {
const gl_type = toGLType(F);
switch (gl_type) {
c.GL_HALF_FLOAT, c.GL_FLOAT => {
c.glVertexAttribPointer(index, amt, gl_type, 0, stride, pointer);
},
else => {
c.glVertexAttribIPointer(index, amt, gl_type, stride, pointer);
},
}
}
pub fn attribute(index: c_uint, comptime T: type, comptime field: []const u8) void {
const F = @TypeOf(@field(@as(T, undefined), field));
const stride = @sizeOf(T);
const pointer = @intToPtr(?*const c_void, @byteOffsetOf(T, field));
defer c.glEnableVertexAttribArray(index);
inline for (.{ "2", "3", "4" }) |t| {
const Vec = @field(zlm, "Vec" ++ t);
if (F == Vec) {
c.glVertexAttribPointer(index, t[0] - '0', c.GL_FLOAT, 0, stride, pointer);
return;
}
}
if (@typeInfo(F) == .Array) {
const ti = @typeInfo(F).Array;
if (ti.len >= 1 and ti.len <= 4) {
attributeScalar(index, @intCast(u3, ti.len), stride, ti.child, pointer);
return;
}
}
attributeScalar(index, 1, stride, F, pointer);
}
};
pub const BufferType = enum(c.GLenum) {
array = c.GL_ARRAY_BUFFER,
read = c.GL_COPY_READ_BUFFER,
write = c.GL_COPY_WRITE_BUFFER,
element_array = c.GL_ELEMENT_ARRAY_BUFFER,
pixel_pack = c.GL_PIXEL_PACK_BUFFER,
pixel_unpack = c.GL_PIXEL_UNPACK_BUFFER,
transform_feedback = c.GL_TRANSFORM_FEEDBACK_BUFFER,
uniform = c.GL_UNIFORM_BUFFER,
};
pub const BufferUsage = enum(c.GLenum) {
stream_draw = c.GL_STREAM_DRAW,
stream_read = c.GL_STREAM_READ,
stream_copy = c.GL_STREAM_COPY,
static_draw = c.GL_STATIC_DRAW,
static_read = c.GL_STATIC_READ,
static_copy = c.GL_STATIC_COPY,
dynamic_draw = c.GL_DYNAMIC_DRAW,
dynamic_read = c.GL_DYNAMIC_READ,
dynamic_copy = c.GL_DYNAMIC_COPY,
};
pub const Buffer = struct {
handle: c_uint,
pub usingnamespace BatchManagement(Buffer, c.glGenBuffers, c.glDeleteBuffers);
pub fn bind(self: Buffer, buffer_type: BufferType) void {
c.glBindBuffer(@enumToInt(buffer_type), self.handle);
}
pub fn data(buffer_type: BufferType, slice: anytype, usage: BufferUsage) void {
c.glBufferData(@enumToInt(buffer_type), @intCast(c_long, @sizeOf(@typeInfo(@TypeOf(slice)).Pointer.child) * slice.len), slice.ptr, @enumToInt(usage));
}
};
pub const TextureTarget = enum(c.GLenum) {
@"2d" = c.GL_TEXTURE_2D,
@"3d" = c.GL_TEXTURE_3D,
@"2d_array" = c.GL_TEXTURE_2D_ARRAY,
cube_map = c.GL_TEXTURE_CUBE_MAP,
};
pub const TextureMinFilter = enum(c_int) {
nearest = c.GL_NEAREST,
linear = c.GL_LINEAR,
nearest_mipmap_nearest = c.GL_NEAREST_MIPMAP_NEAREST,
linear_mipmap_nearest = c.GL_LINEAR_MIPMAP_NEAREST,
nearest_mipmap_linear = c.GL_NEAREST_MIPMAP_LINEAR,
linear_mipmap_linear = c.GL_LINEAR_MIPMAP_LINEAR,
};
pub const TextureMagFilter = enum(c_int) {
nearest = c.GL_NEAREST,
linear = c.GL_LINEAR,
};
pub const Texture = struct {
handle: c_uint,
pub usingnamespace BatchManagement(Texture, c.glGenTextures, c.glDeleteTextures);
pub fn bind(self: Texture, target: TextureTarget) void {
c.glBindTexture(@enumToInt(target), self.handle);
}
pub fn minFilter(target: TextureTarget, f: TextureMinFilter) void {
c.glTexParameteri(@enumToInt(target), c.GL_TEXTURE_MIN_FILTER, @enumToInt(f));
}
pub fn magFilter(target: TextureTarget, f: TextureMagFilter) void {
c.glTexParameteri(@enumToInt(target), c.GL_TEXTURE_MAG_FILTER, @enumToInt(f));
}
// TODO better abstraction
pub fn image2D(
target: TextureTarget,
lod: c_int,
internal_format: c_int,
width: c_int,
height: c_int,
format: c.GLenum,
pixel_type: c.GLenum,
data: [*]const u8,
) void {
c.glTexImage2D(@enumToInt(target), lod, internal_format, width, height, 0, format, pixel_type, data);
}
};
|
src/render/gl.zig
|
use @import("./4_0_tokenization.zig");
fn ParseAnPlusB(p: Parser) -> %AnPlusB {
var ab = AnPlusB{};
ab.parse(p, false);
ab;
}
const AnPlusB = struct {
a: i32,
b: i32,
pub fn string(self: &const AnPlusB) -> string {
a.string() + (if (b >= 0) "n+" else "n") + b.string()
}
fn parse(self: &AnPlusB, p: Parser, comptime have_plus: bool) -> %void {
// If we had a leading '+', do not consume whitespace, since it should be
// consumed in the switch below, causing an error.
if (!have_plus) {
skipWhitespace(p);
}
switch (consumeToken(p)) {
Token.Delim => |delim| {
if (have_plus or delim != '+')
return error.SyntaxError
else
self.parse(p, true) // recursive call indicating '+' was found
},
Token.Number => |n|
if (have_plus or n.is_number) {
return error.SyntaxError
} else {
self.a = 0;
self.b = n.num.i32(); // 0, <integer>
},
Token.Dimension => |d|
if (have_plus or d.is_number) {
return error.SyntaxError
} else {
// <n-dimension>
// <n-dimension> <signed-integer>
// <n-dimension> ['+' | '-'] <signless-integer>
// <ndash-dimension> <signless-integer>
// <ndashdigit-dimension>
self.a = d.num.i32();
self.parse_b("n-", d.unit.lower(), p);
},
Token.Ident => |ident|
const lower_ident = ident.lower();
// Start with those that start with a '-'
if ((%%ident[0]) == '-') {
if (have_plus) {
return error.SyntaxError
} else {
// -n
// -n <signed-integer>
// -n ['+' | '-'] <signless-integer>
// -n- <signless-integer>
// <dashndashdigit-ident>
self.a = -1;
self.parse_b("-n-", lower_ident, p);
}
} else switch (lower_ident) {
"odd" =>
if (have_plus) {
return error.SyntaxError;
} else {
self.a = 2;
self.b = 1;
},
"even" =>
if (have_plus) {
return error.SyntaxError;
} else {
self.a = 2;
self.b = 0;
},
else => {
// +?n
// +?n <signed-integer>
// +?n ['+' | '-'] <signless-integer>
// +?n- <signless-integer>
// +?<ndashdigit-ident>
self.a = 1;
self.parse_b("n-", lower_ident, p);
},
},
else =>
return error.SyntaxError,
}
skipWhitespace(p);
if (consumeToken(p) != Token.EOF) {
return error.SyntaxError;
}
}
// `pattern` is either "n-" or "-n-" and must begin the `s` string. If needed,
// the last `-` and its subsequent digits are parsed. Any failure means `None`.
fn parse_b(self: &AnPlusB, pattern: string, str: []u8, p: Parser) %void {
switch (str) {
"n", "-n" => return self.b_opt_signed_or_delim_signless_integer(p),
"n-", "-n-" => return self.b_signless_integer(true, p),
else =>
if (str.startsWith(pattern)) {
// Parse the remainder of `str` (including the '-') into an I32
self.b = str.substring(pattern.size().isize()-1).i32(10);
return;
},
}
error.SyntaxError;
}
// `b` is already known to be pos or neg, so this function just checks that the
// next-after-space token is a Number/Integer that start with a digit.
fn b_signless_integer(self: &AnPlusB, is_neg: bool, p: Parser) -> %void {
skipWhitespace(p);
switch (consumeToken(p)) {
Token.Number => |n|
if (!n.is_number and isDigit(%%n.repr[0])) { // [-+]<signless-integer>
self.b = (if (is_neg) -1 else 1) * n.num.i32());
return;
}
}
error.SyntaxError;
}
// `b` is optional (EOF), a signed Int or a +- Delim followed by a signless Int
fn b_opt_signed_or_delim_signless_integer(
self: &AnPlusB, p: Parser,
) -> %void {
skipWhitespace(p);
switch (consumeToken(p)) {
Token.EOF => {
self.b = 0; // a, 0
return;
},
Token.Number => |n|
if (!n.is_number) {
const c = %%n.repr[0];
if (c == '+' or c == '-') {
self.b = n.num.i32(); // a, <signed-integer>
return;
}
}
Token.Delim => |d|
if (d.delim == '+' or d.delim == '-') {
return self.b_signless_integer(d.delim == '-', p);
}
}
error.SyntaxError
}
}
|
parser/6_0_an_b_microsyntax.zig
|
const Self = @This();
const utils = @import("utils");
const Ansi = utils.AnsiEscProcessor;
pub const HexColor = Ansi.HexColor;
pub const Layer = Ansi.Layer;
row: u32 = undefined,
column: u32 = undefined,
width: u32 = undefined,
height: u32 = undefined,
ansi: Ansi = undefined,
utf32_buffer: [128]u32 = undefined,
utf8_to_utf32: utils.Utf8ToUtf32 = undefined,
place_impl: fn(console: *Self, utf32_value: u32, row: u32, col: u32) void,
scroll_impl: fn(console: *Self) void,
set_hex_color_impl: fn(console: *Self, color: HexColor, layer: Layer) void,
get_hex_color_impl: fn(console: *Self, layer: Layer) HexColor,
reset_attributes_impl: fn(console: *Self) void,
move_cursor_impl: fn(console: *Self, row: u32, col: u32) void,
show_cursor_impl: fn(console: *Self, show: bool) void,
clear_screen_impl: fn(console: *Self) void,
pub fn init(self: *Self, width: u32, height: u32) void {
self.width = width;
self.height = height;
self.ansi = .{
.print_char = ansi_print_char,
.newline = ansi_newline,
.backspace = ansi_backspace,
.hex_color = ansi_hex_color,
.invert_colors = ansi_invert_colors,
.reset_attributes = ansi_reset_attributes,
.reset_terminal = ansi_reset_terminal,
.move_cursor = ansi_move_cursor,
.show_cursor = ansi_show_cursor,
};
self.utf8_to_utf32 = .{.input = undefined, .buffer = self.utf32_buffer[0..]};
self.reset_terminal();
}
/// Takes a UTF8/ANSI escape code byte
pub fn print(self: *Self, byte: u8) void {
self.ansi.feed_char(byte);
}
pub fn print_utf8(self: *Self, utf8_value: u8) void {
self.utf8_to_utf32.input = @ptrCast([*]const u8, &utf8_value)[0..1];
for (self.utf8_to_utf32.next() catch @panic("UTF-8 Console Failure")) |utf32_value| {
self.print_utf32(utf32_value);
}
}
pub fn print_utf32(self: *Self, utf32_value: u32) void {
if ((self.column + 1) > self.width) {
self.newline();
}
self.place(utf32_value, self.row, self.column);
self.move_cursor(self.row, self.column + 1);
}
pub fn place(self: *Self, utf32_value: u32, row: u32, col: u32) void {
self.place_impl(self, utf32_value, row, col);
}
pub fn ansi_print_char(ansi: *Ansi, char: u8) void {
const self = @fieldParentPtr(Self, "ansi", ansi);
self.print_utf8(char);
}
pub fn newline(self: *Self) void {
if (self.row == (self.height - 1)) {
self.scroll_impl(self);
} else {
self.row += 1;
}
self.move_cursor(self.row, 0);
}
pub fn ansi_newline(ansi: *Ansi) void {
const self = @fieldParentPtr(Self, "ansi", ansi);
self.newline();
}
pub fn backspace(self: *Self) void {
var row = self.row;
var col = self.column;
if (col == 0 and row > 0) {
col = self.width - 1;
row -= 1;
} else {
col -= 1;
}
self.move_cursor(row, col);
self.place(' ', self.row, self.column);
}
pub fn ansi_backspace(ansi: *Ansi) void {
const self = @fieldParentPtr(Self, "ansi", ansi);
self.backspace();
}
pub fn set_hex_color(self: *Self, color: HexColor, layer: Layer) void {
self.set_hex_color_impl(self, color, layer);
}
pub fn ansi_hex_color(ansi: *Ansi, color: HexColor, layer: Layer) void {
const self = @fieldParentPtr(Self, "ansi", ansi);
self.set_hex_color(color, layer);
}
pub fn set_hex_colors(self: *Self, fg: HexColor, bg: HexColor) void {
self.set_hex_color(fg, .Foreground);
self.set_hex_color(bg, .Background);
}
pub fn get_hex_color(self: *Self, layer: Layer) HexColor {
return self.get_hex_color_impl(self, layer);
}
pub fn invert_colors(self: *Self) void {
const fg = self.get_hex_color(.Foreground);
const bg = self.get_hex_color(.Background);
self.set_hex_colors(bg, fg);
}
pub fn ansi_invert_colors(ansi: *Ansi) void {
const self = @fieldParentPtr(Self, "ansi", ansi);
self.invert_colors();
}
pub fn reset_attributes(self: *Self) void {
self.reset_attributes_impl(self);
}
pub fn ansi_reset_attributes(ansi: *Ansi) void {
const self = @fieldParentPtr(Self, "ansi", ansi);
self.reset_attributes();
}
pub fn move_cursor(self: *Self, row: u32, col: u32) void {
self.row = row;
self.column = col;
self.move_cursor_impl(self, row, col);
}
pub fn ansi_move_cursor(ansi: *Ansi, row: u32, col: u32) void {
const self = @fieldParentPtr(Self, "ansi", ansi);
self.move_cursor(row, col);
}
pub fn show_cursor(self: *Self, show: bool) void {
self.show_cursor_impl(self, show);
}
pub fn ansi_show_cursor(ansi: *Ansi, show: bool) void {
const self = @fieldParentPtr(Self, "ansi", ansi);
self.show_cursor(show);
}
pub fn reset_cursor(self: *Self) void {
self.move_cursor(0, 0);
self.show_cursor(true);
}
pub fn clear_screen(self: *Self) void {
self.clear_screen_impl(self);
}
pub fn reset_terminal(self: *Self) void {
self.reset_attributes();
self.clear_screen_impl(self);
self.reset_cursor();
}
pub fn ansi_reset_terminal(ansi: *Ansi) void {
const self = @fieldParentPtr(Self, "ansi", ansi);
self.reset_terminal();
}
|
kernel/Console.zig
|