code
stringlengths 38
801k
| repo_path
stringlengths 6
263
|
---|---|
const std = @import("std");
const input = [_]i32{ 0, 12, 6, 13, 20, 1, 17 };
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 part1 = findNumberAtTurn(allocator, &input, 2020);
const part2 = findNumberAtTurn(allocator, &input, 30000000);
print("[Part1] 2020th: {}", .{part1});
print("[Part2] 30000000th: {}", .{part2});
}
fn findNumberAtTurn(allocator: *std.mem.Allocator, numbers: []const i32, comptime target_turn: i32) i32 {
var spoken = NumberMap.init(allocator);
defer spoken.deinit();
var turn: i32 = 1;
var lastNumber: i32 = undefined;
for (numbers) |n| {
insertNumber(&spoken, n, turn);
turn += 1;
lastNumber = n;
}
while (true) : (turn += 1) {
if (spoken.get(lastNumber)) |numInfo| {
const n = if (numInfo.prevTurn == 0) 0 else (std.math.absInt(numInfo.turn - numInfo.prevTurn) catch @panic("absInt failed"));
insertNumber(&spoken, n, turn);
lastNumber = n;
if (turn == target_turn) {
return n;
}
} else unreachable;
}
}
const NumberInfo = struct { turn: i32, prevTurn: i32 };
const NumberMap = std.AutoHashMap(i32, NumberInfo);
fn insertNumber(map: *NumberMap, number: i32, turn: i32) void {
if (map.get(number)) |info| {
map.put(number, .{ .turn = turn, .prevTurn = info.turn }) catch @panic("put failed");
} else {
map.put(number, .{ .turn = turn, .prevTurn = 0 }) catch @panic("put failed");
}
}
const expectEqual = std.testing.expectEqual;
test "findNumberAtTurn2020" {
var allocator_state = std.heap.ArenaAllocator.init(std.testing.allocator);
defer allocator_state.deinit();
const allocator = &allocator_state.allocator;
expectEqual(@as(i32, 436), findNumberAtTurn(allocator, &[_]i32{ 0, 3, 6 }, 2020));
expectEqual(@as(i32, 1), findNumberAtTurn(allocator, &[_]i32{ 1, 3, 2 }, 2020));
expectEqual(@as(i32, 10), findNumberAtTurn(allocator, &[_]i32{ 2, 1, 3 }, 2020));
expectEqual(@as(i32, 27), findNumberAtTurn(allocator, &[_]i32{ 1, 2, 3 }, 2020));
expectEqual(@as(i32, 78), findNumberAtTurn(allocator, &[_]i32{ 2, 3, 1 }, 2020));
expectEqual(@as(i32, 438), findNumberAtTurn(allocator, &[_]i32{ 3, 2, 1 }, 2020));
expectEqual(@as(i32, 1836), findNumberAtTurn(allocator, &[_]i32{ 3, 1, 2 }, 2020));
}
test "findNumberAtTurn30000000" {
var allocator_state = std.heap.ArenaAllocator.init(std.testing.allocator);
defer allocator_state.deinit();
const allocator = &allocator_state.allocator;
expectEqual(@as(i32, 175594), findNumberAtTurn(allocator, &[_]i32{ 0, 3, 6 }, 30000000));
expectEqual(@as(i32, 2578), findNumberAtTurn(allocator, &[_]i32{ 1, 3, 2 }, 30000000));
expectEqual(@as(i32, 3544142), findNumberAtTurn(allocator, &[_]i32{ 2, 1, 3 }, 30000000));
expectEqual(@as(i32, 261214), findNumberAtTurn(allocator, &[_]i32{ 1, 2, 3 }, 30000000));
expectEqual(@as(i32, 6895259), findNumberAtTurn(allocator, &[_]i32{ 2, 3, 1 }, 30000000));
expectEqual(@as(i32, 18), findNumberAtTurn(allocator, &[_]i32{ 3, 2, 1 }, 30000000));
expectEqual(@as(i32, 362), findNumberAtTurn(allocator, &[_]i32{ 3, 1, 2 }, 30000000));
} | src/day15.zig |
const std = @import("std");
const Self = @This();
pub const HexColor = enum(u4) {
White = 15, // Spec name is bright white
LightGray = 7, // Spec name is white
DarkGray = 8, // Spec name is bright black
Black = 0,
Red = 1,
Green = 2,
Yellow = 3,
Blue = 4,
Magenta = 5,
Cyan = 6,
LightRed = 9,
LightGreen = 10,
LightYellow = 11,
LightBlue = 12,
LightMagenta = 13,
LightCyan = 14,
};
pub const Layer = enum {
Foreground,
Background,
};
const State = enum {
Unescaped,
Escaped,
Csi,
};
print_char: ?fn(self: *Self, char: u8) void = null,
hex_color: ?fn(self: *Self, color: HexColor, layer: Layer) void = null,
invert_colors: ?fn(self: *Self) void = null,
backspace: ?fn(self: *Self) void = null,
newline: ?fn(self: *Self) void = null,
reset_attributes: ?fn(self: *Self) void = null,
reset_terminal: ?fn(self: *Self) void = null,
move_cursor: ?fn(self: *Self, r: usize, c: usize) void = null,
show_cursor: ?fn(self: *Self, show: bool) void = null,
state: State = .Unescaped,
saved: [64]u8 = undefined,
parameter_start: ?usize = null,
parameters: [16]usize = undefined,
parameter_count: usize = 0,
saved_so_far: usize = 0,
malformed_sequences: usize = 0,
fn process_parameter(self: *Self) bool {
var parameter: ?u16 = null;
if (self.parameter_start) |start| {
const parameter_str = self.saved[start..self.saved_so_far];
parameter = std.fmt.parseUnsigned(u16, parameter_str, 10) catch null;
self.parameter_start = null;
} else { // empty parameter
parameter = 0;
}
if (parameter) |p| {
// std.debug.warn("Parameter: {}\n", .{p});
if (self.parameter_count < self.parameters.len) {
self.parameters[self.parameter_count] = p;
self.parameter_count += 1;
} else {
return true;
}
}
return parameter == null;
}
fn select_graphic_rendition(self: *Self) void {
var i: usize = 0;
while (i < self.parameter_count) {
const p = self.parameters[i];
// std.debug.warn("SGR: {}\n", .{p});
switch (p) {
0 => if (self.reset_attributes) |reset_attributes| reset_attributes(self),
7 => if (self.invert_colors) |invert_colors| invert_colors(self),
30...37 => if (self.hex_color) |hex_color|
hex_color(self, @intToEnum(HexColor, p - 30), .Foreground),
40...47 => if (self.hex_color) |hex_color|
hex_color(self, @intToEnum(HexColor, p - 40), .Background),
90...97 => if (self.hex_color) |hex_color|
hex_color(self, @intToEnum(HexColor, p - 82), .Foreground),
100...107 => if (self.hex_color) |hex_color|
hex_color(self, @intToEnum(HexColor, p - 92), .Background),
else => {},
}
i += 1;
}
}
fn process_move_cursor(self: *Self) void {
var column: usize = 0;
if (self.parameter_count > 1) {
column = self.parameters[1];
}
var row: usize = 0;
if (self.parameter_count > 0) {
row = self.parameters[0];
}
if (self.move_cursor) |move_cursor| {
move_cursor(self, row, column);
}
}
pub fn feed_char(self: *Self, char: u8) void {
self.saved[self.saved_so_far] = char;
// std.debug.warn("feed_char {c}\n", .{char});
var abort = false;
var reset = false;
switch (self.state) {
.Unescaped => {
reset = true;
switch (char) {
0x08 => if (self.backspace) |backspace| backspace(self),
'\n' => {
if (self.newline) |newline| {
newline(self);
} else if (self.print_char) |print_char| {
print_char(self, char);
}
},
0x1b => {
self.state = .Escaped;
reset = false;
},
else => {
if (self.print_char) |print_char| {
print_char(self, char);
}
},
}
},
.Escaped => {
switch (char) {
'[' => self.state = .Csi,
'c' => {
if (self.reset_terminal) |reset_terminal| {
reset_terminal(self);
}
reset = true;
},
else => abort = true,
}
},
.Csi => {
switch (char) {
'0'...'9' => {
if (self.parameter_start == null) {
self.parameter_start = self.saved_so_far;
}
},
'?' => {
// TODO
// private = true;
},
';' => {
abort = self.process_parameter();
},
'm' => {
abort = self.process_parameter();
if (!abort) {
self.select_graphic_rendition();
reset = true;
}
},
'H' => {
abort = self.process_parameter();
if (!abort) {
self.process_move_cursor();
reset = true;
}
},
'l' => {
// if (self.parameter_count == 1 and self.parameters[0] == 25) {
if (self.show_cursor) |show_cursor| {
show_cursor(self, false);
}
reset = true;
// } else {
// abort = true;
// }
},
else => abort = true,
}
},
}
self.saved_so_far += 1;
reset = reset or abort;
// If we're not gonna reset, abort if we're gonna be outa room on the
// next character.
if (!reset and self.saved_so_far == self.saved.len) {
abort = true;
}
if (abort) {
// std.debug.warn("Abort\n", .{});
if (self.print_char) |print_char| {
// Dump the malformed sequence. Seems to be what Gnome's terminal does.
for (self.saved[0..self.saved_so_far]) |c| {
print_char(self, c);
}
}
self.malformed_sequences += 1;
}
if (reset) {
self.parameter_count = 0;
self.state = .Unescaped;
self.saved_so_far = 0;
self.parameter_start = null;
}
// std.debug.warn("state {s}\n", .{@tagName(self.state)});
}
pub fn feed_str(self: *Self, str: []const u8) void {
for (str) |char| {
self.feed_char(char);
}
}
// Testing ====================================================================
var test_print_char_buffer: [128]u8 = undefined;
var test_print_char_got: usize = 0;
fn test_print_char(self: *Self, char: u8) void {
_ = self;
test_print_char_buffer[test_print_char_got] = char;
test_print_char_got += 1;
}
fn test_reset(self: *Self) void {
_ = self;
test_print_char(self, 'R');
}
fn test_invert_colors(self: *Self) void {
_ = self;
test_print_char(self, 'I');
}
fn test_hex_color(self: *Self, color: HexColor, layer: Layer) void {
test_print_char(self, if (layer == .Background) 'B' else 'F');
test_print_char(self, 'C');
test_print_char(self, '(');
test_print_char(self, switch (color) {
.LightRed => 'R',
.Green => 'g',
else => '?',
});
test_print_char(self, ')');
}
test "AnsiEscProcessor" {
var esc = Self{
.print_char = test_print_char,
.reset_attributes = test_reset,
.invert_colors = test_invert_colors,
.hex_color = test_hex_color,
};
esc.feed_str("Hello \x1b[7mBob\x1b[0m \x1b[91;42mGoodbye");
try std.testing.expectEqualStrings("Hello IBobR FC(R)BC(g)Goodbye",
test_print_char_buffer[0..test_print_char_got]);
// TODO: More Tests
} | libs/utils/AnsiEscProcessor.zig |
const builtin = @import("std").builtin;
const utils = @import("utils");
const io = @import("io.zig");
const File = io.File;
const FileError = io.FileError;
/// Print a char
pub fn char(file: *File, ch: u8) FileError!void {
_ = try file.write(([_]u8{ch})[0..]);
}
/// Print a string.
pub fn string(file: *File, str: []const u8) FileError!void {
_ = try file.write(str);
}
/// Print a string with a null terminator.
pub fn cstring(file: *File, str: [*]const u8) FileError!void {
var i: usize = 0;
while (str[i] > 0) {
try char(file, str[i]);
i += 1;
}
}
/// Print string stripped of trailing whitespace.
pub fn stripped_string(file: *File, str: [*]const u8, size: usize) FileError!void {
try string(file, str[0..utils.stripped_string_size(str[0..size])]);
}
fn uint_recurse(comptime uint_type: type, file: *File, value: uint_type) FileError!void {
const digit: u8 = @intCast(u8, value % 10);
const next = value / 10;
if (next > 0) {
try uint_recurse(uint_type, file, next);
}
try char(file, '0' + digit);
}
/// Print a unsigned integer
pub fn uint(file: *File, value: usize) FileError!void {
if (value == 0) {
try char(file, '0');
return;
}
try uint_recurse(usize, file, value);
}
pub fn uint64(file: *File, value: u64) FileError!void {
if (value == 0) {
try char(file, '0');
return;
}
try uint_recurse(u64, file, value);
}
/// Print a signed integer
pub fn int(file: *File, value: isize) FileError!void {
var x = value;
if (value < 0) {
try char(file, '-');
x = -value;
}
try uint(file, @intCast(usize, x));
}
/// Print a signed integer with an optional '+' sign.
pub fn int_sign(file: *File, value: usize, show_positive: bool) FileError!void {
if (value > 0 and show_positive) {
try char(file, '+');
}
try int(file, value);
}
fn nibble(file: *File, value: u4) FileError!void {
try char(file, utils.nibble_char(value));
}
fn hex_recurse(file: *File, value: usize) FileError!void {
const next = value / 0x10;
if (next > 0) {
try hex_recurse(file, next);
}
try nibble(file, @intCast(u4, value % 0x10));
}
/// Print a unsigned integer as a hexadecimal number with a "0x" prefix
pub fn hex(file: *File, value: usize) FileError!void {
try string(file, "0x");
if (value == 0) {
try char(file, '0');
return;
}
try hex_recurse(file, value);
}
/// Print a unsigned integer as a hexadecimal number a padded to usize and
/// prefixed with "@0x".
pub fn address(file: *File, value: usize) FileError!void {
const prefix = "@0x";
// For 32b: @0xXXXXXXXX
// For 64b: @0xXXXXXXXXXXXXXXXX
const nibble_count = @sizeOf(usize) * 2;
const char_count = prefix.len + nibble_count;
var buffer: [char_count]u8 = undefined;
for (prefix) |c, i| {
buffer[i] = c;
}
for (buffer[prefix.len..]) |*ptr, i| {
const nibble_index: usize = (nibble_count - 1) - i;
ptr.* = utils.nibble_char(utils.select_nibble(usize, value, nibble_index));
}
try string(file, buffer[0..]);
}
test "address" {
const std = @import("std");
const BufferFile = io.BufferFile;
var file_buffer: [128]u8 = undefined;
utils.memory_set(file_buffer[0..], 0);
var buffer_file = BufferFile{};
buffer_file.init(file_buffer[0..]);
const file = &buffer_file.file;
try address(file, 0x7bc75e39);
const length = utils.string_length(file_buffer[0..]);
const expected = if (@sizeOf(usize) == 4)
"@0x7bc75e39"
else if (@sizeOf(usize) == 8)
"@0x000000007bc75e39"
else
@compileError("usize size missing in this test");
try std.testing.expectEqualSlices(u8, expected[0..], file_buffer[0..length]);
}
/// Print a hexadecimal representation of a byte (no "0x" prefix)
pub fn byte(file: *File, value: u8) FileError!void {
var buffer: [2]u8 = undefined;
utils.byte_buffer(buffer[0..], value);
try string(file, buffer);
}
/// Print a boolean as "true" or "false".
pub fn boolean(file: *File, value: bool) FileError!void {
try string(file, if (value) "true" else "false");
}
/// Try to guess how to print a value based on its type.
pub fn any(file: *File, value: anytype) FileError!void {
const Type = @TypeOf(value);
const Traits = @typeInfo(Type);
switch (Traits) {
builtin.TypeId.Int => |int_type| {
if (int_type.signedness == .signed) {
try int(file, value);
} else {
if (int_type.bits * 8 > @sizeOf(usize)) {
try uint64(file, value);
} else {
try uint(file, value);
}
}
},
builtin.TypeId.Bool => try boolean(file, value),
builtin.TypeId.Array => |array_type| {
const t = array_type.child;
if (t == u8) {
try string(file, value[0..]);
} else {
comptime var i: usize = 0;
inline while (i < array_type.len) {
try format(file, "[{}] = {},", .{i, value[i]});
i += 1;
}
}
},
builtin.TypeId.Pointer => |ptr_type| {
const t = ptr_type.child;
if (ptr_type.is_allowzero and value == 0) {
try string(file, "null");
} else if (t == u8) {
if (ptr_type.size == builtin.TypeInfo.Pointer.Size.Slice) {
try string(file, value);
} else {
try cstring(file, value);
}
} else {
try any(file, value.*);
// @compileError("Can't Print Pointer to " ++ @typeName(t));
}
},
builtin.TypeId.Struct => |struct_type| {
inline for (struct_type.fields) |field| {
try string(file, field.name);
try string(file, ": ");
try any(file, @field(value, field.name));
try string(file, "\n");
}
},
builtin.TypeId.Enum => {
if (utils.enum_name(Type, value)) |name| {
try string(file, name);
} else {
try string(file, "<Invalid Value For " ++ @typeName(Type) ++ ">");
}
},
else => @compileError("Can't Print " ++ @typeName(Type)),
}
}
/// Print Using Format String, meant to work somewhat like Zig's
/// `std.fmt.format`.
///
/// Layout of a valid format marker is `{[specifier:]}`.
///
/// TODO: Match std.fmt.format instead of Python string.format and use
/// {[specifier]:...}
///
/// `specifier`:
/// None
/// Insert next argument using default formating and `fprint.any()`.
/// `x` and `X`
/// Insert next argument using hexadecimal format. It must be an
/// unsigned integer. The case of the letters A-F of the result depends
/// on if `x` or `X` was used as the specifier (TODO).
/// 'a'
/// Like "x", but prints the full address value prefixed with "@".
/// 'c'
/// Insert the u8 as a character (more specficially as a UTF-8 byte).
///
/// Escapes:
/// `{{` is replaced with `{` and `}}` is replaced by `}`.
pub fn format(file: *File, comptime fmtstr: []const u8, args: anytype) FileError!void {
const State = enum {
NoFormat, // Outside Braces
Format, // Inside Braces
EscapeEnd, // Expecting }
FormatSpec, // After {:
};
const Spec = enum {
Default,
Hex,
Address,
Char,
};
comptime var arg: usize = 0;
comptime var state = State.NoFormat;
comptime var spec = Spec.Default;
comptime var no_format_start: usize = 0;
inline for (fmtstr) |ch, index| {
switch (state) {
State.NoFormat => switch (ch) {
'{' => {
if (no_format_start < index) {
try string(file, fmtstr[no_format_start..index]);
}
state = State.Format;
spec = Spec.Default;
},
'}' => { // Should be Escaped }
if (no_format_start < index) {
try string(file, fmtstr[no_format_start..index]);
}
state = State.EscapeEnd;
},
else => {},
},
State.Format => switch (ch) {
'{' => { // Escaped {
state = State.NoFormat;
no_format_start = index;
},
'}' => {
switch (spec) {
Spec.Hex => try hex(file, args[arg]),
Spec.Address => try address(file, args[arg]),
Spec.Char => try char(file, args[arg]),
Spec.Default => try any(file, args[arg]),
}
arg += 1;
state = State.NoFormat;
no_format_start = index + 1;
},
':' => {
state = State.FormatSpec;
},
else => @compileError(
"Unexpected Format chacter: " ++ fmtstr[index..index+1]),
},
State.FormatSpec => switch (ch) {
'x' => {
spec = Spec.Hex;
state = State.Format;
},
'a' => {
spec = Spec.Address;
state = State.Format;
},
'c' => {
spec = Spec.Char;
state = State.Format;
},
else => @compileError(
"Unexpected Format chacter after ':': " ++
fmtstr[index..index+1]),
},
State.EscapeEnd => switch (ch) {
'}' => { // Escaped }
state = State.NoFormat;
no_format_start = index;
},
else => @compileError(
"Expected } for end brace escape, but found: " ++
fmtstr[index..index+1]),
},
}
}
if (args.len != arg) {
@compileError("Unused arguments");
}
if (state != State.NoFormat) {
@compileError("Incomplete format string: " ++ fmtstr);
}
if (no_format_start < fmtstr.len) {
try string(file, fmtstr[no_format_start..fmtstr.len]);
}
}
pub fn dump_memory(file: *File, ptr: usize, size: usize) FileError!void {
// Print hex data like this:
// VV group_sep
// 00 01 02 03 04 05 06 07 08 09 0A 0B 0C 0D 0E 0F
// ^^ Byte ^ byte_sep Group^^^^^^^^^^^^^^^^^^^^^^^
const group_byte_count = 8;
const byte_sep = " ";
const group_size =
group_byte_count * 2 + // Bytes
((group_byte_count * byte_sep.len) - 1); // byte_sep Between Bytes
const group_count = 2;
const group_sep = " ";
const buffer_size =
group_size * group_count + // Groups
(group_count - 1) * group_sep.len + // group_sep Between Groups
1; // Newline
var buffer: [buffer_size]u8 = undefined;
var i: usize = 0;
var buffer_pos: usize = 0;
var byte_i: usize = 0;
var group_i: usize = 0;
var has_next = i < size;
var print_buffer = false;
while (has_next) {
const next_i = i + 1;
has_next = next_i < size;
print_buffer = !has_next;
{
const new_pos = buffer_pos + 2;
utils.byte_buffer(buffer[buffer_pos..new_pos],
@intToPtr(*allowzero u8, ptr + i).*);
buffer_pos = new_pos;
}
byte_i += 1;
if (byte_i == group_byte_count) {
byte_i = 0;
group_i += 1;
if (group_i == group_count) {
group_i = 0;
print_buffer = true;
} else {
for (group_sep[0..group_sep.len]) |b| {
buffer[buffer_pos] = b;
buffer_pos += 1;
}
}
} else if (has_next) {
for (byte_sep[0..byte_sep.len]) |b| {
buffer[buffer_pos] = b;
buffer_pos += 1;
}
}
if (print_buffer) {
buffer[buffer_pos] = '\n';
buffer_pos += 1;
try string(file, buffer[0..buffer_pos]);
buffer_pos = 0;
print_buffer = false;
}
i = next_i;
}
}
pub fn dump_bytes(file: *File, byteslice: []const u8) FileError!void {
try dump_memory(file, @ptrToInt(byteslice.ptr), byteslice.len);
}
pub fn dump_raw_object(file: *File, comptime Type: type, value: *const Type) FileError!void {
const size: usize = @sizeOf(Type);
const ptr: usize = @ptrToInt(value);
try format(file, "type: {} at {:a} size: {} data:\n", @typeName(Type), ptr, size);
try dump_memory(file, ptr, size);
} | kernel/fprint.zig |
const std = @import("std");
const assert = std.debug.assert;
const builtin = std.builtin;
const TypeId = builtin.TypeId;
// usingnamespace @import("../main/util.zig");
pub fn zero_struct(comptime T: type) T {
var out: T = undefined;
std.mem.set(u8, @ptrCast([*]u8, &out)[0..@sizeOf(T)], 0);
return out;
}
pub const String = []u8;
pub const Entity = u16;
pub const Hash = u64;
pub const Tag = u32;
pub const TagUnset: Tag = 0;
pub fn stringHash(s: []const u8) Hash {
return std.hash.Wyhash.hash(0, s);
}
pub fn stringTag(comptime s: []const u8) Tag {
return @truncate(u32, std.hash.Wyhash.hash(0, s));
}
pub const FullTag = struct {
tag: Tag,
string: String,
pub fn init(string: String) FullTag {
return .{
.tag = stringTag(string),
.string = string,
};
}
};
pub const VariantType = union(enum) {
int64: i64,
boolean: bool,
hash: Hash,
tag: Tag,
ptr: usize,
};
pub const Variant = struct {
value: VariantType = undefined,
tag: Tag = 0,
count: u32 = 1,
pub fn create_ptr(ptr: var, tag: Tag) Variant {
assert(tag != 0);
return Variant{
.value = .{ .ptr = @ptrToInt(ptr) },
.tag = tag,
};
}
pub fn create_slice(slice: var, tag: Tag) Variant {
assert(tag != 0);
return Variant{
.value = .{ .ptr = @ptrToInt(slice.ptr) },
.tag = tag,
.count = slice.len,
};
}
pub fn create_int(int: var) Variant {
self.tag = 0; // TODO
return Variant{
.value = .{ .int64 = @intCast(i64, int) },
};
}
pub fn set_ptr(self: *Variant, ptr: var, tag: Tag) void {
assert(tag != 0);
self.value = .{ .ptr = @ptrToInt(ptr) };
self.tag = tag;
}
pub fn set_slice(slice: var, tag: Tag) Variant {
assert(tag != 0);
self.value = .{ .ptr = @ptrToInt(slice.ptr) };
self.tag = tag;
self.count = slice.len;
}
pub fn set_int(int: var) Variant {
var v = VariantType{ .int64 = @intCast(i64, int) };
return Variant{
.value = .{ .int64 = @intCast(i64, int) },
};
}
pub fn get_ptr(self: Variant, comptime T: type, tag: Hash) *T {
assert(tag == self.tag);
return @intToPtr(*T, self.value.ptr);
}
pub fn get_slice(self: Variant, comptime T: type, tag: Hash) []T {
assert(tag == self.tag);
var ptr = @intToPtr([*]T, self.value.ptr);
return ptr[0..self.count];
}
pub fn get_int(self: Variant) i64 {
return self.value.int64;
}
};
pub const VariantMap = std.StringHashMap(Variant);
pub fn fillContext(params: VariantMap, comptime ContextT: type) ContextT {
var context: ContextT = undefined;
inline for (@typeInfo(ContextT).Struct.fields) |f, i| {
const field_name = f.name;
const typ = @memberType(ContextT, i);
const ti = @typeInfo(typ);
const variant = (params.getValue(field_name) orelse unreachable);
switch (ti) {
TypeId.Int => {
@field(context, field_name) = @intCast(typ, variant.get_int());
},
TypeId.Bool => {
@field(context, field_name) = variant.get_bool;
},
TypeId.Pointer => {
switch (ti.Pointer.size) {
builtin.TypeInfo.Pointer.Size.One => {
var ptr = variant.get_ptr(ti.Pointer.child, stringTag(field_name));
@field(context, field_name) = ptr;
},
else => {
unreachable;
},
}
},
else => {
unreachable;
},
}
}
return context;
}
pub fn DoubleBuffer(comptime BufferedType: type) type {
return struct {
const Self = @This();
allocator: *Allocator,
current_buffer: u8 = 0,
buffers: [2]BufferedType,
pub fn init(allocator: *Allocator, capacity: usize) !Self {
var res = try Self{
.buffers = .{
BufferedType.init(allocator),
BufferedType.init(allocator),
},
};
res.buffers[0].ensureCapacity(capacity);
res.buffers[1].ensureCapacity(capacity);
return res;
}
pub fn deinit(self: DoubleBuffer) void {
self.buffers[0].deinit();
self.buffers[1].deinit();
}
pub fn frontHasData(self: DoubleBuffer) []T {
return self.buffers[self.current_buffer].count() > 0;
}
pub fn front(self: DoubleBuffer) *ArrayList(T) {
return self.buffers[self.current_buffer];
}
pub fn back(self: DoubleBuffer) *ArrayList(T) {
return self.buffers[1 - self.current_buffer];
}
pub fn swap(self: *DoubleBuffer) []T {
self.currBuffer().resize(0);
return self.current_buffer = 1 - self.current_buffer;
}
};
} | code/main/util.zig |
const xbeam = @import("../index.zig");
const std = @import("std");
const AtomicUsize = std.atomic.Atomic(usize);
/// A bounded multi-producer multi-consumer queue.
///
/// This queue allocates a fixed-capacity buffer on construction, which is used to store pushed
/// elements. The queue cannot hold more elements than the buffer allows. Attempting to push an
/// element into a full queue will fail.
pub fn ArrayQueue(comptime T: type) type {
return struct {
const Self = @This();
/// A slot in a queue.
const Slot = struct {
/// The current stamp.
///
/// If the stamp equals the tail, this node will be next written to. If it equals head + 1,
/// this node will be next read from.
stamp: AtomicUsize,
/// The value in this slot.
value: T = undefined,
};
allocator: *std.mem.Allocator,
/// A stamp with the value of `{ lap: 1, index: 0 }`.
one_lap: usize,
/// The head of the queue.
///
/// This value is a "stamp" consisting of an index into the buffer and a lap, but packed into a
/// single `usize`. The lower bits represent the index, while the upper bits represent the lap.
///
/// Elements are popped from the head of the queue.
head: AtomicUsize align(xbeam.utils.CACHE_LINE_LENGTH) = AtomicUsize.init(0),
/// The tail of the queue.
///
/// This value is a "stamp" consisting of an index into the buffer and a lap, but packed into a
/// single `usize`. The lower bits represent the index, while the upper bits represent the lap.
///
/// Elements are pushed into the tail of the queue.
tail: AtomicUsize align(xbeam.utils.CACHE_LINE_LENGTH) = AtomicUsize.init(0),
/// The buffer holding slots.
buffer: []Slot,
pub fn init(allocator: *std.mem.Allocator, capacity: usize) !Self {
const buffer = try allocator.alloc(Slot, capacity);
for (buffer) |*slot, i| {
slot.* = Slot{ .stamp = AtomicUsize.init(i) };
}
return Self{
.allocator = allocator,
.buffer = buffer,
.one_lap = try std.math.ceilPowerOfTwo(usize, capacity + 1),
};
}
pub fn deinit(self: *Self) void {
self.allocator.free(self.buffer);
}
/// Attempts to push an element into the queue.
/// If the queue is full, returns an error.
pub fn push(self: *Self, value: T) !void {
const one_lap = self.one_lap;
var backoff = xbeam.utils.Backoff.init();
var tail = self.tail.load(.Unordered);
while (true) {
// deconstruct the tail
const index = tail & (one_lap - 1);
const lap = tail & ~(one_lap - 1);
// inspect the corresponding slot.
const slot: *Slot = &self.buffer[index];
const stamp = slot.stamp.load(.Acquire);
// if the tail and the stamp match, we may attempt to push.
if (tail == stamp) {
const new_tail = blk: {
if (index + 1 < self.buffer.len) {
// Same lap, incremented index.
break :blk tail + 1;
} else {
// One lap forward, index wraps around to zero.
break :blk lap +% one_lap;
}
};
// try moving the tail.
if (@cmpxchgWeak(usize, &self.tail.value, tail, new_tail, .SeqCst, .Monotonic)) |t| {
// failed to swap
tail = t;
backoff.spin();
} else {
slot.value = value;
slot.stamp.store(tail + 1, .Release);
return;
}
} else if (stamp +% one_lap == tail + 1) {
@fence(.SeqCst);
const head = self.head.load(.Unordered);
// if the head lags one lap behind the tail as well...
if (head +% one_lap == tail) {
// ...then the queue is full
return error.QueueIsFull;
}
backoff.spin();
tail = self.tail.load(.Unordered);
} else {
// we need to wait for the stamp to get updated.
backoff.snooze();
tail = self.tail.load(.Unordered);
}
}
}
/// Attempts to pop an element from the queue.
/// If the queue is empty, `null` is returned.
pub fn pop(self: *Self) ?T {
const one_lap = self.one_lap;
var backoff = xbeam.utils.Backoff.init();
var head = self.head.load(.Unordered);
while (true) {
// deconstruct the head
const index = head & (one_lap - 1);
const lap = head & ~(one_lap - 1);
// inspect the corresponding slot.
const slot: *Slot = &self.buffer[index];
const stamp = slot.stamp.load(.Acquire);
// if the the stamp is ahead of the head by 1, we may attempt to pop.
if (head + 1 == stamp) {
const new_head = blk: {
if (index + 1 < self.buffer.len) {
// Same lap, incremented index.
break :blk head + 1;
} else {
// One lap forward, index wraps around to zero.
break :blk lap +% one_lap;
}
};
// try moving the head.
if (@cmpxchgWeak(usize, &self.head.value, head, new_head, .SeqCst, .Monotonic)) |h| {
// failed to swap
head = h;
backoff.spin();
} else {
const msg = slot.value;
slot.stamp.store(head +% one_lap, .Release);
return msg;
}
} else if (stamp == head) {
@fence(.SeqCst);
const tail = self.head.load(.Unordered);
// If the tail equals the head, that means the queue is empty.
if (tail == head) return null;
backoff.spin();
head = self.head.load(.Unordered);
} else {
// we need to wait for the stamp to get updated.
backoff.snooze();
head = self.head.load(.Unordered);
}
}
}
/// Returns `true` if the queue is empty.
pub fn isEmpty(self: *Self) bool {
const head = self.head.load(.SeqCst);
const tail = self.tail.load(.SeqCst);
// Is the tail lagging one lap behind head?
// Is the tail equal to the head?
//
// Note: If the head changes just before we load the tail, that means there was a moment
// when the channel was not empty, so it is safe to just return `false`.
return head == tail;
}
/// Returns `true` if the queue is full.
pub fn isFull(self: *Self) bool {
const head = self.head.load(.SeqCst);
const tail = self.tail.load(.SeqCst);
// Is the head lagging one lap behind tail?
//
// Note: If the tail changes just before we load the head, that means there was a moment
// when the queue was not full, so it is safe to just return `false`.
return head +% self.one_lap == tail;
}
pub fn len(self: *Self) usize {
const one_lap = self.one_lap;
while (true) {
const head = self.head.load(.SeqCst);
const tail = self.tail.load(.SeqCst);
// If the tail didn't change, we've got consistent values to work with.
if (self.tail.load(.SeqCst) == tail) {
const hix = head & (one_lap - 1);
const tix = tail & (one_lap - 1);
if (hix < tix) {
return tix - hix;
} else if (hix > tix) {
return self.buffer.len - hix + tix;
} else if (tail == head) {
return 0;
} else {
return self.buffer.len;
}
}
}
}
comptime {
std.testing.refAllDecls(@This());
}
};
}
comptime {
std.testing.refAllDecls(@This());
}
test "distinct buffers" {
var q1 = try ArrayQueue(usize).init(std.testing.allocator, 10);
defer q1.deinit();
var q2 = try ArrayQueue(usize).init(std.testing.allocator, 10);
defer q2.deinit();
q1.buffer[0].value = 10;
q2.buffer[0].value = 20;
try std.testing.expectEqual(@as(usize, 10), q1.buffer[0].value);
try std.testing.expectEqual(@as(usize, 20), q2.buffer[0].value);
}
test "push" {
var q = try ArrayQueue(usize).init(std.testing.allocator, 2);
defer q.deinit();
try q.push(10);
try q.push(20);
try std.testing.expectEqual(@as(usize, 10), q.buffer[0].value);
try std.testing.expectEqual(@as(usize, 20), q.buffer[1].value);
try std.testing.expectError(error.QueueIsFull, q.push(0));
}
test "isEmpty" {
var q = try ArrayQueue(usize).init(std.testing.allocator, 2);
defer q.deinit();
try std.testing.expectEqual(true, q.isEmpty());
try q.push(10);
try std.testing.expectEqual(false, q.isEmpty());
try std.testing.expectEqual(@as(usize, 10), q.pop().?);
try std.testing.expectEqual(true, q.isEmpty());
}
test "isFull" {
var q = try ArrayQueue(usize).init(std.testing.allocator, 2);
defer q.deinit();
try std.testing.expectEqual(false, q.isFull());
try q.push(10);
try std.testing.expectEqual(false, q.isFull());
try q.push(20);
try std.testing.expectEqual(true, q.isFull());
try std.testing.expectEqual(@as(usize, 10), q.pop().?);
try std.testing.expectEqual(false, q.isFull());
}
test "len" {
var q = try ArrayQueue(usize).init(std.testing.allocator, 2);
defer q.deinit();
try std.testing.expectEqual(@as(usize, 0), q.len());
try q.push(10);
try std.testing.expectEqual(@as(usize, 1), q.len());
try q.push(20);
try std.testing.expectEqual(@as(usize, 2), q.len());
try std.testing.expectEqual(@as(usize, 10), q.pop().?);
try std.testing.expectEqual(@as(usize, 1), q.len());
try std.testing.expectEqual(@as(usize, 20), q.pop().?);
try std.testing.expectEqual(@as(usize, 0), q.len());
}
test "pop" {
var q = try ArrayQueue(usize).init(std.testing.allocator, 2);
defer q.deinit();
try q.push(10);
try q.push(20);
try std.testing.expectError(error.QueueIsFull, q.push(100));
try std.testing.expectEqual(@as(usize, 10), q.pop().?);
try std.testing.expectEqual(@as(usize, 20), q.pop().?);
try std.testing.expect(q.pop() == null);
try q.push(0);
try q.push(1);
try std.testing.expectError(error.QueueIsFull, q.push(100));
try std.testing.expectEqual(@as(usize, 0), q.pop().?);
try std.testing.expectEqual(@as(usize, 1), q.pop().?);
try std.testing.expect(q.pop() == null);
} | src/queue/array_queue.zig |
const std = @import("std");
const koino = @import("koino");
const markdown_options = koino.Options{
.extensions = .{
.table = true,
.autolink = true,
.strikethrough = true,
},
.render = .{
.header_anchors = true,
.anchor_icon = "§ ",
},
};
/// verifies and parses a file name in the format
/// "YYYY-MM-DD - " [.*] ".md"
fn isValidArticleFileName(path: []const u8) ?Date {
if (path.len < 16)
return null;
if (!std.mem.endsWith(u8, path, ".md"))
return null;
if (path[4] != '-' or path[7] != '-' or !std.mem.eql(u8, path[10..13], " - "))
return null;
return Date{
.year = std.fmt.parseInt(u16, path[0..4], 10) catch return null,
.month = std.fmt.parseInt(u8, path[5..7], 10) catch return null,
.day = std.fmt.parseInt(u8, path[8..10], 10) catch return null,
};
}
pub fn main() anyerror!void {
var gpa = std.heap.GeneralPurposeAllocator(.{}){};
defer _ = gpa.deinit();
const allocator = &gpa.allocator;
var website = Website{
.allocator = allocator,
.arena = std.heap.ArenaAllocator.init(allocator),
.articles = std.ArrayList(Article).init(allocator),
.tutorials = std.ArrayList(Tutorial).init(allocator),
.images = std.ArrayList([]const u8).init(allocator),
};
defer website.deinit();
// gather step
{
var root_dir = try std.fs.cwd().openDir("website", .{});
defer root_dir.close();
// Tutorials are maintained manually right now
try website.addTutorial(Tutorial{
.src_file = "website/tutorials/01-embedded-basics.md",
});
try website.addTutorial(Tutorial{
.src_file = "website/tutorials/02-embedded-programming.md",
});
try website.addTutorial(Tutorial{
.src_file = "website/tutorials/03-lpc1768.md",
});
try website.addTutorial(Tutorial{
.src_file = "website/tutorials/03-nrf52.md",
});
try website.addTutorial(Tutorial{
.src_file = "website/tutorials/03-avr.md",
});
try website.addTutorial(Tutorial{
.src_file = "website/tutorials/03-pi-pico.md",
});
try website.addTutorial(Tutorial{
.src_file = "website/tutorials/03-stm32.md",
});
try website.addTutorial(Tutorial{
.src_file = "website/tutorials/04-chose-device.md",
});
try website.addTutorial(Tutorial{
.src_file = "website/tutorials/05-hal.md",
});
// img articles
{
var dir = try root_dir.openDir("img", .{ .iterate = true });
defer dir.close();
var iter = dir.iterate();
while (try iter.next()) |entry| {
if (entry.kind != .File) {
std.log.err("Illegal folder in directory website/img: {s}", .{entry.name});
continue;
}
const path = try std.fs.path.join(&website.arena.allocator, &[_][]const u8{
"website",
"img",
entry.name,
});
try website.addImage(path);
}
}
// gather articles
{
var dir = try root_dir.openDir("articles", .{ .iterate = true });
defer dir.close();
var iter = dir.iterate();
while (try iter.next()) |entry| {
if (entry.kind != .File) {
std.log.err("Illegal folder in directory website/articles: {s}", .{entry.name});
continue;
}
const date = isValidArticleFileName(entry.name) orelse {
std.log.err("Illegal file name in directory website/articles: {s}", .{entry.name});
continue;
};
var article = Article{
.title = "Not yet generated",
.src_file = undefined,
.date = date,
};
article.src_file = try std.fs.path.join(&website.arena.allocator, &[_][]const u8{
"website",
"articles",
entry.name,
});
try website.addArticle(article);
}
}
}
try website.prepareRendering();
// final rendering
{
var root_dir = try std.fs.cwd().makeOpenPath("render", .{});
defer root_dir.close();
try website.renderMarkdownFile("website/index.md", root_dir, "index.htm");
try website.renderArticleIndex(root_dir, "articles.htm");
var art_dir = try root_dir.makeOpenPath("articles", .{});
defer art_dir.close();
var tut_dir = try root_dir.makeOpenPath("tutorials", .{});
defer tut_dir.close();
var img_dir = try root_dir.makeOpenPath("img", .{});
defer img_dir.close();
try website.renderArticles(art_dir);
try website.renderTutorials(tut_dir);
try website.renderAtomFeed(root_dir, "feed.atom");
try website.renderImages(img_dir);
}
}
const Date = struct {
const Self = @This();
day: u8,
month: u8,
year: u16,
fn toInteger(self: Self) u32 {
return @as(u32, self.day) + 33 * @as(u32, self.month) + (33 * 13) * @as(u32, self.year);
}
pub fn lessThan(lhs: Self, rhs: Self) bool {
return lhs.toInteger() < rhs.toInteger();
}
pub fn eql(a: Self, b: Self) bool {
return std.meta.eql(a, b);
}
pub fn format(self: Self, comptime fmt: []const u8, options: std.fmt.FormatOptions, writer: anytype) !void {
try writer.print("{d:0>4}-{d:0>2}-{d:0>2}", .{
self.year, self.month, self.day,
});
}
};
const Article = struct {
date: Date,
src_file: []const u8,
title: []const u8 = "<undetermined>",
};
const Tutorial = struct {
src_file: []const u8,
title: []const u8 = "<undetermined>",
};
const Website = struct {
const Self = @This();
is_prepared: bool = false,
allocator: *std.mem.Allocator,
arena: std.heap.ArenaAllocator,
articles: std.ArrayList(Article),
tutorials: std.ArrayList(Tutorial),
images: std.ArrayList([]const u8),
fn deinit(self: *Self) void {
self.tutorials.deinit();
self.articles.deinit();
self.images.deinit();
self.arena.deinit();
self.* = undefined;
}
fn addArticle(self: *Self, article: Article) !void {
self.is_prepared = false;
try self.articles.append(Article{
.date = article.date,
.src_file = try self.arena.allocator.dupe(u8, article.src_file),
.title = try self.arena.allocator.dupe(u8, article.title),
});
}
fn addTutorial(self: *Self, tutorial: Tutorial) !void {
self.is_prepared = false;
try self.tutorials.append(Tutorial{
.src_file = try self.arena.allocator.dupe(u8, tutorial.src_file),
.title = try self.arena.allocator.dupe(u8, tutorial.title),
});
}
fn addImage(self: *Self, path: []const u8) !void {
self.is_prepared = false;
try self.images.append(try self.arena.allocator.dupe(u8, path));
}
fn findTitle(self: *Self, file: []const u8) !?[]const u8 {
var doc = blk: {
var p = try koino.parser.Parser.init(self.allocator, markdown_options);
defer p.deinit();
const markdown = try std.fs.cwd().readFileAlloc(self.allocator, file, 10_000_000);
defer self.allocator.free(markdown);
try p.feed(markdown);
break :blk try p.finish();
};
defer doc.deinit();
std.debug.assert(doc.data.value == .Document);
var iter = doc.first_child;
var heading_or_null: ?*koino.nodes.AstNode = while (iter) |item| : (iter = item.next) {
if (item.data.value == .Heading) {
if (item.data.value.Heading.level == 1) {
break item;
}
}
} else null;
if (heading_or_null) |heading| {
var list = std.ArrayList(u8).init(&self.arena.allocator);
defer list.deinit();
var options = markdown_options;
options.render.header_anchors = false;
try koino.html.print(list.writer(), &self.arena.allocator, options, heading);
const string = list.toOwnedSlice();
std.debug.assert(std.mem.startsWith(u8, string, "<h1>"));
std.debug.assert(std.mem.endsWith(u8, string, "</h1>\n"));
return string[4 .. string.len - 6];
} else {
return null;
}
}
fn prepareRendering(self: *Self) !void {
std.sort.sort(Article, self.articles.items, self.*, sortArticlesDesc);
for (self.articles.items) |*article| {
if (try self.findTitle(article.src_file)) |title| {
article.title = title;
}
}
for (self.tutorials.items) |*tutorial| {
if (try self.findTitle(tutorial.src_file)) |title| {
tutorial.title = title;
}
}
self.is_prepared = true;
}
fn sortArticlesDesc(self: Self, lhs: Article, rhs: Article) bool {
if (lhs.date.lessThan(rhs.date))
return false;
if (rhs.date.lessThan(lhs.date))
return true;
return (std.mem.order(u8, lhs.title, rhs.title) == .gt);
}
fn removeExtension(src_name: []const u8) []const u8 {
const ext = std.fs.path.extension(src_name);
return src_name[0 .. src_name.len - ext.len];
}
fn changeExtension(self: *Self, src_name: []const u8, new_ext: []const u8) ![]const u8 {
return std.mem.join(&self.arena.allocator, "", &[_][]const u8{
removeExtension(src_name),
new_ext,
});
}
fn urlEscape(self: *Self, text: []const u8) ![]u8 {
const legal_character = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-._~";
var len: usize = 0;
for (text) |c| {
len += if (std.mem.indexOfScalar(u8, legal_character, c) == null)
@as(usize, 3)
else
@as(usize, 1);
}
const buf = try self.arena.allocator.alloc(u8, len);
var offset: usize = 0;
for (text) |c| {
if (std.mem.indexOfScalar(u8, legal_character, c) == null) {
const hexdigits = "0123456789ABCDEF";
buf[offset + 0] = '%';
buf[offset + 1] = hexdigits[(c >> 4) & 0xF];
buf[offset + 2] = hexdigits[(c >> 0) & 0xF];
offset += 3;
} else {
buf[offset] = c;
offset += 1;
}
}
return buf;
}
fn renderArticles(self: *Self, dst_dir: std.fs.Dir) !void {
std.debug.assert(self.is_prepared);
for (self.articles.items) |art| {
try self.renderMarkdownFile(
art.src_file,
dst_dir,
try self.changeExtension(std.fs.path.basename(art.src_file), ".htm"),
);
}
}
fn renderTutorials(self: *Self, dst_dir: std.fs.Dir) !void {
std.debug.assert(self.is_prepared);
for (self.tutorials.items) |tut| {
try self.renderMarkdownFile(
tut.src_file,
dst_dir,
try self.changeExtension(std.fs.path.basename(tut.src_file), ".htm"),
);
}
}
/// Renders a list of all possible articles
fn renderArticleIndex(self: *Self, dst_dir: std.fs.Dir, file_name: []const u8) !void {
std.debug.assert(self.is_prepared);
try self.renderMarkdown(
\\# Articles
\\
\\<!-- ARTICLES -->
, dst_dir, file_name);
}
/// Render a given markdown file into `dst_path`.
fn renderMarkdownFile(self: *Self, src_path: []const u8, dst_dir: std.fs.Dir, dst_path: []const u8) !void {
std.debug.assert(self.is_prepared);
var markdown_input = try std.fs.cwd().readFileAlloc(self.allocator, src_path, 10_000_000);
defer self.allocator.free(markdown_input);
try self.renderMarkdown(markdown_input, dst_dir, dst_path);
}
/// Render the given markdown source into `dst_path`.
/// supported features here are:
/// - `<!-- TOC -->` (renders a table of contents with all items that come *after* said TOC
/// - `<!-- ARTICLES10 -->` Renders the 10 latest articles
/// - `<!-- ARTICLES -->` Renders all articles
fn renderMarkdown(self: *Self, source: []const u8, dst_dir: std.fs.Dir, dst_path: []const u8) !void {
std.debug.assert(self.is_prepared);
var doc: *koino.nodes.AstNode = blk: {
var p = try koino.parser.Parser.init(&self.arena.allocator, markdown_options);
try p.feed(source);
defer p.deinit();
break :blk try p.finish();
};
defer doc.deinit();
std.debug.assert(doc.data.value == .Document);
var output_file = try dst_dir.createFile(dst_path, .{});
defer output_file.close();
var writer = output_file.writer();
try self.renderHeader(writer);
{
var renderer = koino.html.makeHtmlFormatter(writer, &self.arena.allocator, markdown_options);
defer renderer.deinit();
var iter = doc.first_child;
while (iter) |item| : (iter = item.next) {
if (item.data.value == .HtmlBlock) {
const raw_string = item.data.value.HtmlBlock.literal.items;
const string = std.mem.trim(u8, raw_string, " \t\r\n");
if (std.mem.eql(u8, string, "<!-- TOC -->")) {
var min_heading_level: ?u8 = null;
var current_heading_level: u8 = undefined;
var heading_options = markdown_options;
heading_options.render.header_anchors = false;
try writer.writeAll("<ul>");
var it = item.next;
while (it) |child| : (it = child.next) {
if (child.data.value == .Heading) {
var heading = child.data.value.Heading;
if (min_heading_level == null) {
min_heading_level = heading.level;
current_heading_level = heading.level;
}
if (heading.level < min_heading_level.?)
continue;
while (current_heading_level > heading.level) {
try writer.writeAll("</ul>");
current_heading_level -= 1;
}
while (current_heading_level < heading.level) {
try writer.writeAll("<ul>");
current_heading_level += 1;
}
try writer.writeAll("<li><a href=\"#");
try writer.writeAll(try renderer.getNodeAnchor(child));
try writer.writeAll("\">");
{
var i = child.first_child;
while (i) |c| : (i = c.next) {
try koino.html.print(
writer,
&self.arena.allocator,
heading_options,
c,
);
}
}
try writer.writeAll("</a>");
while (current_heading_level > heading.level) {
try writer.writeAll("</ul>");
current_heading_level -= 1;
}
try writer.writeAll("</li>");
}
}
if (min_heading_level) |mhl| {
while (current_heading_level > mhl) {
try writer.writeAll("</ul>");
current_heading_level -= 1;
}
}
try writer.writeAll("</ul>");
} else if (std.mem.eql(u8, string, "<!-- ARTICLES -->")) {
for (self.articles.items[0..std.math.min(self.articles.items.len, 10)]) |art| {
try writer.print(
\\<li><a href="articles/{s}.htm">{} - {s}</a></li>
\\
, .{
try self.urlEscape(removeExtension(std.fs.path.basename(art.src_file))),
art.date,
art.title,
});
}
} else if (std.mem.eql(u8, string, "<!-- ARTICLES -->")) {
try writer.writeAll("<ul>\n");
for (self.articles.items[0..std.math.min(self.articles.items.len, 10)]) |art| {
try writer.print(
\\<li><a href="articles/{s}.htm">{} - {s}</a></li>
\\
, .{
try self.urlEscape(removeExtension(std.fs.path.basename(art.src_file))),
art.date,
art.title,
});
}
try writer.writeAll("</ul>\n");
} else {
std.log.err("Unhandled HTML inline: {s}", .{string});
}
} else {
try renderer.format(item, false);
}
}
}
try self.renderFooter(writer);
}
/// Render the markdown body into `dst_path`.
fn renderHtml(self: Self, source: []const u8, dst_dir: std.fs.Dir, dst_path: []const u8) !void {
std.debug.assert(self.is_prepared);
var output_file = try dst_dir.createFile(dst_path, .{});
defer output_file.close();
var writer = output_file.writer();
try self.renderHeader(writer);
try writer.writeAll(source);
try self.renderFooter(writer);
}
fn renderHeader(self: Self, writer: anytype) !void {
std.debug.assert(self.is_prepared);
try writer.writeAll(
\\<!DOCTYPE html>
\\<html lang="en">
\\
\\<head>
\\ <meta charset="utf-8">
\\ <meta name="viewport" content="width=device-width, initial-scale=1">
\\ <title>ZEG</title>
\\<style>
// Limit the text width of the body to roughly 40 characters
\\ body {
\\ max-width: 40em;
\\ margin-left: auto;
\\ margin-right: auto;
\\ font-family: sans;
\\ }
\\
// Align top-level headings
\\ h1 {
\\ text-align: center;
\\ }
\\
// Make images in headings and links exactly 1 character high.
\\ h1 img, h2 img, h3 img, h3 img, h4 img, h5 img, h6 img, a img {
\\ width: 1em;
\\ height: 1em;
\\ vertical-align: middle;
\\ }
\\
// center images in a paragraph and display them as a block
\\ p > img {
\\ display: block;
\\ max-width: 100%;
\\ margin-left: auto;
\\ margin-right: auto;
\\ }
\\
// Make nice top-level codeblocks
\\ body > pre {
\\ background-color: #EEE;
\\ padding: 0.5em;
\\ }
\\
// Make nice top-level blockquotes
\\ body > blockquote {
\\ border-left: 3pt solid cornflowerblue;
\\ padding-left: 0.5em;
\\ margin-left: 0.5em;
\\ }
\\
// Make links in headings invisible
\\ h1 a, h2 a, h3 a, h4 a, h5 a, h6 a {
\\ text-decoration: none;
\\ font-weight: lighter;
\\ color: unset;
\\ opacity: 10%;
\\ margin-left: -1.5em;
\\ padding-left: 0.5em;
\\ }
\\ h1:hover a, h2:hover a, h3:hover a, h4:hover a, h5:hover a, h6:hover a {
\\ opacity: 50%;
\\ }
\\</style>
\\</head>
\\<body>
);
}
fn renderFooter(self: Self, writer: anytype) !void {
std.debug.assert(self.is_prepared);
try writer.writeAll(
\\</body>
\\</html>
\\
);
}
fn renderAtomFeed(self: *Self, dir: std.fs.Dir, file_name: []const u8) !void {
var feed_file = try dir.createFile(file_name, .{});
defer feed_file.close();
var feed_writer = feed_file.writer();
try feed_writer.writeAll(
\\<?xml version="1.0" encoding="utf-8"?>
\\<feed xmlns="http://www.w3.org/2005/Atom">
\\ <author>
\\ <name><NAME></name>
\\ </author>
\\ <title>Zig Embedded Group</title>
\\ <id>https://zeg.random-projects.net/</id>
\\
);
var last_update = Date{ .year = 0, .month = 0, .day = 0 };
var article_count: usize = 0;
for (self.articles.items) |article| {
if (last_update.lessThan(article.date)) {
last_update = article.date;
article_count = 0;
} else {
article_count += 1;
}
}
try feed_writer.print(" <updated>{d:0>4}-{d:0>2}-{d:0>2}T{d:0>2}:00:00Z</updated>\n", .{
last_update.year,
last_update.month,
last_update.day,
article_count, // this is fake, but is just here for creating a incremental version for multiple articles a day
});
for (self.articles.items) |article| {
const uri_name = try self.urlEscape(removeExtension(article.src_file));
try feed_writer.print(
\\ <entry>
\\ <title>{s}</title>
\\ <link href="https://zeg.random-projects.net/articles/{s}.htm" />
\\ <id>zeg.random-projects.net/articles/{s}.htm</id>
\\ <updated>{d:0>4}-{d:0>2}-{d:0>2}T00:00:00Z</updated>
\\ </entry>
\\
, .{
article.title,
uri_name,
uri_name,
article.date.year,
article.date.month,
article.date.day,
});
}
try feed_writer.writeAll("</feed>");
}
fn renderImages(self: Self, target_dir: std.fs.Dir) !void {
for (self.images.items) |img| {
try std.fs.Dir.copyFile(
std.fs.cwd(),
img,
target_dir,
std.fs.path.basename(img),
.{},
);
}
}
fn renderArticle(self: *Website, article: Article, dst_dir: std.fs.Dir, dst_name: []const u8) !void {
var formatter = HtmlFormatter.init(allocator, options);
defer formatter.deinit();
try formatter.format(root, false);
return formatter.buffer.toOwnedSlice();
}
}; | src/main.zig |
const std = @import("std");
const server = &@import("../main.zig").server;
const Direction = @import("../command.zig").Direction;
const Error = @import("../command.zig").Error;
const Seat = @import("../Seat.zig");
const View = @import("../View.zig");
const ViewStack = @import("../view_stack.zig").ViewStack;
/// Focus either the next or the previous visible view, depending on the enum
/// passed. Does nothing if there are 1 or 0 views in the stack.
pub fn focusView(
allocator: *std.mem.Allocator,
seat: *Seat,
args: []const [:0]const u8,
out: *?[]const u8,
) Error!void {
if (args.len < 2) return Error.NotEnoughArguments;
if (args.len > 2) return Error.TooManyArguments;
const direction = std.meta.stringToEnum(Direction, args[1]) orelse return Error.InvalidDirection;
const output = seat.focused_output;
if (seat.focused == .view) {
// If the focused view is fullscreen, do nothing
if (seat.focused.view.current.fullscreen) return;
// If there is a currently focused view, focus the next visible view in the stack.
const focused_node = @fieldParentPtr(ViewStack(View).Node, "view", seat.focused.view);
var it = switch (direction) {
.next => ViewStack(View).iter(focused_node, .forward, output.pending.tags, filter),
.previous => ViewStack(View).iter(focused_node, .reverse, output.pending.tags, filter),
};
// Skip past the focused node
_ = it.next();
// Focus the next visible node if there is one
if (it.next()) |view| {
seat.focus(view);
server.root.startTransaction();
return;
}
}
// There is either no currently focused view or the last visible view in the
// stack is focused and we need to wrap.
var it = switch (direction) {
.next => ViewStack(View).iter(output.views.first, .forward, output.pending.tags, filter),
.previous => ViewStack(View).iter(output.views.last, .reverse, output.pending.tags, filter),
};
seat.focus(it.next());
server.root.startTransaction();
}
fn filter(view: *View, filter_tags: u32) bool {
return view.surface != null and view.pending.tags & filter_tags != 0;
} | source/river-0.1.0/river/command/focus_view.zig |
const std = @import("std");
const options = @import("build_options");
const encode = @import("encoder.zig");
const decode = @import("decoder.zig");
const encoder = encode.BottomEncoder;
const decoder = decode.BottomDecoder;
const CSlice = extern struct {
ptr: ?[*]const u8,
len: usize,
};
/// Error code 0 - no error
/// Error code 1 = not enough memory
/// Error code 2 = Invalid Input
export var bottom_current_error: u8 = 0;
var gpa = std.heap.GeneralPurposeAllocator(.{}){};
fn bottomEncodeAlloc(input: [*]u8, len: usize) callconv(.C) CSlice {
var allocator = blk: {
if (options.use_c) {
break :blk std.heap.c_allocator;
} else {
break :blk gpa.allocator();
}
};
var res = encoder.encodeAlloc(input[0..len], allocator) catch |err| {
if (err == error.OutOfMemory) {
bottom_current_error = 1;
}
return CSlice{ .ptr = null, .len = 0 };
};
return CSlice{ .ptr = res.ptr, .len = res.len };
}
fn bottomEncodeBuf(input: [*]u8, len: usize, buf: [*]u8, buf_len: usize) callconv(.C) CSlice {
if (buf_len < len) {
bottom_current_error = 1;
return CSlice{ .ptr = null, .len = 0 };
}
if (buf_len < len * encoder.max_expansion_per_byte) {
bottom_current_error = 1;
return CSlice{ .ptr = null, .len = 0 };
}
var a = encoder.encode(input[0..len], buf[0..buf_len]);
return CSlice{ .ptr = a.ptr, .len = a.len };
}
fn bottomDecodeAlloc(input: [*]u8, len: usize) callconv(.C) CSlice {
var allocator = blk: {
if (options.use_c) {
break :blk std.heap.c_allocator;
} else {
break :blk gpa.allocator();
}
};
var res = decoder.decodeAlloc(input[0..len], allocator) catch |err| {
if (err == error.OutOfMemory) {
bottom_current_error = 1;
} else if (err == error.invalid_input) {
bottom_current_error = 2;
}
return CSlice{ .ptr = null, .len = 0 };
};
return CSlice{ .ptr = res.ptr, .len = res.len };
}
fn bottomDecodeBuf(input: [*]u8, len: usize, buf: [*]u8, buf_len: usize) callconv(.C) CSlice {
if (buf_len < len) {
bottom_current_error = 1;
return CSlice{ .ptr = null, .len = 0 };
}
var a = decoder.decode(input[0..len], buf[0..buf_len]) catch |err| {
if (err == error.invalid_input) {
bottom_current_error = 2;
}
return CSlice{ .ptr = null, .len = 0 };
};
return CSlice{ .ptr = a.ptr, .len = a.len };
}
fn getError() callconv(.C) u8 {
defer {
bottom_current_error = 0;
}
return bottom_current_error;
}
const error_no_error_string = "No error";
const error_not_enough_memory_string = "Not enough memory";
const error_invalid_input_string = "Invalid input";
const error_unknown_error_string = "Unknown error";
fn getErrorString(error_code: u8) callconv(.C) CSlice {
if (error_code == 0) {
return CSlice{ .ptr = error_no_error_string, .len = error_no_error_string.len };
}
if (error_code == 1) {
return CSlice{ .ptr = error_not_enough_memory_string, .len = error_not_enough_memory_string.len };
}
if (error_code == 2) {
return CSlice{ .ptr = error_invalid_input_string, .len = error_invalid_input_string.len };
}
return CSlice{ .ptr = error_unknown_error_string, .len = error_unknown_error_string.len };
}
fn getVersion() callconv(.C) CSlice {
const version = options.version;
return CSlice{ .ptr = version.ptr, .len = version.len };
}
fn freeSlice(slice: CSlice) callconv(.C) void{
var allocator = blk: {
if (options.use_c) {
break :blk std.heap.c_allocator;
} else {
break :blk gpa.allocator();
}
};
allocator.free(slice.ptr.?[0..slice.len]);
}
comptime {
@export(bottomDecodeAlloc, .{ .name = "bottom_decode_alloc", .linkage = .Strong });
@export(bottomDecodeBuf, .{ .name = "bottom_decode_buf", .linkage = .Strong });
@export(bottomEncodeAlloc, .{ .name = "bottom_encode_alloc", .linkage = .Strong });
@export(bottomEncodeBuf, .{ .name = "bottom_encode_buf", .linkage = .Strong });
@export(getError, .{ .name = "bottom_get_error", .linkage = .Strong });
@export(getErrorString, .{ .name = "bottom_get_error_string", .linkage = .Strong });
@export(getVersion, .{ .name = "bottom_get_version", .linkage = .Strong });
@export(freeSlice, .{ .name = "bottom_free_slice", .linkage = .Strong });
} | src/clib.zig |
const std = @import("std");
const Allocator = std.mem.Allocator;
// This is used to keep track of values that
// are defined.
const Environment = std.StringHashMap(*Value);
const EvaluationError = error{
Undefined,
NonFunctionCalled,
} || Allocator.Error;
const Expression = union(enum) {
variable: []const u8,
lambda: struct {
name: []const u8,
body: *Expression,
},
application: struct {
operator: *Expression,
operand: *Expression,
},
fn eval(self: *Expression, environment: *Environment, allocator: Allocator) EvaluationError!*Value {
return switch (self.*) {
.variable => |variable| blk: {
if (environment.get(variable)) |value| {
break :blk value;
} else {
return error.Undefined;
}
},
.lambda => |lambda| blk: {
var closure = try allocator.create(Value);
closure.* = Value{
.closure = .{
.name = lambda.name,
.body = lambda.body,
.environment = environment,
},
};
break :blk closure;
},
.application => |application| blk: {
var left = try application.operator.eval(environment, allocator);
defer allocator.destroy(left);
var right = try application.operand.eval(environment, allocator);
break :blk try left.call(right, allocator);
},
};
}
};
const Value = union(enum) {
int: usize,
str: []const u8,
closure: struct {
name: []const u8,
body: *Expression,
environment: *Environment,
},
fn call(self: *Value, argument: *Value, allocator: Allocator) EvaluationError!*Value {
return switch (self.*) {
.closure => |closure| blk: {
try closure.environment.put(closure.name, argument);
break :blk try closure.body.eval(closure.environment, allocator);
},
else => {
return error.NonFunctionCalled;
},
};
}
};
test "calculus" {
var environment = Environment.init(std.testing.allocator);
defer environment.deinit();
var x_variable = Expression{ .variable = "x" };
const undefined_result = x_variable.eval(&environment, std.testing.allocator);
// x is undefined
try std.testing.expectError(
error.Undefined,
undefined_result,
);
var int_value = Value{ .int = 123 };
try environment.put("x", &int_value);
const int_result = try x_variable.eval(&environment, std.testing.allocator);
try std.testing.expectEqual(
int_value,
int_result.*,
);
var identity = Expression{
.lambda = .{
.name = "x",
.body = &x_variable,
},
};
var y_variable = Expression{ .variable = "y" };
var application = Expression{
.application = .{
.operator = &identity,
.operand = &y_variable,
},
};
const another_undefined_result = application.eval(&environment, std.testing.allocator);
// y is undefined
try std.testing.expectError(
error.Undefined,
another_undefined_result,
);
var str_value = Value{ .str = "some string" };
try environment.put("y", &str_value);
const str_result = try application.eval(&environment, std.testing.allocator);
try std.testing.expectEqual(
str_value,
str_result.*,
);
} | src/main.zig |
const std = @import("std");
const formats = @import("formats.zig");
const int = @import("../int.zig");
const nds = @import("../nds.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 os = std.os;
const testing = std.testing;
const lu16 = int.lu16;
const lu32 = int.lu32;
pub const Dir = struct { i: u16 };
pub const File = struct { i: u32 };
pub const Handle = union(enum) {
file: File,
dir: Dir,
};
pub const root = Dir{ .i = 0 };
pub const Fs = struct {
fnt_main: []FntMainEntry,
fnt: []u8,
fat: []nds.Range,
data: []u8,
pub fn openNarc(fs: nds.fs.Fs, dir: Dir, path: []const u8) !nds.fs.Fs {
const file = try fs.openFileData(dir, path);
return try nds.fs.Fs.fromNarc(file);
}
pub fn openFileData(fs: Fs, dir: Dir, path: []const u8) ![]u8 {
const file = try fs.openFile(dir, path);
return fs.fileData(file);
}
pub fn openFile(fs: Fs, dir: Dir, path: []const u8) !File {
const handle = try fs.open(dir, path);
if (handle == .dir)
return error.DoesntExist;
return handle.file;
}
pub fn openDir(fs: Fs, dir: Dir, path: []const u8) !Dir {
const handle = try fs.open(dir, path);
if (handle == .file)
return error.DoesntExist;
return handle.dir;
}
pub fn open(fs: Fs, dir: Dir, path: []const u8) !Handle {
var handle = Handle{ .dir = dir };
const relative = if (mem.startsWith(u8, path, "/")) blk: {
handle.dir = root; // Set handle to root
break :blk path[1..];
} else path;
var split = mem.split(u8, relative, "/");
while (split.next()) |name| {
switch (handle) {
.file => return error.DoesntExist,
.dir => |d| {
var it = fs.iterate(d);
handle = it.find(name) orelse return error.DoesntExist;
},
}
}
return handle;
}
pub fn iterate(fs: Fs, dir: Dir) Iterator {
const fnt_entry = fs.fnt_main[dir.i];
const file_handle = fnt_entry.first_file_handle.value();
const offset = fnt_entry.offset_to_subtable.value();
debug.assert(fs.fnt.len >= offset);
return Iterator{
.file_handle = file_handle,
.fnt_sub_table = fs.fnt[offset..],
};
}
pub fn fileAs(fs: Fs, file: File, comptime T: type) !*T {
const data = fs.fileData(file);
if (@sizeOf(T) > data.len)
return error.FileToSmall;
return @ptrCast(*T, data.ptr);
}
pub fn fileData(fs: Fs, file: File) []u8 {
const f = fs.fat[file.i];
return fs.data[f.start.value()..f.end.value()];
}
/// Reinterprets the file system as a slice of T. This can only be
/// done if the file system is arranged in a certain way:
/// * All files must have the same size of `@sizeOf(T)`
/// * All files must be arranged sequentially in memory with no padding
/// and in the same order as the `fat`.
///
/// This function is useful when working with roms that stores arrays
/// of structs in narc file systems.
pub fn toSlice(fs: Fs, first: usize, comptime T: type) ![]T {
if (fs.fat.len == first)
return &[0]T{};
const start = fs.fat[first].start.value();
var end = start;
for (fs.fat[first..]) |fat| {
const fat_start = fat.start.value();
if (fat_start != end)
return error.FsIsNotSequential;
end += @sizeOf(T);
}
return mem.bytesAsSlice(T, fs.data[start..end]);
}
pub fn fromFnt(fnt: []u8, fat: []nds.Range, data: []u8) Fs {
return Fs{
.fnt_main = fntMainTable(fnt),
.fnt = fnt,
.fat = fat,
.data = data,
};
}
fn fntMainTable(fnt: []u8) []FntMainEntry {
const rem = fnt.len % @sizeOf(FntMainEntry);
const fnt_mains = mem.bytesAsSlice(FntMainEntry, fnt[0 .. fnt.len - rem]);
const len = fnt_mains[0].parent_id.value();
debug.assert(fnt_mains.len >= len and len <= 4096 and len != 0);
return fnt_mains[0..len];
}
/// Get a file system from a narc file. This function can faile if the
/// bytes are not a valid narc.
pub fn fromNarc(data: []u8) !Fs {
var fbs = io.fixedBufferStream(data);
const reader = fbs.reader();
const names = formats.Chunk.names;
const header = try reader.readStruct(formats.Header);
if (!mem.eql(u8, &header.chunk_name, names.narc))
return error.InvalidNarcHeader;
if (header.byte_order.value() != 0xFFFE)
return error.InvalidNarcHeader;
if (header.chunk_size.value() != 0x0010)
return error.InvalidNarcHeader;
if (header.following_chunks.value() != 0x0003)
return error.InvalidNarcHeader;
const fat_header = try reader.readStruct(formats.FatChunk);
if (!mem.eql(u8, &fat_header.header.name, names.fat))
return error.InvalidNarcHeader;
const fat_size = fat_header.header.size.value() - @sizeOf(formats.FatChunk);
const fat = mem.bytesAsSlice(nds.Range, data[fbs.pos..][0..fat_size]);
fbs.pos += fat_size;
const fnt_header = try reader.readStruct(formats.Chunk);
const fnt_size = fnt_header.size.value() - @sizeOf(formats.Chunk);
if (!mem.eql(u8, &fnt_header.name, names.fnt))
return error.InvalidNarcHeader;
const fnt = data[fbs.pos..][0..fnt_size];
fbs.pos += fnt_size;
const file_data_header = try reader.readStruct(formats.Chunk);
if (!mem.eql(u8, &file_data_header.name, names.file_data))
return error.InvalidNarcHeader;
return Fs.fromFnt(fnt, fat, data[fbs.pos..]);
}
};
pub const Iterator = struct {
file_handle: u32,
fnt_sub_table: []const u8,
pub const Result = struct {
handle: Handle,
name: []const u8,
};
pub fn next(it: *Iterator) ?Result {
var fbs = io.fixedBufferStream(it.fnt_sub_table);
const reader = fbs.reader();
const type_length = reader.readByte() catch return null;
if (type_length == 0)
return null;
const length = type_length & 0x7F;
const is_folder = (type_length & 0x80) != 0;
const name = fbs.buffer[fbs.pos..][0..length];
fbs.pos += length;
const handle = if (is_folder) blk: {
const read_id = reader.readIntLittle(u16) catch return null;
debug.assert(read_id >= 0xF001 and read_id <= 0xFFFF);
break :blk read_id & 0x0FFF;
} else blk: {
defer it.file_handle += 1;
break :blk it.file_handle;
};
it.fnt_sub_table = fbs.buffer[fbs.pos..];
return Result{
.handle = if (is_folder)
Handle{ .dir = .{ .i = @intCast(u16, handle) } }
else
Handle{ .file = .{ .i = handle } },
.name = name,
};
}
pub fn find(it: *Iterator, name: []const u8) ?Handle {
while (it.next()) |entry| {
if (mem.eql(u8, entry.name, name))
return entry.handle;
}
return null;
}
};
pub const FntMainEntry = packed struct {
offset_to_subtable: lu32,
first_file_handle: lu16,
// For the first entry in main-table, the parent id is actually,
// the total number of directories (See FNT Directory Main-Table):
// http://problemkaputt.de/gbatek.htm#dscartridgenitroromandnitroarcfilesystems
parent_id: lu16,
};
pub fn narcSize(file_count: usize, data_size: usize) usize {
return @sizeOf(formats.Header) +
@sizeOf(formats.FatChunk) +
@sizeOf(nds.Range) * file_count +
@sizeOf(formats.Chunk) * 2 +
@sizeOf(FntMainEntry) +
data_size;
}
pub const SimpleNarcBuilder = struct {
stream: io.FixedBufferStream([]u8),
pub fn init(buf: []u8, file_count: usize) SimpleNarcBuilder {
const writer = io.fixedBufferStream(buf).writer();
writer.writeAll(&mem.toBytes(formats.Header.narc(0))) catch unreachable;
writer.writeAll(&mem.toBytes(formats.FatChunk.init(@intCast(u16, file_count)))) catch unreachable;
writer.context.pos += file_count * @sizeOf(nds.Range);
writer.writeAll(&mem.toBytes(formats.Chunk{
.name = formats.Chunk.names.fnt.*,
.size = lu32.init(@sizeOf(formats.Chunk) + @sizeOf(FntMainEntry)),
})) catch unreachable;
writer.writeAll(&mem.toBytes(FntMainEntry{
.offset_to_subtable = lu32.init(0),
.first_file_handle = lu16.init(0),
.parent_id = lu16.init(1),
})) catch unreachable;
writer.writeAll(&mem.toBytes(formats.Chunk{
.name = formats.Chunk.names.file_data.*,
.size = lu32.init(0),
})) catch unreachable;
return SimpleNarcBuilder{ .stream = writer.context.* };
}
pub fn fat(builder: SimpleNarcBuilder) []nds.Range {
const res = builder.stream.buffer;
const off = @sizeOf(formats.Header);
const fat_header = mem.bytesAsValue(
formats.FatChunk,
res[off..][0..@sizeOf(formats.FatChunk)],
);
const size = fat_header.header.size.value();
return mem.bytesAsSlice(
nds.Range,
res[off..][0..size][@sizeOf(formats.FatChunk)..],
);
}
pub fn finish(builder: *SimpleNarcBuilder) []u8 {
const res = builder.stream.buffer;
var off: usize = 0;
const header = mem.bytesAsValue(
formats.Header,
res[0..@sizeOf(formats.Header)],
);
off += @sizeOf(formats.Header);
const fat_header = mem.bytesAsValue(
formats.FatChunk,
res[off..][0..@sizeOf(formats.FatChunk)],
);
off += fat_header.header.size.value();
const fnt_header = mem.bytesAsValue(
formats.Chunk,
res[off..][0..@sizeOf(formats.Chunk)],
);
off += fnt_header.size.value();
const file_header = mem.bytesAsValue(
formats.Chunk,
res[off..][0..@sizeOf(formats.Chunk)],
);
header.file_size = lu32.init(@intCast(u32, res.len));
file_header.size = lu32.init(@intCast(u32, res.len - off));
return res;
}
};
pub const Builder = struct {
fnt_main: std.ArrayList(FntMainEntry),
fnt_sub: std.ArrayList(u8),
fat: std.ArrayList(nds.Range),
file_bytes: u32,
pub fn init(allocator: mem.Allocator) !Builder {
var fnt_main = std.ArrayList(FntMainEntry).init(allocator);
var fnt_sub = std.ArrayList(u8).init(allocator);
errdefer fnt_main.deinit();
errdefer fnt_sub.deinit();
try fnt_main.append(.{
.offset_to_subtable = lu32.init(0),
.first_file_handle = lu16.init(0),
.parent_id = lu16.init(1),
});
try fnt_sub.append(0);
return Builder{
.fnt_main = fnt_main,
.fnt_sub = fnt_sub,
.fat = std.ArrayList(nds.Range).init(allocator),
.file_bytes = 0,
};
}
pub fn createTree(b: *Builder, dir: Dir, path: []const u8) !Dir {
var curr = dir;
const relative = if (mem.startsWith(u8, path, "/")) blk: {
curr = root; // Set handle to root
break :blk path[1..];
} else path;
var split = mem.split(u8, relative, "/");
while (split.next()) |name|
curr = try b.createDir(curr, name);
return curr;
}
pub fn createDir(b: *Builder, dir: Dir, path: []const u8) !Dir {
const fs = b.toFs();
const dir_name = std.fs.path.basenamePosix(path);
const parent = if (std.fs.path.dirnamePosix(path)) |parent_path|
try fs.openDir(dir, parent_path)
else
dir;
if (fs.openDir(parent, dir_name)) |handle| {
return handle;
} else |err| switch (err) {
error.DoesntExist => {},
}
const parent_entry = b.fnt_main.items[parent.i];
const parent_offset = parent_entry.offset_to_subtable.value();
const handle = @intCast(u16, b.fnt_main.items.len);
var buf: [1024]u8 = undefined;
const fbs = io.fixedBufferStream(&buf).writer();
const len = @intCast(u7, dir_name.len);
const kind = @as(u8, @boolToInt(true)) << 7;
const id = @intCast(u16, 0xF000 | b.fnt_main.items.len);
try fbs.writeByte(kind | len);
try fbs.writeAll(dir_name);
try fbs.writeIntLittle(u16, id);
const written = fbs.context.getWritten();
try b.fnt_sub.ensureTotalCapacity(b.fnt_sub.items.len + written.len + 1);
b.fnt_sub.insertSlice(parent_offset, written) catch unreachable;
const offset = @intCast(u32, b.fnt_sub.items.len);
b.fnt_sub.appendAssumeCapacity(0);
for (b.fnt_main.items) |*entry| {
const old_offset = entry.offset_to_subtable.value();
const new_offset = old_offset + written.len;
if (old_offset > parent_offset)
entry.offset_to_subtable = lu32.init(@intCast(u32, new_offset));
}
try b.fnt_main.append(.{
.offset_to_subtable = lu32.init(offset),
.first_file_handle = parent_entry.first_file_handle,
.parent_id = lu16.init(parent.i),
});
return Dir{ .i = handle };
}
pub fn createFile(b: *Builder, dir: Dir, path: []const u8, size: u32) !File {
const fs = b.toFs();
const file_name = std.fs.path.basenamePosix(path);
const parent = if (std.fs.path.dirnamePosix(path)) |parent_path|
try fs.openDir(dir, parent_path)
else
dir;
if (fs.openFile(parent, file_name)) |handle| {
return handle;
} else |err| switch (err) {
error.DoesntExist => {},
}
const parent_entry = b.fnt_main.items[parent.i];
const parent_offset = parent_entry.offset_to_subtable.value();
const handle = parent_entry.first_file_handle.value();
var buf: [1024]u8 = undefined;
const fbs = io.fixedBufferStream(&buf).writer();
const len = @intCast(u7, file_name.len);
const kind = @as(u8, @boolToInt(false)) << 7;
try fbs.writeByte(kind | len);
try fbs.writeAll(file_name);
const written = fbs.context.getWritten();
try b.fnt_sub.ensureTotalCapacity(b.fnt_sub.items.len + written.len);
b.fnt_sub.insertSlice(parent_offset, written) catch unreachable;
for (b.fnt_main.items) |*entry, i| {
const old_offset = entry.offset_to_subtable.value();
const new_offset = old_offset + written.len;
if (old_offset > parent_offset)
entry.offset_to_subtable = lu32.init(@intCast(u32, new_offset));
const old_file_handle = entry.first_file_handle.value();
const new_file_handle = old_file_handle + 1;
if (old_file_handle >= handle and parent.i != i)
entry.first_file_handle = lu16.init(@intCast(u16, new_file_handle));
}
const start = b.file_bytes;
try b.fat.insert(handle, nds.Range.init(start, start + size));
b.file_bytes += size;
return File{ .i = handle };
}
pub fn toFs(b: Builder) Fs {
return Fs{
.fnt_main = b.fnt_main.items,
.fnt = b.fnt_sub.items,
.fat = b.fat.items,
.data = &[_]u8{},
};
}
// Leaves builder in a none usable state. Only `deinit` is valid
// after `finish`
pub fn finish(builder: *Builder) !Fs {
const sub_table_offset = builder.fnt_main.items.len * @sizeOf(FntMainEntry);
for (builder.fnt_main.items) |*entry| {
const new_offset = entry.offset_to_subtable.value() + sub_table_offset;
entry.offset_to_subtable = lu32.init(@intCast(u32, new_offset));
}
const fnt_main_bytes = mem.sliceAsBytes(builder.fnt_main.items);
try builder.fnt_sub.insertSlice(0, fnt_main_bytes);
return Fs{
.fnt_main = builder.fnt_main.toOwnedSlice(),
.fnt = builder.fnt_sub.toOwnedSlice(),
.fat = builder.fat.toOwnedSlice(),
.data = &[_]u8{},
};
}
pub fn deinit(builder: Builder) void {
builder.fnt_main.deinit();
builder.fnt_sub.deinit();
builder.fat.deinit();
}
};
test "Builder" {
const paths = [_][]const u8{
"a/a",
"a/b",
"a/c/a",
"b",
"d/a",
};
var b = try Builder.init(testing.allocator);
defer b.deinit();
for (paths) |path| {
if (std.fs.path.dirnamePosix(path)) |dir_path|
_ = try b.createTree(root, dir_path);
_ = try b.createFile(root, path, 0);
}
const fs = try b.finish();
defer testing.allocator.free(fs.fnt_main);
defer testing.allocator.free(fs.fnt);
defer testing.allocator.free(fs.fat);
for (paths) |path|
_ = try fs.openFile(root, path);
try testing.expectError(error.DoesntExist, fs.openFile(root, "a"));
try testing.expectError(error.DoesntExist, fs.openFile(root, "a/c"));
try testing.expectError(error.DoesntExist, fs.openFile(root, "a/c/b"));
} | src/core/rom/nds/fs.zig |
usingnamespace @import("root").preamble;
const fmt_lib = @import("fmt.zig");
const Mutex = os.thread.Mutex;
var mutex = Mutex{};
noinline fn getLock() Mutex.Held {
return mutex.acquire();
}
const enable_all_logging = false;
fn enabled(comptime tag: anytype, comptime log_level: ?std.log.Level) bool {
if (enable_all_logging) return true;
const filter: ?std.log.Level = tag.filter;
if (filter) |f| {
if (log_level) |l| {
return @enumToInt(l) < @enumToInt(f);
}
}
return true;
}
fn held_t(comptime tag: anytype, comptime log_level: ?std.log.Level) type {
return if (enabled(tag, log_level)) Mutex.Held else void;
}
fn taggedLogFmt(comptime tag: anytype, comptime log_level: ?std.log.Level, comptime fmt: []const u8) []const u8 {
if (log_level != null)
return "[" ++ tag.prefix ++ "] " ++ @tagName(log_level.?) ++ ": " ++ fmt;
return "[" ++ tag.prefix ++ "] " ++ fmt;
}
fn writeImpl(comptime tag: anytype, comptime log_level: ?std.log.Level, comptime fmt: []const u8, args: anytype) callconv(.Inline) void {
if (comptime enabled(tag, log_level)) {
const l = getLock();
defer l.release();
fmt_lib.doFmt(comptime taggedLogFmt(tag, log_level, fmt), args);
}
}
fn startImpl(comptime tag: anytype, comptime log_level: ?std.log.Level, comptime fmt: []const u8, args: anytype) callconv(.Inline) held_t(tag, log_level) {
if (comptime enabled(tag, log_level)) {
const l = getLock();
fmt_lib.doFmtNoEndl(comptime taggedLogFmt(tag, log_level, fmt), args);
return l;
}
}
fn contImpl(comptime tag: anytype, comptime log_level: ?std.log.Level, comptime fmt: []const u8, args: anytype, _: held_t(tag, log_level)) callconv(.Inline) void {
if (comptime enabled(tag, log_level)) {
fmt_lib.doFmtNoEndl(fmt, args);
}
}
fn finishImpl(comptime tag: anytype, comptime log_level: ?std.log.Level, comptime fmt: []const u8, args: anytype, l: held_t(tag, log_level)) callconv(.Inline) void {
if (comptime enabled(tag, log_level)) {
fmt_lib.doFmt(fmt, args);
l.release();
}
}
pub fn scoped(comptime tag: anytype) type {
return struct {
pub const write = struct {
pub fn f(comptime log_level: ?std.log.Level, comptime fmt: []const u8, args: anytype) callconv(.Inline) void {
writeImpl(tag, log_level, fmt, args);
}
}.f;
pub const start = struct {
pub fn f(comptime log_level: ?std.log.Level, comptime fmt: []const u8, args: anytype) callconv(.Inline) held_t(tag, log_level) {
return startImpl(tag, log_level, fmt, args);
}
}.f;
pub const cont = struct {
pub fn f(comptime log_level: ?std.log.Level, comptime fmt: []const u8, args: anytype, m: held_t(tag, log_level)) callconv(.Inline) void {
return contImpl(tag, log_level, fmt, args, m);
}
}.f;
pub const finish = struct {
pub fn f(comptime log_level: ?std.log.Level, comptime fmt: []const u8, args: anytype, m: held_t(tag, log_level)) callconv(.Inline) void {
return finishImpl(tag, log_level, fmt, args, m);
}
}.f;
};
} | lib/output/log.zig |
const std = @import("std");
const path = std.fs.path;
const Builder = std.build.Builder;
const LibExeObjStep = std.build.LibExeObjStep;
const glslc_command = if (std.builtin.os.tag == .windows) "tools/win/glslc.exe" else "glslc";
pub fn build(b: *Builder) void {
{
const exe = exampleExe(b, "example_glfw_vulkan");
linkGlfw(exe);
linkVulkan(exe);
}
{
const exe = exampleExe(b, "example_glfw_opengl3");
linkGlfw(exe);
linkGlad(exe);
}
}
fn exampleExe(b: *Builder, comptime name: var) *LibExeObjStep {
const mode = b.standardReleaseOptions();
const exe = b.addExecutable(name, name ++ ".zig");
exe.setBuildMode(mode);
exe.linkLibC();
exe.addPackagePath("imgui", "../zig/imgui.zig");
if (std.builtin.os.tag == .windows) {
exe.linkSystemLibrary("../lib/win/cimguid");
} else {
@compileError("TODO: Build and link cimgui for non-windows platforms");
}
exe.install();
const run_step = b.step(name, "Run " ++ name);
const run_cmd = exe.run();
run_step.dependOn(&run_cmd.step);
return exe;
}
fn linkGlad(exe: *LibExeObjStep) void {
exe.addIncludeDir("include/c_include");
exe.addCSourceFile("c_src/glad.c", &[_][]const u8{"-std=c99"});
//exe.linkSystemLibrary("opengl");
}
fn linkGlfw(exe: *LibExeObjStep) void {
if (std.builtin.os.tag == .windows) {
exe.linkSystemLibrary("lib/win/glfw3");
exe.linkSystemLibrary("gdi32");
exe.linkSystemLibrary("shell32");
} else {
exe.linkSystemLibrary("glfw");
}
}
fn linkVulkan(exe: *LibExeObjStep) void {
if (std.builtin.os.tag == .windows) {
exe.linkSystemLibrary("lib/win/vulkan-1");
} else {
exe.linkSystemLibrary("vulkan");
}
}
fn linkStbImage(exe: *LibExeObjStep) void {
@compileError("This file hasn't actually been added to the project yet.");
exe.addCSourceFile("c_src/stb_image.c", [_][]const u8{ "-std=c99", "-DSTB_IMAGE_IMPLEMENTATION=1" });
}
fn addShader(b: *Builder, exe: var, in_file: []const u8, out_file: []const u8) !void {
// example:
// glslc -o shaders/vert.spv shaders/shader.vert
const dirname = "shaders";
const full_in = try path.join(b.allocator, [_][]const u8{ dirname, in_file });
const full_out = try path.join(b.allocator, [_][]const u8{ dirname, out_file });
const run_cmd = b.addSystemCommand([_][]const u8{
glslc_command,
"-o",
full_out,
full_in,
});
exe.step.dependOn(&run_cmd.step);
} | examples/build.zig |
const std = @import("std");
const builtin = @import("builtin");
const shared = @import("./src/shared.zig");
pub fn build(b: *std.build.Builder) !void {
const target = b.standardTargetOptions(.{});
const mode = b.standardReleaseOptions();
const exe = b.addExecutable("zls", "src/main.zig");
const exe_options = b.addOptions();
exe.addOptions("build_options", exe_options);
exe_options.addOption(
shared.ZigVersion,
"data_version",
b.option(shared.ZigVersion, "data_version", "The Zig version your compiler is.") orelse .master,
);
exe_options.addOption(
std.log.Level,
"log_level",
b.option(std.log.Level, "log_level", "The Log Level to be used.") orelse .info,
);
const enable_tracy = b.option(bool, "enable_tracy", "Whether of not tracy should be enabled.") orelse false;
exe_options.addOption(
bool,
"enable_tracy",
enable_tracy,
);
exe_options.addOption(
bool,
"enable_tracy_allocation",
b.option(bool, "enable_tracy_allocation", "Enable using TracyAllocator to monitor allocations.") orelse false,
);
exe_options.addOption(
bool,
"enable_tracy_callstack",
b.option(bool, "enable_tracy_callstack", "Enable callstack graphs.") orelse false,
);
exe.addPackage(.{ .name = "known-folders", .source = .{ .path = "src/known-folders/known-folders.zig" } });
if (enable_tracy) {
const client_cpp = "src/tracy/TracyClient.cpp";
// On mingw, we need to opt into windows 7+ to get some features required by tracy.
const tracy_c_flags: []const []const u8 = if (target.isWindows() and target.getAbi() == .gnu)
&[_][]const u8{ "-DTRACY_ENABLE=1", "-fno-sanitize=undefined", "-D_WIN32_WINNT=0x601" }
else
&[_][]const u8{ "-DTRACY_ENABLE=1", "-fno-sanitize=undefined" };
exe.addIncludePath("src/tracy");
exe.addCSourceFile(client_cpp, tracy_c_flags);
exe.linkSystemLibraryName("c++");
exe.linkLibC();
if (target.isWindows()) {
exe.linkSystemLibrary("dbghelp");
exe.linkSystemLibrary("ws2_32");
}
}
exe.setTarget(target);
exe.setBuildMode(mode);
exe.install();
b.installFile("src/special/build_runner.zig", "bin/build_runner.zig");
const test_step = b.step("test", "Run all the tests");
test_step.dependOn(b.getInstallStep());
var unit_tests = b.addTest("src/unit_tests.zig");
unit_tests.setBuildMode(.Debug);
unit_tests.setTarget(target);
test_step.dependOn(&unit_tests.step);
var session_tests = b.addTest("tests/sessions.zig");
session_tests.addPackage(.{ .name = "header", .source = .{ .path = "src/header.zig" } });
session_tests.setBuildMode(.Debug);
session_tests.setTarget(target);
test_step.dependOn(&session_tests.step);
} | build.zig |
const zang = @import("zang");
const note_frequencies = @import("zang-12tet");
const common = @import("common.zig");
const c = @import("common/c.zig");
pub const AUDIO_FORMAT: zang.AudioFormat = .signed16_lsb;
pub const AUDIO_SAMPLE_RATE = 48000;
pub const AUDIO_BUFFER_SIZE = 1024;
pub const DESCRIPTION =
\\example_envelope
\\
\\Basic example demonstrating the ADSR envelope. Press
\\spacebar to trigger the envelope.
;
const a4 = 440.0;
pub const Instrument = struct {
pub const num_outputs = 1;
pub const num_temps = 2;
pub const Params = struct {
sample_rate: f32,
freq: f32,
note_on: bool,
};
osc: zang.PulseOsc,
env: zang.Envelope,
pub fn init() Instrument {
return .{
.osc = zang.PulseOsc.init(),
.env = zang.Envelope.init(),
};
}
pub fn paint(
self: *Instrument,
span: zang.Span,
outputs: [num_outputs][]f32,
temps: [num_temps][]f32,
note_id_changed: bool,
params: Params,
) void {
zang.zero(span, temps[0]);
self.osc.paint(span, .{temps[0]}, .{}, note_id_changed, .{
.sample_rate = params.sample_rate,
.freq = zang.constant(params.freq),
.color = 0.5,
});
zang.zero(span, temps[1]);
self.env.paint(span, .{temps[1]}, .{}, note_id_changed, .{
.sample_rate = params.sample_rate,
.attack = .{ .cubed = 1.0 },
.decay = .{ .cubed = 1.0 },
.release = .{ .cubed = 1.0 },
.sustain_volume = 0.5,
.note_on = params.note_on,
});
zang.multiplyWithScalar(span, temps[1], 5.0);
zang.multiply(span, outputs[0], temps[0], temps[1]);
}
};
pub const MainModule = struct {
pub const num_outputs = 1;
pub const num_temps = 2;
pub const output_audio = common.AudioOut{ .mono = 0 };
pub const output_visualize = 0;
iq: zang.Notes(Instrument.Params).ImpulseQueue,
idgen: zang.IdGenerator,
instr: Instrument,
trig: zang.Trigger(Instrument.Params),
pub fn init() MainModule {
return .{
.iq = zang.Notes(Instrument.Params).ImpulseQueue.init(),
.idgen = zang.IdGenerator.init(),
.instr = Instrument.init(),
.trig = zang.Trigger(Instrument.Params).init(),
};
}
pub fn paint(
self: *MainModule,
span: zang.Span,
outputs: [num_outputs][]f32,
temps: [num_temps][]f32,
) void {
var ctr = self.trig.counter(span, self.iq.consume());
while (self.trig.next(&ctr)) |result| {
self.instr.paint(
result.span,
outputs,
temps,
result.note_id_changed,
result.params,
);
}
}
pub fn keyEvent(self: *MainModule, key: i32, down: bool, impulse_frame: usize) bool {
if (key == c.SDLK_SPACE) {
const freq = a4 * note_frequencies.c2;
self.iq.push(impulse_frame, self.idgen.nextId(), .{
.sample_rate = AUDIO_SAMPLE_RATE,
.freq = freq,
.note_on = down,
});
return true;
}
return false;
}
}; | examples/example_envelope.zig |
const std = @import("std");
const expect = std.testing.expect;
const expectEq = std.testing.expectEqual;
const Op = @import("./ops.zig").Op;
pub const RecordLengthType: type = usize;
pub const KeyLengthType: type = u16;
pub const RecordError = error{ BufferTooSmall, KeyTooBig };
/// A record is an array of contiguous bytes in the following form:
///
/// 1 byte to store the op type of the record
/// 8 bytes T to store the total bytes that the record uses
/// 2 bytes L to store the key length
/// K bytes to store the key, where K = key.len
/// V bytes to store the value, where V = value.len
pub const Record = struct {
op: Op = Op.Create,
key: []u8,
value: []u8,
record_size_in_bytes: usize = 0,
allocator: *std.mem.Allocator,
const Self = @This();
/// Call deinit() to deallocate this struct and its values
pub fn init(key: []const u8, value: []const u8, op: Op, alloc: *std.mem.Allocator) !*Self {
var s = try alloc.create(Self);
s.op = op;
s.key = try alloc.alloc(u8, key.len);
std.mem.copy(u8, s.key, key);
s.value = try alloc.alloc(u8, value.len);
std.mem.copy(u8, s.value, value);
s.allocator = alloc;
s.record_size_in_bytes = 0;
_ = s.bytesLen();
return s;
}
pub fn init_string(key: []const u8, value: []const u8, alloc: *std.mem.Allocator) !*Self {
return Record.init(key[0..], value[0..], alloc);
}
pub fn valueSize(self: *Self) usize {
return self.value.len;
}
/// length of the op + key + the key length type
fn totalKeyLen(self: *const Self) usize {
// K bytes to store a number that indicates how many bytes the key has
const key_length = @sizeOf(KeyLengthType);
return 1 + key_length + self.key.len;
}
/// total size in bytes of the record
pub fn bytesLen(self: *Self) usize {
if (self.record_size_in_bytes != 0) {
return self.record_size_in_bytes;
}
// total bytes (usually 8 bytes) to store the total bytes in the entire record
const record_len_type_len = @sizeOf(RecordLengthType);
// Total
self.record_size_in_bytes = self.totalKeyLen() + record_len_type_len + self.value.len;
return self.record_size_in_bytes;
}
// the minimum size possible for a record:
// op + key length type + key 1 byte + value size + value 1 byte
// 1 + 8 + 1 + 8 + 1
pub fn minimum_size() usize {
return 1 + @sizeOf(KeyLengthType) + 1 + @sizeOf(RecordLengthType) + 1;
}
pub fn deinit(self: *Self) void {
self.allocator.free(self.key);
self.allocator.free(self.value);
self.allocator.destroy(self);
}
};
test "record.init" {
var alloc = std.testing.allocator;
var r = try Record.init("hell0", "world1", Op.Update, &alloc);
defer r.deinit();
try expectEq(@as(usize, 22), r.record_size_in_bytes);
try expectEq(@as(usize, 22), r.bytesLen());
try expectEq(@as(usize, 8), r.totalKeyLen());
try std.testing.expectEqualStrings("hell0", r.key);
try std.testing.expectEqualStrings("world1", r.value);
try expectEq(Op.Update, r.op);
}
test "record.size" {
var alloc = std.testing.allocator;
var r = try Record.init("hello", "world", Op.Create, &alloc);
defer r.deinit();
const size = r.bytesLen();
try expectEq(@as(u64, 21), size);
}
test "record.minimum size" {
try expectEq(@as(usize, 13), Record.minimum_size());
} | src/record.zig |
const parsers = @import("parsers.zig");
const ParseNumber = parsers.ParseNumber;
const ParseAllocated = parsers.ParseAllocated;
const std = @import("std");
const debug = std.debug;
const assert = debug.assert;
const assertError = debug.assertError;
const warn = debug.warn;
const fmt = std.fmt;
const mem = std.mem;
const HashMap = std.HashMap;
const ArrayList = std.ArrayList;
const Allocator = mem.Allocator;
const builtin = @import("builtin");
const TypeId = builtin.TypeId;
const globals = @import("modules/globals.zig");
const pDb = &globals.debug_bits;
fn d(bit: usize) bool {
return pDb.r(globals.dbg_offset_parse_args + bit) == 1;
}
fn dbgw(bit: usize, value: usize) void {
pDb.w(globals.dbg_offset_parse_args + bit, value);
}
pub const ArgIteratorTest = struct {
const Self = @This();
index: usize,
count: usize,
args: []const []const u8,
pub fn init(args: []const []const u8) Self {
return Self{
.index = 0,
.count = args.len,
.args = args,
};
}
pub fn next(pSelf: *Self) ?[]const u8 {
if (d(1)) warn("ArgIteratorTest.next:+ count={} index={}\n", pSelf.count, pSelf.index);
defer if (d(1)) warn("ArgIteratorTest.next:-\n");
if (pSelf.index == pSelf.count) return null;
var n = pSelf.args[pSelf.index];
pSelf.index += 1;
if (d(1)) warn("&ArgIteratorTest: &n[0]={*} '{}'\n", &n[0], n);
return n;
}
pub fn skip(pSelf: *Self) bool {
if (pSelf.index == pSelf.count) return false;
pSelf.index += 1;
return true;
}
};
pub const ArgIter = struct {
const Self = @This();
const ArgIteratorEnum = union(enum) {
testArgIter: ArgIteratorTest,
osArgIter: std.os.ArgIterator,
};
ai: ArgIteratorEnum,
pub fn initOsArgIter() Self {
return Self{
.ai = ArgIteratorEnum{ .osArgIter = std.os.ArgIterator.init() },
};
}
pub fn initTestArgIter(args: []const []const u8) Self {
return Self{
.ai = ArgIteratorEnum{ .testArgIter = ArgIteratorTest.init(args) },
};
}
// Caller must free memory
//
// TODO: See if this analysis is true and see if we can fix it?
//
// This is needed because osArgIter.next needs an allocator.
// More specifically, ArgIteratorWindows needs an allocator
// where as ArgIteratorPosix does not. The reason
// ArgIteratorWindows needs the allocator is that
// the command line is parsed during next(). I believe
// if the parsing was done by the bootstrap code
// the allocator would not be necessary.
pub fn next(pSelf: *Self, pAllocator: *Allocator) ?anyerror![]const u8 { // <<< This works
//pub fn next(pSelf: *Self, pAllocator: *Allocator) ?(error![]const u8) { // <<< This works
//pub fn next(pSelf: *Self, pAllocator: *Allocator) ?(![]const u8) { // <<< Why doesn't this work
//pub fn next(pSelf: *Self, pAllocator: *Allocator) ?![]const u8 { // <<< Why doesn't this work
switch (pSelf.ai) {
ArgIteratorEnum.testArgIter => {
var elem = pSelf.ai.testArgIter.next();
if (elem == null) return null;
return mem.dupe(pAllocator, u8, elem.?);
//var n = mem.dupe(pAllocator, u8, elem.?) catch |err| return (error![]const u8)(err);
//if (d(1)) warn("&ArgIteratorEnum: &n[0]={*}\n", &n[0]);
//return (error![]const u8)(n);
},
ArgIteratorEnum.osArgIter => return (?anyerror![]const u8)(pSelf.ai.osArgIter.next(pAllocator)),
}
}
pub fn skip(pSelf: *Self) bool {
switch (pSelf.ai) {
ArgIteratorEnum.testArgIter => {
return pSelf.ai.testArgIter.skip();
},
ArgIteratorEnum.osArgIter => {
return pSelf.ai.osArgIter.skip();
},
}
}
};
pub const ArgRec = struct {
/// empty if none
leader: []const u8,
/// name of arg
name: []const u8,
// Upon exit from parseArg the following holds:
//
// If value_set == false and value_default_set == false
// ArgUnion.value is undefined
// ArgUnion.value_default undefined
//
// If value_set == false and value_default_set == true
// ArgUnion.value == ArgUnion.value_default
// ArgUnion.value_default as defined when ArgRec was created
//
// If value_set == true and value_default_set == false
// ArgUnion.value == value from command line
// ArgUnion.value_default undefined
//
// If value_set == true and value_default_set == false
// ArgUnion.value == value from command line
// ArgUnion.value_default as defined when ArgRec was created
//
// Thus if the user initializes value_default and sets value_default_set to true
// then value will always have a "valid" value and value_set will be true if
// the value came from the command line and false if it came from value_default.
/// true if value_default has default value
value_default_set: bool,
/// true if parseArgs set the value from command line
value_set: bool,
/// union
arg_union: ArgUnionFields,
fn initNamed(
comptime T: type,
name: []const u8,
default: T,
) ArgRec {
return initFlag(T, "", name, default);
}
fn initFlag(
comptime T: type,
leader: []const u8,
name: []const u8,
default: T,
) ArgRec {
var v: ArgRec = undefined;
v.leader = leader;
v.name = name;
v.value_default_set = true;
v.value_set = false;
switch (T) {
u32 => {
if (d(1)) warn("initFlag: u32\n");
v.arg_union = ArgUnionFields{
.argU32 = ArgUnion(u32){
.value_default = default,
.value = default,
.parser = ParseNumber(u32).parse,
},
};
},
i32 => {
if (d(1)) warn("initFlag: i32\n");
v.arg_union = ArgUnionFields{
.argI32 = ArgUnion(i32){
.value_default = default,
.value = default,
.parser = ParseNumber(i32).parse,
},
};
},
u64 => {
if (d(1)) warn("initFlag: u64\n");
v.arg_union = ArgUnionFields{
.argU64 = ArgUnion(u64){
.value_default = default,
.value = default,
.parser = ParseNumber(u64).parse,
},
};
},
i64 => {
if (d(1)) warn("initFlag: i64\n");
v.arg_union = ArgUnionFields{
.argI64 = ArgUnion(i64){
.value_default = default,
.value = default,
.parser = ParseNumber(i64).parse,
},
};
},
u128 => {
if (d(1)) warn("initFlag: u128\n");
v.arg_union = ArgUnionFields{
.argU128 = ArgUnion(u128){
.value_default = default,
.value = default,
.parser = ParseNumber(u128).parse,
},
};
},
i128 => {
if (d(1)) warn("initFlag: i128\n");
v.arg_union = ArgUnionFields{
.argI128 = ArgUnion(i128){
.value_default = default,
.value = default,
.parser = ParseNumber(i128).parse,
},
};
},
f32 => {
if (d(1)) warn("initFlag: f32\n");
v.arg_union = ArgUnionFields{
.argF32 = ArgUnion(f32){
.value_default = default,
.value = default,
.parser = ParseNumber(f32).parse,
},
};
},
f64 => {
if (d(1)) warn("initFlag: f64\n");
v.arg_union = ArgUnionFields{
.argF64 = ArgUnion(f64){
.value_default = default,
.value = default,
.parser = ParseNumber(f64).parse,
},
};
},
[]const u8 => {
if (d(1)) warn("initFlag: []const u8\n");
v.arg_union = ArgUnionFields{
.argAlloced = ArgUnion([]const u8){
.value_default = default,
.value = default,
.parser = ParseAllocated([]const u8).parse,
},
};
},
else => unreachable,
}
return v;
}
};
// ArgUnionFields should be more generic
pub const ArgUnionFields = union(enum) {
argU32: ArgUnion(u32),
argI32: ArgUnion(i32),
argU64: ArgUnion(u64),
argI64: ArgUnion(i64),
argU128: ArgUnion(u128),
argI128: ArgUnion(i128),
argF32: ArgUnion(f32),
argF64: ArgUnion(f64),
argAlloced: ArgUnion([]const u8),
};
pub fn ArgUnion(comptime T: type) type {
return struct {
const Self = This();
/// Parse the []const u8 to T
parser: comptime switch (TypeId(@typeInfo(T))) {
TypeId.Pointer, TypeId.Array, TypeId.Struct => fn (*Allocator, []const u8) anyerror!T,
else => fn ([]const u8) anyerror!T,
},
/// value_default copied to value if .value_default_set is true and value_set is false
value_default: T,
/// value is from command line if .value_set is true
value: T,
};
}
const ParsedArg = struct {
leader: []const u8,
lhs: []const u8,
sep: []const u8,
rhs: []const u8,
};
fn parseArg(leader: []const u8, raw_arg: []const u8, sep: []const u8) ParsedArg {
if (d(0)) warn("&leader[0]={*} &raw_arg[0]={*} &sep[0]={*}\n", &leader[0], &raw_arg[0], &sep[0]);
var parsedArg = ParsedArg{
.leader = "",
.lhs = "",
.sep = "",
.rhs = "",
};
var idx: usize = 0;
if (mem.eql(u8, leader, raw_arg[idx..leader.len])) {
idx += leader.len;
parsedArg.leader = leader;
}
var sep_idx = idx;
var found_sep = while (sep_idx < raw_arg.len) : (sep_idx += 1) {
if (mem.eql(u8, raw_arg[sep_idx..(sep_idx + sep.len)], sep[0..])) {
parsedArg.sep = sep;
if (d(0)) warn("&parsedArg.sep[0]={*} &sep[0]={*}\n", &parsedArg.sep[0], &sep[0]);
break true;
}
} else false;
if (found_sep) {
parsedArg.lhs = raw_arg[idx..sep_idx];
parsedArg.sep = sep;
parsedArg.rhs = raw_arg[(sep_idx + sep.len)..];
} else {
parsedArg.lhs = raw_arg[idx..];
}
if (d(0))
warn("&parsedArg={*} &leader[0]={*} &lhs[0]={*} &sep[0]={*} &rhs[0]={*}\n", &parsedArg, if (parsedArg.leader.len != 0) &parsedArg.leader[0] else null, if (parsedArg.lhs.len != 0) &parsedArg.lhs[0] else null, if (parsedArg.sep.len != 0) &parsedArg.sep[0] else null, if (parsedArg.rhs.len != 0) &parsedArg.rhs[0] else null);
return parsedArg; // Assume this isn't copyied?
}
pub fn parseArgs(
pAllocator: *Allocator,
args_it: *ArgIter,
arg_proto_list: ArrayList(ArgRec),
) !ArrayList([]const u8) {
if (!args_it.skip()) @panic("expected arg[0] to exist");
if (d(0)) warn("parseArgs:+ arg_proto_list.len={}\n", arg_proto_list.len);
defer if (d(0)) warn("parseArgs:-\n");
var positionalArgs = ArrayList([]const u8).init(pAllocator);
// Add the arg_prototypes to a hash map
const ArgProtoMap = HashMap([]const u8, *ArgRec, mem.hash_slice_u8, mem.eql_slice_u8);
var arg_proto_map = ArgProtoMap.init(pAllocator);
var i: usize = 0;
while (i < arg_proto_list.len) {
var arg_proto: *ArgRec = &arg_proto_list.items[i];
if (d(0)) warn("&arg_proto={*} name={}\n", arg_proto, arg_proto.name);
if (arg_proto_map.contains(arg_proto.name)) {
var pKV = arg_proto_map.get(arg_proto.name);
var v = pKV.?.value;
if (d(0)) warn("Duplicate arg_proto.name={} previous value was at index {}\n", arg_proto.name, i);
return error.ArgProtoDuplicate;
}
_ = try arg_proto_map.put(arg_proto.name, arg_proto);
i += 1;
}
// Loop through all of the arguments passed setting the prototype values
// and returning the positional list.
while (args_it.next(pAllocator)) |arg_or_error| {
// raw_arg must be freed is was allocated by args_it.next(pAllocator) above!
var raw_arg = try arg_or_error;
defer if (d(1)) {
warn("free: &raw_arg[0]={*} &raw_arg={*} raw_arg={}\n", &raw_arg[0], &raw_arg, raw_arg);
pAllocator.free(raw_arg);
};
if (d(1)) warn("&raw_arg[0]={*} raw_arg={}\n", &raw_arg[0], raw_arg);
var parsed_arg = parseArg("--", raw_arg, "=");
if (d(1))
warn("&parsed_arg={*} &leader[0]={*} &lhs[0]={*} &sep[0]={*} &rhs[0]={*}\n", &parsed_arg, if (parsed_arg.leader.len != 0) &parsed_arg.leader[0] else null, if (parsed_arg.lhs.len != 0) &parsed_arg.lhs[0] else null, if (parsed_arg.sep.len != 0) &parsed_arg.sep[0] else null, if (parsed_arg.rhs.len != 0) &parsed_arg.rhs[0] else null);
var pKV = arg_proto_map.get(parsed_arg.lhs);
if (pKV == null) {
// Doesn't match
if (mem.eql(u8, parsed_arg.leader, "") and mem.eql(u8, parsed_arg.rhs, "")) {
if (mem.eql(u8, parsed_arg.sep, "")) {
try positionalArgs.append(parsed_arg.lhs);
continue;
} else {
if (d(1))
warn("error.UnknownButEmptyNamedParameterUnknown, raw_arg={} parsed parsed_arg={}\n", raw_arg, parsed_arg);
return error.UnknownButEmptyNamedParameter;
}
} else {
if (d(1)) warn("error.UnknownOption raw_arg={} parsed parsed_arg={}\n", raw_arg, parsed_arg);
return error.UnknownOption;
}
}
// Got a match
var v = pKV.?.value;
var isa_option = if (mem.eql(u8, parsed_arg.leader, "")) false else mem.eql(u8, parsed_arg.leader[0..], v.leader[0..]);
if (!mem.eql(u8, parsed_arg.rhs, "")) {
// Set value to the rhs
switch (v.arg_union) {
ArgUnionFields.argU32 => v.arg_union.argU32.value = try v.arg_union.argU32.parser(parsed_arg.rhs[0..]),
ArgUnionFields.argI32 => v.arg_union.argI32.value = try v.arg_union.argI32.parser(parsed_arg.rhs[0..]),
ArgUnionFields.argU64 => v.arg_union.argU64.value = try v.arg_union.argU64.parser(parsed_arg.rhs[0..]),
ArgUnionFields.argI64 => v.arg_union.argI64.value = try v.arg_union.argI64.parser(parsed_arg.rhs[0..]),
ArgUnionFields.argU128 => v.arg_union.argU128.value = try v.arg_union.argU128.parser(parsed_arg.rhs[0..]),
ArgUnionFields.argI128 => v.arg_union.argI128.value = try v.arg_union.argI128.parser(parsed_arg.rhs[0..]),
ArgUnionFields.argF32 => v.arg_union.argF32.value = try v.arg_union.argF32.parser(parsed_arg.rhs[0..]),
ArgUnionFields.argF64 => v.arg_union.argF64.value = try v.arg_union.argF64.parser(parsed_arg.rhs[0..]),
ArgUnionFields.argAlloced => v.arg_union.argAlloced.value = try v.arg_union.argAlloced.parser(pAllocator, parsed_arg.rhs[0..]),
}
v.value_set = true; // set value_set as it's initialised via an argument
} else {
// parsed_arg.rhs is empty so use "default" if is was set
if (v.value_default_set) {
switch (v.arg_union) {
ArgUnionFields.argU32 => v.arg_union.argU32.value = v.arg_union.argU32.value_default,
ArgUnionFields.argI32 => v.arg_union.argI32.value = v.arg_union.argI32.value_default,
ArgUnionFields.argU64 => v.arg_union.argU64.value = v.arg_union.argU64.value_default,
ArgUnionFields.argI64 => v.arg_union.argI64.value = v.arg_union.argI64.value_default,
ArgUnionFields.argU128 => v.arg_union.argU128.value = v.arg_union.argU128.value_default,
ArgUnionFields.argI128 => v.arg_union.argI128.value = v.arg_union.argI128.value_default,
ArgUnionFields.argF32 => v.arg_union.argF32.value = v.arg_union.argF32.value_default,
ArgUnionFields.argF64 => v.arg_union.argF64.value = v.arg_union.argF64.value_default,
ArgUnionFields.argAlloced => v.arg_union.argAlloced.value = v.arg_union.argAlloced.value_default,
}
v.value_set = false; // Since we used the default we'll clear value_set
}
}
}
return positionalArgs;
}
test "parseArgs.basic" {
// Initialize the debug bits
dbgw(0, 0);
dbgw(1, 0);
warn("\n");
// Create the list of options
var argList = ArrayList(ArgRec).init(debug.global_allocator);
try argList.append(ArgRec.initNamed(u32, "countU32", 32));
try argList.append(ArgRec.initFlag(i32, "--", "countI32", 32));
try argList.append(ArgRec.initNamed(u64, "countU64", 64));
try argList.append(ArgRec.initNamed(i64, "countI64", -64));
try argList.append(ArgRec.initNamed(u128, "countU128", 128));
try argList.append(ArgRec.initNamed(i128, "countI128", -128));
try argList.append(ArgRec.initNamed(f32, "valueF32", -32.32));
try argList.append(ArgRec.initNamed(f64, "valueF64", -64.64));
try argList.append(ArgRec.initNamed([]const u8, "first_name", "ken"));
// Create arguments that we will parse
var arg_iter = ArgIter.initTestArgIter([]const []const u8{
"file.exe", // The first argument is the "executable" and is skipped
"hello",
"countU32=321",
"--countI32=-321",
"countU64=641",
"countI64=-641",
"countU128=123_456_789",
"countI128=-1_281",
"valueF32=1_232.321_021",
"valueF64=64.64",
"first_name=wink",
"world",
});
// Parse the arguments
var positionalArgs = try parseArgs(debug.global_allocator, &arg_iter, argList);
// Display positional arguments
for (positionalArgs.toSlice()) |arg, i| {
warn("positionalArgs[{}]={}\n", i, arg);
}
// Display the options
for (argList.toSlice()) |arg, i| {
warn("argList[{}]: name={} value_set={} arg.value=", i, arg.name, arg.value_set);
switch (arg.arg_union) {
ArgUnionFields.argU32 => warn("{}", arg.arg_union.argU32.value),
ArgUnionFields.argI32 => warn("{}", arg.arg_union.argI32.value),
ArgUnionFields.argU64 => warn("{}", arg.arg_union.argU64.value),
ArgUnionFields.argI64 => warn("{}", arg.arg_union.argI64.value),
ArgUnionFields.argU128 => warn("{}", arg.arg_union.argU128.value),
ArgUnionFields.argI128 => warn("{}", arg.arg_union.argI128.value),
ArgUnionFields.argF32 => warn("{}", arg.arg_union.argF32.value),
ArgUnionFields.argF64 => warn("{}", arg.arg_union.argF64.value),
ArgUnionFields.argAlloced => {
warn("{} &value[0]={*}", arg.arg_union.argAlloced.value, &arg.arg_union.argAlloced.value[0]);
},
}
warn("\n");
}
// Assert we have the expected values
assert(argList.items[0].arg_union.argU32.value == 321);
assert(argList.items[1].arg_union.argI32.value == -321);
assert(argList.items[2].arg_union.argU64.value == 641);
assert(argList.items[3].arg_union.argI64.value == -641);
assert(argList.items[4].arg_union.argU128.value == 123456789);
assert(argList.items[5].arg_union.argI128.value == -1281);
assert(argList.items[6].arg_union.argF32.value == 1232.321021);
assert(argList.items[7].arg_union.argF64.value == 64.64);
assert(mem.eql(u8, argList.items[8].arg_union.argAlloced.value, "wink"));
// Free data any allocated data of ArgUnionFields.argAlloced
for (argList.toSlice()) |arg, i| {
switch (arg.arg_union) {
ArgUnionFields.argAlloced => {
if (arg.value_set) {
warn("free argList[{}]: name={} value_set={} arg.value={}\n", i, arg.name, arg.value_set, arg.arg_union.argAlloced.value);
debug.global_allocator.free(arg.arg_union.argAlloced.value);
}
},
else => {},
}
}
debug.global_allocator.free(argList.items);
} | parse_args.zig |
const std = @import("std");
const tracy = @import("tracy");
const PAGE_SIZE = 4096;
const LEAF_CELL_SIZE = 32;
const INTERNAL_CELL_SIZE = 32;
const MAX_LEAF_CELLS = (PAGE_SIZE - @sizeOf(NodeHeader)) / LEAF_CELL_SIZE;
const MAX_INTERNAL_CELLS = (PAGE_SIZE - @sizeOf(NodeHeader)) / INTERNAL_CELL_SIZE;
const MAX_DEPTH = 10;
comptime {
std.debug.assert(LEAF_CELL_SIZE == @sizeOf(LeafCell));
std.debug.assert(INTERNAL_CELL_SIZE == @sizeOf(InternalCell));
}
pub const Tree = struct {
allocator: *std.mem.Allocator,
root: ?NodePtr,
freeNodes: std.ArrayList(NodePtr),
pub fn init(allocator: *std.mem.Allocator) @This() {
return @This(){
.allocator = allocator,
.root = null,
.freeNodes = std.ArrayList(NodePtr).init(allocator),
};
}
pub fn deinit(this: *@This()) void {
if (this.root) |root| {
// Iterate over root and free children nodes
root.destroyChildrenAlloc(this.allocator);
this.allocator.destroy(root);
}
for (this.freeNodes.items) |free_node| {
this.allocator.destroy(free_node);
}
this.freeNodes.deinit();
}
fn createNode(this: *@This()) !NodePtr {
return this.freeNodes.popOrNull() orelse {
const node_slice = try this.allocator.allocWithOptions(Node, 1, PAGE_SIZE, null);
return &node_slice[0];
};
}
fn destroyNode(this: *@This(), node: NodePtr) void {
this.freeNodes.append(node) catch {
this.allocator.destroy(node);
};
}
const PathSegment = struct {
node: NodePtr,
cellIdx: usize,
};
pub fn putNoClobber(this: *@This(), timestamp: i64, change: i128) !void {
const t = tracy.trace(@src());
defer t.end();
if (this.root) |root| {
switch (root.header.nodeType) {
.leaf => {
switch (try this.putIntoLeafNode(root, timestamp, change)) {
.update => |new_node| {
this.root = new_node;
this.destroyNode(root);
},
.split => |new_nodes| {
const new_root = try this.createNode();
std.debug.assert(new_nodes.len == 2);
new_root.header = .{
.nodeType = .internal,
.count = 2,
};
for (new_nodes) |new_node, new_idx| {
new_root.cells.internal[new_idx] = .{
.node = new_node,
.greatestTimestamp = new_node.greatestTimestamp(),
.cumulativeChange = new_node.cumulativeChange(),
};
}
this.root = new_root;
this.destroyNode(root);
},
}
},
.internal => {
var path = try std.BoundedArray(PathSegment, MAX_DEPTH).init(0);
try path.append(.{ .node = root, .cellIdx = undefined });
// Find leaf node
{
const t1 = tracy.trace(@src());
defer t1.end();
while (path.slice()[path.slice().len - 1].node.header.nodeType == .internal) {
const current = &path.slice()[path.slice().len - 1];
current.cellIdx = current.node.findInternalCellIdx(timestamp) orelse current.node.header.count - 1;
const next_node = current.node.cells.internal[current.cellIdx].node;
try path.append(.{ .node = next_node, .cellIdx = undefined });
}
}
const leaf_node = path.slice()[path.slice().len - 1].node;
std.debug.assert(leaf_node.header.nodeType == .leaf);
// Iterate over every node in path except the last
var put_result = try this.putIntoLeafNode(leaf_node, timestamp, change);
errdefer {
switch (put_result) {
.update => |new_node| {
new_node.destroyChildren(this);
this.destroyNode(new_node);
},
.split => |new_nodes| {
for (new_nodes) |new_node| {
new_node.destroyChildren(this);
this.destroyNode(new_node);
}
},
}
}
var path_idx = @intCast(isize, path.slice().len) - 2;
while (path_idx >= 0) : (path_idx -= 1) {
const path_segment = &path.slice()[@intCast(usize, path_idx)];
const new_put_result = try this.updateInternalNode(path_segment.node, path_segment.cellIdx, put_result);
put_result = new_put_result;
}
switch (put_result) {
.update => |new_node| this.root = new_node,
.split => |new_nodes| {
const new_root = try this.createNode();
std.debug.assert(new_nodes.len == 2);
new_root.header = .{
.nodeType = .internal,
.count = 2,
};
for (new_nodes) |new_node, new_idx| {
new_root.cells.internal[new_idx] = .{
.node = new_node,
.greatestTimestamp = new_node.greatestTimestamp(),
.cumulativeChange = new_node.cumulativeChange(),
};
}
this.root = new_root;
},
}
{
const t1 = tracy.trace(@src());
defer t1.end();
for (path.slice()) |segment| {
this.destroyNode(segment.node);
}
}
},
}
} else {
const root = try this.createNode();
root.* = .{
.header = .{
.nodeType = .leaf,
.count = 1,
},
.cells = undefined,
};
root.cells.leaf[0] = .{
.timestamp = timestamp,
.change = change,
};
this.root = root;
}
}
const PutLeafResult = union(enum) {
update: NodePtr,
split: [2]NodePtr,
};
/// Duplicates the leaf node and puts the given value into it. Caller is responsible for
/// freeing the returned nodes and the node that was passed into.
fn putIntoLeafNode(this: *@This(), leafNode: NodePtr, timestamp: i64, change: i128) !PutLeafResult {
const t = tracy.trace(@src());
defer t.end();
std.debug.assert(leafNode.header.nodeType == .leaf);
if (leafNode.header.count < MAX_LEAF_CELLS) {
const new_leaf = try this.createNode();
leafNode.copyTo(new_leaf);
new_leaf.putLeafMutNoSplit(timestamp, change);
return PutLeafResult{ .update = new_leaf };
} else {
const left_node = try this.createNode();
const right_node = try this.createNode();
const midpoint = leafNode.header.count / 2;
left_node.header = .{
.nodeType = .leaf,
.count = midpoint,
};
std.mem.copy(LeafCell, left_node.cells.leaf[0..left_node.header.count], leafNode.cells.leaf[0..midpoint]);
right_node.header = .{
.nodeType = .leaf,
.count = leafNode.header.count - midpoint,
};
std.mem.copy(LeafCell, right_node.cells.leaf[0..right_node.header.count], leafNode.cells.leaf[midpoint..leafNode.header.count]);
std.debug.assert(leafNode.header.count == left_node.header.count + right_node.header.count);
// insert value into the approriate new node
if (timestamp <= left_node.greatestTimestamp()) {
left_node.putLeafMutNoSplit(timestamp, change);
} else {
right_node.putLeafMutNoSplit(timestamp, change);
}
return PutLeafResult{ .split = .{ left_node, right_node } };
}
}
/// Duplicates the internal node and points it to the new child nodes.
///
/// `cellIdx` is the index of the cell that was pointing to the child node before the update.
fn updateInternalNode(this: *@This(), internalNode: NodePtr, cellIdx: usize, prevResult: PutLeafResult) !PutLeafResult {
const t = tracy.trace(@src());
defer t.end();
std.debug.assert(internalNode.header.nodeType == .internal);
std.debug.assert(cellIdx <= internalNode.header.count);
if (prevResult == .update or internalNode.header.count < MAX_INTERNAL_CELLS) {
const new_internal = try this.createNode();
new_internal.header = internalNode.header;
std.mem.copy(
InternalCell,
new_internal.cells.internal[0..cellIdx],
internalNode.cells.internal[0..cellIdx],
);
switch (prevResult) {
.update => |new_node| {
std.mem.copy(
InternalCell,
new_internal.cells.internal[cellIdx + 1 .. internalNode.header.count],
internalNode.cells.internal[cellIdx + 1 .. internalNode.header.count],
);
new_internal.cells.internal[cellIdx] = .{
.node = new_node,
.greatestTimestamp = new_node.greatestTimestamp(),
.cumulativeChange = new_node.cumulativeChange(),
};
},
.split => |new_nodes| {
std.mem.copy(
InternalCell,
new_internal.cells.internal[cellIdx + 2 .. internalNode.header.count + 1],
internalNode.cells.internal[cellIdx + 1 .. internalNode.header.count],
);
for (new_nodes) |new_node, offset| {
new_internal.cells.internal[cellIdx + offset] = .{
.node = new_node,
.greatestTimestamp = new_node.greatestTimestamp(),
.cumulativeChange = new_node.cumulativeChange(),
};
}
new_internal.header.count += 1;
},
}
return PutLeafResult{ .update = new_internal };
} else {
const left_node = try this.createNode();
const right_node = try this.createNode();
const midpoint = internalNode.header.count / 2;
left_node.header = .{
.nodeType = .internal,
.count = midpoint,
};
right_node.header = .{
.nodeType = .internal,
.count = internalNode.header.count - midpoint,
};
std.debug.assert(internalNode.header.count == left_node.header.count + right_node.header.count);
if (cellIdx < midpoint) {
std.mem.copy(InternalCell, right_node.cells.internal[0..right_node.header.count], internalNode.cells.internal[midpoint..internalNode.header.count]);
const idx = cellIdx;
std.mem.copy(InternalCell, left_node.cells.internal[0..idx], internalNode.cells.internal[0..idx]);
std.mem.copy(InternalCell, left_node.cells.internal[idx + 2 .. left_node.header.count + 1], internalNode.cells.internal[idx + 1 .. left_node.header.count]);
for (prevResult.split) |new_node, offset| {
left_node.cells.internal[idx + offset] = .{
.node = new_node,
.greatestTimestamp = new_node.greatestTimestamp(),
.cumulativeChange = new_node.cumulativeChange(),
};
}
left_node.header.count += 1;
} else if (cellIdx == midpoint) {
std.mem.copy(InternalCell, left_node.cells.internal[0..left_node.header.count], internalNode.cells.internal[0..midpoint]);
std.mem.copy(InternalCell, right_node.cells.internal[0..right_node.header.count], internalNode.cells.internal[midpoint..internalNode.header.count]);
left_node.cells.internal[left_node.header.count] = .{
.node = prevResult.split[0],
.greatestTimestamp = prevResult.split[0].greatestTimestamp(),
.cumulativeChange = prevResult.split[0].cumulativeChange(),
};
left_node.header.count += 1;
right_node.cells.internal[0] = .{
.node = prevResult.split[1],
.greatestTimestamp = prevResult.split[1].greatestTimestamp(),
.cumulativeChange = prevResult.split[1].cumulativeChange(),
};
} else {
std.mem.copy(InternalCell, left_node.cells.internal[0..left_node.header.count], internalNode.cells.internal[0..left_node.header.count]);
const idx = cellIdx - midpoint;
std.mem.copy(InternalCell, right_node.cells.internal[0..idx], internalNode.cells.internal[midpoint..cellIdx]);
std.mem.copy(InternalCell, right_node.cells.internal[idx + 2 .. right_node.header.count + 1], internalNode.cells.internal[cellIdx + 1 .. internalNode.header.count]);
for (prevResult.split) |new_node, offset| {
right_node.cells.internal[idx + offset] = .{
.node = new_node,
.greatestTimestamp = new_node.greatestTimestamp(),
.cumulativeChange = new_node.cumulativeChange(),
};
}
right_node.header.count += 1;
}
std.debug.assert(internalNode.header.count + 1 == left_node.header.count + right_node.header.count);
return PutLeafResult{ .split = .{ left_node, right_node } };
}
}
pub fn getBalance(this: @This()) i128 {
const t = tracy.trace(@src());
defer t.end();
if (this.root) |root| {
return root.cumulativeChange();
}
return 0;
}
pub fn getBalanceAtTime(this: @This(), timestamp: i64) i128 {
const t = tracy.trace(@src());
defer t.end();
var balance: i128 = 0;
if (this.root) |root| {
var node = root;
while (node.header.nodeType == .internal) {
var idx: usize = 0;
while (idx < node.header.count and node.cells.internal[idx].greatestTimestamp < timestamp) : (idx += 1) {
balance += node.cells.internal[idx].cumulativeChange;
}
if (idx >= node.header.count) return balance;
node = node.cells.internal[idx].node;
}
std.debug.assert(node.header.nodeType == .leaf);
for (node.cells.leaf[0..node.header.count]) |leaf_cell| {
if (leaf_cell.timestamp < timestamp) {
balance += leaf_cell.change;
} else {
break;
}
}
}
return balance;
}
pub const Entry = struct {
timestamp: i64,
change: i128,
};
const Iterator = struct {
tree: *const Tree,
path: std.BoundedArray(PathSegment, MAX_DEPTH),
pub fn next(this: *@This()) !?Entry {
if (this.path.len == 0) return null;
var currentNode = &this.path.slice()[this.path.len - 1];
while (currentNode.cellIdx >= currentNode.node.header.count) {
_ = this.path.pop();
if (this.path.len < 1) return null;
currentNode = &this.path.slice()[this.path.len - 1];
}
while (currentNode.node.header.nodeType == .internal) {
if (currentNode.cellIdx >= currentNode.node.header.count) return null;
try this.path.append(.{
.node = currentNode.node.cells.internal[currentNode.cellIdx].node,
.cellIdx = 0,
});
currentNode.cellIdx += 1;
currentNode = &this.path.slice()[this.path.len - 1];
}
const cell = currentNode.node.cells.leaf[currentNode.cellIdx];
const entry = Entry{
.timestamp = cell.timestamp,
.change = cell.change,
};
currentNode.cellIdx += 1;
return entry;
}
pub fn prev(this: *@This()) !?Entry {
if (this.path.len == 0) return null;
var currentNode = &this.path.slice()[this.path.len - 1];
while (currentNode.cellIdx == 0) {
_ = this.path.pop();
if (this.path.len < 1) return null;
currentNode = &this.path.slice()[this.path.len - 1];
}
while (currentNode.node.header.nodeType == .internal) {
if (currentNode.cellIdx == 0) return null;
const prev_node = currentNode.node.cells.internal[currentNode.cellIdx - 1].node;
try this.path.append(.{
.node = prev_node,
.cellIdx = prev_node.header.count,
});
currentNode.cellIdx -= 1;
currentNode = &this.path.slice()[this.path.len - 1];
}
const cell = currentNode.node.cells.leaf[currentNode.cellIdx - 1];
const entry = Entry{
.timestamp = cell.timestamp,
.change = cell.change,
};
currentNode.cellIdx -= 1;
return entry;
}
};
pub const Position = union(enum) {
first: void,
last: void,
};
pub fn iterator(this: *const @This(), pos: Position) Iterator {
var path = std.BoundedArray(PathSegment, MAX_DEPTH).init(0) catch unreachable;
if (this.root) |root| {
switch (pos) {
.first => path.append(.{
.node = root,
.cellIdx = 0,
}) catch unreachable,
.last => path.append(.{
.node = root,
.cellIdx = root.header.count,
}) catch unreachable,
}
}
return Iterator{
.tree = this,
.path = path,
};
}
};
const NodePtr = *align(PAGE_SIZE) Node;
//const NodePtrMut = *align(PAGE_SIZE) Node;
const Node = extern struct {
header: NodeHeader,
cells: packed union {
leaf: [MAX_LEAF_CELLS]LeafCell,
internal: [MAX_INTERNAL_CELLS]InternalCell,
},
pub fn destroyChildren(this: @This(), tree: *Tree) void {
if (this.header.nodeType == .leaf) return;
for (this.cells.internal[0..this.header.count]) |internal_cell| {
internal_cell.node.destroyChildren(tree);
tree.destroyNode(internal_cell.node);
}
}
pub fn destroyChildrenAlloc(this: @This(), allocator: *std.mem.Allocator) void {
if (this.header.nodeType == .leaf) return;
for (this.cells.internal[0..this.header.count]) |internal_cell| {
internal_cell.node.destroyChildrenAlloc(allocator);
allocator.destroy(internal_cell.node);
}
}
pub fn copyTo(this: @This(), other: NodePtr) void {
other.header = this.header;
const count = this.header.count;
switch (this.header.nodeType) {
.leaf => std.mem.copy(
LeafCell,
other.cells.leaf[0..count],
this.cells.leaf[0..count],
),
.internal => std.mem.copy(
InternalCell,
other.cells.internal[0..count],
this.cells.internal[0..count],
),
}
}
pub fn smallestTimestamp(this: @This()) i64 {
std.debug.assert(this.header.count != 0);
return switch (this.header.nodeType) {
.leaf => this.cells.leaf[0].timestamp,
.internal => this.cells.internal[0].node.smallestTimestamp(),
};
}
pub fn greatestTimestamp(this: @This()) i64 {
const count = this.header.count;
return switch (this.header.nodeType) {
.leaf => this.cells.leaf[count - 1].timestamp,
.internal => this.cells.internal[count - 1].greatestTimestamp,
};
}
pub fn cumulativeChange(this: @This()) i128 {
const count = this.header.count;
var cumulative_change: i128 = 0;
switch (this.header.nodeType) {
.leaf => {
var i: usize = 0;
while (i < count) : (i += 1) {
cumulative_change += this.cells.leaf[i].change;
}
//for (this.cells.leaf[0..count]) |_, idx| {
// cumulative_change += this.cells.leaf[idx].change;
//}
},
.internal => {
//for (this.cells.internal[0..count]) |internal_cell| {
// cumulative_change += internal_cell.cumulativeChange;
//}
var i: usize = 0;
while (i < count) : (i += 1) {
cumulative_change += this.cells.internal[i].cumulativeChange;
}
},
}
return cumulative_change;
}
/// Find the internal cell that points to a node that may contain the given timestamp, or
/// null if the timestamp is greater than any timestamp in this node.
pub fn findInternalCellIdx(this: @This(), timestamp: i64) ?usize {
const t = tracy.trace(@src());
defer t.end();
std.debug.assert(this.header.nodeType == .internal);
const count = this.header.count;
for (this.cells.internal[0..count]) |cell, idx| {
if (timestamp < cell.greatestTimestamp) {
return idx;
}
}
return null;
}
fn putLeafMutNoSplit(this: *@This(), timestamp: i64, change: i128) void {
std.debug.assert(this.header.nodeType == .leaf);
std.debug.assert(this.header.count < MAX_LEAF_CELLS);
// Find where to insert cell in leaf cell array
for (this.cells.leaf[0..this.header.count]) |leaf_cell, idx| {
if (leaf_cell.timestamp == timestamp) {
// Replace cell
unreachable; // No clobber, user guarantees this won't happen
} else if (leaf_cell.timestamp > timestamp) {
// Insert cell in the middle of the array
var prev_cell = LeafCell{ .timestamp = timestamp, .change = change };
for (this.cells.leaf[idx .. this.header.count + 1]) |*cell_to_move| {
const tmp = cell_to_move.*;
cell_to_move.* = prev_cell;
prev_cell = tmp;
//std.mem.swap(LeafCell, &prev_cell, cell_to_move);
}
this.header.count += 1;
break;
}
} else {
// Insert cell at end of array
this.cells.leaf[this.header.count] = .{
.timestamp = timestamp,
.change = change,
};
this.header.count += 1;
}
}
};
const NodeHeader = extern struct {
nodeType: NodeType,
count: u16,
};
const NodeType = enum(u8) {
leaf,
internal,
};
const LeafCell = extern struct {
change: i128,
timestamp: i64,
};
const InternalCell = extern struct {
greatestTimestamp: i64,
node: NodePtr,
cumulativeChange: i128,
};
test "align of node" {
const nodes = try std.testing.allocator.allocWithOptions(Node, 2, PAGE_SIZE, null);
defer std.testing.allocator.free(nodes);
try std.testing.expect(@ptrToInt(nodes[1..].ptr) - @ptrToInt(nodes[0..].ptr) <= PAGE_SIZE);
}
test "tree returns balance up to timestamp non inclusive" {
var tree = Tree.init(std.testing.allocator);
defer tree.deinit();
try tree.putNoClobber(100, 1_000);
try tree.putNoClobber(300, 1_000);
try tree.putNoClobber(666, 666);
try tree.putNoClobber(1000, 1_337);
try tree.putNoClobber(1001, -500);
try std.testing.expectEqual(@as(i128, 0), tree.getBalanceAtTime(100));
try std.testing.expectEqual(@as(i128, 1_000), tree.getBalanceAtTime(101));
try std.testing.expectEqual(@as(i128, 1_000), tree.getBalanceAtTime(300));
try std.testing.expectEqual(@as(i128, 2_000), tree.getBalanceAtTime(301));
try std.testing.expectEqual(@as(i128, 2_000), tree.getBalanceAtTime(666));
try std.testing.expectEqual(@as(i128, 2_666), tree.getBalanceAtTime(667));
try std.testing.expectEqual(@as(i128, 2_666), tree.getBalanceAtTime(1000));
try std.testing.expectEqual(@as(i128, 4_003), tree.getBalanceAtTime(1001));
try std.testing.expectEqual(@as(i128, 3_503), tree.getBalanceAtTime(1002));
}
test "add 10_000 transactions and randomly query balance" {
const t = tracy.trace(@src());
defer t.end();
var tree = Tree.init(std.testing.allocator);
defer tree.deinit();
var default_prng = std.rand.DefaultPrng.init(13500266781291126803);
const random = &default_prng.random;
var transactions = std.ArrayList(i128).init(std.testing.allocator);
defer transactions.deinit();
var running_balance = std.ArrayList(i128).init(std.testing.allocator);
defer running_balance.deinit();
// Generate random transactions
{
const t1 = tracy.trace(@src());
defer t1.end();
var balance: i128 = 0;
var i: usize = 0;
while (i < 10_000) : (i += 1) {
const amount = random.int(i64);
try transactions.append(amount);
try running_balance.append(balance);
balance += amount;
}
try running_balance.append(balance);
}
// Put transactions into tree in random order
{
const t1 = tracy.trace(@src());
defer t1.end();
var shuffled_transaction_indices = try std.ArrayList(usize).initCapacity(std.testing.allocator, transactions.items.len);
defer shuffled_transaction_indices.deinit();
for (transactions.items) |_, i| {
shuffled_transaction_indices.appendAssumeCapacity(i);
}
random.shuffle(usize, shuffled_transaction_indices.items);
for (shuffled_transaction_indices.items) |txIdx| {
const amount = transactions.items[txIdx];
try tree.putNoClobber(@intCast(i64, txIdx), amount);
}
}
// Ensure that the tree matches the running balance at each index
const t1 = tracy.trace(@src());
defer t1.end();
for (running_balance.items) |balance, txIdx| {
try std.testing.expectEqual(balance, tree.getBalanceAtTime(@intCast(i64, txIdx)));
}
}
test "add 1_000 transactions and iterate" {
var tree = Tree.init(std.testing.allocator);
defer tree.deinit();
var default_prng = std.rand.DefaultPrng.init(13280421048943141057);
const random = &default_prng.random;
var transactions = std.ArrayList(i128).init(std.testing.allocator);
defer transactions.deinit();
// Generate random transactions
{
var i: usize = 0;
while (i < 1_000) : (i += 1) {
try transactions.append(random.int(i64));
}
}
// Put transactions into tree in random order
{
var shuffled_transaction_indices = try std.ArrayList(usize).initCapacity(std.testing.allocator, transactions.items.len);
defer shuffled_transaction_indices.deinit();
for (transactions.items) |_, i| {
shuffled_transaction_indices.appendAssumeCapacity(i);
}
random.shuffle(usize, shuffled_transaction_indices.items);
for (shuffled_transaction_indices.items) |txIdx| {
const amount = transactions.items[txIdx];
try tree.putNoClobber(@intCast(i64, txIdx), amount);
}
}
// Ensure that the tree matches the running balance at each index
{
var iterator = tree.iterator(.first);
var count: usize = 0;
while (try iterator.next()) |entry| {
try std.testing.expectEqual(transactions.items[@intCast(usize, entry.timestamp)], entry.change);
count += 1;
}
try std.testing.expectEqual(transactions.items.len, count);
}
{
var iterator = tree.iterator(.last);
var count: usize = 0;
while (try iterator.prev()) |entry| {
try std.testing.expectEqual(transactions.items[@intCast(usize, entry.timestamp)], entry.change);
count += 1;
}
try std.testing.expectEqual(transactions.items.len, count);
}
} | src/transaction_tree.zig |
const std = @import("std");
const assert = std.debug.assert;
const buf = @import("Buffer.zig");
const window = @import("Window.zig");
const c = @import("c.zig").c;
const ReferenceCounter = @import("../RefCount.zig").ReferenceCounter;
var null_vao: ?VertexMeta = null;
pub const VertexMeta = struct {
ref_count: ReferenceCounter = ReferenceCounter{},
pub const VertexInput = struct {
// Input is ignored if componentCount == 0
pub const DataType = enum {
Float,
IntegerToFloat,
Integer,
CompactInts, // GL_INT_2_10_10_10_REV or GL_UNSIGNED_INT_2_10_10_10_REV
};
offset: u32, // offset into vertex buffer of first element
componentCount: u4, // 1, 2, 3, or 4
stride: u32, // byte offset between elements
dataType: DataType,
dataElementSize: u3, // how many bytes for each component in each element in the array
signed: bool, // for IntegerToFloat and Integer
normalised: bool, // for IntegerToFloat and Normals, if true maps values to range 0.0 - 1.0
source: *buf.Buffer,
};
const primitive_type_gl = [_]c_uint{
c.GL_POINTS,
c.GL_LINE_STRIP,
c.GL_LINE_LOOP,
c.GL_LINES,
//c.GL_LINE_STRIP_ADJACENCY,
//c.GL_LINES_ADJACENCY,
c.GL_TRIANGLE_STRIP,
c.GL_TRIANGLE_FAN,
c.GL_TRIANGLES,
//c.GL_TRIANGLE_STRIP_ADJACENCY,
//c.GL_TRIANGLES_ADJACENCY
};
pub const PrimitiveType = enum(u32) {
Points,
LineStrips,
LineLoops,
Lines,
//LineStripAdjacency,
//LinesAdjacency,
TriangleStrips,
TriangleFans,
Triangles,
//TriangleStripAdjacency,
//TrianglesAdjacency
};
id: u32,
fn getGLDataType(dataElementSize: u32, signed: bool) !u32 {
if (dataElementSize == 1) {
if (signed) {
return c.GL_BYTE;
} else {
return c.GL_UNSIGNED_BYTE;
}
} else if (dataElementSize == 2) {
if (signed) {
return c.GL_SHORT;
} else {
return c.GL_UNSIGNED_SHORT;
}
} else if (dataElementSize == 4) {
if (signed) {
return c.GL_INT;
} else {
return c.GL_UNSIGNED_INT;
}
}
return error.InvalidParameter;
}
pub fn init(inputs: []const VertexInput, indices_source: ?*buf.Buffer) !VertexMeta {
assert(inputs.len <= window.maximumNumVertexAttributes());
if (inputs.len > window.maximumNumVertexAttributes()) {
return error.InvalidParameter;
}
var id: u32 = 0;
c.glGenVertexArrays(1, @ptrCast([*c]c_uint, &id));
errdefer c.glDeleteVertexArrays(1, @ptrCast([*c]c_uint, &id));
if (id == 0) {
assert(false);
return error.OpenGLError;
}
c.glBindVertexArray(id);
if (indices_source != null) {
try indices_source.?.bind(buf.Buffer.BufferType.IndexData);
}
// Set buffer offsets and strides for vertex inputs
var i: u32 = 0;
for (inputs) |inp| {
if (inp.dataType != VertexInput.DataType.CompactInts and (inp.componentCount == 0 or inp.componentCount > 4)) {
assert(false);
return error.InvalidParameter;
}
try inp.source.bind(buf.Buffer.BufferType.VertexData);
if (inp.dataType == VertexInput.DataType.Float) {
if (inp.dataElementSize != 4 and inp.dataElementSize != 2) {
assert(false);
return error.InvalidParameter;
}
var dataType: u32 = 0;
if (inp.dataElementSize == 4) {
dataType = c.GL_FLOAT;
} else if (inp.dataElementSize == 2) {
dataType = c.GL_HALF_FLOAT;
}
assert(dataType != 0);
c.glVertexAttribPointer(i, inp.componentCount, dataType, 0, @intCast(c_int, inp.stride), @intToPtr(?*const c_void, inp.offset));
} else if (inp.dataType == VertexInput.DataType.CompactInts) {
var dataType: u32 = 0;
if (inp.signed) {
dataType = c.GL_INT_2_10_10_10_REV;
} else {
dataType = c.GL_UNSIGNED_INT_2_10_10_10_REV;
}
c.glVertexAttribPointer(i, 4, dataType, @boolToInt(inp.normalised), @intCast(c_int, inp.stride), @intToPtr(?*const c_void, inp.offset));
} else {
if (inp.componentCount * inp.dataElementSize % 4 != 0) {
assert(false);
return error.InvalidParameter;
}
if (inp.dataType == VertexInput.DataType.IntegerToFloat) {
var dataType: u32 = try getGLDataType(inp.dataElementSize, inp.signed);
assert(dataType != 0);
c.glVertexAttribPointer(i, inp.componentCount, dataType, @boolToInt(inp.normalised), @intCast(c_int, inp.stride), @intToPtr(?*const c_void, inp.offset));
} else if (inp.dataType == VertexInput.DataType.Integer) {
var dataType: u32 = try getGLDataType(inp.dataElementSize, inp.signed);
assert(dataType != 0);
c.glVertexAttribIPointer(i, inp.componentCount, dataType, @intCast(c_int, inp.stride), @intToPtr(?*const c_void, inp.offset));
}
}
c.glEnableVertexAttribArray(i);
i += 1;
}
return VertexMeta{ .id = id };
}
pub fn bind(self: VertexMeta) !void {
if (self.id == 0) {
assert(false);
return error.InvalidState;
}
c.glBindVertexArray(self.id);
}
pub fn draw(self: *VertexMeta, mode: PrimitiveType, first: u32, count: u32) !void {
if (count == 0) {
assert(false);
return error.InvalidParameter;
}
try self.bind();
c.glDrawArrays(primitive_type_gl[@enumToInt(mode)], @intCast(c_int, first), @intCast(c_int, count));
}
pub fn drawWithoutData(mode: PrimitiveType, first: u32, count: u32) !void {
if (count == 0) {
assert(false);
return error.InvalidParameter;
}
if (null_vao == null) {
null_vao = try VertexMeta.init(&[_]VertexInput{}, null);
}
try null_vao.?.bind();
c.glDrawArrays(primitive_type_gl[@enumToInt(mode)], @intCast(c_int, first), @intCast(c_int, count));
}
pub fn drawWithIndices(self: *VertexMeta, mode: PrimitiveType, large_indices: bool, first: u32, count: u32) !void {
if (count == 0) {
assert(false);
return error.InvalidParameter;
}
try self.bind();
if (large_indices) {
c.glDrawElements(primitive_type_gl[@enumToInt(mode)], @intCast(c_int, count), c.GL_UNSIGNED_INT, @intToPtr(?*const c_void, first * 4));
} else {
c.glDrawElements(primitive_type_gl[@enumToInt(mode)], @intCast(c_int, count), c.GL_UNSIGNED_SHORT, @intToPtr(?*const c_void, first * 2));
}
}
pub fn free(self: *VertexMeta) void {
if (self.id == 0) {
assert(false);
return;
}
self.ref_count.deinit();
c.glDeleteVertexArrays(1, @ptrCast([*c]const c_uint, &self.id));
self.id = 0;
}
pub fn unbind() void {
c.glBindVertexArray(0);
}
};
test "vao" {
try window.createWindow(false, 200, 200, "test", true, 0);
defer window.closeWindow();
const inData = [4]f32{ 1, 2, 3, 4 };
var buffer: buf.Buffer = try buf.Buffer.init();
try buffer.upload(buf.Buffer.BufferType.VertexData, std.mem.sliceAsBytes(inData[0..]), false);
const inputs = [_]VertexMeta.VertexInput{VertexMeta.VertexInput{
.offset = 0,
.componentCount = 4,
.stride = 0,
.dataType = VertexMeta.VertexInput.DataType.Float,
.dataElementSize = 4,
.signed = false,
.normalised = false,
.source = &buffer,
}};
var vao: VertexMeta = try VertexMeta.init(inputs[0..], null);
vao.free();
buffer.free();
} | src/WindowGraphicsInput/VertexMeta.zig |
const std = @import("std");
const io = std.io;
const mem = std.mem;
const meta = std.meta;
const net = std.net;
const os = std.os;
const testing = @import("testing.zig");
pub const Value = union(enum) {
Set: []const u8,
NotSet: void,
Null: void,
};
/// This struct is intended to be used as a field in a struct/tuple argument
/// passed to query/execute.
///
/// For example if you have a prepared update query where you don't want to touch
/// the second field, you can pass a struct/tuple like this:
///
/// .{
/// .arg1 = ...,
/// .arg2 = NotSet{ .type = i64 },
/// }
///
/// TODO(vincent): the `type` field is necessary for now to make NotSet work but it's not great.
pub const NotSet = struct {
type: type,
};
pub const NamedValue = struct {
name: []const u8,
value: Value,
};
pub const Values = union(enum) {
Normal: []Value,
Named: []NamedValue,
};
pub const CQLVersion = struct {
major: u16,
minor: u16,
patch: u16,
pub fn fromString(s: []const u8) !CQLVersion {
var version = CQLVersion{
.major = 0,
.minor = 0,
.patch = 0,
};
var it = mem.split(s, ".");
var pos: usize = 0;
while (it.next()) |v| {
const n = std.fmt.parseInt(u16, v, 10) catch return error.InvalidCQLVersion;
switch (pos) {
0 => version.major = n,
1 => version.minor = n,
2 => version.patch = n,
else => break,
}
pos += 1;
}
if (version.major < 3) {
return error.InvalidCQLVersion;
}
return version;
}
pub fn print(self: @This(), buf: []u8) ![]u8 {
return std.fmt.bufPrint(buf, "{}.{}.{}", .{
self.major,
self.minor,
self.patch,
});
}
};
pub const ProtocolVersion = packed struct {
const Self = @This();
version: u8,
pub fn init(b: u8) !Self {
var res = Self{
.version = b,
};
if ((res.version & 0x7) < 3 or (res.version & 0x7) > 5) {
return error.InvalidProtocolVersion;
}
return res;
}
pub fn is(self: Self, comptime version: comptime_int) bool {
return self.version & 0x7 == @as(u8, version);
}
pub fn isAtLeast(self: Self, comptime version: comptime_int) bool {
const tmp = self.version & 0x7;
return tmp >= version;
}
pub fn isRequest(self: Self) bool {
return self.version & 0x0f == self.version;
}
pub fn isResponse(self: Self) bool {
return self.version & 0xf0 == 0x80;
}
pub fn fromString(s: []const u8) !ProtocolVersion {
if (mem.startsWith(u8, s, "3/")) {
return ProtocolVersion{ .version = 3 };
} else if (mem.startsWith(u8, s, "4/")) {
return ProtocolVersion{ .version = 4 };
} else if (mem.startsWith(u8, s, "5/")) {
return ProtocolVersion{ .version = 5 };
} else {
return error.InvalidProtocolVersion;
}
}
pub fn toString(self: Self) ![]const u8 {
if (self.is(3)) {
return "3/v3";
} else if (self.is(4)) {
return "4/v4";
} else if (self.is(5)) {
return "5/v5-beta";
} else {
return error.InvalidProtocolVersion;
}
}
};
pub const Opcode = packed enum(u8) {
Error = 0x00,
Startup = 0x01,
Ready = 0x02,
Authenticate = 0x03,
Options = 0x05,
Supported = 0x06,
Query = 0x07,
Result = 0x08,
Prepare = 0x09,
Execute = 0x0A,
Register = 0x0B,
Event = 0x0C,
Batch = 0x0D,
AuthChallenge = 0x0E,
AuthResponse = 0x0F,
AuthSuccess = 0x10,
};
pub const CompressionAlgorithm = enum {
LZ4,
Snappy,
pub fn fromString(s: []const u8) !CompressionAlgorithm {
if (mem.eql(u8, "lz4", s)) {
return CompressionAlgorithm.LZ4;
} else if (mem.eql(u8, "snappy", s)) {
return CompressionAlgorithm.Snappy;
} else {
return error.InvalidCompressionAlgorithm;
}
}
pub fn toString(self: @This()) []const u8 {
return switch (self) {
.LZ4 => "lz4",
.Snappy => "snappy",
};
}
};
pub const Consistency = packed enum(u16) {
Any = 0x0000,
One = 0x0001,
Two = 0x0002,
Three = 0x0003,
Quorum = 0x0004,
All = 0x0005,
LocalQuorum = 0x0006,
EachQuorum = 0x0007,
Serial = 0x0008,
LocalSerial = 0x0009,
LocalOne = 0x000A,
};
pub const BatchType = packed enum(u8) {
Logged = 0,
Unlogged = 1,
Counter = 2,
};
pub const OptionID = packed enum(u16) {
Custom = 0x0000,
Ascii = 0x0001,
Bigint = 0x0002,
Blob = 0x0003,
Boolean = 0x0004,
Counter = 0x0005,
Decimal = 0x0006,
Double = 0x0007,
Float = 0x0008,
Int = 0x0009,
Timestamp = 0x000B,
UUID = 0x000C,
Varchar = 0x000D,
Varint = 0x000E,
Timeuuid = 0x000F,
Inet = 0x0010,
Date = 0x0011,
Time = 0x0012,
Smallint = 0x0013,
Tinyint = 0x0014,
Duration = 0x0015,
List = 0x0020,
Map = 0x0021,
Set = 0x0022,
UDT = 0x0030,
Tuple = 0x0031,
};
test "cql version: fromString" {
testing.expectEqual(CQLVersion{ .major = 3, .minor = 0, .patch = 0 }, try CQLVersion.fromString("3.0.0"));
testing.expectEqual(CQLVersion{ .major = 3, .minor = 4, .patch = 0 }, try CQLVersion.fromString("3.4.0"));
testing.expectEqual(CQLVersion{ .major = 3, .minor = 5, .patch = 4 }, try CQLVersion.fromString("3.5.4"));
testing.expectError(error.InvalidCQLVersion, CQLVersion.fromString("1.0.0"));
}
test "protocol version: fromString" {
testing.expect((try ProtocolVersion.fromString("3/v3")).is(3));
testing.expect((try ProtocolVersion.fromString("4/v4")).is(4));
testing.expect((try ProtocolVersion.fromString("5/v5")).is(5));
testing.expect((try ProtocolVersion.fromString("5/v5-beta")).is(5));
testing.expectError(error.InvalidProtocolVersion, ProtocolVersion.fromString("lalal"));
}
test "protocol version: serialize and deserialize" {
const testCase = struct {
exp: comptime_int,
b: [2]u8,
err: ?anyerror,
};
const testCases = [_]testCase{
testCase{
.exp = 3,
.b = [2]u8{ 0x03, 0x83 },
.err = null,
},
testCase{
.exp = 4,
.b = [2]u8{ 0x04, 0x84 },
.err = null,
},
testCase{
.exp = 5,
.b = [2]u8{ 0x05, 0x85 },
.err = null,
},
testCase{
.exp = 0,
.b = [2]u8{ 0x00, 0x00 },
.err = error.InvalidProtocolVersion,
},
};
inline for (testCases) |tc| {
var version: ProtocolVersion = undefined;
if (tc.err) |err| {
testing.expectError(err, ProtocolVersion.init(tc.b[0]));
} else {
var v1 = try ProtocolVersion.init(tc.b[0]);
var v2 = try ProtocolVersion.init(tc.b[1]);
testing.expect(v1.is(tc.exp));
testing.expect(v1.isRequest());
testing.expect(v2.isResponse());
}
}
}
test "compression algorith: fromString" {
testing.expectEqual(CompressionAlgorithm.LZ4, try CompressionAlgorithm.fromString("lz4"));
testing.expectEqual(CompressionAlgorithm.Snappy, try CompressionAlgorithm.fromString("snappy"));
testing.expectError(error.InvalidCompressionAlgorithm, CompressionAlgorithm.fromString("foobar"));
} | src/primitive_types.zig |
const std = @import("std");
const mem = std.mem;
const v = @import("vector_types.zig");
const _mm256_storeu_si256 = @import("llvm_intrinsics.zig")._mm256_storeu_si256;
const common = @import("common.zig");
const escape_map = [256]u8{
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 0x0.
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0x22, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0x2f,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 0x4.
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0x5c, 0, 0, 0, // 0x5.
0, 0, 0x08, 0, 0, 0, 0x0c, 0, 0, 0, 0, 0, 0, 0, 0x0a, 0, // 0x6.
0, 0, 0x0d, 0, 0x09, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 0x7.
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
};
// handle a unicode codepoint
// write appropriate values into dest
// src will advance 6 bytes or 12 bytes
// dest will advance a variable amount (return via pointer)
// return true if the unicode codepoint was valid
// We work in little-endian then swap at write time
// inline fn handle_unicode_codepoint(src: *std.io.StreamSource, dst: *std.ArrayListUnmanaged(u8), allocator: *mem.Allocator) !bool {
inline fn handle_unicode_codepoint2(dst: []u8) !bool {
// jsoncharutils::hex_to_u32_nocheck fills high 16 bits of the return value with 1s if the
// conversion isn't valid; we defer the check for this to inside the
// multilingual plane check
var buf: [6]u8 = undefined;
var dst_buf: [4]u8 = undefined;
{
// const nbytes = try src.read(&buf);
// if (nbytes != 6) return error.EndOfStream;
buf[0..6].* = dst[0..6].*;
}
var code_point = CharUtils.hex_to_u32_nocheck(buf[2..6].*);
// check for low surrogate for characters outside the Basic
// Multilingual Plane.
if (code_point >= 0xd800 and code_point < 0xdc00) {
if ((buf[0] != '\\') or buf[1] != 'u') {
return false;
}
const code_point_2 = CharUtils.hex_to_u32_nocheck(buf[2..6].*);
// if the first code point is invalid we will get here, as we will go past
// the check for being outside the Basic Multilingual plane. If we don't
// find a \u immediately afterwards we fail out anyhow, but if we do,
// this check catches both the case of the first code point being invalid
// or the second code point being invalid.
if ((code_point | code_point_2) >> 16 != 0) {
return false;
}
code_point =
(((code_point - 0xd800) << 10) | (code_point_2 -% 0xdc00)) +% 0x10000;
// const nbytes = try src.read(&buf);
// if (nbytes != 6) return error.EndOfStream;
buf[0..6].* = dst[6..12].*;
}
const offset = CharUtils.codepoint_to_utf8(code_point, &dst_buf);
// try dst.appendSlice(allocator, dst_buf[0..offset]);
mem.copy(u8, dst, dst_buf[0..offset]);
return offset > 0;
}
inline fn handle_unicode_codepoint(src_ptr: *[*]const u8, dst_ptr: *[*]u8) bool {
// jsoncharutils::hex_to_u32_nocheck fills high 16 bits of the return value with 1s if the
// conversion isn't valid; we defer the check for this to inside the
// multilingual plane check
var code_point = CharUtils.hex_to_u32_nocheck(src_ptr.* + 2);
src_ptr.* += 6;
// check for low surrogate for characters outside the Basic
// Multilingual Plane.
if (code_point >= 0xd800 and code_point < 0xdc00) {
if ((src_ptr.*[0] != '\\') or src_ptr.*[1] != 'u') {
return false;
}
const code_point_2 = CharUtils.hex_to_u32_nocheck(src_ptr.* + 2);
// if the first code point is invalid we will get here, as we will go past
// the check for being outside the Basic Multilingual plane. If we don't
// find a \u immediately afterwards we fail out anyhow, but if we do,
// this check catches both the case of the first code point being invalid
// or the second code point being invalid.
if ((code_point | code_point_2) >> 16 != 0) {
return false;
}
code_point =
(((code_point - 0xd800) << 10) | (code_point_2 -% 0xdc00)) +% 0x10000;
src_ptr.* += 6;
}
const offset = CharUtils.codepoint_to_utf8(code_point, dst_ptr.*);
dst_ptr.* += offset;
return offset > 0;
}
/// Unescape a string from src to dst, stopping at a final unescaped quote. E.g., if src points at 'joe"', then
/// dst needs to have four free bytes.
pub inline fn parse_string(src_: [*]const u8, dst_: [*]u8) ?[*]u8 {
var src = src_;
var dst = dst_;
while (true) {
// Copy the next n bytes, and find the backslash and quote in them.
const bs_quote = try BackslashAndQuote.copy_and_find(src, dst);
// std.log.debug("bs_quote {b}", .{bs_quote});
// If the next thing is the end quote, copy and return
if (bs_quote.has_quote_first()) {
// we encountered quotes first. Move dst to point to quotes and exit
// std.log.debug("has_quote_first quote_index {} dst.items.len {}", .{ bs_quote.quote_index(), dst.items.len });
return dst + bs_quote.quote_index();
}
if (bs_quote.has_backslash()) {
// find out where the backspace is */
const bs_dist = bs_quote.backslash_index();
const escape_char = src[bs_dist + 1];
// we encountered backslash first. Handle backslash */
if (escape_char == 'u') {
// move src/dst up to the start; they will be further adjusted
// within the unicode codepoint handling code. */
src += bs_dist;
dst += bs_dist;
if (!handle_unicode_codepoint(&src, &dst)) {
return null;
}
} else {
// simple 1:1 conversion. Will eat bs_dist+2 characters in input and
// * write bs_dist+1 characters to output
// * note this may reach beyond the part of the buffer we've actually
// * seen. I think this is ok */
const escape_result = escape_map[escape_char];
if (escape_result == 0) {
return null; // bogus escape value is an error */
}
// std.debug.panic("TODO put escape result into dest", .{});
dst[bs_dist] = escape_result;
src += bs_dist + 2;
dst += bs_dist + 1;
}
} else {
// /* they are the same. Since they can't co-occur, it means we
// * encountered neither. */
src += BackslashAndQuote.BYTES_PROCESSED;
dst += BackslashAndQuote.BYTES_PROCESSED;
}
}
// /* can't be reached */
unreachable;
}
/// allocates and returns an unescaped a string from src, stopping at a final unescaped quote.
/// e.g., if src points at 'joe"', returns 'joe'.
/// caller owns the memory.
pub inline fn parse_string_alloc(comptime T: type, src_: [*]const u8, allocator: mem.Allocator, str_len: u16) !T {
var src = src_;
var dst_slice = try allocator.alloc(u8, str_len);
dst_slice.len = 0;
errdefer allocator.free(dst_slice);
while (true) {
if (dst_slice.len >= str_len) return error.CAPACITY;
// Copy the next n bytes, and find the backslash and quote in them.
const bs_quote = try BackslashAndQuote.copy_and_find(src, dst_slice.ptr + dst_slice.len);
// std.log.debug("bs_quote {b}", .{bs_quote});
// If the next thing is the end quote, copy and return
if (bs_quote.has_quote_first()) {
// we encountered quotes first. Move dst to point to quotes and exit
// std.log.debug("has_quote_first quote_index {} dst.items.len {}", .{ bs_quote.quote_index(), dst.items.len });
// return dst + bs_quote.quote_index();
dst_slice.len += bs_quote.quote_index();
dst_slice = try allocator.realloc(dst_slice, dst_slice.len);
return dst_slice;
}
if (bs_quote.has_backslash()) {
// find out where the backspace is */
const bs_dist = bs_quote.backslash_index();
const escape_char = src[bs_dist + 1];
// we encountered backslash first. Handle backslash */
if (escape_char == 'u') {
// move src/dst up to the start; they will be further adjusted
// within the unicode codepoint handling code. */
src += bs_dist;
dst_slice.len += bs_dist;
var dst = dst_slice.ptr + dst_slice.len;
if (!handle_unicode_codepoint(&src, &dst))
return error.STRING_ERROR;
dst_slice.len += try common.ptr_diff(u8, dst, dst_slice.ptr + dst_slice.len);
} else {
// simple 1:1 conversion. Will eat bs_dist+2 characters in input and
// * write bs_dist+1 characters to output
// * note this may reach beyond the part of the buffer we've actually
// * seen. I think this is ok */
const escape_result = escape_map[escape_char];
if (escape_result == 0) {
return error.STRING_ERROR; // bogus escape value is an error */
}
(dst_slice.ptr + dst_slice.len)[bs_dist] = escape_result;
src += bs_dist + 2;
dst_slice.len += 1;
}
} else {
// /* they are the same. Since they can't co-occur, it means we
// * encountered neither. */
src += BackslashAndQuote.BYTES_PROCESSED;
dst_slice.len += BackslashAndQuote.BYTES_PROCESSED;
}
}
// /* can't be reached */
unreachable;
}
pub const BackslashAndQuote = struct {
bs_bits: u32,
quote_bits: u32,
pub const BYTES_PROCESSED = 32;
pub inline fn copy_and_find(src: [*]const u8, dst: [*]u8) !BackslashAndQuote {
// std.log.debug("nbytes {} s: '{s}'", .{ nbytes, s[0..nbytes] });
const src_vec: v.u8x32 = src[0..BYTES_PROCESSED].*;
// store to dest unconditionally - we can overwrite the bits we don't like later
// v.store(dst);
// VMOVDQU
// _mm256_storeu_si256(dst, v);
dst[0..BYTES_PROCESSED].* = src_vec;
const bs = src_vec == @splat(BYTES_PROCESSED, @as(u8, '\\'));
const qs = src_vec == @splat(BYTES_PROCESSED, @as(u8, '"'));
return BackslashAndQuote{ .bs_bits = @ptrCast(*const u32, &bs).*, .quote_bits = @ptrCast(*const u32, &qs).* };
}
fn has_quote_first(bsq: BackslashAndQuote) bool {
return ((bsq.bs_bits -% 1) & bsq.quote_bits) != 0;
}
fn has_backslash(bsq: BackslashAndQuote) bool {
return ((bsq.quote_bits -% 1) & bsq.bs_bits) != 0;
}
fn quote_index(bsq: BackslashAndQuote) u32 {
return @ctz(u32, bsq.quote_bits);
}
fn backslash_index(bsq: BackslashAndQuote) u32 {
return @ctz(u32, bsq.bs_bits);
}
pub fn format(value: BackslashAndQuote, comptime _: []const u8, options: std.fmt.FormatOptions, writer: anytype) !void {
_ = options;
_ = try writer.print("bs_bits {b:0>32} quote_bits {b:0>32}", .{ value.bs_bits, value.quote_bits });
}
};
pub const Value128 = struct {
low: u64,
high: u64,
};
pub const CharUtils = struct {
const digit_to_val32 = [886]u32{
0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF,
0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF,
0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF,
0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF,
0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF,
0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF,
0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF,
0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF,
0x0, 0x1, 0x2, 0x3, 0x4, 0x5,
0x6, 0x7, 0x8, 0x9, 0xFFFFFFFF, 0xFFFFFFFF,
0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xa,
0xb, 0xc, 0xd, 0xe, 0xf, 0xFFFFFFFF,
0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF,
0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF,
0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF,
0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF,
0xFFFFFFFF, 0xa, 0xb, 0xc, 0xd, 0xe,
0xf, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF,
0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF,
0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF,
0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF,
0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF,
0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF,
0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF,
0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF,
0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF,
0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF,
0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF,
0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF,
0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF,
0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF,
0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF,
0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF,
0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF,
0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF,
0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF,
0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF,
0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF,
0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF,
0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF,
0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF,
0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF,
0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF,
0x0, 0x10, 0x20, 0x30, 0x40, 0x50,
0x60, 0x70, 0x80, 0x90, 0xFFFFFFFF, 0xFFFFFFFF,
0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xa0,
0xb0, 0xc0, 0xd0, 0xe0, 0xf0, 0xFFFFFFFF,
0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF,
0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF,
0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF,
0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF,
0xFFFFFFFF, 0xa0, 0xb0, 0xc0, 0xd0, 0xe0,
0xf0, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF,
0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF,
0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF,
0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF,
0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF,
0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF,
0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF,
0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF,
0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF,
0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF,
0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF,
0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF,
0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF,
0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF,
0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF,
0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF,
0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF,
0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF,
0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF,
0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF,
0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF,
0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF,
0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF,
0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF,
0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF,
0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF,
0x0, 0x100, 0x200, 0x300, 0x400, 0x500,
0x600, 0x700, 0x800, 0x900, 0xFFFFFFFF, 0xFFFFFFFF,
0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xa00,
0xb00, 0xc00, 0xd00, 0xe00, 0xf00, 0xFFFFFFFF,
0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF,
0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF,
0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF,
0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF,
0xFFFFFFFF, 0xa00, 0xb00, 0xc00, 0xd00, 0xe00,
0xf00, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF,
0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF,
0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF,
0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF,
0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF,
0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF,
0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF,
0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF,
0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF,
0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF,
0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF,
0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF,
0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF,
0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF,
0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF,
0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF,
0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF,
0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF,
0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF,
0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF,
0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF,
0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF,
0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF,
0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF,
0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF,
0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF,
0x0, 0x1000, 0x2000, 0x3000, 0x4000, 0x5000,
0x6000, 0x7000, 0x8000, 0x9000, 0xFFFFFFFF, 0xFFFFFFFF,
0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xa000,
0xb000, 0xc000, 0xd000, 0xe000, 0xf000, 0xFFFFFFFF,
0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF,
0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF,
0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF,
0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF,
0xFFFFFFFF, 0xa000, 0xb000, 0xc000, 0xd000, 0xe000,
0xf000, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF,
0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF,
0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF,
0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF,
0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF,
0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF,
0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF,
0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF,
0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF,
0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF,
0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF,
0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF,
0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF,
0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF,
0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF,
0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF,
0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF,
0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF,
0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF,
0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF,
0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF,
0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF,
0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF,
0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF,
0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF,
0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF,
};
pub inline fn hex_to_u32_nocheck(src: [*]const u8) u32 {
const v1 = digit_to_val32[630 + @as(u16, src[0])];
const v2 = digit_to_val32[420 + @as(u16, src[1])];
const v3 = digit_to_val32[210 + @as(u16, src[2])];
const v4 = digit_to_val32[0 + @as(u16, src[3])];
return v1 | v2 | v3 | v4;
}
pub inline fn codepoint_to_utf8(cp: u32, c: [*]u8) u3 {
if (cp <= 0x7F) {
c[0] = @truncate(u8, cp);
return 1; // ascii
}
if (cp <= 0x7FF) {
c[0] = @truncate(u8, (cp >> 6) + 192);
c[1] = @truncate(u8, (cp & 63) + 128);
return 2; // universal plane
// Surrogates are treated elsewhere...
//} //else if (0xd800 <= cp && cp <= 0xdfff) {
// return 0; // surrogates // could put assert here
} else if (cp <= 0xFFFF) {
c[0] = @truncate(u8, (cp >> 12) + 224);
c[1] = @truncate(u8, ((cp >> 6) & 63) + 128);
c[2] = @truncate(u8, (cp & 63) + 128);
return 3;
} else if (cp <= 0x10FFFF) { // if you know you have a valid code point, this
// is not needed
c[0] = @truncate(u8, (cp >> 18) + 240);
c[1] = @truncate(u8, ((cp >> 12) & 63) + 128);
c[2] = @truncate(u8, ((cp >> 6) & 63) + 128);
c[3] = @truncate(u8, (cp & 63) + 128);
return 4;
}
// will return 0 when the code point was too large.
return 0; // bad r
}
// return non-zero if not a structural or whitespace char
// zero otherwise
pub fn is_not_structural_or_whitespace(c: u8) bool {
return structural_or_whitespace_negated[c] != 0;
}
pub fn is_structural_or_whitespace(c: u8) bool {
return structural_or_whitespace[c] != 0;
}
const structural_or_whitespace_negated = [256]u1{
1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 0, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 0, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
};
const structural_or_whitespace = [256]u1{
0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 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, 0, 1, 0, 0,
0, 0, 0, 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, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
};
pub fn full_multiplication(value1: u64, value2: u64) Value128 {
const r = @as(u128, value1) * value2;
return .{
.low = @truncate(u64, r),
.high = @truncate(u64, r >> 64),
};
}
}; | src/string_parsing.zig |
const std = @import("std");
const Allocator = std.mem.Allocator;
const gui = @import("gui");
const nvg = @import("nanovg");
const geometry = @import("gui/geometry.zig");
const Rect = geometry.Rect;
pub const Buttons = enum {
ok,
ok_cancel,
yes_no,
yes_no_cancel,
};
pub const Icon = enum {
none,
@"error",
warning,
question,
};
pub const Result = enum {
none,
ok,
cancel,
yes,
no,
};
const MessageBoxWidget = @This();
widget: gui.Widget,
allocator: Allocator,
drawIconFn: fn (nvg, f32, f32) void,
message_label: *gui.Label,
ok_button: *gui.Button,
cancel_button: *gui.Button,
yes_button: *gui.Button,
no_button: *gui.Button,
result: Result = .none,
pub fn init(allocator: Allocator, message: []const u8) !*MessageBoxWidget {
const width = 240;
const height = 100;
var self = try allocator.create(MessageBoxWidget);
self.* = MessageBoxWidget{
.widget = gui.Widget.init(allocator, Rect(f32).make(0, 0, width, height)),
.allocator = allocator,
.drawIconFn = drawNoIcon,
.message_label = try gui.Label.init(allocator, Rect(f32).make(10 + 32 + 10, 10, width - 30 - 32, 40), message),
.ok_button = try gui.Button.init(allocator, Rect(f32).make(width - 80 - 10, height - 25 - 10, 80, 25), "OK"),
.cancel_button = try gui.Button.init(allocator, Rect(f32).make(width - 80 - 10, height - 25 - 10, 80, 25), "Cancel"),
.yes_button = try gui.Button.init(allocator, Rect(f32).make(width - 80 - 10, height - 25 - 10, 80, 25), "Yes"),
.no_button = try gui.Button.init(allocator, Rect(f32).make(width - 80 - 10, height - 25 - 10, 80, 25), "No"),
};
self.widget.onKeyDownFn = onKeyDown;
self.ok_button.onClickFn = onOkButtonClick;
self.cancel_button.onClickFn = onCancelButtonClick;
self.yes_button.onClickFn = onYesButtonClick;
self.no_button.onClickFn = onNoButtonClick;
try self.widget.addChild(&self.message_label.widget);
try self.widget.addChild(&self.ok_button.widget);
try self.widget.addChild(&self.cancel_button.widget);
try self.widget.addChild(&self.yes_button.widget);
try self.widget.addChild(&self.no_button.widget);
self.widget.drawFn = draw;
return self;
}
pub fn deinit(self: *MessageBoxWidget) void {
self.message_label.deinit();
self.ok_button.deinit();
self.cancel_button.deinit();
self.yes_button.deinit();
self.no_button.deinit();
self.widget.deinit();
self.allocator.destroy(self);
}
pub fn setSize(self: *MessageBoxWidget, width: f32, height: f32) void {
self.message_label.widget.setSize(width - 30 - 32, 40);
self.widget.setSize(width, height);
}
pub fn configure(self: *MessageBoxWidget, icon: Icon, buttons: Buttons, message: []const u8) void {
self.drawIconFn = switch (icon) {
.none => drawNoIcon,
.@"error" => drawErrorIcon,
.warning => drawWarningIcon,
.question => drawQuestionIcon,
};
const rect = self.widget.relative_rect;
switch (buttons) {
.ok => {
self.ok_button.widget.setPosition(0.5 * rect.w - 40, rect.h - 35);
self.ok_button.widget.visible = true;
self.cancel_button.widget.visible = false;
self.yes_button.widget.visible = false;
self.no_button.widget.visible = false;
},
.ok_cancel => {
self.ok_button.widget.setPosition(rect.w - 90 - 90, rect.h - 35);
self.ok_button.widget.visible = true;
self.cancel_button.widget.setPosition(rect.w - 90, rect.h - 35);
self.cancel_button.widget.visible = true;
self.yes_button.widget.visible = false;
self.no_button.widget.visible = false;
},
.yes_no => {
self.ok_button.widget.visible = false;
self.cancel_button.widget.visible = false;
self.yes_button.widget.setPosition(rect.w - 90 - 90, rect.h - 35);
self.yes_button.widget.visible = true;
self.no_button.widget.setPosition(rect.w - 90, rect.h - 35);
self.no_button.widget.visible = true;
},
.yes_no_cancel => {
self.ok_button.widget.visible = false;
self.cancel_button.widget.setPosition(rect.w - 90, rect.h - 35);
self.cancel_button.widget.visible = true;
self.yes_button.widget.setPosition(rect.w - 90 - 90 - 90, rect.h - 35);
self.yes_button.widget.visible = true;
self.no_button.widget.setPosition(rect.w - 90 - 90, rect.h - 35);
self.no_button.widget.visible = true;
}
}
self.message_label.text = message;
}
fn onKeyDown(widget: *gui.Widget, event: *gui.KeyEvent) void {
widget.onKeyDown(event);
var self = @fieldParentPtr(MessageBoxWidget, "widget", widget);
switch (event.key) {
.Return => self.setResult(if (self.ok_button.widget.visible) .ok else .yes),
.Escape => self.setResult(if (self.cancel_button.widget.visible) .cancel else .none),
else => event.event.ignore(),
}
}
fn onOkButtonClick(button: *gui.Button) void {
if (button.widget.parent) |parent| {
var self = @fieldParentPtr(MessageBoxWidget, "widget", parent);
self.setResult(.ok);
}
}
fn onCancelButtonClick(button: *gui.Button) void {
if (button.widget.parent) |parent| {
var self = @fieldParentPtr(MessageBoxWidget, "widget", parent);
self.setResult(.cancel);
}
}
fn onYesButtonClick(button: *gui.Button) void {
if (button.widget.parent) |parent| {
var self = @fieldParentPtr(MessageBoxWidget, "widget", parent);
self.setResult(.yes);
}
}
fn onNoButtonClick(button: *gui.Button) void {
if (button.widget.parent) |parent| {
var self = @fieldParentPtr(MessageBoxWidget, "widget", parent);
self.setResult(.no);
}
}
fn setResult(self: *MessageBoxWidget, result: Result) void {
self.result = result;
if (self.widget.getWindow()) |window| {
window.close();
}
}
fn drawNoIcon(vg: nvg, x: f32, y: f32) void {
_ = vg;
_ = x;
_ = y;
}
fn drawErrorIcon(vg: nvg, x: f32, y: f32) void {
vg.save();
defer vg.restore();
vg.translate(x, y);
vg.beginPath();
vg.circle(16, 16, 15.5);
vg.fillColor(nvg.rgb(250, 10, 0));
vg.fill();
vg.strokeColor(nvg.rgb(0, 0, 0));
vg.stroke();
vg.beginPath();
vg.moveTo(9, 9);
vg.lineTo(23, 23);
vg.moveTo(23, 9);
vg.lineTo(9, 23);
vg.strokeColor(nvg.rgbf(1, 1, 1));
vg.strokeWidth(3);
vg.stroke();
}
fn drawWarningIcon(vg: nvg, x: f32, y: f32) void {
vg.save();
defer vg.restore();
vg.translate(x, y);
vg.beginPath();
vg.moveTo(16, 31.5);
vg.arcTo(31.5, 31.5, 16, 0.5, 2);
vg.arcTo(16, 0.5, 0.5, 31.5, 2);
vg.arcTo(0.5, 31.5, 16, 31.5, 2);
vg.closePath();
vg.fillColor(nvg.rgb(247, 226,107));
vg.fill();
vg.strokeColor(nvg.rgb(164, 100, 34));
vg.stroke();
vg.beginPath();
vg.moveTo(16, 12);
vg.arcTo(14, 12, 15, 23, 1);
vg.arcTo(15, 23, 17, 23, 1);
vg.arcTo(17, 23, 18, 12, 1);
vg.arcTo(18, 12, 16, 12, 1);
vg.closePath();
vg.ellipse(16, 26, 2, 2);
vg.fillColor(nvg.rgb(66, 66, 66));
vg.fill();
}
fn drawQuestionIcon(vg: nvg, x: f32, y: f32) void {
vg.save();
defer vg.restore();
vg.translate(x, y);
vg.beginPath();
vg.circle(16, 16, 15.5);
vg.fillColor(nvg.rgbf(1, 1, 1));
vg.fill();
vg.strokeColor(nvg.rgb(0, 0, 0));
vg.stroke();
vg.fillColor(nvg.rgb(10, 32, 231));
vg.fontFace("guifontbold");
vg.fontSize(22);
vg.textAlign(.{ .horizontal = .center, .vertical = .middle });
_ = vg.text(16, 16 + 2, "?");
}
pub fn draw(widget: *gui.Widget, vg: nvg) void {
var self = @fieldParentPtr(MessageBoxWidget, "widget", widget);
const rect = widget.relative_rect;
vg.beginPath();
vg.rect(0, 0, rect.w, rect.h - 45);
vg.fillColor(nvg.rgbf(1, 1, 1));
vg.fill();
vg.beginPath();
vg.rect(0, rect.h - 45, rect.w, 45);
vg.fillColor(gui.theme_colors.background);
vg.fill();
self.drawIconFn(vg, 10, 13);
widget.drawChildren(vg);
} | src/MessageBoxWidget.zig |
const std = @import("std");
const gui = @import("gui.zig");
const Gradient = @import("gradient.zig").Gradient;
const prefs = @import("prefs.zig");
const VTE = @import("vte");
const c = VTE.c;
const gtk = VTE.gtk;
const vte = VTE.vte;
const known_folders = @import("known-folders");
const nt = @import("nestedtext");
const allocator = std.heap.page_allocator;
const fmt = std.fmt;
const fs = std.fs;
const path = fs.path;
const math = std.math;
const mem = std.mem;
const meta = std.meta;
const os = std.os;
const stderr = std.io.getStdErr().writer();
pub const known_folders_config = .{
.xdg_on_mac = true,
};
pub fn parseEnum(comptime T: type, style: [*c]const u8) ?T {
const len = mem.len(style);
return meta.stringToEnum(T, style[0..len]);
}
pub fn getConfigDir(alloc: mem.Allocator) ?[]const u8 {
const dir = known_folders.getPath(alloc, .local_configuration) catch return null;
if (dir) |d| {
return path.join(alloc, &[_][]const u8{ d, "zterm" }) catch return null;
} else {
return if (os.getenv("HOME")) |h| path.join(alloc, &[_][]const u8{ h, ".config/zterm"}) catch return null else null;
}
}
pub fn getConfigDirHandle(dir: []const u8) ?std.fs.Dir {
defer allocator.free(dir);
if (fs.openDirAbsolute(dir, .{})) |d| {
return d;
} else |err| {
switch (err) {
fs.File.OpenError.FileNotFound => {
os.mkdir(dir, 0o755) catch return null;
if (fs.openDirAbsolute(dir, .{})) |d| {
return d;
} else |new_err| {
std.debug.print("OpenDir: {s}\n", .{new_err});
return null;
}
},
else => {
std.debug.print("Create Directory: {s}\n", .{err});
return null;
},
}
}
}
pub fn getConfigFile(alloc: mem.Allocator) ?[]const u8 {
const dir = known_folders.getPath(alloc, .local_configuration) catch return null;
if (dir) |d| {
return path.join(alloc, &[_][]const u8{ d, "zterm/config.nt" }) catch return null;
} else {
return if (os.getenv("HOME")) |h| path.join(alloc, &[_][]const u8{ h, ".config/zterm/config.nt" }) catch return null else null;
}
}
pub const DynamicTitleStyle = enum {
replaces_title,
before_title,
after_title,
not_displayed,
const Self = @This();
pub fn default() Self {
return Self.after_title;
}
};
pub const CustomCommand = union(enum) {
none,
command: []const u8,
const Self = @This();
pub fn default() Self {
return Self.none;
}
};
pub const Scrollback = union(enum) {
finite: f64,
infinite,
const Self = @This();
pub fn default() Self {
return Self{ .finite = 1500 };
}
pub fn set(self: Self, term: *c.VteTerminal) void {
switch (self) {
.finite => |v| c.vte_terminal_set_scrollback_lines(term, @floatToInt(c_long, v)),
.infinite => c.vte_terminal_set_scrollback_lines(term, -1),
}
}
};
pub const Font = union(enum) {
system,
custom: []const u8,
const Self = @This();
pub fn default() Self {
return Self.system;
}
fn set(self: Self, term: *c.VteTerminal) void {
switch (self) {
.system => c.vte_terminal_set_font(term, null),
.custom => |v| {
const font = fmt.allocPrintZ(allocator, "{s}", .{v}) catch |e| {
stderr.print("{s}\n", .{e}) catch {};
c.vte_terminal_set_font(term, null);
return;
};
defer allocator.free(font);
const fontdesc = c.pango_font_description_from_string(font.ptr);
c.vte_terminal_set_font(term, fontdesc);
},
}
}
};
pub const CursorStyle = enum {
block,
ibeam,
underline,
const Self = @This();
pub fn default() Self {
return Self.block;
}
fn set(self: Self, term: *c.VteTerminal) void {
switch (self) {
.block => c.vte_terminal_set_cursor_shape(term, c.VTE_CURSOR_SHAPE_BLOCK),
.ibeam => c.vte_terminal_set_cursor_shape(term, c.VTE_CURSOR_SHAPE_IBEAM),
.underline => c.vte_terminal_set_cursor_shape(term, c.VTE_CURSOR_SHAPE_UNDERLINE),
}
}
};
pub const Cursor = struct {
style: CursorStyle,
blinks: bool,
const Self = @This();
pub fn default() Self {
return Self{
.style = CursorStyle.default(),
.blinks = true,
};
}
pub fn set(self: Cursor, term: *c.VteTerminal) void {
self.style.set(term);
if (self.blinks) {
c.vte_terminal_set_cursor_blink_mode(term, c.VTE_CURSOR_BLINK_ON);
} else {
c.vte_terminal_set_cursor_blink_mode(term, c.VTE_CURSOR_BLINK_OFF);
}
}
};
pub const BackgroundStyle = enum {
solid_color,
image,
transparent,
gradient,
const Self = @This();
pub fn default() Self {
return Self.solid_color;
}
};
pub const ImageStyle = enum {
tiled,
centered,
scaled,
stretched,
const Self = @This();
pub fn default() Self {
return Self.tiled;
}
};
pub const BackgroundImage = struct {
file: []const u8,
style: ImageStyle,
};
pub const Background = union(BackgroundStyle) {
solid_color: void,
image: BackgroundImage,
transparent: f64,
gradient: Gradient,
const Self = @This();
pub fn default() Self {
return Self.solid_color;
}
};
pub const RGB = struct {
red: u8,
green: u8,
blue: u8,
const Self = @This();
pub fn default() Self {
return Self{
.red = 0,
.blue = 0,
.green = 0,
};
}
pub fn fromButton(button: gtk.ColorButton) Self {
const rgba = button.as_color_chooser().get_rgba();
return Self{
.red = @floatToInt(u8, math.round(rgba.red * 255.0)),
.green = @floatToInt(u8, math.round(rgba.green * 255.0)),
.blue = @floatToInt(u8, math.round(rgba.blue * 255.0)),
};
}
pub fn toGdk(self: Self) c.GdkRGBA {
return c.GdkRGBA{
.red = @intToFloat(f64, self.red) / 255.0,
.green = @intToFloat(f64, self.green) / 255.0,
.blue = @intToFloat(f64, self.blue) / 255.0,
.alpha = 1.0,
};
}
fn toGdkAlpha(self: Self, opacity: f64) c.GdkRGBA {
return c.GdkRGBA{
.red = @intToFloat(f64, self.red) / 255.0,
.green = @intToFloat(f64, self.green) / 255.0,
.blue = @intToFloat(f64, self.blue) / 255.0,
.alpha = opacity,
};
}
};
pub const Colors = struct {
text_color: RGB,
background_color: RGB,
black_color: RGB,
red_color: RGB,
green_color: RGB,
brown_color: RGB,
blue_color: RGB,
magenta_color: RGB,
cyan_color: RGB,
light_grey_color: RGB,
dark_grey_color: RGB,
light_red_color: RGB,
light_green_color: RGB,
yellow_color: RGB,
light_blue_color: RGB,
light_magenta_color: RGB,
light_cyan_color: RGB,
white_color: RGB,
pub fn default() Colors {
return Colors{
.text_color = RGB{ .red = 225, .green = 225, .blue = 225 },
.background_color = RGB{ .red = 36, .green = 34, .blue = 34 },
.black_color = RGB{ .red = 36, .green = 34, .blue = 34 },
.red_color = RGB{ .red = 165, .green = 29, .blue = 45 },
.green_color = RGB{ .red = 0, .green = 170, .blue = 0 },
.brown_color = RGB{ .red = 99, .green = 69, .blue = 44 },
.blue_color = RGB{ .red = 0, .green = 0, .blue = 170 },
.magenta_color = RGB{ .red = 170, .green = 0, .blue = 170 },
.cyan_color = RGB{ .red = 0, .green = 170, .blue = 170 },
.light_grey_color = RGB{ .red = 170, .green = 170, .blue = 170 },
.dark_grey_color = RGB{ .red = 85, .green = 85, .blue = 85 },
.light_red_color = RGB{ .red = 255, .green = 85, .blue = 85 },
.light_green_color = RGB{ .red = 85, .green = 255, .blue = 85 },
.yellow_color = RGB{ .red = 225, .green = 189, .blue = 0 },
.light_blue_color = RGB{ .red = 85, .green = 85, .blue = 255 },
.light_magenta_color = RGB{ .red = 255, .green = 85, .blue = 255 },
.light_cyan_color = RGB{ .red = 85, .green = 255, .blue = 255 },
.white_color = RGB{ .red = 225, .green = 225, .blue = 225 },
};
}
fn set(self: Colors, term: *c.VteTerminal) void {
const fgcolor = self.text_color.toGdk();
const bgcolor = self.background_color.toGdk();
const palette = self.toPalette();
c.vte_terminal_set_color_foreground(term, &fgcolor);
c.vte_terminal_set_colors(term, &fgcolor, &bgcolor, &palette, 16);
}
fn setBg(self: Colors, term: *c.VteTerminal) void {
const bgcolor = self.background_color.toGdk();
c.vte_terminal_set_color_background(term, &bgcolor);
}
fn toPalette(self: Colors) [16]c.GdkRGBA {
return [16]c.GdkRGBA{
self.black_color.toGdk(),
self.red_color.toGdk(),
self.green_color.toGdk(),
self.yellow_color.toGdk(),
self.blue_color.toGdk(),
self.magenta_color.toGdk(),
self.cyan_color.toGdk(),
self.light_grey_color.toGdk(),
self.dark_grey_color.toGdk(),
self.brown_color.toGdk(),
self.light_red_color.toGdk(),
self.light_green_color.toGdk(),
self.light_blue_color.toGdk(),
self.light_magenta_color.toGdk(),
self.light_cyan_color.toGdk(),
self.white_color.toGdk(),
};
}
};
pub const Config = struct {
initial_title: []const u8,
dynamic_title_style: DynamicTitleStyle,
custom_command: CustomCommand,
scrollback: Scrollback,
font: Font,
background: Background,
colors: Colors,
cursor: Cursor,
pub fn default() Config {
return Config{
.initial_title = "Zterm",
.dynamic_title_style = DynamicTitleStyle.default(),
.custom_command = CustomCommand.default(),
.scrollback = Scrollback.default(),
.font = Font.default(),
.background = Background.default(),
.colors = Colors.default(),
.cursor = Cursor.default(),
};
}
pub fn fromFile(dir: []const u8) ?Config {
if (getConfigDirHandle(dir)) |dir_fd| {
const fd = dir_fd.openFile("config.nt", .{ .read = true }) catch return null;
defer {
fd.close();
var dir_handle = dir_fd;
dir_handle.close();
}
const text = fd.reader().readAllAlloc(allocator, math.maxInt(usize)) catch return null;
defer allocator.free(text);
var parser = nt.Parser.init(allocator, .{});
@setEvalBranchQuota(4000);
const cfg = parser.parseTyped(Config, text) catch return null;
return cfg;
}
return null;
}
pub fn setBg(self: Config) void {
const provider = gui.css_provider;
const color = self.colors.background_color;
var buf: [55]u8 = undefined;
const bg_color = fmt.bufPrint(&buf, "\n background-color: rgb({d}, {d}, {d});",
.{color.red, color.green, color.blue}) catch return;
switch (self.background) {
.solid_color => {
const css_string = fmt.allocPrintZ(allocator,
".workview stack {{{s}\n background-size: 100% 100%;}}",
.{bg_color}) catch return;
_ = c.gtk_css_provider_load_from_data(provider, css_string, -1, null);
},
.image => |img| {
const file = fs.cwd().openFile(img.file, .{}) catch return;
file.close();
const centered =
\\ background-position: center;
\\ background-repeat: no-repeat;
;
const scaled =
\\ background-size: contain;
\\ background-repeat: no-repeat;
\\ background-position: center;
;
const styling = switch (img.style) {
.tiled => " background-repeat: repeat;\n",
.centered => centered,
.scaled => scaled,
.stretched => " background-size: 100% 100%;\n",
};
const css_string = fmt.allocPrintZ(allocator,
".workview stack {{\n background-image: url(\"{s}\");{s}\n{s}}}",
.{img.file, bg_color, styling}) catch return;
_ = c.gtk_css_provider_load_from_data(provider, css_string, -1, null);
},
.transparent => {},
.gradient => |g| {
if (g.toCss(".workview stack")) |css| {
defer allocator.free(css);
_ = c.gtk_css_provider_load_from_data(provider, css, -1, null);
}
},
}
}
pub fn set(self: Config, term: *c.VteTerminal) void {
self.colors.set(term);
self.scrollback.set(term);
self.font.set(term);
self.cursor.set(term);
}
pub fn save(self: Config, dir: []const u8) void {
const cfg_tree = nt.fromArbitraryType(allocator, self) catch return;
defer cfg_tree.deinit();
if (getConfigDirHandle(dir)) |h| {
var handle = h;
defer handle.close();
if (handle.createFile("config.nt", .{ .truncate = true })) |file| {
cfg_tree.stringify(.{}, file.writer()) catch return;
} else |write_err| {
std.debug.print("Write Error: {s}\n", .{write_err});
return;
}
}
}
}; | src/config.zig |
const std = @import("std");
// glslc -mfmt=num graphics/src/backend/vk/shaders/tex_vert.glsl -o -
pub const tex_vert_spv = std.mem.toBytes([_]u32{
0x07230203,0x00010000,0x000d000a,0x00000026,
0x00000000,0x00020011,0x00000001,0x0006000b,
0x00000001,0x4c534c47,0x6474732e,0x3035342e,
0x00000000,0x0003000e,0x00000000,0x00000001,
0x000b000f,0x00000000,0x00000004,0x6e69616d,
0x00000000,0x00000009,0x0000000b,0x0000000f,
0x00000011,0x00000018,0x0000001b,0x00030003,
0x00000002,0x000001c2,0x000a0004,0x475f4c47,
0x4c474f4f,0x70635f45,0x74735f70,0x5f656c79,
0x656e696c,0x7269645f,0x69746365,0x00006576,
0x00080004,0x475f4c47,0x4c474f4f,0x6e695f45,
0x64756c63,0x69645f65,0x74636572,0x00657669,
0x00040005,0x00000004,0x6e69616d,0x00000000,
0x00040005,0x00000009,0x76755f76,0x00000000,
0x00040005,0x0000000b,0x76755f61,0x00000000,
0x00040005,0x0000000f,0x6f635f76,0x00726f6c,
0x00040005,0x00000011,0x6f635f61,0x00726f6c,
0x00060005,0x00000016,0x505f6c67,0x65567265,
0x78657472,0x00000000,0x00060006,0x00000016,
0x00000000,0x505f6c67,0x7469736f,0x006e6f69,
0x00070006,0x00000016,0x00000001,0x505f6c67,
0x746e696f,0x657a6953,0x00000000,0x00070006,
0x00000016,0x00000002,0x435f6c67,0x4470696c,
0x61747369,0x0065636e,0x00070006,0x00000016,
0x00000003,0x435f6c67,0x446c6c75,0x61747369,
0x0065636e,0x00030005,0x00000018,0x00000000,
0x00040005,0x0000001b,0x6f705f61,0x00000073,
0x00060005,0x0000001e,0x74726556,0x736e6f43,
0x746e6174,0x00000073,0x00040006,0x0000001e,
0x00000000,0x0074616d,0x00040005,0x00000020,
0x6f635f75,0x0074736e,0x00040047,0x00000009,
0x0000001e,0x00000000,0x00040047,0x0000000b,
0x0000001e,0x00000001,0x00040047,0x0000000f,
0x0000001e,0x00000001,0x00040047,0x00000011,
0x0000001e,0x00000002,0x00050048,0x00000016,
0x00000000,0x0000000b,0x00000000,0x00050048,
0x00000016,0x00000001,0x0000000b,0x00000001,
0x00050048,0x00000016,0x00000002,0x0000000b,
0x00000003,0x00050048,0x00000016,0x00000003,
0x0000000b,0x00000004,0x00030047,0x00000016,
0x00000002,0x00040047,0x0000001b,0x0000001e,
0x00000000,0x00040048,0x0000001e,0x00000000,
0x00000005,0x00050048,0x0000001e,0x00000000,
0x00000023,0x00000000,0x00050048,0x0000001e,
0x00000000,0x00000007,0x00000010,0x00030047,
0x0000001e,0x00000002,0x00020013,0x00000002,
0x00030021,0x00000003,0x00000002,0x00030016,
0x00000006,0x00000020,0x00040017,0x00000007,
0x00000006,0x00000002,0x00040020,0x00000008,
0x00000003,0x00000007,0x0004003b,0x00000008,
0x00000009,0x00000003,0x00040020,0x0000000a,
0x00000001,0x00000007,0x0004003b,0x0000000a,
0x0000000b,0x00000001,0x00040017,0x0000000d,
0x00000006,0x00000004,0x00040020,0x0000000e,
0x00000003,0x0000000d,0x0004003b,0x0000000e,
0x0000000f,0x00000003,0x00040020,0x00000010,
0x00000001,0x0000000d,0x0004003b,0x00000010,
0x00000011,0x00000001,0x00040015,0x00000013,
0x00000020,0x00000000,0x0004002b,0x00000013,
0x00000014,0x00000001,0x0004001c,0x00000015,
0x00000006,0x00000014,0x0006001e,0x00000016,
0x0000000d,0x00000006,0x00000015,0x00000015,
0x00040020,0x00000017,0x00000003,0x00000016,
0x0004003b,0x00000017,0x00000018,0x00000003,
0x00040015,0x00000019,0x00000020,0x00000001,
0x0004002b,0x00000019,0x0000001a,0x00000000,
0x0004003b,0x00000010,0x0000001b,0x00000001,
0x00040018,0x0000001d,0x0000000d,0x00000004,
0x0003001e,0x0000001e,0x0000001d,0x00040020,
0x0000001f,0x00000009,0x0000001e,0x0004003b,
0x0000001f,0x00000020,0x00000009,0x00040020,
0x00000021,0x00000009,0x0000001d,0x00050036,
0x00000002,0x00000004,0x00000000,0x00000003,
0x000200f8,0x00000005,0x0004003d,0x00000007,
0x0000000c,0x0000000b,0x0003003e,0x00000009,
0x0000000c,0x0004003d,0x0000000d,0x00000012,
0x00000011,0x0003003e,0x0000000f,0x00000012,
0x0004003d,0x0000000d,0x0000001c,0x0000001b,
0x00050041,0x00000021,0x00000022,0x00000020,
0x0000001a,0x0004003d,0x0000001d,0x00000023,
0x00000022,0x00050090,0x0000000d,0x00000024,
0x0000001c,0x00000023,0x00050041,0x0000000e,
0x00000025,0x00000018,0x0000001a,0x0003003e,
0x00000025,0x00000024,0x000100fd,0x00010038
});
// glslc -mfmt=num graphics/src/backend/vk/shaders/tex_frag.glsl -o -
pub const tex_frag_spv = std.mem.toBytes([_]u32{
0x07230203,0x00010000,0x000d000a,0x00000018,
0x00000000,0x00020011,0x00000001,0x0006000b,
0x00000001,0x4c534c47,0x6474732e,0x3035342e,
0x00000000,0x0003000e,0x00000000,0x00000001,
0x0008000f,0x00000004,0x00000004,0x6e69616d,
0x00000000,0x00000009,0x00000011,0x00000015,
0x00030010,0x00000004,0x00000007,0x00030003,
0x00000002,0x000001c2,0x000a0004,0x475f4c47,
0x4c474f4f,0x70635f45,0x74735f70,0x5f656c79,
0x656e696c,0x7269645f,0x69746365,0x00006576,
0x00080004,0x475f4c47,0x4c474f4f,0x6e695f45,
0x64756c63,0x69645f65,0x74636572,0x00657669,
0x00040005,0x00000004,0x6e69616d,0x00000000,
0x00040005,0x00000009,0x6f635f66,0x00726f6c,
0x00040005,0x0000000d,0x65745f75,0x00000078,
0x00040005,0x00000011,0x76755f76,0x00000000,
0x00040005,0x00000015,0x6f635f76,0x00726f6c,
0x00040047,0x00000009,0x0000001e,0x00000000,
0x00040047,0x0000000d,0x00000022,0x00000000,
0x00040047,0x0000000d,0x00000021,0x00000000,
0x00040047,0x00000011,0x0000001e,0x00000000,
0x00040047,0x00000015,0x0000001e,0x00000001,
0x00020013,0x00000002,0x00030021,0x00000003,
0x00000002,0x00030016,0x00000006,0x00000020,
0x00040017,0x00000007,0x00000006,0x00000004,
0x00040020,0x00000008,0x00000003,0x00000007,
0x0004003b,0x00000008,0x00000009,0x00000003,
0x00090019,0x0000000a,0x00000006,0x00000001,
0x00000000,0x00000000,0x00000000,0x00000001,
0x00000000,0x0003001b,0x0000000b,0x0000000a,
0x00040020,0x0000000c,0x00000000,0x0000000b,
0x0004003b,0x0000000c,0x0000000d,0x00000000,
0x00040017,0x0000000f,0x00000006,0x00000002,
0x00040020,0x00000010,0x00000001,0x0000000f,
0x0004003b,0x00000010,0x00000011,0x00000001,
0x00040020,0x00000014,0x00000001,0x00000007,
0x0004003b,0x00000014,0x00000015,0x00000001,
0x00050036,0x00000002,0x00000004,0x00000000,
0x00000003,0x000200f8,0x00000005,0x0004003d,
0x0000000b,0x0000000e,0x0000000d,0x0004003d,
0x0000000f,0x00000012,0x00000011,0x00050057,
0x00000007,0x00000013,0x0000000e,0x00000012,
0x0004003d,0x00000007,0x00000016,0x00000015,
0x00050085,0x00000007,0x00000017,0x00000013,
0x00000016,0x0003003e,0x00000009,0x00000017,
0x000100fd,0x00010038
});
// glslc -mfmt=num graphics/src/backend/vk/shaders/gradient_vert.glsl -o -
pub const gradient_vert_spv = std.mem.toBytes([_]u32{
0x07230203,0x00010000,0x000d000a,0x0000001d,
0x00000000,0x00020011,0x00000001,0x0006000b,
0x00000001,0x4c534c47,0x6474732e,0x3035342e,
0x00000000,0x0003000e,0x00000000,0x00000001,
0x0007000f,0x00000000,0x00000004,0x6e69616d,
0x00000000,0x0000000d,0x00000011,0x00030003,
0x00000002,0x000001c2,0x000a0004,0x475f4c47,
0x4c474f4f,0x70635f45,0x74735f70,0x5f656c79,
0x656e696c,0x7269645f,0x69746365,0x00006576,
0x00080004,0x475f4c47,0x4c474f4f,0x6e695f45,
0x64756c63,0x69645f65,0x74636572,0x00657669,
0x00040005,0x00000004,0x6e69616d,0x00000000,
0x00060005,0x0000000b,0x505f6c67,0x65567265,
0x78657472,0x00000000,0x00060006,0x0000000b,
0x00000000,0x505f6c67,0x7469736f,0x006e6f69,
0x00070006,0x0000000b,0x00000001,0x505f6c67,
0x746e696f,0x657a6953,0x00000000,0x00070006,
0x0000000b,0x00000002,0x435f6c67,0x4470696c,
0x61747369,0x0065636e,0x00070006,0x0000000b,
0x00000003,0x435f6c67,0x446c6c75,0x61747369,
0x0065636e,0x00030005,0x0000000d,0x00000000,
0x00040005,0x00000011,0x6f705f61,0x00000073,
0x00060005,0x00000014,0x74726556,0x736e6f43,
0x746e6174,0x00000073,0x00040006,0x00000014,
0x00000000,0x0070766d,0x00040005,0x00000016,
0x6f635f75,0x0074736e,0x00050048,0x0000000b,
0x00000000,0x0000000b,0x00000000,0x00050048,
0x0000000b,0x00000001,0x0000000b,0x00000001,
0x00050048,0x0000000b,0x00000002,0x0000000b,
0x00000003,0x00050048,0x0000000b,0x00000003,
0x0000000b,0x00000004,0x00030047,0x0000000b,
0x00000002,0x00040047,0x00000011,0x0000001e,
0x00000000,0x00040048,0x00000014,0x00000000,
0x00000005,0x00050048,0x00000014,0x00000000,
0x00000023,0x00000000,0x00050048,0x00000014,
0x00000000,0x00000007,0x00000010,0x00030047,
0x00000014,0x00000002,0x00020013,0x00000002,
0x00030021,0x00000003,0x00000002,0x00030016,
0x00000006,0x00000020,0x00040017,0x00000007,
0x00000006,0x00000004,0x00040015,0x00000008,
0x00000020,0x00000000,0x0004002b,0x00000008,
0x00000009,0x00000001,0x0004001c,0x0000000a,
0x00000006,0x00000009,0x0006001e,0x0000000b,
0x00000007,0x00000006,0x0000000a,0x0000000a,
0x00040020,0x0000000c,0x00000003,0x0000000b,
0x0004003b,0x0000000c,0x0000000d,0x00000003,
0x00040015,0x0000000e,0x00000020,0x00000001,
0x0004002b,0x0000000e,0x0000000f,0x00000000,
0x00040020,0x00000010,0x00000001,0x00000007,
0x0004003b,0x00000010,0x00000011,0x00000001,
0x00040018,0x00000013,0x00000007,0x00000004,
0x0003001e,0x00000014,0x00000013,0x00040020,
0x00000015,0x00000009,0x00000014,0x0004003b,
0x00000015,0x00000016,0x00000009,0x00040020,
0x00000017,0x00000009,0x00000013,0x00040020,
0x0000001b,0x00000003,0x00000007,0x00050036,
0x00000002,0x00000004,0x00000000,0x00000003,
0x000200f8,0x00000005,0x0004003d,0x00000007,
0x00000012,0x00000011,0x00050041,0x00000017,
0x00000018,0x00000016,0x0000000f,0x0004003d,
0x00000013,0x00000019,0x00000018,0x00050090,
0x00000007,0x0000001a,0x00000012,0x00000019,
0x00050041,0x0000001b,0x0000001c,0x0000000d,
0x0000000f,0x0003003e,0x0000001c,0x0000001a,
0x000100fd,0x00010038
});
// glslc -mfmt=num graphics/src/backend/vk/shaders/gradient_frag.glsl -o -
pub const gradient_frag_spv = std.mem.toBytes([_]u32{
0x07230203,0x00010000,0x000d000a,0x00000033,
0x00000000,0x00020011,0x00000001,0x0006000b,
0x00000001,0x4c534c47,0x6474732e,0x3035342e,
0x00000000,0x0003000e,0x00000000,0x00000001,
0x0007000f,0x00000004,0x00000004,0x6e69616d,
0x00000000,0x0000001c,0x00000026,0x00030010,
0x00000004,0x00000007,0x00030003,0x00000002,
0x000001c2,0x000a0004,0x475f4c47,0x4c474f4f,
0x70635f45,0x74735f70,0x5f656c79,0x656e696c,
0x7269645f,0x69746365,0x00006576,0x00080004,
0x475f4c47,0x4c474f4f,0x6e695f45,0x64756c63,
0x69645f65,0x74636572,0x00657669,0x00040005,
0x00000004,0x6e69616d,0x00000000,0x00050005,
0x00000009,0x64617267,0x6365765f,0x00000000,
0x00060005,0x0000000b,0x67617246,0x736e6f43,
0x746e6174,0x00000073,0x00060006,0x0000000b,
0x00000000,0x72617473,0x6f635f74,0x00726f6c,
0x00060006,0x0000000b,0x00000001,0x5f646e65,
0x6f6c6f63,0x00000072,0x00060006,0x0000000b,
0x00000002,0x72617473,0x6f705f74,0x00000073,
0x00050006,0x0000000b,0x00000003,0x5f646e65,
0x00736f70,0x00040005,0x0000000d,0x6f635f75,
0x0074736e,0x00030005,0x00000018,0x006e656c,
0x00040005,0x0000001c,0x6f635f66,0x00726f6c,
0x00060005,0x00000026,0x465f6c67,0x43676172,
0x64726f6f,0x00000000,0x00050048,0x0000000b,
0x00000000,0x00000023,0x00000040,0x00050048,
0x0000000b,0x00000001,0x00000023,0x00000050,
0x00050048,0x0000000b,0x00000002,0x00000023,
0x00000060,0x00050048,0x0000000b,0x00000003,
0x00000023,0x00000068,0x00030047,0x0000000b,
0x00000002,0x00040047,0x0000001c,0x0000001e,
0x00000000,0x00040047,0x00000026,0x0000000b,
0x0000000f,0x00020013,0x00000002,0x00030021,
0x00000003,0x00000002,0x00030016,0x00000006,
0x00000020,0x00040017,0x00000007,0x00000006,
0x00000002,0x00040020,0x00000008,0x00000007,
0x00000007,0x00040017,0x0000000a,0x00000006,
0x00000004,0x0006001e,0x0000000b,0x0000000a,
0x0000000a,0x00000007,0x00000007,0x00040020,
0x0000000c,0x00000009,0x0000000b,0x0004003b,
0x0000000c,0x0000000d,0x00000009,0x00040015,
0x0000000e,0x00000020,0x00000001,0x0004002b,
0x0000000e,0x0000000f,0x00000003,0x00040020,
0x00000010,0x00000009,0x00000007,0x0004002b,
0x0000000e,0x00000013,0x00000002,0x00040020,
0x00000017,0x00000007,0x00000006,0x00040020,
0x0000001b,0x00000003,0x0000000a,0x0004003b,
0x0000001b,0x0000001c,0x00000003,0x0004002b,
0x0000000e,0x0000001d,0x00000000,0x00040020,
0x0000001e,0x00000009,0x0000000a,0x0004002b,
0x0000000e,0x00000021,0x00000001,0x00040020,
0x00000025,0x00000001,0x0000000a,0x0004003b,
0x00000025,0x00000026,0x00000001,0x00050036,
0x00000002,0x00000004,0x00000000,0x00000003,
0x000200f8,0x00000005,0x0004003b,0x00000008,
0x00000009,0x00000007,0x0004003b,0x00000017,
0x00000018,0x00000007,0x00050041,0x00000010,
0x00000011,0x0000000d,0x0000000f,0x0004003d,
0x00000007,0x00000012,0x00000011,0x00050041,
0x00000010,0x00000014,0x0000000d,0x00000013,
0x0004003d,0x00000007,0x00000015,0x00000014,
0x00050083,0x00000007,0x00000016,0x00000012,
0x00000015,0x0003003e,0x00000009,0x00000016,
0x0004003d,0x00000007,0x00000019,0x00000009,
0x0006000c,0x00000006,0x0000001a,0x00000001,
0x00000042,0x00000019,0x0003003e,0x00000018,
0x0000001a,0x00050041,0x0000001e,0x0000001f,
0x0000000d,0x0000001d,0x0004003d,0x0000000a,
0x00000020,0x0000001f,0x00050041,0x0000001e,
0x00000022,0x0000000d,0x00000021,0x0004003d,
0x0000000a,0x00000023,0x00000022,0x0004003d,
0x00000007,0x00000024,0x00000009,0x0004003d,
0x0000000a,0x00000027,0x00000026,0x0007004f,
0x00000007,0x00000028,0x00000027,0x00000027,
0x00000000,0x00000001,0x00050041,0x00000010,
0x00000029,0x0000000d,0x00000013,0x0004003d,
0x00000007,0x0000002a,0x00000029,0x00050083,
0x00000007,0x0000002b,0x00000028,0x0000002a,
0x00050094,0x00000006,0x0000002c,0x00000024,
0x0000002b,0x0004003d,0x00000006,0x0000002d,
0x00000018,0x0004003d,0x00000006,0x0000002e,
0x00000018,0x00050085,0x00000006,0x0000002f,
0x0000002d,0x0000002e,0x00050088,0x00000006,
0x00000030,0x0000002c,0x0000002f,0x00070050,
0x0000000a,0x00000031,0x00000030,0x00000030,
0x00000030,0x00000030,0x0008000c,0x0000000a,
0x00000032,0x00000001,0x0000002e,0x00000020,
0x00000023,0x00000031,0x0003003e,0x0000001c,
0x00000032,0x000100fd,0x00010038
});
// glslc -mfmt=num graphics/src/backend/vk/shaders/plane_vert.glsl -o -
pub const plane_vert_spv = std.mem.toBytes([_]u32{
0x07230203,0x00010000,0x000d000a,0x0000006c,
0x00000000,0x00020011,0x00000001,0x0006000b,
0x00000001,0x4c534c47,0x6474732e,0x3035342e,
0x00000000,0x0003000e,0x00000000,0x00000001,
0x000a000f,0x00000000,0x00000004,0x6e69616d,
0x00000000,0x00000037,0x0000003d,0x00000050,
0x0000005e,0x00000064,0x00030003,0x00000002,
0x000001c2,0x000a0004,0x475f4c47,0x4c474f4f,
0x70635f45,0x74735f70,0x5f656c79,0x656e696c,
0x7269645f,0x69746365,0x00006576,0x00080004,
0x475f4c47,0x4c474f4f,0x6e695f45,0x64756c63,
0x69645f65,0x74636572,0x00657669,0x00040005,
0x00000004,0x6e69616d,0x00000000,0x000a0005,
0x00000011,0x72706e55,0x63656a6f,0x696f5074,
0x6628746e,0x31663b31,0x3b31663b,0x3434666d,
0x0000003b,0x00030005,0x0000000d,0x00000078,
0x00030005,0x0000000e,0x00000079,0x00030005,
0x0000000f,0x0000007a,0x00030005,0x00000010,
0x0070766d,0x00050005,0x00000017,0x64697267,
0x6e616c50,0x00000065,0x00040005,0x0000001f,
0x5f70766d,0x00766e69,0x00070005,0x00000023,
0x72706e75,0x63656a6f,0x50646574,0x746e696f,
0x00000000,0x00030005,0x00000034,0x00000070,
0x00060005,0x00000037,0x565f6c67,0x65747265,
0x646e4978,0x00007865,0x00050005,0x0000003d,
0x7261656e,0x6e696f50,0x00000074,0x00060005,
0x0000003e,0x74726556,0x736e6f43,0x746e6174,
0x00000073,0x00040006,0x0000003e,0x00000000,
0x0070766d,0x00040005,0x00000040,0x6f635f75,
0x0074736e,0x00040005,0x00000042,0x61726170,
0x0000006d,0x00040005,0x00000046,0x61726170,
0x0000006d,0x00040005,0x0000004a,0x61726170,
0x0000006d,0x00040005,0x0000004b,0x61726170,
0x0000006d,0x00050005,0x00000050,0x50726166,
0x746e696f,0x00000000,0x00040005,0x00000052,
0x61726170,0x0000006d,0x00040005,0x00000055,
0x61726170,0x0000006d,0x00040005,0x00000058,
0x61726170,0x0000006d,0x00040005,0x00000059,
0x61726170,0x0000006d,0x00030005,0x0000005e,
0x0070766d,0x00060005,0x00000062,0x505f6c67,
0x65567265,0x78657472,0x00000000,0x00060006,
0x00000062,0x00000000,0x505f6c67,0x7469736f,
0x006e6f69,0x00070006,0x00000062,0x00000001,
0x505f6c67,0x746e696f,0x657a6953,0x00000000,
0x00070006,0x00000062,0x00000002,0x435f6c67,
0x4470696c,0x61747369,0x0065636e,0x00070006,
0x00000062,0x00000003,0x435f6c67,0x446c6c75,
0x61747369,0x0065636e,0x00030005,0x00000064,
0x00000000,0x00040047,0x00000037,0x0000000b,
0x0000002a,0x00040047,0x0000003d,0x0000001e,
0x00000000,0x00040048,0x0000003e,0x00000000,
0x00000005,0x00050048,0x0000003e,0x00000000,
0x00000023,0x00000000,0x00050048,0x0000003e,
0x00000000,0x00000007,0x00000010,0x00030047,
0x0000003e,0x00000002,0x00040047,0x00000050,
0x0000001e,0x00000001,0x00040047,0x0000005e,
0x0000001e,0x00000002,0x00050048,0x00000062,
0x00000000,0x0000000b,0x00000000,0x00050048,
0x00000062,0x00000001,0x0000000b,0x00000001,
0x00050048,0x00000062,0x00000002,0x0000000b,
0x00000003,0x00050048,0x00000062,0x00000003,
0x0000000b,0x00000004,0x00030047,0x00000062,
0x00000002,0x00020013,0x00000002,0x00030021,
0x00000003,0x00000002,0x00030016,0x00000006,
0x00000020,0x00040020,0x00000007,0x00000007,
0x00000006,0x00040017,0x00000008,0x00000006,
0x00000004,0x00040018,0x00000009,0x00000008,
0x00000004,0x00040020,0x0000000a,0x00000007,
0x00000009,0x00040017,0x0000000b,0x00000006,
0x00000003,0x00070021,0x0000000c,0x0000000b,
0x00000007,0x00000007,0x00000007,0x0000000a,
0x00040015,0x00000013,0x00000020,0x00000000,
0x0004002b,0x00000013,0x00000014,0x00000006,
0x0004001c,0x00000015,0x0000000b,0x00000014,
0x00040020,0x00000016,0x00000006,0x00000015,
0x0004003b,0x00000016,0x00000017,0x00000006,
0x0004002b,0x00000006,0x00000018,0x3f800000,
0x0006002c,0x0000000b,0x00000019,0x00000018,
0x00000018,0x00000018,0x0004002b,0x00000006,
0x0000001a,0xbf800000,0x0006002c,0x0000000b,
0x0000001b,0x0000001a,0x0000001a,0x00000018,
0x0006002c,0x0000000b,0x0000001c,0x0000001a,
0x00000018,0x00000018,0x0006002c,0x0000000b,
0x0000001d,0x00000018,0x0000001a,0x00000018,
0x0009002c,0x00000015,0x0000001e,0x00000019,
0x0000001b,0x0000001c,0x0000001b,0x00000019,
0x0000001d,0x00040020,0x00000022,0x00000007,
0x00000008,0x0004002b,0x00000013,0x0000002c,
0x00000003,0x00040020,0x00000033,0x00000007,
0x0000000b,0x00040015,0x00000035,0x00000020,
0x00000001,0x00040020,0x00000036,0x00000001,
0x00000035,0x0004003b,0x00000036,0x00000037,
0x00000001,0x00040020,0x00000039,0x00000006,
0x0000000b,0x00040020,0x0000003c,0x00000003,
0x0000000b,0x0004003b,0x0000003c,0x0000003d,
0x00000003,0x0003001e,0x0000003e,0x00000009,
0x00040020,0x0000003f,0x00000009,0x0000003e,
0x0004003b,0x0000003f,0x00000040,0x00000009,
0x0004002b,0x00000035,0x00000041,0x00000000,
0x0004002b,0x00000013,0x00000043,0x00000000,
0x0004002b,0x00000013,0x00000047,0x00000001,
0x00040020,0x0000004c,0x00000009,0x00000009,
0x0004003b,0x0000003c,0x00000050,0x00000003,
0x0004002b,0x00000006,0x00000051,0x00000000,
0x00040020,0x0000005d,0x00000003,0x00000009,
0x0004003b,0x0000005d,0x0000005e,0x00000003,
0x0004001c,0x00000061,0x00000006,0x00000047,
0x0006001e,0x00000062,0x00000008,0x00000006,
0x00000061,0x00000061,0x00040020,0x00000063,
0x00000003,0x00000062,0x0004003b,0x00000063,
0x00000064,0x00000003,0x00040020,0x0000006a,
0x00000003,0x00000008,0x00050036,0x00000002,
0x00000004,0x00000000,0x00000003,0x000200f8,
0x00000005,0x0004003b,0x00000033,0x00000034,
0x00000007,0x0004003b,0x00000007,0x00000042,
0x00000007,0x0004003b,0x00000007,0x00000046,
0x00000007,0x0004003b,0x00000007,0x0000004a,
0x00000007,0x0004003b,0x0000000a,0x0000004b,
0x00000007,0x0004003b,0x00000007,0x00000052,
0x00000007,0x0004003b,0x00000007,0x00000055,
0x00000007,0x0004003b,0x00000007,0x00000058,
0x00000007,0x0004003b,0x0000000a,0x00000059,
0x00000007,0x0003003e,0x00000017,0x0000001e,
0x0004003d,0x00000035,0x00000038,0x00000037,
0x00050041,0x00000039,0x0000003a,0x00000017,
0x00000038,0x0004003d,0x0000000b,0x0000003b,
0x0000003a,0x0003003e,0x00000034,0x0000003b,
0x00050041,0x00000007,0x00000044,0x00000034,
0x00000043,0x0004003d,0x00000006,0x00000045,
0x00000044,0x0003003e,0x00000042,0x00000045,
0x00050041,0x00000007,0x00000048,0x00000034,
0x00000047,0x0004003d,0x00000006,0x00000049,
0x00000048,0x0003003e,0x00000046,0x00000049,
0x0003003e,0x0000004a,0x00000018,0x00050041,
0x0000004c,0x0000004d,0x00000040,0x00000041,
0x0004003d,0x00000009,0x0000004e,0x0000004d,
0x0003003e,0x0000004b,0x0000004e,0x00080039,
0x0000000b,0x0000004f,0x00000011,0x00000042,
0x00000046,0x0000004a,0x0000004b,0x0003003e,
0x0000003d,0x0000004f,0x00050041,0x00000007,
0x00000053,0x00000034,0x00000043,0x0004003d,
0x00000006,0x00000054,0x00000053,0x0003003e,
0x00000052,0x00000054,0x00050041,0x00000007,
0x00000056,0x00000034,0x00000047,0x0004003d,
0x00000006,0x00000057,0x00000056,0x0003003e,
0x00000055,0x00000057,0x0003003e,0x00000058,
0x00000051,0x00050041,0x0000004c,0x0000005a,
0x00000040,0x00000041,0x0004003d,0x00000009,
0x0000005b,0x0000005a,0x0003003e,0x00000059,
0x0000005b,0x00080039,0x0000000b,0x0000005c,
0x00000011,0x00000052,0x00000055,0x00000058,
0x00000059,0x0003003e,0x00000050,0x0000005c,
0x00050041,0x0000004c,0x0000005f,0x00000040,
0x00000041,0x0004003d,0x00000009,0x00000060,
0x0000005f,0x0003003e,0x0000005e,0x00000060,
0x0004003d,0x0000000b,0x00000065,0x00000034,
0x00050051,0x00000006,0x00000066,0x00000065,
0x00000000,0x00050051,0x00000006,0x00000067,
0x00000065,0x00000001,0x00050051,0x00000006,
0x00000068,0x00000065,0x00000002,0x00070050,
0x00000008,0x00000069,0x00000066,0x00000067,
0x00000068,0x00000018,0x00050041,0x0000006a,
0x0000006b,0x00000064,0x00000041,0x0003003e,
0x0000006b,0x00000069,0x000100fd,0x00010038,
0x00050036,0x0000000b,0x00000011,0x00000000,
0x0000000c,0x00030037,0x00000007,0x0000000d,
0x00030037,0x00000007,0x0000000e,0x00030037,
0x00000007,0x0000000f,0x00030037,0x0000000a,
0x00000010,0x000200f8,0x00000012,0x0004003b,
0x0000000a,0x0000001f,0x00000007,0x0004003b,
0x00000022,0x00000023,0x00000007,0x0004003d,
0x00000009,0x00000020,0x00000010,0x0006000c,
0x00000009,0x00000021,0x00000001,0x00000022,
0x00000020,0x0003003e,0x0000001f,0x00000021,
0x0004003d,0x00000006,0x00000024,0x0000000d,
0x0004003d,0x00000006,0x00000025,0x0000000e,
0x0004003d,0x00000006,0x00000026,0x0000000f,
0x00070050,0x00000008,0x00000027,0x00000024,
0x00000025,0x00000026,0x00000018,0x0004003d,
0x00000009,0x00000028,0x0000001f,0x00050090,
0x00000008,0x00000029,0x00000027,0x00000028,
0x0003003e,0x00000023,0x00000029,0x0004003d,
0x00000008,0x0000002a,0x00000023,0x0008004f,
0x0000000b,0x0000002b,0x0000002a,0x0000002a,
0x00000000,0x00000001,0x00000002,0x00050041,
0x00000007,0x0000002d,0x00000023,0x0000002c,
0x0004003d,0x00000006,0x0000002e,0x0000002d,
0x00060050,0x0000000b,0x0000002f,0x0000002e,
0x0000002e,0x0000002e,0x00050088,0x0000000b,
0x00000030,0x0000002b,0x0000002f,0x000200fe,
0x00000030,0x00010038
});
// glslc -mfmt=num graphics/src/backend/vk/shaders/plane_frag.glsl -o -
pub const plane_frag_spv = std.mem.toBytes([_]u32{
0x07230203,0x00010000,0x000d000a,0x0000009a,
0x00000000,0x00020011,0x00000001,0x0006000b,
0x00000001,0x4c534c47,0x6474732e,0x3035342e,
0x00000000,0x0003000e,0x00000000,0x00000001,
0x000a000f,0x00000004,0x00000004,0x6e69616d,
0x00000000,0x00000069,0x0000006e,0x00000085,
0x00000089,0x00000090,0x00030010,0x00000004,
0x00000007,0x00030010,0x00000004,0x0000000c,
0x00030003,0x00000002,0x000001c2,0x000a0004,
0x475f4c47,0x4c474f4f,0x70635f45,0x74735f70,
0x5f656c79,0x656e696c,0x7269645f,0x69746365,
0x00006576,0x00080004,0x475f4c47,0x4c474f4f,
0x6e695f45,0x64756c63,0x69645f65,0x74636572,
0x00657669,0x00040005,0x00000004,0x6e69616d,
0x00000000,0x00060005,0x0000000e,0x64697267,
0x33667628,0x3b31663b,0x00000000,0x00050005,
0x0000000c,0x67617266,0x33736f50,0x00000044,
0x00050005,0x0000000d,0x6c6c6563,0x7a69735f,
0x00000065,0x00050005,0x00000010,0x666c6168,
0x6469775f,0x00006874,0x00030005,0x00000014,
0x00006464,0x00060005,0x0000001a,0x656e696c,
0x6c61665f,0x66666f6c,0x00000000,0x00040005,
0x00000029,0x656e696c,0x00000000,0x00040005,
0x00000033,0x6f6c6f63,0x00000072,0x00030005,
0x00000038,0x00326464,0x00030005,0x00000067,
0x00000074,0x00050005,0x00000069,0x7261656e,
0x6e696f50,0x00000074,0x00050005,0x0000006e,
0x50726166,0x746e696f,0x00000000,0x00050005,
0x00000075,0x67617266,0x33736f50,0x00000044,
0x00060005,0x0000007d,0x70696c63,0x6170735f,
0x705f6563,0x0000736f,0x00030005,0x00000085,
0x0070766d,0x00060005,0x00000089,0x465f6c67,
0x44676172,0x68747065,0x00000000,0x00050005,
0x00000090,0x4374756f,0x726f6c6f,0x00000000,
0x00040005,0x00000091,0x61726170,0x0000006d,
0x00040005,0x00000093,0x61726170,0x0000006d,
0x00040047,0x00000069,0x0000001e,0x00000000,
0x00040047,0x0000006e,0x0000001e,0x00000001,
0x00040047,0x00000085,0x0000001e,0x00000002,
0x00040047,0x00000089,0x0000000b,0x00000016,
0x00040047,0x00000090,0x0000001e,0x00000000,
0x00020013,0x00000002,0x00030021,0x00000003,
0x00000002,0x00030016,0x00000006,0x00000020,
0x00040017,0x00000007,0x00000006,0x00000003,
0x00040020,0x00000008,0x00000007,0x00000007,
0x00040020,0x00000009,0x00000007,0x00000006,
0x00040017,0x0000000a,0x00000006,0x00000004,
0x00050021,0x0000000b,0x0000000a,0x00000008,
0x00000009,0x0004002b,0x00000006,0x00000011,
0x3f800000,0x00040017,0x00000012,0x00000006,
0x00000002,0x00040020,0x00000013,0x00000007,
0x00000012,0x00040015,0x0000002a,0x00000020,
0x00000000,0x0004002b,0x0000002a,0x0000002b,
0x00000000,0x0004002b,0x0000002a,0x0000002e,
0x00000001,0x00040020,0x00000032,0x00000007,
0x0000000a,0x0004002b,0x00000006,0x00000034,
0x3e4ccccd,0x0004002b,0x00000006,0x0000003a,
0x41200000,0x00020014,0x0000003d,0x0004002b,
0x0000002a,0x0000003e,0x00000002,0x0004002b,
0x0000002a,0x00000050,0x00000003,0x00040020,
0x00000068,0x00000001,0x00000007,0x0004003b,
0x00000068,0x00000069,0x00000001,0x00040020,
0x0000006a,0x00000001,0x00000006,0x0004003b,
0x00000068,0x0000006e,0x00000001,0x00040018,
0x00000083,0x0000000a,0x00000004,0x00040020,
0x00000084,0x00000001,0x00000083,0x0004003b,
0x00000084,0x00000085,0x00000001,0x00040020,
0x00000088,0x00000003,0x00000006,0x0004003b,
0x00000088,0x00000089,0x00000003,0x00040020,
0x0000008f,0x00000003,0x0000000a,0x0004003b,
0x0000008f,0x00000090,0x00000003,0x0004002b,
0x00000006,0x00000096,0x00000000,0x00050036,
0x00000002,0x00000004,0x00000000,0x00000003,
0x000200f8,0x00000005,0x0004003b,0x00000009,
0x00000067,0x00000007,0x0004003b,0x00000008,
0x00000075,0x00000007,0x0004003b,0x00000032,
0x0000007d,0x00000007,0x0004003b,0x00000008,
0x00000091,0x00000007,0x0004003b,0x00000009,
0x00000093,0x00000007,0x00050041,0x0000006a,
0x0000006b,0x00000069,0x0000002e,0x0004003d,
0x00000006,0x0000006c,0x0000006b,0x0004007f,
0x00000006,0x0000006d,0x0000006c,0x00050041,
0x0000006a,0x0000006f,0x0000006e,0x0000002e,
0x0004003d,0x00000006,0x00000070,0x0000006f,
0x00050041,0x0000006a,0x00000071,0x00000069,
0x0000002e,0x0004003d,0x00000006,0x00000072,
0x00000071,0x00050083,0x00000006,0x00000073,
0x00000070,0x00000072,0x00050088,0x00000006,
0x00000074,0x0000006d,0x00000073,0x0003003e,
0x00000067,0x00000074,0x0004003d,0x00000007,
0x00000076,0x00000069,0x0004003d,0x00000006,
0x00000077,0x00000067,0x0004003d,0x00000007,
0x00000078,0x0000006e,0x0004003d,0x00000007,
0x00000079,0x00000069,0x00050083,0x00000007,
0x0000007a,0x00000078,0x00000079,0x0005008e,
0x00000007,0x0000007b,0x0000007a,0x00000077,
0x00050081,0x00000007,0x0000007c,0x00000076,
0x0000007b,0x0003003e,0x00000075,0x0000007c,
0x0004003d,0x00000007,0x0000007e,0x00000075,
0x00050051,0x00000006,0x0000007f,0x0000007e,
0x00000000,0x00050051,0x00000006,0x00000080,
0x0000007e,0x00000001,0x00050051,0x00000006,
0x00000081,0x0000007e,0x00000002,0x00070050,
0x0000000a,0x00000082,0x0000007f,0x00000080,
0x00000081,0x00000011,0x0004003d,0x00000083,
0x00000086,0x00000085,0x00050090,0x0000000a,
0x00000087,0x00000082,0x00000086,0x0003003e,
0x0000007d,0x00000087,0x00050041,0x00000009,
0x0000008a,0x0000007d,0x0000003e,0x0004003d,
0x00000006,0x0000008b,0x0000008a,0x00050041,
0x00000009,0x0000008c,0x0000007d,0x00000050,
0x0004003d,0x00000006,0x0000008d,0x0000008c,
0x00050088,0x00000006,0x0000008e,0x0000008b,
0x0000008d,0x0003003e,0x00000089,0x0000008e,
0x0004003d,0x00000007,0x00000092,0x00000075,
0x0003003e,0x00000091,0x00000092,0x0003003e,
0x00000093,0x0000003a,0x00060039,0x0000000a,
0x00000094,0x0000000e,0x00000091,0x00000093,
0x0004003d,0x00000006,0x00000095,0x00000067,
0x000500ba,0x0000003d,0x00000097,0x00000095,
0x00000096,0x000600a9,0x00000006,0x00000098,
0x00000097,0x00000011,0x00000096,0x0005008e,
0x0000000a,0x00000099,0x00000094,0x00000098,
0x0003003e,0x00000090,0x00000099,0x000100fd,
0x00010038,0x00050036,0x0000000a,0x0000000e,
0x00000000,0x0000000b,0x00030037,0x00000008,
0x0000000c,0x00030037,0x00000009,0x0000000d,
0x000200f8,0x0000000f,0x0004003b,0x00000009,
0x00000010,0x00000007,0x0004003b,0x00000013,
0x00000014,0x00000007,0x0004003b,0x00000013,
0x0000001a,0x00000007,0x0004003b,0x00000009,
0x00000029,0x00000007,0x0004003b,0x00000032,
0x00000033,0x00000007,0x0004003b,0x00000013,
0x00000038,0x00000007,0x0003003e,0x00000010,
0x00000011,0x0004003d,0x00000007,0x00000015,
0x0000000c,0x0007004f,0x00000012,0x00000016,
0x00000015,0x00000015,0x00000000,0x00000002,
0x000400d1,0x00000012,0x00000017,0x00000016,
0x0004003d,0x00000006,0x00000018,0x00000010,
0x0005008e,0x00000012,0x00000019,0x00000017,
0x00000018,0x0003003e,0x00000014,0x00000019,
0x0004003d,0x00000007,0x0000001b,0x0000000c,
0x0007004f,0x00000012,0x0000001c,0x0000001b,
0x0000001b,0x00000000,0x00000002,0x0004003d,
0x00000012,0x0000001d,0x00000014,0x00050081,
0x00000012,0x0000001e,0x0000001c,0x0000001d,
0x0004003d,0x00000006,0x0000001f,0x0000000d,
0x00050050,0x00000012,0x00000020,0x0000001f,
0x0000001f,0x0005008d,0x00000012,0x00000021,
0x0000001e,0x00000020,0x0004003d,0x00000012,
0x00000022,0x00000014,0x00050083,0x00000012,
0x00000023,0x00000021,0x00000022,0x0006000c,
0x00000012,0x00000024,0x00000001,0x00000004,
0x00000023,0x0004003d,0x00000012,0x00000025,
0x00000014,0x00050088,0x00000012,0x00000026,
0x00000024,0x00000025,0x00050050,0x00000012,
0x00000027,0x00000011,0x00000011,0x0007000c,
0x00000012,0x00000028,0x00000001,0x00000025,
0x00000026,0x00000027,0x0003003e,0x0000001a,
0x00000028,0x00050041,0x00000009,0x0000002c,
0x0000001a,0x0000002b,0x0004003d,0x00000006,
0x0000002d,0x0000002c,0x00050041,0x00000009,
0x0000002f,0x0000001a,0x0000002e,0x0004003d,
0x00000006,0x00000030,0x0000002f,0x0007000c,
0x00000006,0x00000031,0x00000001,0x00000025,
0x0000002d,0x00000030,0x0003003e,0x00000029,
0x00000031,0x0004003d,0x00000006,0x00000035,
0x00000029,0x00050083,0x00000006,0x00000036,
0x00000011,0x00000035,0x00070050,0x0000000a,
0x00000037,0x00000034,0x00000034,0x00000034,
0x00000036,0x0003003e,0x00000033,0x00000037,
0x0004003d,0x00000012,0x00000039,0x00000014,
0x00050050,0x00000012,0x0000003b,0x0000003a,
0x0000003a,0x0007000c,0x00000012,0x0000003c,
0x00000001,0x00000025,0x00000039,0x0000003b,
0x0003003e,0x00000038,0x0000003c,0x00050041,
0x00000009,0x0000003f,0x0000000c,0x0000003e,
0x0004003d,0x00000006,0x00000040,0x0000003f,
0x00050041,0x00000009,0x00000041,0x00000038,
0x0000002e,0x0004003d,0x00000006,0x00000042,
0x00000041,0x0004007f,0x00000006,0x00000043,
0x00000042,0x000500be,0x0000003d,0x00000044,
0x00000040,0x00000043,0x000300f7,0x00000046,
0x00000000,0x000400fa,0x00000044,0x00000045,
0x00000046,0x000200f8,0x00000045,0x00050041,
0x00000009,0x00000047,0x0000000c,0x0000003e,
0x0004003d,0x00000006,0x00000048,0x00000047,
0x00050041,0x00000009,0x00000049,0x00000038,
0x0000002e,0x0004003d,0x00000006,0x0000004a,
0x00000049,0x000500bc,0x0000003d,0x0000004b,
0x00000048,0x0000004a,0x000200f9,0x00000046,
0x000200f8,0x00000046,0x000700f5,0x0000003d,
0x0000004c,0x00000044,0x0000000f,0x0000004b,
0x00000045,0x000300f7,0x0000004e,0x00000000,
0x000400fa,0x0000004c,0x0000004d,0x0000004e,
0x000200f8,0x0000004d,0x00050041,0x00000009,
0x0000004f,0x00000033,0x0000002b,0x0003003e,
0x0000004f,0x00000011,0x00050041,0x00000009,
0x00000051,0x00000033,0x00000050,0x0003003e,
0x00000051,0x00000011,0x000200f9,0x0000004e,
0x000200f8,0x0000004e,0x00050041,0x00000009,
0x00000052,0x0000000c,0x0000002b,0x0004003d,
0x00000006,0x00000053,0x00000052,0x00050041,
0x00000009,0x00000054,0x00000038,0x0000002b,
0x0004003d,0x00000006,0x00000055,0x00000054,
0x0004007f,0x00000006,0x00000056,0x00000055,
0x000500be,0x0000003d,0x00000057,0x00000053,
0x00000056,0x000300f7,0x00000059,0x00000000,
0x000400fa,0x00000057,0x00000058,0x00000059,
0x000200f8,0x00000058,0x00050041,0x00000009,
0x0000005a,0x0000000c,0x0000002b,0x0004003d,
0x00000006,0x0000005b,0x0000005a,0x00050041,
0x00000009,0x0000005c,0x00000038,0x0000002b,
0x0004003d,0x00000006,0x0000005d,0x0000005c,
0x000500bc,0x0000003d,0x0000005e,0x0000005b,
0x0000005d,0x000200f9,0x00000059,0x000200f8,
0x00000059,0x000700f5,0x0000003d,0x0000005f,
0x00000057,0x0000004e,0x0000005e,0x00000058,
0x000300f7,0x00000061,0x00000000,0x000400fa,
0x0000005f,0x00000060,0x00000061,0x000200f8,
0x00000060,0x00050041,0x00000009,0x00000062,
0x00000033,0x0000003e,0x0003003e,0x00000062,
0x00000011,0x00050041,0x00000009,0x00000063,
0x00000033,0x00000050,0x0003003e,0x00000063,
0x00000011,0x000200f9,0x00000061,0x000200f8,
0x00000061,0x0004003d,0x0000000a,0x00000064,
0x00000033,0x000200fe,0x00000064,0x00010038
}); | graphics/src/backend/vk/shaders/shaders.zig |
const std = @import("../std.zig");
const mem = std.mem;
const testing = std.testing;
// Apply sbox0 to each byte in w.
fn subw(w: u32) u32 {
return @as(u32, sbox0[w >> 24]) << 24 | @as(u32, sbox0[w >> 16 & 0xff]) << 16 | @as(u32, sbox0[w >> 8 & 0xff]) << 8 | @as(u32, sbox0[w & 0xff]);
}
fn rotw(w: u32) u32 {
return w << 8 | w >> 24;
}
// Encrypt one block from src into dst, using the expanded key xk.
fn encryptBlock(xk: []const u32, dst: []u8, src: []const u8) void {
var s0 = mem.readIntBig(u32, src[0..4]);
var s1 = mem.readIntBig(u32, src[4..8]);
var s2 = mem.readIntBig(u32, src[8..12]);
var s3 = mem.readIntBig(u32, src[12..16]);
// First round just XORs input with key.
s0 ^= xk[0];
s1 ^= xk[1];
s2 ^= xk[2];
s3 ^= xk[3];
// Middle rounds shuffle using tables.
// Number of rounds is set by length of expanded key.
var nr = xk.len / 4 - 2; // - 2: one above, one more below
var k: usize = 4;
var t0: u32 = undefined;
var t1: u32 = undefined;
var t2: u32 = undefined;
var t3: u32 = undefined;
var r: usize = 0;
while (r < nr) : (r += 1) {
t0 = xk[k + 0] ^ te0[@truncate(u8, s0 >> 24)] ^ te1[@truncate(u8, s1 >> 16)] ^ te2[@truncate(u8, s2 >> 8)] ^ te3[@truncate(u8, s3)];
t1 = xk[k + 1] ^ te0[@truncate(u8, s1 >> 24)] ^ te1[@truncate(u8, s2 >> 16)] ^ te2[@truncate(u8, s3 >> 8)] ^ te3[@truncate(u8, s0)];
t2 = xk[k + 2] ^ te0[@truncate(u8, s2 >> 24)] ^ te1[@truncate(u8, s3 >> 16)] ^ te2[@truncate(u8, s0 >> 8)] ^ te3[@truncate(u8, s1)];
t3 = xk[k + 3] ^ te0[@truncate(u8, s3 >> 24)] ^ te1[@truncate(u8, s0 >> 16)] ^ te2[@truncate(u8, s1 >> 8)] ^ te3[@truncate(u8, s2)];
k += 4;
s0 = t0;
s1 = t1;
s2 = t2;
s3 = t3;
}
// Last round uses s-box directly and XORs to produce output.
s0 = @as(u32, sbox0[t0 >> 24]) << 24 | @as(u32, sbox0[t1 >> 16 & 0xff]) << 16 | @as(u32, sbox0[t2 >> 8 & 0xff]) << 8 | @as(u32, sbox0[t3 & 0xff]);
s1 = @as(u32, sbox0[t1 >> 24]) << 24 | @as(u32, sbox0[t2 >> 16 & 0xff]) << 16 | @as(u32, sbox0[t3 >> 8 & 0xff]) << 8 | @as(u32, sbox0[t0 & 0xff]);
s2 = @as(u32, sbox0[t2 >> 24]) << 24 | @as(u32, sbox0[t3 >> 16 & 0xff]) << 16 | @as(u32, sbox0[t0 >> 8 & 0xff]) << 8 | @as(u32, sbox0[t1 & 0xff]);
s3 = @as(u32, sbox0[t3 >> 24]) << 24 | @as(u32, sbox0[t0 >> 16 & 0xff]) << 16 | @as(u32, sbox0[t1 >> 8 & 0xff]) << 8 | @as(u32, sbox0[t2 & 0xff]);
s0 ^= xk[k + 0];
s1 ^= xk[k + 1];
s2 ^= xk[k + 2];
s3 ^= xk[k + 3];
mem.writeIntBig(u32, dst[0..4], s0);
mem.writeIntBig(u32, dst[4..8], s1);
mem.writeIntBig(u32, dst[8..12], s2);
mem.writeIntBig(u32, dst[12..16], s3);
}
// Decrypt one block from src into dst, using the expanded key xk.
pub fn decryptBlock(xk: []const u32, dst: []u8, src: []const u8) void {
var s0 = mem.readIntBig(u32, src[0..4]);
var s1 = mem.readIntBig(u32, src[4..8]);
var s2 = mem.readIntBig(u32, src[8..12]);
var s3 = mem.readIntBig(u32, src[12..16]);
// First round just XORs input with key.
s0 ^= xk[0];
s1 ^= xk[1];
s2 ^= xk[2];
s3 ^= xk[3];
// Middle rounds shuffle using tables.
// Number of rounds is set by length of expanded key.
var nr = xk.len / 4 - 2; // - 2: one above, one more below
var k: usize = 4;
var t0: u32 = undefined;
var t1: u32 = undefined;
var t2: u32 = undefined;
var t3: u32 = undefined;
var r: usize = 0;
while (r < nr) : (r += 1) {
t0 = xk[k + 0] ^ td0[@truncate(u8, s0 >> 24)] ^ td1[@truncate(u8, s3 >> 16)] ^ td2[@truncate(u8, s2 >> 8)] ^ td3[@truncate(u8, s1)];
t1 = xk[k + 1] ^ td0[@truncate(u8, s1 >> 24)] ^ td1[@truncate(u8, s0 >> 16)] ^ td2[@truncate(u8, s3 >> 8)] ^ td3[@truncate(u8, s2)];
t2 = xk[k + 2] ^ td0[@truncate(u8, s2 >> 24)] ^ td1[@truncate(u8, s1 >> 16)] ^ td2[@truncate(u8, s0 >> 8)] ^ td3[@truncate(u8, s3)];
t3 = xk[k + 3] ^ td0[@truncate(u8, s3 >> 24)] ^ td1[@truncate(u8, s2 >> 16)] ^ td2[@truncate(u8, s1 >> 8)] ^ td3[@truncate(u8, s0)];
k += 4;
s0 = t0;
s1 = t1;
s2 = t2;
s3 = t3;
}
// Last round uses s-box directly and XORs to produce output.
s0 = @as(u32, sbox1[t0 >> 24]) << 24 | @as(u32, sbox1[t3 >> 16 & 0xff]) << 16 | @as(u32, sbox1[t2 >> 8 & 0xff]) << 8 | @as(u32, sbox1[t1 & 0xff]);
s1 = @as(u32, sbox1[t1 >> 24]) << 24 | @as(u32, sbox1[t0 >> 16 & 0xff]) << 16 | @as(u32, sbox1[t3 >> 8 & 0xff]) << 8 | @as(u32, sbox1[t2 & 0xff]);
s2 = @as(u32, sbox1[t2 >> 24]) << 24 | @as(u32, sbox1[t1 >> 16 & 0xff]) << 16 | @as(u32, sbox1[t0 >> 8 & 0xff]) << 8 | @as(u32, sbox1[t3 & 0xff]);
s3 = @as(u32, sbox1[t3 >> 24]) << 24 | @as(u32, sbox1[t2 >> 16 & 0xff]) << 16 | @as(u32, sbox1[t1 >> 8 & 0xff]) << 8 | @as(u32, sbox1[t0 & 0xff]);
s0 ^= xk[k + 0];
s1 ^= xk[k + 1];
s2 ^= xk[k + 2];
s3 ^= xk[k + 3];
mem.writeIntBig(u32, dst[0..4], s0);
mem.writeIntBig(u32, dst[4..8], s1);
mem.writeIntBig(u32, dst[8..12], s2);
mem.writeIntBig(u32, dst[12..16], s3);
}
fn xorBytes(dst: []u8, a: []const u8, b: []const u8) usize {
var n = std.math.min(dst.len, std.math.min(a.len, b.len));
for (dst[0..n]) |_, i| {
dst[i] = a[i] ^ b[i];
}
return n;
}
pub const AES128 = AES(128);
pub const AES256 = AES(256);
fn AES(comptime keysize: usize) type {
return struct {
const Self = @This();
const nn = (keysize / 8) + 28;
enc: [nn]u32,
dec: [nn]u32,
pub fn init(key: [keysize / 8]u8) Self {
var ctx: Self = undefined;
expandKey(&key, ctx.enc[0..], ctx.dec[0..]);
return ctx;
}
pub fn encrypt(ctx: Self, dst: []u8, src: []const u8) void {
encryptBlock(ctx.enc[0..], dst, src);
}
pub fn decrypt(ctx: Self, dst: []u8, src: []const u8) void {
decryptBlock(ctx.dec[0..], dst, src);
}
pub fn ctr(ctx: Self, dst: []u8, src: []const u8, iv: [16]u8) void {
std.debug.assert(dst.len >= src.len);
var keystream: [16]u8 = undefined;
var ctrbuf = iv;
var n: usize = 0;
while (n < src.len) {
ctx.encrypt(keystream[0..], ctrbuf[0..]);
var ctr_i = std.mem.readIntBig(u128, ctrbuf[0..]);
std.mem.writeIntBig(u128, ctrbuf[0..], ctr_i +% 1);
n += xorBytes(dst[n..], src[n..], &keystream);
}
}
};
}
test "ctr" {
// NIST SP 800-38A pp 55-58
{
const key = [_]u8{ 0x2b, 0x7e, 0x15, 0x16, 0x28, 0xae, 0xd2, 0xa6, 0xab, 0xf7, 0x15, 0x88, 0x09, 0xcf, 0x4f, 0x3c };
const iv = [_]u8{ 0xf0, 0xf1, 0xf2, 0xf3, 0xf4, 0xf5, 0xf6, 0xf7, 0xf8, 0xf9, 0xfa, 0xfb, 0xfc, 0xfd, 0xfe, 0xff };
const in = [_]u8{
0x6b, 0xc1, 0xbe, 0xe2, 0x2e, 0x40, 0x9f, 0x96, 0xe9, 0x3d, 0x7e, 0x11, 0x73, 0x93, 0x17, 0x2a,
0xae, 0x2d, 0x8a, 0x57, 0x1e, 0x03, 0xac, 0x9c, 0x9e, 0xb7, 0x6f, 0xac, 0x45, 0xaf, 0x8e, 0x51,
0x30, 0xc8, 0x1c, 0x46, 0xa3, 0x5c, 0xe4, 0x11, 0xe5, 0xfb, 0xc1, 0x19, 0x1a, 0x0a, 0x52, 0xef,
0xf6, 0x9f, 0x24, 0x45, 0xdf, 0x4f, 0x9b, 0x17, 0xad, 0x2b, 0x41, 0x7b, 0xe6, 0x6c, 0x37, 0x10,
};
const exp_out = [_]u8{
0x87, 0x4d, 0x61, 0x91, 0xb6, 0x20, 0xe3, 0x26, 0x1b, 0xef, 0x68, 0x64, 0x99, 0x0d, 0xb6, 0xce,
0x98, 0x06, 0xf6, 0x6b, 0x79, 0x70, 0xfd, 0xff, 0x86, 0x17, 0x18, 0x7b, 0xb9, 0xff, 0xfd, 0xff,
0x5a, 0xe4, 0xdf, 0x3e, 0xdb, 0xd5, 0xd3, 0x5e, 0x5b, 0x4f, 0x09, 0x02, 0x0d, 0xb0, 0x3e, 0xab,
0x1e, 0x03, 0x1d, 0xda, 0x2f, 0xbe, 0x03, 0xd1, 0x79, 0x21, 0x70, 0xa0, 0xf3, 0x00, 0x9c, 0xee,
};
var out: [exp_out.len]u8 = undefined;
var aes = AES128.init(key);
aes.ctr(out[0..], in[0..], iv);
testing.expectEqualSlices(u8, exp_out[0..], out[0..]);
}
}
test "encrypt" {
// Appendix B
{
const key = [_]u8{ 0x2b, 0x7e, 0x15, 0x16, 0x28, 0xae, 0xd2, 0xa6, 0xab, 0xf7, 0x15, 0x88, 0x09, 0xcf, 0x4f, 0x3c };
const in = [_]u8{ 0x32, 0x43, 0xf6, 0xa8, 0x88, 0x5a, 0x30, 0x8d, 0x31, 0x31, 0x98, 0xa2, 0xe0, 0x37, 0x07, 0x34 };
const exp_out = [_]u8{ 0x39, 0x25, 0x84, 0x1d, 0x02, 0xdc, 0x09, 0xfb, 0xdc, 0x11, 0x85, 0x97, 0x19, 0x6a, 0x0b, 0x32 };
var out: [exp_out.len]u8 = undefined;
var aes = AES128.init(key);
aes.encrypt(out[0..], in[0..]);
testing.expectEqualSlices(u8, exp_out[0..], out[0..]);
}
// Appendix C.3
{
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 in = [_]u8{ 0x00, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88, 0x99, 0xaa, 0xbb, 0xcc, 0xdd, 0xee, 0xff };
const exp_out = [_]u8{ 0x8e, 0xa2, 0xb7, 0xca, 0x51, 0x67, 0x45, 0xbf, 0xea, 0xfc, 0x49, 0x90, 0x4b, 0x49, 0x60, 0x89 };
var out: [exp_out.len]u8 = undefined;
var aes = AES256.init(key);
aes.encrypt(out[0..], in[0..]);
testing.expectEqualSlices(u8, exp_out[0..], out[0..]);
}
}
test "decrypt" {
// Appendix B
{
const key = [_]u8{ 0x2b, 0x7e, 0x15, 0x16, 0x28, 0xae, 0xd2, 0xa6, 0xab, 0xf7, 0x15, 0x88, 0x09, 0xcf, 0x4f, 0x3c };
const in = [_]u8{ 0x39, 0x25, 0x84, 0x1d, 0x02, 0xdc, 0x09, 0xfb, 0xdc, 0x11, 0x85, 0x97, 0x19, 0x6a, 0x0b, 0x32 };
const exp_out = [_]u8{ 0x32, 0x43, 0xf6, 0xa8, 0x88, 0x5a, 0x30, 0x8d, 0x31, 0x31, 0x98, 0xa2, 0xe0, 0x37, 0x07, 0x34 };
var out: [exp_out.len]u8 = undefined;
var aes = AES128.init(key);
aes.decrypt(out[0..], in[0..]);
testing.expectEqualSlices(u8, exp_out[0..], out[0..]);
}
// Appendix C.3
{
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 in = [_]u8{ 0x8e, 0xa2, 0xb7, 0xca, 0x51, 0x67, 0x45, 0xbf, 0xea, 0xfc, 0x49, 0x90, 0x4b, 0x49, 0x60, 0x89 };
const exp_out = [_]u8{ 0x00, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88, 0x99, 0xaa, 0xbb, 0xcc, 0xdd, 0xee, 0xff };
var out: [exp_out.len]u8 = undefined;
var aes = AES256.init(key);
aes.decrypt(out[0..], in[0..]);
testing.expectEqualSlices(u8, exp_out[0..], out[0..]);
}
}
// Key expansion algorithm. See FIPS-197, Figure 11.
fn expandKey(key: []const u8, enc: []u32, dec: []u32) void {
var i: usize = 0;
var nk = key.len / 4;
while (i < nk) : (i += 1) {
enc[i] = mem.readIntBig(u32, key[4 * i ..][0..4]);
}
while (i < enc.len) : (i += 1) {
var t = enc[i - 1];
if (i % nk == 0) {
t = subw(rotw(t)) ^ (@as(u32, powx[i / nk - 1]) << 24);
} else if (nk > 6 and i % nk == 4) {
t = subw(t);
}
enc[i] = enc[i - nk] ^ t;
}
var n = enc.len;
i = 0;
while (i < n) : (i += 4) {
var ei = n - i - 4;
var j: usize = 0;
while (j < 4) : (j += 1) {
var x = enc[ei + j];
if (i > 0 and i + 4 < n) {
x = td0[sbox0[x >> 24]] ^ td1[sbox0[x >> 16 & 0xff]] ^ td2[sbox0[x >> 8 & 0xff]] ^ td3[sbox0[x & 0xff]];
}
dec[i + j] = x;
}
}
}
test "expand key" {
const key = [_]u8{ 0x2b, 0x7e, 0x15, 0x16, 0x28, 0xae, 0xd2, 0xa6, 0xab, 0xf7, 0x15, 0x88, 0x09, 0xcf, 0x4f, 0x3c };
const exp_enc = [_]u32{
0x2b7e1516, 0x28aed2a6, 0xabf71588, 0x09cf4f3c,
0xa0fafe17, 0x88542cb1, 0x23a33939, 0x2a6c7605,
0xf2c295f2, 0x7a96b943, 0x5935807a, 0x7359f67f,
0x3d80477d, 0x4716fe3e, 0x1e237e44, 0x6d7a883b,
0xef44a541, 0xa8525b7f, 0xb671253b, 0xdb0bad00,
0xd4d1c6f8, 0x7c839d87, 0xcaf2b8bc, 0x11f915bc,
0x6d88a37a, 0x110b3efd, 0xdbf98641, 0xca0093fd,
0x4e54f70e, 0x5f5fc9f3, 0x84a64fb2, 0x4ea6dc4f,
0xead27321, 0xb58dbad2, 0x312bf560, 0x7f8d292f,
0xac7766f3, 0x19fadc21, 0x28d12941, 0x575c006e,
0xd014f9a8, 0xc9ee2589, 0xe13f0cc8, 0xb6630ca6,
};
const exp_dec = [_]u32{
0xd014f9a8, 0xc9ee2589, 0xe13f0cc8, 0xb6630ca6,
0xc7b5a63, 0x1319eafe, 0xb0398890, 0x664cfbb4,
0xdf7d925a, 0x1f62b09d, 0xa320626e, 0xd6757324,
0x12c07647, 0xc01f22c7, 0xbc42d2f3, 0x7555114a,
0x6efcd876, 0xd2df5480, 0x7c5df034, 0xc917c3b9,
0x6ea30afc, 0xbc238cf6, 0xae82a4b4, 0xb54a338d,
0x90884413, 0xd280860a, 0x12a12842, 0x1bc89739,
0x7c1f13f7, 0x4208c219, 0xc021ae48, 0x969bf7b,
0xcc7505eb, 0x3e17d1ee, 0x82296c51, 0xc9481133,
0x2b3708a7, 0xf262d405, 0xbc3ebdbf, 0x4b617d62,
0x2b7e1516, 0x28aed2a6, 0xabf71588, 0x9cf4f3c,
};
var enc: [exp_enc.len]u32 = undefined;
var dec: [exp_dec.len]u32 = undefined;
expandKey(key[0..], enc[0..], dec[0..]);
testing.expectEqualSlices(u32, exp_enc[0..], enc[0..]);
testing.expectEqualSlices(u32, exp_dec[0..], dec[0..]);
}
// constants
const poly = 1 << 8 | 1 << 4 | 1 << 3 | 1 << 1 | 1 << 0;
const powx = [16]u8{
0x01,
0x02,
0x04,
0x08,
0x10,
0x20,
0x40,
0x80,
0x1b,
0x36,
0x6c,
0xd8,
0xab,
0x4d,
0x9a,
0x2f,
};
const sbox0 = [256]u8{
0x63, 0x7c, 0x77, 0x7b, 0xf2, 0x6b, 0x6f, 0xc5, 0x30, 0x01, 0x67, 0x2b, 0xfe, 0xd7, 0xab, 0x76,
0xca, 0x82, 0xc9, 0x7d, 0xfa, 0x59, 0x47, 0xf0, 0xad, 0xd4, 0xa2, 0xaf, 0x9c, 0xa4, 0x72, 0xc0,
0xb7, 0xfd, 0x93, 0x26, 0x36, 0x3f, 0xf7, 0xcc, 0x34, 0xa5, 0xe5, 0xf1, 0x71, 0xd8, 0x31, 0x15,
0x04, 0xc7, 0x23, 0xc3, 0x18, 0x96, 0x05, 0x9a, 0x07, 0x12, 0x80, 0xe2, 0xeb, 0x27, 0xb2, 0x75,
0x09, 0x83, 0x2c, 0x1a, 0x1b, 0x6e, 0x5a, 0xa0, 0x52, 0x3b, 0xd6, 0xb3, 0x29, 0xe3, 0x2f, 0x84,
0x53, 0xd1, 0x00, 0xed, 0x20, 0xfc, 0xb1, 0x5b, 0x6a, 0xcb, 0xbe, 0x39, 0x4a, 0x4c, 0x58, 0xcf,
0xd0, 0xef, 0xaa, 0xfb, 0x43, 0x4d, 0x33, 0x85, 0x45, 0xf9, 0x02, 0x7f, 0x50, 0x3c, 0x9f, 0xa8,
0x51, 0xa3, 0x40, 0x8f, 0x92, 0x9d, 0x38, 0xf5, 0xbc, 0xb6, 0xda, 0x21, 0x10, 0xff, 0xf3, 0xd2,
0xcd, 0x0c, 0x13, 0xec, 0x5f, 0x97, 0x44, 0x17, 0xc4, 0xa7, 0x7e, 0x3d, 0x64, 0x5d, 0x19, 0x73,
0x60, 0x81, 0x4f, 0xdc, 0x22, 0x2a, 0x90, 0x88, 0x46, 0xee, 0xb8, 0x14, 0xde, 0x5e, 0x0b, 0xdb,
0xe0, 0x32, 0x3a, 0x0a, 0x49, 0x06, 0x24, 0x5c, 0xc2, 0xd3, 0xac, 0x62, 0x91, 0x95, 0xe4, 0x79,
0xe7, 0xc8, 0x37, 0x6d, 0x8d, 0xd5, 0x4e, 0xa9, 0x6c, 0x56, 0xf4, 0xea, 0x65, 0x7a, 0xae, 0x08,
0xba, 0x78, 0x25, 0x2e, 0x1c, 0xa6, 0xb4, 0xc6, 0xe8, 0xdd, 0x74, 0x1f, 0x4b, 0xbd, 0x8b, 0x8a,
0x70, 0x3e, 0xb5, 0x66, 0x48, 0x03, 0xf6, 0x0e, 0x61, 0x35, 0x57, 0xb9, 0x86, 0xc1, 0x1d, 0x9e,
0xe1, 0xf8, 0x98, 0x11, 0x69, 0xd9, 0x8e, 0x94, 0x9b, 0x1e, 0x87, 0xe9, 0xce, 0x55, 0x28, 0xdf,
0x8c, 0xa1, 0x89, 0x0d, 0xbf, 0xe6, 0x42, 0x68, 0x41, 0x99, 0x2d, 0x0f, 0xb0, 0x54, 0xbb, 0x16,
};
const sbox1 = [256]u8{
0x52, 0x09, 0x6a, 0xd5, 0x30, 0x36, 0xa5, 0x38, 0xbf, 0x40, 0xa3, 0x9e, 0x81, 0xf3, 0xd7, 0xfb,
0x7c, 0xe3, 0x39, 0x82, 0x9b, 0x2f, 0xff, 0x87, 0x34, 0x8e, 0x43, 0x44, 0xc4, 0xde, 0xe9, 0xcb,
0x54, 0x7b, 0x94, 0x32, 0xa6, 0xc2, 0x23, 0x3d, 0xee, 0x4c, 0x95, 0x0b, 0x42, 0xfa, 0xc3, 0x4e,
0x08, 0x2e, 0xa1, 0x66, 0x28, 0xd9, 0x24, 0xb2, 0x76, 0x5b, 0xa2, 0x49, 0x6d, 0x8b, 0xd1, 0x25,
0x72, 0xf8, 0xf6, 0x64, 0x86, 0x68, 0x98, 0x16, 0xd4, 0xa4, 0x5c, 0xcc, 0x5d, 0x65, 0xb6, 0x92,
0x6c, 0x70, 0x48, 0x50, 0xfd, 0xed, 0xb9, 0xda, 0x5e, 0x15, 0x46, 0x57, 0xa7, 0x8d, 0x9d, 0x84,
0x90, 0xd8, 0xab, 0x00, 0x8c, 0xbc, 0xd3, 0x0a, 0xf7, 0xe4, 0x58, 0x05, 0xb8, 0xb3, 0x45, 0x06,
0xd0, 0x2c, 0x1e, 0x8f, 0xca, 0x3f, 0x0f, 0x02, 0xc1, 0xaf, 0xbd, 0x03, 0x01, 0x13, 0x8a, 0x6b,
0x3a, 0x91, 0x11, 0x41, 0x4f, 0x67, 0xdc, 0xea, 0x97, 0xf2, 0xcf, 0xce, 0xf0, 0xb4, 0xe6, 0x73,
0x96, 0xac, 0x74, 0x22, 0xe7, 0xad, 0x35, 0x85, 0xe2, 0xf9, 0x37, 0xe8, 0x1c, 0x75, 0xdf, 0x6e,
0x47, 0xf1, 0x1a, 0x71, 0x1d, 0x29, 0xc5, 0x89, 0x6f, 0xb7, 0x62, 0x0e, 0xaa, 0x18, 0xbe, 0x1b,
0xfc, 0x56, 0x3e, 0x4b, 0xc6, 0xd2, 0x79, 0x20, 0x9a, 0xdb, 0xc0, 0xfe, 0x78, 0xcd, 0x5a, 0xf4,
0x1f, 0xdd, 0xa8, 0x33, 0x88, 0x07, 0xc7, 0x31, 0xb1, 0x12, 0x10, 0x59, 0x27, 0x80, 0xec, 0x5f,
0x60, 0x51, 0x7f, 0xa9, 0x19, 0xb5, 0x4a, 0x0d, 0x2d, 0xe5, 0x7a, 0x9f, 0x93, 0xc9, 0x9c, 0xef,
0xa0, 0xe0, 0x3b, 0x4d, 0xae, 0x2a, 0xf5, 0xb0, 0xc8, 0xeb, 0xbb, 0x3c, 0x83, 0x53, 0x99, 0x61,
0x17, 0x2b, 0x04, 0x7e, 0xba, 0x77, 0xd6, 0x26, 0xe1, 0x69, 0x14, 0x63, 0x55, 0x21, 0x0c, 0x7d,
};
const te0 = [256]u32{
0xc66363a5, 0xf87c7c84, 0xee777799, 0xf67b7b8d, 0xfff2f20d, 0xd66b6bbd, 0xde6f6fb1, 0x91c5c554,
0x60303050, 0x02010103, 0xce6767a9, 0x562b2b7d, 0xe7fefe19, 0xb5d7d762, 0x4dababe6, 0xec76769a,
0x8fcaca45, 0x1f82829d, 0x89c9c940, 0xfa7d7d87, 0xeffafa15, 0xb25959eb, 0x8e4747c9, 0xfbf0f00b,
0x41adadec, 0xb3d4d467, 0x5fa2a2fd, 0x45afafea, 0x239c9cbf, 0x53a4a4f7, 0xe4727296, 0x9bc0c05b,
0x75b7b7c2, 0xe1fdfd1c, 0x3d9393ae, 0x4c26266a, 0x6c36365a, 0x7e3f3f41, 0xf5f7f702, 0x83cccc4f,
0x6834345c, 0x51a5a5f4, 0xd1e5e534, 0xf9f1f108, 0xe2717193, 0xabd8d873, 0x62313153, 0x2a15153f,
0x0804040c, 0x95c7c752, 0x46232365, 0x9dc3c35e, 0x30181828, 0x379696a1, 0x0a05050f, 0x2f9a9ab5,
0x0e070709, 0x24121236, 0x1b80809b, 0xdfe2e23d, 0xcdebeb26, 0x4e272769, 0x7fb2b2cd, 0xea75759f,
0x1209091b, 0x1d83839e, 0x582c2c74, 0x341a1a2e, 0x361b1b2d, 0xdc6e6eb2, 0xb45a5aee, 0x5ba0a0fb,
0xa45252f6, 0x763b3b4d, 0xb7d6d661, 0x7db3b3ce, 0x5229297b, 0xdde3e33e, 0x5e2f2f71, 0x13848497,
0xa65353f5, 0xb9d1d168, 0x00000000, 0xc1eded2c, 0x40202060, 0xe3fcfc1f, 0x79b1b1c8, 0xb65b5bed,
0xd46a6abe, 0x8dcbcb46, 0x67bebed9, 0x7239394b, 0x944a4ade, 0x984c4cd4, 0xb05858e8, 0x85cfcf4a,
0xbbd0d06b, 0xc5efef2a, 0x4faaaae5, 0xedfbfb16, 0x864343c5, 0x9a4d4dd7, 0x66333355, 0x11858594,
0x8a4545cf, 0xe9f9f910, 0x04020206, 0xfe7f7f81, 0xa05050f0, 0x783c3c44, 0x259f9fba, 0x4ba8a8e3,
0xa25151f3, 0x5da3a3fe, 0x804040c0, 0x058f8f8a, 0x3f9292ad, 0x219d9dbc, 0x70383848, 0xf1f5f504,
0x63bcbcdf, 0x77b6b6c1, 0xafdada75, 0x42212163, 0x20101030, 0xe5ffff1a, 0xfdf3f30e, 0xbfd2d26d,
0x81cdcd4c, 0x180c0c14, 0x26131335, 0xc3ecec2f, 0xbe5f5fe1, 0x359797a2, 0x884444cc, 0x2e171739,
0x93c4c457, 0x55a7a7f2, 0xfc7e7e82, 0x7a3d3d47, 0xc86464ac, 0xba5d5de7, 0x3219192b, 0xe6737395,
0xc06060a0, 0x19818198, 0x9e4f4fd1, 0xa3dcdc7f, 0x44222266, 0x542a2a7e, 0x3b9090ab, 0x0b888883,
0x8c4646ca, 0xc7eeee29, 0x6bb8b8d3, 0x2814143c, 0xa7dede79, 0xbc5e5ee2, 0x160b0b1d, 0xaddbdb76,
0xdbe0e03b, 0x64323256, 0x743a3a4e, 0x140a0a1e, 0x924949db, 0x0c06060a, 0x4824246c, 0xb85c5ce4,
0x9fc2c25d, 0xbdd3d36e, 0x43acacef, 0xc46262a6, 0x399191a8, 0x319595a4, 0xd3e4e437, 0xf279798b,
0xd5e7e732, 0x8bc8c843, 0x6e373759, 0xda6d6db7, 0x018d8d8c, 0xb1d5d564, 0x9c4e4ed2, 0x49a9a9e0,
0xd86c6cb4, 0xac5656fa, 0xf3f4f407, 0xcfeaea25, 0xca6565af, 0xf47a7a8e, 0x47aeaee9, 0x10080818,
0x6fbabad5, 0xf0787888, 0x4a25256f, 0x5c2e2e72, 0x381c1c24, 0x57a6a6f1, 0x73b4b4c7, 0x97c6c651,
0xcbe8e823, 0xa1dddd7c, 0xe874749c, 0x3e1f1f21, 0x964b4bdd, 0x61bdbddc, 0x0d8b8b86, 0x0f8a8a85,
0xe0707090, 0x7c3e3e42, 0x71b5b5c4, 0xcc6666aa, 0x904848d8, 0x06030305, 0xf7f6f601, 0x1c0e0e12,
0xc26161a3, 0x6a35355f, 0xae5757f9, 0x69b9b9d0, 0x17868691, 0x99c1c158, 0x3a1d1d27, 0x279e9eb9,
0xd9e1e138, 0xebf8f813, 0x2b9898b3, 0x22111133, 0xd26969bb, 0xa9d9d970, 0x078e8e89, 0x339494a7,
0x2d9b9bb6, 0x3c1e1e22, 0x15878792, 0xc9e9e920, 0x87cece49, 0xaa5555ff, 0x50282878, 0xa5dfdf7a,
0x038c8c8f, 0x59a1a1f8, 0x09898980, 0x1a0d0d17, 0x65bfbfda, 0xd7e6e631, 0x844242c6, 0xd06868b8,
0x824141c3, 0x299999b0, 0x5a2d2d77, 0x1e0f0f11, 0x7bb0b0cb, 0xa85454fc, 0x6dbbbbd6, 0x2c16163a,
};
const te1 = [256]u32{
0xa5c66363, 0x84f87c7c, 0x99ee7777, 0x8df67b7b, 0x0dfff2f2, 0xbdd66b6b, 0xb1de6f6f, 0x5491c5c5,
0x50603030, 0x03020101, 0xa9ce6767, 0x7d562b2b, 0x19e7fefe, 0x62b5d7d7, 0xe64dabab, 0x9aec7676,
0x458fcaca, 0x9d1f8282, 0x4089c9c9, 0x87fa7d7d, 0x15effafa, 0xebb25959, 0xc98e4747, 0x0bfbf0f0,
0xec41adad, 0x67b3d4d4, 0xfd5fa2a2, 0xea45afaf, 0xbf239c9c, 0xf753a4a4, 0x96e47272, 0x5b9bc0c0,
0xc275b7b7, 0x1ce1fdfd, 0xae3d9393, 0x6a4c2626, 0x5a6c3636, 0x417e3f3f, 0x02f5f7f7, 0x4f83cccc,
0x5c683434, 0xf451a5a5, 0x34d1e5e5, 0x08f9f1f1, 0x93e27171, 0x73abd8d8, 0x53623131, 0x3f2a1515,
0x0c080404, 0x5295c7c7, 0x65462323, 0x5e9dc3c3, 0x28301818, 0xa1379696, 0x0f0a0505, 0xb52f9a9a,
0x090e0707, 0x36241212, 0x9b1b8080, 0x3ddfe2e2, 0x26cdebeb, 0x694e2727, 0xcd7fb2b2, 0x9fea7575,
0x1b120909, 0x9e1d8383, 0x74582c2c, 0x2e341a1a, 0x2d361b1b, 0xb2dc6e6e, 0xeeb45a5a, 0xfb5ba0a0,
0xf6a45252, 0x4d763b3b, 0x61b7d6d6, 0xce7db3b3, 0x7b522929, 0x3edde3e3, 0x715e2f2f, 0x97138484,
0xf5a65353, 0x68b9d1d1, 0x00000000, 0x2cc1eded, 0x60402020, 0x1fe3fcfc, 0xc879b1b1, 0xedb65b5b,
0xbed46a6a, 0x468dcbcb, 0xd967bebe, 0x4b723939, 0xde944a4a, 0xd4984c4c, 0xe8b05858, 0x4a85cfcf,
0x6bbbd0d0, 0x2ac5efef, 0xe54faaaa, 0x16edfbfb, 0xc5864343, 0xd79a4d4d, 0x55663333, 0x94118585,
0xcf8a4545, 0x10e9f9f9, 0x06040202, 0x81fe7f7f, 0xf0a05050, 0x44783c3c, 0xba259f9f, 0xe34ba8a8,
0xf3a25151, 0xfe5da3a3, 0xc0804040, 0x8a058f8f, 0xad3f9292, 0xbc219d9d, 0x48703838, 0x04f1f5f5,
0xdf63bcbc, 0xc177b6b6, 0x75afdada, 0x63422121, 0x30201010, 0x1ae5ffff, 0x0efdf3f3, 0x6dbfd2d2,
0x4c81cdcd, 0x14180c0c, 0x35261313, 0x2fc3ecec, 0xe1be5f5f, 0xa2359797, 0xcc884444, 0x392e1717,
0x5793c4c4, 0xf255a7a7, 0x82fc7e7e, 0x477a3d3d, 0xacc86464, 0xe7ba5d5d, 0x2b321919, 0x95e67373,
0xa0c06060, 0x98198181, 0xd19e4f4f, 0x7fa3dcdc, 0x66442222, 0x7e542a2a, 0xab3b9090, 0x830b8888,
0xca8c4646, 0x29c7eeee, 0xd36bb8b8, 0x3c281414, 0x79a7dede, 0xe2bc5e5e, 0x1d160b0b, 0x76addbdb,
0x3bdbe0e0, 0x56643232, 0x4e743a3a, 0x1e140a0a, 0xdb924949, 0x0a0c0606, 0x6c482424, 0xe4b85c5c,
0x5d9fc2c2, 0x6ebdd3d3, 0xef43acac, 0xa6c46262, 0xa8399191, 0xa4319595, 0x37d3e4e4, 0x8bf27979,
0x32d5e7e7, 0x438bc8c8, 0x596e3737, 0xb7da6d6d, 0x8c018d8d, 0x64b1d5d5, 0xd29c4e4e, 0xe049a9a9,
0xb4d86c6c, 0xfaac5656, 0x07f3f4f4, 0x25cfeaea, 0xafca6565, 0x8ef47a7a, 0xe947aeae, 0x18100808,
0xd56fbaba, 0x88f07878, 0x6f4a2525, 0x725c2e2e, 0x24381c1c, 0xf157a6a6, 0xc773b4b4, 0x5197c6c6,
0x23cbe8e8, 0x7ca1dddd, 0x9ce87474, 0x213e1f1f, 0xdd964b4b, 0xdc61bdbd, 0x860d8b8b, 0x850f8a8a,
0x90e07070, 0x427c3e3e, 0xc471b5b5, 0xaacc6666, 0xd8904848, 0x05060303, 0x01f7f6f6, 0x121c0e0e,
0xa3c26161, 0x5f6a3535, 0xf9ae5757, 0xd069b9b9, 0x91178686, 0x5899c1c1, 0x273a1d1d, 0xb9279e9e,
0x38d9e1e1, 0x13ebf8f8, 0xb32b9898, 0x33221111, 0xbbd26969, 0x70a9d9d9, 0x89078e8e, 0xa7339494,
0xb62d9b9b, 0x223c1e1e, 0x92158787, 0x20c9e9e9, 0x4987cece, 0xffaa5555, 0x78502828, 0x7aa5dfdf,
0x8f038c8c, 0xf859a1a1, 0x80098989, 0x171a0d0d, 0xda65bfbf, 0x31d7e6e6, 0xc6844242, 0xb8d06868,
0xc3824141, 0xb0299999, 0x775a2d2d, 0x111e0f0f, 0xcb7bb0b0, 0xfca85454, 0xd66dbbbb, 0x3a2c1616,
};
const te2 = [256]u32{
0x63a5c663, 0x7c84f87c, 0x7799ee77, 0x7b8df67b, 0xf20dfff2, 0x6bbdd66b, 0x6fb1de6f, 0xc55491c5,
0x30506030, 0x01030201, 0x67a9ce67, 0x2b7d562b, 0xfe19e7fe, 0xd762b5d7, 0xabe64dab, 0x769aec76,
0xca458fca, 0x829d1f82, 0xc94089c9, 0x7d87fa7d, 0xfa15effa, 0x59ebb259, 0x47c98e47, 0xf00bfbf0,
0xadec41ad, 0xd467b3d4, 0xa2fd5fa2, 0xafea45af, 0x9cbf239c, 0xa4f753a4, 0x7296e472, 0xc05b9bc0,
0xb7c275b7, 0xfd1ce1fd, 0x93ae3d93, 0x266a4c26, 0x365a6c36, 0x3f417e3f, 0xf702f5f7, 0xcc4f83cc,
0x345c6834, 0xa5f451a5, 0xe534d1e5, 0xf108f9f1, 0x7193e271, 0xd873abd8, 0x31536231, 0x153f2a15,
0x040c0804, 0xc75295c7, 0x23654623, 0xc35e9dc3, 0x18283018, 0x96a13796, 0x050f0a05, 0x9ab52f9a,
0x07090e07, 0x12362412, 0x809b1b80, 0xe23ddfe2, 0xeb26cdeb, 0x27694e27, 0xb2cd7fb2, 0x759fea75,
0x091b1209, 0x839e1d83, 0x2c74582c, 0x1a2e341a, 0x1b2d361b, 0x6eb2dc6e, 0x5aeeb45a, 0xa0fb5ba0,
0x52f6a452, 0x3b4d763b, 0xd661b7d6, 0xb3ce7db3, 0x297b5229, 0xe33edde3, 0x2f715e2f, 0x84971384,
0x53f5a653, 0xd168b9d1, 0x00000000, 0xed2cc1ed, 0x20604020, 0xfc1fe3fc, 0xb1c879b1, 0x5bedb65b,
0x6abed46a, 0xcb468dcb, 0xbed967be, 0x394b7239, 0x4ade944a, 0x4cd4984c, 0x58e8b058, 0xcf4a85cf,
0xd06bbbd0, 0xef2ac5ef, 0xaae54faa, 0xfb16edfb, 0x43c58643, 0x4dd79a4d, 0x33556633, 0x85941185,
0x45cf8a45, 0xf910e9f9, 0x02060402, 0x7f81fe7f, 0x50f0a050, 0x3c44783c, 0x9fba259f, 0xa8e34ba8,
0x51f3a251, 0xa3fe5da3, 0x40c08040, 0x8f8a058f, 0x92ad3f92, 0x9dbc219d, 0x38487038, 0xf504f1f5,
0xbcdf63bc, 0xb6c177b6, 0xda75afda, 0x21634221, 0x10302010, 0xff1ae5ff, 0xf30efdf3, 0xd26dbfd2,
0xcd4c81cd, 0x0c14180c, 0x13352613, 0xec2fc3ec, 0x5fe1be5f, 0x97a23597, 0x44cc8844, 0x17392e17,
0xc45793c4, 0xa7f255a7, 0x7e82fc7e, 0x3d477a3d, 0x64acc864, 0x5de7ba5d, 0x192b3219, 0x7395e673,
0x60a0c060, 0x81981981, 0x4fd19e4f, 0xdc7fa3dc, 0x22664422, 0x2a7e542a, 0x90ab3b90, 0x88830b88,
0x46ca8c46, 0xee29c7ee, 0xb8d36bb8, 0x143c2814, 0xde79a7de, 0x5ee2bc5e, 0x0b1d160b, 0xdb76addb,
0xe03bdbe0, 0x32566432, 0x3a4e743a, 0x0a1e140a, 0x49db9249, 0x060a0c06, 0x246c4824, 0x5ce4b85c,
0xc25d9fc2, 0xd36ebdd3, 0xacef43ac, 0x62a6c462, 0x91a83991, 0x95a43195, 0xe437d3e4, 0x798bf279,
0xe732d5e7, 0xc8438bc8, 0x37596e37, 0x6db7da6d, 0x8d8c018d, 0xd564b1d5, 0x4ed29c4e, 0xa9e049a9,
0x6cb4d86c, 0x56faac56, 0xf407f3f4, 0xea25cfea, 0x65afca65, 0x7a8ef47a, 0xaee947ae, 0x08181008,
0xbad56fba, 0x7888f078, 0x256f4a25, 0x2e725c2e, 0x1c24381c, 0xa6f157a6, 0xb4c773b4, 0xc65197c6,
0xe823cbe8, 0xdd7ca1dd, 0x749ce874, 0x1f213e1f, 0x4bdd964b, 0xbddc61bd, 0x8b860d8b, 0x8a850f8a,
0x7090e070, 0x3e427c3e, 0xb5c471b5, 0x66aacc66, 0x48d89048, 0x03050603, 0xf601f7f6, 0x0e121c0e,
0x61a3c261, 0x355f6a35, 0x57f9ae57, 0xb9d069b9, 0x86911786, 0xc15899c1, 0x1d273a1d, 0x9eb9279e,
0xe138d9e1, 0xf813ebf8, 0x98b32b98, 0x11332211, 0x69bbd269, 0xd970a9d9, 0x8e89078e, 0x94a73394,
0x9bb62d9b, 0x1e223c1e, 0x87921587, 0xe920c9e9, 0xce4987ce, 0x55ffaa55, 0x28785028, 0xdf7aa5df,
0x8c8f038c, 0xa1f859a1, 0x89800989, 0x0d171a0d, 0xbfda65bf, 0xe631d7e6, 0x42c68442, 0x68b8d068,
0x41c38241, 0x99b02999, 0x2d775a2d, 0x0f111e0f, 0xb0cb7bb0, 0x54fca854, 0xbbd66dbb, 0x163a2c16,
};
const te3 = [256]u32{
0x6363a5c6, 0x7c7c84f8, 0x777799ee, 0x7b7b8df6, 0xf2f20dff, 0x6b6bbdd6, 0x6f6fb1de, 0xc5c55491,
0x30305060, 0x01010302, 0x6767a9ce, 0x2b2b7d56, 0xfefe19e7, 0xd7d762b5, 0xababe64d, 0x76769aec,
0xcaca458f, 0x82829d1f, 0xc9c94089, 0x7d7d87fa, 0xfafa15ef, 0x5959ebb2, 0x4747c98e, 0xf0f00bfb,
0xadadec41, 0xd4d467b3, 0xa2a2fd5f, 0xafafea45, 0x9c9cbf23, 0xa4a4f753, 0x727296e4, 0xc0c05b9b,
0xb7b7c275, 0xfdfd1ce1, 0x9393ae3d, 0x26266a4c, 0x36365a6c, 0x3f3f417e, 0xf7f702f5, 0xcccc4f83,
0x34345c68, 0xa5a5f451, 0xe5e534d1, 0xf1f108f9, 0x717193e2, 0xd8d873ab, 0x31315362, 0x15153f2a,
0x04040c08, 0xc7c75295, 0x23236546, 0xc3c35e9d, 0x18182830, 0x9696a137, 0x05050f0a, 0x9a9ab52f,
0x0707090e, 0x12123624, 0x80809b1b, 0xe2e23ddf, 0xebeb26cd, 0x2727694e, 0xb2b2cd7f, 0x75759fea,
0x09091b12, 0x83839e1d, 0x2c2c7458, 0x1a1a2e34, 0x1b1b2d36, 0x6e6eb2dc, 0x5a5aeeb4, 0xa0a0fb5b,
0x5252f6a4, 0x3b3b4d76, 0xd6d661b7, 0xb3b3ce7d, 0x29297b52, 0xe3e33edd, 0x2f2f715e, 0x84849713,
0x5353f5a6, 0xd1d168b9, 0x00000000, 0xeded2cc1, 0x20206040, 0xfcfc1fe3, 0xb1b1c879, 0x5b5bedb6,
0x6a6abed4, 0xcbcb468d, 0xbebed967, 0x39394b72, 0x4a4ade94, 0x4c4cd498, 0x5858e8b0, 0xcfcf4a85,
0xd0d06bbb, 0xefef2ac5, 0xaaaae54f, 0xfbfb16ed, 0x4343c586, 0x4d4dd79a, 0x33335566, 0x85859411,
0x4545cf8a, 0xf9f910e9, 0x02020604, 0x7f7f81fe, 0x5050f0a0, 0x3c3c4478, 0x9f9fba25, 0xa8a8e34b,
0x5151f3a2, 0xa3a3fe5d, 0x4040c080, 0x8f8f8a05, 0x9292ad3f, 0x9d9dbc21, 0x38384870, 0xf5f504f1,
0xbcbcdf63, 0xb6b6c177, 0xdada75af, 0x21216342, 0x10103020, 0xffff1ae5, 0xf3f30efd, 0xd2d26dbf,
0xcdcd4c81, 0x0c0c1418, 0x13133526, 0xecec2fc3, 0x5f5fe1be, 0x9797a235, 0x4444cc88, 0x1717392e,
0xc4c45793, 0xa7a7f255, 0x7e7e82fc, 0x3d3d477a, 0x6464acc8, 0x5d5de7ba, 0x19192b32, 0x737395e6,
0x6060a0c0, 0x81819819, 0x4f4fd19e, 0xdcdc7fa3, 0x22226644, 0x2a2a7e54, 0x9090ab3b, 0x8888830b,
0x4646ca8c, 0xeeee29c7, 0xb8b8d36b, 0x14143c28, 0xdede79a7, 0x5e5ee2bc, 0x0b0b1d16, 0xdbdb76ad,
0xe0e03bdb, 0x32325664, 0x3a3a4e74, 0x0a0a1e14, 0x4949db92, 0x06060a0c, 0x24246c48, 0x5c5ce4b8,
0xc2c25d9f, 0xd3d36ebd, 0xacacef43, 0x6262a6c4, 0x9191a839, 0x9595a431, 0xe4e437d3, 0x79798bf2,
0xe7e732d5, 0xc8c8438b, 0x3737596e, 0x6d6db7da, 0x8d8d8c01, 0xd5d564b1, 0x4e4ed29c, 0xa9a9e049,
0x6c6cb4d8, 0x5656faac, 0xf4f407f3, 0xeaea25cf, 0x6565afca, 0x7a7a8ef4, 0xaeaee947, 0x08081810,
0xbabad56f, 0x787888f0, 0x25256f4a, 0x2e2e725c, 0x1c1c2438, 0xa6a6f157, 0xb4b4c773, 0xc6c65197,
0xe8e823cb, 0xdddd7ca1, 0x74749ce8, 0x1f1f213e, 0x4b4bdd96, 0xbdbddc61, 0x8b8b860d, 0x8a8a850f,
0x707090e0, 0x3e3e427c, 0xb5b5c471, 0x6666aacc, 0x4848d890, 0x03030506, 0xf6f601f7, 0x0e0e121c,
0x6161a3c2, 0x35355f6a, 0x5757f9ae, 0xb9b9d069, 0x86869117, 0xc1c15899, 0x1d1d273a, 0x9e9eb927,
0xe1e138d9, 0xf8f813eb, 0x9898b32b, 0x11113322, 0x6969bbd2, 0xd9d970a9, 0x8e8e8907, 0x9494a733,
0x9b9bb62d, 0x1e1e223c, 0x87879215, 0xe9e920c9, 0xcece4987, 0x5555ffaa, 0x28287850, 0xdfdf7aa5,
0x8c8c8f03, 0xa1a1f859, 0x89898009, 0x0d0d171a, 0xbfbfda65, 0xe6e631d7, 0x4242c684, 0x6868b8d0,
0x4141c382, 0x9999b029, 0x2d2d775a, 0x0f0f111e, 0xb0b0cb7b, 0x5454fca8, 0xbbbbd66d, 0x16163a2c,
};
const td0 = [256]u32{
0x51f4a750, 0x7e416553, 0x1a17a4c3, 0x3a275e96, 0x3bab6bcb, 0x1f9d45f1, 0xacfa58ab, 0x4be30393,
0x2030fa55, 0xad766df6, 0x88cc7691, 0xf5024c25, 0x4fe5d7fc, 0xc52acbd7, 0x26354480, 0xb562a38f,
0xdeb15a49, 0x25ba1b67, 0x45ea0e98, 0x5dfec0e1, 0xc32f7502, 0x814cf012, 0x8d4697a3, 0x6bd3f9c6,
0x038f5fe7, 0x15929c95, 0xbf6d7aeb, 0x955259da, 0xd4be832d, 0x587421d3, 0x49e06929, 0x8ec9c844,
0x75c2896a, 0xf48e7978, 0x99583e6b, 0x27b971dd, 0xbee14fb6, 0xf088ad17, 0xc920ac66, 0x7dce3ab4,
0x63df4a18, 0xe51a3182, 0x97513360, 0x62537f45, 0xb16477e0, 0xbb6bae84, 0xfe81a01c, 0xf9082b94,
0x70486858, 0x8f45fd19, 0x94de6c87, 0x527bf8b7, 0xab73d323, 0x724b02e2, 0xe31f8f57, 0x6655ab2a,
0xb2eb2807, 0x2fb5c203, 0x86c57b9a, 0xd33708a5, 0x302887f2, 0x23bfa5b2, 0x02036aba, 0xed16825c,
0x8acf1c2b, 0xa779b492, 0xf307f2f0, 0x4e69e2a1, 0x65daf4cd, 0x0605bed5, 0xd134621f, 0xc4a6fe8a,
0x342e539d, 0xa2f355a0, 0x058ae132, 0xa4f6eb75, 0x0b83ec39, 0x4060efaa, 0x5e719f06, 0xbd6e1051,
0x3e218af9, 0x96dd063d, 0xdd3e05ae, 0x4de6bd46, 0x91548db5, 0x71c45d05, 0x0406d46f, 0x605015ff,
0x1998fb24, 0xd6bde997, 0x894043cc, 0x67d99e77, 0xb0e842bd, 0x07898b88, 0xe7195b38, 0x79c8eedb,
0xa17c0a47, 0x7c420fe9, 0xf8841ec9, 0x00000000, 0x09808683, 0x322bed48, 0x1e1170ac, 0x6c5a724e,
0xfd0efffb, 0x0f853856, 0x3daed51e, 0x362d3927, 0x0a0fd964, 0x685ca621, 0x9b5b54d1, 0x24362e3a,
0x0c0a67b1, 0x9357e70f, 0xb4ee96d2, 0x1b9b919e, 0x80c0c54f, 0x61dc20a2, 0x5a774b69, 0x1c121a16,
0xe293ba0a, 0xc0a02ae5, 0x3c22e043, 0x121b171d, 0x0e090d0b, 0xf28bc7ad, 0x2db6a8b9, 0x141ea9c8,
0x57f11985, 0xaf75074c, 0xee99ddbb, 0xa37f60fd, 0xf701269f, 0x5c72f5bc, 0x44663bc5, 0x5bfb7e34,
0x8b432976, 0xcb23c6dc, 0xb6edfc68, 0xb8e4f163, 0xd731dcca, 0x42638510, 0x13972240, 0x84c61120,
0x854a247d, 0xd2bb3df8, 0xaef93211, 0xc729a16d, 0x1d9e2f4b, 0xdcb230f3, 0x0d8652ec, 0x77c1e3d0,
0x2bb3166c, 0xa970b999, 0x119448fa, 0x47e96422, 0xa8fc8cc4, 0xa0f03f1a, 0x567d2cd8, 0x223390ef,
0x87494ec7, 0xd938d1c1, 0x8ccaa2fe, 0x98d40b36, 0xa6f581cf, 0xa57ade28, 0xdab78e26, 0x3fadbfa4,
0x2c3a9de4, 0x5078920d, 0x6a5fcc9b, 0x547e4662, 0xf68d13c2, 0x90d8b8e8, 0x2e39f75e, 0x82c3aff5,
0x9f5d80be, 0x69d0937c, 0x6fd52da9, 0xcf2512b3, 0xc8ac993b, 0x10187da7, 0xe89c636e, 0xdb3bbb7b,
0xcd267809, 0x6e5918f4, 0xec9ab701, 0x834f9aa8, 0xe6956e65, 0xaaffe67e, 0x21bccf08, 0xef15e8e6,
0xbae79bd9, 0x4a6f36ce, 0xea9f09d4, 0x29b07cd6, 0x31a4b2af, 0x2a3f2331, 0xc6a59430, 0x35a266c0,
0x744ebc37, 0xfc82caa6, 0xe090d0b0, 0x33a7d815, 0xf104984a, 0x41ecdaf7, 0x7fcd500e, 0x1791f62f,
0x764dd68d, 0x43efb04d, 0xccaa4d54, 0xe49604df, 0x9ed1b5e3, 0x4c6a881b, 0xc12c1fb8, 0x4665517f,
0x9d5eea04, 0x018c355d, 0xfa877473, 0xfb0b412e, 0xb3671d5a, 0x92dbd252, 0xe9105633, 0x6dd64713,
0x9ad7618c, 0x37a10c7a, 0x59f8148e, 0xeb133c89, 0xcea927ee, 0xb761c935, 0xe11ce5ed, 0x7a47b13c,
0x9cd2df59, 0x55f2733f, 0x1814ce79, 0x73c737bf, 0x53f7cdea, 0x5ffdaa5b, 0xdf3d6f14, 0x7844db86,
0xcaaff381, 0xb968c43e, 0x3824342c, 0xc2a3405f, 0x161dc372, 0xbce2250c, 0x283c498b, 0xff0d9541,
0x39a80171, 0x080cb3de, 0xd8b4e49c, 0x6456c190, 0x7bcb8461, 0xd532b670, 0x486c5c74, 0xd0b85742,
};
const td1 = [256]u32{
0x5051f4a7, 0x537e4165, 0xc31a17a4, 0x963a275e, 0xcb3bab6b, 0xf11f9d45, 0xabacfa58, 0x934be303,
0x552030fa, 0xf6ad766d, 0x9188cc76, 0x25f5024c, 0xfc4fe5d7, 0xd7c52acb, 0x80263544, 0x8fb562a3,
0x49deb15a, 0x6725ba1b, 0x9845ea0e, 0xe15dfec0, 0x02c32f75, 0x12814cf0, 0xa38d4697, 0xc66bd3f9,
0xe7038f5f, 0x9515929c, 0xebbf6d7a, 0xda955259, 0x2dd4be83, 0xd3587421, 0x2949e069, 0x448ec9c8,
0x6a75c289, 0x78f48e79, 0x6b99583e, 0xdd27b971, 0xb6bee14f, 0x17f088ad, 0x66c920ac, 0xb47dce3a,
0x1863df4a, 0x82e51a31, 0x60975133, 0x4562537f, 0xe0b16477, 0x84bb6bae, 0x1cfe81a0, 0x94f9082b,
0x58704868, 0x198f45fd, 0x8794de6c, 0xb7527bf8, 0x23ab73d3, 0xe2724b02, 0x57e31f8f, 0x2a6655ab,
0x07b2eb28, 0x032fb5c2, 0x9a86c57b, 0xa5d33708, 0xf2302887, 0xb223bfa5, 0xba02036a, 0x5ced1682,
0x2b8acf1c, 0x92a779b4, 0xf0f307f2, 0xa14e69e2, 0xcd65daf4, 0xd50605be, 0x1fd13462, 0x8ac4a6fe,
0x9d342e53, 0xa0a2f355, 0x32058ae1, 0x75a4f6eb, 0x390b83ec, 0xaa4060ef, 0x065e719f, 0x51bd6e10,
0xf93e218a, 0x3d96dd06, 0xaedd3e05, 0x464de6bd, 0xb591548d, 0x0571c45d, 0x6f0406d4, 0xff605015,
0x241998fb, 0x97d6bde9, 0xcc894043, 0x7767d99e, 0xbdb0e842, 0x8807898b, 0x38e7195b, 0xdb79c8ee,
0x47a17c0a, 0xe97c420f, 0xc9f8841e, 0x00000000, 0x83098086, 0x48322bed, 0xac1e1170, 0x4e6c5a72,
0xfbfd0eff, 0x560f8538, 0x1e3daed5, 0x27362d39, 0x640a0fd9, 0x21685ca6, 0xd19b5b54, 0x3a24362e,
0xb10c0a67, 0x0f9357e7, 0xd2b4ee96, 0x9e1b9b91, 0x4f80c0c5, 0xa261dc20, 0x695a774b, 0x161c121a,
0x0ae293ba, 0xe5c0a02a, 0x433c22e0, 0x1d121b17, 0x0b0e090d, 0xadf28bc7, 0xb92db6a8, 0xc8141ea9,
0x8557f119, 0x4caf7507, 0xbbee99dd, 0xfda37f60, 0x9ff70126, 0xbc5c72f5, 0xc544663b, 0x345bfb7e,
0x768b4329, 0xdccb23c6, 0x68b6edfc, 0x63b8e4f1, 0xcad731dc, 0x10426385, 0x40139722, 0x2084c611,
0x7d854a24, 0xf8d2bb3d, 0x11aef932, 0x6dc729a1, 0x4b1d9e2f, 0xf3dcb230, 0xec0d8652, 0xd077c1e3,
0x6c2bb316, 0x99a970b9, 0xfa119448, 0x2247e964, 0xc4a8fc8c, 0x1aa0f03f, 0xd8567d2c, 0xef223390,
0xc787494e, 0xc1d938d1, 0xfe8ccaa2, 0x3698d40b, 0xcfa6f581, 0x28a57ade, 0x26dab78e, 0xa43fadbf,
0xe42c3a9d, 0x0d507892, 0x9b6a5fcc, 0x62547e46, 0xc2f68d13, 0xe890d8b8, 0x5e2e39f7, 0xf582c3af,
0xbe9f5d80, 0x7c69d093, 0xa96fd52d, 0xb3cf2512, 0x3bc8ac99, 0xa710187d, 0x6ee89c63, 0x7bdb3bbb,
0x09cd2678, 0xf46e5918, 0x01ec9ab7, 0xa8834f9a, 0x65e6956e, 0x7eaaffe6, 0x0821bccf, 0xe6ef15e8,
0xd9bae79b, 0xce4a6f36, 0xd4ea9f09, 0xd629b07c, 0xaf31a4b2, 0x312a3f23, 0x30c6a594, 0xc035a266,
0x37744ebc, 0xa6fc82ca, 0xb0e090d0, 0x1533a7d8, 0x4af10498, 0xf741ecda, 0x0e7fcd50, 0x2f1791f6,
0x8d764dd6, 0x4d43efb0, 0x54ccaa4d, 0xdfe49604, 0xe39ed1b5, 0x1b4c6a88, 0xb8c12c1f, 0x7f466551,
0x049d5eea, 0x5d018c35, 0x73fa8774, 0x2efb0b41, 0x5ab3671d, 0x5292dbd2, 0x33e91056, 0x136dd647,
0x8c9ad761, 0x7a37a10c, 0x8e59f814, 0x89eb133c, 0xeecea927, 0x35b761c9, 0xede11ce5, 0x3c7a47b1,
0x599cd2df, 0x3f55f273, 0x791814ce, 0xbf73c737, 0xea53f7cd, 0x5b5ffdaa, 0x14df3d6f, 0x867844db,
0x81caaff3, 0x3eb968c4, 0x2c382434, 0x5fc2a340, 0x72161dc3, 0x0cbce225, 0x8b283c49, 0x41ff0d95,
0x7139a801, 0xde080cb3, 0x9cd8b4e4, 0x906456c1, 0x617bcb84, 0x70d532b6, 0x74486c5c, 0x42d0b857,
};
const td2 = [256]u32{
0xa75051f4, 0x65537e41, 0xa4c31a17, 0x5e963a27, 0x6bcb3bab, 0x45f11f9d, 0x58abacfa, 0x03934be3,
0xfa552030, 0x6df6ad76, 0x769188cc, 0x4c25f502, 0xd7fc4fe5, 0xcbd7c52a, 0x44802635, 0xa38fb562,
0x5a49deb1, 0x1b6725ba, 0x0e9845ea, 0xc0e15dfe, 0x7502c32f, 0xf012814c, 0x97a38d46, 0xf9c66bd3,
0x5fe7038f, 0x9c951592, 0x7aebbf6d, 0x59da9552, 0x832dd4be, 0x21d35874, 0x692949e0, 0xc8448ec9,
0x896a75c2, 0x7978f48e, 0x3e6b9958, 0x71dd27b9, 0x4fb6bee1, 0xad17f088, 0xac66c920, 0x3ab47dce,
0x4a1863df, 0x3182e51a, 0x33609751, 0x7f456253, 0x77e0b164, 0xae84bb6b, 0xa01cfe81, 0x2b94f908,
0x68587048, 0xfd198f45, 0x6c8794de, 0xf8b7527b, 0xd323ab73, 0x02e2724b, 0x8f57e31f, 0xab2a6655,
0x2807b2eb, 0xc2032fb5, 0x7b9a86c5, 0x08a5d337, 0x87f23028, 0xa5b223bf, 0x6aba0203, 0x825ced16,
0x1c2b8acf, 0xb492a779, 0xf2f0f307, 0xe2a14e69, 0xf4cd65da, 0xbed50605, 0x621fd134, 0xfe8ac4a6,
0x539d342e, 0x55a0a2f3, 0xe132058a, 0xeb75a4f6, 0xec390b83, 0xefaa4060, 0x9f065e71, 0x1051bd6e,
0x8af93e21, 0x063d96dd, 0x05aedd3e, 0xbd464de6, 0x8db59154, 0x5d0571c4, 0xd46f0406, 0x15ff6050,
0xfb241998, 0xe997d6bd, 0x43cc8940, 0x9e7767d9, 0x42bdb0e8, 0x8b880789, 0x5b38e719, 0xeedb79c8,
0x0a47a17c, 0x0fe97c42, 0x1ec9f884, 0x00000000, 0x86830980, 0xed48322b, 0x70ac1e11, 0x724e6c5a,
0xfffbfd0e, 0x38560f85, 0xd51e3dae, 0x3927362d, 0xd9640a0f, 0xa621685c, 0x54d19b5b, 0x2e3a2436,
0x67b10c0a, 0xe70f9357, 0x96d2b4ee, 0x919e1b9b, 0xc54f80c0, 0x20a261dc, 0x4b695a77, 0x1a161c12,
0xba0ae293, 0x2ae5c0a0, 0xe0433c22, 0x171d121b, 0x0d0b0e09, 0xc7adf28b, 0xa8b92db6, 0xa9c8141e,
0x198557f1, 0x074caf75, 0xddbbee99, 0x60fda37f, 0x269ff701, 0xf5bc5c72, 0x3bc54466, 0x7e345bfb,
0x29768b43, 0xc6dccb23, 0xfc68b6ed, 0xf163b8e4, 0xdccad731, 0x85104263, 0x22401397, 0x112084c6,
0x247d854a, 0x3df8d2bb, 0x3211aef9, 0xa16dc729, 0x2f4b1d9e, 0x30f3dcb2, 0x52ec0d86, 0xe3d077c1,
0x166c2bb3, 0xb999a970, 0x48fa1194, 0x642247e9, 0x8cc4a8fc, 0x3f1aa0f0, 0x2cd8567d, 0x90ef2233,
0x4ec78749, 0xd1c1d938, 0xa2fe8cca, 0x0b3698d4, 0x81cfa6f5, 0xde28a57a, 0x8e26dab7, 0xbfa43fad,
0x9de42c3a, 0x920d5078, 0xcc9b6a5f, 0x4662547e, 0x13c2f68d, 0xb8e890d8, 0xf75e2e39, 0xaff582c3,
0x80be9f5d, 0x937c69d0, 0x2da96fd5, 0x12b3cf25, 0x993bc8ac, 0x7da71018, 0x636ee89c, 0xbb7bdb3b,
0x7809cd26, 0x18f46e59, 0xb701ec9a, 0x9aa8834f, 0x6e65e695, 0xe67eaaff, 0xcf0821bc, 0xe8e6ef15,
0x9bd9bae7, 0x36ce4a6f, 0x09d4ea9f, 0x7cd629b0, 0xb2af31a4, 0x23312a3f, 0x9430c6a5, 0x66c035a2,
0xbc37744e, 0xcaa6fc82, 0xd0b0e090, 0xd81533a7, 0x984af104, 0xdaf741ec, 0x500e7fcd, 0xf62f1791,
0xd68d764d, 0xb04d43ef, 0x4d54ccaa, 0x04dfe496, 0xb5e39ed1, 0x881b4c6a, 0x1fb8c12c, 0x517f4665,
0xea049d5e, 0x355d018c, 0x7473fa87, 0x412efb0b, 0x1d5ab367, 0xd25292db, 0x5633e910, 0x47136dd6,
0x618c9ad7, 0x0c7a37a1, 0x148e59f8, 0x3c89eb13, 0x27eecea9, 0xc935b761, 0xe5ede11c, 0xb13c7a47,
0xdf599cd2, 0x733f55f2, 0xce791814, 0x37bf73c7, 0xcdea53f7, 0xaa5b5ffd, 0x6f14df3d, 0xdb867844,
0xf381caaf, 0xc43eb968, 0x342c3824, 0x405fc2a3, 0xc372161d, 0x250cbce2, 0x498b283c, 0x9541ff0d,
0x017139a8, 0xb3de080c, 0xe49cd8b4, 0xc1906456, 0x84617bcb, 0xb670d532, 0x5c74486c, 0x5742d0b8,
};
const td3 = [256]u32{
0xf4a75051, 0x4165537e, 0x17a4c31a, 0x275e963a, 0xab6bcb3b, 0x9d45f11f, 0xfa58abac, 0xe303934b,
0x30fa5520, 0x766df6ad, 0xcc769188, 0x024c25f5, 0xe5d7fc4f, 0x2acbd7c5, 0x35448026, 0x62a38fb5,
0xb15a49de, 0xba1b6725, 0xea0e9845, 0xfec0e15d, 0x2f7502c3, 0x4cf01281, 0x4697a38d, 0xd3f9c66b,
0x8f5fe703, 0x929c9515, 0x6d7aebbf, 0x5259da95, 0xbe832dd4, 0x7421d358, 0xe0692949, 0xc9c8448e,
0xc2896a75, 0x8e7978f4, 0x583e6b99, 0xb971dd27, 0xe14fb6be, 0x88ad17f0, 0x20ac66c9, 0xce3ab47d,
0xdf4a1863, 0x1a3182e5, 0x51336097, 0x537f4562, 0x6477e0b1, 0x6bae84bb, 0x81a01cfe, 0x082b94f9,
0x48685870, 0x45fd198f, 0xde6c8794, 0x7bf8b752, 0x73d323ab, 0x4b02e272, 0x1f8f57e3, 0x55ab2a66,
0xeb2807b2, 0xb5c2032f, 0xc57b9a86, 0x3708a5d3, 0x2887f230, 0xbfa5b223, 0x036aba02, 0x16825ced,
0xcf1c2b8a, 0x79b492a7, 0x07f2f0f3, 0x69e2a14e, 0xdaf4cd65, 0x05bed506, 0x34621fd1, 0xa6fe8ac4,
0x2e539d34, 0xf355a0a2, 0x8ae13205, 0xf6eb75a4, 0x83ec390b, 0x60efaa40, 0x719f065e, 0x6e1051bd,
0x218af93e, 0xdd063d96, 0x3e05aedd, 0xe6bd464d, 0x548db591, 0xc45d0571, 0x06d46f04, 0x5015ff60,
0x98fb2419, 0xbde997d6, 0x4043cc89, 0xd99e7767, 0xe842bdb0, 0x898b8807, 0x195b38e7, 0xc8eedb79,
0x7c0a47a1, 0x420fe97c, 0x841ec9f8, 0x00000000, 0x80868309, 0x2bed4832, 0x1170ac1e, 0x5a724e6c,
0x0efffbfd, 0x8538560f, 0xaed51e3d, 0x2d392736, 0x0fd9640a, 0x5ca62168, 0x5b54d19b, 0x362e3a24,
0x0a67b10c, 0x57e70f93, 0xee96d2b4, 0x9b919e1b, 0xc0c54f80, 0xdc20a261, 0x774b695a, 0x121a161c,
0x93ba0ae2, 0xa02ae5c0, 0x22e0433c, 0x1b171d12, 0x090d0b0e, 0x8bc7adf2, 0xb6a8b92d, 0x1ea9c814,
0xf1198557, 0x75074caf, 0x99ddbbee, 0x7f60fda3, 0x01269ff7, 0x72f5bc5c, 0x663bc544, 0xfb7e345b,
0x4329768b, 0x23c6dccb, 0xedfc68b6, 0xe4f163b8, 0x31dccad7, 0x63851042, 0x97224013, 0xc6112084,
0x4a247d85, 0xbb3df8d2, 0xf93211ae, 0x29a16dc7, 0x9e2f4b1d, 0xb230f3dc, 0x8652ec0d, 0xc1e3d077,
0xb3166c2b, 0x70b999a9, 0x9448fa11, 0xe9642247, 0xfc8cc4a8, 0xf03f1aa0, 0x7d2cd856, 0x3390ef22,
0x494ec787, 0x38d1c1d9, 0xcaa2fe8c, 0xd40b3698, 0xf581cfa6, 0x7ade28a5, 0xb78e26da, 0xadbfa43f,
0x3a9de42c, 0x78920d50, 0x5fcc9b6a, 0x7e466254, 0x8d13c2f6, 0xd8b8e890, 0x39f75e2e, 0xc3aff582,
0x5d80be9f, 0xd0937c69, 0xd52da96f, 0x2512b3cf, 0xac993bc8, 0x187da710, 0x9c636ee8, 0x3bbb7bdb,
0x267809cd, 0x5918f46e, 0x9ab701ec, 0x4f9aa883, 0x956e65e6, 0xffe67eaa, 0xbccf0821, 0x15e8e6ef,
0xe79bd9ba, 0x6f36ce4a, 0x9f09d4ea, 0xb07cd629, 0xa4b2af31, 0x3f23312a, 0xa59430c6, 0xa266c035,
0x4ebc3774, 0x82caa6fc, 0x90d0b0e0, 0xa7d81533, 0x04984af1, 0xecdaf741, 0xcd500e7f, 0x91f62f17,
0x4dd68d76, 0xefb04d43, 0xaa4d54cc, 0x9604dfe4, 0xd1b5e39e, 0x6a881b4c, 0x2c1fb8c1, 0x65517f46,
0x5eea049d, 0x8c355d01, 0x877473fa, 0x0b412efb, 0x671d5ab3, 0xdbd25292, 0x105633e9, 0xd647136d,
0xd7618c9a, 0xa10c7a37, 0xf8148e59, 0x133c89eb, 0xa927eece, 0x61c935b7, 0x1ce5ede1, 0x47b13c7a,
0xd2df599c, 0xf2733f55, 0x14ce7918, 0xc737bf73, 0xf7cdea53, 0xfdaa5b5f, 0x3d6f14df, 0x44db8678,
0xaff381ca, 0x68c43eb9, 0x24342c38, 0xa3405fc2, 0x1dc37216, 0xe2250cbc, 0x3c498b28, 0x0d9541ff,
0xa8017139, 0x0cb3de08, 0xb4e49cd8, 0x56c19064, 0xcb84617b, 0x32b670d5, 0x6c5c7448, 0xb85742d0,
}; | lib/std/crypto/aes.zig |
const std = @import("../std.zig");
const math = std.math;
const expect = std.testing.expect;
pub fn acos(x: var) @typeOf(x) {
const T = @typeOf(x);
return switch (T) {
f32 => acos32(x),
f64 => acos64(x),
else => @compileError("acos not implemented for " ++ @typeName(T)),
};
}
fn r32(z: f32) f32 {
const pS0 = 1.6666586697e-01;
const pS1 = -4.2743422091e-02;
const pS2 = -8.6563630030e-03;
const qS1 = -7.0662963390e-01;
const p = z * (pS0 + z * (pS1 + z * pS2));
const q = 1.0 + z * qS1;
return p / q;
}
fn acos32(x: f32) f32 {
const pio2_hi = 1.5707962513e+00;
const pio2_lo = 7.5497894159e-08;
const hx: u32 = @bitCast(u32, x);
const ix: u32 = hx & 0x7FFFFFFF;
// |x| >= 1 or nan
if (ix >= 0x3F800000) {
if (ix == 0x3F800000) {
if (hx >> 31 != 0) {
return 2.0 * pio2_hi + 0x1.0p-120;
} else {
return 0.0;
}
} else {
return math.nan(f32);
}
}
// |x| < 0.5
if (ix < 0x3F000000) {
if (ix <= 0x32800000) { // |x| < 2^(-26)
return pio2_hi + 0x1.0p-120;
} else {
return pio2_hi - (x - (pio2_lo - x * r32(x * x)));
}
}
// x < -0.5
if (hx >> 31 != 0) {
const z = (1 + x) * 0.5;
const s = math.sqrt(z);
const w = r32(z) * s - pio2_lo;
return 2 * (pio2_hi - (s + w));
}
// x > 0.5
const z = (1.0 - x) * 0.5;
const s = math.sqrt(z);
const jx = @bitCast(u32, s);
const df = @bitCast(f32, jx & 0xFFFFF000);
const c = (z - df * df) / (s + df);
const w = r32(z) * s + c;
return 2 * (df + w);
}
fn r64(z: f64) f64 {
const pS0: f64 = 1.66666666666666657415e-01;
const pS1: f64 = -3.25565818622400915405e-01;
const pS2: f64 = 2.01212532134862925881e-01;
const pS3: f64 = -4.00555345006794114027e-02;
const pS4: f64 = 7.91534994289814532176e-04;
const pS5: f64 = 3.47933107596021167570e-05;
const qS1: f64 = -2.40339491173441421878e+00;
const qS2: f64 = 2.02094576023350569471e+00;
const qS3: f64 = -6.88283971605453293030e-01;
const qS4: f64 = 7.70381505559019352791e-02;
const p = z * (pS0 + z * (pS1 + z * (pS2 + z * (pS3 + z * (pS4 + z * pS5)))));
const q = 1.0 + z * (qS1 + z * (qS2 + z * (qS3 + z * qS4)));
return p / q;
}
fn acos64(x: f64) f64 {
const pio2_hi: f64 = 1.57079632679489655800e+00;
const pio2_lo: f64 = 6.12323399573676603587e-17;
const ux = @bitCast(u64, x);
const hx = @intCast(u32, ux >> 32);
const ix = hx & 0x7FFFFFFF;
// |x| >= 1 or nan
if (ix >= 0x3FF00000) {
const lx = @intCast(u32, ux & 0xFFFFFFFF);
// acos(1) = 0, acos(-1) = pi
if ((ix - 0x3FF00000) | lx == 0) {
if (hx >> 31 != 0) {
return 2 * pio2_hi + 0x1.0p-120;
} else {
return 0;
}
}
return math.nan(f32);
}
// |x| < 0.5
if (ix < 0x3FE00000) {
// |x| < 2^(-57)
if (ix <= 0x3C600000) {
return pio2_hi + 0x1.0p-120;
} else {
return pio2_hi - (x - (pio2_lo - x * r64(x * x)));
}
}
// x < -0.5
if (hx >> 31 != 0) {
const z = (1.0 + x) * 0.5;
const s = math.sqrt(z);
const w = r64(z) * s - pio2_lo;
return 2 * (pio2_hi - (s + w));
}
// x > 0.5
const z = (1.0 - x) * 0.5;
const s = math.sqrt(z);
const jx = @bitCast(u64, s);
const df = @bitCast(f64, jx & 0xFFFFFFFF00000000);
const c = (z - df * df) / (s + df);
const w = r64(z) * s + c;
return 2 * (df + w);
}
test "math.acos" {
expect(acos(f32(0.0)) == acos32(0.0));
expect(acos(f64(0.0)) == acos64(0.0));
}
test "math.acos32" {
const epsilon = 0.000001;
expect(math.approxEq(f32, acos32(0.0), 1.570796, epsilon));
expect(math.approxEq(f32, acos32(0.2), 1.369438, epsilon));
expect(math.approxEq(f32, acos32(0.3434), 1.220262, epsilon));
expect(math.approxEq(f32, acos32(0.5), 1.047198, epsilon));
expect(math.approxEq(f32, acos32(0.8923), 0.468382, epsilon));
expect(math.approxEq(f32, acos32(-0.2), 1.772154, epsilon));
}
test "math.acos64" {
const epsilon = 0.000001;
expect(math.approxEq(f64, acos64(0.0), 1.570796, epsilon));
expect(math.approxEq(f64, acos64(0.2), 1.369438, epsilon));
expect(math.approxEq(f64, acos64(0.3434), 1.220262, epsilon));
expect(math.approxEq(f64, acos64(0.5), 1.047198, epsilon));
expect(math.approxEq(f64, acos64(0.8923), 0.468382, epsilon));
expect(math.approxEq(f64, acos64(-0.2), 1.772154, epsilon));
}
test "math.acos32.special" {
expect(math.isNan(acos32(-2)));
expect(math.isNan(acos32(1.5)));
}
test "math.acos64.special" {
expect(math.isNan(acos64(-2)));
expect(math.isNan(acos64(1.5)));
} | std/math/acos.zig |
const Emit = @This();
const std = @import("std");
const math = std.math;
const Mir = @import("Mir.zig");
const bits = @import("bits.zig");
const link = @import("../../link.zig");
const Module = @import("../../Module.zig");
const ErrorMsg = Module.ErrorMsg;
const assert = std.debug.assert;
const DW = std.dwarf;
const leb128 = std.leb;
const Instruction = bits.Instruction;
const Register = bits.Register;
const log = std.log.scoped(.aarch64_emit);
const DebugInfoOutput = @import("../../codegen.zig").DebugInfoOutput;
mir: Mir,
bin_file: *link.File,
debug_output: DebugInfoOutput,
target: *const std.Target,
err_msg: ?*ErrorMsg = null,
src_loc: Module.SrcLoc,
code: *std.ArrayList(u8),
prev_di_line: u32,
prev_di_column: u32,
/// Relative to the beginning of `code`.
prev_di_pc: usize,
/// The branch type of every branch
branch_types: std.AutoHashMapUnmanaged(Mir.Inst.Index, BranchType) = .{},
/// For every forward branch, maps the target instruction to a list of
/// branches which branch to this target instruction
branch_forward_origins: std.AutoHashMapUnmanaged(Mir.Inst.Index, std.ArrayListUnmanaged(Mir.Inst.Index)) = .{},
/// For backward branches: stores the code offset of the target
/// instruction
///
/// For forward branches: stores the code offset of the branch
/// instruction
code_offset_mapping: std.AutoHashMapUnmanaged(Mir.Inst.Index, usize) = .{},
stack_size: u32,
const InnerError = error{
OutOfMemory,
EmitFail,
};
const BranchType = enum {
cbz,
b_cond,
unconditional_branch_immediate,
fn default(tag: Mir.Inst.Tag) BranchType {
return switch (tag) {
.cbz => .cbz,
.b, .bl => .unconditional_branch_immediate,
.b_cond => .b_cond,
else => unreachable,
};
}
};
pub fn emitMir(
emit: *Emit,
) !void {
const mir_tags = emit.mir.instructions.items(.tag);
// Find smallest lowerings for branch instructions
try emit.lowerBranches();
// Emit machine code
for (mir_tags) |tag, index| {
const inst = @intCast(u32, index);
switch (tag) {
.add_immediate => try emit.mirAddSubtractImmediate(inst),
.cmp_immediate => try emit.mirAddSubtractImmediate(inst),
.sub_immediate => try emit.mirAddSubtractImmediate(inst),
.b_cond => try emit.mirConditionalBranchImmediate(inst),
.b => try emit.mirBranch(inst),
.bl => try emit.mirBranch(inst),
.cbz => try emit.mirCompareAndBranch(inst),
.blr => try emit.mirUnconditionalBranchRegister(inst),
.ret => try emit.mirUnconditionalBranchRegister(inst),
.brk => try emit.mirExceptionGeneration(inst),
.svc => try emit.mirExceptionGeneration(inst),
.call_extern => try emit.mirCallExtern(inst),
.add_shifted_register => try emit.mirAddSubtractShiftedRegister(inst),
.cmp_shifted_register => try emit.mirAddSubtractShiftedRegister(inst),
.sub_shifted_register => try emit.mirAddSubtractShiftedRegister(inst),
.cset => try emit.mirConditionalSelect(inst),
.dbg_line => try emit.mirDbgLine(inst),
.dbg_prologue_end => try emit.mirDebugPrologueEnd(),
.dbg_epilogue_begin => try emit.mirDebugEpilogueBegin(),
.eor_shifted_register => try emit.mirLogicalShiftedRegister(inst),
.load_memory_got => try emit.mirLoadMemoryPie(inst),
.load_memory_direct => try emit.mirLoadMemoryPie(inst),
.load_memory_ptr_got => try emit.mirLoadMemoryPie(inst),
.load_memory_ptr_direct => try emit.mirLoadMemoryPie(inst),
.ldp => try emit.mirLoadStoreRegisterPair(inst),
.stp => try emit.mirLoadStoreRegisterPair(inst),
.ldr_stack => try emit.mirLoadStoreStack(inst),
.ldrb_stack => try emit.mirLoadStoreStack(inst),
.ldrh_stack => try emit.mirLoadStoreStack(inst),
.str_stack => try emit.mirLoadStoreStack(inst),
.strb_stack => try emit.mirLoadStoreStack(inst),
.strh_stack => try emit.mirLoadStoreStack(inst),
.ldr_register => try emit.mirLoadStoreRegisterRegister(inst),
.ldrb_register => try emit.mirLoadStoreRegisterRegister(inst),
.ldrh_register => try emit.mirLoadStoreRegisterRegister(inst),
.str_register => try emit.mirLoadStoreRegisterRegister(inst),
.strb_register => try emit.mirLoadStoreRegisterRegister(inst),
.strh_register => try emit.mirLoadStoreRegisterRegister(inst),
.ldr_immediate => try emit.mirLoadStoreRegisterImmediate(inst),
.ldrb_immediate => try emit.mirLoadStoreRegisterImmediate(inst),
.ldrh_immediate => try emit.mirLoadStoreRegisterImmediate(inst),
.str_immediate => try emit.mirLoadStoreRegisterImmediate(inst),
.strb_immediate => try emit.mirLoadStoreRegisterImmediate(inst),
.strh_immediate => try emit.mirLoadStoreRegisterImmediate(inst),
.mov_register => try emit.mirMoveRegister(inst),
.mov_to_from_sp => try emit.mirMoveRegister(inst),
.mvn => try emit.mirMoveRegister(inst),
.movk => try emit.mirMoveWideImmediate(inst),
.movz => try emit.mirMoveWideImmediate(inst),
.mul => try emit.mirDataProcessing3Source(inst),
.nop => try emit.mirNop(),
.push_regs => try emit.mirPushPopRegs(inst),
.pop_regs => try emit.mirPushPopRegs(inst),
}
}
}
pub fn deinit(emit: *Emit) void {
var iter = emit.branch_forward_origins.valueIterator();
while (iter.next()) |origin_list| {
origin_list.deinit(emit.bin_file.allocator);
}
emit.branch_types.deinit(emit.bin_file.allocator);
emit.branch_forward_origins.deinit(emit.bin_file.allocator);
emit.code_offset_mapping.deinit(emit.bin_file.allocator);
emit.* = undefined;
}
fn optimalBranchType(emit: *Emit, tag: Mir.Inst.Tag, offset: i64) !BranchType {
assert(offset & 0b11 == 0);
switch (tag) {
.cbz => {
if (std.math.cast(i19, @shrExact(offset, 2))) |_| {
return BranchType.cbz;
} else |_| {
return emit.fail("TODO support cbz branches larger than +-1 MiB", .{});
}
},
.b, .bl => {
if (std.math.cast(i26, @shrExact(offset, 2))) |_| {
return BranchType.unconditional_branch_immediate;
} else |_| {
return emit.fail("TODO support unconditional branches larger than +-128 MiB", .{});
}
},
.b_cond => {
if (std.math.cast(i19, @shrExact(offset, 2))) |_| {
return BranchType.b_cond;
} else |_| {
return emit.fail("TODO support conditional branches larger than +-1 MiB", .{});
}
},
else => unreachable,
}
}
fn instructionSize(emit: *Emit, inst: Mir.Inst.Index) usize {
const tag = emit.mir.instructions.items(.tag)[inst];
if (isBranch(tag)) {
switch (emit.branch_types.get(inst).?) {
.cbz,
.unconditional_branch_immediate,
.b_cond,
=> return 4,
}
}
switch (tag) {
.load_memory_direct => return 3 * 4,
.load_memory_got,
.load_memory_ptr_got,
.load_memory_ptr_direct,
=> return 2 * 4,
.pop_regs, .push_regs => {
const reg_list = emit.mir.instructions.items(.data)[inst].reg_list;
const number_of_regs = @popCount(u32, reg_list);
const number_of_insts = std.math.divCeil(u6, number_of_regs, 2) catch unreachable;
return number_of_insts * 4;
},
.call_extern => return 4,
.dbg_line,
.dbg_epilogue_begin,
.dbg_prologue_end,
=> return 0,
else => return 4,
}
}
fn isBranch(tag: Mir.Inst.Tag) bool {
return switch (tag) {
.cbz,
.b,
.bl,
.b_cond,
=> true,
else => false,
};
}
fn branchTarget(emit: *Emit, inst: Mir.Inst.Index) Mir.Inst.Index {
const tag = emit.mir.instructions.items(.tag)[inst];
switch (tag) {
.cbz => return emit.mir.instructions.items(.data)[inst].r_inst.inst,
.b, .bl => return emit.mir.instructions.items(.data)[inst].inst,
.b_cond => return emit.mir.instructions.items(.data)[inst].inst_cond.inst,
else => unreachable,
}
}
fn lowerBranches(emit: *Emit) !void {
const mir_tags = emit.mir.instructions.items(.tag);
const allocator = emit.bin_file.allocator;
// First pass: Note down all branches and their target
// instructions, i.e. populate branch_types,
// branch_forward_origins, and code_offset_mapping
//
// TODO optimization opportunity: do this in codegen while
// generating MIR
for (mir_tags) |tag, index| {
const inst = @intCast(u32, index);
if (isBranch(tag)) {
const target_inst = emit.branchTarget(inst);
// Remember this branch instruction
try emit.branch_types.put(allocator, inst, BranchType.default(tag));
// Forward branches require some extra stuff: We only
// know their offset once we arrive at the target
// instruction. Therefore, we need to be able to
// access the branch instruction when we visit the
// target instruction in order to manipulate its type
// etc.
if (target_inst > inst) {
// Remember the branch instruction index
try emit.code_offset_mapping.put(allocator, inst, 0);
if (emit.branch_forward_origins.getPtr(target_inst)) |origin_list| {
try origin_list.append(allocator, inst);
} else {
var origin_list: std.ArrayListUnmanaged(Mir.Inst.Index) = .{};
try origin_list.append(allocator, inst);
try emit.branch_forward_origins.put(allocator, target_inst, origin_list);
}
}
// Remember the target instruction index so that we
// update the real code offset in all future passes
//
// putNoClobber may not be used as the put operation
// may clobber the entry when multiple branches branch
// to the same target instruction
try emit.code_offset_mapping.put(allocator, target_inst, 0);
}
}
// Further passes: Until all branches are lowered, interate
// through all instructions and calculate new offsets and
// potentially new branch types
var all_branches_lowered = false;
while (!all_branches_lowered) {
all_branches_lowered = true;
var current_code_offset: usize = 0;
for (mir_tags) |tag, index| {
const inst = @intCast(u32, index);
// If this instruction contained in the code offset
// mapping (when it is a target of a branch or if it is a
// forward branch), update the code offset
if (emit.code_offset_mapping.getPtr(inst)) |offset| {
offset.* = current_code_offset;
}
// If this instruction is a backward branch, calculate the
// offset, which may potentially update the branch type
if (isBranch(tag)) {
const target_inst = emit.branchTarget(inst);
if (target_inst < inst) {
const target_offset = emit.code_offset_mapping.get(target_inst).?;
const offset = @intCast(i64, target_offset) - @intCast(i64, current_code_offset);
const branch_type = emit.branch_types.getPtr(inst).?;
const optimal_branch_type = try emit.optimalBranchType(tag, offset);
if (branch_type.* != optimal_branch_type) {
branch_type.* = optimal_branch_type;
all_branches_lowered = false;
}
log.debug("lowerBranches: branch {} has offset {}", .{ inst, offset });
}
}
// If this instruction is the target of one or more
// forward branches, calculate the offset, which may
// potentially update the branch type
if (emit.branch_forward_origins.get(inst)) |origin_list| {
for (origin_list.items) |forward_branch_inst| {
const branch_tag = emit.mir.instructions.items(.tag)[forward_branch_inst];
const forward_branch_inst_offset = emit.code_offset_mapping.get(forward_branch_inst).?;
const offset = @intCast(i64, current_code_offset) - @intCast(i64, forward_branch_inst_offset);
const branch_type = emit.branch_types.getPtr(forward_branch_inst).?;
const optimal_branch_type = try emit.optimalBranchType(branch_tag, offset);
if (branch_type.* != optimal_branch_type) {
branch_type.* = optimal_branch_type;
all_branches_lowered = false;
}
log.debug("lowerBranches: branch {} has offset {}", .{ forward_branch_inst, offset });
}
}
// Increment code offset
current_code_offset += emit.instructionSize(inst);
}
}
}
fn writeInstruction(emit: *Emit, instruction: Instruction) !void {
const endian = emit.target.cpu.arch.endian();
std.mem.writeInt(u32, try emit.code.addManyAsArray(4), instruction.toU32(), endian);
}
fn fail(emit: *Emit, comptime format: []const u8, args: anytype) InnerError {
@setCold(true);
assert(emit.err_msg == null);
emit.err_msg = try ErrorMsg.create(emit.bin_file.allocator, emit.src_loc, format, args);
return error.EmitFail;
}
fn moveImmediate(emit: *Emit, reg: Register, imm64: u64) !void {
try emit.writeInstruction(Instruction.movz(reg, @truncate(u16, imm64), 0));
if (imm64 > math.maxInt(u16)) {
try emit.writeInstruction(Instruction.movk(reg, @truncate(u16, imm64 >> 16), 16));
}
if (imm64 > math.maxInt(u32)) {
try emit.writeInstruction(Instruction.movk(reg, @truncate(u16, imm64 >> 32), 32));
}
if (imm64 > math.maxInt(u48)) {
try emit.writeInstruction(Instruction.movk(reg, @truncate(u16, imm64 >> 48), 48));
}
}
fn dbgAdvancePCAndLine(self: *Emit, line: u32, column: u32) !void {
const delta_line = @intCast(i32, line) - @intCast(i32, self.prev_di_line);
const delta_pc: usize = self.code.items.len - self.prev_di_pc;
switch (self.debug_output) {
.dwarf => |dbg_out| {
// TODO Look into using the DWARF special opcodes to compress this data.
// It lets you emit single-byte opcodes that add different numbers to
// both the PC and the line number at the same time.
try dbg_out.dbg_line.ensureUnusedCapacity(11);
dbg_out.dbg_line.appendAssumeCapacity(DW.LNS.advance_pc);
leb128.writeULEB128(dbg_out.dbg_line.writer(), delta_pc) catch unreachable;
if (delta_line != 0) {
dbg_out.dbg_line.appendAssumeCapacity(DW.LNS.advance_line);
leb128.writeILEB128(dbg_out.dbg_line.writer(), delta_line) catch unreachable;
}
dbg_out.dbg_line.appendAssumeCapacity(DW.LNS.copy);
self.prev_di_pc = self.code.items.len;
self.prev_di_line = line;
self.prev_di_column = column;
self.prev_di_pc = self.code.items.len;
},
.plan9 => |dbg_out| {
if (delta_pc <= 0) return; // only do this when the pc changes
// we have already checked the target in the linker to make sure it is compatable
const quant = @import("../../link/Plan9/aout.zig").getPCQuant(self.target.cpu.arch) catch unreachable;
// increasing the line number
try @import("../../link/Plan9.zig").changeLine(dbg_out.dbg_line, delta_line);
// increasing the pc
const d_pc_p9 = @intCast(i64, delta_pc) - quant;
if (d_pc_p9 > 0) {
// minus one because if its the last one, we want to leave space to change the line which is one quanta
try dbg_out.dbg_line.append(@intCast(u8, @divExact(d_pc_p9, quant) + 128) - quant);
if (dbg_out.pcop_change_index.*) |pci|
dbg_out.dbg_line.items[pci] += 1;
dbg_out.pcop_change_index.* = @intCast(u32, dbg_out.dbg_line.items.len - 1);
} else if (d_pc_p9 == 0) {
// we don't need to do anything, because adding the quant does it for us
} else unreachable;
if (dbg_out.start_line.* == null)
dbg_out.start_line.* = self.prev_di_line;
dbg_out.end_line.* = line;
// only do this if the pc changed
self.prev_di_line = line;
self.prev_di_column = column;
self.prev_di_pc = self.code.items.len;
},
.none => {},
}
}
fn mirAddSubtractImmediate(emit: *Emit, inst: Mir.Inst.Index) !void {
const tag = emit.mir.instructions.items(.tag)[inst];
switch (tag) {
.add_immediate,
.sub_immediate,
=> {
const rr_imm12_sh = emit.mir.instructions.items(.data)[inst].rr_imm12_sh;
const rd = rr_imm12_sh.rd;
const rn = rr_imm12_sh.rn;
const imm12 = rr_imm12_sh.imm12;
const sh = rr_imm12_sh.sh == 1;
switch (tag) {
.add_immediate => try emit.writeInstruction(Instruction.add(rd, rn, imm12, sh)),
.sub_immediate => try emit.writeInstruction(Instruction.sub(rd, rn, imm12, sh)),
else => unreachable,
}
},
.cmp_immediate => {
const r_imm12_sh = emit.mir.instructions.items(.data)[inst].r_imm12_sh;
const rn = r_imm12_sh.rn;
const imm12 = r_imm12_sh.imm12;
const sh = r_imm12_sh.sh == 1;
try emit.writeInstruction(Instruction.subs(.xzr, rn, imm12, sh));
},
else => unreachable,
}
}
fn mirConditionalBranchImmediate(emit: *Emit, inst: Mir.Inst.Index) !void {
const tag = emit.mir.instructions.items(.tag)[inst];
const inst_cond = emit.mir.instructions.items(.data)[inst].inst_cond;
const offset = @intCast(i64, emit.code_offset_mapping.get(inst_cond.inst).?) - @intCast(i64, emit.code.items.len);
const branch_type = emit.branch_types.get(inst).?;
log.debug("mirConditionalBranchImmediate: {} offset={}", .{ inst, offset });
switch (branch_type) {
.b_cond => switch (tag) {
.b_cond => try emit.writeInstruction(Instruction.bCond(inst_cond.cond, @intCast(i21, offset))),
else => unreachable,
},
else => unreachable,
}
}
fn mirBranch(emit: *Emit, inst: Mir.Inst.Index) !void {
const tag = emit.mir.instructions.items(.tag)[inst];
const target_inst = emit.mir.instructions.items(.data)[inst].inst;
log.debug("branch {}(tag: {}) -> {}(tag: {})", .{
inst,
tag,
target_inst,
emit.mir.instructions.items(.tag)[target_inst],
});
const offset = @intCast(i64, emit.code_offset_mapping.get(target_inst).?) - @intCast(i64, emit.code.items.len);
const branch_type = emit.branch_types.get(inst).?;
log.debug("mirBranch: {} offset={}", .{ inst, offset });
switch (branch_type) {
.unconditional_branch_immediate => switch (tag) {
.b => try emit.writeInstruction(Instruction.b(@intCast(i28, offset))),
.bl => try emit.writeInstruction(Instruction.bl(@intCast(i28, offset))),
else => unreachable,
},
else => unreachable,
}
}
fn mirCompareAndBranch(emit: *Emit, inst: Mir.Inst.Index) !void {
const tag = emit.mir.instructions.items(.tag)[inst];
const r_inst = emit.mir.instructions.items(.data)[inst].r_inst;
const offset = @intCast(i64, emit.code_offset_mapping.get(r_inst.inst).?) - @intCast(i64, emit.code.items.len);
const branch_type = emit.branch_types.get(inst).?;
log.debug("mirCompareAndBranch: {} offset={}", .{ inst, offset });
switch (branch_type) {
.cbz => switch (tag) {
.cbz => try emit.writeInstruction(Instruction.cbz(r_inst.rt, @intCast(i21, offset))),
else => unreachable,
},
else => unreachable,
}
}
fn mirUnconditionalBranchRegister(emit: *Emit, inst: Mir.Inst.Index) !void {
const tag = emit.mir.instructions.items(.tag)[inst];
const reg = emit.mir.instructions.items(.data)[inst].reg;
switch (tag) {
.blr => try emit.writeInstruction(Instruction.blr(reg)),
.ret => try emit.writeInstruction(Instruction.ret(reg)),
else => unreachable,
}
}
fn mirExceptionGeneration(emit: *Emit, inst: Mir.Inst.Index) !void {
const tag = emit.mir.instructions.items(.tag)[inst];
const imm16 = emit.mir.instructions.items(.data)[inst].imm16;
switch (tag) {
.brk => try emit.writeInstruction(Instruction.brk(imm16)),
.svc => try emit.writeInstruction(Instruction.svc(imm16)),
else => unreachable,
}
}
fn mirDbgLine(emit: *Emit, inst: Mir.Inst.Index) !void {
const tag = emit.mir.instructions.items(.tag)[inst];
const dbg_line_column = emit.mir.instructions.items(.data)[inst].dbg_line_column;
switch (tag) {
.dbg_line => try emit.dbgAdvancePCAndLine(dbg_line_column.line, dbg_line_column.column),
else => unreachable,
}
}
fn mirDebugPrologueEnd(self: *Emit) !void {
switch (self.debug_output) {
.dwarf => |dbg_out| {
try dbg_out.dbg_line.append(DW.LNS.set_prologue_end);
try self.dbgAdvancePCAndLine(self.prev_di_line, self.prev_di_column);
},
.plan9 => {},
.none => {},
}
}
fn mirDebugEpilogueBegin(self: *Emit) !void {
switch (self.debug_output) {
.dwarf => |dbg_out| {
try dbg_out.dbg_line.append(DW.LNS.set_epilogue_begin);
try self.dbgAdvancePCAndLine(self.prev_di_line, self.prev_di_column);
},
.plan9 => {},
.none => {},
}
}
fn mirCallExtern(emit: *Emit, inst: Mir.Inst.Index) !void {
assert(emit.mir.instructions.items(.tag)[inst] == .call_extern);
const extern_fn = emit.mir.instructions.items(.data)[inst].extern_fn;
if (emit.bin_file.cast(link.File.MachO)) |macho_file| {
const offset = blk: {
const offset = @intCast(u32, emit.code.items.len);
// bl
try emit.writeInstruction(Instruction.bl(0));
break :blk offset;
};
// Add relocation to the decl.
const atom = macho_file.atom_by_index_table.get(extern_fn.atom_index).?;
try atom.relocs.append(emit.bin_file.allocator, .{
.offset = offset,
.target = .{ .global = extern_fn.sym_name },
.addend = 0,
.subtractor = null,
.pcrel = true,
.length = 2,
.@"type" = @enumToInt(std.macho.reloc_type_arm64.ARM64_RELOC_BRANCH26),
});
} else {
return emit.fail("Implement call_extern for linking backends != MachO", .{});
}
}
fn mirAddSubtractShiftedRegister(emit: *Emit, inst: Mir.Inst.Index) !void {
const tag = emit.mir.instructions.items(.tag)[inst];
const rrr_imm6_shift = emit.mir.instructions.items(.data)[inst].rrr_imm6_shift;
const rd = rrr_imm6_shift.rd;
const rn = rrr_imm6_shift.rn;
const rm = rrr_imm6_shift.rm;
const shift = rrr_imm6_shift.shift;
const imm6 = rrr_imm6_shift.imm6;
switch (tag) {
.add_shifted_register => try emit.writeInstruction(Instruction.addShiftedRegister(rd, rn, rm, shift, imm6)),
.cmp_shifted_register => try emit.writeInstruction(Instruction.subsShiftedRegister(rd, rn, rm, shift, imm6)),
.sub_shifted_register => try emit.writeInstruction(Instruction.subShiftedRegister(rd, rn, rm, shift, imm6)),
else => unreachable,
}
}
fn mirConditionalSelect(emit: *Emit, inst: Mir.Inst.Index) !void {
const tag = emit.mir.instructions.items(.tag)[inst];
switch (tag) {
.cset => {
const r_cond = emit.mir.instructions.items(.data)[inst].r_cond;
try emit.writeInstruction(Instruction.csinc(r_cond.rd, .xzr, .xzr, r_cond.cond));
},
else => unreachable,
}
}
fn mirLogicalShiftedRegister(emit: *Emit, inst: Mir.Inst.Index) !void {
const tag = emit.mir.instructions.items(.tag)[inst];
const rrr_imm6_logical_shift = emit.mir.instructions.items(.data)[inst].rrr_imm6_logical_shift;
const rd = rrr_imm6_logical_shift.rd;
const rn = rrr_imm6_logical_shift.rn;
const rm = rrr_imm6_logical_shift.rm;
const shift = rrr_imm6_logical_shift.shift;
const imm6 = rrr_imm6_logical_shift.imm6;
switch (tag) {
.eor_shifted_register => try emit.writeInstruction(Instruction.eor(rd, rn, rm, shift, imm6)),
else => unreachable,
}
}
fn mirLoadMemoryPie(emit: *Emit, inst: Mir.Inst.Index) !void {
const tag = emit.mir.instructions.items(.tag)[inst];
const payload = emit.mir.instructions.items(.data)[inst].payload;
const data = emit.mir.extraData(Mir.LoadMemoryPie, payload).data;
const reg = @intToEnum(Register, data.register);
// PC-relative displacement to the entry in memory.
// adrp
const offset = @intCast(u32, emit.code.items.len);
try emit.writeInstruction(Instruction.adrp(reg, 0));
switch (tag) {
.load_memory_got => {
// ldr reg, reg, offset
try emit.writeInstruction(Instruction.ldr(
reg,
reg,
Instruction.LoadStoreOffset.imm(0),
));
},
.load_memory_direct => {
// We cannot load the offset directly as it may not be aligned properly.
// For example, load for 64bit register will require the target address offset
// to be 8-byte aligned, while the value might have non-8-byte natural alignment,
// meaning the linker might have put it at a non-8-byte aligned address. To circumvent
// this, we use `adrp, add` to form the address value which we then dereference with
// `ldr`.
// Note that this can potentially be optimised out by the codegen/linker if the
// target address is appropriately aligned.
// add reg, reg, offset
try emit.writeInstruction(Instruction.add(reg, reg, 0, false));
// ldr reg, reg, offset
try emit.writeInstruction(Instruction.ldr(
reg,
reg,
Instruction.LoadStoreOffset.imm(0),
));
},
.load_memory_ptr_got,
.load_memory_ptr_direct,
=> {
// add reg, reg, offset
try emit.writeInstruction(Instruction.add(reg, reg, 0, false));
},
else => unreachable,
}
if (emit.bin_file.cast(link.File.MachO)) |macho_file| {
const atom = macho_file.atom_by_index_table.get(data.atom_index).?;
// Page reloc for adrp instruction.
try atom.relocs.append(emit.bin_file.allocator, .{
.offset = offset,
.target = .{ .local = data.sym_index },
.addend = 0,
.subtractor = null,
.pcrel = true,
.length = 2,
.@"type" = switch (tag) {
.load_memory_got,
.load_memory_ptr_got,
=> @enumToInt(std.macho.reloc_type_arm64.ARM64_RELOC_GOT_LOAD_PAGE21),
.load_memory_direct,
.load_memory_ptr_direct,
=> @enumToInt(std.macho.reloc_type_arm64.ARM64_RELOC_PAGE21),
else => unreachable,
},
});
// Pageoff reloc for adrp instruction.
try atom.relocs.append(emit.bin_file.allocator, .{
.offset = offset + 4,
.target = .{ .local = data.sym_index },
.addend = 0,
.subtractor = null,
.pcrel = false,
.length = 2,
.@"type" = switch (tag) {
.load_memory_got,
.load_memory_ptr_got,
=> @enumToInt(std.macho.reloc_type_arm64.ARM64_RELOC_GOT_LOAD_PAGEOFF12),
.load_memory_direct,
.load_memory_ptr_direct,
=> @enumToInt(std.macho.reloc_type_arm64.ARM64_RELOC_PAGEOFF12),
else => unreachable,
},
});
} else {
return emit.fail("TODO implement load_memory for PIE GOT indirection on this platform", .{});
}
}
fn mirLoadStoreRegisterPair(emit: *Emit, inst: Mir.Inst.Index) !void {
const tag = emit.mir.instructions.items(.tag)[inst];
const load_store_register_pair = emit.mir.instructions.items(.data)[inst].load_store_register_pair;
const rt = load_store_register_pair.rt;
const rt2 = load_store_register_pair.rt2;
const rn = load_store_register_pair.rn;
const offset = load_store_register_pair.offset;
switch (tag) {
.stp => try emit.writeInstruction(Instruction.stp(rt, rt2, rn, offset)),
.ldp => try emit.writeInstruction(Instruction.ldp(rt, rt2, rn, offset)),
else => unreachable,
}
}
fn mirLoadStoreStack(emit: *Emit, inst: Mir.Inst.Index) !void {
const tag = emit.mir.instructions.items(.tag)[inst];
const load_store_stack = emit.mir.instructions.items(.data)[inst].load_store_stack;
const rt = load_store_stack.rt;
const raw_offset = emit.stack_size - load_store_stack.offset;
const offset = switch (tag) {
.ldrb_stack, .strb_stack => blk: {
if (math.cast(u12, raw_offset)) |imm| {
break :blk Instruction.LoadStoreOffset.imm(imm);
} else |_| {
return emit.fail("TODO load/store stack byte with larger offset", .{});
}
},
.ldrh_stack, .strh_stack => blk: {
assert(std.mem.isAlignedGeneric(u32, raw_offset, 2)); // misaligned stack entry
if (math.cast(u12, @divExact(raw_offset, 2))) |imm| {
break :blk Instruction.LoadStoreOffset.imm(imm);
} else |_| {
return emit.fail("TODO load/store stack halfword with larger offset", .{});
}
},
.ldr_stack, .str_stack => blk: {
const alignment: u32 = switch (rt.size()) {
32 => 4,
64 => 8,
else => unreachable,
};
assert(std.mem.isAlignedGeneric(u32, raw_offset, alignment)); // misaligned stack entry
if (math.cast(u12, @divExact(raw_offset, alignment))) |imm| {
break :blk Instruction.LoadStoreOffset.imm(imm);
} else |_| {
return emit.fail("TODO load/store stack with larger offset", .{});
}
},
else => unreachable,
};
switch (tag) {
.ldr_stack => try emit.writeInstruction(Instruction.ldr(rt, .sp, offset)),
.ldrb_stack => try emit.writeInstruction(Instruction.ldrb(rt, .sp, offset)),
.ldrh_stack => try emit.writeInstruction(Instruction.ldrh(rt, .sp, offset)),
.str_stack => try emit.writeInstruction(Instruction.str(rt, .sp, offset)),
.strb_stack => try emit.writeInstruction(Instruction.strb(rt, .sp, offset)),
.strh_stack => try emit.writeInstruction(Instruction.strh(rt, .sp, offset)),
else => unreachable,
}
}
fn mirLoadStoreRegisterImmediate(emit: *Emit, inst: Mir.Inst.Index) !void {
const tag = emit.mir.instructions.items(.tag)[inst];
const load_store_register_immediate = emit.mir.instructions.items(.data)[inst].load_store_register_immediate;
const rt = load_store_register_immediate.rt;
const rn = load_store_register_immediate.rn;
const offset = Instruction.LoadStoreOffset{ .immediate = load_store_register_immediate.offset };
switch (tag) {
.ldr_immediate => try emit.writeInstruction(Instruction.ldr(rt, rn, offset)),
.ldrb_immediate => try emit.writeInstruction(Instruction.ldrb(rt, rn, offset)),
.ldrh_immediate => try emit.writeInstruction(Instruction.ldrh(rt, rn, offset)),
.str_immediate => try emit.writeInstruction(Instruction.str(rt, rn, offset)),
.strb_immediate => try emit.writeInstruction(Instruction.strb(rt, rn, offset)),
.strh_immediate => try emit.writeInstruction(Instruction.strh(rt, rn, offset)),
else => unreachable,
}
}
fn mirLoadStoreRegisterRegister(emit: *Emit, inst: Mir.Inst.Index) !void {
const tag = emit.mir.instructions.items(.tag)[inst];
const load_store_register_register = emit.mir.instructions.items(.data)[inst].load_store_register_register;
const rt = load_store_register_register.rt;
const rn = load_store_register_register.rn;
const offset = Instruction.LoadStoreOffset{ .register = load_store_register_register.offset };
switch (tag) {
.ldr_register => try emit.writeInstruction(Instruction.ldr(rt, rn, offset)),
.ldrb_register => try emit.writeInstruction(Instruction.ldrb(rt, rn, offset)),
.ldrh_register => try emit.writeInstruction(Instruction.ldrh(rt, rn, offset)),
.str_register => try emit.writeInstruction(Instruction.str(rt, rn, offset)),
.strb_register => try emit.writeInstruction(Instruction.strb(rt, rn, offset)),
.strh_register => try emit.writeInstruction(Instruction.strh(rt, rn, offset)),
else => unreachable,
}
}
fn mirMoveRegister(emit: *Emit, inst: Mir.Inst.Index) !void {
const tag = emit.mir.instructions.items(.tag)[inst];
switch (tag) {
.mov_register => {
const rr = emit.mir.instructions.items(.data)[inst].rr;
try emit.writeInstruction(Instruction.orr(rr.rd, .xzr, rr.rn, .lsl, 0));
},
.mov_to_from_sp => {
const rr = emit.mir.instructions.items(.data)[inst].rr;
try emit.writeInstruction(Instruction.add(rr.rd, rr.rn, 0, false));
},
.mvn => {
const rr_imm6_shift = emit.mir.instructions.items(.data)[inst].rr_imm6_shift;
try emit.writeInstruction(Instruction.orn(rr_imm6_shift.rd, .xzr, rr_imm6_shift.rm, .lsl, 0));
},
else => unreachable,
}
}
fn mirMoveWideImmediate(emit: *Emit, inst: Mir.Inst.Index) !void {
const tag = emit.mir.instructions.items(.tag)[inst];
const r_imm16_sh = emit.mir.instructions.items(.data)[inst].r_imm16_sh;
switch (tag) {
.movz => try emit.writeInstruction(Instruction.movz(r_imm16_sh.rd, r_imm16_sh.imm16, @as(u6, r_imm16_sh.hw) << 4)),
.movk => try emit.writeInstruction(Instruction.movk(r_imm16_sh.rd, r_imm16_sh.imm16, @as(u6, r_imm16_sh.hw) << 4)),
else => unreachable,
}
}
fn mirDataProcessing3Source(emit: *Emit, inst: Mir.Inst.Index) !void {
const tag = emit.mir.instructions.items(.tag)[inst];
const rrr = emit.mir.instructions.items(.data)[inst].rrr;
switch (tag) {
.mul => try emit.writeInstruction(Instruction.mul(rrr.rd, rrr.rn, rrr.rm)),
else => unreachable,
}
}
fn mirNop(emit: *Emit) !void {
try emit.writeInstruction(Instruction.nop());
}
fn mirPushPopRegs(emit: *Emit, inst: Mir.Inst.Index) !void {
const tag = emit.mir.instructions.items(.tag)[inst];
const reg_list = emit.mir.instructions.items(.data)[inst].reg_list;
if (reg_list & @as(u32, 1) << 31 != 0) return emit.fail("xzr is not a valid register for {}", .{tag});
// sp must be aligned at all times, so we only use stp and ldp
// instructions for minimal instruction count. However, if we do
// not have an even number of registers, we use str and ldr
const number_of_regs = @popCount(u32, reg_list);
switch (tag) {
.pop_regs => {
var i: u6 = 32;
var count: u6 = 0;
var other_reg: Register = undefined;
while (i > 0) : (i -= 1) {
const reg = @intToEnum(Register, i - 1);
if (reg_list & @as(u32, 1) << @intCast(u5, reg.id()) != 0) {
if (count % 2 == 0) {
if (count == number_of_regs - 1) {
try emit.writeInstruction(Instruction.ldr(
reg,
.sp,
Instruction.LoadStoreOffset.imm_post_index(16),
));
} else {
other_reg = reg;
}
} else {
try emit.writeInstruction(Instruction.ldp(
reg,
other_reg,
.sp,
Instruction.LoadStorePairOffset.post_index(16),
));
}
count += 1;
}
}
assert(count == number_of_regs);
},
.push_regs => {
var i: u6 = 0;
var count: u6 = 0;
var other_reg: Register = undefined;
while (i < 32) : (i += 1) {
const reg = @intToEnum(Register, i);
if (reg_list & @as(u32, 1) << @intCast(u5, reg.id()) != 0) {
if (count % 2 == 0) {
if (count == number_of_regs - 1) {
try emit.writeInstruction(Instruction.str(
reg,
.sp,
Instruction.LoadStoreOffset.imm_pre_index(-16),
));
} else {
other_reg = reg;
}
} else {
try emit.writeInstruction(Instruction.stp(
other_reg,
reg,
.sp,
Instruction.LoadStorePairOffset.pre_index(-16),
));
}
count += 1;
}
}
assert(count == number_of_regs);
},
else => unreachable,
}
} | src/arch/aarch64/Emit.zig |
const std = @import("std");
const core = @import("../core.zig");
const debug = std.debug;
const fs = std.fs;
const io = std.io;
const math = std.math;
const mem = std.mem;
const os = std.os;
pub const History = core.List(core.Text);
pub const File = struct {
path: []const u8,
stat: ?os.Stat,
};
pub const Editor = struct {
allocator: *mem.Allocator,
history: History,
history_pos: usize = 0,
on_disk_pos: usize = 0,
copy_pos: usize = 0,
file: ?File = null,
pub fn fromString(allocator: *mem.Allocator, str: []const u8) !Editor {
var res = Editor{
.allocator = allocator,
.history = History{ .allocator = allocator },
};
const t = try core.Text.fromString(allocator, str);
res.history = try res.history.append(t);
return res;
}
pub fn fromFile(allocator: *mem.Allocator, path: []const u8) !Editor {
const file = fs.cwd().openFile(path, .{}) catch |err| switch (err) {
error.FileNotFound => {
var res = try fromString(allocator, "");
res.file = File{
.path = path,
.stat = null,
};
return res;
},
else => |err2| return err2,
};
defer file.close();
const stat = try os.fstat(file.handle);
var res = if (stat.size == 0)
try Editor.fromString(allocator, "")
else blk: {
const content = try os.mmap(null, @intCast(usize, stat.size), os.PROT_READ, os.MAP_PRIVATE, file.handle, 0);
defer os.munmap(content);
break :blk try Editor.fromString(allocator, content);
};
res.file = File{
.path = path,
.stat = stat,
};
return res;
}
pub fn save(editor: Editor) !Editor {
if (!editor.dirty())
return editor;
const editor_file = editor.file orelse return error.NoFile;
const file = try fs.cwd().openFile(editor_file.path, .{ .write = true });
defer file.close();
const curr = editor.current();
const out_stream = file.outStream();
var buf_out_stream = io.bufferedOutStream(out_stream);
const Stream = @TypeOf(buf_out_stream.outStream());
try curr.content.foreach(0, buf_out_stream.outStream(), struct {
fn each(stream: Stream, i: usize, item: u8) !void {
try stream.writeByte(item);
}
}.each);
try buf_out_stream.flush();
var res = editor;
res.on_disk_pos = res.history_pos;
return res;
}
pub fn addUndo(editor: Editor, t: core.Text) !Editor {
if (t.equal(editor.current()))
return editor;
var res = editor;
debug.assert(res.history_pos < res.history.len());
res.history_pos = res.history.len();
res.history = try res.history.append(t);
return res;
}
pub fn current(editor: Editor) core.Text {
return editor.history.at(editor.history_pos);
}
pub fn onDisk(editor: Editor) core.Text {
return editor.history.at(editor.on_disk_pos);
}
pub fn copied(editor: Editor) core.Text {
return editor.history.at(editor.copy_pos);
}
pub fn undo(editor: Editor) !Editor {
const curr = editor.current();
var res = editor;
while (res.history_pos != 0) {
res.history_pos -= 1;
const prev = res.current();
if (!curr.content.equal(prev.content))
break;
}
res.history = try res.history.append(res.current());
return res;
}
pub fn dirty(editor: Editor) bool {
return !core.Text.Content.equal(editor.onDisk().content, editor.current().content);
}
pub fn copy(editor: Editor) Editor {
var res = editor;
res.copy_pos = res.history_pos;
return res;
}
pub fn copyClipboard(editor: Editor) !void {
const allocator = editor.allocator;
const text = editor.current();
const proc = try core.clipboard.copy(allocator);
errdefer _ = proc.kill() catch undefined;
var file_out = proc.stdin.?.outStream();
var buf_out = io.bufferedOutStream(file_out);
const Stream = @TypeOf(buf_out.outStream());
const Context = struct {
stream: Stream,
text: core.Text,
end: usize = 0,
};
try text.cursors.foreach(
0,
Context{
.stream = buf_out.outStream(),
.text = text,
},
struct {
fn each(c: Context, i: usize, cursor: core.Cursor) !void {
if (i != 0)
try c.stream.writeAll("\n");
var new_c = c;
new_c.end = cursor.end().index;
c.text.content.foreach(
cursor.start().index,
new_c,
struct {
fn each2(context: Context, j: usize, char: u8) !void {
if (j == context.end)
return error.Break;
try context.stream.writeAll(&[_]u8{char});
}
}.each2,
) catch |err| switch (err) {
error.Break => {},
else => |err2| return err2,
};
}
}.each,
);
try buf_out.flush();
proc.stdin.?.close();
proc.stdin = null;
const term = try proc.wait();
}
pub fn pasteClipboard(editor: Editor) !Editor {
const allocator = editor.allocator;
var res = editor;
var text = res.current();
const proc = try core.clipboard.paste(allocator);
errdefer _ = proc.kill() catch undefined;
var file_out = proc.stdout.?.inStream();
const str = try file_out.readAllAlloc(allocator, 1024 * 1024 * 512);
switch (try proc.wait()) {
.Exited => |status| {
if (status != 0)
return error.CopyFailed;
},
else => return error.CopyFailed,
}
text = try text.paste(str);
res = try res.addUndo(text);
return res;
}
}; | src/core/editor.zig |
const std = @import("std");
const common = @import("common.zig");
const slimy = @import("slimy.zig");
const zc = @import("zcompute");
const log = std.log.scoped(.gpu);
pub fn search(
params: slimy.SearchParams,
callback_context: anytype,
comptime resultCallback: fn (@TypeOf(callback_context), slimy.Result) void,
comptime progressCallback: ?fn (@TypeOf(callback_context), completed: u64, total: u64) void,
) !void {
var ctx = Context{};
try ctx.init();
defer ctx.deinit();
try ctx.search(params, callback_context, resultCallback, progressCallback);
}
pub const Context = struct {
inited: bool = false,
ctx: zc.Context = undefined,
shad: Shader = undefined,
buffers: [2]ResultBuffers = undefined,
buf_idx: u1 = 0,
const Shader = zc.Shader(&.{
zc.pushConstant("params", 0, GpuParams),
zc.storageBuffer("result_count", 0, zc.Buffer(u32)),
zc.storageBuffer("results", 1, zc.Buffer(slimy.Result)),
});
pub fn init(self: *Context) !void {
var arena = std.heap.ArenaAllocator.init(std.heap.page_allocator);
defer arena.deinit();
self.ctx = zc.Context.init(arena.allocator(), .{}) catch |err| {
log.err("Vulkan init error: {s}", .{@errorName(err)});
return error.VulkanInit;
};
self.shad = Shader.initBytes(arena.allocator(), &self.ctx, @embedFile("shader/search.spv")) catch |err| {
log.err("Shader init error: {s}", .{@errorName(err)});
return error.ShaderInit;
};
errdefer self.shad.deinit();
// Result buffers - two of these so we can double-buffer
self.buffers[0] = ResultBuffers.init(&self.ctx) catch |err| {
log.err("Buffer 0 init error: {s}", .{@errorName(err)});
return error.BufferInit;
};
errdefer self.buffers[0].deinit();
self.buffers[1] = ResultBuffers.init(&self.ctx) catch |err| {
log.err("Buffer 1 init error: {s}", .{@errorName(err)});
return error.BufferInit;
};
errdefer self.buffers[1].deinit();
log.debug("init ok", .{});
self.inited = true;
}
pub fn deinit(self: Context) void {
self.buffers[0].deinit();
self.buffers[1].deinit();
self.shad.deinit();
self.ctx.deinit();
}
pub fn search(
self: *Context,
params: slimy.SearchParams,
callback_context: anytype,
comptime resultCallback: fn (@TypeOf(callback_context), slimy.Result) void,
comptime progressCallback: ?fn (@TypeOf(callback_context), completed: u64, total: u64) void,
) !void {
std.debug.assert(self.inited);
log.debug("start search", .{});
const useed = @bitCast(u64, params.world_seed);
const gpu_params = GpuParams{
.world_seed = .{
@intCast(u32, useed >> 32),
@truncate(u32, useed),
},
.offset = .{ params.x0, params.z0 },
.threshold = params.threshold,
};
const search_size = [2]u32{
@intCast(u32, @as(i33, params.x1) - params.x0),
@intCast(u32, @as(i33, params.z1) - params.z0),
};
var z: u32 = 0;
while (z < search_size[1]) : (z += batch_size[1]) {
const batch_z = @minimum(search_size[1] - z, batch_size[1]);
var x: u32 = 0;
while (x < search_size[0]) : (x += batch_size[0]) {
const batch_x = @minimum(search_size[0] - x, batch_size[0]);
if (progressCallback) |cb| {
const chunk_index = x + z * @as(u64, search_size[0]);
cb(callback_context, chunk_index, @as(u64, search_size[0]) * search_size[1]);
}
self.shad.exec(std.time.ns_per_s, .{
.x = batch_x,
.y = batch_z,
.baseX = x,
.baseY = z,
}, .{
.params = gpu_params,
.result_count = self.buffers[self.buf_idx].count,
.results = self.buffers[self.buf_idx].results,
}) catch |err| switch (err) {
error.Timeout => return error.Timeout,
else => return error.ShaderExec,
};
self.buf_idx ^= 1;
if (x != 0 or z != 0) { // If we're the first batch, there are no previous results to report
try self.buffers[self.buf_idx].report(callback_context, resultCallback);
}
}
}
if (!(self.shad.waitTimeout(std.time.ns_per_s) catch return error.ShaderExec)) {
return error.Timeout;
}
self.buf_idx ^= 1;
try self.buffers[self.buf_idx].report(callback_context, resultCallback);
}
};
const ResultBuffers = struct {
count: zc.Buffer(u32),
results: zc.Buffer(slimy.Result),
fn init(ctx: *zc.Context) !ResultBuffers {
const count = try zc.Buffer(u32).init(ctx, 1, .{ .map = true, .storage = true });
errdefer count.deinit();
(try count.map())[0] = 0;
count.unmap();
const results = try zc.Buffer(slimy.Result).init(ctx, batch_size[0] * batch_size[1], .{
.map = true,
.storage = true,
});
errdefer results.deinit();
return ResultBuffers{ .count = count, .results = results };
}
fn deinit(self: ResultBuffers) void {
self.results.deinit();
self.count.deinit();
}
fn report(
self: ResultBuffers,
callback_context: anytype,
comptime resultCallback: fn (@TypeOf(callback_context), slimy.Result) void,
) !void {
const count_mem = self.count.map() catch return error.MemoryMapFailed;
const count = count_mem[0];
count_mem[0] = 0;
self.count.unmap();
const result_mem = self.results.map() catch return error.MemoryMapFailed;
for (result_mem[0..count]) |res| {
resultCallback(callback_context, res);
}
self.results.unmap();
}
};
const batch_size = [2]u32{ 1024, 1024 };
const GpuParams = extern struct {
world_seed: [2]u32,
offset: [2]i32,
threshold: i32,
}; | src/gpu.zig |
pub const ptrdiff_t = c_long;
pub const wchar_t = c_int;
pub const max_align_t = extern struct {
__clang_max_align_nonce1: c_longlong,
__clang_max_align_nonce2: c_longdouble,
};
pub extern fn memcpy(__dest: ?*c_void, __src: ?*const c_void, __n: c_ulong) ?*c_void;
pub extern fn memmove(__dest: ?*c_void, __src: ?*const c_void, __n: c_ulong) ?*c_void;
pub extern fn memccpy(noalias __dest: ?*c_void, noalias __src: ?*const c_void, __c: c_int, __n: usize) ?*c_void;
pub extern fn memset(__s: ?*c_void, __c: c_int, __n: c_ulong) ?*c_void;
pub extern fn memcmp(__s1: ?*const c_void, __s2: ?*const c_void, __n: c_ulong) c_int;
pub extern fn memchr(__s: ?*const c_void, __c: c_int, __n: c_ulong) ?*c_void;
pub extern fn strcpy(__dest: ?[*]u8, __src: ?[*]const u8) ?[*]u8;
pub extern fn strncpy(__dest: ?[*]u8, __src: ?[*]const u8, __n: c_ulong) ?[*]u8;
pub extern fn strcat(__dest: ?[*]u8, __src: ?[*]const u8) ?[*]u8;
pub extern fn strncat(__dest: ?[*]u8, __src: ?[*]const u8, __n: c_ulong) ?[*]u8;
pub extern fn strcmp(__s1: ?[*]const u8, __s2: ?[*]const u8) c_int;
pub extern fn strncmp(__s1: ?[*]const u8, __s2: ?[*]const u8, __n: c_ulong) c_int;
pub extern fn strcoll(__s1: ?[*]const u8, __s2: ?[*]const u8) c_int;
pub extern fn strxfrm(__dest: ?[*]u8, __src: ?[*]const u8, __n: c_ulong) c_ulong;
pub const struct___locale_data = @OpaqueType();
pub const struct___locale_struct = extern struct {
__locales: [13](?*struct___locale_data),
__ctype_b: ?[*]const c_ushort,
__ctype_tolower: ?[*]const c_int,
__ctype_toupper: ?[*]const c_int,
__names: [13](?[*]const u8),
};
pub const __locale_t = ?[*]struct___locale_struct;
pub const locale_t = __locale_t;
pub extern fn strcoll_l(__s1: ?[*]const u8, __s2: ?[*]const u8, __l: locale_t) c_int;
pub extern fn strxfrm_l(__dest: ?[*]u8, __src: ?[*]const u8, __n: usize, __l: locale_t) usize;
pub extern fn strdup(__s: ?[*]const u8) ?[*]u8;
pub extern fn strndup(__string: ?[*]const u8, __n: c_ulong) ?[*]u8;
pub extern fn strchr(__s: ?[*]const u8, __c: c_int) ?[*]u8;
pub extern fn strrchr(__s: ?[*]const u8, __c: c_int) ?[*]u8;
pub extern fn strcspn(__s: ?[*]const u8, __reject: ?[*]const u8) c_ulong;
pub extern fn strspn(__s: ?[*]const u8, __accept: ?[*]const u8) c_ulong;
pub extern fn strpbrk(__s: ?[*]const u8, __accept: ?[*]const u8) ?[*]u8;
pub extern fn strstr(__haystack: ?[*]const u8, __needle: ?[*]const u8) ?[*]u8;
pub extern fn strtok(__s: ?[*]u8, __delim: ?[*]const u8) ?[*]u8;
pub extern fn __strtok_r(noalias __s: ?[*]u8, noalias __delim: ?[*]const u8, noalias __save_ptr: ?[*](?[*]u8)) ?[*]u8;
pub extern fn strtok_r(noalias __s: ?[*]u8, noalias __delim: ?[*]const u8, noalias __save_ptr: ?[*](?[*]u8)) ?[*]u8;
pub extern fn strlen(__s: ?[*]const u8) c_ulong;
pub extern fn strnlen(__string: ?[*]const u8, __maxlen: usize) usize;
pub extern fn strerror(__errnum: c_int) ?[*]u8;
pub extern fn strerror_r(__errnum: c_int, __buf: ?[*]u8, __buflen: usize) c_int;
pub extern fn strerror_l(__errnum: c_int, __l: locale_t) ?[*]u8;
pub extern fn bcmp(__s1: ?*const c_void, __s2: ?*const c_void, __n: usize) c_int;
pub extern fn bcopy(__src: ?*const c_void, __dest: ?*c_void, __n: usize) void;
pub extern fn bzero(__s: ?*c_void, __n: c_ulong) void;
pub extern fn index(__s: ?[*]const u8, __c: c_int) ?[*]u8;
pub extern fn rindex(__s: ?[*]const u8, __c: c_int) ?[*]u8;
pub extern fn ffs(__i: c_int) c_int;
pub extern fn ffsl(__l: c_long) c_int;
pub extern fn ffsll(__ll: c_longlong) c_int;
pub extern fn strcasecmp(__s1: ?[*]const u8, __s2: ?[*]const u8) c_int;
pub extern fn strncasecmp(__s1: ?[*]const u8, __s2: ?[*]const u8, __n: c_ulong) c_int;
pub extern fn strcasecmp_l(__s1: ?[*]const u8, __s2: ?[*]const u8, __loc: locale_t) c_int;
pub extern fn strncasecmp_l(__s1: ?[*]const u8, __s2: ?[*]const u8, __n: usize, __loc: locale_t) c_int;
pub extern fn explicit_bzero(__s: ?*c_void, __n: usize) void;
pub extern fn strsep(noalias __stringp: ?[*](?[*]u8), noalias __delim: ?[*]const u8) ?[*]u8;
pub extern fn strsignal(__sig: c_int) ?[*]u8;
pub extern fn __stpcpy(noalias __dest: ?[*]u8, noalias __src: ?[*]const u8) ?[*]u8;
pub extern fn stpcpy(__dest: ?[*]u8, __src: ?[*]const u8) ?[*]u8;
pub extern fn __stpncpy(noalias __dest: ?[*]u8, noalias __src: ?[*]const u8, __n: usize) ?[*]u8;
pub extern fn stpncpy(__dest: ?[*]u8, __src: ?[*]const u8, __n: c_ulong) ?[*]u8;
pub const struct___va_list_tag = extern struct {
gp_offset: c_uint,
fp_offset: c_uint,
overflow_arg_area: ?*c_void,
reg_save_area: ?*c_void,
};
pub const __builtin_va_list = [1]struct___va_list_tag;
pub const va_list = __builtin_va_list;
pub const __gnuc_va_list = __builtin_va_list;
pub const __u_char = u8;
pub const __u_short = c_ushort;
pub const __u_int = c_uint;
pub const __u_long = c_ulong;
pub const __int8_t = i8;
pub const __uint8_t = u8;
pub const __int16_t = c_short;
pub const __uint16_t = c_ushort;
pub const __int32_t = c_int;
pub const __uint32_t = c_uint;
pub const __int64_t = c_long;
pub const __uint64_t = c_ulong;
pub const __int_least8_t = __int8_t;
pub const __uint_least8_t = __uint8_t;
pub const __int_least16_t = __int16_t;
pub const __uint_least16_t = __uint16_t;
pub const __int_least32_t = __int32_t;
pub const __uint_least32_t = __uint32_t;
pub const __int_least64_t = __int64_t;
pub const __uint_least64_t = __uint64_t;
pub const __quad_t = c_long;
pub const __u_quad_t = c_ulong;
pub const __intmax_t = c_long;
pub const __uintmax_t = c_ulong;
pub const __dev_t = c_ulong;
pub const __uid_t = c_uint;
pub const __gid_t = c_uint;
pub const __ino_t = c_ulong;
pub const __ino64_t = c_ulong;
pub const __mode_t = c_uint;
pub const __nlink_t = c_ulong;
pub const __off_t = c_long;
pub const __off64_t = c_long;
pub const __pid_t = c_int;
pub const __fsid_t = extern struct {
__val: [2]c_int,
};
pub const __clock_t = c_long;
pub const __rlim_t = c_ulong;
pub const __rlim64_t = c_ulong;
pub const __id_t = c_uint;
pub const __time_t = c_long;
pub const __useconds_t = c_uint;
pub const __suseconds_t = c_long;
pub const __daddr_t = c_int;
pub const __key_t = c_int;
pub const __clockid_t = c_int;
pub const __timer_t = ?*c_void;
pub const __blksize_t = c_long;
pub const __blkcnt_t = c_long;
pub const __blkcnt64_t = c_long;
pub const __fsblkcnt_t = c_ulong;
pub const __fsblkcnt64_t = c_ulong;
pub const __fsfilcnt_t = c_ulong;
pub const __fsfilcnt64_t = c_ulong;
pub const __fsword_t = c_long;
pub const __ssize_t = c_long;
pub const __syscall_slong_t = c_long;
pub const __syscall_ulong_t = c_ulong;
pub const __loff_t = __off64_t;
pub const __caddr_t = ?[*]u8;
pub const __intptr_t = c_long;
pub const __socklen_t = c_uint;
pub const __sig_atomic_t = c_int;
pub const __mbstate_t = extern struct {
__count: c_int,
__value: extern union {
__wch: c_uint,
__wchb: [4]u8,
},
};
pub const struct__G_fpos_t = extern struct {
__pos: __off_t,
__state: __mbstate_t,
};
pub const __fpos_t = struct__G_fpos_t;
pub const struct__G_fpos64_t = extern struct {
__pos: __off64_t,
__state: __mbstate_t,
};
pub const __fpos64_t = struct__G_fpos64_t;
pub const struct__IO_marker = @OpaqueType();
pub const _IO_lock_t = c_void;
pub const struct__IO_codecvt = @OpaqueType();
pub const struct__IO_wide_data = @OpaqueType();
pub const struct__IO_FILE = extern struct {
_flags: c_int,
_IO_read_ptr: ?[*]u8,
_IO_read_end: ?[*]u8,
_IO_read_base: ?[*]u8,
_IO_write_base: ?[*]u8,
_IO_write_ptr: ?[*]u8,
_IO_write_end: ?[*]u8,
_IO_buf_base: ?[*]u8,
_IO_buf_end: ?[*]u8,
_IO_save_base: ?[*]u8,
_IO_backup_base: ?[*]u8,
_IO_save_end: ?[*]u8,
_markers: ?*struct__IO_marker,
_chain: ?[*]struct__IO_FILE,
_fileno: c_int,
_flags2: c_int,
_old_offset: __off_t,
_cur_column: c_ushort,
_vtable_offset: i8,
_shortbuf: [1]u8,
_lock: ?*_IO_lock_t,
_offset: __off64_t,
_codecvt: ?*struct__IO_codecvt,
_wide_data: ?*struct__IO_wide_data,
_freeres_list: ?[*]struct__IO_FILE,
_freeres_buf: ?*c_void,
__pad5: usize,
_mode: c_int,
_unused2: [20]u8,
};
pub const __FILE = struct__IO_FILE;
pub const FILE = struct__IO_FILE;
pub const off_t = __off_t;
pub const fpos_t = __fpos_t;
pub extern var stdin: ?[*]FILE;
pub extern var stdout: ?[*]FILE;
pub extern var stderr: ?[*]FILE;
pub extern fn remove(__filename: ?[*]const u8) c_int;
pub extern fn rename(__old: ?[*]const u8, __new: ?[*]const u8) c_int;
pub extern fn renameat(__oldfd: c_int, __old: ?[*]const u8, __newfd: c_int, __new: ?[*]const u8) c_int;
pub extern fn tmpfile() ?[*]FILE;
pub extern fn tmpnam(__s: ?[*]u8) ?[*]u8;
pub extern fn tmpnam_r(__s: ?[*]u8) ?[*]u8;
pub extern fn tempnam(__dir: ?[*]const u8, __pfx: ?[*]const u8) ?[*]u8;
pub extern fn fclose(__stream: ?[*]FILE) c_int;
pub extern fn fflush(__stream: ?[*]FILE) c_int;
pub extern fn fflush_unlocked(__stream: ?[*]FILE) c_int;
pub extern fn fopen(__filename: ?[*]const u8, __modes: ?[*]const u8) ?[*]FILE;
pub extern fn freopen(noalias __filename: ?[*]const u8, noalias __modes: ?[*]const u8, noalias __stream: ?[*]FILE) ?[*]FILE;
pub extern fn fdopen(__fd: c_int, __modes: ?[*]const u8) ?[*]FILE;
pub extern fn fmemopen(__s: ?*c_void, __len: usize, __modes: ?[*]const u8) ?[*]FILE;
pub extern fn open_memstream(__bufloc: ?[*](?[*]u8), __sizeloc: ?[*]usize) ?[*]FILE;
pub extern fn setbuf(noalias __stream: ?[*]FILE, noalias __buf: ?[*]u8) void;
pub extern fn setvbuf(noalias __stream: ?[*]FILE, noalias __buf: ?[*]u8, __modes: c_int, __n: usize) c_int;
pub extern fn setbuffer(noalias __stream: ?[*]FILE, noalias __buf: ?[*]u8, __size: usize) void;
pub extern fn setlinebuf(__stream: ?[*]FILE) void;
pub extern fn fprintf(__stream: ?[*]FILE, __format: ?[*]const u8) c_int;
pub extern fn printf(__format: ?[*]const u8) c_int;
pub extern fn sprintf(__s: ?[*]u8, __format: ?[*]const u8) c_int;
pub extern fn vfprintf(__s: ?[*]FILE, __format: ?[*]const u8, __arg: ?[*]struct___va_list_tag) c_int;
pub extern fn vprintf(__format: ?[*]const u8, __arg: ?[*]struct___va_list_tag) c_int;
pub extern fn vsprintf(__s: ?[*]u8, __format: ?[*]const u8, __arg: ?[*]struct___va_list_tag) c_int;
pub extern fn snprintf(__s: ?[*]u8, __maxlen: c_ulong, __format: ?[*]const u8) c_int;
pub extern fn vsnprintf(__s: ?[*]u8, __maxlen: c_ulong, __format: ?[*]const u8, __arg: ?[*]struct___va_list_tag) c_int;
pub extern fn vdprintf(__fd: c_int, noalias __fmt: ?[*]const u8, __arg: ?[*]struct___va_list_tag) c_int;
pub extern fn dprintf(__fd: c_int, noalias __fmt: ?[*]const u8) c_int;
pub extern fn fscanf(noalias __stream: ?[*]FILE, noalias __format: ?[*]const u8) c_int;
pub extern fn scanf(noalias __format: ?[*]const u8) c_int;
pub extern fn sscanf(noalias __s: ?[*]const u8, noalias __format: ?[*]const u8) c_int;
pub extern fn vfscanf(noalias __s: ?[*]FILE, noalias __format: ?[*]const u8, __arg: ?[*]struct___va_list_tag) c_int;
pub extern fn vscanf(noalias __format: ?[*]const u8, __arg: ?[*]struct___va_list_tag) c_int;
pub extern fn vsscanf(noalias __s: ?[*]const u8, noalias __format: ?[*]const u8, __arg: ?[*]struct___va_list_tag) c_int;
pub extern fn fgetc(__stream: ?[*]FILE) c_int;
pub extern fn getc(__stream: ?[*]FILE) c_int;
pub extern fn getchar() c_int;
pub extern fn getc_unlocked(__stream: ?[*]FILE) c_int;
pub extern fn getchar_unlocked() c_int;
pub extern fn fgetc_unlocked(__stream: ?[*]FILE) c_int;
pub extern fn fputc(__c: c_int, __stream: ?[*]FILE) c_int;
pub extern fn putc(__c: c_int, __stream: ?[*]FILE) c_int;
pub extern fn putchar(__c: c_int) c_int;
pub extern fn fputc_unlocked(__c: c_int, __stream: ?[*]FILE) c_int;
pub extern fn putc_unlocked(__c: c_int, __stream: ?[*]FILE) c_int;
pub extern fn putchar_unlocked(__c: c_int) c_int;
pub extern fn getw(__stream: ?[*]FILE) c_int;
pub extern fn putw(__w: c_int, __stream: ?[*]FILE) c_int;
pub extern fn fgets(noalias __s: ?[*]u8, __n: c_int, noalias __stream: ?[*]FILE) ?[*]u8;
pub extern fn __getdelim(noalias __lineptr: ?[*](?[*]u8), noalias __n: ?[*]usize, __delimiter: c_int, noalias __stream: ?[*]FILE) __ssize_t;
pub extern fn getdelim(noalias __lineptr: ?[*](?[*]u8), noalias __n: ?[*]usize, __delimiter: c_int, noalias __stream: ?[*]FILE) __ssize_t;
pub extern fn getline(noalias __lineptr: ?[*](?[*]u8), noalias __n: ?[*]usize, noalias __stream: ?[*]FILE) __ssize_t;
pub extern fn fputs(noalias __s: ?[*]const u8, noalias __stream: ?[*]FILE) c_int;
pub extern fn puts(__s: ?[*]const u8) c_int;
pub extern fn ungetc(__c: c_int, __stream: ?[*]FILE) c_int;
pub extern fn fread(__ptr: ?*c_void, __size: c_ulong, __n: c_ulong, __stream: ?[*]FILE) c_ulong;
pub extern fn fwrite(__ptr: ?*const c_void, __size: c_ulong, __n: c_ulong, __s: ?[*]FILE) c_ulong;
pub extern fn fread_unlocked(noalias __ptr: ?*c_void, __size: usize, __n: usize, noalias __stream: ?[*]FILE) usize;
pub extern fn fwrite_unlocked(noalias __ptr: ?*const c_void, __size: usize, __n: usize, noalias __stream: ?[*]FILE) usize;
pub extern fn fseek(__stream: ?[*]FILE, __off: c_long, __whence: c_int) c_int;
pub extern fn ftell(__stream: ?[*]FILE) c_long;
pub extern fn rewind(__stream: ?[*]FILE) void;
pub extern fn fseeko(__stream: ?[*]FILE, __off: __off_t, __whence: c_int) c_int;
pub extern fn ftello(__stream: ?[*]FILE) __off_t;
pub extern fn fgetpos(noalias __stream: ?[*]FILE, noalias __pos: ?[*]fpos_t) c_int;
pub extern fn fsetpos(__stream: ?[*]FILE, __pos: ?[*]const fpos_t) c_int;
pub extern fn clearerr(__stream: ?[*]FILE) void;
pub extern fn feof(__stream: ?[*]FILE) c_int;
pub extern fn ferror(__stream: ?[*]FILE) c_int;
pub extern fn clearerr_unlocked(__stream: ?[*]FILE) void;
pub extern fn feof_unlocked(__stream: ?[*]FILE) c_int;
pub extern fn ferror_unlocked(__stream: ?[*]FILE) c_int;
pub extern fn perror(__s: ?[*]const u8) void;
pub extern var sys_nerr: c_int;
pub extern const sys_errlist: [*]const (?[*]const u8);
pub extern fn fileno(__stream: ?[*]FILE) c_int;
pub extern fn fileno_unlocked(__stream: ?[*]FILE) c_int;
pub extern fn popen(__command: ?[*]const u8, __modes: ?[*]const u8) ?[*]FILE;
pub extern fn pclose(__stream: ?[*]FILE) c_int;
pub extern fn ctermid(__s: ?[*]u8) ?[*]u8;
pub extern fn flockfile(__stream: ?[*]FILE) void;
pub extern fn ftrylockfile(__stream: ?[*]FILE) c_int;
pub extern fn funlockfile(__stream: ?[*]FILE) void;
pub extern fn __uflow(arg0: ?[*]FILE) c_int;
pub extern fn __overflow(arg0: ?[*]FILE, arg1: c_int) c_int;
pub const _Float32 = f32;
pub const _Float64 = f64;
pub const _Float32x = f64;
pub const _Float64x = c_longdouble;
pub const div_t = extern struct {
quot: c_int,
rem: c_int,
};
pub const ldiv_t = extern struct {
quot: c_long,
rem: c_long,
};
pub const lldiv_t = extern struct {
quot: c_longlong,
rem: c_longlong,
};
pub extern fn __ctype_get_mb_cur_max() usize;
pub extern fn atof(__nptr: ?[*]const u8) f64;
pub extern fn atoi(__nptr: ?[*]const u8) c_int;
pub extern fn atol(__nptr: ?[*]const u8) c_long;
pub extern fn atoll(__nptr: ?[*]const u8) c_longlong;
pub extern fn strtod(__nptr: ?[*]const u8, __endptr: ?[*](?[*]u8)) f64;
pub extern fn strtof(__nptr: ?[*]const u8, __endptr: ?[*](?[*]u8)) f32;
pub extern fn strtold(__nptr: ?[*]const u8, __endptr: ?[*](?[*]u8)) c_longdouble;
pub extern fn strtol(__nptr: ?[*]const u8, __endptr: ?[*](?[*]u8), __base: c_int) c_long;
pub extern fn strtoul(__nptr: ?[*]const u8, __endptr: ?[*](?[*]u8), __base: c_int) c_ulong;
pub extern fn strtoq(noalias __nptr: ?[*]const u8, noalias __endptr: ?[*](?[*]u8), __base: c_int) c_longlong;
pub extern fn strtouq(noalias __nptr: ?[*]const u8, noalias __endptr: ?[*](?[*]u8), __base: c_int) c_ulonglong;
pub extern fn strtoll(__nptr: ?[*]const u8, __endptr: ?[*](?[*]u8), __base: c_int) c_longlong;
pub extern fn strtoull(__nptr: ?[*]const u8, __endptr: ?[*](?[*]u8), __base: c_int) c_ulonglong;
pub extern fn l64a(__n: c_long) ?[*]u8;
pub extern fn a64l(__s: ?[*]const u8) c_long;
pub const u_char = __u_char;
pub const u_short = __u_short;
pub const u_int = __u_int;
pub const u_long = __u_long;
pub const quad_t = __quad_t;
pub const u_quad_t = __u_quad_t;
pub const fsid_t = __fsid_t;
pub const loff_t = __loff_t;
pub const ino_t = __ino_t;
pub const dev_t = __dev_t;
pub const gid_t = __gid_t;
pub const mode_t = __mode_t;
pub const nlink_t = __nlink_t;
pub const uid_t = __uid_t;
pub const pid_t = __pid_t;
pub const id_t = __id_t;
pub const daddr_t = __daddr_t;
pub const caddr_t = __caddr_t;
pub const key_t = __key_t;
pub const clock_t = __clock_t;
pub const clockid_t = __clockid_t;
pub const time_t = __time_t;
pub const timer_t = __timer_t;
pub const ulong = c_ulong;
pub const ushort = c_ushort;
pub const uint = c_uint;
pub const u_int8_t = u8;
pub const u_int16_t = c_ushort;
pub const u_int32_t = c_uint;
pub const u_int64_t = c_ulong;
pub const register_t = c_long;
pub fn __bswap_16(__bsx: __uint16_t) __uint16_t {
return __uint16_t(((c_int(__bsx) >> @import("std").math.Log2Int(c_int)(8)) & 255) | ((c_int(__bsx) & 255) << @import("std").math.Log2Int(c_int)(8)));
}
pub fn __bswap_32(__bsx: __uint32_t) __uint32_t {
return ((((__bsx & -16777216) >> @import("std").math.Log2Int(c_uint)(24)) | ((__bsx & 16711680) >> @import("std").math.Log2Int(c_uint)(8))) | ((__bsx & 65280) << @import("std").math.Log2Int(c_uint)(8))) | ((__bsx & 255) << @import("std").math.Log2Int(c_uint)(24));
}
pub fn __bswap_64(__bsx: __uint64_t) __uint64_t {
return __uint64_t(((((((((c_ulonglong(__bsx) & -72057594037927936) >> @import("std").math.Log2Int(c_ulonglong)(56)) | ((c_ulonglong(__bsx) & 71776119061217280) >> @import("std").math.Log2Int(c_ulonglong)(40))) | ((c_ulonglong(__bsx) & 280375465082880) >> @import("std").math.Log2Int(c_ulonglong)(24))) | ((c_ulonglong(__bsx) & 1095216660480) >> @import("std").math.Log2Int(c_ulonglong)(8))) | ((c_ulonglong(__bsx) & 4278190080) << @import("std").math.Log2Int(c_ulonglong)(8))) | ((c_ulonglong(__bsx) & 16711680) << @import("std").math.Log2Int(c_ulonglong)(24))) | ((c_ulonglong(__bsx) & 65280) << @import("std").math.Log2Int(c_ulonglong)(40))) | ((c_ulonglong(__bsx) & 255) << @import("std").math.Log2Int(c_ulonglong)(56)));
}
pub fn __uint16_identity(__x: __uint16_t) __uint16_t {
return __x;
}
pub fn __uint32_identity(__x: __uint32_t) __uint32_t {
return __x;
}
pub fn __uint64_identity(__x: __uint64_t) __uint64_t {
return __x;
}
pub const __sigset_t = extern struct {
__val: [16]c_ulong,
};
pub const sigset_t = __sigset_t;
pub const struct_timeval = extern struct {
tv_sec: __time_t,
tv_usec: __suseconds_t,
};
pub const struct_timespec = extern struct {
tv_sec: __time_t,
tv_nsec: __syscall_slong_t,
};
pub const suseconds_t = __suseconds_t;
pub const __fd_mask = c_long;
pub const fd_set = extern struct {
__fds_bits: [16]__fd_mask,
};
pub const fd_mask = __fd_mask;
pub extern fn select(__nfds: c_int, noalias __readfds: ?[*]fd_set, noalias __writefds: ?[*]fd_set, noalias __exceptfds: ?[*]fd_set, noalias __timeout: ?[*]struct_timeval) c_int;
pub extern fn pselect(__nfds: c_int, noalias __readfds: ?[*]fd_set, noalias __writefds: ?[*]fd_set, noalias __exceptfds: ?[*]fd_set, noalias __timeout: ?[*]const struct_timespec, noalias __sigmask: ?[*]const __sigset_t) c_int;
pub const blksize_t = __blksize_t;
pub const blkcnt_t = __blkcnt_t;
pub const fsblkcnt_t = __fsblkcnt_t;
pub const fsfilcnt_t = __fsfilcnt_t;
pub const struct___pthread_rwlock_arch_t = extern struct {
__readers: c_uint,
__writers: c_uint,
__wrphase_futex: c_uint,
__writers_futex: c_uint,
__pad3: c_uint,
__pad4: c_uint,
__cur_writer: c_int,
__shared: c_int,
__rwelision: i8,
__pad1: [7]u8,
__pad2: c_ulong,
__flags: c_uint,
};
pub const struct___pthread_internal_list = extern struct {
__prev: ?[*]struct___pthread_internal_list,
__next: ?[*]struct___pthread_internal_list,
};
pub const __pthread_list_t = struct___pthread_internal_list;
pub const struct___pthread_mutex_s = extern struct {
__lock: c_int,
__count: c_uint,
__owner: c_int,
__nusers: c_uint,
__kind: c_int,
__spins: c_short,
__elision: c_short,
__list: __pthread_list_t,
};
pub const struct___pthread_cond_s = extern struct {
@"": extern union {
__wseq: c_ulonglong,
__wseq32: extern struct {
__low: c_uint,
__high: c_uint,
},
},
@"": extern union {
__g1_start: c_ulonglong,
__g1_start32: extern struct {
__low: c_uint,
__high: c_uint,
},
},
__g_refs: [2]c_uint,
__g_size: [2]c_uint,
__g1_orig_size: c_uint,
__wrefs: c_uint,
__g_signals: [2]c_uint,
};
pub const pthread_t = c_ulong;
pub const pthread_mutexattr_t = extern union {
__size: [4]u8,
__align: c_int,
};
pub const pthread_condattr_t = extern union {
__size: [4]u8,
__align: c_int,
};
pub const pthread_key_t = c_uint;
pub const pthread_once_t = c_int;
pub const union_pthread_attr_t = extern union {
__size: [56]u8,
__align: c_long,
};
pub const pthread_attr_t = union_pthread_attr_t;
pub const pthread_mutex_t = extern union {
__data: struct___pthread_mutex_s,
__size: [40]u8,
__align: c_long,
};
pub const pthread_cond_t = extern union {
__data: struct___pthread_cond_s,
__size: [48]u8,
__align: c_longlong,
};
pub const pthread_rwlock_t = extern union {
__data: struct___pthread_rwlock_arch_t,
__size: [56]u8,
__align: c_long,
};
pub const pthread_rwlockattr_t = extern union {
__size: [8]u8,
__align: c_long,
};
pub const pthread_spinlock_t = c_int;
pub const pthread_barrier_t = extern union {
__size: [32]u8,
__align: c_long,
};
pub const pthread_barrierattr_t = extern union {
__size: [4]u8,
__align: c_int,
};
pub extern fn random() c_long;
pub extern fn srandom(__seed: c_uint) void;
pub extern fn initstate(__seed: c_uint, __statebuf: ?[*]u8, __statelen: usize) ?[*]u8;
pub extern fn setstate(__statebuf: ?[*]u8) ?[*]u8;
pub const struct_random_data = extern struct {
fptr: ?[*]i32,
rptr: ?[*]i32,
state: ?[*]i32,
rand_type: c_int,
rand_deg: c_int,
rand_sep: c_int,
end_ptr: ?[*]i32,
};
pub extern fn random_r(noalias __buf: ?[*]struct_random_data, noalias __result: ?[*]i32) c_int;
pub extern fn srandom_r(__seed: c_uint, __buf: ?[*]struct_random_data) c_int;
pub extern fn initstate_r(__seed: c_uint, noalias __statebuf: ?[*]u8, __statelen: usize, noalias __buf: ?[*]struct_random_data) c_int;
pub extern fn setstate_r(noalias __statebuf: ?[*]u8, noalias __buf: ?[*]struct_random_data) c_int;
pub extern fn rand() c_int;
pub extern fn srand(__seed: c_uint) void;
pub extern fn rand_r(__seed: ?[*]c_uint) c_int;
pub extern fn drand48() f64;
pub extern fn erand48(__xsubi: ?[*]c_ushort) f64;
pub extern fn lrand48() c_long;
pub extern fn nrand48(__xsubi: ?[*]c_ushort) c_long;
pub extern fn mrand48() c_long;
pub extern fn jrand48(__xsubi: ?[*]c_ushort) c_long;
pub extern fn srand48(__seedval: c_long) void;
pub extern fn seed48(__seed16v: ?[*]c_ushort) ?[*]c_ushort;
pub extern fn lcong48(__param: ?[*]c_ushort) void;
pub const struct_drand48_data = extern struct {
__x: [3]c_ushort,
__old_x: [3]c_ushort,
__c: c_ushort,
__init: c_ushort,
__a: c_ulonglong,
};
pub extern fn drand48_r(noalias __buffer: ?[*]struct_drand48_data, noalias __result: ?[*]f64) c_int;
pub extern fn erand48_r(__xsubi: ?[*]c_ushort, noalias __buffer: ?[*]struct_drand48_data, noalias __result: ?[*]f64) c_int;
pub extern fn lrand48_r(noalias __buffer: ?[*]struct_drand48_data, noalias __result: ?[*]c_long) c_int;
pub extern fn nrand48_r(__xsubi: ?[*]c_ushort, noalias __buffer: ?[*]struct_drand48_data, noalias __result: ?[*]c_long) c_int;
pub extern fn mrand48_r(noalias __buffer: ?[*]struct_drand48_data, noalias __result: ?[*]c_long) c_int;
pub extern fn jrand48_r(__xsubi: ?[*]c_ushort, noalias __buffer: ?[*]struct_drand48_data, noalias __result: ?[*]c_long) c_int;
pub extern fn srand48_r(__seedval: c_long, __buffer: ?[*]struct_drand48_data) c_int;
pub extern fn seed48_r(__seed16v: ?[*]c_ushort, __buffer: ?[*]struct_drand48_data) c_int;
pub extern fn lcong48_r(__param: ?[*]c_ushort, __buffer: ?[*]struct_drand48_data) c_int;
pub extern fn malloc(__size: c_ulong) ?*c_void;
pub extern fn calloc(__nmemb: c_ulong, __size: c_ulong) ?*c_void;
pub extern fn realloc(__ptr: ?*c_void, __size: c_ulong) ?*c_void;
pub extern fn free(__ptr: ?*c_void) void;
pub extern fn alloca(__size: c_ulong) ?*c_void;
pub extern fn valloc(__size: usize) ?*c_void;
pub extern fn posix_memalign(__memptr: ?[*](?*c_void), __alignment: usize, __size: usize) c_int;
pub extern fn aligned_alloc(__alignment: usize, __size: usize) ?*c_void;
pub extern fn abort() noreturn;
pub extern fn atexit(__func: ?extern fn() void) c_int;
pub extern fn at_quick_exit(__func: ?extern fn() void) c_int;
pub extern fn on_exit(__func: ?extern fn(c_int, ?*c_void) void, __arg: ?*c_void) c_int;
pub extern fn exit(__status: c_int) noreturn;
pub extern fn quick_exit(__status: c_int) noreturn;
pub extern fn _Exit(__status: c_int) noreturn;
pub extern fn getenv(__name: ?[*]const u8) ?[*]u8;
pub extern fn putenv(__string: ?[*]u8) c_int;
pub extern fn setenv(__name: ?[*]const u8, __value: ?[*]const u8, __replace: c_int) c_int;
pub extern fn unsetenv(__name: ?[*]const u8) c_int;
pub extern fn clearenv() c_int;
pub extern fn mktemp(__template: ?[*]u8) ?[*]u8;
pub extern fn mkstemp(__template: ?[*]u8) c_int;
pub extern fn mkstemps(__template: ?[*]u8, __suffixlen: c_int) c_int;
pub extern fn mkdtemp(__template: ?[*]u8) ?[*]u8;
pub extern fn system(__command: ?[*]const u8) c_int;
pub extern fn realpath(noalias __name: ?[*]const u8, noalias __resolved: ?[*]u8) ?[*]u8;
pub const __compar_fn_t = ?extern fn(?*const c_void, ?*const c_void) c_int;
pub extern fn bsearch(__key: ?*const c_void, __base: ?*const c_void, __nmemb: usize, __size: usize, __compar: __compar_fn_t) ?*c_void;
pub extern fn qsort(__base: ?*c_void, __nmemb: usize, __size: usize, __compar: __compar_fn_t) void;
pub extern fn abs(__x: c_int) c_int;
pub extern fn labs(__x: c_long) c_long;
pub extern fn llabs(__x: c_longlong) c_longlong;
pub extern fn div(__numer: c_int, __denom: c_int) div_t;
pub extern fn ldiv(__numer: c_long, __denom: c_long) ldiv_t;
pub extern fn lldiv(__numer: c_longlong, __denom: c_longlong) lldiv_t;
pub extern fn ecvt(__value: f64, __ndigit: c_int, noalias __decpt: ?[*]c_int, noalias __sign: ?[*]c_int) ?[*]u8;
pub extern fn fcvt(__value: f64, __ndigit: c_int, noalias __decpt: ?[*]c_int, noalias __sign: ?[*]c_int) ?[*]u8;
pub extern fn gcvt(__value: f64, __ndigit: c_int, __buf: ?[*]u8) ?[*]u8;
pub extern fn qecvt(__value: c_longdouble, __ndigit: c_int, noalias __decpt: ?[*]c_int, noalias __sign: ?[*]c_int) ?[*]u8;
pub extern fn qfcvt(__value: c_longdouble, __ndigit: c_int, noalias __decpt: ?[*]c_int, noalias __sign: ?[*]c_int) ?[*]u8;
pub extern fn qgcvt(__value: c_longdouble, __ndigit: c_int, __buf: ?[*]u8) ?[*]u8;
pub extern fn ecvt_r(__value: f64, __ndigit: c_int, noalias __decpt: ?[*]c_int, noalias __sign: ?[*]c_int, noalias __buf: ?[*]u8, __len: usize) c_int;
pub extern fn fcvt_r(__value: f64, __ndigit: c_int, noalias __decpt: ?[*]c_int, noalias __sign: ?[*]c_int, noalias __buf: ?[*]u8, __len: usize) c_int;
pub extern fn qecvt_r(__value: c_longdouble, __ndigit: c_int, noalias __decpt: ?[*]c_int, noalias __sign: ?[*]c_int, noalias __buf: ?[*]u8, __len: usize) c_int;
pub extern fn qfcvt_r(__value: c_longdouble, __ndigit: c_int, noalias __decpt: ?[*]c_int, noalias __sign: ?[*]c_int, noalias __buf: ?[*]u8, __len: usize) c_int;
pub extern fn mblen(__s: ?[*]const u8, __n: usize) c_int;
pub extern fn mbtowc(noalias __pwc: ?[*]wchar_t, noalias __s: ?[*]const u8, __n: usize) c_int;
pub extern fn wctomb(__s: ?[*]u8, __wchar: wchar_t) c_int;
pub extern fn mbstowcs(noalias __pwcs: ?[*]wchar_t, noalias __s: ?[*]const u8, __n: usize) usize;
pub extern fn wcstombs(noalias __s: ?[*]u8, noalias __pwcs: ?[*]const wchar_t, __n: usize) usize;
pub extern fn rpmatch(__response: ?[*]const u8) c_int;
pub extern fn getsubopt(noalias __optionp: ?[*](?[*]u8), noalias __tokens: ?[*]const (?[*]u8), noalias __valuep: ?[*](?[*]u8)) c_int;
pub extern fn getloadavg(__loadavg: ?[*]f64, __nelem: c_int) c_int;
pub const __jmp_buf = [8]c_long;
pub const struct___jmp_buf_tag = extern struct {
__jmpbuf: __jmp_buf,
__mask_was_saved: c_int,
__saved_mask: __sigset_t,
};
pub const jmp_buf = [1]struct___jmp_buf_tag;
pub extern fn setjmp(__env: ?[*]struct___jmp_buf_tag) c_int;
pub extern fn __sigsetjmp(__env: ?[*]struct___jmp_buf_tag, __savemask: c_int) c_int;
pub extern fn _setjmp(__env: ?[*]struct___jmp_buf_tag) c_int;
pub extern fn longjmp(__env: ?[*]struct___jmp_buf_tag, __val: c_int) noreturn;
pub extern fn _longjmp(__env: ?[*]struct___jmp_buf_tag, __val: c_int) noreturn;
pub const sigjmp_buf = [1]struct___jmp_buf_tag;
pub extern fn siglongjmp(__env: ?[*]struct___jmp_buf_tag, __val: c_int) noreturn;
pub const FT_Int16 = c_short;
pub const FT_UInt16 = c_ushort;
pub const FT_Int32 = c_int;
pub const FT_UInt32 = c_uint;
pub const FT_Fast = c_int;
pub const FT_UFast = c_uint;
pub const FT_Int64 = c_long;
pub const FT_UInt64 = c_ulong;
pub const FT_Memory = ?[*]struct_FT_MemoryRec_;
pub const FT_Alloc_Func = ?extern fn(FT_Memory, c_long) ?*c_void;
pub const FT_Free_Func = ?extern fn(FT_Memory, ?*c_void) void;
pub const FT_Realloc_Func = ?extern fn(FT_Memory, c_long, c_long, ?*c_void) ?*c_void;
pub const struct_FT_MemoryRec_ = extern struct {
user: ?*c_void,
alloc: FT_Alloc_Func,
free: FT_Free_Func,
realloc: FT_Realloc_Func,
};
pub const union_FT_StreamDesc_ = extern union {
value: c_long,
pointer: ?*c_void,
};
pub const FT_StreamDesc = union_FT_StreamDesc_;
pub const FT_Stream = ?[*]struct_FT_StreamRec_;
pub const FT_Stream_IoFunc = ?extern fn(FT_Stream, c_ulong, ?[*]u8, c_ulong) c_ulong;
pub const FT_Stream_CloseFunc = ?extern fn(FT_Stream) void;
pub const struct_FT_StreamRec_ = extern struct {
base: ?[*]u8,
size: c_ulong,
pos: c_ulong,
descriptor: FT_StreamDesc,
pathname: FT_StreamDesc,
read: FT_Stream_IoFunc,
close: FT_Stream_CloseFunc,
memory: FT_Memory,
cursor: ?[*]u8,
limit: ?[*]u8,
};
pub const FT_StreamRec = struct_FT_StreamRec_;
pub const FT_Pos = c_long;
pub const struct_FT_Vector_ = extern struct {
x: FT_Pos,
y: FT_Pos,
};
pub const FT_Vector = struct_FT_Vector_;
pub const struct_FT_BBox_ = extern struct {
xMin: FT_Pos,
yMin: FT_Pos,
xMax: FT_Pos,
yMax: FT_Pos,
};
pub const FT_BBox = struct_FT_BBox_;
pub const FT_PIXEL_MODE_NONE = enum_FT_Pixel_Mode_.FT_PIXEL_MODE_NONE;
pub const FT_PIXEL_MODE_MONO = enum_FT_Pixel_Mode_.FT_PIXEL_MODE_MONO;
pub const FT_PIXEL_MODE_GRAY = enum_FT_Pixel_Mode_.FT_PIXEL_MODE_GRAY;
pub const FT_PIXEL_MODE_GRAY2 = enum_FT_Pixel_Mode_.FT_PIXEL_MODE_GRAY2;
pub const FT_PIXEL_MODE_GRAY4 = enum_FT_Pixel_Mode_.FT_PIXEL_MODE_GRAY4;
pub const FT_PIXEL_MODE_LCD = enum_FT_Pixel_Mode_.FT_PIXEL_MODE_LCD;
pub const FT_PIXEL_MODE_LCD_V = enum_FT_Pixel_Mode_.FT_PIXEL_MODE_LCD_V;
pub const FT_PIXEL_MODE_BGRA = enum_FT_Pixel_Mode_.FT_PIXEL_MODE_BGRA;
pub const FT_PIXEL_MODE_MAX = enum_FT_Pixel_Mode_.FT_PIXEL_MODE_MAX;
pub const enum_FT_Pixel_Mode_ = extern enum {
FT_PIXEL_MODE_NONE = 0,
FT_PIXEL_MODE_MONO = 1,
FT_PIXEL_MODE_GRAY = 2,
FT_PIXEL_MODE_GRAY2 = 3,
FT_PIXEL_MODE_GRAY4 = 4,
FT_PIXEL_MODE_LCD = 5,
FT_PIXEL_MODE_LCD_V = 6,
FT_PIXEL_MODE_BGRA = 7,
FT_PIXEL_MODE_MAX = 8,
};
pub const FT_Pixel_Mode = enum_FT_Pixel_Mode_;
pub const struct_FT_Bitmap_ = extern struct {
rows: c_uint,
width: c_uint,
pitch: c_int,
buffer: ?[*]u8,
num_grays: c_ushort,
pixel_mode: u8,
palette_mode: u8,
palette: ?*c_void,
};
pub const FT_Bitmap = struct_FT_Bitmap_;
pub const struct_FT_Outline_ = extern struct {
n_contours: c_short,
n_points: c_short,
points: ?[*]FT_Vector,
tags: ?[*]u8,
contours: ?[*]c_short,
flags: c_int,
};
pub const FT_Outline = struct_FT_Outline_;
pub const FT_Outline_MoveToFunc = ?extern fn(?[*]const FT_Vector, ?*c_void) c_int;
pub const FT_Outline_LineToFunc = ?extern fn(?[*]const FT_Vector, ?*c_void) c_int;
pub const FT_Outline_ConicToFunc = ?extern fn(?[*]const FT_Vector, ?[*]const FT_Vector, ?*c_void) c_int;
pub const FT_Outline_CubicToFunc = ?extern fn(?[*]const FT_Vector, ?[*]const FT_Vector, ?[*]const FT_Vector, ?*c_void) c_int;
pub const struct_FT_Outline_Funcs_ = extern struct {
move_to: FT_Outline_MoveToFunc,
line_to: FT_Outline_LineToFunc,
conic_to: FT_Outline_ConicToFunc,
cubic_to: FT_Outline_CubicToFunc,
shift: c_int,
delta: FT_Pos,
};
pub const FT_Outline_Funcs = struct_FT_Outline_Funcs_;
pub const FT_GLYPH_FORMAT_NONE = enum_FT_Glyph_Format_.FT_GLYPH_FORMAT_NONE;
pub const FT_GLYPH_FORMAT_COMPOSITE = enum_FT_Glyph_Format_.FT_GLYPH_FORMAT_COMPOSITE;
pub const FT_GLYPH_FORMAT_BITMAP = enum_FT_Glyph_Format_.FT_GLYPH_FORMAT_BITMAP;
pub const FT_GLYPH_FORMAT_OUTLINE = enum_FT_Glyph_Format_.FT_GLYPH_FORMAT_OUTLINE;
pub const FT_GLYPH_FORMAT_PLOTTER = enum_FT_Glyph_Format_.FT_GLYPH_FORMAT_PLOTTER;
pub const enum_FT_Glyph_Format_ = extern enum {
FT_GLYPH_FORMAT_NONE = 0,
FT_GLYPH_FORMAT_COMPOSITE = 1668246896,
FT_GLYPH_FORMAT_BITMAP = 1651078259,
FT_GLYPH_FORMAT_OUTLINE = 1869968492,
FT_GLYPH_FORMAT_PLOTTER = 1886154612,
};
pub const FT_Glyph_Format = enum_FT_Glyph_Format_;
pub const struct_FT_RasterRec_ = @OpaqueType();
pub const FT_Raster = ?*struct_FT_RasterRec_;
pub const struct_FT_Span_ = extern struct {
x: c_short,
len: c_ushort,
coverage: u8,
};
pub const FT_Span = struct_FT_Span_;
pub const FT_SpanFunc = ?extern fn(c_int, c_int, ?[*]const FT_Span, ?*c_void) void;
pub const FT_Raster_BitTest_Func = ?extern fn(c_int, c_int, ?*c_void) c_int;
pub const FT_Raster_BitSet_Func = ?extern fn(c_int, c_int, ?*c_void) void;
pub const struct_FT_Raster_Params_ = extern struct {
target: ?[*]const FT_Bitmap,
source: ?*const c_void,
flags: c_int,
gray_spans: FT_SpanFunc,
black_spans: FT_SpanFunc,
bit_test: FT_Raster_BitTest_Func,
bit_set: FT_Raster_BitSet_Func,
user: ?*c_void,
clip_box: FT_BBox,
};
pub const FT_Raster_Params = struct_FT_Raster_Params_;
pub const FT_Raster_NewFunc = ?extern fn(?*c_void, ?[*]FT_Raster) c_int;
pub const FT_Raster_DoneFunc = ?extern fn(FT_Raster) void;
pub const FT_Raster_ResetFunc = ?extern fn(FT_Raster, ?[*]u8, c_ulong) void;
pub const FT_Raster_SetModeFunc = ?extern fn(FT_Raster, c_ulong, ?*c_void) c_int;
pub const FT_Raster_RenderFunc = ?extern fn(FT_Raster, ?[*]const FT_Raster_Params) c_int;
pub const struct_FT_Raster_Funcs_ = extern struct {
glyph_format: FT_Glyph_Format,
raster_new: FT_Raster_NewFunc,
raster_reset: FT_Raster_ResetFunc,
raster_set_mode: FT_Raster_SetModeFunc,
raster_render: FT_Raster_RenderFunc,
raster_done: FT_Raster_DoneFunc,
};
pub const FT_Raster_Funcs = struct_FT_Raster_Funcs_;
pub const FT_Bool = u8;
pub const FT_FWord = c_short;
pub const FT_UFWord = c_ushort;
pub const FT_Char = i8;
pub const FT_Byte = u8;
pub const FT_Bytes = ?[*]const FT_Byte;
pub const FT_Tag = FT_UInt32;
pub const FT_String = u8;
pub const FT_Short = c_short;
pub const FT_UShort = c_ushort;
pub const FT_Int = c_int;
pub const FT_UInt = c_uint;
pub const FT_Long = c_long;
pub const FT_ULong = c_ulong;
pub const FT_F2Dot14 = c_short;
pub const FT_F26Dot6 = c_long;
pub const FT_Fixed = c_long;
pub const FT_Error = c_int;
pub const FT_Pointer = ?*c_void;
pub const FT_Offset = usize;
pub const FT_PtrDist = ptrdiff_t;
pub const struct_FT_UnitVector_ = extern struct {
x: FT_F2Dot14,
y: FT_F2Dot14,
};
pub const FT_UnitVector = struct_FT_UnitVector_;
pub const struct_FT_Matrix_ = extern struct {
xx: FT_Fixed,
xy: FT_Fixed,
yx: FT_Fixed,
yy: FT_Fixed,
};
pub const FT_Matrix = struct_FT_Matrix_;
pub const struct_FT_Data_ = extern struct {
pointer: ?[*]const FT_Byte,
length: FT_Int,
};
pub const FT_Data = struct_FT_Data_;
pub const FT_Generic_Finalizer = ?extern fn(?*c_void) void;
pub const struct_FT_Generic_ = extern struct {
data: ?*c_void,
finalizer: FT_Generic_Finalizer,
};
pub const FT_Generic = struct_FT_Generic_;
pub const FT_ListNode = ?[*]struct_FT_ListNodeRec_;
pub const struct_FT_ListNodeRec_ = extern struct {
prev: FT_ListNode,
next: FT_ListNode,
data: ?*c_void,
};
pub const struct_FT_ListRec_ = extern struct {
head: FT_ListNode,
tail: FT_ListNode,
};
pub const FT_List = ?[*]struct_FT_ListRec_;
pub const FT_ListNodeRec = struct_FT_ListNodeRec_;
pub const FT_ListRec = struct_FT_ListRec_;
pub const FT_Mod_Err_Base = 0;
pub const FT_Mod_Err_Autofit = 0;
pub const FT_Mod_Err_BDF = 0;
pub const FT_Mod_Err_Bzip2 = 0;
pub const FT_Mod_Err_Cache = 0;
pub const FT_Mod_Err_CFF = 0;
pub const FT_Mod_Err_CID = 0;
pub const FT_Mod_Err_Gzip = 0;
pub const FT_Mod_Err_LZW = 0;
pub const FT_Mod_Err_OTvalid = 0;
pub const FT_Mod_Err_PCF = 0;
pub const FT_Mod_Err_PFR = 0;
pub const FT_Mod_Err_PSaux = 0;
pub const FT_Mod_Err_PShinter = 0;
pub const FT_Mod_Err_PSnames = 0;
pub const FT_Mod_Err_Raster = 0;
pub const FT_Mod_Err_SFNT = 0;
pub const FT_Mod_Err_Smooth = 0;
pub const FT_Mod_Err_TrueType = 0;
pub const FT_Mod_Err_Type1 = 0;
pub const FT_Mod_Err_Type42 = 0;
pub const FT_Mod_Err_Winfonts = 0;
pub const FT_Mod_Err_GXvalid = 0;
pub const FT_Mod_Err_Max = 1;
pub const FT_Err_Ok = 0;
pub const FT_Err_Cannot_Open_Resource = 1;
pub const FT_Err_Unknown_File_Format = 2;
pub const FT_Err_Invalid_File_Format = 3;
pub const FT_Err_Invalid_Version = 4;
pub const FT_Err_Lower_Module_Version = 5;
pub const FT_Err_Invalid_Argument = 6;
pub const FT_Err_Unimplemented_Feature = 7;
pub const FT_Err_Invalid_Table = 8;
pub const FT_Err_Invalid_Offset = 9;
pub const FT_Err_Array_Too_Large = 10;
pub const FT_Err_Missing_Module = 11;
pub const FT_Err_Missing_Property = 12;
pub const FT_Err_Invalid_Glyph_Index = 16;
pub const FT_Err_Invalid_Character_Code = 17;
pub const FT_Err_Invalid_Glyph_Format = 18;
pub const FT_Err_Cannot_Render_Glyph = 19;
pub const FT_Err_Invalid_Outline = 20;
pub const FT_Err_Invalid_Composite = 21;
pub const FT_Err_Too_Many_Hints = 22;
pub const FT_Err_Invalid_Pixel_Size = 23;
pub const FT_Err_Invalid_Handle = 32;
pub const FT_Err_Invalid_Library_Handle = 33;
pub const FT_Err_Invalid_Driver_Handle = 34;
pub const FT_Err_Invalid_Face_Handle = 35;
pub const FT_Err_Invalid_Size_Handle = 36;
pub const FT_Err_Invalid_Slot_Handle = 37;
pub const FT_Err_Invalid_CharMap_Handle = 38;
pub const FT_Err_Invalid_Cache_Handle = 39;
pub const FT_Err_Invalid_Stream_Handle = 40;
pub const FT_Err_Too_Many_Drivers = 48;
pub const FT_Err_Too_Many_Extensions = 49;
pub const FT_Err_Out_Of_Memory = 64;
pub const FT_Err_Unlisted_Object = 65;
pub const FT_Err_Cannot_Open_Stream = 81;
pub const FT_Err_Invalid_Stream_Seek = 82;
pub const FT_Err_Invalid_Stream_Skip = 83;
pub const FT_Err_Invalid_Stream_Read = 84;
pub const FT_Err_Invalid_Stream_Operation = 85;
pub const FT_Err_Invalid_Frame_Operation = 86;
pub const FT_Err_Nested_Frame_Access = 87;
pub const FT_Err_Invalid_Frame_Read = 88;
pub const FT_Err_Raster_Uninitialized = 96;
pub const FT_Err_Raster_Corrupted = 97;
pub const FT_Err_Raster_Overflow = 98;
pub const FT_Err_Raster_Negative_Height = 99;
pub const FT_Err_Too_Many_Caches = 112;
pub const FT_Err_Invalid_Opcode = 128;
pub const FT_Err_Too_Few_Arguments = 129;
pub const FT_Err_Stack_Overflow = 130;
pub const FT_Err_Code_Overflow = 131;
pub const FT_Err_Bad_Argument = 132;
pub const FT_Err_Divide_By_Zero = 133;
pub const FT_Err_Invalid_Reference = 134;
pub const FT_Err_Debug_OpCode = 135;
pub const FT_Err_ENDF_In_Exec_Stream = 136;
pub const FT_Err_Nested_DEFS = 137;
pub const FT_Err_Invalid_CodeRange = 138;
pub const FT_Err_Execution_Too_Long = 139;
pub const FT_Err_Too_Many_Function_Defs = 140;
pub const FT_Err_Too_Many_Instruction_Defs = 141;
pub const FT_Err_Table_Missing = 142;
pub const FT_Err_Horiz_Header_Missing = 143;
pub const FT_Err_Locations_Missing = 144;
pub const FT_Err_Name_Table_Missing = 145;
pub const FT_Err_CMap_Table_Missing = 146;
pub const FT_Err_Hmtx_Table_Missing = 147;
pub const FT_Err_Post_Table_Missing = 148;
pub const FT_Err_Invalid_Horiz_Metrics = 149;
pub const FT_Err_Invalid_CharMap_Format = 150;
pub const FT_Err_Invalid_PPem = 151;
pub const FT_Err_Invalid_Vert_Metrics = 152;
pub const FT_Err_Could_Not_Find_Context = 153;
pub const FT_Err_Invalid_Post_Table_Format = 154;
pub const FT_Err_Invalid_Post_Table = 155;
pub const FT_Err_DEF_In_Glyf_Bytecode = 156;
pub const FT_Err_Missing_Bitmap = 157;
pub const FT_Err_Syntax_Error = 160;
pub const FT_Err_Stack_Underflow = 161;
pub const FT_Err_Ignore = 162;
pub const FT_Err_No_Unicode_Glyph_Name = 163;
pub const FT_Err_Glyph_Too_Big = 164;
pub const FT_Err_Missing_Startfont_Field = 176;
pub const FT_Err_Missing_Font_Field = 177;
pub const FT_Err_Missing_Size_Field = 178;
pub const FT_Err_Missing_Fontboundingbox_Field = 179;
pub const FT_Err_Missing_Chars_Field = 180;
pub const FT_Err_Missing_Startchar_Field = 181;
pub const FT_Err_Missing_Encoding_Field = 182;
pub const FT_Err_Missing_Bbx_Field = 183;
pub const FT_Err_Bbx_Too_Big = 184;
pub const FT_Err_Corrupted_Font_Header = 185;
pub const FT_Err_Corrupted_Font_Glyphs = 186;
pub const FT_Err_Max = 187;
pub const struct_FT_Glyph_Metrics_ = extern struct {
width: FT_Pos,
height: FT_Pos,
horiBearingX: FT_Pos,
horiBearingY: FT_Pos,
horiAdvance: FT_Pos,
vertBearingX: FT_Pos,
vertBearingY: FT_Pos,
vertAdvance: FT_Pos,
};
pub const FT_Glyph_Metrics = struct_FT_Glyph_Metrics_;
pub const struct_FT_Bitmap_Size_ = extern struct {
height: FT_Short,
width: FT_Short,
size: FT_Pos,
x_ppem: FT_Pos,
y_ppem: FT_Pos,
};
pub const FT_Bitmap_Size = struct_FT_Bitmap_Size_;
pub const struct_FT_LibraryRec_ = @OpaqueType();
pub const FT_Library = ?*struct_FT_LibraryRec_;
pub const struct_FT_ModuleRec_ = @OpaqueType();
pub const FT_Module = ?*struct_FT_ModuleRec_;
pub const struct_FT_DriverRec_ = @OpaqueType();
pub const FT_Driver = ?*struct_FT_DriverRec_;
pub const struct_FT_RendererRec_ = @OpaqueType();
pub const FT_Renderer = ?*struct_FT_RendererRec_;
pub const FT_Face = ?[*]struct_FT_FaceRec_;
pub const FT_ENCODING_NONE = enum_FT_Encoding_.FT_ENCODING_NONE;
pub const FT_ENCODING_MS_SYMBOL = enum_FT_Encoding_.FT_ENCODING_MS_SYMBOL;
pub const FT_ENCODING_UNICODE = enum_FT_Encoding_.FT_ENCODING_UNICODE;
pub const FT_ENCODING_SJIS = enum_FT_Encoding_.FT_ENCODING_SJIS;
pub const FT_ENCODING_PRC = enum_FT_Encoding_.FT_ENCODING_PRC;
pub const FT_ENCODING_BIG5 = enum_FT_Encoding_.FT_ENCODING_BIG5;
pub const FT_ENCODING_WANSUNG = enum_FT_Encoding_.FT_ENCODING_WANSUNG;
pub const FT_ENCODING_JOHAB = enum_FT_Encoding_.FT_ENCODING_JOHAB;
pub const FT_ENCODING_GB2312 = enum_FT_Encoding_.FT_ENCODING_GB2312;
pub const FT_ENCODING_MS_SJIS = enum_FT_Encoding_.FT_ENCODING_MS_SJIS;
pub const FT_ENCODING_MS_GB2312 = enum_FT_Encoding_.FT_ENCODING_MS_GB2312;
pub const FT_ENCODING_MS_BIG5 = enum_FT_Encoding_.FT_ENCODING_MS_BIG5;
pub const FT_ENCODING_MS_WANSUNG = enum_FT_Encoding_.FT_ENCODING_MS_WANSUNG;
pub const FT_ENCODING_MS_JOHAB = enum_FT_Encoding_.FT_ENCODING_MS_JOHAB;
pub const FT_ENCODING_ADOBE_STANDARD = enum_FT_Encoding_.FT_ENCODING_ADOBE_STANDARD;
pub const FT_ENCODING_ADOBE_EXPERT = enum_FT_Encoding_.FT_ENCODING_ADOBE_EXPERT;
pub const FT_ENCODING_ADOBE_CUSTOM = enum_FT_Encoding_.FT_ENCODING_ADOBE_CUSTOM;
pub const FT_ENCODING_ADOBE_LATIN_1 = enum_FT_Encoding_.FT_ENCODING_ADOBE_LATIN_1;
pub const FT_ENCODING_OLD_LATIN_2 = enum_FT_Encoding_.FT_ENCODING_OLD_LATIN_2;
pub const FT_ENCODING_APPLE_ROMAN = enum_FT_Encoding_.FT_ENCODING_APPLE_ROMAN;
pub const enum_FT_Encoding_ = extern enum {
FT_ENCODING_NONE = 0,
FT_ENCODING_MS_SYMBOL = 1937337698,
FT_ENCODING_UNICODE = 1970170211,
FT_ENCODING_SJIS = 1936353651,
FT_ENCODING_PRC = 1734484000,
FT_ENCODING_BIG5 = 1651074869,
FT_ENCODING_WANSUNG = 2002873971,
FT_ENCODING_JOHAB = 1785686113,
FT_ENCODING_GB2312 = 1734484000,
FT_ENCODING_MS_SJIS = 1936353651,
FT_ENCODING_MS_GB2312 = 1734484000,
FT_ENCODING_MS_BIG5 = 1651074869,
FT_ENCODING_MS_WANSUNG = 2002873971,
FT_ENCODING_MS_JOHAB = 1785686113,
FT_ENCODING_ADOBE_STANDARD = 1094995778,
FT_ENCODING_ADOBE_EXPERT = 1094992453,
FT_ENCODING_ADOBE_CUSTOM = 1094992451,
FT_ENCODING_ADOBE_LATIN_1 = 1818326065,
FT_ENCODING_OLD_LATIN_2 = 1818326066,
FT_ENCODING_APPLE_ROMAN = 1634889070,
};
pub const FT_Encoding = extern enum {
FT_ENCODING_NONE = 0,
FT_ENCODING_MS_SYMBOL = 1937337698,
FT_ENCODING_UNICODE = 1970170211,
FT_ENCODING_SJIS = 1936353651,
FT_ENCODING_PRC = 1734484000,
FT_ENCODING_BIG5 = 1651074869,
FT_ENCODING_WANSUNG = 2002873971,
FT_ENCODING_JOHAB = 1785686113,
FT_ENCODING_GB2312 = 1734484000,
FT_ENCODING_MS_SJIS = 1936353651,
FT_ENCODING_MS_GB2312 = 1734484000,
FT_ENCODING_MS_BIG5 = 1651074869,
FT_ENCODING_MS_WANSUNG = 2002873971,
FT_ENCODING_MS_JOHAB = 1785686113,
FT_ENCODING_ADOBE_STANDARD = 1094995778,
FT_ENCODING_ADOBE_EXPERT = 1094992453,
FT_ENCODING_ADOBE_CUSTOM = 1094992451,
FT_ENCODING_ADOBE_LATIN_1 = 1818326065,
FT_ENCODING_OLD_LATIN_2 = 1818326066,
FT_ENCODING_APPLE_ROMAN = 1634889070,
};
pub const struct_FT_CharMapRec_ = extern struct {
face: FT_Face,
encoding: FT_Encoding,
platform_id: FT_UShort,
encoding_id: FT_UShort,
};
pub const FT_CharMap = ?[*]struct_FT_CharMapRec_;
pub const struct_FT_SubGlyphRec_ = @OpaqueType();
pub const FT_SubGlyph = ?*struct_FT_SubGlyphRec_;
pub const struct_FT_Slot_InternalRec_ = @OpaqueType();
pub const FT_Slot_Internal = ?*struct_FT_Slot_InternalRec_;
pub const struct_FT_GlyphSlotRec_ = extern struct {
library: FT_Library,
face: FT_Face,
next: FT_GlyphSlot,
reserved: FT_UInt,
generic: FT_Generic,
metrics: FT_Glyph_Metrics,
linearHoriAdvance: FT_Fixed,
linearVertAdvance: FT_Fixed,
advance: FT_Vector,
format: FT_Glyph_Format,
bitmap: FT_Bitmap,
bitmap_left: FT_Int,
bitmap_top: FT_Int,
outline: FT_Outline,
num_subglyphs: FT_UInt,
subglyphs: FT_SubGlyph,
control_data: ?*c_void,
control_len: c_long,
lsb_delta: FT_Pos,
rsb_delta: FT_Pos,
other: ?*c_void,
internal: FT_Slot_Internal,
};
pub const FT_GlyphSlot = ?[*]struct_FT_GlyphSlotRec_;
pub const struct_FT_Size_Metrics_ = extern struct {
x_ppem: FT_UShort,
y_ppem: FT_UShort,
x_scale: FT_Fixed,
y_scale: FT_Fixed,
ascender: FT_Pos,
descender: FT_Pos,
height: FT_Pos,
max_advance: FT_Pos,
};
pub const FT_Size_Metrics = struct_FT_Size_Metrics_;
pub const struct_FT_Size_InternalRec_ = @OpaqueType();
pub const FT_Size_Internal = ?*struct_FT_Size_InternalRec_;
pub const struct_FT_SizeRec_ = extern struct {
face: FT_Face,
generic: FT_Generic,
metrics: FT_Size_Metrics,
internal: FT_Size_Internal,
};
pub const FT_Size = ?[*]struct_FT_SizeRec_;
pub const struct_FT_Face_InternalRec_ = @OpaqueType();
pub const FT_Face_Internal = ?*struct_FT_Face_InternalRec_;
pub const struct_FT_FaceRec_ = extern struct {
num_faces: FT_Long,
face_index: FT_Long,
face_flags: FT_Long,
style_flags: FT_Long,
num_glyphs: FT_Long,
family_name: ?[*]FT_String,
style_name: ?[*]FT_String,
num_fixed_sizes: FT_Int,
available_sizes: ?[*]FT_Bitmap_Size,
num_charmaps: FT_Int,
charmaps: ?[*]FT_CharMap,
generic: FT_Generic,
bbox: FT_BBox,
units_per_EM: FT_UShort,
ascender: FT_Short,
descender: FT_Short,
height: FT_Short,
max_advance_width: FT_Short,
max_advance_height: FT_Short,
underline_position: FT_Short,
underline_thickness: FT_Short,
glyph: FT_GlyphSlot,
size: FT_Size,
charmap: FT_CharMap,
driver: FT_Driver,
memory: FT_Memory,
stream: FT_Stream,
sizes_list: FT_ListRec,
autohint: FT_Generic,
extensions: ?*c_void,
internal: FT_Face_Internal,
};
pub const FT_CharMapRec = struct_FT_CharMapRec_;
pub const FT_FaceRec = struct_FT_FaceRec_;
pub const FT_SizeRec = struct_FT_SizeRec_;
pub const FT_GlyphSlotRec = struct_FT_GlyphSlotRec_;
pub extern fn FT_Init_FreeType(alibrary: ?[*]FT_Library) FT_Error;
pub extern fn FT_Done_FreeType(library: FT_Library) FT_Error;
pub const struct_FT_Parameter_ = extern struct {
tag: FT_ULong,
data: FT_Pointer,
};
pub const FT_Parameter = struct_FT_Parameter_;
pub const struct_FT_Open_Args_ = extern struct {
flags: FT_UInt,
memory_base: ?[*]const FT_Byte,
memory_size: FT_Long,
pathname: ?[*]FT_String,
stream: FT_Stream,
driver: FT_Module,
num_params: FT_Int,
params: ?[*]FT_Parameter,
};
pub const FT_Open_Args = struct_FT_Open_Args_;
pub extern fn FT_New_Face(library: FT_Library, filepathname: ?[*]const u8, face_index: FT_Long, aface: ?[*]FT_Face) FT_Error;
pub extern fn FT_New_Memory_Face(library: FT_Library, file_base: ?[*]const FT_Byte, file_size: FT_Long, face_index: FT_Long, aface: ?[*]FT_Face) FT_Error;
pub extern fn FT_Open_Face(library: FT_Library, args: ?[*]const FT_Open_Args, face_index: FT_Long, aface: ?[*]FT_Face) FT_Error;
pub extern fn FT_Attach_File(face: FT_Face, filepathname: ?[*]const u8) FT_Error;
pub extern fn FT_Attach_Stream(face: FT_Face, parameters: ?[*]FT_Open_Args) FT_Error;
pub extern fn FT_Reference_Face(face: FT_Face) FT_Error;
pub extern fn FT_Done_Face(face: FT_Face) FT_Error;
pub extern fn FT_Select_Size(face: FT_Face, strike_index: FT_Int) FT_Error;
pub const FT_SIZE_REQUEST_TYPE_NOMINAL = enum_FT_Size_Request_Type_.FT_SIZE_REQUEST_TYPE_NOMINAL;
pub const FT_SIZE_REQUEST_TYPE_REAL_DIM = enum_FT_Size_Request_Type_.FT_SIZE_REQUEST_TYPE_REAL_DIM;
pub const FT_SIZE_REQUEST_TYPE_BBOX = enum_FT_Size_Request_Type_.FT_SIZE_REQUEST_TYPE_BBOX;
pub const FT_SIZE_REQUEST_TYPE_CELL = enum_FT_Size_Request_Type_.FT_SIZE_REQUEST_TYPE_CELL;
pub const FT_SIZE_REQUEST_TYPE_SCALES = enum_FT_Size_Request_Type_.FT_SIZE_REQUEST_TYPE_SCALES;
pub const FT_SIZE_REQUEST_TYPE_MAX = enum_FT_Size_Request_Type_.FT_SIZE_REQUEST_TYPE_MAX;
pub const enum_FT_Size_Request_Type_ = extern enum {
FT_SIZE_REQUEST_TYPE_NOMINAL,
FT_SIZE_REQUEST_TYPE_REAL_DIM,
FT_SIZE_REQUEST_TYPE_BBOX,
FT_SIZE_REQUEST_TYPE_CELL,
FT_SIZE_REQUEST_TYPE_SCALES,
FT_SIZE_REQUEST_TYPE_MAX,
};
pub const FT_Size_Request_Type = enum_FT_Size_Request_Type_;
pub const struct_FT_Size_RequestRec_ = extern struct {
type: FT_Size_Request_Type,
width: FT_Long,
height: FT_Long,
horiResolution: FT_UInt,
vertResolution: FT_UInt,
};
pub const FT_Size_RequestRec = struct_FT_Size_RequestRec_;
pub const FT_Size_Request = ?[*]struct_FT_Size_RequestRec_;
pub extern fn FT_Request_Size(face: FT_Face, req: FT_Size_Request) FT_Error;
pub extern fn FT_Set_Char_Size(face: FT_Face, char_width: FT_F26Dot6, char_height: FT_F26Dot6, horz_resolution: FT_UInt, vert_resolution: FT_UInt) FT_Error;
pub extern fn FT_Set_Pixel_Sizes(face: FT_Face, pixel_width: FT_UInt, pixel_height: FT_UInt) FT_Error;
pub extern fn FT_Load_Glyph(face: FT_Face, glyph_index: FT_UInt, load_flags: FT_Int32) FT_Error;
pub extern fn FT_Load_Char(face: FT_Face, char_code: FT_ULong, load_flags: FT_Int32) FT_Error;
pub extern fn FT_Set_Transform(face: FT_Face, matrix: ?[*]FT_Matrix, delta: ?[*]FT_Vector) void;
pub const FT_RENDER_MODE_NORMAL = enum_FT_Render_Mode_.FT_RENDER_MODE_NORMAL;
pub const FT_RENDER_MODE_LIGHT = enum_FT_Render_Mode_.FT_RENDER_MODE_LIGHT;
pub const FT_RENDER_MODE_MONO = enum_FT_Render_Mode_.FT_RENDER_MODE_MONO;
pub const FT_RENDER_MODE_LCD = enum_FT_Render_Mode_.FT_RENDER_MODE_LCD;
pub const FT_RENDER_MODE_LCD_V = enum_FT_Render_Mode_.FT_RENDER_MODE_LCD_V;
pub const FT_RENDER_MODE_MAX = enum_FT_Render_Mode_.FT_RENDER_MODE_MAX;
pub const enum_FT_Render_Mode_ = extern enum {
FT_RENDER_MODE_NORMAL = 0,
FT_RENDER_MODE_LIGHT = 1,
FT_RENDER_MODE_MONO = 2,
FT_RENDER_MODE_LCD = 3,
FT_RENDER_MODE_LCD_V = 4,
FT_RENDER_MODE_MAX = 5,
};
pub const FT_Render_Mode = enum_FT_Render_Mode_;
pub extern fn FT_Render_Glyph(slot: FT_GlyphSlot, render_mode: FT_Render_Mode) FT_Error;
pub const FT_KERNING_DEFAULT = enum_FT_Kerning_Mode_.FT_KERNING_DEFAULT;
pub const FT_KERNING_UNFITTED = enum_FT_Kerning_Mode_.FT_KERNING_UNFITTED;
pub const FT_KERNING_UNSCALED = enum_FT_Kerning_Mode_.FT_KERNING_UNSCALED;
pub const enum_FT_Kerning_Mode_ = extern enum {
FT_KERNING_DEFAULT = 0,
FT_KERNING_UNFITTED = 1,
FT_KERNING_UNSCALED = 2,
};
pub const FT_Kerning_Mode = enum_FT_Kerning_Mode_;
pub extern fn FT_Get_Kerning(face: FT_Face, left_glyph: FT_UInt, right_glyph: FT_UInt, kern_mode: FT_UInt, akerning: ?[*]FT_Vector) FT_Error;
pub extern fn FT_Get_Track_Kerning(face: FT_Face, point_size: FT_Fixed, degree: FT_Int, akerning: ?[*]FT_Fixed) FT_Error;
pub extern fn FT_Get_Glyph_Name(face: FT_Face, glyph_index: FT_UInt, buffer: FT_Pointer, buffer_max: FT_UInt) FT_Error;
pub extern fn FT_Get_Postscript_Name(face: FT_Face) ?[*]const u8;
pub extern fn FT_Select_Charmap(face: FT_Face, encoding: FT_Encoding) FT_Error;
pub extern fn FT_Set_Charmap(face: FT_Face, charmap: FT_CharMap) FT_Error;
pub extern fn FT_Get_Charmap_Index(charmap: FT_CharMap) FT_Int;
pub extern fn FT_Get_Char_Index(face: FT_Face, charcode: FT_ULong) FT_UInt;
pub extern fn FT_Get_First_Char(face: FT_Face, agindex: ?[*]FT_UInt) FT_ULong;
pub extern fn FT_Get_Next_Char(face: FT_Face, char_code: FT_ULong, agindex: ?[*]FT_UInt) FT_ULong;
pub extern fn FT_Face_Properties(face: FT_Face, num_properties: FT_UInt, properties: ?[*]FT_Parameter) FT_Error;
pub extern fn FT_Get_Name_Index(face: FT_Face, glyph_name: ?[*]FT_String) FT_UInt;
pub extern fn FT_Get_SubGlyph_Info(glyph: FT_GlyphSlot, sub_index: FT_UInt, p_index: ?[*]FT_Int, p_flags: ?[*]FT_UInt, p_arg1: ?[*]FT_Int, p_arg2: ?[*]FT_Int, p_transform: ?[*]FT_Matrix) FT_Error;
pub extern fn FT_Get_FSType_Flags(face: FT_Face) FT_UShort;
pub extern fn FT_Face_GetCharVariantIndex(face: FT_Face, charcode: FT_ULong, variantSelector: FT_ULong) FT_UInt;
pub extern fn FT_Face_GetCharVariantIsDefault(face: FT_Face, charcode: FT_ULong, variantSelector: FT_ULong) FT_Int;
pub extern fn FT_Face_GetVariantSelectors(face: FT_Face) ?[*]FT_UInt32;
pub extern fn FT_Face_GetVariantsOfChar(face: FT_Face, charcode: FT_ULong) ?[*]FT_UInt32;
pub extern fn FT_Face_GetCharsOfVariant(face: FT_Face, variantSelector: FT_ULong) ?[*]FT_UInt32;
pub extern fn FT_MulDiv(a: FT_Long, b: FT_Long, c: FT_Long) FT_Long;
pub extern fn FT_MulFix(a: FT_Long, b: FT_Long) FT_Long;
pub extern fn FT_DivFix(a: FT_Long, b: FT_Long) FT_Long;
pub extern fn FT_RoundFix(a: FT_Fixed) FT_Fixed;
pub extern fn FT_CeilFix(a: FT_Fixed) FT_Fixed;
pub extern fn FT_FloorFix(a: FT_Fixed) FT_Fixed;
pub extern fn FT_Vector_Transform(vec: ?[*]FT_Vector, matrix: ?[*]const FT_Matrix) void;
pub extern fn FT_Library_Version(library: FT_Library, amajor: ?[*]FT_Int, aminor: ?[*]FT_Int, apatch: ?[*]FT_Int) void;
pub extern fn FT_Face_CheckTrueTypePatents(face: FT_Face) FT_Bool;
pub extern fn FT_Face_SetUnpatentedHinting(face: FT_Face, value: FT_Bool) FT_Bool;
pub const SCHAR_MAX = __SCHAR_MAX__;
pub const __BIGGEST_ALIGNMENT__ = 16;
pub const LLONG_MIN = if (@typeId(@typeOf(-1)) == @import("builtin").TypeId.Pointer) @ptrCast(-LLONG_MAX, -1) else if (@typeId(@typeOf(-1)) == @import("builtin").TypeId.Int) @intToPtr(-LLONG_MAX, -1) else (-LLONG_MAX)(-1);
pub const _IO_USER_LOCK = 32768;
pub const __INT64_FMTd__ = c"ld";
pub const __STDC_VERSION__ = c_long(201112);
pub const FT_ERR_BASE = 0;
pub const ft_ptrdiff_t = ptrdiff_t;
pub const __INT_LEAST8_FMTi__ = c"hhi";
pub const FT_UINT_MAX = UINT_MAX;
pub const __GCC_ATOMIC_LLONG_LOCK_FREE = 2;
pub const __clang_version__ = c"7.0.1 (tags/RELEASE_701/final)";
pub const __UINT_LEAST8_FMTo__ = c"hho";
pub const ft_fclose = fclose;
pub const __INTMAX_FMTd__ = c"ld";
pub const __HAVE_DISTINCT_FLOAT16 = __HAVE_FLOAT16;
pub const ft_jmp_buf = jmp_buf;
pub const ft_strtol = strtol;
pub const FT_OUTLINE_EVEN_ODD_FILL = 2;
pub const __CLANG_ATOMIC_CHAR_LOCK_FREE = 2;
pub const __INT_LEAST16_FMTi__ = c"hi";
pub const ft_raster_flag_default = FT_RASTER_FLAG_DEFAULT;
pub const ft_strrchr = strrchr;
pub const __MMX__ = 1;
pub const FREETYPE_MINOR = 9;
pub const FT_AUTOHINTER_H = FT_DRIVER_H;
pub const _THREAD_SHARED_TYPES_H = 1;
pub const _POSIX2_RE_DUP_MAX = 255;
pub const __INO_T_TYPE = __SYSCALL_ULONG_TYPE;
pub const FT_INT_MIN = INT_MIN;
pub const FT_OUTLINE_OWNER = 1;
pub const __FSBLKCNT_T_TYPE = __SYSCALL_ULONG_TYPE;
pub const __ptr_t = [*]void;
pub const __WCHAR_WIDTH__ = 32;
pub const FT_RASTER_FLAG_DEFAULT = 0;
pub const HOST_NAME_MAX = 64;
pub const FT_SUBGLYPH_FLAG_ARGS_ARE_WORDS = 1;
pub const __USE_MISC = 1;
pub const _POSIX_AIO_LISTIO_MAX = 2;
pub const __SIZEOF_PTHREAD_ATTR_T = 56;
pub const __PTRDIFF_FMTd__ = c"ld";
pub const __FLT_EVAL_METHOD__ = 0;
pub const __SSE_MATH__ = 1;
pub const __UINT_FAST8_FMTo__ = c"hho";
pub const __UINT_LEAST64_MAX__ = c_ulong(18446744073709551615);
pub const __UINT_LEAST64_FMTx__ = c"lx";
pub const __INT8_MAX__ = 127;
pub const FT_CHAR_BIT = CHAR_BIT;
pub const __NLINK_T_TYPE = __SYSCALL_ULONG_TYPE;
pub const __DBL_DECIMAL_DIG__ = 17;
pub const _POSIX2_BC_SCALE_MAX = 99;
pub const LONG_MIN = if (@typeId(@typeOf(-c_long(1))) == @import("builtin").TypeId.Pointer) @ptrCast(-__LONG_MAX__, -c_long(1)) else if (@typeId(@typeOf(-c_long(1))) == @import("builtin").TypeId.Int) @intToPtr(-__LONG_MAX__, -c_long(1)) else (-__LONG_MAX__)(-c_long(1));
pub const __PTHREAD_MUTEX_HAVE_PREV = 1;
pub const __CONSTANT_CFSTRINGS__ = 1;
pub const _SYS_CDEFS_H = 1;
pub const _ATFILE_SOURCE = 1;
pub const ft_strncpy = strncpy;
pub const __RLIM_T_TYPE = __SYSCALL_ULONG_TYPE;
pub const __LDBL_MAX_EXP__ = 16384;
pub const __USE_POSIX199309 = 1;
pub const __NO_MATH_INLINES = 1;
pub const RE_DUP_MAX = 32767;
pub const __WCHAR_TYPE__ = int;
pub const __LONG_MAX__ = c_long(9223372036854775807);
pub const FREETYPE_MAJOR = 2;
pub const FT_OUTLINE_SMART_DROPOUTS = 16;
pub const MAX_INPUT = 255;
pub const __pic__ = 2;
pub const ft_open_driver = FT_OPEN_DRIVER;
pub const __INT_FAST16_FMTi__ = c"hi";
pub const __PTRDIFF_WIDTH__ = 64;
pub const FT_Raster_Span_Func = FT_SpanFunc;
pub const __LDBL_DENORM_MIN__ = 0.000000;
pub const FT_LOAD_DEFAULT = 0;
pub const RAND_MAX = 2147483647;
pub const __FLOAT_WORD_ORDER = __BYTE_ORDER;
pub const FT_RASTER_FLAG_AA = 1;
pub const _IOFBF = 0;
pub const __INT64_C_SUFFIX__ = L;
pub const __FSFILCNT_T_TYPE = __SYSCALL_ULONG_TYPE;
pub const __SSIZE_T_TYPE = __SWORD_TYPE;
pub const __SIZEOF_PTRDIFF_T__ = 8;
pub const FT_CACHE_INTERNAL_MRU_H = FT_CACHE_H;
pub const __SIG_ATOMIC_MAX__ = 2147483647;
pub const __struct_FILE_defined = 1;
pub const _IO_EOF_SEEN = 16;
pub const __USE_ATFILE = 1;
pub const __WALL = 1073741824;
pub const __UINT64_MAX__ = c_ulong(18446744073709551615);
pub const _POSIX_LINK_MAX = 8;
pub const FT_CURVE_TAG_CONIC = 0;
pub const _POSIX_CLOCKRES_MIN = 20000000;
pub const __FLT_DECIMAL_DIG__ = 9;
pub const __DBL_DIG__ = 15;
pub const __ATOMIC_ACQUIRE = 2;
pub const PTHREAD_STACK_MIN = 16384;
pub const _LIBC_LIMITS_H_ = 1;
pub const FT_CACHE_SMALL_BITMAPS_H = FT_CACHE_H;
pub const __FLT16_HAS_DENORM__ = 1;
pub const _POSIX_RE_DUP_MAX = 255;
pub const __UINT_FAST16_FMTu__ = c"hu";
pub const __INTPTR_FMTi__ = c"li";
pub const __UINT_FAST8_FMTX__ = c"hhX";
pub const SHRT_MIN = if (@typeId(@typeOf(-1)) == @import("builtin").TypeId.Pointer) @ptrCast(-__SHRT_MAX__, -1) else if (@typeId(@typeOf(-1)) == @import("builtin").TypeId.Int) @intToPtr(-__SHRT_MAX__, -1) else (-__SHRT_MAX__)(-1);
pub const _POSIX_ARG_MAX = 4096;
pub const __UINT8_FMTo__ = c"hho";
pub const __UINT_LEAST16_FMTx__ = c"hx";
pub const __UINT_FAST16_FMTX__ = c"hX";
pub const __VERSION__ = c"4.2.1 Compatible Clang 7.0.1 (tags/RELEASE_701/final)";
pub const __UINT_FAST32_FMTx__ = c"x";
pub const __UINT_FAST8_FMTu__ = c"hhu";
pub const __UINT_LEAST64_FMTo__ = c"lo";
pub const PATH_MAX = 4096;
pub const __clockid_t_defined = 1;
pub const __UINT_LEAST8_MAX__ = 255;
pub const _POSIX2_EXPR_NEST_MAX = 32;
pub const FT_SUBGLYPH_FLAG_USE_MY_METRICS = 512;
pub const FT_Raster_New_Func = FT_Raster_NewFunc;
pub const __GLIBC_USE_DEPRECATED_GETS = 0;
pub const __UINT16_MAX__ = 65535;
pub const __CLOCK_T_TYPE = __SYSCALL_SLONG_TYPE;
pub const __x86_64 = 1;
pub const __PTHREAD_RWLOCK_INT_FLAGS_SHARED = 1;
pub const __SIZEOF_WINT_T__ = 4;
pub const FT_FSTYPE_EDITABLE_EMBEDDING = 8;
pub const __UINTMAX_FMTo__ = c"lo";
pub const FT_CURVE_TAG_HAS_SCANMODE = 4;
pub const __UINT_LEAST8_FMTX__ = c"hhX";
pub const __HAVE_FLOAT64X = 1;
pub const __WINT_UNSIGNED__ = 1;
pub const _POSIX_HOST_NAME_MAX = 255;
pub const XATTR_NAME_MAX = 255;
pub const __HAVE_FLOAT16 = 0;
pub const FT_CACHE_IMAGE_H = FT_CACHE_H;
pub const __SIZEOF_PTHREAD_RWLOCKATTR_T = 8;
pub const FT_OUTLINE_HIGH_PRECISION = 256;
pub const __POINTER_WIDTH__ = 64;
pub const ft_render_mode_normal = FT_RENDER_MODE_NORMAL;
pub const __PTRDIFF_MAX__ = c_long(9223372036854775807);
pub const __FLT16_DIG__ = 3;
pub const FT_OUTLINE_NONE = 0;
pub const __SIZEOF_LONG__ = 8;
pub const __TIME_T_TYPE = __SYSCALL_SLONG_TYPE;
pub const __W_CONTINUED = 65535;
pub const __NO_INLINE__ = 1;
pub const __HAVE_FLOAT128 = 0;
pub const __INT_FAST32_MAX__ = 2147483647;
pub const _BITS_PTHREADTYPES_COMMON_H = 1;
pub const __UINTMAX_FMTu__ = c"lu";
pub const ft_strcmp = strcmp;
pub const ft_outline_reverse_fill = FT_OUTLINE_REVERSE_FILL;
pub const NGROUPS_MAX = 65536;
pub const __FLT_RADIX__ = 2;
pub const __GLIBC_MINOR__ = 28;
pub const AIO_PRIO_DELTA_MAX = 20;
pub const _BITS_BYTESWAP_H = 1;
pub const _BITS_SETJMP_H = 1;
pub const _STRUCT_TIMESPEC = 1;
pub const __FLT16_DECIMAL_DIG__ = 5;
pub const __PRAGMA_REDEFINE_EXTNAME = 1;
pub const __CPU_MASK_TYPE = __SYSCALL_ULONG_TYPE;
pub const _POSIX_LOGIN_NAME_MAX = 9;
pub const CFF_CONFIG_OPTION_DARKENING_PARAMETER_X2 = 1000;
pub const FOPEN_MAX = 16;
pub const __UINTMAX_WIDTH__ = 64;
pub const FT_CACHE_INTERNAL_IMAGE_H = FT_CACHE_H;
pub const __PTHREAD_MUTEX_USE_UNION = 0;
pub const __INT64_FMTi__ = c"li";
pub const __UINT_FAST64_FMTu__ = c"lu";
pub const _POSIX_TZNAME_MAX = 6;
pub const __INT_FAST16_TYPE__ = short;
pub const __HAVE_DISTINCT_FLOAT128 = 0;
pub const __DBL_MAX_10_EXP__ = 308;
pub const __LDBL_MIN__ = 0.000000;
pub const __CLANG_ATOMIC_LLONG_LOCK_FREE = 2;
pub const __FSFILCNT64_T_TYPE = __UQUAD_TYPE;
pub const MQ_PRIO_MAX = 32768;
pub const __GID_T_TYPE = __U32_TYPE;
pub const __PIC__ = 2;
pub const ft_encoding_johab = FT_ENCODING_JOHAB;
pub const _POSIX_NAME_MAX = 14;
pub const _DEFAULT_SOURCE = 1;
pub const __FD_SETSIZE = 1024;
pub const __LDBL_DECIMAL_DIG__ = 21;
pub const __UINT_LEAST64_FMTX__ = c"lX";
pub const ft_strcpy = strcpy;
pub const __clang_minor__ = 0;
pub const FT_CFF_DRIVER_H = FT_DRIVER_H;
pub const __SIZEOF_FLOAT128__ = 16;
pub const FT_OUTLINE_SINGLE_PASS = 512;
pub const __CLOCKID_T_TYPE = __S32_TYPE;
pub const __UINT_FAST64_FMTo__ = c"lo";
pub const _POSIX_SYMLINK_MAX = 255;
pub const MB_LEN_MAX = 16;
pub const __DBL_MAX__ = 179769313486231570814527423731704356798070567525844996598917476803157260780028538760589558632766878;
pub const ft_fopen = fopen;
pub const LINK_MAX = 127;
pub const __UINT64_FMTx__ = c"lx";
pub const ft_raster_flag_aa = FT_RASTER_FLAG_AA;
pub const P_tmpdir = c"/tmp";
pub const __WCOREFLAG = 128;
pub const SEEK_END = 2;
pub const __SLONG32_TYPE = int;
pub const _DEBUG = 1;
pub const __restrict_arr = __restrict;
pub const __RLIM_T_MATCHES_RLIM64_T = 1;
pub const __UINT8_FMTX__ = c"hhX";
pub const _POSIX_NGROUPS_MAX = 8;
pub const __UINTPTR_WIDTH__ = 64;
pub const __WNOTHREAD = 536870912;
pub const __time_t_defined = 1;
pub const __k8 = 1;
pub const __DADDR_T_TYPE = __S32_TYPE;
pub const __UINT8_FMTx__ = c"hhx";
pub const __INTMAX_C_SUFFIX__ = L;
pub const FT_CALLBACK_TABLE = @"extern";
pub const __ORDER_LITTLE_ENDIAN__ = 1234;
pub const __INT16_FMTd__ = c"hd";
pub const __SUSECONDS_T_TYPE = __SYSCALL_SLONG_TYPE;
pub const FT_LONG_MAX = LONG_MAX;
pub const __GCC_HAVE_SYNC_COMPARE_AND_SWAP_4 = 1;
pub const __INTMAX_WIDTH__ = 64;
pub const __INO64_T_TYPE = __UQUAD_TYPE;
pub const ft_pixel_mode_none = FT_PIXEL_MODE_NONE;
pub const __CLANG_ATOMIC_BOOL_LOCK_FREE = 2;
pub const EXIT_FAILURE = 1;
pub const __USE_POSIX = 1;
pub const __SIZE_FMTo__ = c"lo";
pub const BC_STRING_MAX = _POSIX2_BC_STRING_MAX;
pub const __PDP_ENDIAN = 3412;
pub const __INT_FAST8_FMTi__ = c"hhi";
pub const __UINT_LEAST32_FMTo__ = c"o";
pub const __UINT_FAST16_FMTx__ = c"hx";
pub const __FLT_MIN_EXP__ = -125;
pub const __UINT_LEAST64_FMTu__ = c"lu";
pub const __GCC_ATOMIC_LONG_LOCK_FREE = 2;
pub const FT_CURVE_TAG_ON = 1;
pub const __INT_FAST64_FMTd__ = c"ld";
pub const _POSIX_MAX_INPUT = 255;
pub const __CLANG_ATOMIC_LONG_LOCK_FREE = 2;
pub const ft_pixel_mode_pal2 = FT_PIXEL_MODE_GRAY2;
pub const CHAR_BIT = __CHAR_BIT__;
pub const __GXX_ABI_VERSION = 1002;
pub const ft_encoding_latin_1 = FT_ENCODING_ADOBE_LATIN_1;
pub const T1_MAX_DICT_DEPTH = 5;
pub const __FLT_MANT_DIG__ = 24;
pub const FT_OPEN_STREAM = 2;
pub const __UINT_FAST64_FMTx__ = c"lx";
pub const __STDC__ = 1;
pub const __HAVE_FLOAT64X_LONG_DOUBLE = 1;
pub const __INTPTR_FMTd__ = c"ld";
pub const __GNUC_PATCHLEVEL__ = 1;
pub const RTSIG_MAX = 32;
pub const __SIZE_WIDTH__ = 64;
pub const __UINT_LEAST8_FMTx__ = c"hhx";
pub const __INT_LEAST64_FMTi__ = c"li";
pub const __HAVE_DISTINCT_FLOAT64 = 0;
pub const __INT_FAST16_MAX__ = 32767;
pub const __CLANG_ATOMIC_CHAR16_T_LOCK_FREE = 2;
pub const __have_pthread_attr_t = 1;
pub const __INT_MAX__ = 2147483647;
pub const __BLKSIZE_T_TYPE = __SYSCALL_SLONG_TYPE;
pub const ft_sfree = free;
pub const __DBL_DENORM_MIN__ = 0.000000;
pub const __clang_major__ = 7;
pub const __FLT16_MANT_DIG__ = 11;
pub const XATTR_LIST_MAX = 65536;
pub const INT_MIN = if (@typeId(@typeOf(-1)) == @import("builtin").TypeId.Pointer) @ptrCast(-__INT_MAX__, -1) else if (@typeId(@typeOf(-1)) == @import("builtin").TypeId.Int) @intToPtr(-__INT_MAX__, -1) else (-__INT_MAX__)(-1);
pub const ft_encoding_none = FT_ENCODING_NONE;
pub const __FLT_DENORM_MIN__ = 0.000000;
pub const __BIG_ENDIAN = 4321;
pub const ft_kerning_unscaled = FT_KERNING_UNSCALED;
pub const __UINT_LEAST16_MAX__ = 65535;
pub const __HAVE_DISTINCT_FLOAT32X = 0;
pub const __LDBL_HAS_DENORM__ = 1;
pub const __LDBL_HAS_QUIET_NAN__ = 1;
pub const TMP_MAX = 238328;
pub const FT_Curve_Tag_Conic = FT_CURVE_TAG_CONIC;
pub const FT_RASTER_FLAG_CLIP = 4;
pub const __UINT_FAST8_MAX__ = 255;
pub const __DBL_MIN_10_EXP__ = -307;
pub const __GLIBC_USE_LIB_EXT2 = 0;
pub const LONG_MAX = __LONG_MAX__;
pub const FREETYPE_PATCH = 1;
pub const __SIZEOF_PTHREAD_MUTEX_T = 40;
pub const __OFF_T_MATCHES_OFF64_T = 1;
pub const __UINT8_FMTu__ = c"hhu";
pub const __RLIM64_T_TYPE = __UQUAD_TYPE;
pub const CHAR_MAX = __SCHAR_MAX__;
pub const FT_SUBGLYPH_FLAG_ARGS_ARE_XY_VALUES = 2;
pub const __HAVE_FLOAT128X = 0;
pub const __UINT16_FMTu__ = c"hu";
pub const __SIZE_FMTu__ = c"lu";
pub const __LDBL_MIN_EXP__ = -16381;
pub const __UINT_FAST32_FMTu__ = c"u";
pub const __pie__ = 2;
pub const __SSP_STRONG__ = 2;
pub const __BYTE_ORDER = __LITTLE_ENDIAN;
pub const __clang_patchlevel__ = 1;
pub const FT_CACHE_INTERNAL_SBITS_H = FT_CACHE_H;
pub const MAX_CANON = 255;
pub const EOF = -1;
pub const CFF_CONFIG_OPTION_DARKENING_PARAMETER_X4 = 2333;
pub const __FXSR__ = 1;
pub const _IOLBF = 1;
pub const ft_sprintf = sprintf;
pub const __UINT32_FMTx__ = c"x";
pub const __UINT32_FMTu__ = c"u";
pub const WNOHANG = 1;
pub const __SIZEOF_PTHREAD_COND_T = 48;
pub const __SIZE_MAX__ = c_ulong(18446744073709551615);
pub const _BITS_UINTN_IDENTITY_H = 1;
pub const CFF_CONFIG_OPTION_DARKENING_PARAMETER_X3 = 1667;
pub const FT_OUTLINE_REVERSE_FILL = 4;
pub const FT_Curve_Tag_Cubic = FT_CURVE_TAG_CUBIC;
pub const CFF_CONFIG_OPTION_DARKENING_PARAMETER_Y1 = 400;
pub const _POSIX_MQ_OPEN_MAX = 8;
pub const FT_Raster_Render_Func = FT_Raster_RenderFunc;
pub const __HAVE_DISTINCT_FLOAT32 = 0;
pub const __USE_ISOC11 = 1;
pub const _POSIX_STREAM_MAX = 8;
pub const __tune_k8__ = 1;
pub const _POSIX2_CHARCLASS_NAME_MAX = 14;
pub const __x86_64__ = 1;
pub const __WORDSIZE_TIME64_COMPAT32 = 1;
pub const __UINTMAX_FMTx__ = c"lx";
pub const __UINT64_C_SUFFIX__ = UL;
pub const __INT_LEAST16_MAX__ = 32767;
pub const ARG_MAX = 131072;
pub const __clock_t_defined = 1;
pub const __UINT32_FMTo__ = c"o";
pub const _SYS_SELECT_H = 1;
pub const FT_OPEN_PARAMS = 16;
pub const _IONBF = 2;
pub const _SYS_TYPES_H = 1;
pub const ft_encoding_adobe_expert = FT_ENCODING_ADOBE_EXPERT;
pub const __INT_LEAST16_TYPE__ = short;
pub const ft_encoding_wansung = FT_ENCODING_WANSUNG;
pub const ft_strncmp = strncmp;
pub const __ORDER_BIG_ENDIAN__ = 4321;
pub const __LDBL_MIN_10_EXP__ = -4931;
pub const __SIZEOF_INT__ = 4;
pub const __USE_POSIX_IMPLICITLY = 1;
pub const _POSIX_DELAYTIMER_MAX = 32;
pub const BC_SCALE_MAX = _POSIX2_BC_SCALE_MAX;
pub const ft_open_memory = FT_OPEN_MEMORY;
pub const _IO_ERR_SEEN = 32;
pub const __amd64 = 1;
pub const __OBJC_BOOL_IS_BOOL = 0;
pub const __LDBL_MAX_10_EXP__ = 4932;
pub const __SIZEOF_INT128__ = 16;
pub const ft_encoding_adobe_standard = FT_ENCODING_ADOBE_STANDARD;
pub const __glibc_c99_flexarr_available = 1;
pub const __linux = 1;
pub const __sigset_t_defined = 1;
pub const __SIZEOF_PTHREAD_MUTEXATTR_T = 4;
pub const __clang__ = 1;
pub const __LDBL_DIG__ = 18;
pub const __GCC_ATOMIC_CHAR32_T_LOCK_FREE = 2;
pub const _BITS_POSIX1_LIM_H = 1;
pub const __UINT64_FMTo__ = c"lo";
pub const __INT_FAST32_FMTd__ = c"d";
pub const BIG_ENDIAN = __BIG_ENDIAN;
pub const __ATOMIC_ACQ_REL = 4;
pub const ft_open_stream = FT_OPEN_STREAM;
pub const __OPENCL_MEMORY_SCOPE_SUB_GROUP = 4;
pub const ____mbstate_t_defined = 1;
pub const _ENDIAN_H = 1;
pub const ft_memmove = memmove;
pub const FT_Raster_Done_Func = FT_Raster_DoneFunc;
pub const CHARCLASS_NAME_MAX = 2048;
pub const __GLIBC__ = 2;
pub const FT_FSTYPE_BITMAP_EMBEDDING_ONLY = 512;
pub const __WORDSIZE = 64;
pub const __INT64_MAX__ = c_long(9223372036854775807);
pub const _BITS_TYPES_LOCALE_T_H = 1;
pub const ft_encoding_adobe_custom = FT_ENCODING_ADOBE_CUSTOM;
pub const __INT_LEAST64_MAX__ = c_long(9223372036854775807);
pub const PTHREAD_KEYS_MAX = 1024;
pub const __OPENCL_MEMORY_SCOPE_WORK_ITEM = 0;
pub const __FLT_HAS_DENORM__ = 1;
pub const __DECIMAL_DIG__ = __LDBL_DECIMAL_DIG__;
pub const FT_OPEN_PATHNAME = 4;
pub const __SYSCALL_SLONG_TYPE = __SLONGWORD_TYPE;
pub const __DEV_T_TYPE = __UQUAD_TYPE;
pub const __INT32_FMTi__ = c"i";
pub const __DBL_HAS_INFINITY__ = 1;
pub const __FINITE_MATH_ONLY__ = 0;
pub const ft_outline_high_precision = FT_OUTLINE_HIGH_PRECISION;
pub const ft_glyph_format_plotter = FT_GLYPH_FORMAT_PLOTTER;
pub const FT_SUBGLYPH_FLAG_ROUND_XY_TO_GRID = 4;
pub const __GCC_ATOMIC_TEST_AND_SET_TRUEVAL = 1;
pub const _STDC_PREDEF_H = 1;
pub const __FLT16_MAX_EXP__ = 15;
pub const __GNUC_VA_LIST = 1;
pub const EXIT_SUCCESS = 0;
pub const _POSIX2_BC_BASE_MAX = 99;
pub const ft_open_params = FT_OPEN_PARAMS;
pub const __SIZEOF_FLOAT__ = 4;
pub const FT_PCF_DRIVER_H = FT_DRIVER_H;
pub const __INT_LEAST32_FMTi__ = c"i";
pub const __LDBL_EPSILON__ = 0.000000;
pub const __INT_LEAST32_FMTd__ = c"d";
pub const __STDC_UTF_32__ = 1;
pub const FT_TRUETYPE_DRIVER_H = FT_DRIVER_H;
pub const __SIG_ATOMIC_WIDTH__ = 32;
pub const __FD_ZERO_STOS = c"stosq";
pub const __UINT_FAST64_FMTX__ = c"lX";
pub const FT_XFREE86_H = FT_FONT_FORMATS_H;
pub const _POSIX_SSIZE_MAX = 32767;
pub const __SIZEOF_DOUBLE__ = 8;
pub const ft_encoding_gb2312 = FT_ENCODING_PRC;
pub const LITTLE_ENDIAN = __LITTLE_ENDIAN;
pub const ft_open_pathname = FT_OPEN_PATHNAME;
pub const __GCC_ATOMIC_SHORT_LOCK_FREE = 2;
pub const _STDLIB_H = 1;
pub const _BITS_STDIO_LIM_H = 1;
pub const __HAVE_FLOAT64 = 1;
pub const BYTE_ORDER = __BYTE_ORDER;
pub const ft_render_mode_mono = FT_RENDER_MODE_MONO;
pub const FT_FSTYPE_INSTALLABLE_EMBEDDING = 0;
pub const __SIZE_FMTX__ = c"lX";
pub const __ID_T_TYPE = __U32_TYPE;
pub const _POSIX_MAX_CANON = 255;
pub const ft_kerning_default = FT_KERNING_DEFAULT;
pub const _BITS_TYPES_H = 1;
pub const __STDC_IEC_559_COMPLEX__ = 1;
pub const __FSBLKCNT64_T_TYPE = __UQUAD_TYPE;
pub const LOGIN_NAME_MAX = 256;
pub const __DBL_MIN_EXP__ = -1021;
pub const __HAVE_FLOAT32X = 1;
pub const __lldiv_t_defined = 1;
pub const ft_glyph_format_none = FT_GLYPH_FORMAT_NONE;
pub const __USECONDS_T_TYPE = __U32_TYPE;
pub const __PID_T_TYPE = __S32_TYPE;
pub const _ALLOCA_H = 1;
pub const FT_CURVE_TAG_CUBIC = 2;
pub const __DBL_HAS_DENORM__ = 1;
pub const __FLOAT128__ = 1;
pub const __HAVE_GENERIC_SELECTION = 1;
pub const __FLT16_HAS_QUIET_NAN__ = 1;
pub const ft_memchr = memchr;
pub const FT_Outline_CubicTo_Func = FT_Outline_CubicToFunc;
pub const __ATOMIC_RELAXED = 0;
pub const __SIZEOF_SHORT__ = 2;
pub const ____FILE_defined = 1;
pub const __UINT_FAST16_MAX__ = 65535;
pub const __UINT16_FMTX__ = c"hX";
pub const TTY_NAME_MAX = 32;
pub const PIPE_BUF = 4096;
pub const __timeval_defined = 1;
pub const __CLANG_ATOMIC_SHORT_LOCK_FREE = 2;
pub const FT_MAX_MODULES = 32;
pub const WEXITED = 4;
pub const __MODE_T_TYPE = __U32_TYPE;
pub const __WINT_MAX__ = c_uint(4294967295);
pub const _STDIO_H = 1;
pub const __STDC_ISO_10646__ = c_long(201706);
pub const FT_RASTER_FLAG_DIRECT = 2;
pub const FT_RENDER_POOL_SIZE = c_long(16384);
pub const __BLKCNT64_T_TYPE = __SQUAD_TYPE;
pub const __STDC_HOSTED__ = 1;
pub const __INT_LEAST32_TYPE__ = int;
pub const __SCHAR_MAX__ = 127;
pub const __USE_POSIX2 = 1;
pub const __HAVE_FLOATN_NOT_TYPEDEF = 0;
pub const __FLT16_MIN_EXP__ = -14;
pub const ft_fread = fread;
pub const __USE_XOPEN2K = 1;
pub const TT_CONFIG_OPTION_MAX_RUNNABLE_OPCODES = c_long(1000000);
pub const __USE_FORTIFY_LEVEL = 0;
pub const __ELF__ = 1;
pub const __LDBL_MANT_DIG__ = 64;
pub const __PTHREAD_MUTEX_LOCK_ELISION = 1;
pub const BC_BASE_MAX = _POSIX2_BC_BASE_MAX;
pub const __USE_XOPEN2K8 = 1;
pub const __CLANG_ATOMIC_INT_LOCK_FREE = 2;
pub const SCHAR_MIN = if (@typeId(@typeOf(-1)) == @import("builtin").TypeId.Pointer) @ptrCast(-__SCHAR_MAX__, -1) else if (@typeId(@typeOf(-1)) == @import("builtin").TypeId.Int) @intToPtr(-__SCHAR_MAX__, -1) else (-__SCHAR_MAX__)(-1);
pub const __UINT64_FMTX__ = c"lX";
pub const ft_strcat = strcat;
pub const __DBL_MANT_DIG__ = 53;
pub const _BITS_POSIX2_LIM_H = 1;
pub const _____fpos_t_defined = 1;
pub const __INT_LEAST32_MAX__ = 2147483647;
pub const _STRING_H = 1;
pub const __OPENCL_MEMORY_SCOPE_WORK_GROUP = 1;
pub const __USE_ISOC95 = 1;
pub const T1_MAX_CHARSTRINGS_OPERANDS = 256;
pub const ft_ftell = ftell;
pub const __UID_T_TYPE = __U32_TYPE;
pub const SHRT_MAX = __SHRT_MAX__;
pub const FT_Outline_ConicTo_Func = FT_Outline_ConicToFunc;
pub const __LITTLE_ENDIAN__ = 1;
pub const __SSE__ = 1;
pub const __FLT_HAS_QUIET_NAN__ = 1;
pub const __SIZEOF_SIZE_T__ = 8;
pub const __UINT_LEAST16_FMTo__ = c"ho";
pub const __HAVE_FLOAT32 = 1;
pub const ft_outline_single_pass = FT_OUTLINE_SINGLE_PASS;
pub const __CLANG_ATOMIC_WCHAR_T_LOCK_FREE = 2;
pub const ft_srealloc = realloc;
pub const __UINTPTR_MAX__ = c_ulong(18446744073709551615);
pub const __UINT_LEAST8_FMTu__ = c"hhu";
pub const __SYSCALL_ULONG_TYPE = __ULONGWORD_TYPE;
pub const __warnattr = msg;
pub const ft_raster_flag_direct = FT_RASTER_FLAG_DIRECT;
pub const __STD_TYPE = typedef;
pub const ft_encoding_big5 = FT_ENCODING_BIG5;
pub const __SIZEOF_WCHAR_T__ = 4;
pub const __LDBL_MAX__ = inf;
pub const _LP64 = 1;
pub const FD_SETSIZE = __FD_SETSIZE;
pub const _POSIX2_COLL_WEIGHTS_MAX = 2;
pub const linux = 1;
pub const FT_FSTYPE_NO_SUBSETTING = 256;
pub const __FLT_DIG__ = 6;
pub const __INT16_MAX__ = 32767;
pub const __FLT_MAX_10_EXP__ = 38;
pub const _FEATURES_H = 1;
pub const __CLANG_ATOMIC_POINTER_LOCK_FREE = 2;
pub const __UINTPTR_FMTX__ = c"lX";
pub const __UINT_LEAST16_FMTu__ = c"hu";
pub const __WINT_WIDTH__ = 32;
pub const __SHRT_MAX__ = 32767;
pub const __GCC_ATOMIC_BOOL_LOCK_FREE = 2;
pub const __INT32_FMTd__ = c"d";
pub const __DBL_MIN__ = 0.000000;
pub const _POSIX_TIMER_MAX = 32;
pub const ft_strlen = strlen;
pub const __S32_TYPE = int;
pub const __INTPTR_WIDTH__ = 64;
pub const T1_MAX_SUBRS_CALLS = 16;
pub const __FLT16_MAX_10_EXP__ = 4;
pub const ft_strstr = strstr;
pub const __INT_FAST32_TYPE__ = int;
pub const __UINT_FAST32_FMTX__ = c"X";
pub const _POSIX_SOURCE = 1;
pub const INT_MAX = __INT_MAX__;
pub const __LITTLE_ENDIAN = 1234;
pub const __gnu_linux__ = 1;
pub const PTHREAD_DESTRUCTOR_ITERATIONS = _POSIX_THREAD_DESTRUCTOR_ITERATIONS;
pub const __FILE_defined = 1;
pub const _____fpos64_t_defined = 1;
pub const _POSIX2_BC_DIM_MAX = 2048;
pub const ft_scalloc = calloc;
pub const __timer_t_defined = 1;
pub const __FLT16_HAS_INFINITY__ = 1;
pub const __GCC_HAVE_SYNC_COMPARE_AND_SWAP_1 = 1;
pub const __GCC_ATOMIC_INT_LOCK_FREE = 2;
pub const ft_memset = memset;
pub const __OPENCL_MEMORY_SCOPE_ALL_SVM_DEVICES = 3;
pub const _POSIX_THREAD_KEYS_MAX = 128;
pub const _BITS_STDINT_INTN_H = 1;
pub const __INT_FAST8_FMTd__ = c"hhd";
pub const __KEY_T_TYPE = __S32_TYPE;
pub const SEEK_SET = 0;
pub const ft_raster_flag_clip = FT_RASTER_FLAG_CLIP;
pub const __USE_POSIX199506 = 1;
pub const __INT32_TYPE__ = int;
pub const ft_pixel_mode_pal4 = FT_PIXEL_MODE_GRAY4;
pub const __FLT_MIN__ = 0.000000;
pub const FT_ULONG_MAX = ULONG_MAX;
pub const __INT8_FMTd__ = c"hhd";
pub const ft_glyph_format_composite = FT_GLYPH_FORMAT_COMPOSITE;
pub const __FLT_MAX_EXP__ = 128;
pub const ft_encoding_unicode = FT_ENCODING_UNICODE;
pub const FT_CACHE_INTERNAL_MANAGER_H = FT_CACHE_H;
pub const FT_FILE = FILE;
pub const FT_CURVE_TAG_TOUCH_Y = 16;
pub const FT_Curve_Tag_Touch_Y = FT_CURVE_TAG_TOUCH_Y;
pub const __INT_FAST64_FMTi__ = c"li";
pub const __INT_LEAST8_FMTd__ = c"hhd";
pub const _POSIX_MQ_PRIO_MAX = 32;
pub const __UINT_LEAST32_FMTX__ = c"X";
pub const __UINTMAX_MAX__ = c_ulong(18446744073709551615);
pub const __UINT_FAST16_FMTo__ = c"ho";
pub const ft_fseek = fseek;
pub const FT_Curve_Tag_On = FT_CURVE_TAG_ON;
pub const _SETJMP_H = 1;
pub const __LDBL_REDIR_DECL = name;
pub const COLL_WEIGHTS_MAX = 255;
pub const ft_pixel_mode_grays = FT_PIXEL_MODE_GRAY;
pub const __OFF64_T_TYPE = __SQUAD_TYPE;
pub const BC_DIM_MAX = _POSIX2_BC_DIM_MAX;
pub const FT_Outline_MoveTo_Func = FT_Outline_MoveToFunc;
pub const _POSIX_PATH_MAX = 256;
pub const FT_SUBGLYPH_FLAG_2X2 = 128;
pub const __SIZE_FMTx__ = c"lx";
pub const _POSIX_OPEN_MAX = 20;
pub const __DBL_EPSILON__ = 0.000000;
pub const __BLKCNT_T_TYPE = __SYSCALL_SLONG_TYPE;
pub const __CHAR_BIT__ = 8;
pub const __INT16_FMTi__ = c"hi";
pub const SEEK_CUR = 1;
pub const __GNUC_MINOR__ = 2;
pub const FT_SUBGLYPH_FLAG_XY_SCALE = 64;
pub const __UINT_FAST32_MAX__ = c_uint(4294967295);
pub const FT_CACHE_MANAGER_H = FT_CACHE_H;
pub const ft_longjmp = longjmp;
pub const NFDBITS = __NFDBITS;
pub const FT_FSTYPE_RESTRICTED_LICENSE_EMBEDDING = 2;
pub const __FLT_EPSILON__ = 0.000000;
pub const ft_memcpy = memcpy;
pub const __llvm__ = 1;
pub const __UINT_FAST64_MAX__ = c_ulong(18446744073709551615);
pub const FT_CACHE_INTERNAL_CACHE_H = FT_CACHE_H;
pub const __INT_FAST32_FMTi__ = c"i";
pub const NR_OPEN = 1024;
pub const __FLT_HAS_INFINITY__ = 1;
pub const __FSWORD_T_TYPE = __SYSCALL_SLONG_TYPE;
pub const NULL = if (@typeId(@typeOf(0)) == @import("builtin").TypeId.Pointer) @ptrCast([*]void, 0) else if (@typeId(@typeOf(0)) == @import("builtin").TypeId.Int) @intToPtr([*]void, 0) else ([*]void)(0);
pub const __OFF_T_TYPE = __SYSCALL_SLONG_TYPE;
pub const FT_ERR_PREFIX = FT_Err_;
pub const XATTR_SIZE_MAX = 65536;
pub const TT_CONFIG_OPTION_SUBPIXEL_HINTING = 2;
pub const __GCC_ATOMIC_CHAR16_T_LOCK_FREE = 2;
pub const __UINT32_FMTX__ = c"X";
pub const __PTHREAD_MUTEX_NUSERS_AFTER_KIND = 0;
pub const FT_OUTLINE_POINTS_MAX = SHRT_MAX;
pub const __UINT32_C_SUFFIX__ = U;
pub const __INT32_MAX__ = 2147483647;
pub const __GCC_ATOMIC_CHAR_LOCK_FREE = 2;
pub const __BIT_TYPES_DEFINED__ = 1;
pub const CFF_CONFIG_OPTION_DARKENING_PARAMETER_X1 = 500;
pub const __DBL_HAS_QUIET_NAN__ = 1;
pub const _POSIX_THREAD_DESTRUCTOR_ITERATIONS = 4;
pub const CFF_CONFIG_OPTION_DARKENING_PARAMETER_Y3 = 275;
pub const __STDC_UTF_16__ = 1;
pub const __UINT_LEAST32_MAX__ = c_uint(4294967295);
pub const __ATOMIC_RELEASE = 3;
pub const __UINTMAX_C_SUFFIX__ = UL;
pub const FT_OUTLINE_IGNORE_DROPOUTS = 8;
pub const __SIZEOF_LONG_DOUBLE__ = 16;
pub const __ldiv_t_defined = 1;
pub const ft_outline_none = FT_OUTLINE_NONE;
pub const __ORDER_PDP_ENDIAN__ = 3412;
pub const __SIZEOF_PTHREAD_BARRIER_T = 32;
pub const __GLIBC_USE_IEC_60559_FUNCS_EXT = 0;
pub const FILENAME_MAX = 4096;
pub const FT_INT64 = long;
pub const FT_FSTYPE_PREVIEW_AND_PRINT_EMBEDDING = 4;
pub const _POSIX_TTY_NAME_MAX = 9;
pub const __INT16_TYPE__ = short;
pub const CFF_CONFIG_OPTION_DARKENING_PARAMETER_Y4 = 0;
pub const __SSE2_MATH__ = 1;
pub const __GLIBC_USE_IEC_60559_TYPES_EXT = 0;
pub const EXPR_NEST_MAX = _POSIX2_EXPR_NEST_MAX;
pub const ft_outline_ignore_dropouts = FT_OUTLINE_IGNORE_DROPOUTS;
pub const ft_pixel_mode_mono = FT_PIXEL_MODE_MONO;
pub const __INT_FAST8_MAX__ = 127;
pub const __STDC_IEC_559__ = 1;
pub const __USE_ISOC99 = 1;
pub const __INTPTR_MAX__ = c_long(9223372036854775807);
pub const __UINT64_FMTu__ = c"lu";
pub const __BYTE_ORDER__ = __ORDER_LITTLE_ENDIAN__;
pub const __SSE2__ = 1;
pub const __INTMAX_FMTi__ = c"li";
pub const __GNUC__ = 4;
pub const __UINT32_MAX__ = c_uint(4294967295);
pub const _BITS_TYPES___LOCALE_T_H = 1;
pub const FT_SUBGLYPH_FLAG_SCALE = 8;
pub const _POSIX_C_SOURCE = c_long(200809);
pub const ft_smalloc = malloc;
pub const __DBL_MAX_EXP__ = 1024;
pub const __INT8_FMTi__ = c"hhi";
pub const L_tmpnam = 20;
pub const __FLT16_MIN_10_EXP__ = -13;
pub const ft_memcmp = memcmp;
pub const _POSIX_THREAD_THREADS_MAX = 64;
pub const __INT_FAST64_MAX__ = c_long(9223372036854775807);
pub const __ATOMIC_SEQ_CST = 5;
pub const ft_qsort = qsort;
pub const FT_OPEN_MEMORY = 1;
pub const _POSIX_PIPE_BUF = 512;
pub const ft_encoding_sjis = FT_ENCODING_SJIS;
pub const ft_encoding_apple_roman = FT_ENCODING_APPLE_ROMAN;
pub const _POSIX_SEM_NSEMS_MAX = 256;
pub const __SIZEOF_LONG_LONG__ = 8;
pub const __HAVE_DISTINCT_FLOAT64X = 0;
pub const __GNUC_STDC_INLINE__ = 1;
pub const SEM_VALUE_MAX = 2147483647;
pub const __UINT8_MAX__ = 255;
pub const _STRINGS_H = 1;
pub const __GCC_HAVE_SYNC_COMPARE_AND_SWAP_2 = 1;
pub const ft_glyph_format_outline = FT_GLYPH_FORMAT_OUTLINE;
pub const __UINT16_FMTo__ = c"ho";
pub const __OPENCL_MEMORY_SCOPE_DEVICE = 2;
pub const __SIZEOF_PTHREAD_CONDATTR_T = 4;
pub const FT_Outline_LineTo_Func = FT_Outline_LineToFunc;
pub const FT_OPEN_DRIVER = 8;
pub const __SIZEOF_POINTER__ = 8;
pub const __TIMER_T_TYPE = [*]void;
pub const __unix = 1;
pub const __GLIBC_USE_IEC_60559_BFP_EXT = 0;
pub const __INT_FAST16_FMTd__ = c"hd";
pub const unix = 1;
pub const __UINT_LEAST32_FMTu__ = c"u";
pub const __FLT_MAX__ = 340282346999999984391321947108527833088.000000;
pub const BUFSIZ = 8192;
pub const ft_encoding_latin_2 = FT_ENCODING_OLD_LATIN_2;
pub const __GCC_ATOMIC_WCHAR_T_LOCK_FREE = 2;
pub const __k8__ = 1;
pub const ft_encoding_symbol = FT_ENCODING_MS_SYMBOL;
pub const __ATOMIC_CONSUME = 1;
pub const __unix__ = 1;
pub const __LDBL_HAS_INFINITY__ = 1;
pub const __GNU_LIBRARY__ = 6;
pub const FT_CURVE_TAG_TOUCH_X = 8;
pub const FT_Curve_Tag_Touch_X = FT_CURVE_TAG_TOUCH_X;
pub const __FLT_MIN_10_EXP__ = -37;
pub const ft_outline_owner = FT_OUTLINE_OWNER;
pub const __UINTPTR_FMTo__ = c"lo";
pub const __INT_LEAST16_FMTd__ = c"hd";
pub const __UINTPTR_FMTx__ = c"lx";
pub const __GCC_HAVE_SYNC_COMPARE_AND_SWAP_8 = 1;
pub const __INT_LEAST64_FMTd__ = c"ld";
pub const FT_OUTLINE_INCLUDE_STUBS = 32;
pub const SSIZE_MAX = LONG_MAX;
pub const __attribute_alloc_size__ = params;
pub const __INT_LEAST8_MAX__ = 127;
pub const _POSIX2_BC_STRING_MAX = 1000;
pub const __GCC_ATOMIC_POINTER_LOCK_FREE = 2;
pub const LLONG_MAX = __LONG_LONG_MAX__;
pub const L_ctermid = 9;
pub const ft_getenv = getenv;
pub const FT_Raster_Set_Mode_Func = FT_Raster_SetModeFunc;
pub const __UINT_FAST8_FMTx__ = c"hhx";
pub const __PIE__ = 2;
pub const __SIZEOF_PTHREAD_RWLOCK_T = 56;
pub const CHAR_MIN = SCHAR_MIN;
pub const FT_INT_MAX = INT_MAX;
pub const __UINT16_FMTx__ = c"hx";
pub const __UINTPTR_FMTu__ = c"lu";
pub const __UINT_LEAST16_FMTX__ = c"hX";
pub const __amd64__ = 1;
pub const __UINT_FAST32_FMTo__ = c"o";
pub const __linux__ = 1;
pub const __LP64__ = 1;
pub const __SYSCALL_WORDSIZE = 64;
pub const __PTRDIFF_FMTi__ = c"li";
pub const _POSIX_RTSIG_MAX = 8;
pub const FT_CACHE_INTERNAL_GLYPH_H = FT_CACHE_H;
pub const _BITS_TYPESIZES_H = 1;
pub const FT_USHORT_MAX = USHRT_MAX;
pub const WCONTINUED = 8;
pub const __HAVE_DISTINCT_FLOAT128X = __HAVE_FLOAT128X;
pub const _BITS_PTHREADTYPES_ARCH_H = 1;
pub const _POSIX_CHILD_MAX = 25;
pub const FT_OUTLINE_CONTOURS_MAX = SHRT_MAX;
pub const PDP_ENDIAN = __PDP_ENDIAN;
pub const __SIZEOF_PTHREAD_BARRIERATTR_T = 4;
pub const __LONG_LONG_MAX__ = c_longlong(9223372036854775807);
pub const _POSIX_SYMLOOP_MAX = 8;
pub const _POSIX_SIGQUEUE_MAX = 32;
pub const FT_Raster_Reset_Func = FT_Raster_ResetFunc;
pub const FT_CACHE_CHARMAP_H = FT_CACHE_H;
pub const _POSIX_SEM_VALUE_MAX = 32767;
pub const __INO_T_MATCHES_INO64_T = 1;
pub const FT_LONG_MIN = LONG_MIN;
pub const WUNTRACED = 2;
pub const ft_glyph_format_bitmap = FT_GLYPH_FORMAT_BITMAP;
pub const __INTMAX_MAX__ = c_long(9223372036854775807);
pub const __UINT_LEAST32_FMTx__ = c"x";
pub const __WCHAR_MAX__ = 2147483647;
pub const ft_kerning_unfitted = FT_KERNING_UNFITTED;
pub const WSTOPPED = 2;
pub const __CLANG_ATOMIC_CHAR32_T_LOCK_FREE = 2;
pub const WNOWAIT = 16777216;
pub const __UINTMAX_FMTX__ = c"lX";
pub const CFF_CONFIG_OPTION_DARKENING_PARAMETER_Y2 = 275;
pub const LINE_MAX = _POSIX2_LINE_MAX;
pub const ft_outline_even_odd_fill = FT_OUTLINE_EVEN_ODD_FILL;
pub const _POSIX_AIO_MAX = 1;
pub const _POSIX2_LINE_MAX = 2048;
pub const __WCLONE = 2147483648;
pub const NAME_MAX = 255;
pub const DELAYTIMER_MAX = 2147483647;
pub const __locale_data = struct___locale_data;
pub const __locale_struct = struct___locale_struct;
pub const __va_list_tag = struct___va_list_tag;
pub const _G_fpos_t = struct__G_fpos_t;
pub const _G_fpos64_t = struct__G_fpos64_t;
pub const _IO_marker = struct__IO_marker;
pub const _IO_codecvt = struct__IO_codecvt;
pub const _IO_wide_data = struct__IO_wide_data;
pub const _IO_FILE = struct__IO_FILE;
pub const timeval = struct_timeval;
pub const timespec = struct_timespec;
pub const __pthread_rwlock_arch_t = struct___pthread_rwlock_arch_t;
pub const __pthread_internal_list = struct___pthread_internal_list;
pub const __pthread_mutex_s = struct___pthread_mutex_s;
pub const __pthread_cond_s = struct___pthread_cond_s;
pub const random_data = struct_random_data;
pub const drand48_data = struct_drand48_data;
pub const __jmp_buf_tag = struct___jmp_buf_tag;
pub const FT_MemoryRec_ = struct_FT_MemoryRec_;
pub const FT_StreamDesc_ = union_FT_StreamDesc_;
pub const FT_StreamRec_ = struct_FT_StreamRec_;
pub const FT_Vector_ = struct_FT_Vector_;
pub const FT_BBox_ = struct_FT_BBox_;
pub const FT_Pixel_Mode_ = enum_FT_Pixel_Mode_;
pub const FT_Bitmap_ = struct_FT_Bitmap_;
pub const FT_Outline_ = struct_FT_Outline_;
pub const FT_Outline_Funcs_ = struct_FT_Outline_Funcs_;
pub const FT_Glyph_Format_ = enum_FT_Glyph_Format_;
pub const FT_RasterRec_ = struct_FT_RasterRec_;
pub const FT_Span_ = struct_FT_Span_;
pub const FT_Raster_Params_ = struct_FT_Raster_Params_;
pub const FT_Raster_Funcs_ = struct_FT_Raster_Funcs_;
pub const FT_UnitVector_ = struct_FT_UnitVector_;
pub const FT_Matrix_ = struct_FT_Matrix_;
pub const FT_Data_ = struct_FT_Data_;
pub const FT_Generic_ = struct_FT_Generic_;
pub const FT_ListNodeRec_ = struct_FT_ListNodeRec_;
pub const FT_ListRec_ = struct_FT_ListRec_;
pub const FT_Glyph_Metrics_ = struct_FT_Glyph_Metrics_;
pub const FT_Bitmap_Size_ = struct_FT_Bitmap_Size_;
pub const FT_LibraryRec_ = struct_FT_LibraryRec_;
pub const FT_ModuleRec_ = struct_FT_ModuleRec_;
pub const FT_DriverRec_ = struct_FT_DriverRec_;
pub const FT_RendererRec_ = struct_FT_RendererRec_;
pub const FT_Encoding_ = enum_FT_Encoding_;
pub const FT_CharMapRec_ = struct_FT_CharMapRec_;
pub const FT_SubGlyphRec_ = struct_FT_SubGlyphRec_;
pub const FT_Slot_InternalRec_ = struct_FT_Slot_InternalRec_;
pub const FT_GlyphSlotRec_ = struct_FT_GlyphSlotRec_;
pub const FT_Size_Metrics_ = struct_FT_Size_Metrics_;
pub const FT_Size_InternalRec_ = struct_FT_Size_InternalRec_;
pub const FT_SizeRec_ = struct_FT_SizeRec_;
pub const FT_Face_InternalRec_ = struct_FT_Face_InternalRec_;
pub const FT_FaceRec_ = struct_FT_FaceRec_;
pub const FT_Parameter_ = struct_FT_Parameter_;
pub const FT_Open_Args_ = struct_FT_Open_Args_;
pub const FT_Size_Request_Type_ = enum_FT_Size_Request_Type_;
pub const FT_Size_RequestRec_ = struct_FT_Size_RequestRec_;
pub const FT_Render_Mode_ = enum_FT_Render_Mode_;
pub const FT_Kerning_Mode_ = enum_FT_Kerning_Mode_; | freetype2.original.zig |
const std = @import("std");
const os = std.os;
const builtin = @import("builtin");
const assert = std.debug.assert;
const Allocator = std.mem.Allocator;
const page_size = std.os.page_size;
const posix = std.os.posix;
fn up_to_nearest_power_of_2(comptime T: type, n: T) T {
var power: T = 1;
while (power < n)
power *= 2;
return power;
}
// Number of stack frames to capture
const stack_n = 4;
const one_trace_size = @sizeOf(usize) * stack_n;
const traces_per_slot = 2;
// Bucket: In memory, in order:
// * BucketHeader
// * bucket_used_bits: [N]u8, // 1 bit for every slot; 1 byte for every 8 slots
// * stack_trace_addresses: [N]usize, // traces_per_slot for every allocation
const BucketHeader = struct {
prev: *BucketHeader,
next: *BucketHeader,
page: [*]align(page_size) u8,
used_bits_index: usize,
used_count: usize,
fn usedBits(bucket: *BucketHeader, index: usize) *u8 {
return @intToPtr(*u8, @ptrToInt(bucket) + @sizeOf(BucketHeader) + index);
}
fn stackTracePtr(
bucket: *BucketHeader,
size_class: usize,
slot_index: usize,
trace_kind: TraceKind,
) *[stack_n]usize {
const start_ptr = @ptrCast([*]u8, bucket) + bucketStackFramesStart(size_class);
const addr = start_ptr + one_trace_size * traces_per_slot * slot_index +
@enumToInt(trace_kind) * usize(one_trace_size);
return @ptrCast(*[stack_n]usize, addr);
}
fn captureStackTrace(
bucket: *BucketHeader,
return_address: usize,
size_class: usize,
slot_index: usize,
trace_kind: TraceKind,
) void {
// Initialize them to 0. When determining the count we must look
// for non zero addresses.
const stack_addresses = bucket.stackTracePtr(size_class, slot_index, trace_kind);
std.mem.set(usize, stack_addresses, 0);
var stack_trace = builtin.StackTrace{
.instruction_addresses = stack_addresses,
.index = 0,
};
std.debug.captureStackTrace(return_address, &stack_trace);
}
};
const TraceKind = enum {
Alloc,
Free,
};
fn bucketStackTrace(
bucket: *BucketHeader,
size_class: usize,
slot_index: usize,
trace_kind: TraceKind,
) builtin.StackTrace {
const stack_addresses = bucket.stackTracePtr(size_class, slot_index, trace_kind);
var len: usize = 0;
while (len < stack_n and stack_addresses[len] != 0) {
len += 1;
}
return builtin.StackTrace{
.instruction_addresses = stack_addresses,
.index = len,
};
}
fn bucketStackFramesStart(size_class: usize) usize {
return std.mem.alignForward(
@sizeOf(BucketHeader) + usedBitsCount(size_class),
@alignOf(usize),
);
}
fn bucketSize(size_class: usize) usize {
const slot_count = @divExact(page_size, size_class);
return bucketStackFramesStart(size_class) + one_trace_size * traces_per_slot * slot_count;
}
fn usedBitsCount(size_class: usize) usize {
const slot_count = @divExact(page_size, size_class);
return @divExact(slot_count, 8);
}
fn hash_addr(addr: usize) u32 {
// TODO ignore the least significant bits because addr is guaranteed
// to be page aligned
if (@sizeOf(usize) == @sizeOf(u32))
return addr;
comptime assert(@sizeOf(usize) == 8);
return @intCast(u32, addr >> 32) ^ @truncate(u32, addr);
}
fn eql_addr(a: usize, b: usize) bool {
return a == b;
}
fn sysAlloc(len: usize) error{OutOfMemory}![]align(page_size) u8 {
const perms = posix.PROT_READ | posix.PROT_WRITE;
const flags = posix.MAP_PRIVATE | posix.MAP_ANONYMOUS;
const addr = posix.mmap(null, len, perms, flags, -1, 0);
if (addr == posix.MAP_FAILED) return error.OutOfMemory;
return @intToPtr([*]align(page_size) u8, addr)[0..len];
}
fn sysFree(old_mem: []u8) void {
assert(posix.getErrno(posix.munmap(@ptrToInt(old_mem.ptr), old_mem.len)) == 0);
}
const SimpleAllocator = struct {
allocator: Allocator,
active_allocation: []u8,
fn init() SimpleAllocator {
return SimpleAllocator{
.allocator = Allocator{
.reallocFn = realloc,
.shrinkFn = shrink,
},
.active_allocation = (([*]u8)(undefined))[0..0],
};
}
fn deinit(self: SimpleAllocator) void {
if (self.active_allocation.len == 0) return;
sysFree(self.active_allocation);
}
fn realloc(
allocator: *Allocator,
old_mem: []u8,
old_align: u29,
new_size: usize,
new_align: u29,
) error{OutOfMemory}![]u8 {
assert(old_mem.len == 0);
assert(new_align < page_size);
const self = @fieldParentPtr(SimpleAllocator, "allocator", allocator);
const result = try sysAlloc(new_size);
self.active_allocation = result;
return result;
}
fn shrink(
allocator: *Allocator,
old_mem: []u8,
old_align: u29,
new_size: usize,
new_align: u29,
) []u8 {
assert(new_size == 0);
sysFree(old_mem);
return old_mem[0..0];
}
/// Applies to all of the bytes in the entire allocator.
pub fn mprotect(self: *SimpleAllocator, protection: u32) void {
if (self.active_allocation.len == 0) return;
os.posixMProtect(
@ptrToInt(self.active_allocation.ptr),
std.mem.alignForward(self.active_allocation.len, page_size),
protection,
) catch unreachable;
}
};
pub const GeneralPurposeDebugAllocator = struct {
allocator: Allocator,
buckets: [small_bucket_count]?*BucketHeader,
simple_allocator: SimpleAllocator,
large_allocations: LargeAllocTable,
pub const Error = std.mem.Allocator.Error;
const small_bucket_count = std.math.log2(page_size);
const largest_bucket_object_size = 1 << (small_bucket_count - 1);
const LargeAlloc = struct {
bytes: []u8,
stack_addresses: [stack_n]usize,
fn dumpStackTrace(self: *LargeAlloc) void {
var len: usize = 0;
while (len < stack_n and self.stack_addresses[len] != 0) {
len += 1;
}
const stack_trace = builtin.StackTrace{
.instruction_addresses = &self.stack_addresses,
.index = len,
};
std.debug.dumpStackTrace(stack_trace);
}
};
const LargeAllocTable = std.HashMap(usize, LargeAlloc, hash_addr, eql_addr);
pub fn create() !*GeneralPurposeDebugAllocator {
const self_bytes = try sysAlloc(@sizeOf(GeneralPurposeDebugAllocator));
const self = @ptrCast(*GeneralPurposeDebugAllocator, self_bytes.ptr);
self.* = GeneralPurposeDebugAllocator{
.allocator = Allocator{
.reallocFn = realloc,
.shrinkFn = shrink,
},
.buckets = [1]?*BucketHeader{null} ** small_bucket_count,
.simple_allocator = SimpleAllocator.init(),
.large_allocations = LargeAllocTable.init(&self.simple_allocator.allocator),
};
try self.mprotectInit(posix.PROT_READ);
return self;
}
fn mprotectInit(self: *GeneralPurposeDebugAllocator, protection: u32) !void {
os.posixMProtect(@ptrToInt(self), page_size, protection) catch |e| switch (e) {
error.AccessDenied => unreachable,
error.OutOfMemory => return error.OutOfMemory,
error.Unexpected => return error.OutOfMemory,
};
}
fn mprotect(self: *GeneralPurposeDebugAllocator, protection: u32) void {
os.posixMProtect(@ptrToInt(self), page_size, protection) catch unreachable;
}
pub fn destroy(self: *GeneralPurposeDebugAllocator) void {
for (self.buckets) |optional_bucket, bucket_i| {
const bucket = optional_bucket orelse continue;
const size_class = usize(1) << @intCast(u6, bucket_i);
const used_bits_count = usedBitsCount(size_class);
var used_bits_byte: usize = 0;
while (used_bits_byte < used_bits_count) : (used_bits_byte += 1) {
const used_byte = bucket.usedBits(used_bits_byte).*;
if (used_byte != 0) {
var bit_index: u3 = 0;
while (true) : (bit_index += 1) {
const is_used = @truncate(u1, used_byte >> bit_index) != 0;
if (is_used) {
std.debug.warn("\nMemory leak detected:\n");
const slot_index = used_bits_byte * 8 + bit_index;
const stack_trace = bucketStackTrace(
bucket,
size_class,
slot_index,
TraceKind.Alloc,
);
std.debug.dumpStackTrace(stack_trace);
}
if (bit_index == std.math.maxInt(u3))
break;
}
}
}
}
var large_it = self.large_allocations.iterator();
while (large_it.next()) |large_alloc| {
std.debug.warn("\nMemory leak detected:\n");
large_alloc.value.dumpStackTrace();
}
self.simple_allocator.deinit(); // Free large_allocations memory.
sysFree(@ptrCast([*]u8, self)[0..@sizeOf(GeneralPurposeDebugAllocator)]);
}
fn directAlloc(
self: *GeneralPurposeDebugAllocator,
n: usize,
alignment: u29,
first_trace_addr: usize,
) Error![]u8 {
const p = posix;
const alloc_size = if (alignment <= os.page_size) n else n + alignment;
const slice = try sysAlloc(alloc_size);
errdefer sysFree(slice);
if (alloc_size == n) {
try self.trackLargeAlloc(slice, first_trace_addr);
return slice;
}
const addr = @ptrToInt(slice.ptr);
const aligned_addr = std.mem.alignForward(addr, alignment);
// We can unmap the unused portions of our mmap, but we must only
// pass munmap bytes that exist outside our allocated pages or it
// will happily eat us too.
// Since alignment > page_size, we are by definition on a page boundary.
const unused_len = aligned_addr - 1 - addr;
sysFree(slice[0..unused_len]);
// It is impossible that there is an unoccupied page at the top of our
// mmap.
const result = @intToPtr([*]u8, aligned_addr)[0..n];
try self.trackLargeAlloc(result, first_trace_addr);
return result;
}
fn trackLargeAlloc(
self: *GeneralPurposeDebugAllocator,
bytes: []u8,
first_trace_addr: usize,
) !void {
self.simple_allocator.mprotect(posix.PROT_WRITE | posix.PROT_READ);
defer self.simple_allocator.mprotect(posix.PROT_READ);
const gop = try self.large_allocations.getOrPut(@ptrToInt(bytes.ptr));
if (gop.found_existing) {
@panic("OS provided unexpected memory address");
}
gop.kv.value.bytes = bytes;
std.mem.set(usize, &gop.kv.value.stack_addresses, 0);
var stack_trace = builtin.StackTrace{
.instruction_addresses = &gop.kv.value.stack_addresses,
.index = 0,
};
std.debug.captureStackTrace(first_trace_addr, &stack_trace);
}
fn allocSlot(
self: *GeneralPurposeDebugAllocator,
size_class: usize,
trace_addr: usize,
) Error![*]u8 {
const bucket_index = std.math.log2(size_class);
const first_bucket = self.buckets[bucket_index] orelse try self.createBucket(
size_class,
bucket_index,
);
var bucket = first_bucket;
while (bucket.used_count == usize(page_size) >> @intCast(u6, bucket_index)) {
const prev_bucket = bucket;
bucket = prev_bucket.next;
if (bucket == first_bucket) {
// make a new one
bucket = try self.createBucket(size_class, bucket_index);
bucket.prev = prev_bucket;
bucket.next = prev_bucket.next;
prev_bucket.next = bucket;
bucket.next.prev = bucket;
}
}
// change the allocator's current bucket to be this one
self.buckets[bucket_index] = bucket;
bucket.used_count += 1;
var used_bits_byte = bucket.usedBits(bucket.used_bits_index);
while (used_bits_byte.* == 0xff) {
bucket.used_bits_index = (bucket.used_bits_index + 1) %
usedBitsCount(size_class);
used_bits_byte = bucket.usedBits(bucket.used_bits_index);
}
var used_bit_index: u3 = 0;
while (@truncate(u1, used_bits_byte.* >> used_bit_index) == 1) {
used_bit_index += 1;
}
used_bits_byte.* |= (u8(1) << used_bit_index);
const slot_index = bucket.used_bits_index * 8 + used_bit_index;
bucket.captureStackTrace(trace_addr, size_class, slot_index, TraceKind.Alloc);
return bucket.page + slot_index * size_class;
}
fn reallocLarge(
self: *GeneralPurposeDebugAllocator,
old_mem: []u8,
old_align: u29,
new_size: usize,
alignment: u29,
) Error![]u8 {
@panic("TODO handle realloc of large object");
}
fn searchBucket(
self: *GeneralPurposeDebugAllocator,
bucket_index: usize,
addr: usize,
) ?*BucketHeader {
const first_bucket = self.buckets[bucket_index].?;
var bucket = first_bucket;
while (true) {
const in_bucket_range = (addr >= @ptrToInt(bucket.page) and
addr < @ptrToInt(bucket.page) + page_size);
if (in_bucket_range) return bucket;
bucket = bucket.prev;
if (bucket == first_bucket) {
return null;
}
self.buckets[bucket_index] = bucket;
}
}
fn freeSlot(
self: *GeneralPurposeDebugAllocator,
bucket: *BucketHeader,
bucket_index: usize,
size_class: usize,
slot_index: usize,
used_byte: *u8,
used_bit_index: u3,
trace_addr: usize,
) void {
// Capture stack trace to be the "first free", in case a double free happens.
bucket.captureStackTrace(@returnAddress(), size_class, slot_index, TraceKind.Free);
used_byte.* &= ~(u8(1) << used_bit_index);
bucket.used_count -= 1;
if (bucket.used_count == 0) {
if (bucket.next == bucket) {
// it's the only bucket and therefore the current one
self.buckets[bucket_index] = null;
} else {
bucket.next.prev = bucket.prev;
bucket.prev.next = bucket.next;
self.buckets[bucket_index] = bucket.prev;
}
sysFree(bucket.page[0..page_size]);
const bucket_size = bucketSize(size_class);
const aligned_bucket_size = std.mem.alignForward(bucket_size, page_size);
sysFree(@ptrCast([*]u8, bucket)[0..aligned_bucket_size]);
}
}
fn realloc(
allocator: *Allocator,
old_mem: []u8,
old_align: u29,
new_size: usize,
new_align: u29,
) Error![]u8 {
const self = @fieldParentPtr(GeneralPurposeDebugAllocator, "allocator", allocator);
self.mprotect(posix.PROT_WRITE | posix.PROT_READ);
defer self.mprotect(posix.PROT_READ);
if (old_mem.len == 0) {
const new_aligned_size = std.math.max(new_size, new_align);
if (new_aligned_size > largest_bucket_object_size) {
return self.directAlloc(new_size, new_align, @returnAddress());
} else {
const new_size_class = up_to_nearest_power_of_2(usize, new_aligned_size);
const ptr = try self.allocSlot(new_size_class, @returnAddress());
return ptr[0..new_size];
}
}
const aligned_size = std.math.max(old_mem.len, old_align);
if (aligned_size > largest_bucket_object_size) {
return self.reallocLarge(old_mem, old_align, new_size, new_align);
}
const size_class = up_to_nearest_power_of_2(usize, aligned_size);
var bucket_index = std.math.log2(size_class);
const bucket = while (bucket_index < small_bucket_count) : (bucket_index += 1) {
if (self.searchBucket(bucket_index, @ptrToInt(old_mem.ptr))) |bucket| {
break bucket;
}
} else {
return self.reallocLarge(old_mem, old_align, new_size, new_align);
};
const byte_offset = @ptrToInt(old_mem.ptr) - @ptrToInt(bucket.page);
const slot_index = byte_offset / size_class;
const used_byte_index = slot_index / 8;
const used_bit_index = @intCast(u3, slot_index % 8);
const used_byte = bucket.usedBits(used_byte_index);
const is_used = @truncate(u1, used_byte.* >> used_bit_index) != 0;
if (!is_used) {
// print allocation stack trace
std.debug.warn("\nDouble free detected, allocated here:\n");
const alloc_stack_trace = bucketStackTrace(
bucket,
size_class,
slot_index,
TraceKind.Alloc,
);
std.debug.dumpStackTrace(alloc_stack_trace);
std.debug.warn("\nFirst free here:\n");
const free_stack_trace = bucketStackTrace(
bucket,
size_class,
slot_index,
TraceKind.Free,
);
std.debug.dumpStackTrace(free_stack_trace);
@panic("\nSecond free here:");
}
if (new_size == 0) {
self.freeSlot(
bucket,
bucket_index,
size_class,
slot_index,
used_byte,
used_bit_index,
@returnAddress(),
);
return old_mem[0..0];
}
const new_aligned_size = std.math.max(new_size, new_align);
const new_size_class = up_to_nearest_power_of_2(usize, new_aligned_size);
if (size_class == new_size_class) {
return old_mem.ptr[0..new_size];
}
if (new_size_class > largest_bucket_object_size) {
@panic("realloc moving from buckets to non buckets");
}
const ptr = try self.allocSlot(new_size_class, @returnAddress());
@memcpy(ptr, old_mem.ptr, old_mem.len);
self.freeSlot(
bucket,
bucket_index,
size_class,
slot_index,
used_byte,
used_bit_index,
@returnAddress(),
);
return ptr[0..new_size];
}
fn directFree(self: *GeneralPurposeDebugAllocator, bytes: []u8) void {
self.simple_allocator.mprotect(posix.PROT_WRITE | posix.PROT_READ);
defer self.simple_allocator.mprotect(posix.PROT_READ);
const kv = self.large_allocations.get(@ptrToInt(bytes.ptr)).?;
if (bytes.len != kv.value.bytes.len) {
std.debug.warn(
"\nAllocation size {} bytes does not match free size {}. Allocated here:\n",
kv.value.bytes.len,
bytes.len,
);
kv.value.dumpStackTrace();
@panic("\nFree here:");
}
// TODO we should be able to replace the above call to get() with remove()
// is it a hash table bug?
assert(self.large_allocations.remove(@ptrToInt(bytes.ptr)) != null);
sysFree(bytes);
}
fn shrink(
allocator: *Allocator,
old_mem: []u8,
old_align: u29,
new_size: usize,
new_align: u29,
) []u8 {
const self = @fieldParentPtr(GeneralPurposeDebugAllocator, "allocator", allocator);
self.mprotect(posix.PROT_WRITE | posix.PROT_READ);
defer self.mprotect(posix.PROT_READ);
if (new_size > 0) {
@panic("TODO handle shrink to nonzero");
}
const aligned_size = std.math.max(old_mem.len, old_align);
if (aligned_size > largest_bucket_object_size) {
self.directFree(old_mem);
return old_mem[0..0];
}
const size_class = up_to_nearest_power_of_2(usize, aligned_size);
const bucket_index = std.math.log2(size_class);
const bucket = self.searchBucket(bucket_index, @ptrToInt(old_mem.ptr)) orelse {
@panic("Invalid free");
};
const byte_offset = @ptrToInt(old_mem.ptr) - @ptrToInt(bucket.page);
const slot_index = byte_offset / size_class;
const used_byte_index = slot_index / 8;
const used_bit_index = @intCast(u3, slot_index % 8);
const used_byte = bucket.usedBits(used_byte_index);
const is_used = @truncate(u1, used_byte.* >> used_bit_index) != 0;
if (!is_used) {
// print allocation stack trace
std.debug.warn("\nDouble free detected, allocated here:\n");
const alloc_stack_trace = bucketStackTrace(
bucket,
size_class,
slot_index,
TraceKind.Alloc,
);
std.debug.dumpStackTrace(alloc_stack_trace);
std.debug.warn("\nFirst free here:\n");
const free_stack_trace = bucketStackTrace(
bucket,
size_class,
slot_index,
TraceKind.Free,
);
std.debug.dumpStackTrace(free_stack_trace);
@panic("\nSecond free here:");
}
self.freeSlot(
bucket,
bucket_index,
size_class,
slot_index,
used_byte,
used_bit_index,
@returnAddress(),
);
return old_mem[0..0];
}
fn createBucket(
self: *GeneralPurposeDebugAllocator,
size_class: usize,
bucket_index: usize,
) Error!*BucketHeader {
const page = try sysAlloc(page_size);
errdefer sysFree(page);
const bucket_size = bucketSize(size_class);
const aligned_bucket_size = std.mem.alignForward(bucket_size, page_size);
const bucket_bytes = try sysAlloc(aligned_bucket_size);
const ptr = @ptrCast(*BucketHeader, bucket_bytes.ptr);
ptr.* = BucketHeader{
.prev = ptr,
.next = ptr,
.page = page.ptr,
.used_bits_index = 0,
.used_count = 0,
};
self.buckets[bucket_index] = ptr;
return ptr;
}
};
test "small allocations - free in same order" {
const gpda = try GeneralPurposeDebugAllocator.create();
defer gpda.destroy();
const allocator = &gpda.allocator;
var list = std.ArrayList(*u64).init(std.debug.global_allocator);
var i: usize = 0;
while (i < 513) : (i += 1) {
const ptr = try allocator.create(u64);
try list.append(ptr);
}
for (list.toSlice()) |ptr| {
allocator.destroy(ptr);
}
}
test "small allocations - free in reverse order" {
const gpda = try GeneralPurposeDebugAllocator.create();
defer gpda.destroy();
const allocator = &gpda.allocator;
var list = std.ArrayList(*u64).init(std.debug.global_allocator);
var i: usize = 0;
while (i < 513) : (i += 1) {
const ptr = try allocator.create(u64);
try list.append(ptr);
}
while (list.popOrNull()) |ptr| {
allocator.destroy(ptr);
}
}
test "large allocations" {
const gpda = try GeneralPurposeDebugAllocator.create();
defer gpda.destroy();
const allocator = &gpda.allocator;
const ptr1 = try allocator.alloc(u64, 42768);
const ptr2 = try allocator.alloc(u64, 52768);
allocator.free(ptr1);
const ptr3 = try allocator.alloc(u64, 62768);
allocator.free(ptr3);
allocator.free(ptr2);
}
test "realloc" {
const gpda = try GeneralPurposeDebugAllocator.create();
defer gpda.destroy();
const allocator = &gpda.allocator;
var slice = try allocator.alignedAlloc(u8, @alignOf(u32), 1);
defer allocator.free(slice);
slice[0] = 0x12;
// This reallocation should keep its pointer address.
const old_slice = slice;
slice = try allocator.realloc(slice, 2);
assert(old_slice.ptr == slice.ptr);
assert(slice[0] == 0x12);
slice[1] = 0x34;
// This requires upgrading to a larger size class
slice = try allocator.realloc(slice, 17);
assert(slice[0] == 0x12);
assert(slice[1] == 0x34);
} | gpda.zig |
const std = @import("../std.zig");
const builtin = @import("builtin");
const Futex = @This();
const os = std.os;
const assert = std.debug.assert;
const testing = std.testing;
const Atomic = std.atomic.Atomic;
/// Checks if `ptr` still contains the value `expect` and, if so, blocks the caller until either:
/// - The value at `ptr` is no longer equal to `expect`.
/// - The caller is unblocked by a matching `wake()`.
/// - The caller is unblocked spuriously ("at random").
///
/// The checking of `ptr` and `expect`, along with blocking the caller, is done atomically
/// and totally ordered (sequentially consistent) with respect to other wait()/wake() calls on the same `ptr`.
pub fn wait(ptr: *const Atomic(u32), expect: u32) void {
@setCold(true);
Impl.wait(ptr, expect, null) catch |err| switch (err) {
error.Timeout => unreachable, // null timeout meant to wait forever
};
}
/// Checks if `ptr` still contains the value `expect` and, if so, blocks the caller until either:
/// - The value at `ptr` is no longer equal to `expect`.
/// - The caller is unblocked by a matching `wake()`.
/// - The caller is unblocked spuriously ("at random").
/// - The caller blocks for longer than the given timeout. In which case, `error.Timeout` is returned.
///
/// The checking of `ptr` and `expect`, along with blocking the caller, is done atomically
/// and totally ordered (sequentially consistent) with respect to other wait()/wake() calls on the same `ptr`.
pub fn timedWait(ptr: *const Atomic(u32), expect: u32, timeout_ns: u64) error{Timeout}!void {
@setCold(true);
// Avoid calling into the OS for no-op timeouts.
if (timeout_ns == 0) {
if (ptr.load(.SeqCst) != expect) return;
return error.Timeout;
}
return Impl.wait(ptr, expect, timeout_ns);
}
/// Unblocks at most `max_waiters` callers blocked in a `wait()` call on `ptr`.
pub fn wake(ptr: *const Atomic(u32), max_waiters: u32) void {
@setCold(true);
// Avoid calling into the OS if there's nothing to wake up.
if (max_waiters == 0) {
return;
}
Impl.wake(ptr, max_waiters);
}
const Impl = if (builtin.single_threaded)
SingleThreadedImpl
else if (builtin.os.tag == .windows)
WindowsImpl
else if (builtin.os.tag.isDarwin())
DarwinImpl
else if (builtin.os.tag == .linux)
LinuxImpl
else if (builtin.os.tag == .freebsd)
FreebsdImpl
else if (builtin.os.tag == .openbsd)
OpenbsdImpl
else if (builtin.os.tag == .dragonfly)
DragonflyImpl
else if (std.Thread.use_pthreads)
PosixImpl
else
UnsupportedImpl;
/// We can't do @compileError() in the `Impl` switch statement above as its eagerly evaluated.
/// So instead, we @compileError() on the methods themselves for platforms which don't support futex.
const UnsupportedImpl = struct {
fn wait(ptr: *const Atomic(u32), expect: u32, timeout: ?u64) error{Timeout}!void {
return unsupported(.{ ptr, expect, timeout });
}
fn wake(ptr: *const Atomic(u32), max_waiters: u32) void {
return unsupported(.{ ptr, max_waiters });
}
fn unsupported(unused: anytype) noreturn {
_ = unused;
@compileError("Unsupported operating system " ++ @tagName(builtin.target.os.tag));
}
};
const SingleThreadedImpl = struct {
fn wait(ptr: *const Atomic(u32), expect: u32, timeout: ?u64) error{Timeout}!void {
if (ptr.loadUnchecked() != expect) {
return;
}
// There are no threads to wake us up.
// So if we wait without a timeout we would never wake up.
const delay = timeout orelse {
unreachable; // deadlock detected
};
std.time.sleep(delay);
return error.Timeout;
}
fn wake(ptr: *const Atomic(u32), max_waiters: u32) void {
// There are no other threads to possibly wake up
_ = ptr;
_ = max_waiters;
}
};
// We use WaitOnAddress through NtDll instead of API-MS-Win-Core-Synch-l1-2-0.dll
// as it's generally already a linked target and is autoloaded into all processes anyway.
const WindowsImpl = struct {
fn wait(ptr: *const Atomic(u32), expect: u32, timeout: ?u64) error{Timeout}!void {
var timeout_value: os.windows.LARGE_INTEGER = undefined;
var timeout_ptr: ?*const os.windows.LARGE_INTEGER = null;
// NTDLL functions work with time in units of 100 nanoseconds.
// Positive values are absolute deadlines while negative values are relative durations.
if (timeout) |delay| {
timeout_value = @intCast(os.windows.LARGE_INTEGER, delay / 100);
timeout_value = -timeout_value;
timeout_ptr = &timeout_value;
}
const rc = os.windows.ntdll.RtlWaitOnAddress(
@ptrCast(?*const anyopaque, ptr),
@ptrCast(?*const anyopaque, &expect),
@sizeOf(@TypeOf(expect)),
timeout_ptr,
);
switch (rc) {
.SUCCESS => {},
.TIMEOUT => {
assert(timeout != null);
return error.Timeout;
},
else => unreachable,
}
}
fn wake(ptr: *const Atomic(u32), max_waiters: u32) void {
const address = @ptrCast(?*const anyopaque, ptr);
assert(max_waiters != 0);
switch (max_waiters) {
1 => os.windows.ntdll.RtlWakeAddressSingle(address),
else => os.windows.ntdll.RtlWakeAddressAll(address),
}
}
};
const DarwinImpl = struct {
fn wait(ptr: *const Atomic(u32), expect: u32, timeout: ?u64) error{Timeout}!void {
// Darwin XNU 7195.192.168.127.12 introduced __ulock_wait2 and migrated code paths (notably pthread_cond_t) towards it:
// https://github.com/apple/darwin-xnu/commit/d4061fb0260b3ed486147341b72468f836ed6c8f#diff-08f993cc40af475663274687b7c326cc6c3031e0db3ac8de7b24624610616be6
//
// This XNU version appears to correspond to 11.0.1:
// https://kernelshaman.blogspot.com/2021/01/building-xnu-for-macos-big-sur-1101.html
//
// ulock_wait() uses 32-bit micro-second timeouts where 0 = INFINITE or no-timeout
// ulock_wait2() uses 64-bit nano-second timeouts (with the same convention)
const supports_ulock_wait2 = builtin.target.os.version_range.semver.min.major >= 11;
var timeout_ns: u64 = 0;
if (timeout) |delay| {
assert(delay != 0); // handled by timedWait()
timeout_ns = delay;
}
// If we're using `__ulock_wait` and `timeout` is too big to fit inside a `u32` count of
// micro-seconds (around 70min), we'll request a shorter timeout. This is fine (users
// should handle spurious wakeups), but we need to remember that we did so, so that
// we don't return `Timeout` incorrectly. If that happens, we set this variable to
// true so that we we know to ignore the ETIMEDOUT result.
var timeout_overflowed = false;
const addr = @ptrCast(*const anyopaque, ptr);
const flags = os.darwin.UL_COMPARE_AND_WAIT | os.darwin.ULF_NO_ERRNO;
const status = blk: {
if (supports_ulock_wait2) {
break :blk os.darwin.__ulock_wait2(flags, addr, expect, timeout_ns, 0);
}
const timeout_us = std.math.cast(u32, timeout_ns / std.time.ns_per_us) orelse overflow: {
timeout_overflowed = true;
break :overflow std.math.maxInt(u32);
};
break :blk os.darwin.__ulock_wait(flags, addr, expect, timeout_us);
};
if (status >= 0) return;
switch (@intToEnum(std.os.E, -status)) {
// Wait was interrupted by the OS or other spurious signalling.
.INTR => {},
// Address of the futex was paged out. This is unlikely, but possible in theory, and
// pthread/libdispatch on darwin bother to handle it. In this case we'll return
// without waiting, but the caller should retry anyway.
.FAULT => {},
// Only report Timeout if we didn't have to cap the timeout
.TIMEDOUT => {
assert(timeout != null);
if (!timeout_overflowed) return error.Timeout;
},
else => unreachable,
}
}
fn wake(ptr: *const Atomic(u32), max_waiters: u32) void {
var flags: u32 = os.darwin.UL_COMPARE_AND_WAIT | os.darwin.ULF_NO_ERRNO;
if (max_waiters > 1) {
flags |= os.darwin.ULF_WAKE_ALL;
}
while (true) {
const addr = @ptrCast(*const anyopaque, ptr);
const status = os.darwin.__ulock_wake(flags, addr, 0);
if (status >= 0) return;
switch (@intToEnum(std.os.E, -status)) {
.INTR => continue, // spurious wake()
.FAULT => unreachable, // __ulock_wake doesn't generate EFAULT according to darwin pthread_cond_t
.NOENT => return, // nothing was woken up
.ALREADY => unreachable, // only for ULF_WAKE_THREAD
else => unreachable,
}
}
}
};
// https://man7.org/linux/man-pages/man2/futex.2.html
const LinuxImpl = struct {
fn wait(ptr: *const Atomic(u32), expect: u32, timeout: ?u64) error{Timeout}!void {
var ts: os.timespec = undefined;
if (timeout) |timeout_ns| {
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);
}
const rc = os.linux.futex_wait(
@ptrCast(*const i32, &ptr.value),
os.linux.FUTEX.PRIVATE_FLAG | os.linux.FUTEX.WAIT,
@bitCast(i32, expect),
if (timeout != null) &ts else null,
);
switch (os.linux.getErrno(rc)) {
.SUCCESS => {}, // notified by `wake()`
.INTR => {}, // spurious wakeup
.AGAIN => {}, // ptr.* != expect
.TIMEDOUT => {
assert(timeout != null);
return error.Timeout;
},
.INVAL => {}, // possibly timeout overflow
.FAULT => unreachable, // ptr was invalid
else => unreachable,
}
}
fn wake(ptr: *const Atomic(u32), max_waiters: u32) void {
const rc = os.linux.futex_wake(
@ptrCast(*const i32, &ptr.value),
os.linux.FUTEX.PRIVATE_FLAG | os.linux.FUTEX.WAKE,
std.math.cast(i32, max_waiters) orelse std.math.maxInt(i32),
);
switch (os.linux.getErrno(rc)) {
.SUCCESS => {}, // successful wake up
.INVAL => {}, // invalid futex_wait() on ptr done elsewhere
.FAULT => {}, // pointer became invalid while doing the wake
else => unreachable,
}
}
};
// https://www.freebsd.org/cgi/man.cgi?query=_umtx_op&sektion=2&n=1
const FreebsdImpl = struct {
fn wait(ptr: *const Atomic(u32), expect: u32, timeout: ?u64) error{Timeout}!void {
var tm_size: usize = 0;
var tm: os.freebsd._umtx_time = undefined;
var tm_ptr: ?*const os.freebsd._umtx_time = null;
if (timeout) |timeout_ns| {
tm_ptr = &tm;
tm_size = @sizeOf(@TypeOf(tm));
tm._flags = 0; // use relative time not UMTX_ABSTIME
tm._clockid = os.CLOCK.MONOTONIC;
tm._timeout.tv_sec = @intCast(@TypeOf(tm._timeout.tv_sec), timeout_ns / std.time.ns_per_s);
tm._timeout.tv_nsec = @intCast(@TypeOf(tm._timeout.tv_nsec), timeout_ns % std.time.ns_per_s);
}
const rc = os.freebsd._umtx_op(
@ptrToInt(&ptr.value),
@enumToInt(os.freebsd.UMTX_OP.WAIT_UINT_PRIVATE),
@as(c_ulong, expect),
tm_size,
@ptrToInt(tm_ptr),
);
switch (os.errno(rc)) {
.SUCCESS => {},
.FAULT => unreachable, // one of the args points to invalid memory
.INVAL => unreachable, // arguments should be correct
.TIMEDOUT => {
assert(timeout != null);
return error.Timeout;
},
.INTR => {}, // spurious wake
else => unreachable,
}
}
fn wake(ptr: *const Atomic(u32), max_waiters: u32) void {
const rc = os.freebsd._umtx_op(
@ptrToInt(&ptr.value),
@enumToInt(os.freebsd.UMTX_OP.WAKE_PRIVATE),
@as(c_ulong, max_waiters),
0, // there is no timeout struct
0, // there is no timeout struct pointer
);
switch (os.errno(rc)) {
.SUCCESS => {},
.FAULT => {}, // it's ok if the ptr doesn't point to valid memory
.INVAL => unreachable, // arguments should be correct
else => unreachable,
}
}
};
// https://man.openbsd.org/futex.2
const OpenbsdImpl = struct {
fn wait(ptr: *const Atomic(u32), expect: u32, timeout: ?u64) error{Timeout}!void {
var ts: os.timespec = undefined;
if (timeout) |timeout_ns| {
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);
}
const rc = os.openbsd.futex(
@ptrCast(*const volatile u32, &ptr.value),
os.openbsd.FUTEX_WAIT | os.openbsd.FUTEX_PRIVATE_FLAG,
@bitCast(c_int, expect),
if (timeout != null) &ts else null,
null, // FUTEX_WAIT takes no requeue address
);
switch (os.errno(rc)) {
.SUCCESS => {}, // woken up by wake
.NOSYS => unreachable, // the futex operation shouldn't be invalid
.FAULT => unreachable, // ptr was invalid
.AGAIN => {}, // ptr != expect
.INVAL => unreachable, // invalid timeout
.TIMEDOUT => {
assert(timeout != null);
return error.Timeout;
},
.INTR => {}, // spurious wake from signal
.CANCELED => {}, // spurious wake from signal with SA_RESTART
else => unreachable,
}
}
fn wake(ptr: *const Atomic(u32), max_waiters: u32) void {
const rc = os.openbsd.futex(
@ptrCast(*const volatile u32, &ptr.value),
os.openbsd.FUTEX_WAKE | os.openbsd.FUTEX_PRIVATE_FLAG,
std.math.cast(c_int, max_waiters) orelse std.math.maxInt(c_int),
null, // FUTEX_WAKE takes no timeout ptr
null, // FUTEX_WAKE takes no requeue address
);
// returns number of threads woken up.
assert(rc >= 0);
}
};
// https://man.dragonflybsd.org/?command=umtx§ion=2
const DragonflyImpl = struct {
fn wait(ptr: *const Atomic(u32), expect: u32, timeout: ?u64) error{Timeout}!void {
// Dragonfly uses a scheme where 0 timeout means wait until signaled or spurious wake.
// It's reporting of timeout's is also unrealiable so we use an external timing source (Timer) instead.
var timeout_us: c_int = 0;
var timeout_overflowed = false;
var sleep_timer: std.time.Timer = undefined;
if (timeout) |delay| {
assert(delay != 0); // handled by timedWait().
timeout_us = std.math.cast(c_int, delay / std.time.ns_per_us) orelse blk: {
timeout_overflowed = true;
break :blk std.math.maxInt(c_int);
};
// Only need to record the start time if we can provide somewhat accurate error.Timeout's
if (!timeout_overflowed) {
sleep_timer = std.time.Timer.start() catch unreachable;
}
}
const value = @bitCast(c_int, expect);
const addr = @ptrCast(*const volatile c_int, &ptr.value);
const rc = os.dragonfly.umtx_sleep(addr, value, timeout_us);
switch (os.errno(rc)) {
.SUCCESS => {},
.BUSY => {}, // ptr != expect
.AGAIN => { // maybe timed out, or paged out, or hit 2s kernel refresh
if (timeout) |timeout_ns| {
// Report error.Timeout only if we know the timeout duration has passed.
// If not, there's not much choice other than treating it as a spurious wake.
if (!timeout_overflowed and sleep_timer.read() >= timeout_ns) {
return error.Timeout;
}
}
},
.INTR => {}, // spurious wake
.INVAL => unreachable, // invalid timeout
else => unreachable,
}
}
fn wake(ptr: *const Atomic(u32), max_waiters: u32) void {
// A count of zero means wake all waiters.
assert(max_waiters != 0);
const to_wake = std.math.cast(c_int, max_waiters) orelse 0;
// https://man.dragonflybsd.org/?command=umtx§ion=2
// > umtx_wakeup() will generally return 0 unless the address is bad.
// We are fine with the address being bad (e.g. for Semaphore.post() where Semaphore.wait() frees the Semaphore)
const addr = @ptrCast(*const volatile c_int, &ptr.value);
_ = os.dragonfly.umtx_wakeup(addr, to_wake);
}
};
/// Modified version of linux's futex and Go's sema to implement userspace wait queues with pthread:
/// https://code.woboq.org/linux/linux/kernel/futex.c.html
/// https://go.dev/src/runtime/sema.go
const PosixImpl = struct {
const Event = struct {
cond: std.c.pthread_cond_t,
mutex: std.c.pthread_mutex_t,
state: enum { empty, waiting, notified },
fn init(self: *Event) void {
// Use static init instead of pthread_cond/mutex_init() since this is generally faster.
self.cond = .{};
self.mutex = .{};
self.state = .empty;
}
fn deinit(self: *Event) void {
// Some platforms reportedly give EINVAL for statically initialized pthread types.
const rc = std.c.pthread_cond_destroy(&self.cond);
assert(rc == .SUCCESS or rc == .INVAL);
const rm = std.c.pthread_mutex_destroy(&self.mutex);
assert(rm == .SUCCESS or rm == .INVAL);
self.* = undefined;
}
fn wait(self: *Event, timeout: ?u64) error{Timeout}!void {
assert(std.c.pthread_mutex_lock(&self.mutex) == .SUCCESS);
defer assert(std.c.pthread_mutex_unlock(&self.mutex) == .SUCCESS);
// Early return if the event was already set.
if (self.state == .notified) {
return;
}
// Compute the absolute timeout if one was specified.
// POSIX requires that REALTIME is used by default for the pthread timedwait functions.
// This can be changed with pthread_condattr_setclock, but it's an extension and may not be available everywhere.
var ts: os.timespec = undefined;
if (timeout) |timeout_ns| {
os.clock_gettime(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;
}
}
// Start waiting on the event - there can be only one thread waiting.
assert(self.state == .empty);
self.state = .waiting;
while (true) {
// Block using either pthread_cond_wait or pthread_cond_timewait if there's an absolute timeout.
const rc = blk: {
if (timeout == null) break :blk std.c.pthread_cond_wait(&self.cond, &self.mutex);
break :blk std.c.pthread_cond_timedwait(&self.cond, &self.mutex, &ts);
};
// After waking up, check if the event was set.
if (self.state == .notified) {
return;
}
assert(self.state == .waiting);
switch (rc) {
.SUCCESS => {},
.TIMEDOUT => {
// If timed out, reset the event to avoid the set() thread doing an unnecessary signal().
self.state = .empty;
return error.Timeout;
},
.INVAL => unreachable, // cond, mutex, and potentially ts should all be valid
.PERM => unreachable, // mutex is locked when cond_*wait() functions are called
else => unreachable,
}
}
}
fn set(self: *Event) void {
assert(std.c.pthread_mutex_lock(&self.mutex) == .SUCCESS);
defer assert(std.c.pthread_mutex_unlock(&self.mutex) == .SUCCESS);
// Make sure that multiple calls to set() were not done on the same Event.
const old_state = self.state;
assert(old_state != .notified);
// Mark the event as set and wake up the waiting thread if there was one.
// This must be done while the mutex as the wait() thread could deallocate
// the condition variable once it observes the new state, potentially causing a UAF if done unlocked.
self.state = .notified;
if (old_state == .waiting) {
assert(std.c.pthread_cond_signal(&self.cond) == .SUCCESS);
}
}
};
const Treap = std.Treap(usize, std.math.order);
const Waiter = struct {
node: Treap.Node,
prev: ?*Waiter,
next: ?*Waiter,
tail: ?*Waiter,
is_queued: bool,
event: Event,
};
// An unordered set of Waiters
const WaitList = struct {
top: ?*Waiter = null,
len: usize = 0,
fn push(self: *WaitList, waiter: *Waiter) void {
waiter.next = self.top;
self.top = waiter;
self.len += 1;
}
fn pop(self: *WaitList) ?*Waiter {
const waiter = self.top orelse return null;
self.top = waiter.next;
self.len -= 1;
return waiter;
}
};
const WaitQueue = struct {
fn insert(treap: *Treap, address: usize, waiter: *Waiter) void {
// prepare the waiter to be inserted.
waiter.next = null;
waiter.is_queued = true;
// Find the wait queue entry associated with the address.
// If there isn't a wait queue on the address, this waiter creates the queue.
var entry = treap.getEntryFor(address);
const entry_node = entry.node orelse {
waiter.prev = null;
waiter.tail = waiter;
entry.set(&waiter.node);
return;
};
// There's a wait queue on the address; get the queue head and tail.
const head = @fieldParentPtr(Waiter, "node", entry_node);
const tail = head.tail orelse unreachable;
// Push the waiter to the tail by replacing it and linking to the previous tail.
head.tail = waiter;
tail.next = waiter;
waiter.prev = tail;
}
fn remove(treap: *Treap, address: usize, max_waiters: usize) WaitList {
// Find the wait queue associated with this address and get the head/tail if any.
var entry = treap.getEntryFor(address);
var queue_head = if (entry.node) |node| @fieldParentPtr(Waiter, "node", node) else null;
const queue_tail = if (queue_head) |head| head.tail else null;
// Once we're done updating the head, fix it's tail pointer and update the treap's queue head as well.
defer entry.set(blk: {
const new_head = queue_head orelse break :blk null;
new_head.tail = queue_tail;
break :blk &new_head.node;
});
var removed = WaitList{};
while (removed.len < max_waiters) {
// dequeue and collect waiters from their wait queue.
const waiter = queue_head orelse break;
queue_head = waiter.next;
removed.push(waiter);
// When dequeueing, we must mark is_queued as false.
// This ensures that a waiter which calls tryRemove() returns false.
assert(waiter.is_queued);
waiter.is_queued = false;
}
return removed;
}
fn tryRemove(treap: *Treap, address: usize, waiter: *Waiter) bool {
if (!waiter.is_queued) {
return false;
}
queue_remove: {
// Find the wait queue associated with the address.
var entry = blk: {
// A waiter without a previous link means it's the queue head that's in the treap so we can avoid lookup.
if (waiter.prev == null) {
assert(waiter.node.key == address);
break :blk treap.getEntryForExisting(&waiter.node);
}
break :blk treap.getEntryFor(address);
};
// The queue head and tail must exist if we're removing a queued waiter.
const head = @fieldParentPtr(Waiter, "node", entry.node orelse unreachable);
const tail = head.tail orelse unreachable;
// A waiter with a previous link is never the head of the queue.
if (waiter.prev) |prev| {
assert(waiter != head);
prev.next = waiter.next;
// A waiter with both a previous and next link is in the middle.
// We only need to update the surrounding waiter's links to remove it.
if (waiter.next) |next| {
assert(waiter != tail);
next.prev = waiter.prev;
break :queue_remove;
}
// A waiter with a previous but no next link means it's the tail of the queue.
// In that case, we need to update the head's tail reference.
assert(waiter == tail);
head.tail = waiter.prev;
break :queue_remove;
}
// A waiter with no previous link means it's the queue head of queue.
// We must replace (or remove) the head waiter reference in the treap.
assert(waiter == head);
entry.set(blk: {
const new_head = waiter.next orelse break :blk null;
new_head.tail = head.tail;
break :blk &new_head.node;
});
}
// Mark the waiter as successfully removed.
waiter.is_queued = false;
return true;
}
};
const Bucket = struct {
mutex: std.c.pthread_mutex_t align(std.atomic.cache_line) = .{},
pending: Atomic(usize) = Atomic(usize).init(0),
treap: Treap = .{},
// Global array of buckets that addresses map to.
// Bucket array size is pretty much arbitrary here, but it must be a power of two for fibonacci hashing.
var buckets = [_]Bucket{.{}} ** @bitSizeOf(usize);
// https://github.com/Amanieu/parking_lot/blob/1cf12744d097233316afa6c8b7d37389e4211756/core/src/parking_lot.rs#L343-L353
fn from(address: usize) *Bucket {
// The upper `@bitSizeOf(usize)` bits of the fibonacci golden ratio.
// Hashing this via (h * k) >> (64 - b) where k=golden-ration and b=bitsize-of-array
// evenly lays out h=hash values over the bit range even when the hash has poor entropy (identity-hash for pointers).
const max_multiplier_bits = @bitSizeOf(usize);
const fibonacci_multiplier = 0x9E3779B97F4A7C15 >> (64 - max_multiplier_bits);
const max_bucket_bits = @ctz(usize, buckets.len);
comptime assert(std.math.isPowerOfTwo(buckets.len));
const index = (address *% fibonacci_multiplier) >> (max_multiplier_bits - max_bucket_bits);
return &buckets[index];
}
};
const Address = struct {
fn from(ptr: *const Atomic(u32)) usize {
// Get the alignment of the pointer.
const alignment = @alignOf(Atomic(u32));
comptime assert(std.math.isPowerOfTwo(alignment));
// Make sure the pointer is aligned,
// then cut off the zero bits from the alignment to get the unique address.
const addr = @ptrToInt(ptr);
assert(addr & (alignment - 1) == 0);
return addr >> @ctz(usize, alignment);
}
};
fn wait(ptr: *const Atomic(u32), expect: u32, timeout: ?u64) error{Timeout}!void {
const address = Address.from(ptr);
const bucket = Bucket.from(address);
// Announce that there's a waiter in the bucket before checking the ptr/expect condition.
// If the announcement is reordered after the ptr check, the waiter could deadlock:
//
// - T1: checks ptr == expect which is true
// - T2: updates ptr to != expect
// - T2: does Futex.wake(), sees no pending waiters, exits
// - T1: bumps pending waiters (was reordered after the ptr == expect check)
// - T1: goes to sleep and misses both the ptr change and T2's wake up
//
// SeqCst as Acquire barrier to ensure the announcement happens before the ptr check below.
// SeqCst as shared modification order to form a happens-before edge with the fence(.SeqCst)+load() in wake().
var pending = bucket.pending.fetchAdd(1, .SeqCst);
assert(pending < std.math.maxInt(usize));
// If the wait gets cancelled, remove the pending count we previously added.
// This is done outside the mutex lock to keep the critical section short in case of contention.
var cancelled = false;
defer if (cancelled) {
pending = bucket.pending.fetchSub(1, .Monotonic);
assert(pending > 0);
};
var waiter: Waiter = undefined;
{
assert(std.c.pthread_mutex_lock(&bucket.mutex) == .SUCCESS);
defer assert(std.c.pthread_mutex_unlock(&bucket.mutex) == .SUCCESS);
cancelled = ptr.load(.Monotonic) != expect;
if (cancelled) {
return;
}
waiter.event.init();
WaitQueue.insert(&bucket.treap, address, &waiter);
}
defer {
assert(!waiter.is_queued);
waiter.event.deinit();
}
waiter.event.wait(timeout) catch {
// If we fail to cancel after a timeout, it means a wake() thread dequeued us and will wake us up.
// We must wait until the event is set as that's a signal that the wake() thread wont access the waiter memory anymore.
// If we return early without waiting, the waiter on the stack would be invalidated and the wake() thread risks a UAF.
defer if (!cancelled) waiter.event.wait(null) catch unreachable;
assert(std.c.pthread_mutex_lock(&bucket.mutex) == .SUCCESS);
defer assert(std.c.pthread_mutex_unlock(&bucket.mutex) == .SUCCESS);
cancelled = WaitQueue.tryRemove(&bucket.treap, address, &waiter);
if (cancelled) {
return error.Timeout;
}
};
}
fn wake(ptr: *const Atomic(u32), max_waiters: u32) void {
const address = Address.from(ptr);
const bucket = Bucket.from(address);
// Quick check if there's even anything to wake up.
// The change to the ptr's value must happen before we check for pending waiters.
// If not, the wake() thread could miss a sleeping waiter and have it deadlock:
//
// - T2: p = has pending waiters (reordered before the ptr update)
// - T1: bump pending waiters
// - T1: if ptr == expected: sleep()
// - T2: update ptr != expected
// - T2: p is false from earlier so doesn't wake (T1 missed ptr update and T2 missed T1 sleeping)
//
// What we really want here is a Release load, but that doesn't exist under the C11 memory model.
// We could instead do `bucket.pending.fetchAdd(0, Release) == 0` which achieves effectively the same thing,
// but the RMW operation unconditionally marks the cache-line as modified for others causing unnecessary fetching/contention.
//
// Instead we opt to do a full-fence + load instead which avoids taking ownership of the cache-line.
// fence(SeqCst) effectively converts the ptr update to SeqCst and the pending load to SeqCst: creating a Store-Load barrier.
//
// The pending count increment in wait() must also now use SeqCst for the update + this pending load
// to be in the same modification order as our load isn't using Release/Acquire to guarantee it.
bucket.pending.fence(.SeqCst);
if (bucket.pending.load(.Monotonic) == 0) {
return;
}
// Keep a list of all the waiters notified and wake then up outside the mutex critical section.
var notified = WaitList{};
defer if (notified.len > 0) {
const pending = bucket.pending.fetchSub(notified.len, .Monotonic);
assert(pending >= notified.len);
while (notified.pop()) |waiter| {
assert(!waiter.is_queued);
waiter.event.set();
}
};
assert(std.c.pthread_mutex_lock(&bucket.mutex) == .SUCCESS);
defer assert(std.c.pthread_mutex_unlock(&bucket.mutex) == .SUCCESS);
// Another pending check again to avoid the WaitQueue lookup if not necessary.
if (bucket.pending.load(.Monotonic) > 0) {
notified = WaitQueue.remove(&bucket.treap, address, max_waiters);
}
}
};
test "Futex - smoke test" {
var value = Atomic(u32).init(0);
// Try waits with invalid values.
Futex.wait(&value, 0xdeadbeef);
Futex.timedWait(&value, 0xdeadbeef, 0) catch {};
// Try timeout waits.
try testing.expectError(error.Timeout, Futex.timedWait(&value, 0, 0));
try testing.expectError(error.Timeout, Futex.timedWait(&value, 0, std.time.ns_per_ms));
// Try wakes
Futex.wake(&value, 0);
Futex.wake(&value, 1);
Futex.wake(&value, std.math.maxInt(u32));
}
test "Futex - signaling" {
// This test requires spawning threads
if (builtin.single_threaded) {
return error.SkipZigTest;
}
const num_threads = 4;
const num_iterations = 4;
const Paddle = struct {
value: Atomic(u32) = Atomic(u32).init(0),
current: u32 = 0,
fn hit(self: *@This()) void {
_ = self.value.fetchAdd(1, .Release);
Futex.wake(&self.value, 1);
}
fn run(self: *@This(), hit_to: *@This()) !void {
while (self.current < num_iterations) {
// Wait for the value to change from hit()
var new_value: u32 = undefined;
while (true) {
new_value = self.value.load(.Acquire);
if (new_value != self.current) break;
Futex.wait(&self.value, self.current);
}
// change the internal "current" value
try testing.expectEqual(new_value, self.current + 1);
self.current = new_value;
// hit the next paddle
hit_to.hit();
}
}
};
var paddles = [_]Paddle{.{}} ** num_threads;
var threads = [_]std.Thread{undefined} ** num_threads;
// Create a circle of paddles which hit each other
for (threads) |*t, i| {
const paddle = &paddles[i];
const hit_to = &paddles[(i + 1) % paddles.len];
t.* = try std.Thread.spawn(.{}, Paddle.run, .{ paddle, hit_to });
}
// Hit the first paddle and wait for them all to complete by hitting each other for num_iterations.
paddles[0].hit();
for (threads) |t| t.join();
for (paddles) |p| try testing.expectEqual(p.current, num_iterations);
}
test "Futex - broadcasting" {
// This test requires spawning threads
if (builtin.single_threaded) {
return error.SkipZigTest;
}
const num_threads = 4;
const num_iterations = 4;
const Barrier = struct {
count: Atomic(u32) = Atomic(u32).init(num_threads),
futex: Atomic(u32) = Atomic(u32).init(0),
fn wait(self: *@This()) !void {
// Decrement the counter.
// Release ensures stuff before this barrier.wait() happens before the last one.
const count = self.count.fetchSub(1, .Release);
try testing.expect(count <= num_threads);
try testing.expect(count > 0);
// First counter to reach zero wakes all other threads.
// Acquire for the last counter ensures stuff before previous barrier.wait()s happened before it.
// Release on futex update ensures stuff before all barrier.wait()'s happens before they all return.
if (count - 1 == 0) {
_ = self.count.load(.Acquire); // TODO: could be fence(Acquire) if not for TSAN
self.futex.store(1, .Release);
Futex.wake(&self.futex, num_threads - 1);
return;
}
// Other threads wait until last counter wakes them up.
// Acquire on futex synchronizes with last barrier count to ensure stuff before all barrier.wait()'s happen before us.
while (self.futex.load(.Acquire) == 0) {
Futex.wait(&self.futex, 0);
}
}
};
const Broadcast = struct {
barriers: [num_iterations]Barrier = [_]Barrier{.{}} ** num_iterations,
threads: [num_threads]std.Thread = undefined,
fn run(self: *@This()) !void {
for (self.barriers) |*barrier| {
try barrier.wait();
}
}
};
var broadcast = Broadcast{};
for (broadcast.threads) |*t| t.* = try std.Thread.spawn(.{}, Broadcast.run, .{&broadcast});
for (broadcast.threads) |t| t.join();
}
/// Deadline is used to wait efficiently for a pointer's value to change using Futex and a fixed timeout.
///
/// Futex's timedWait() api uses a relative duration which suffers from over-waiting
/// when used in a loop which is often required due to the possibility of spurious wakeups.
///
/// Deadline instead converts the relative timeout to an absolute one so that multiple calls
/// to Futex timedWait() can block for and report more accurate error.Timeouts.
pub const Deadline = struct {
timeout: ?u64,
started: std.time.Timer,
/// Create the deadline to expire after the given amount of time in nanoseconds passes.
/// Pass in `null` to have the deadline call `Futex.wait()` and never expire.
pub fn init(expires_in_ns: ?u64) Deadline {
var deadline: Deadline = undefined;
deadline.timeout = expires_in_ns;
// std.time.Timer is required to be supported for somewhat accurate reportings of error.Timeout.
if (deadline.timeout != null) {
deadline.started = std.time.Timer.start() catch unreachable;
}
return deadline;
}
/// Wait until either:
/// - the `ptr`'s value changes from `expect`.
/// - `Futex.wake()` is called on the `ptr`.
/// - A spurious wake occurs.
/// - The deadline expires; In which case `error.Timeout` is returned.
pub fn wait(self: *Deadline, ptr: *const Atomic(u32), expect: u32) error{Timeout}!void {
@setCold(true);
// Check if we actually have a timeout to wait until.
// If not just wait "forever".
const timeout_ns = self.timeout orelse {
return Futex.wait(ptr, expect);
};
// Get how much time has passed since we started waiting
// then subtract that from the init() timeout to get how much longer to wait.
// Use overflow to detect when we've been waiting longer than the init() timeout.
const elapsed_ns = self.started.read();
const until_timeout_ns = std.math.sub(u64, timeout_ns, elapsed_ns) catch 0;
return Futex.timedWait(ptr, expect, until_timeout_ns);
}
};
test "Futex - Deadline" {
var deadline = Deadline.init(100 * std.time.ns_per_ms);
var futex_word = Atomic(u32).init(0);
while (true) {
deadline.wait(&futex_word, 0) catch break;
}
} | lib/std/Thread/Futex.zig |
const libpoke = @import("../src/pokemon/index.zig");
const nds = @import("../src/nds/index.zig");
const gba = @import("../src/gba.zig");
const utils = @import("../src/utils/index.zig");
const std = @import("std");
const fun = @import("../lib/fun-with-zig/src/index.zig"); // TODO: Package stuff
const mem = std.mem;
const fmt = std.fmt;
const os = std.os;
const math = std.math;
const heap = std.heap;
const debug = std.debug;
const io = std.io;
const path = os.path;
const loop = fun.loop;
const generic = fun.generic;
const lu16 = fun.platform.lu16;
const lu32 = fun.platform.lu32;
const lu64 = fun.platform.lu64;
const lu128 = fun.platform.lu128;
const tmp_folder = "zig-cache" ++ []u8{path.sep} ++ "__fake_roms__" ++ []u8{path.sep};
pub const level = 1;
pub const party_size = 2;
pub const species = 3;
pub const item = 4;
pub const move = 5;
pub const power = 6;
pub const ptype = 7;
pub const pp = 8;
pub const hp = 10;
pub const attack = 11;
pub const defense = 12;
pub const speed = 13;
pub const sp_attack = 14;
pub const sp_defense = 15;
pub const rate = 16;
pub const has_moves = 0b01;
pub const has_item = 0b10;
const trainer_count = 800;
const move_count = 200;
const pokemon_count = 800;
const level_up_move_count = pokemon_count;
const zone_count = 100;
pub fn generateFakeRoms(allocator: *mem.Allocator) ![][]u8 {
const tmp = try allocator.alloc(u8, 2 * 1024 * 1024);
defer allocator.free(tmp);
var tmp_fix_buf_alloc = heap.FixedBufferAllocator.init(tmp[0..]);
const tmp_allocator = &tmp_fix_buf_alloc.allocator;
deleteFakeRoms(tmp_allocator);
try os.makeDir(tmp_folder);
errdefer deleteFakeRoms(tmp_allocator);
tmp_fix_buf_alloc = heap.FixedBufferAllocator.init(tmp[0..]);
var rom_names = std.ArrayList([]u8).init(allocator);
errdefer {
for (rom_names.toSliceConst()) |name|
allocator.free(name);
rom_names.deinit();
}
for (libpoke.gen3.constants.infos) |info| {
const name = try genGen3FakeRom(tmp_allocator, info);
try rom_names.append(try mem.dupe(allocator, u8, name));
tmp_fix_buf_alloc = heap.FixedBufferAllocator.init(tmp[0..]);
}
for (libpoke.gen4.constants.infos) |info| {
const name = try genGen4FakeRom(tmp_allocator, info);
try rom_names.append(try mem.dupe(allocator, u8, name));
tmp_fix_buf_alloc = heap.FixedBufferAllocator.init(tmp[0..]);
}
for (libpoke.gen5.constants.infos) |info| {
const name = try genGen5FakeRom(tmp_allocator, info);
try rom_names.append(try mem.dupe(allocator, u8, name));
tmp_fix_buf_alloc = heap.FixedBufferAllocator.init(tmp[0..]);
}
return rom_names.toOwnedSlice();
}
pub fn deleteFakeRoms(allocator: *mem.Allocator) void {
os.deleteTree(allocator, tmp_folder) catch {};
}
fn genGen3FakeRom(allocator: *mem.Allocator, info: libpoke.gen3.constants.Info) ![]u8 {
const name = try fmt.allocPrint(allocator, "{}__{}_{}_{}__", tmp_folder, info.game_title, info.gamecode, @tagName(info.version));
errdefer allocator.free(name);
var free_space_offset = getGen3FreeSpace(info);
var file = try os.File.openWrite(name);
errdefer os.deleteFile(name) catch {};
defer file.close();
const header = gba.Header{
.rom_entry_point = undefined,
.nintendo_logo = undefined,
.game_title = info.game_title,
.gamecode = info.gamecode,
.makercode = "AA",
.fixed_value = 0x96,
.main_unit_code = undefined,
.device_type = undefined,
.reserved1 = []u8{0} ** 7,
.software_version = undefined,
.complement_check = undefined,
.reserved2 = []u8{0} ** 2,
};
try file.write(mem.toBytes(header));
for (loop.to(info.trainers.len)) |_, i| {
var party_type: u8 = 0;
if (i & has_moves != 0)
party_type |= libpoke.gen3.Trainer.has_moves;
if (i & has_item != 0)
party_type |= libpoke.gen3.Trainer.has_item;
// Output trainer
try file.seekTo(info.trainers.start + i * @sizeOf(libpoke.gen3.Trainer));
try file.write(mem.toBytes(libpoke.gen3.Trainer{
.party_type = party_type,
.class = undefined,
.encounter_music = undefined,
.trainer_picture = undefined,
.name = undefined,
.items = undefined,
.is_double = undefined,
.ai = undefined,
.party = try libpoke.gen3.Slice(u8).init(@intCast(u32, free_space_offset), party_size),
}));
// Output party
try file.seekTo(free_space_offset);
for (loop.to(party_size)) |_2, j| {
try file.write(mem.toBytes(libpoke.gen3.PartyMember{
.iv = undefined,
.level = lu16.init(level),
.species = lu16.init(species),
}));
if (party_type & libpoke.gen3.Trainer.has_item != 0)
try file.write(lu16.init(item).bytes);
if (party_type & libpoke.gen3.Trainer.has_moves != 0) {
try file.write(lu16.init(move).bytes);
try file.write(lu16.init(move).bytes);
try file.write(lu16.init(move).bytes);
try file.write(lu16.init(move).bytes);
}
if (party_type & libpoke.gen3.Trainer.has_item == 0)
try file.write([]u8{ 0x00, 0x00 });
}
free_space_offset = try file.getPos();
}
try file.seekTo(info.moves.start);
for (loop.to(info.moves.len)) |_, i| {
try file.write(mem.toBytes(libpoke.gen3.Move{
.effect = undefined,
.power = power,
.@"type" = @intToEnum(libpoke.gen3.Type, ptype),
.accuracy = undefined,
.pp = pp,
.side_effect_chance = undefined,
.target = undefined,
.priority = undefined,
.flags = undefined,
}));
}
try file.seekTo(info.machine_learnsets.start);
for (loop.to(info.machine_learnsets.len)) |_, i| {
try file.write(lu64.init(0).bytes);
}
try file.seekTo(info.base_stats.start);
for (loop.to(info.base_stats.len)) |_, i| {
try file.write(mem.toBytes(libpoke.gen3.BasePokemon{
.stats = libpoke.common.Stats{
.hp = hp,
.attack = attack,
.defense = defense,
.speed = speed,
.sp_attack = sp_attack,
.sp_defense = sp_defense,
},
.types = [2]libpoke.gen3.Type{
@intToEnum(libpoke.gen3.Type, ptype),
@intToEnum(libpoke.gen3.Type, ptype),
},
.catch_rate = undefined,
.base_exp_yield = undefined,
.ev_yield = undefined,
.items = undefined,
.gender_ratio = undefined,
.egg_cycles = undefined,
.base_friendship = undefined,
.growth_rate = undefined,
.egg_group1 = undefined,
.egg_group1_pad = undefined,
.egg_group2 = undefined,
.egg_group2_pad = undefined,
.abilities = undefined,
.safari_zone_rate = undefined,
.color = undefined,
.flip = undefined,
.padding = undefined,
}));
}
for (loop.to(info.level_up_learnset_pointers.len)) |_, i| {
try file.seekTo(info.level_up_learnset_pointers.start + i * @sizeOf(lu32));
try file.write(lu32.init(@intCast(u32, free_space_offset + 0x8000000)).bytes);
try file.seekTo(free_space_offset);
try file.write(mem.toBytes(libpoke.gen3.LevelUpMove{
.move_id = move,
.level = level,
}));
try file.write([]u8{ 0xFF, 0xFF });
free_space_offset = try file.getPos();
}
try file.seekTo(info.hms.start);
for (loop.to(info.hms.len)) |_, i| {
try file.write(lu16.init(move).bytes);
}
try file.seekTo(info.tms.start);
for (loop.to(info.tms.len)) |_, i| {
try file.write(lu16.init(move).bytes);
}
for (loop.to(info.wild_pokemon_headers.len)) |_, i| {
try file.seekTo(free_space_offset);
const lens = []usize{ 12, 5, 5, 10 };
var offsets: [lens.len]u32 = undefined;
inline for (lens) |len, j| {
const offset = try file.getPos();
for (loop.to(len)) |_2| {
try file.write(mem.toBytes(libpoke.gen3.WildPokemon{
.min_level = level,
.max_level = level,
.species = lu16.init(species),
}));
}
offsets[j] = @intCast(u32, try file.getPos());
try file.write(mem.toBytes(libpoke.gen3.WildPokemonInfo(len){
.encounter_rate = rate,
.pad = undefined,
.wild_pokemons = try libpoke.gen3.Ref([len]libpoke.gen3.WildPokemon).init(@intCast(u32, offset)),
}));
}
free_space_offset = try file.getPos();
try file.seekTo(info.wild_pokemon_headers.start + i * @sizeOf(libpoke.gen3.WildPokemonHeader));
try file.write(mem.toBytes(libpoke.gen3.WildPokemonHeader{
.map_group = undefined,
.map_num = undefined,
.pad = undefined,
.land_pokemons = try libpoke.gen3.Ref(libpoke.gen3.WildPokemonInfo(12)).init(offsets[0]),
.surf_pokemons = try libpoke.gen3.Ref(libpoke.gen3.WildPokemonInfo(5)).init(offsets[1]),
.rock_smash_pokemons = try libpoke.gen3.Ref(libpoke.gen3.WildPokemonInfo(5)).init(offsets[2]),
.fishing_pokemons = try libpoke.gen3.Ref(libpoke.gen3.WildPokemonInfo(10)).init(offsets[3]),
}));
}
const end = try file.getEndPos();
try file.seekTo(end);
const rem = end % 0x1000000;
if (rem != 0) {
var file_stream = file.outStream();
var buf_stream = io.BufferedOutStream(os.File.OutStream.Error).init(&file_stream.stream);
var stream = &buf_stream.stream;
try stream.writeByteNTimes(0, 0x1000000 - rem);
try buf_stream.flush();
}
return name;
}
fn getGen3FreeSpace(info: libpoke.gen3.constants.Info) usize {
var res = info.trainers.end();
res = math.max(res, info.moves.end());
res = math.max(res, info.machine_learnsets.end());
res = math.max(res, info.base_stats.end());
res = math.max(res, info.evolutions.end());
res = math.max(res, info.level_up_learnset_pointers.end());
res = math.max(res, info.hms.end());
res = math.max(res, info.tms.end());
res = math.max(res, info.wild_pokemon_headers.end());
return math.max(res, info.items.end());
}
fn ndsHeader(game_title: [12]u8, gamecode: [4]u8) nds.Header {
return nds.Header{
.game_title = game_title,
.gamecode = gamecode,
.makercode = "ST",
.unitcode = 0x00,
.encryption_seed_select = 0x00,
.device_capacity = 0x00,
.reserved1 = []u8{0} ** 7,
.reserved2 = 0x00,
.nds_region = 0x00,
.rom_version = 0x00,
.autostart = 0x00,
.arm9_rom_offset = lu32.init(0x4000),
.arm9_entry_address = lu32.init(0x2000000),
.arm9_ram_address = lu32.init(0x2000000),
.arm9_size = lu32.init(0x3BFE00),
.arm7_rom_offset = lu32.init(0x8000),
.arm7_entry_address = lu32.init(0x2000000),
.arm7_ram_address = lu32.init(0x2000000),
.arm7_size = lu32.init(0x3BFE00),
.fnt_offset = lu32.init(0x00),
.fnt_size = lu32.init(0x00),
.fat_offset = lu32.init(0x00),
.fat_size = lu32.init(0x00),
.arm9_overlay_offset = lu32.init(0x00),
.arm9_overlay_size = lu32.init(0x00),
.arm7_overlay_offset = lu32.init(0x00),
.arm7_overlay_size = lu32.init(0x00),
.port_40001A4h_setting_for_normal_commands = []u8{0} ** 4,
.port_40001A4h_setting_for_key1_commands = []u8{0} ** 4,
.banner_offset = lu32.init(0x00),
.secure_area_checksum = lu16.init(0x00),
.secure_area_delay = lu16.init(0x051E),
.arm9_auto_load_list_ram_address = lu32.init(0x00),
.arm7_auto_load_list_ram_address = lu32.init(0x00),
.secure_area_disable = lu64.init(0x00),
.total_used_rom_size = lu32.init(0x00),
.rom_header_size = lu32.init(0x4000),
.reserved3 = []u8{0x00} ** 0x38,
.nintendo_logo = []u8{0x00} ** 0x9C,
.nintendo_logo_checksum = lu16.init(0x00),
.header_checksum = lu16.init(0x00),
.debug_rom_offset = lu32.init(0x00),
.debug_size = lu32.init(0x00),
.debug_ram_address = lu32.init(0x00),
.reserved4 = []u8{0x00} ** 4,
.reserved5 = []u8{0x00} ** 0x10,
.wram_slots = []u8{0x00} ** 20,
.arm9_wram_areas = []u8{0x00} ** 12,
.arm7_wram_areas = []u8{0x00} ** 12,
.wram_slot_master = []u8{0x00} ** 3,
.unknown = 0,
.region_flags = []u8{0x00} ** 4,
.access_control = []u8{0x00} ** 4,
.arm7_scfg_ext_setting = []u8{0x00} ** 4,
.reserved6 = []u8{0x00} ** 3,
.unknown_flags = 0,
.arm9i_rom_offset = lu32.init(0x00),
.reserved7 = []u8{0x00} ** 4,
.arm9i_ram_load_address = lu32.init(0x00),
.arm9i_size = lu32.init(0x00),
.arm7i_rom_offset = lu32.init(0x00),
.device_list_arm7_ram_addr = lu32.init(0x00),
.arm7i_ram_load_address = lu32.init(0x00),
.arm7i_size = lu32.init(0x00),
.digest_ntr_region_offset = lu32.init(0x4000),
.digest_ntr_region_length = lu32.init(0x00),
.digest_twl_region_offset = lu32.init(0x00),
.digest_twl_region_length = lu32.init(0x00),
.digest_sector_hashtable_offset = lu32.init(0x00),
.digest_sector_hashtable_length = lu32.init(0x00),
.digest_block_hashtable_offset = lu32.init(0x00),
.digest_block_hashtable_length = lu32.init(0x00),
.digest_sector_size = lu32.init(0x00),
.digest_block_sectorcount = lu32.init(0x00),
.banner_size = lu32.init(0x00),
.reserved8 = []u8{0x00} ** 4,
.total_used_rom_size_including_dsi_area = lu32.init(0x00),
.reserved9 = []u8{0x00} ** 4,
.reserved10 = []u8{0x00} ** 4,
.reserved11 = []u8{0x00} ** 4,
.modcrypt_area_1_offset = lu32.init(0x00),
.modcrypt_area_1_size = lu32.init(0x00),
.modcrypt_area_2_offset = lu32.init(0x00),
.modcrypt_area_2_size = lu32.init(0x00),
.title_id_emagcode = []u8{0x00} ** 4,
.title_id_filetype = 0,
.title_id_rest = []u8{ 0x00, 0x03, 0x00 },
.public_sav_filesize = lu32.init(0x00),
.private_sav_filesize = lu32.init(0x00),
.reserved12 = []u8{0x00} ** 176,
.cero_japan = 0,
.esrb_us_canada = 0,
.reserved13 = 0,
.usk_germany = 0,
.pegi_pan_europe = 0,
.resereved14 = 0,
.pegi_portugal = 0,
.pegi_and_bbfc_uk = 0,
.agcb_australia = 0,
.grb_south_korea = 0,
.reserved15 = []u8{0x00} ** 6,
.arm9_hash_with_secure_area = []u8{0x00} ** 20,
.arm7_hash = []u8{0x00} ** 20,
.digest_master_hash = []u8{0x00} ** 20,
.icon_title_hash = []u8{0x00} ** 20,
.arm9i_hash = []u8{0x00} ** 20,
.arm7i_hash = []u8{0x00} ** 20,
.reserved16 = []u8{0x00} ** 40,
.arm9_hash_without_secure_area = []u8{0x00} ** 20,
.reserved17 = []u8{0x00} ** 2636,
.reserved18 = []u8{0x00} ** 0x180,
.signature_across_header_entries = []u8{0x00} ** 0x80,
};
}
const ndsBanner = nds.Banner{
.version = nds.Banner.Version.Original,
.version_padding = 0,
.has_animated_dsi_icon = false,
.has_animated_dsi_icon_padding = 0,
.crc16_across_0020h_083Fh = lu16.init(0x00),
.crc16_across_0020h_093Fh = lu16.init(0x00),
.crc16_across_0020h_0A3Fh = lu16.init(0x00),
.crc16_across_1240h_23BFh = lu16.init(0x00),
.reserved1 = []u8{0x00} ** 0x16,
.icon_bitmap = []u8{0x00} ** 0x200,
.icon_palette = []u8{0x00} ** 0x20,
.title_japanese = []u8{0x00} ** 0x100,
.title_english = []u8{0x00} ** 0x100,
.title_french = []u8{0x00} ** 0x100,
.title_german = []u8{0x00} ** 0x100,
.title_italian = []u8{0x00} ** 0x100,
.title_spanish = []u8{0x00} ** 0x100,
};
fn repeat(allocator: *mem.Allocator, comptime T: type, m: []const T, n: usize) ![]T {
const to_alloc = math.mul(usize, m.len, n) catch return mem.Allocator.Error.OutOfMemory;
const res = try allocator.alloc(T, to_alloc);
for (loop.to(n)) |_, i| {
const off = i * m.len;
mem.copy(T, res[off..], m);
}
return res;
}
test "repeat" {
var buf: [10 * 1024]u8 = undefined;
var fix_buf_alloc = heap.FixedBufferAllocator.init(buf[0..]);
const allocator = &fix_buf_alloc.allocator;
debug.assert(mem.eql(u8, try repeat(allocator, u8, "ab", 0), ""));
debug.assert(mem.eql(u8, try repeat(allocator, u8, "ab", 1), "ab"));
debug.assert(mem.eql(u8, try repeat(allocator, u8, "ab", 2), "abab"));
debug.assert(mem.eql(u8, try repeat(allocator, u8, "ab", 4), "abababab"));
}
fn genGen4FakeRom(allocator: *mem.Allocator, info: libpoke.gen4.constants.Info) ![]u8 {
const machine_len = libpoke.gen4.constants.tm_count + libpoke.gen4.constants.hm_count;
const machines = []lu16{comptime lu16.init(move)} ** machine_len;
const arm9 = try fmt.allocPrint(allocator, "{}{}", info.hm_tm_prefix, @sliceToBytes(machines[0..]));
defer allocator.free(arm9);
const rom = nds.Rom{
.allocator = allocator,
.header = ndsHeader(info.game_title, info.gamecode),
.banner = ndsBanner,
.arm9 = arm9,
.arm7 = []u8{},
.nitro_footer = []lu32{comptime lu32.init(0)} ** 3,
.arm9_overlay_table = []nds.Overlay{},
.arm9_overlay_files = [][]u8{},
.arm7_overlay_table = []nds.Overlay{},
.arm7_overlay_files = [][]u8{},
.root = try nds.fs.Nitro.create(allocator),
};
const root = rom.root;
{
// TODO: This can leak on err
const trainer_narc = try nds.fs.Narc.create(allocator);
const party_narc = try nds.fs.Narc.create(allocator);
try trainer_narc.ensureCapacity(trainer_count);
try party_narc.ensureCapacity(trainer_count);
_ = try root.createPathAndFile(info.trainers, nds.fs.Nitro.File{ .Narc = trainer_narc });
_ = try root.createPathAndFile(info.parties, nds.fs.Nitro.File{ .Narc = party_narc });
for (loop.to(trainer_count)) |_, i| {
var name_buf: [10]u8 = undefined;
const name = try fmt.bufPrint(name_buf[0..], "{}", i);
var party_type: u8 = 0;
if (i & has_moves != 0)
party_type |= libpoke.gen4.Trainer.has_moves;
if (i & has_item != 0)
party_type |= libpoke.gen4.Trainer.has_item;
{
const trainer = try allocator.create(libpoke.gen4.Trainer{
.party_type = party_type,
.class = undefined,
.battle_type = undefined,
.party_size = party_size,
.items = []lu16{comptime lu16.init(item)} ** 4,
.ai = undefined,
.battle_type2 = undefined,
});
errdefer allocator.destroy(trainer);
_ = try trainer_narc.createFile(name, nds.fs.Narc.File{
.allocator = allocator,
.data = mem.asBytes(trainer)[0..],
});
}
var tmp_buf: [100]u8 = undefined;
const party_member = libpoke.gen4.PartyMember{
.iv = undefined,
.gender = undefined,
.ability = undefined,
.level = lu16.init(level),
.species = species,
.form = undefined,
};
const held_item_bytes = lu16.init(item).bytes;
const moves_bytes = mem.toBytes([]lu16{comptime lu16.init(move)} ** 4);
const padding = switch (info.version) {
libpoke.Version.HeartGold, libpoke.Version.SoulSilver, libpoke.Version.Platinum => usize(2),
else => usize(0),
};
const full_party_member_bytes = try fmt.bufPrint(
tmp_buf[0..],
"{}{}{}{}",
mem.toBytes(party_member)[0..],
held_item_bytes[0 .. held_item_bytes.len * @boolToInt(i & has_item != 0)],
moves_bytes[0 .. moves_bytes.len * @boolToInt(i & has_moves != 0)],
([]u8{0x00} ** 2)[0..padding],
);
errdefer allocator.free(full_party_member_bytes);
_ = try party_narc.createFile(name, nds.fs.Narc.File{
.allocator = allocator,
.data = try repeat(allocator, u8, full_party_member_bytes, party_size),
});
}
}
{
// TODO: This can leak on err
const narc = try nds.fs.Narc.create(allocator);
try narc.ensureCapacity(move_count);
_ = try root.createPathAndFile(info.moves, nds.fs.Nitro.File{ .Narc = narc });
for (loop.to(move_count)) |_, i| {
var name_buf: [10]u8 = undefined;
const name = try fmt.bufPrint(name_buf[0..], "{}", i);
// TODO: This can leak on err
const gen4_move = try allocator.create(libpoke.gen4.Move{
.u8_0 = undefined,
.u8_1 = undefined,
.category = undefined,
.power = power,
.@"type" = @intToEnum(libpoke.gen4.Type, ptype),
.accuracy = undefined,
.pp = pp,
.u8_7 = undefined,
.u8_8 = undefined,
.u8_9 = undefined,
.u8_10 = undefined,
.u8_11 = undefined,
.u8_12 = undefined,
.u8_13 = undefined,
.u8_14 = undefined,
.u8_15 = undefined,
});
_ = try narc.createFile(name, nds.fs.Narc.File{
.allocator = allocator,
.data = mem.asBytes(gen4_move),
});
}
}
{
// TODO: This can leak on err
const narc = try nds.fs.Narc.create(allocator);
try narc.ensureCapacity(pokemon_count);
_ = try root.createPathAndFile(info.base_stats, nds.fs.Nitro.File{ .Narc = narc });
for (loop.to(pokemon_count)) |_, i| {
var name_buf: [10]u8 = undefined;
const name = try fmt.bufPrint(name_buf[0..], "{}", i);
// TODO: This can leak on err
const base_stats = try allocator.create(libpoke.gen4.BasePokemon{
.stats = libpoke.common.Stats{
.hp = hp,
.attack = attack,
.defense = defense,
.speed = speed,
.sp_attack = sp_attack,
.sp_defense = sp_defense,
},
.types = [2]libpoke.gen4.Type{
@intToEnum(libpoke.gen4.Type, ptype),
@intToEnum(libpoke.gen4.Type, ptype),
},
.catch_rate = undefined,
.base_exp_yield = undefined,
.evs = undefined,
.items = []lu16{comptime lu16.init(item)} ** 2,
.gender_ratio = undefined,
.egg_cycles = undefined,
.base_friendship = undefined,
.growth_rate = undefined,
.egg_group1 = undefined,
.egg_group1_pad = undefined,
.egg_group2 = undefined,
.egg_group2_pad = undefined,
.abilities = undefined,
.flee_rate = undefined,
.color = undefined,
.color_padding = undefined,
.machine_learnset = lu128.init(0),
});
_ = try narc.createFile(name, nds.fs.Narc.File{
.allocator = allocator,
.data = mem.asBytes(base_stats),
});
}
}
{
// TODO: This can leak on err
const narc = try nds.fs.Narc.create(allocator);
try narc.ensureCapacity(level_up_move_count);
_ = try root.createPathAndFile(info.level_up_moves, nds.fs.Nitro.File{ .Narc = narc });
for (loop.to(level_up_move_count)) |_, i| {
var name_buf: [10]u8 = undefined;
const name = try fmt.bufPrint(name_buf[0..], "{}", i);
const lvlup_learnset = libpoke.gen4.LevelUpMove{
.move_id = move,
.level = level,
};
_ = try narc.createFile(name, nds.fs.Narc.File{
.allocator = allocator,
// TODO: This can leak on err
.data = try fmt.allocPrint(
allocator,
"{}{}",
mem.toBytes(lvlup_learnset)[0..],
[]u8{0xFF} ** @sizeOf(libpoke.gen4.LevelUpMove),
),
});
}
}
{
// TODO: This can leak on err
const narc = try nds.fs.Narc.create(allocator);
try narc.ensureCapacity(zone_count);
_ = try root.createPathAndFile(info.wild_pokemons, nds.fs.Nitro.File{ .Narc = narc });
for (loop.to(zone_count)) |_, i| {
var name_buf: [10]u8 = undefined;
const name = try fmt.bufPrint(name_buf[0..], "{}", i);
switch (info.version) {
libpoke.Version.Diamond, libpoke.Version.Pearl, libpoke.Version.Platinum => {
const WildPokemons = libpoke.gen4.DpptWildPokemons;
const Grass = WildPokemons.Grass;
const Replacement = WildPokemons.Replacement;
const Sea = WildPokemons.Sea;
const sea = comptime Sea{
.level_max = level,
.level_min = level,
.pad1 = undefined,
.species = lu16.init(species),
.pad2 = undefined,
};
// TODO: This can leak on err
const wild_pokemon = try allocator.create(WildPokemons{
.grass_rate = lu32.init(rate),
.grass = []Grass{comptime Grass{
.level = level,
.pad1 = undefined,
.species = lu16.init(species),
.pad2 = undefined,
}} ** 12,
.swarm_replacements = []Replacement{Replacement{
.species = comptime lu16.init(species),
.pad = undefined,
}} ** 2,
.day_replacements = []Replacement{Replacement{
.species = comptime lu16.init(species),
.pad = undefined,
}} ** 2,
.night_replacements = []Replacement{Replacement{
.species = comptime lu16.init(species),
.pad = undefined,
}} ** 2,
.radar_replacements = []Replacement{Replacement{
.species = comptime lu16.init(species),
.pad = undefined,
}} ** 4,
.unknown_replacements = []Replacement{Replacement{
.species = comptime lu16.init(species),
.pad = undefined,
}} ** 6,
.gba_replacements = []Replacement{Replacement{
.species = comptime lu16.init(species),
.pad = undefined,
}} ** 10,
.surf = []Sea{sea} ** 5,
.sea_unknown = []Sea{sea} ** 5,
.old_rod = []Sea{sea} ** 5,
.good_rod = []Sea{sea} ** 5,
.super_rod = []Sea{sea} ** 5,
});
_ = try narc.createFile(name, nds.fs.Narc.File{
.allocator = allocator,
.data = mem.asBytes(wild_pokemon),
});
},
libpoke.Version.HeartGold, libpoke.Version.SoulSilver => {
const WildPokemons = libpoke.gen4.HgssWildPokemons;
const Sea = WildPokemons.Sea;
const sea = comptime Sea{
.level_min = level,
.level_max = level,
.species = lu16.init(species),
};
// TODO: This can leak on err
const wild_pokemon = try allocator.create(WildPokemons{
.grass_rate = rate,
.sea_rates = []u8{rate} ** 5,
.unknown = undefined,
.grass_levels = []u8{level} ** 12,
.grass_morning = []lu16{comptime lu16.init(species)} ** 12,
.grass_day = []lu16{comptime lu16.init(species)} ** 12,
.grass_night = []lu16{comptime lu16.init(species)} ** 12,
.radio = []lu16{comptime lu16.init(species)} ** 4,
.surf = []Sea{sea} ** 5,
.sea_unknown = []Sea{sea} ** 2,
.old_rod = []Sea{sea} ** 5,
.good_rod = []Sea{sea} ** 5,
.super_rod = []Sea{sea} ** 5,
.swarm = []lu16{comptime lu16.init(species)} ** 4,
});
_ = try narc.createFile(name, nds.fs.Narc.File{
.allocator = allocator,
.data = mem.asBytes(wild_pokemon),
});
},
else => unreachable,
}
}
}
const name = try fmt.allocPrint(allocator, "{}__{}_{}_{}__", tmp_folder, info.game_title, info.gamecode, @tagName(info.version));
errdefer allocator.free(name);
var file = try os.File.openWrite(name);
errdefer os.deleteFile(name) catch {};
defer file.close();
try rom.writeToFile(file, allocator);
return name;
}
fn genGen5FakeRom(allocator: *mem.Allocator, info: libpoke.gen5.constants.Info) ![]u8 {
const machine_len = libpoke.gen5.constants.tm_count + libpoke.gen5.constants.hm_count;
const machines = []lu16{comptime lu16.init(move)} ** machine_len;
const arm9 = try fmt.allocPrint(allocator, "{}{}", libpoke.gen5.constants.hm_tm_prefix, @sliceToBytes(machines[0..]));
defer allocator.free(arm9);
const rom = nds.Rom{
.allocator = allocator,
.header = ndsHeader(info.game_title, info.gamecode),
.banner = ndsBanner,
.arm9 = arm9,
.arm7 = []u8{},
.nitro_footer = []lu32{comptime lu32.init(0)} ** 3,
.arm9_overlay_table = []nds.Overlay{},
.arm9_overlay_files = [][]u8{},
.arm7_overlay_table = []nds.Overlay{},
.arm7_overlay_files = [][]u8{},
.root = try nds.fs.Nitro.create(allocator),
};
const root = rom.root;
{
// TODO: This can leak on err
const trainer_narc = try nds.fs.Narc.create(allocator);
const party_narc = try nds.fs.Narc.create(allocator);
try trainer_narc.ensureCapacity(trainer_count);
try party_narc.ensureCapacity(trainer_count);
_ = try root.createPathAndFile(info.trainers, nds.fs.Nitro.File{ .Narc = trainer_narc });
_ = try root.createPathAndFile(info.parties, nds.fs.Nitro.File{ .Narc = party_narc });
for (loop.to(trainer_count)) |_, i| {
var name_buf: [10]u8 = undefined;
const name = try fmt.bufPrint(name_buf[0..], "{}", i);
var party_type: u8 = 0;
if (i & has_moves != 0)
party_type |= libpoke.gen5.Trainer.has_moves;
if (i & has_item != 0)
party_type |= libpoke.gen5.Trainer.has_item;
// TODO: This can leak on err
const trainer = try allocator.create(libpoke.gen5.Trainer{
.party_type = party_type,
.class = undefined,
.battle_type = undefined,
.party_size = party_size,
.items = []lu16{comptime lu16.init(item)} ** 4,
.ai = undefined,
.healer = undefined,
.healer_padding = undefined,
.cash = undefined,
.post_battle_item = undefined,
});
_ = try trainer_narc.createFile(name, nds.fs.Narc.File{
.allocator = allocator,
.data = mem.asBytes(trainer)[0..],
});
var tmp_buf: [100]u8 = undefined;
const party_member = libpoke.gen5.PartyMember{
.iv = undefined,
.gender = undefined,
.ability = undefined,
.level = level,
.padding = undefined,
.species = lu16.init(species),
.form = undefined,
};
const held_item_bytes = lu16.init(item).bytes;
const moves_bytes = mem.toBytes([]lu16{comptime lu16.init(move)} ** 4);
// TODO: This can leak on err
const full_party_member_bytes = try fmt.bufPrint(
tmp_buf[0..],
"{}{}{}",
mem.toBytes(party_member)[0..],
held_item_bytes[0 .. held_item_bytes.len * @boolToInt(i & has_item != 0)],
moves_bytes[0 .. moves_bytes.len * @boolToInt(i & has_moves != 0)],
);
_ = try party_narc.createFile(name, nds.fs.Narc.File{
.allocator = allocator,
.data = try repeat(allocator, u8, full_party_member_bytes, party_size),
});
}
}
{
// TODO: This can leak on err
const narc = try nds.fs.Narc.create(allocator);
try narc.ensureCapacity(move_count);
_ = try root.createPathAndFile(info.moves, nds.fs.Nitro.File{ .Narc = narc });
for (loop.to(move_count)) |_, i| {
var name_buf: [10]u8 = undefined;
const name = try fmt.bufPrint(name_buf[0..], "{}", i);
// TODO: This can leak on err
const gen5_move = try allocator.create(libpoke.gen5.Move{
.@"type" = @intToEnum(libpoke.gen5.Type, ptype),
.effect_category = undefined,
.category = undefined,
.power = power,
.accuracy = undefined,
.pp = pp,
.priority = undefined,
.hits = undefined,
.min_hits = undefined,
.max_hits = undefined,
.crit_chance = undefined,
.flinch = undefined,
.effect = undefined,
.target_hp = undefined,
.user_hp = undefined,
.target = undefined,
.stats_affected = undefined,
.stats_affected_magnetude = undefined,
.stats_affected_chance = undefined,
.padding = undefined,
.flags = undefined,
});
_ = try narc.createFile(name, nds.fs.Narc.File{
.allocator = allocator,
.data = mem.asBytes(gen5_move),
});
}
}
{
// TODO: This can leak on err
const narc = try nds.fs.Narc.create(allocator);
try narc.ensureCapacity(pokemon_count);
_ = try root.createPathAndFile(info.base_stats, nds.fs.Nitro.File{ .Narc = narc });
for (loop.to(pokemon_count)) |_, i| {
var name_buf: [10]u8 = undefined;
const name = try fmt.bufPrint(name_buf[0..], "{}", i);
// TODO: This can leak on err
const base_stats = try allocator.create(libpoke.gen5.BasePokemon{
.stats = libpoke.common.Stats{
.hp = hp,
.attack = attack,
.defense = defense,
.speed = speed,
.sp_attack = sp_attack,
.sp_defense = sp_defense,
},
.types = [2]libpoke.gen5.Type{
@intToEnum(libpoke.gen5.Type, ptype),
@intToEnum(libpoke.gen5.Type, ptype),
},
.catch_rate = undefined,
.evs = undefined,
.items = []lu16{comptime lu16.init(item)} ** 3,
.gender_ratio = undefined,
.egg_cycles = undefined,
.base_friendship = undefined,
.growth_rate = undefined,
.egg_group1 = undefined,
.egg_group1_pad = undefined,
.egg_group2 = undefined,
.egg_group2_pad = undefined,
.abilities = undefined,
.flee_rate = undefined,
.form_stats_start = undefined,
.form_sprites_start = undefined,
.form_count = undefined,
.color = undefined,
.color_padding = undefined,
.base_exp_yield = undefined,
.height = undefined,
.weight = undefined,
.machine_learnset = undefined,
});
_ = try narc.createFile(name, nds.fs.Narc.File{
.allocator = allocator,
.data = mem.asBytes(base_stats),
});
}
}
{
// TODO: This can leak on err
const narc = try nds.fs.Narc.create(allocator);
try narc.ensureCapacity(level_up_move_count);
_ = try root.createPathAndFile(info.level_up_moves, nds.fs.Nitro.File{ .Narc = narc });
for (loop.to(level_up_move_count)) |_, i| {
var name_buf: [10]u8 = undefined;
const name = try fmt.bufPrint(name_buf[0..], "{}", i);
const lvlup_learnset = libpoke.gen5.LevelUpMove{
.move_id = lu16.init(move),
.level = lu16.init(level),
};
_ = try narc.createFile(name, nds.fs.Narc.File{
.allocator = allocator,
// TODO: This can leak on err
.data = try fmt.allocPrint(
allocator,
"{}{}",
mem.toBytes(lvlup_learnset)[0..],
[]u8{0xFF} ** @sizeOf(libpoke.gen5.LevelUpMove),
),
});
}
}
{
// TODO: This can leak on err
const narc = try nds.fs.Narc.create(allocator);
try narc.ensureCapacity(level_up_move_count);
_ = try root.createPathAndFile(info.wild_pokemons, nds.fs.Nitro.File{ .Narc = narc });
for (loop.to(zone_count)) |_, i| {
var name_buf: [10]u8 = undefined;
const name = try fmt.bufPrint(name_buf[0..], "{}", i);
const WildPokemon = libpoke.gen5.WildPokemon;
const wild_pokemon = comptime WildPokemon{
.species = lu16.init(species),
.level_min = level,
.level_max = level,
};
// TODO: This can leak on err
const wild_pokemons = try allocator.create(libpoke.gen5.WildPokemons{
.rates = []u8{rate} ** 7,
.pad = undefined,
.grass = []WildPokemon{wild_pokemon} ** 12,
.dark_grass = []WildPokemon{wild_pokemon} ** 12,
.rustling_grass = []WildPokemon{wild_pokemon} ** 12,
.surf = []WildPokemon{wild_pokemon} ** 5,
.ripple_surf = []WildPokemon{wild_pokemon} ** 5,
.fishing = []WildPokemon{wild_pokemon} ** 5,
.ripple_fishing = []WildPokemon{wild_pokemon} ** 5,
});
_ = try narc.createFile(name, nds.fs.Narc.File{
.allocator = allocator,
.data = mem.asBytes(wild_pokemons),
});
}
}
const name = try fmt.allocPrint(allocator, "{}__{}_{}_{}__", tmp_folder, info.game_title, info.gamecode, @tagName(info.version));
errdefer allocator.free(name);
var file = try os.File.openWrite(name);
errdefer os.deleteFile(name) catch {};
defer file.close();
try rom.writeToFile(file, allocator);
return name;
} | test/fake_roms.zig |
const std = @import("std");
const assert = std.debug.assert;
pub fn Rc(comptime T: type) type {
return struct {
const refSize = u16;
refs: std.atomic.Int(refSize),
ptr: ?*T,
allocator: *std.mem.Allocator,
pub const Self = @This();
pub fn init(alloc: *std.mem.Allocator) !Self {
var data = try alloc.createOne(T);
return Self {
.refs = std.atomic.Int(refSize).init(1),
.ptr = data,
.allocator = alloc,
};
}
pub fn incRef(self: *Self) *Self {
if (self.ptr != null) {
_ = self.refs.incr();
}
return self;
}
pub fn decRef(self: *Self) void {
if (self.ptr != null) {
const val = self.refs.decr();
if (val == 1){
self.deinit();
}
}
}
pub fn deinit(self: *Self) void {
self.refs.set(0);
self.allocator.destroy(self.ptr.?);
self.ptr = null;
}
pub fn countRef(self: *Self) refSize {
return self.refs.get();
}
};
}
test "Rc all functions" {
var da = std.heap.DirectAllocator.init();
defer da.deinit();
var all = &da.allocator;
var rcint = try Rc(i32).init(all);
assert(rcint.ptr != null);
// reference adjustments
_ = rcint.incRef();
assert(rcint.countRef() == 2);
rcint.decRef();
// assignment
rcint.ptr.?.* = 0;
assert(rcint.ptr.?.* == 0);
// auto free
rcint.decRef();
assert(rcint.ptr == null);
}
test "Rc auto-free" {
var da = std.heap.DirectAllocator.init();
defer da.deinit();
var all = &da.allocator;
var rcint = try Rc(u32).init(all);
assert(rcint.ptr != null);
rcint.ptr.?.* = 1;
assert(freefn(&rcint) == 1);
assert(rcint.ptr == null);
}
fn freefn(data: *Rc(u32)) u32 {
defer data.decRef();
return data.ptr.?.*;
}
test "Threaded Rc" {
var da = std.heap.DirectAllocator.init();
defer da.deinit();
var all = &da.allocator;
var context = try Rc(Ctx).init(all);
context.ptr.?.val = 5;
var threads: [10]*std.os.Thread = undefined;
for (threads) |*t| {
t.* = try std.os.spawnThread(context.incRef(), worker);
}
context.decRef();
for (threads) |t|
t.wait();
assert(context.ptr == null);
}
const Ctx = struct {
val: u32,
};
fn worker(ctx: *Rc(Ctx)) void {
defer ctx.decRef();
if (ctx.ptr.?.val != 5){
@panic("Nope");
}
} | zrc.zig |
const builtin = @import("builtin");
// Zig's own stack-probe routine (available only on x86 and x86_64)
pub fn zig_probe_stack() callconv(.Naked) void {
@setRuntimeSafety(false);
// Versions of the Linux kernel before 5.1 treat any access below SP as
// invalid so let's update it on the go, otherwise we'll get a segfault
// instead of triggering the stack growth.
switch (builtin.arch) {
.x86_64 => {
// %rax = probe length, %rsp = stack pointer
asm volatile (
\\ push %%rcx
\\ mov %%rax, %%rcx
\\ cmp $0x1000,%%rcx
\\ jb 2f
\\ 1:
\\ sub $0x1000,%%rsp
\\ orl $0,16(%%rsp)
\\ sub $0x1000,%%rcx
\\ cmp $0x1000,%%rcx
\\ ja 1b
\\ 2:
\\ sub %%rcx, %%rsp
\\ orl $0,16(%%rsp)
\\ add %%rax,%%rsp
\\ pop %%rcx
\\ ret
);
},
.i386 => {
// %eax = probe length, %esp = stack pointer
asm volatile (
\\ push %%ecx
\\ mov %%eax, %%ecx
\\ cmp $0x1000,%%ecx
\\ jb 2f
\\ 1:
\\ sub $0x1000,%%esp
\\ orl $0,8(%%esp)
\\ sub $0x1000,%%ecx
\\ cmp $0x1000,%%ecx
\\ ja 1b
\\ 2:
\\ sub %%ecx, %%esp
\\ orl $0,8(%%esp)
\\ add %%eax,%%esp
\\ pop %%ecx
\\ ret
);
},
else => {},
}
unreachable;
}
fn win_probe_stack_only() void {
@setRuntimeSafety(false);
switch (builtin.arch) {
.x86_64 => {
asm volatile (
\\ push %%rcx
\\ push %%rax
\\ cmp $0x1000,%%rax
\\ lea 24(%%rsp),%%rcx
\\ jb 1f
\\ 2:
\\ sub $0x1000,%%rcx
\\ test %%rcx,(%%rcx)
\\ sub $0x1000,%%rax
\\ cmp $0x1000,%%rax
\\ ja 2b
\\ 1:
\\ sub %%rax,%%rcx
\\ test %%rcx,(%%rcx)
\\ pop %%rax
\\ pop %%rcx
\\ ret
);
},
.i386 => {
asm volatile (
\\ push %%ecx
\\ push %%eax
\\ cmp $0x1000,%%eax
\\ lea 12(%%esp),%%ecx
\\ jb 1f
\\ 2:
\\ sub $0x1000,%%ecx
\\ test %%ecx,(%%ecx)
\\ sub $0x1000,%%eax
\\ cmp $0x1000,%%eax
\\ ja 2b
\\ 1:
\\ sub %%eax,%%ecx
\\ test %%ecx,(%%ecx)
\\ pop %%eax
\\ pop %%ecx
\\ ret
);
},
else => {},
}
unreachable;
}
fn win_probe_stack_adjust_sp() void {
@setRuntimeSafety(false);
switch (builtin.arch) {
.x86_64 => {
asm volatile (
\\ push %%rcx
\\ cmp $0x1000,%%rax
\\ lea 16(%%rsp),%%rcx
\\ jb 1f
\\ 2:
\\ sub $0x1000,%%rcx
\\ test %%rcx,(%%rcx)
\\ sub $0x1000,%%rax
\\ cmp $0x1000,%%rax
\\ ja 2b
\\ 1:
\\ sub %%rax,%%rcx
\\ test %%rcx,(%%rcx)
\\
\\ lea 8(%%rsp),%%rax
\\ mov %%rcx,%%rsp
\\ mov -8(%%rax),%%rcx
\\ push (%%rax)
\\ sub %%rsp,%%rax
\\ ret
);
},
.i386 => {
asm volatile (
\\ push %%ecx
\\ cmp $0x1000,%%eax
\\ lea 8(%%esp),%%ecx
\\ jb 1f
\\ 2:
\\ sub $0x1000,%%ecx
\\ test %%ecx,(%%ecx)
\\ sub $0x1000,%%eax
\\ cmp $0x1000,%%eax
\\ ja 2b
\\ 1:
\\ sub %%eax,%%ecx
\\ test %%ecx,(%%ecx)
\\
\\ lea 4(%%esp),%%eax
\\ mov %%ecx,%%esp
\\ mov -4(%%eax),%%ecx
\\ push (%%eax)
\\ sub %%esp,%%eax
\\ ret
);
},
else => {},
}
unreachable;
}
// Windows has a multitude of stack-probing functions with similar names and
// slightly different behaviours: some behave as alloca() and update the stack
// pointer after probing the stack, other do not.
//
// Function name | Adjusts the SP? |
// | x86 | x86_64 |
// ----------------------------------------
// _chkstk (_alloca) | yes | yes |
// __chkstk | yes | no |
// __chkstk_ms | no | no |
// ___chkstk (__alloca) | yes | yes |
// ___chkstk_ms | no | no |
pub fn _chkstk() callconv(.Naked) void {
@setRuntimeSafety(false);
@call(.{ .modifier = .always_inline }, win_probe_stack_adjust_sp, .{});
}
pub fn __chkstk() callconv(.Naked) void {
@setRuntimeSafety(false);
switch (builtin.arch) {
.i386 => @call(.{ .modifier = .always_inline }, win_probe_stack_adjust_sp, .{}),
.x86_64 => @call(.{ .modifier = .always_inline }, win_probe_stack_only, .{}),
else => unreachable,
}
}
pub fn ___chkstk() callconv(.Naked) void {
@setRuntimeSafety(false);
@call(.{ .modifier = .always_inline }, win_probe_stack_adjust_sp, .{});
}
pub fn __chkstk_ms() callconv(.Naked) void {
@setRuntimeSafety(false);
@call(.{ .modifier = .always_inline }, win_probe_stack_only, .{});
}
pub fn ___chkstk_ms() callconv(.Naked) void {
@setRuntimeSafety(false);
@call(.{ .modifier = .always_inline }, win_probe_stack_only, .{});
} | lib/std/special/compiler_rt/stack_probe.zig |
const std = @import("std");
const debug = std.debug;
const mem = std.mem;
const testing = std.testing;
/// Determin the runtime size requirement of N types continues in memory (in bytes).
fn runtimeSize(comptime fields: var) comptime_int {
var res = 0;
for (fields) |field| {
res += @sizeOf(field.Value);
}
return res;
}
pub fn Field(comptime T: type) type {
return struct {
key: T,
Value: type,
pub fn init(key: T, comptime Value: type) @This() {
return @This(){
.key = key,
.Value = Value,
};
}
};
}
pub fn Struct(comptime Key: type, comptime field_array: var) type {
for (field_array) |a, i| {
for (field_array[i + 1 ..]) |b| {
// TODO: Abitrary key equal
debug.assert(a.key != b.key);
}
}
return struct {
pub const fields = field_array;
// In order for us to store the tuples values, we have
// to type erase away the values, and store them as bytes.
data: [runtimeSize(fields)]u8,
pub fn field(s: @This(), comptime key: Key) GetField(key).Value {
return s.ptrConst(key).*;
}
pub fn ptr(s: *@This(), comptime key: Key) *align(1) GetField(key).Value {
const i = comptime index(key);
const offset = comptime runtimeSize(fields[0..i]);
return &std.mem.bytesAsSlice(GetField(key).Value, s.data[offset..])[0];
}
pub fn ptrConst(s: *const @This(), comptime key: Key) *align(1) const GetField(key).Value {
const i = comptime index(key);
const offset = comptime runtimeSize(fields[0..i]);
return &std.mem.bytesAsSlice(GetField(key).Value, s.data[offset..])[0];
}
fn GetField(comptime key: Key) Field(Key) {
return fields[index(key)];
}
fn index(comptime key: Key) usize {
inline for (fields) |f, i| {
if (f.key == key)
return i;
}
unreachable;
}
};
}
test "struct" {
const T = Struct(u8, [_]Field(u8){
Field(u8).init(0, u8),
Field(u8).init(1, u16),
Field(u8).init(2, f32),
});
const s = blk: {
var res: T = undefined;
res.ptr(0).* = 11;
res.ptr(1).* = 22;
res.ptr(2).* = 33;
break :blk res;
};
testing.expectEqual(s.field(0), 11);
testing.expectEqual(s.field(1), 22);
testing.expectEqual(s.field(2), 33);
} | src/struct.zig |
const std = @import("std");
const builtin = @import("builtin");
const testing = std.testing;
const expect = testing.expect;
const expectEqual = testing.expectEqual;
test "params" {
try expect(testParamsAdd(22, 11) == 33);
}
fn testParamsAdd(a: i32, b: i32) i32 {
return a + b;
}
test "local variables" {
testLocVars(2);
}
fn testLocVars(b: i32) void {
const a: i32 = 1;
if (a + b != 3) unreachable;
}
test "mutable local variables" {
var zero: i32 = 0;
try expect(zero == 0);
var i = @as(i32, 0);
while (i != 3) {
i += 1;
}
try expect(i == 3);
}
test "separate block scopes" {
{
const no_conflict: i32 = 5;
try expect(no_conflict == 5);
}
const c = x: {
const no_conflict = @as(i32, 10);
break :x no_conflict;
};
try expect(c == 10);
}
fn @"weird function name"() i32 {
return 1234;
}
test "weird function name" {
try expect(@"weird function name"() == 1234);
}
test "assign inline fn to const variable" {
const a = inlineFn;
a();
}
inline fn inlineFn() void {}
fn outer(y: u32) fn (u32) u32 {
const Y = @TypeOf(y);
const st = struct {
fn get(z: u32) u32 {
return z + @sizeOf(Y);
}
};
return st.get;
}
test "return inner function which references comptime variable of outer function" {
var func = outer(10);
try expect(func(3) == 7);
}
test "discard the result of a function that returns a struct" {
const S = struct {
fn entry() void {
_ = func();
}
fn func() Foo {
return undefined;
}
const Foo = struct {
a: u64,
b: u64,
};
};
S.entry();
comptime S.entry();
}
test "inline function call that calls optional function pointer, return pointer at callsite interacts correctly with callsite return type" {
const S = struct {
field: u32,
fn doTheTest() !void {
bar2 = actualFn;
const result = try foo();
try expect(result.field == 1234);
}
const Foo = struct { field: u32 };
fn foo() !Foo {
var res: Foo = undefined;
res.field = bar();
return res;
}
inline fn bar() u32 {
return bar2.?();
}
var bar2: ?fn () u32 = null;
fn actualFn() u32 {
return 1234;
}
};
try S.doTheTest();
} | test/behavior/fn.zig |
const std = @import("std");
const builtin = @import("builtin");
const native_endian = builtin.target.cpu.arch.endian();
const expect = std.testing.expect;
const expectEqual = std.testing.expectEqual;
const expectEqualSlices = std.testing.expectEqualSlices;
const maxInt = std.math.maxInt;
const Node = struct {
val: Val,
next: *Node,
};
const Val = struct {
x: i32,
};
test "struct point to self" {
var root: Node = undefined;
root.val.x = 1;
var node: Node = undefined;
node.next = &root;
node.val.x = 2;
root.next = &node;
try expect(node.next.next.next.val.x == 1);
}
test "void struct fields" {
const foo = VoidStructFieldsFoo{
.a = void{},
.b = 1,
.c = void{},
};
try expect(foo.b == 1);
try expect(@sizeOf(VoidStructFieldsFoo) == 4);
}
const VoidStructFieldsFoo = struct {
a: void,
b: i32,
c: void,
};
test "return empty struct from fn" {
_ = testReturnEmptyStructFromFn();
}
const EmptyStruct2 = struct {};
fn testReturnEmptyStructFromFn() EmptyStruct2 {
return EmptyStruct2{};
}
test "pass slice of empty struct to fn" {
try expect(testPassSliceOfEmptyStructToFn(&[_]EmptyStruct2{EmptyStruct2{}}) == 1);
}
fn testPassSliceOfEmptyStructToFn(slice: []const EmptyStruct2) usize {
return slice.len;
}
test "self-referencing struct via array member" {
const T = struct {
children: [1]*@This(),
};
var x: T = undefined;
x = T{ .children = .{&x} };
try expect(x.children[0] == &x);
}
test "empty struct method call" {
const es = EmptyStruct{};
try expect(es.method() == 1234);
}
const EmptyStruct = struct {
fn method(es: *const EmptyStruct) i32 {
_ = es;
return 1234;
}
};
test "align 1 field before self referential align 8 field as slice return type" {
const result = alloc(Expr);
try expect(result.len == 0);
}
const Expr = union(enum) {
Literal: u8,
Question: *Expr,
};
fn alloc(comptime T: type) []T {
return &[_]T{};
}
const APackedStruct = packed struct {
x: u8,
y: u8,
};
test "packed struct" {
var foo = APackedStruct{
.x = 1,
.y = 2,
};
foo.y += 1;
const four = foo.x + foo.y;
try expect(four == 4);
}
const Foo24Bits = packed struct {
field: u24,
};
const Foo96Bits = packed struct {
a: u24,
b: u24,
c: u24,
d: u24,
};
test "packed struct 24bits" {
comptime {
try expect(@sizeOf(Foo24Bits) == 4);
if (@sizeOf(usize) == 4) {
try expect(@sizeOf(Foo96Bits) == 12);
} else {
try expect(@sizeOf(Foo96Bits) == 16);
}
}
var value = Foo96Bits{
.a = 0,
.b = 0,
.c = 0,
.d = 0,
};
value.a += 1;
try expect(value.a == 1);
try expect(value.b == 0);
try expect(value.c == 0);
try expect(value.d == 0);
value.b += 1;
try expect(value.a == 1);
try expect(value.b == 1);
try expect(value.c == 0);
try expect(value.d == 0);
value.c += 1;
try expect(value.a == 1);
try expect(value.b == 1);
try expect(value.c == 1);
try expect(value.d == 0);
value.d += 1;
try expect(value.a == 1);
try expect(value.b == 1);
try expect(value.c == 1);
try expect(value.d == 1);
}
test "runtime struct initialization of bitfield" {
const s1 = Nibbles{
.x = x1,
.y = x1,
};
const s2 = Nibbles{
.x = @intCast(u4, x2),
.y = @intCast(u4, x2),
};
try expect(s1.x == x1);
try expect(s1.y == x1);
try expect(s2.x == @intCast(u4, x2));
try expect(s2.y == @intCast(u4, x2));
}
var x1 = @as(u4, 1);
var x2 = @as(u8, 2);
const Nibbles = packed struct {
x: u4,
y: u4,
};
const Bitfields = packed struct {
f1: u16,
f2: u16,
f3: u8,
f4: u8,
f5: u4,
f6: u4,
f7: u8,
};
test "native bit field understands endianness" {
var all: u64 = if (native_endian != .Little)
0x1111222233445677
else
0x7765443322221111;
var bytes: [8]u8 = undefined;
@memcpy(&bytes, @ptrCast([*]u8, &all), 8);
var bitfields = @ptrCast(*Bitfields, &bytes).*;
try expect(bitfields.f1 == 0x1111);
try expect(bitfields.f2 == 0x2222);
try expect(bitfields.f3 == 0x33);
try expect(bitfields.f4 == 0x44);
try expect(bitfields.f5 == 0x5);
try expect(bitfields.f6 == 0x6);
try expect(bitfields.f7 == 0x77);
}
test "implicit cast packed struct field to const ptr" {
const LevelUpMove = packed struct {
move_id: u9,
level: u7,
fn toInt(value: u7) u7 {
return value;
}
};
var lup: LevelUpMove = undefined;
lup.level = 12;
const res = LevelUpMove.toInt(lup.level);
try expect(res == 12);
}
test "zero-bit field in packed struct" {
const S = packed struct {
x: u10,
y: void,
};
var x: S = undefined;
_ = x;
}
test "packed struct with non-ABI-aligned field" {
const S = packed struct {
x: u9,
y: u183,
};
var s: S = undefined;
s.x = 1;
s.y = 42;
try expect(s.x == 1);
try expect(s.y == 42);
} | test/behavior/struct_llvm.zig |
const std = @import("std");
const ray = @import("ray.zig");
const camera = @import("camera.zig");
const config = @import("config.zig");
const sphere = @import("sphere.zig");
const vector = @import("vector.zig");
const material = @import("material.zig");
const Vec3 = config.Vec3;
pub const Hit = struct {
object_idx: ?usize = undefined,
ray_scale_factor: f64 = std.math.f64_max,
};
pub const Scene = struct {
camera: *camera.Camera,
lights: std.ArrayList(usize),
objects: std.ArrayList(sphere.Sphere),
pub fn intersect(self: *Scene, cur_ray: ray.Ray) Hit {
var hit: Hit = .{};
var ray_scale_factor: f64 = undefined;
for (self.objects.items) |cur_sphere, idx| {
ray_scale_factor = cur_sphere.computeRaySphereHit(cur_ray);
if (ray_scale_factor > 0.0 and ray_scale_factor < hit.ray_scale_factor) {
hit.ray_scale_factor = ray_scale_factor;
hit.object_idx = idx;
}
}
return hit;
}
pub fn collectLights(self: *Scene) !void {
for (self.objects.items) |object, light_idx| {
if (object.isLight()) {
try self.lights.append(light_idx);
}
}
}
};
pub fn sampleLights(scene: *Scene, hit_point: Vec3, normal: Vec3, ray_direction: Vec3, cur_material: *const material.Material) Vec3 {
var color = config.ZERO_VECTOR;
for (scene.lights.items) |light_idx| {
const light = scene.objects.items[light_idx];
var hit_point_to_light_center = light.center - hit_point;
const distance_to_light_sqrd = vector.dot_product(hit_point_to_light_center, hit_point_to_light_center);
hit_point_to_light_center = vector.normalize(hit_point_to_light_center);
var cos_theta = vector.dot_product(normal, hit_point_to_light_center);
var shadow_ray = ray.Ray{ .origin = hit_point, .direction = hit_point_to_light_center };
var shadow_ray_hit = scene.intersect(shadow_ray);
if (shadow_ray_hit.object_idx) |shadow_idx| {
if (shadow_idx == light_idx) {
if (cos_theta > 0.0) {
const sin_alpha_max_sqrd = light.radius * light.radius / distance_to_light_sqrd;
const cos_alpha_max = @sqrt(1.0 - sin_alpha_max_sqrd);
const omega = 2.0 * (1.0 - cos_alpha_max);
cos_theta *= omega;
color += cur_material.diffuse * light.material.emissive * @splat(config.SCENE_DIMS, cos_theta);
}
if (cur_material.material_type == material.MaterialType.GLOSSY or cur_material.material_type == material.MaterialType.MIRROR) {
const reflected_direction = vector.reflect(hit_point_to_light_center, normal);
cos_theta = -vector.dot_product(reflected_direction, ray_direction);
if (cos_theta > 0.0) {
const specular_color = cur_material.specular * @splat(config.SCENE_DIMS, std.math.pow(f64, cos_theta, cur_material.specular_exponent));
color += specular_color;
}
}
}
}
}
return color;
} | src/scene.zig |
const core = @import("../index.zig");
const Coord = core.geometry.Coord;
const ThingPosition = core.protocol.ThingPosition;
const Species = core.protocol.Species;
const Wall = core.protocol.Wall;
const assert = @import("std").debug.assert;
pub const view_distance = 8;
pub fn getAttackRange(species: Species) i32 {
switch (species) {
.centaur => return 16,
.rhino => return 0,
else => return 1,
}
}
pub fn hasFastMove(species: Species) bool {
return switch (species) {
.rhino => true,
else => false,
};
}
pub fn getInertiaIndex(species: Species) u1 {
switch (species) {
.rhino => return 1,
else => return 0,
}
}
pub fn isFastMoveAligned(position: ThingPosition, move_delta: Coord) bool {
assert(core.geometry.isScaledCardinalDirection(move_delta, 2));
const facing_delta = position.large[0].minus(position.large[1]);
return facing_delta.scaled(2).equals(move_delta);
}
pub fn isAffectedByAttacks(species: Species, position_index: usize) bool {
return switch (species) {
.turtle => false,
// only rhino's tail is affected, not head.
.rhino => position_index == 1,
else => true,
};
}
pub fn isOpenSpace(wall: Wall) bool {
switch (wall) {
.air, .centaur_transformer => return true,
else => return false,
}
}
pub fn getHeadPosition(thing_position: ThingPosition) Coord {
return switch (thing_position) {
.small => |coord| coord,
.large => |coords| coords[0],
};
}
pub fn getAllPositions(thing_position: *const ThingPosition) []const Coord {
return switch (thing_position.*) {
.small => |*coord| @as(*const [1]Coord, coord)[0..],
.large => |*coords| coords[0..],
};
}
pub fn applyMovementToPosition(position: ThingPosition, move_delta: Coord) ThingPosition {
switch (position) {
.small => |coord| {
return .{ .small = coord.plus(move_delta) };
},
.large => |coords| {
const next_head_coord = coords[0].plus(move_delta);
return .{
.large = .{
next_head_coord,
next_head_coord.minus(move_delta.signumed()),
},
};
},
}
}
pub const Anatomy = enum {
humanoid,
centauroid,
quadruped,
kangaroid,
};
pub fn getAnatomy(species: Species) Anatomy {
switch (species) {
.human, .orc => return .humanoid,
.centaur => return .centauroid,
.turtle, .rhino => return .quadruped,
.kangaroo => return .kangaroid,
}
} | src/core/game_logic.zig |
// SPDX-License-Identifier: MIT
// This file is part of the Termelot project under the MIT license.
const std = @import("std");
pub const Style = struct {
fg_color: Color,
bg_color: Color,
decorations: Decorations,
pub fn default() Style {
return Style{
.fg_color = Color.Default,
.bg_color = Color.Default,
.decorations = Decorations{
.bold = false,
.italic = false,
.underline = false,
.blinking = false,
},
};
}
};
pub const Decorations = packed struct {
bold: bool,
italic: bool,
underline: bool,
blinking: bool,
pub fn none() Decorations {
return Decorations{
.bold = false,
.italic = false,
.underline = false,
.blinking = false,
};
}
};
pub const Color = union(ColorType) {
Default: u0,
Named16: ColorNamed16,
Bit8: ColorBit8,
Bit24: ColorBit24,
/// Create a new Color from red, green, and blue values with a ColorBit24.
pub fn RGB(red: u8, green: u8, blue: u8) Color {
return Color{ .Bit24 = ColorBit24.initRGB(red, green, blue) };
}
/// Create a new Color from a hex code with a ColorBit24.
pub fn hex(code: u24) Color {
return Color{ .Bit24 = ColorBit24{ .code = code } };
}
/// Create a new Color from one of 16 color names with a ColorNamed16.
pub inline fn named(n: ColorNamed16) Color {
return Color{ .Named16 = n };
}
};
pub const ColorType = enum {
Default,
Named16,
Bit8,
Bit24,
};
/// The first 8 values of the `ColorNamed16` are supported by all colored terminals. Likely anything
/// reasonably capable of being a terminal will support the first 8 values, and probably the other
/// half, as well. These values are only indexes to a palette stored by the terminal -- users may
/// be able to override palettes -- some terminals may do it automatically.
///
/// But in some rare cases, a terminal is only ASCII and will not support colors at all. Hopefully
/// in at least half of these cases, the backend will detect the terminal's ill support of colors,
/// and will ignore any incoming colors. In the event a backend attempts to use colors on a terminal
/// without support for them, that terminal may stop working. But in general, the basic 16 colors
/// are very safe to use, especially on modern terminals.
///
/// Color names and values based on [ANSI Escape Codes](https://en.wikipedia.org/wiki/ANSI_escape_code).
pub const ColorNamed16 = enum {
Black,
Red,
Green,
Yellow,
Blue,
Magenta,
Cyan,
White,
BrightBlack,
BrightRed,
BrightGreen,
BrightYellow,
BrightBlue,
BrightMagenta,
BrightCyan,
BrightWhite,
};
/// A ColorBit8 is technically an 8-bit reference to a palette containing 24-bit colors.
/// In this library we just refer to it as 8-bit color. Most modern terminals support 256 colors.
///
/// Just like for `ColorBit24`: if 8-bit colors are used on a backend or terminal at runtime that
/// does not support 8-bit color, and the backend knows, then it will round 8-bit colors to
/// `ColorNamed16`s or the highest bit-size color supported.
///
/// Color values based on [ANSI Escape Codes](https://en.wikipedia.org/wiki/ANSI_escape_code).
pub const ColorBit8 = packed struct {
code: u8,
/// `ColorNamed16`s comprise the first 16 values of the `ColorBit8`, so the enum is converted
/// to an integer.
pub fn fromNamed16(named: ColorNamed16) ColorBit8 {
return ColorBit8{ .code = @enumToInt(named) };
}
pub fn roundToNamed16(self: Self) ColorNamed16 {
_ = self;
@compileError("unimplemented");
}
};
/// 16 million color 24-bit, or better known as "True Color" or RGB. Almost an equal number of
/// supporting and non-supporting terminals feature True Color. Some terminals may use rounding
/// to convert 24-bit colors to 8-bit colors, but many more seem not to round, either.
///
/// If 24-bit colors are used on a backend or terminal at runtime that does not support 24-bit color,
/// and the backend knows, then it will round 24-bit colors to the highest bit-size color supported.
/// This rounding may cause differences in appearance: see description of function `roundToBit8`.
///
/// For more information about True Color, see this gist: https://gist.github.com/XVilka/8346728
pub const ColorBit24 = packed struct {
code: u24,
const Self = @This();
pub fn RGB(r: u8, g: u8, b: u8) ColorBit24 {
var code: u24 = 0;
code |= b;
code |= @as(u16, g) << 8;
code |= @as(u24, r) << 16;
return ColorBit24{ .code = code };
}
pub fn red(self: Self) u8 {
return @intCast(u8, self.code >> 16);
}
pub fn green(self: Self) u8 {
return @intCast(u8, (self.code >> 8) & 255);
}
pub fn blue(self: Self) u8 {
return @intCast(u8, self.code & 255);
}
/// Round 24-bit Color to 8-bit using nearest values. This may be useful when
/// terminals don't support "True Color" or RGB color. Uses a lookup table to find
/// nearest 24-bit color equivalents for 8-bit colors on the palette.
///
/// In general, rounding colors to lower bit sizes on terminals cannot be considered
/// reliable for many reasons. Terminals can use different palettes, and the converted
/// colors may be nowhere near accurate. But in the same sense, that is true about ColorBit8
/// already.
pub fn roundToBit8(self: Self) ColorBit8 {
const closest_main_idx = binarySearchClosest(&main_table, 0, main_table.len - 1, self.code);
const closest_grey_idx = binarySearchClosest(&grey_table, 0, grey_table.len - 1, self.code);
const main_diff = std.math.absInt(@intCast(i32, main_table[closest_main_idx]) - @intCast(i32, self.code)) catch unreachable;
const grey_diff = std.math.absInt(@intCast(i32, grey_table[closest_grey_idx]) - @intCast(i32, self.code)) catch unreachable;
if (main_diff < grey_diff) {
return ColorBit8{ .code = @intCast(u8, closest_main_idx) + 16 };
} else {
return ColorBit8{ .code = @intCast(u8, closest_grey_idx) + 232 };
}
}
};
/// Binary search sorted `slice` for closest value to `val` between indices `start` and `end`.
/// Returns index to `slice` where closest number is found.
fn binarySearchClosest(slice: []const u24, start: usize, end: usize, val: u24) usize {
var l = start;
var r = end;
var mid: usize = 0;
while (l <= r) {
mid = l + (r - l) / 2;
// NOTE: this binary search does not include the difference in value between selections,
// so although a number like 0x949493 might be very close to 0x949494, the lower value in
// the table may be selected instead, because we do not weigh the difference between each
// whole color. This is better for performance and might not show much difference.
if (slice[mid] < val) {
l = mid + 1;
} else if (slice[mid] > val) {
r = mid - 1;
} else {
return mid; // Found an exact match
}
}
return mid; // Got closest match
}
// Lookup table for standard 16-bit colors after 15, and before 232, as their equivalent 24-bits.
const main_table = [216]u24{
0x000000, 0x00005f, 0x000087, 0x0000af, 0x0000d7, 0x0000ff,
0x005f00, 0x005f5f, 0x005f87, 0x005faf, 0x005fd7, 0x005fff,
0x008700, 0x00875f, 0x008787, 0x0087af, 0x0087d7, 0x0087ff,
0x00af00, 0x00af5f, 0x00af87, 0x00afaf, 0x00afd7, 0x00afff,
0x00d700, 0x00d75f, 0x00d787, 0x00d7af, 0x00d7d7, 0x00d7ff,
0x00ff00, 0x00ff5f, 0x00ff87, 0x00ffaf, 0x00ffd7, 0x00ffff,
0x5f0000, 0x5f005f, 0x5f0087, 0x5f00af, 0x5f00d7, 0x5f00ff,
0x5f5f00, 0x5f5f5f, 0x5f5f87, 0x5f5faf, 0x5f5fd7, 0x5f5fff,
0x5f8700, 0x5f875f, 0x5f8787, 0x5f87af, 0x5f87d7, 0x5f87ff,
0x5faf00, 0x5faf5f, 0x5faf87, 0x5fafaf, 0x5fafd7, 0x5fafff,
0x5fd700, 0x5fd75f, 0x5fd787, 0x5fd7af, 0x5fd7d7, 0x5fd7ff,
0x5fff00, 0x5fff5f, 0x5fff87, 0x5fffaf, 0x5fffd7, 0x5fffff,
0x870000, 0x87005f, 0x870087, 0x8700af, 0x8700d7, 0x8700ff,
0x875f00, 0x875f5f, 0x875f87, 0x875faf, 0x875fd7, 0x875fff,
0x878700, 0x87875f, 0x878787, 0x8787af, 0x8787d7, 0x8787ff,
0x87af00, 0x87af5f, 0x87af87, 0x87afaf, 0x87afd7, 0x87afff,
0x87d700, 0x87d75f, 0x87d787, 0x87d7af, 0x87d7d7, 0x87d7ff,
0x87ff00, 0x87ff5f, 0x87ff87, 0x87ffaf, 0x87ffd7, 0x87ffff,
0xaf0000, 0xaf005f, 0xaf0087, 0xaf00af, 0xaf00d7, 0xaf00ff,
0xaf5f00, 0xaf5f5f, 0xaf5f87, 0xaf5faf, 0xaf5fd7, 0xaf5fff,
0xaf8700, 0xaf875f, 0xaf8787, 0xaf87af, 0xaf87d7, 0xaf87ff,
0xafaf00, 0xafaf5f, 0xafaf87, 0xafafaf, 0xafafd7, 0xafafff,
0xafd700, 0xafd75f, 0xafd787, 0xafd7af, 0xafd7d7, 0xafd7ff,
0xafff00, 0xafff5f, 0xafff87, 0xafffaf, 0xafffd7, 0xafffff,
0xd70000, 0xd7005f, 0xd70087, 0xd700af, 0xd700d7, 0xd700ff,
0xd75f00, 0xd75f5f, 0xd75f87, 0xd75faf, 0xd75fd7, 0xd75fff,
0xd78700, 0xd7875f, 0xd78787, 0xd787af, 0xd787d7, 0xd787ff,
0xd7af00, 0xd7af5f, 0xd7af87, 0xd7afaf, 0xd7afd7, 0xd7afff,
0xd7d700, 0xd7d75f, 0xd7d787, 0xd7d7af, 0xd7d7d7, 0xd7d7ff,
0xd7ff00, 0xd7ff5f, 0xd7ff87, 0xd7ffaf, 0xd7ffd7, 0xd7ffff,
0xff0000, 0xff005f, 0xff0087, 0xff00af, 0xff00d7, 0xff00ff,
0xff5f00, 0xff5f5f, 0xff5f87, 0xff5faf, 0xff5fd7, 0xff5fff,
0xff8700, 0xff875f, 0xff8787, 0xff87af, 0xff87d7, 0xff87ff,
0xffaf00, 0xffaf5f, 0xffaf87, 0xffafaf, 0xffafd7, 0xffafff,
0xffd700, 0xffd75f, 0xffd787, 0xffd7af, 0xffd7d7, 0xffd7ff,
0xffff00, 0xffff5f, 0xffff87, 0xffffaf, 0xffffd7, 0xffffff,
};
// Lookup table for greys as 24-bits.
const grey_table = [24]u24{
0x080808, 0x121212, 0x1c1c1c, 0x262626, 0x303030, 0x3a3a3a,
0x444444, 0x4e4e4e, 0x585858, 0x606060, 0x666666, 0x767676,
0x808080, 0x8a8a8a, 0x949494, 0x9e9e9e, 0xa8a8a8, 0xb2b2b2,
0xbcbcbc, 0xc6c6c6, 0xd0d0d0, 0xdadada, 0xe4e4e4, 0xeeeeee,
};
// Tables from https://www.calmar.ws/vim/256-xterm-24bit-rgb-color-chart.html
test "roundToBit8" {
std.testing.expectEqual((ColorBit24{ .code = 0xFFFFFF }).roundToBit8().code, 231); // Index for white
std.testing.expectEqual((ColorBit24{ .code = 0xFF0000 }).roundToBit8().code, 196); // Index for red
std.testing.expectEqual((ColorBit24{ .code = 0x949494 }).roundToBit8().code, 246); // Index for some smokey color (grey_table)
std.testing.expectEqual((ColorBit24{ .code = 0x080808 }).roundToBit8().code, 232); // Index for similar to black (grey_table)
// NOTE: cannot test rounding because of inaccuracy. See note in binarySearchClosest().
} | src/style.zig |
const std = @import("std");
const BuildStep = @import("./build_step.zig");
const Self = @This();
builder: *std.build.Builder,
hosted_step: *BuildStep,
plugin_step: *BuildStep,
step: std.build.Step,
pub fn create(build_step: *BuildStep) *Self {
const builder = build_step.builder;
const self = builder.allocator.create(Self) catch unreachable;
self.builder = builder;
self.hosted_step = build_step;
self.step = std.build.Step.init(.custom, "hot reload step", builder.allocator, make);
var options = build_step.options;
options.name = std.mem.join(builder.allocator, " ", &[_][]const u8{
options.name,
"(Auto Reload)",
}) catch unreachable;
options.identifier = std.mem.join(builder.allocator, "_", &[_][]const u8{
"auto_reload",
options.identifier,
}) catch unreachable;
options.package_add = .{ .Automatic = "zig-vst" };
const plugin_src = self.resolveRelativeToSrc("reload.zig") catch unreachable;
self.plugin_step = BuildStep.create(builder, plugin_src, options);
const watch_file_path = self.getWatchFilePath() catch unreachable;
self.plugin_step.lib_step.addBuildOption([]const u8, "watch_patch", watch_file_path);
self.step.dependOn(&self.plugin_step.step);
self.step.dependOn(&build_step.lib_step.step);
return self;
}
fn make(step: *std.build.Step) anyerror!void {
const self = @fieldParentPtr(Self, "step", step);
const lib_output_path = self.hosted_step.getInternalLibOutputPath();
try self.updateWatchPath(lib_output_path);
}
fn resolveRelativeToSrc(self: *Self, path: []const u8) ![]const u8 {
const dirname = std.fs.path.dirname(@src().file) orelse return error.DirnameFailed;
return std.fs.path.resolve(self.builder.allocator, &[_][]const u8{
dirname,
path,
});
}
fn getWatchFileDir(self: *Self) ![]const u8 {
const relative_to_root = try std.fs.path.join(self.builder.allocator, &[_][]const u8{
self.builder.cache_root,
"vst-reload",
});
return self.builder.pathFromRoot(relative_to_root);
}
fn getWatchFilePath(self: *Self) ![]const u8 {
return try std.fs.path.join(self.builder.allocator, &[_][]const u8{
try self.getWatchFileDir(),
self.getWatchFileName(),
});
}
fn getWatchFileName(self: *Self) []const u8 {
return self.hosted_step.options.name;
}
fn updateWatchPath(self: *Self, new_path: []const u8) !void {
const cwd = std.fs.cwd();
const watch_path = try self.getWatchFileDir();
const watch_dir = try cwd.makeOpenPath(watch_path, .{});
const name = self.getWatchFileName();
try watch_dir.writeFile(name, new_path);
} | src/reload_step.zig |
const std = @import("std");
const xml = @import("xml.zig");
const Peripheral = @import("Peripheral.zig");
const Register = @import("Register.zig");
const Field = @import("Field.zig");
const ArenaAllocator = std.heap.ArenaAllocator;
const Allocator = std.mem.Allocator;
pub const Device = struct {
vendor: ?[]const u8 = null,
vendor_id: ?[]const u8 = null,
name: ?[]const u8 = null,
series: ?[]const u8 = null,
version: ?[]const u8 = null,
description: ?[]const u8 = null,
license_text: ?[]const u8 = null,
address_unit_bits: usize,
width: usize,
register_properties: struct {
size: ?usize = null,
access: ?Access = null,
protection: ?[]const u8 = null,
reset_value: ?[]const u8 = null,
reset_mask: ?[]const u8 = null,
},
pub fn parse(arena: *ArenaAllocator, nodes: *xml.Node) !Device {
const allocator = arena.allocator();
return Device{
.vendor = if (xml.findValueForKey(nodes, "vendor")) |str| try allocator.dupe(u8, str) else null,
.vendor_id = if (xml.findValueForKey(nodes, "vendorID")) |str| try allocator.dupe(u8, str) else null,
.name = if (xml.findValueForKey(nodes, "name")) |name| try allocator.dupe(u8, name) else null,
.series = if (xml.findValueForKey(nodes, "series")) |str| try allocator.dupe(u8, str) else null,
.version = if (xml.findValueForKey(nodes, "version")) |str| try allocator.dupe(u8, str) else null,
.description = if (xml.findValueForKey(nodes, "description")) |str| try allocator.dupe(u8, str) else null,
.license_text = if (xml.findValueForKey(nodes, "licenseText")) |str| try allocator.dupe(u8, str) else null,
.address_unit_bits = try std.fmt.parseInt(usize, xml.findValueForKey(nodes, "addressUnitBits") orelse return error.NoAddressUnitBits, 0),
.width = try std.fmt.parseInt(usize, xml.findValueForKey(nodes, "width") orelse return error.NoDeviceWidth, 0),
.register_properties = .{
// register properties group
.size = if (xml.findValueForKey(nodes, "size")) |size_str|
try std.fmt.parseInt(usize, size_str, 0)
else
null,
.access = if (xml.findValueForKey(nodes, "access")) |access_str|
try Access.parse(access_str)
else
null,
.protection = if (xml.findValueForKey(nodes, "protection")) |str| try allocator.dupe(u8, str) else null,
.reset_value = if (xml.findValueForKey(nodes, "resetValue")) |str| try allocator.dupe(u8, str) else null,
.reset_mask = if (xml.findValueForKey(nodes, "resetMask")) |str| try allocator.dupe(u8, str) else null,
},
};
}
};
pub const CpuName = enum {
cortex_m0,
cortex_m0plus,
cortex_m1,
sc000, // kindof like an m3
cortex_m23,
cortex_m3,
cortex_m33,
cortex_m35p,
cortex_m55,
sc300,
cortex_m4,
cortex_m7,
arm_v8_mml,
arm_v8_mbl,
arm_v81_mml,
cortex_a5,
cortex_a7,
cortex_a8,
cortex_a9,
cortex_a15,
cortex_a17,
cortex_a53,
cortex_a57,
cortex_a72,
// avr
avr,
other,
// TODO: finish
pub fn parse(str: []const u8) ?CpuName {
return if (std.mem.eql(u8, "CM0", str))
CpuName.cortex_m0
else if (std.mem.eql(u8, "CM0PLUS", str))
CpuName.cortex_m0plus
else if (std.mem.eql(u8, "CM0+", str))
CpuName.cortex_m0plus
else if (std.mem.eql(u8, "CM1", str))
CpuName.cortex_m1
else if (std.mem.eql(u8, "SC000", str))
CpuName.sc000
else if (std.mem.eql(u8, "CM23", str))
CpuName.cortex_m23
else if (std.mem.eql(u8, "CM3", str))
CpuName.cortex_m3
else if (std.mem.eql(u8, "CM33", str))
CpuName.cortex_m33
else if (std.mem.eql(u8, "CM35P", str))
CpuName.cortex_m35p
else if (std.mem.eql(u8, "CM55", str))
CpuName.cortex_m55
else if (std.mem.eql(u8, "SC300", str))
CpuName.sc300
else if (std.mem.eql(u8, "CM4", str))
CpuName.cortex_m4
else if (std.mem.eql(u8, "CM7", str))
CpuName.cortex_m7
else if (std.mem.eql(u8, "AVR8", str))
CpuName.avr
else
null;
}
};
pub const Endian = enum {
little,
big,
selectable,
other,
pub fn parse(str: []const u8) !Endian {
return if (std.meta.stringToEnum(Endian, str)) |val|
val
else
error.UnknownEndianType;
}
};
pub const Cpu = struct {
//name: ?CpuName,
name: ?[]const u8,
revision: []const u8,
endian: Endian,
//mpu_present: bool,
//fpu_present: bool,
//fpu_dp: bool,
//dsp_present: bool,
//icache_present: bool,
//dcache_present: bool,
//itcm_present: bool,
//dtcm_present: bool,
//vtor_present: bool,
nvic_prio_bits: usize,
vendor_systick_config: bool,
device_num_interrupts: ?usize,
//sau_num_regions: usize,
pub fn parse(arena: *ArenaAllocator, nodes: *xml.Node) !Cpu {
return Cpu{
.name = if (xml.findValueForKey(nodes, "name")) |name| try arena.allocator().dupe(u8, name) else null,
.revision = xml.findValueForKey(nodes, "revision") orelse unreachable,
.endian = try Endian.parse(xml.findValueForKey(nodes, "endian") orelse unreachable),
.nvic_prio_bits = try std.fmt.parseInt(usize, xml.findValueForKey(nodes, "nvicPrioBits") orelse unreachable, 0),
// TODO: booleans
.vendor_systick_config = (try xml.parseBoolean(arena.child_allocator, nodes, "vendorSystickConfig")) orelse false,
.device_num_interrupts = if (xml.findValueForKey(nodes, "deviceNumInterrupts")) |size_str|
try std.fmt.parseInt(usize, size_str, 0)
else
null,
};
}
};
pub const Access = enum {
read_only,
write_only,
read_write,
writeonce,
read_writeonce,
pub fn parse(str: []const u8) !Access {
return if (std.mem.eql(u8, "read-only", str))
Access.read_only
else if (std.mem.eql(u8, "write-only", str))
Access.write_only
else if (std.mem.eql(u8, "read-write", str))
Access.read_write
else if (std.mem.eql(u8, "writeOnce", str))
Access.writeonce
else if (std.mem.eql(u8, "read-writeOnce", str))
Access.read_writeonce
else
error.UnknownAccessType;
}
};
pub fn parsePeripheral(arena: *ArenaAllocator, nodes: *xml.Node) !Peripheral {
const allocator = arena.allocator();
return Peripheral{
.name = try allocator.dupe(u8, xml.findValueForKey(nodes, "name") orelse return error.NoName),
.version = if (xml.findValueForKey(nodes, "version")) |version|
try allocator.dupe(u8, version)
else
null,
.description = try xml.parseDescription(allocator, nodes, "description"),
.base_addr = (try xml.parseIntForKey(usize, arena.child_allocator, nodes, "baseAddress")) orelse return error.NoBaseAddr, // isDefault?
};
}
pub const Interrupt = struct {
name: []const u8,
description: ?[]const u8,
value: usize,
pub fn parse(arena: *ArenaAllocator, nodes: *xml.Node) !Interrupt {
const allocator = arena.allocator();
return Interrupt{
.name = try allocator.dupe(u8, xml.findValueForKey(nodes, "name") orelse return error.NoName),
.description = try xml.parseDescription(allocator, nodes, "description"),
.value = try std.fmt.parseInt(usize, xml.findValueForKey(nodes, "value") orelse return error.NoValue, 0),
};
}
pub fn lessThan(_: void, lhs: Interrupt, rhs: Interrupt) bool {
return lhs.value < rhs.value;
}
pub fn compare(_: void, lhs: Interrupt, rhs: Interrupt) std.math.Order {
return if (lhs.value < rhs.value)
std.math.Order.lt
else if (lhs.value == rhs.value)
std.math.Order.eq
else
std.math.Order.gt;
}
};
pub fn parseRegister(arena: *ArenaAllocator, nodes: *xml.Node, device_width: usize) !Register {
const allocator = arena.allocator();
return Register{
.name = try allocator.dupe(u8, xml.findValueForKey(nodes, "name") orelse return error.NoName),
.description = try xml.parseDescription(allocator, nodes, "description"),
.addr_offset = try std.fmt.parseInt(usize, xml.findValueForKey(nodes, "addressOffset") orelse return error.NoAddrOffset, 0),
.size = (try xml.parseIntForKey(usize, arena.child_allocator, nodes, "size")) orelse device_width,
};
}
pub const Cluster = struct {
name: []const u8,
description: ?[]const u8,
addr_offset: usize,
pub fn parse(arena: *ArenaAllocator, nodes: *xml.Node) !Cluster {
const allocator = arena.allocator();
return Cluster{
.name = try allocator.dupe(u8, xml.findValueForKey(nodes, "name") orelse return error.NoName),
.description = try xml.parseDescription(allocator, nodes, "description"),
.addr_offset = try std.fmt.parseInt(usize, xml.findValueForKey(nodes, "addressOffset") orelse return error.NoAddrOffset, 0),
};
}
};
const BitRange = struct {
offset: u8,
width: u8,
};
pub fn parseField(arena: *ArenaAllocator, nodes: *xml.Node) !Field {
const allocator = arena.allocator();
// TODO:
const bit_range = blk: {
const lsb_opt = xml.findValueForKey(nodes, "lsb");
const msb_opt = xml.findValueForKey(nodes, "msb");
if (lsb_opt != null and msb_opt != null) {
const lsb = try std.fmt.parseInt(u8, lsb_opt.?, 0);
const msb = try std.fmt.parseInt(u8, msb_opt.?, 0);
if (msb < lsb)
return error.InvalidRange;
break :blk BitRange{
.offset = lsb,
.width = msb - lsb + 1,
};
}
const bit_offset_opt = xml.findValueForKey(nodes, "bitOffset");
const bit_width_opt = xml.findValueForKey(nodes, "bitWidth");
if (bit_offset_opt != null and bit_width_opt != null) {
const offset = try std.fmt.parseInt(u8, bit_offset_opt.?, 0);
const width = try std.fmt.parseInt(u8, bit_width_opt.?, 0);
break :blk BitRange{
.offset = offset,
.width = width,
};
}
const bit_range_opt = xml.findValueForKey(nodes, "bitRange");
if (bit_range_opt) |bit_range_str| {
var it = std.mem.tokenize(u8, bit_range_str, "[:]");
const msb = try std.fmt.parseInt(u8, it.next() orelse return error.NoMsb, 0);
const lsb = try std.fmt.parseInt(u8, it.next() orelse return error.NoLsb, 0);
if (msb < lsb)
return error.InvalidRange;
break :blk BitRange{
.offset = lsb,
.width = msb - lsb + 1,
};
}
return error.InvalidRange;
};
return Field{
.name = try allocator.dupe(u8, xml.findValueForKey(nodes, "name") orelse return error.NoName),
.offset = bit_range.offset,
.width = bit_range.width,
.description = try xml.parseDescription(allocator, nodes, "description"),
};
}
pub const EnumeratedValue = struct {
name: []const u8,
description: ?[]const u8,
value: ?usize,
pub fn parse(arena: *ArenaAllocator, nodes: *xml.Node) !EnumeratedValue {
const allocator = arena.allocator();
return EnumeratedValue{
.name = try allocator.dupe(u8, xml.findValueForKey(nodes, "name") orelse return error.NoName),
.description = try xml.parseDescription(allocator, nodes, "description"),
.value = try xml.parseIntForKey(usize, arena.child_allocator, nodes, "value"), // TODO: isDefault?
};
}
};
pub const Dimension = struct {
dim: usize,
increment: usize,
/// a range of 0-index, only index is recorded
index: ?Index,
name: ?[]const u8,
//array_index: ,
const Index = union(enum) {
num: usize,
list: std.ArrayList([]const u8),
};
pub fn parse(arena: *ArenaAllocator, nodes: *xml.Node) !?Dimension {
const allocator = arena.allocator();
return Dimension{
.dim = (try xml.parseIntForKey(usize, arena.child_allocator, nodes, "dim")) orelse return null,
.increment = (try xml.parseIntForKey(usize, arena.child_allocator, nodes, "dimIncrement")) orelse return null,
.index = if (xml.findValueForKey(nodes, "dimIndex")) |index_str|
if (std.mem.indexOf(u8, index_str, ",") != null) blk: {
var list = std.ArrayList([]const u8).init(allocator);
var it = std.mem.tokenize(u8, index_str, ",");
var expected: usize = 0;
while (it.next()) |token| : (expected += 1)
try list.append(try allocator.dupe(u8, token));
break :blk Index{
.list = list,
};
} else blk: {
var it = std.mem.tokenize(u8, index_str, "-");
const begin = try std.fmt.parseInt(usize, it.next() orelse return error.InvalidDimIndex, 10);
const end = try std.fmt.parseInt(usize, it.next() orelse return error.InvalidDimIndex, 10);
if (begin == 0)
break :blk Index{
.num = end + 1,
};
var list = std.ArrayList([]const u8).init(allocator);
var i = begin;
while (i <= end) : (i += 1)
try list.append(try std.fmt.allocPrint(allocator, "{}", .{i}));
break :blk Index{
.list = list,
};
}
else
null,
.name = if (xml.findValueForKey(nodes, "dimName")) |name_str|
try allocator.dupe(u8, name_str)
else
null,
};
}
}; | src/svd.zig |
const std = @import("std");
const c = @import("c.zig");
const gl = @import("gl.zig");
const fs = @import("fs.zig");
const m = @import("math/math.zig");
const utf8 = @import("utf8.zig");
const alog = std.log.scoped(.alka_core_renderer);
/// Error set
pub const Error = error{
ObjectOverflow,
VertexOverflow,
IndexOverflow,
UnknownSubmitFn,
FailedToGenerateBuffers,
FailedToLoadTexture,
FailedToLoadFont,
FailedToGenerateAtlas,
} || fs.Error;
/// Colour generic struct
pub fn ColourGeneric(comptime typ: type) type {
switch (typ) {
f16, f32, f64, f128 => {
return struct {
r: typ = 0,
g: typ = 0,
b: typ = 0,
a: typ = 0,
pub fn rgba(r: u32, g: u32, b: u32, a: u32) @This() {
return .{
.r = @intToFloat(typ, r) / 255.0,
.g = @intToFloat(typ, g) / 255.0,
.b = @intToFloat(typ, b) / 255.0,
.a = @intToFloat(typ, a) / 255.0,
};
}
};
},
u8, u16, u32, u64, u128 => {
return struct {
r: typ = 0,
g: typ = 0,
b: typ = 0,
a: typ = 0,
pub fn rgba(r: u32, g: u32, b: u32, a: u32) @This() {
return .{
.r = @intCast(typ, r),
.g = @intCast(typ, g),
.b = @intCast(typ, b),
.a = @intCast(typ, a),
};
}
};
},
else => @compileError("Non-implemented type"),
}
}
pub const Colour = ColourGeneric(f32);
pub const UColour = ColourGeneric(u8);
/// Vertex generic struct
pub fn VertexGeneric(istextcoord: bool, comptime positiontype: type) type {
if (positiontype == m.Vec2f or positiontype == m.Vec3f) {
if (!istextcoord) {
return struct {
const Self = @This();
position: positiontype = positiontype{},
colour: Colour = Colour{},
};
}
return struct {
const Self = @This();
position: positiontype = positiontype{},
texcoord: m.Vec2f = m.Vec2f{},
colour: Colour = Colour{},
};
}
@compileError("Unknown position type");
}
/// Batch generic structure
pub fn BatchGeneric(max_object: u32, max_index: u32, max_vertex: u32, comptime vertex_type: type) type {
return struct {
const Self = @This();
pub const max_object_count: u32 = max_object;
pub const max_index_count: u32 = max_index;
pub const max_vertex_count: u32 = max_vertex;
pub const Vertex: type = vertex_type;
vertex_array: u32 = 0,
buffers: [2]u32 = [2]u32{ 0, 0 },
vertex_list: [max_object_count][max_vertex_count]vertex_type = undefined,
index_list: [max_object_count][max_index_count]u32 = undefined,
submitfn: ?fn (self: *Self, vertex: [Self.max_vertex_count]vertex_type) Error!void = null,
submission_counter: u32 = 0,
/// Creates the batch
pub fn create(self: *Self, shaderprogram: u32, shadersetattribs: fn () void) Error!void {
self.submission_counter = 0;
gl.vertexArraysGen(1, @ptrCast([*]u32, &self.vertex_array));
gl.buffersGen(2, &self.buffers);
if (self.vertex_array == 0 or self.buffers[0] == 0 or self.buffers[1] == 0) {
gl.vertexArraysDelete(1, @ptrCast([*]const u32, &self.vertex_array));
gl.buffersDelete(2, @ptrCast([*]const u32, &self.buffers));
return Error.FailedToGenerateBuffers;
}
gl.vertexArrayBind(self.vertex_array);
defer gl.vertexArrayBind(0);
gl.bufferBind(gl.BufferType.array, self.buffers[0]);
gl.bufferBind(gl.BufferType.elementarray, self.buffers[1]);
defer gl.bufferBind(gl.BufferType.array, 0);
defer gl.bufferBind(gl.BufferType.elementarray, 0);
gl.bufferData(gl.BufferType.array, @sizeOf(vertex_type) * max_vertex_count * max_object_count, @ptrCast(?*const c_void, &self.vertex_list), gl.DrawType.dynamic);
gl.bufferData(gl.BufferType.elementarray, @sizeOf(u32) * max_index_count * max_object_count, @ptrCast(?*const c_void, &self.index_list), gl.DrawType.dynamic);
gl.shaderProgramUse(shaderprogram);
defer gl.shaderProgramUse(0);
shadersetattribs();
}
/// Destroys the batch
pub fn destroy(self: Self) void {
gl.vertexArraysDelete(1, @ptrCast([*]const u32, &self.vertex_array));
gl.buffersDelete(2, @ptrCast([*]const u32, &self.buffers));
}
/// Set the vertex data from set and given position
pub fn submitVertex(self: *Self, firstposition: u32, lastposition: u32, data: Vertex) Error!void {
if (firstposition >= Self.max_object_count) {
return Error.ObjectOverflow;
} else if (lastposition >= Self.max_vertex_count) {
return Error.VertexOverflow;
}
self.vertex_list[firstposition][lastposition] = data;
}
/// Set the index data from set and given position
pub fn submitIndex(self: *Self, firstposition: u32, lastposition: u32, data: u32) Error!void {
if (firstposition >= Self.max_object_count) {
return Error.ObjectOverflow;
} else if (lastposition >= Self.max_index_count) {
return Error.IndexOverflow;
}
self.index_list[firstposition][lastposition] = data;
}
/// Submit a drawable object
pub fn submitDrawable(self: *Self, obj: [Self.max_vertex_count]vertex_type) Error!void {
if (self.submission_counter >= Self.max_object_count) {
return Error.ObjectOverflow;
} else if (self.submitfn) |fun| {
try fun(self, obj);
return;
}
return Error.UnknownSubmitFn;
}
/// Cleans the lists
pub fn cleanAll(self: *Self) void {
var i: u32 = 0;
while (i < Self.max_object_count) : (i += 1) {
var j: u32 = 0;
while (j < Self.max_index_count) : (j += 1) {
self.index_list[i][j] = 0;
}
j = 0;
while (j < Self.max_vertex_count) : (j += 1) {
self.vertex_list[i][j] = .{};
}
}
}
/// Draw the submitted objects
pub fn draw(self: Self, drawmode: gl.DrawMode) Error!void {
if (self.submission_counter > Self.max_object_count) return Error.ObjectOverflow;
gl.vertexArrayBind(self.vertex_array);
defer gl.vertexArrayBind(0);
gl.bufferBind(gl.BufferType.array, self.buffers[0]);
gl.bufferBind(gl.BufferType.elementarray, self.buffers[1]);
defer gl.bufferBind(gl.BufferType.array, 0);
defer gl.bufferBind(gl.BufferType.elementarray, 0);
gl.bufferSubData(gl.BufferType.array, 0, @sizeOf(Vertex) * max_vertex_count * max_object_count, @ptrCast(?*const c_void, &self.vertex_list));
gl.bufferSubData(gl.BufferType.elementarray, 0, @sizeOf(u32) * max_index_count * max_object_count, @ptrCast(?*const c_void, &self.index_list));
gl.drawElements(drawmode, @intCast(i32, Self.max_object_count * Self.max_index_count), u32, null);
}
};
}
pub const TextureRaw = struct {
width: i32 = 0,
height: i32 = 0,
pixels: ?[]u8 = null,
rpixels: ?[*c]u8 = null,
};
pub const Texture = struct {
id: u32 = 0,
width: i32 = 0,
height: i32 = 0,
fn loadSetup(self: *Texture) void {
gl.texturesGen(1, @ptrCast([*]u32, &self.id));
gl.textureBind(gl.TextureType.t2D, self.id);
gl.textureTexParameteri(gl.TextureType.t2D, gl.TextureParamaterType.min_filter, gl.TextureParamater.filter_nearest);
gl.textureTexParameteri(gl.TextureType.t2D, gl.TextureParamaterType.mag_filter, gl.TextureParamater.filter_linear);
gl.textureTexParameteri(gl.TextureType.t2D, gl.TextureParamaterType.wrap_s, gl.TextureParamater.wrap_repeat);
gl.textureTexParameteri(gl.TextureType.t2D, gl.TextureParamaterType.wrap_t, gl.TextureParamater.wrap_repeat);
}
/// Creates a texture from png file
pub fn createFromPNG(alloc: *std.mem.Allocator, path: []const u8) Error!Texture {
const mem = try fs.readFile(alloc, path);
defer alloc.free(mem);
return try createFromPNGMemory(mem);
}
/// Creates a texture from png memory
pub fn createFromPNGMemory(mem: []const u8) Error!Texture {
var result = Texture{};
loadSetup(&result);
defer gl.textureBind(gl.TextureType.t2D, 0);
var nrchannels: i32 = 0;
c.stbi_set_flip_vertically_on_load(0);
var data: ?*u8 = c.stbi_load_from_memory(@ptrCast([*c]const u8, mem), @intCast(i32, mem.len), &result.width, &result.height, &nrchannels, 4);
defer c.stbi_image_free(data);
if (data == null) {
gl.texturesDelete(1, @ptrCast([*]u32, &result.id));
return Error.FailedToLoadTexture;
}
gl.textureTexImage2D(gl.TextureType.t2D, 0, gl.TextureFormat.rgba8, result.width, result.height, 0, gl.TextureFormat.rgba, u8, data);
gl.texturesGenMipmap(gl.TextureType.t2D);
return result;
}
/// Creates a basic texture from TTF font file with given string
pub fn createFromTTF(alloc: *std.mem.Allocator, filepath: []const u8, string: []const u8, w: i32, h: i32, lineh: i32) Error!Texture {
var result = Texture{ .width = w, .height = h };
loadSetup(&result);
defer gl.textureBind(gl.TextureType.t2D, 0);
const mem = try fs.readFile(alloc, filepath);
defer alloc.free(mem);
var info: c.stbtt_fontinfo = undefined;
if (c.stbtt_InitFont(&info, @ptrCast([*c]const u8, mem), 0) == 0) {
return Error.FailedToLoadFont;
}
// calculate font scaling
const scale: f32 = c.stbtt_ScaleForPixelHeight(&info, @intToFloat(f32, lineh));
var x: i32 = 0;
var ascent: i32 = 0;
var descent: i32 = 0;
var linegap: i32 = 0;
c.stbtt_GetFontVMetrics(&info, &ascent, &descent, &linegap);
ascent = @floatToInt(i32, @round(@intToFloat(f32, ascent) * scale));
descent = @floatToInt(i32, @round(@intToFloat(f32, descent) * scale));
// create a bitmap for the phrase
var bitmap: []u8 = alloc.alloc(u8, @intCast(usize, w * h)) catch return Error.FailedToLoadTexture;
{
var i: usize = 0;
while (i < w * h) : (i += 1) {
bitmap[i] = 0;
}
}
{
var i: usize = 0;
while (i < string.len) : (i += 1) {
if (string[i] == 0) continue;
// how wide is this character
var ax: i32 = 0;
var lsb: i32 = 0;
c.stbtt_GetCodepointHMetrics(&info, string[i], &ax, &lsb);
// get bounding box for character (may be offset to account for chars that
// dip above or below the line
var c_x1: i32 = 0;
var c_y1: i32 = 0;
var c_x2: i32 = 0;
var c_y2: i32 = 0;
c.stbtt_GetCodepointBitmapBox(&info, string[i], scale, scale, &c_x1, &c_y1, &c_x2, &c_y2);
// compute y (different characters have different heights
var y: i32 = ascent + c_y1;
// render character (stride and offset is important here)
var byteOffset = x + @floatToInt(i32, @round(@intToFloat(f32, lsb) * scale) + @intToFloat(f32, (y * w)));
c.stbtt_MakeCodepointBitmap(&info, @ptrCast([*c]u8, bitmap[@intCast(usize, byteOffset)..]), c_x2 - c_x1, c_y2 - c_y1, w, scale, scale, string[i]);
// advance x
x += @floatToInt(i32, @round(@intToFloat(f32, ax) * scale));
if (string.len >= i) continue;
// add kerning
var kern: i32 = 0;
kern = c.stbtt_GetCodepointKernAdvance(&info, string[i], string[i + 1]);
x += @floatToInt(i32, @round(@intToFloat(f32, kern) * scale));
}
}
// convert image data from grayscale to grayalpha
// two channels
var gralpha: []u8 = alloc.alloc(u8, @intCast(usize, w * h * 2)) catch return Error.FailedToLoadTexture;
{
var i: usize = 0;
var k: usize = 0;
while (i < w * h) : (i += 1) {
gralpha[k] = 255;
gralpha[k + 1] = bitmap[i];
k += 2;
}
}
alloc.free(bitmap);
bitmap = gralpha;
defer alloc.free(bitmap);
gl.textureTexImage2D(gl.TextureType.t2D, 0, gl.TextureFormat.rg8, result.width, result.height, 0, gl.TextureFormat.rg, u8, @ptrCast(?*c_void, bitmap));
// source: https://github.com/raysan5/raylib/blob/cba412cc313e4f95eafb3fba9303400e65c98984/src/rlgl.h#L2447
const swizzle = comptime [_]u32{ c.GL_RED, c.GL_RED, c.GL_RED, c.GL_GREEN };
c.glTexParameteriv(c.GL_TEXTURE_2D, c.GL_TEXTURE_SWIZZLE_RGBA, @ptrCast([*c]const i32, &swizzle));
gl.texturesGenMipmap(gl.TextureType.t2D);
return result;
}
/// Creates a texture from given colour
pub fn createFromColour(colour: [*]UColour, w: i32, h: i32) Texture {
var result = Texture{ .width = w, .height = h };
loadSetup(&result);
defer gl.textureBind(gl.TextureType.t2D, 0);
gl.textureTexImage2D(gl.TextureType.t2D, 0, gl.TextureFormat.rgba8, result.width, result.height, 0, gl.TextureFormat.rgba, u8, @ptrCast(?*c_void, colour));
gl.texturesGenMipmap(gl.TextureType.t2D);
return result;
}
/// Changes the filter of the texture
pub fn setFilter(self: Texture, comptime min: gl.TextureParamater, comptime mag: gl.TextureParamater) void {
gl.textureBind(gl.TextureType.t2D, self.id);
defer gl.textureBind(gl.TextureType.t2D, 0);
gl.textureTexParameteri(gl.TextureType.t2D, gl.TextureParamaterType.min_filter, min);
gl.textureTexParameteri(gl.TextureType.t2D, gl.TextureParamaterType.mag_filter, mag);
}
/// Destroys the texture
pub fn destroy(self: *Texture) void {
gl.texturesDelete(1, @ptrCast([*]const u32, &self.id));
self.id = 0;
}
};
pub const Font = struct {
pub const bitmap_alpha_threshold = 80;
pub const char_padding = 4;
pub const char_fallback = 63;
pub const Glyph = struct {
codepoint: i32 = undefined,
offx: i32 = undefined,
offy: i32 = undefined,
advance: i32 = undefined,
raw: TextureRaw = undefined,
};
alloc: *std.mem.Allocator = undefined,
texture: Texture = undefined,
rects: []m.Rectangle = undefined,
glyphs: []Glyph = undefined,
base_size: i32 = undefined,
glyph_padding: i32 = undefined,
// source: https://github.com/raysan5/raylib/blob/cba412cc313e4f95eafb3fba9303400e65 c98984/src/text.c#L553
fn loadFontData(alloc: *std.mem.Allocator, mem: []const u8, fontsize: i32, fontchars: ?[]const i32) Error![]Glyph {
var info: c.stbtt_fontinfo = undefined;
if (c.stbtt_InitFont(&info, @ptrCast([*c]const u8, mem), 0) == 0) {
return Error.FailedToLoadFont;
}
var genfontchars = false;
var chars: []Glyph = undefined;
// calculate font scale factor
const scale_factor: f32 = c.stbtt_ScaleForPixelHeight(&info, @intToFloat(f32, fontsize));
// calculate font basic metrics
// NOTE: ascent is equivalent to font baseline
var ascent: i32 = 0;
var descent: i32 = 0;
var linegap: i32 = 0;
c.stbtt_GetFontVMetrics(&info, &ascent, &descent, &linegap);
// in case np chars provided, default to 95
var charcount = if (fontchars) |ch| ch.len else 95;
// fill fontChars in case not provided externally
// NOTE: by default we fill charsCount consecutevely, starting at 32 (space)
var pfontchars: []i32 = undefined;
defer alloc.free(pfontchars);
pfontchars = alloc.alloc(i32, charcount) catch return Error.FailedToLoadFont;
{
var i: usize = 0;
if (fontchars == null) {
while (i < charcount) : (i += 1) {
pfontchars[i] = @intCast(i32, i) + 32;
}
genfontchars = true;
} else |ch| {
while (i < charcount) : (i += 1) {
pfontchars[i] = ch[i];
}
}
}
chars = alloc.alloc(Glyph, charcount) catch return Error.FailedToLoadFont;
// NOTE: using simple packaging one char after another
var i: usize = 0;
while (i < charcount) : (i += 1) {
// char width & height -on gen-
var chw: i32 = 0;
var chh: i32 = 0;
// char value to get info for
var ch: i32 = pfontchars[i];
chars[i].codepoint = ch;
chars[i].raw.rpixels = c.stbtt_GetCodepointBitmap(&info, scale_factor, scale_factor, @intCast(i32, ch), &chw, &chh, &chars[i].offx, &chars[i].offy);
c.stbtt_GetCodepointHMetrics(&info, @intCast(i32, ch), &chars[i].advance, null);
chars[i].advance = @floatToInt(i32, @intToFloat(f32, chars[i].advance) * scale_factor);
// load char images
chars[i].raw.width = chw;
chars[i].raw.height = chh;
chars[i].offy += @floatToInt(i32, @intToFloat(f32, ascent) * scale_factor);
// NOTE: we create an empty image for space char, it could be further
// required for atlas packing
if (ch == 32) {
chars[i].raw.pixels = alloc.alloc(u8, @intCast(usize, chars[i].advance * fontsize * 2)) catch return Error.FailedToLoadFont; // *2?
var j: usize = 0;
while (j < chars[i].advance * fontsize * 2) : (j += 1) {
chars[i].raw.pixels.?[j] = 0;
}
chars[i].raw.width = chars[i].advance;
chars[i].raw.height = fontsize;
}
// Aliased bitmap (black & white) font generation, avoiding anti-aliasing
// NOTE: For optimum results, bitmap font should be generated at base pixelsize
var j: usize = 0;
while (j < chw * chh) : (j += 1) {
if (chars[i].raw.pixels) |px| {
if (px[j] < bitmap_alpha_threshold) {
px[j] = 0;
} else {
px[j] = 255;
}
} else if (chars[i].raw.rpixels) |px| {
if (px[j] < bitmap_alpha_threshold) {
px[j] = 0;
} else {
px[j] = 255;
}
}
}
}
return chars;
}
fn genImageAtlas(self: *Font) Error!TextureRaw {
var atlas: []u8 = undefined;
var atlasw: i32 = 0;
var atlash: i32 = 0;
var alloc = self.alloc;
const chars = self.glyphs;
const fontsize = self.base_size;
const padding = self.glyph_padding;
self.rects = alloc.alloc(m.Rectangle, chars.len) catch return Error.FailedToGenerateAtlas;
// Calculate image size based on required pixel area
// NOTE 1: Image is forced to be squared and POT... very conservative!
// NOTE 2: SDF font characters already contain an internal padding,
// so image size would result bigger than default font type
var required_area: f32 = 0;
{
var i: usize = 0;
while (i < chars.len) : (i += 1) {
required_area += @intToFloat(f32, ((chars[i].raw.width + 2 * padding) * (chars[i].raw.height + 2 * padding)));
}
var guess_size = @sqrt(required_area) * 1.3;
var v2: f32 = 2; // compiler bug
var image_size = @floatToInt(i32, std.math.pow(f32, 2, @ceil(@log(guess_size) / @log(v2)))); // calculate next POT
atlasw = image_size;
atlash = image_size;
atlas = alloc.alloc(u8, @intCast(usize, atlasw * atlash)) catch return Error.FailedToGenerateAtlas;
i = 0;
while (i < atlasw * atlash) : (i += 1) {
atlas[i] = 0;
}
}
var context: *c.stbrp_context = alloc.create(c.stbrp_context) catch return Error.FailedToGenerateAtlas;
defer alloc.destroy(context);
var nodes: []c.stbrp_node = alloc.alloc(c.stbrp_node, chars.len) catch return Error.FailedToGenerateAtlas;
defer alloc.free(nodes);
c.stbrp_init_target(context, atlasw, atlash, @ptrCast([*c]c.stbrp_node, nodes), @intCast(i32, chars.len));
var rects: []c.stbrp_rect = alloc.alloc(c.stbrp_rect, chars.len) catch return Error.FailedToGenerateAtlas;
defer alloc.free(rects);
// fill rectangles for packing
var i: usize = 0;
while (i < chars.len) : (i += 1) {
rects[i].id = @intCast(i32, i);
rects[i].w = @intCast(u16, chars[i].raw.width + 2 * padding);
rects[i].h = @intCast(u16, chars[i].raw.height + 2 * padding);
}
// pack rects into atlas
_ = c.stbrp_pack_rects(context, @ptrCast([*c]c.stbrp_rect, rects), @intCast(i32, chars.len));
i = 0;
while (i < chars.len) : (i += 1) {
self.rects[i].position.x = @intToFloat(f32, rects[i].x + @intCast(u16, padding));
self.rects[i].position.y = @intToFloat(f32, rects[i].y + @intCast(u16, padding));
self.rects[i].size.x = @intToFloat(f32, chars[i].raw.width);
self.rects[i].size.y = @intToFloat(f32, chars[i].raw.height);
if (rects[i].was_packed == 1) {
// copy pixel data from fc.data to atlas
var y: usize = 0;
while (y < chars[i].raw.height) : (y += 1) {
var x: usize = 0;
while (x < chars[i].raw.width) : (x += 1) {
if (chars[i].raw.pixels) |px| {
const index = @intCast(usize, (rects[i].y + padding + @intCast(i32, y)) * atlasw + (rects[i].x + padding + @intCast(i32, x)));
atlas[index] = px[y * @intCast(usize, chars[i].raw.width) + x];
} else if (chars[i].raw.rpixels) |px| {
const index = @intCast(usize, (rects[i].y + padding + @intCast(i32, y)) * atlasw + (rects[i].x + padding + @intCast(i32, x)));
atlas[index] = px[y * @intCast(usize, chars[i].raw.width) + x];
}
}
}
} else alog.warn("failed to pack char: {}", .{i});
}
// convert image data from grayscale to grayalpha
// two channels
var gralpha: []u8 = alloc.alloc(u8, @intCast(usize, atlasw * atlash * 2)) catch return Error.FailedToLoadTexture;
{
i = 0;
var k: usize = 0;
while (i < atlasw * atlash) : (i += 1) {
gralpha[k] = 255;
gralpha[k + 1] = atlas[i];
k += 2;
}
}
alloc.free(atlas);
atlas = gralpha;
return TextureRaw{ .pixels = atlas, .width = atlasw, .height = atlash };
}
/// Returns index position for a unicode char on font
pub fn glyphIndex(self: Font, codepoint: i32) i32 {
var index: i32 = char_fallback;
var i: usize = 0;
while (i < self.glyphs.len) : (i += 1) {
if (self.glyphs[i].codepoint == codepoint) return @intCast(i32, i);
}
return index;
}
// source: https://github.com/raysan5/raylib/blob/cba412cc313e4f95eafb3fba9303400e65c98984/src/text.c#L1071
/// Measure string size for Font
pub fn measure(self: Font, string: []const u8, pixelsize: f32, spacing: f32) m.Vec2f {
const len = @intCast(i32, string.len);
var tlen: i32 = 0;
var lenc: i32 = 0;
var swi: f32 = 0;
var tswi: f32 = 0;
var shi: f32 = @intToFloat(f32, self.base_size);
var scale_factor: f32 = pixelsize / shi;
var letter: i32 = 0;
var index: usize = 0;
var i: usize = 0;
while (i < len) : (i += 1) {
lenc += 1;
var next: i32 = 0;
letter = utf8.nextCodepoint(string[i..], &next);
index = @intCast(usize, self.glyphIndex(letter));
// NOTE: normally we exit the decoding sequence as soon as a bad byte is found (and return 0x3f)
// but we need to draw all of the bad bytes using the '?' symbol so to not skip any we set next = 1
if (letter == 0x3f) next = 1;
i += @intCast(usize, next - 1);
if (letter == '\n') {
if (self.glyphs[index].advance != 0) {
swi += @intToFloat(f32, self.glyphs[index].advance);
} else swi += self.rects[index].size.x + @intToFloat(f32, self.glyphs[index].offx);
} else {
if (tswi < swi) tswi = swi;
lenc = 0;
tswi = 0;
shi = @intToFloat(f32, self.base_size) * 1.5;
}
if (tlen < lenc) tlen = lenc;
}
if (tswi < swi) tswi = swi;
return m.Vec2f{
.x = tswi * scale_factor + @intToFloat(f32, tlen - 1) * spacing,
.y = shi * scale_factor,
};
}
pub fn createFromTTF(alloc: *std.mem.Allocator, filepath: []const u8, chars: ?[]const i32, pixelsize: i32) Error!Font {
var mem = try fs.readFile(alloc, filepath);
defer alloc.free(mem);
return createFromTTFMemory(alloc, mem, chars, pixelsize);
}
pub fn createFromTTFMemory(alloc: *std.mem.Allocator, mem: []const u8, chars: ?[]const i32, pixelsize: i32) Error!Font {
var result = Font{};
result.alloc = alloc;
result.base_size = pixelsize;
result.glyph_padding = 0;
result.glyphs = try loadFontData(alloc, mem, result.base_size, chars);
result.glyph_padding = char_padding;
var atlas = try result.genImageAtlas();
result.texture.width = atlas.width;
result.texture.height = atlas.height;
gl.texturesGen(1, @ptrCast([*]u32, &result.texture.id));
gl.textureBind(gl.TextureType.t2D, result.texture.id);
defer gl.textureBind(gl.TextureType.t2D, 0);
gl.textureTexParameteri(gl.TextureType.t2D, gl.TextureParamaterType.min_filter, gl.TextureParamater.filter_nearest);
gl.textureTexParameteri(gl.TextureType.t2D, gl.TextureParamaterType.mag_filter, gl.TextureParamater.filter_linear);
gl.textureTexParameteri(gl.TextureType.t2D, gl.TextureParamaterType.wrap_s, gl.TextureParamater.wrap_repeat);
gl.textureTexParameteri(gl.TextureType.t2D, gl.TextureParamaterType.wrap_t, gl.TextureParamater.wrap_repeat);
if (atlas.pixels) |pixels| {
gl.textureTexImage2D(gl.TextureType.t2D, 0, gl.TextureFormat.rg8, result.texture.width, result.texture.height, 0, gl.TextureFormat.rg, u8, @ptrCast(?*c_void, pixels));
// source: https://github.com/raysan5/raylib/blob/cba412cc313e4f95eafb3fba9303400e65c98984/src/rlgl.h#L2447
const swizzle = comptime [_]u32{ c.GL_RED, c.GL_RED, c.GL_RED, c.GL_GREEN };
c.glTexParameteriv(c.GL_TEXTURE_2D, c.GL_TEXTURE_SWIZZLE_RGBA, @ptrCast([*c]const i32, &swizzle));
gl.texturesGenMipmap(gl.TextureType.t2D);
alloc.free(pixels);
}
return result;
}
pub fn destroy(self: *Font) void {
var i: usize = 0;
while (i < self.glyphs.len) : (i += 1) {
if (self.glyphs[i].raw.pixels) |px|
self.alloc.free(px);
}
self.alloc.free(self.rects);
self.alloc.free(self.glyphs);
self.texture.destroy();
}
}; | src/core/renderer.zig |
const aoc = @import("../aoc.zig");
const std = @import("std");
const EffectTimer = u8;
const HitPoints = u8;
const Mana = u16;
const TurnResult = enum {
CONTINUE, WIN, FAIL,
};
const InstantSpell = struct { cost: Mana, heal: HitPoints, damage: HitPoints };
const Spell = union(enum) {
Instant: InstantSpell,
Shield: void,
Poison: void,
Recharge: void,
};
const Player = struct {
const shield_effect: HitPoints = 7;
const recharge_effect: Mana = 101;
const shield_cost: Mana = 113;
const poison_cost: Mana = 173;
const rechage_cost: Mana = 229;
const shield_time: EffectTimer = 6;
const poison_time: EffectTimer = 6;
const recharge_time: EffectTimer = 5;
hp: HitPoints = 50,
mana_remaining: Mana = 500,
mana_used: Mana = 0,
shield_effect_timer: EffectTimer = 0,
recharge_effect_timer: EffectTimer = 0,
armor: HitPoints = undefined,
fn damage(self: *Player, dmg: HitPoints) bool {
if (dmg >= self.hp) {
return true;
}
self.hp -= dmg;
return false;
}
fn tick(self: *Player) void {
if (self.shield_effect_timer != 0) {
self.armor = shield_effect;
self.shield_effect_timer -= 1;
}
else {
self.armor = 0;
}
if (self.recharge_effect_timer != 0) {
self.mana_remaining += recharge_effect;
self.recharge_effect_timer -= 1;
}
}
fn castSpell(self: *Player, spell: Spell, boss: *Boss) TurnResult {
return switch (spell) {
.Instant => |s| self.applyInstantSpell(s, boss),
.Shield => self.applyShieldEffect(),
.Poison => self.applyPoisonEffect(boss),
.Recharge => self.applyRechargeEffect(),
};
}
fn applyInstantSpell(self: *Player, spell: InstantSpell, boss: *Boss) TurnResult {
if (!self.consumeMana(spell.cost)) {
return .FAIL;
}
if (boss.damage(spell.damage)) {
return .WIN;
}
self.hp += spell.heal;
return .CONTINUE;
}
fn applyShieldEffect(self: *Player) TurnResult {
if (self.shield_effect_timer != 0 or !self.consumeMana(shield_cost)) {
return .FAIL;
}
self.shield_effect_timer = shield_time;
return .CONTINUE;
}
fn applyPoisonEffect(self: *Player, boss: *Boss) TurnResult {
if (boss.poison_effect_timer != 0 or !self.consumeMana(poison_cost)) {
return .FAIL;
}
boss.poison_effect_timer = poison_time;
return .CONTINUE;
}
fn applyRechargeEffect(self: *Player) TurnResult {
if (self.recharge_effect_timer != 0 or !self.consumeMana(rechage_cost)) {
return .FAIL;
}
self.recharge_effect_timer = recharge_time;
return .CONTINUE;
}
fn consumeMana(self: *Player, mana: Mana) bool {
if (mana > self.mana_remaining) {
return false;
}
self.mana_remaining -= mana;
self.mana_used += mana;
return true;
}
};
const Boss = struct {
const damage_effect: HitPoints = 3;
hp: HitPoints,
atk: HitPoints,
poison_effect_timer: EffectTimer = 0,
fn damage(self: *Boss, dmg: HitPoints) bool {
if (dmg >= self.hp) {
return true;
}
self.hp -= dmg;
return false;
}
fn tick(self: *Boss) bool {
if (self.poison_effect_timer != 0) {
if (self.damage(damage_effect)) {
return true;
}
self.poison_effect_timer -= 1;
}
return false;
}
fn attack(self: *Boss, player: *Player) bool {
return player.damage(self.atk - player.armor);
}
};
const spells = [_]Spell {
.{ .Instant = .{ .cost = 53, .heal = 0, .damage = 4 } },
.{ .Instant = .{ .cost = 73, .heal = 2, .damage = 2 } },
.{ .Shield = {} },
.{ .Poison = {} },
.{ .Recharge = {} },
};
pub fn run(problem: *aoc.Problem) !aoc.Solution {
var tokens = std.mem.tokenize(u8, problem.input, ": \n");
_ = tokens.next().?; _ = tokens.next().?;
const boss_hp = try std.fmt.parseInt(HitPoints, tokens.next().?, 10);
_ = tokens.next().?;
const boss_atk = try std.fmt.parseInt(HitPoints, tokens.next().?, 10);
const res1 = blk: {
var player = Player {};
var boss = Boss { .hp = boss_hp, .atk = boss_atk };
break :blk getMinManaUsed(&player, &boss, std.math.maxInt(Mana), 0);
};
const res2 = blk: {
var player = Player {};
var boss = Boss { .hp = boss_hp, .atk = boss_atk };
break :blk getMinManaUsed(&player, &boss, std.math.maxInt(Mana), 1);
};
return problem.solution(res1, res2);
}
fn getMinManaUsed(player: *Player, boss: *Boss, max_mana: Mana, player_damage_per_turn: HitPoints) Mana {
var min_mana = max_mana;
if (player.damage(player_damage_per_turn)) {
return min_mana;
}
player.tick();
if (boss.tick()) {
return player.mana_used;
}
for (spells) |spell| {
var new_player = player.*;
var new_boss = boss.*;
const result = new_player.castSpell(spell, &new_boss);
if (new_player.mana_used >= min_mana or result == .FAIL) {
continue;
}
if (result == .WIN) {
min_mana = new_player.mana_used;
continue;
}
new_player.tick();
if (new_boss.tick()) {
min_mana = new_player.mana_used;
continue;
}
if (new_boss.attack(&new_player)) {
continue;
}
min_mana = getMinManaUsed(&new_player, &new_boss, min_mana, player_damage_per_turn);
}
return min_mana;
} | src/main/zig/2015/day22.zig |
const std = @import("std.zig");
const tokenizer = @import("zig/tokenizer.zig");
pub const Token = tokenizer.Token;
pub const Tokenizer = tokenizer.Tokenizer;
pub const parse = @import("zig/parse.zig").parse;
pub const parseStringLiteral = @import("zig/string_literal.zig").parse;
pub const render = @import("zig/render.zig").render;
pub const renderStringLiteral = @import("zig/string_literal.zig").render;
pub const ast = @import("zig/ast.zig");
pub const system = @import("zig/system.zig");
pub const CrossTarget = @import("zig/cross_target.zig").CrossTarget;
pub const SrcHash = [16]u8;
/// If the source is small enough, it is used directly as the hash.
/// If it is long, blake3 hash is computed.
pub fn hashSrc(src: []const u8) SrcHash {
var out: SrcHash = undefined;
if (src.len <= SrcHash.len) {
std.mem.copy(u8, &out, src);
std.mem.set(u8, out[src.len..], 0);
} else {
std.crypto.Blake3.hash(src, &out);
}
return out;
}
pub fn findLineColumn(source: []const u8, byte_offset: usize) struct { line: usize, column: usize } {
var line: usize = 0;
var column: usize = 0;
for (source[0..byte_offset]) |byte| {
switch (byte) {
'\n' => {
line += 1;
column = 0;
},
else => {
column += 1;
},
}
}
return .{ .line = line, .column = column };
}
pub fn lineDelta(source: []const u8, start: usize, end: usize) isize {
var line: isize = 0;
if (end >= start) {
for (source[start..end]) |byte| switch (byte) {
'\n' => line += 1,
else => continue,
};
} else {
for (source[end..start]) |byte| switch (byte) {
'\n' => line -= 1,
else => continue,
};
}
return line;
}
/// Returns the standard file system basename of a binary generated by the Zig compiler.
pub fn binNameAlloc(
allocator: *std.mem.Allocator,
root_name: []const u8,
target: std.Target,
output_mode: std.builtin.OutputMode,
link_mode: ?std.builtin.LinkMode,
) error{OutOfMemory}![]u8 {
switch (output_mode) {
.Exe => return std.fmt.allocPrint(allocator, "{}{}", .{ root_name, target.exeFileExt() }),
.Lib => {
const suffix = switch (link_mode orelse .Static) {
.Static => target.staticLibSuffix(),
.Dynamic => target.dynamicLibSuffix(),
};
return std.fmt.allocPrint(allocator, "{}{}{}", .{ target.libPrefix(), root_name, suffix });
},
.Obj => return std.fmt.allocPrint(allocator, "{}{}", .{ root_name, target.oFileExt() }),
}
}
test "" {
@import("std").meta.refAllDecls(@This());
} | lib/std/zig.zig |
const std = @import("std");
pub const c = @import("c.zig");
pub const content = @import("content.zig");
pub const coordinates = @import("coordinates.zig");
pub const events = @import("events.zig");
pub const frame_timer = @import("frame_timer.zig");
pub const gfx = @import("gfx.zig");
pub const gltf = @import("gltf.zig");
pub const math = @import("math.zig");
pub const states = @import("states.zig");
pub const tiled = @import("tiled.zig");
pub const cube = @import("defaults/cube.zig");
pub const flat = @import("defaults/flat.zig");
//;
test "" {
_ = c;
_ = content;
_ = coordinates;
_ = events;
_ = frame_timer;
_ = gfx;
_ = gltf;
_ = math;
_ = states;
_ = tiled;
_ = cube;
_ = flat;
}
test "gfx main" {
const alloc = std.testing.allocator;
var ctx: gfx.Context = undefined;
try ctx.init(.{
.window_width = 800,
.window_height = 600,
});
defer ctx.deinit();
ctx.installEventHandler(alloc);
const evs = &ctx.event_handler.?;
var img = try gfx.Image.initFromMemory(alloc, content.images.mahou);
defer img.deinit();
var tex = gfx.Texture.initImage(img);
defer tex.deinit();
//;
var defaults = try flat.DrawDefaults.init(alloc);
defer defaults.deinit();
var drawer = try flat.Drawer2d.init(alloc, .{
.spritebatch_size = 500,
.circle_resolution = 50,
});
defer drawer.deinit();
//; 3d
var prog3d = try cube.Program3d.initDefault(alloc, null, null);
defer prog3d.deinit();
//;
while (c.glfwWindowShouldClose(ctx.window) == c.GLFW_FALSE) {
evs.poll();
for (evs.key_events.items) |ev| {
if (ev.key == .Space) {
for (evs.gamepads) |gpd| {
if (gpd.is_connected) {
std.log.warn("{}\n", .{gpd});
}
}
}
}
for (evs.joystick_events.items) |ev| {
std.log.warn("{}\n", .{ev});
}
c.glClear(c.GL_COLOR_BUFFER_BIT | c.GL_DEPTH_BUFFER_BIT);
// {
// var sprites = drawer.bindSpritebatch(false, .{
// .program = &defaults.spritebatch_program,
// .diffuse = &defaults.white_texture,
// .canvas_width = 800,
// .canvas_height = 600,
// });
// defer sprites.unbind();
// sprites.rectangle(0., 0., 800., 600.);
//
// // sprites.rectangle(10., 10., 410., 310.);
// // try sprites.pushCoord(.{ .Shear = math.Vec2.init(1., 0.) });
// // try sprites.pushCoord(.{ .Scale = math.Vec2.init(1., 0.5) });
// // sprites.rectangle(0., 0., 400., 300.);
// // try sprites.popCoord();
// // try sprites.popCoord();
//
// sprites.sprite_color = math.Color.initRgba(0., 0., 0., 1.);
// sprites.print(defaults.ibm_font, "hello world \x01\x02\x03");
// }
c.glfwSwapBuffers(ctx.window);
}
} | src/main.zig |
const std = @import("std");
const expect = @import("std").testing.expect;
const expectEqual = @import("std").testing.expectEqual;
const math = @import("std").math;
const Vec3 = struct {
x: f32,
y: f32,
z: f32,
pub fn init(x: f32, y: f32, z: f32) Vec3 {
return Vec3{
.x = x,
.y = y,
.z = z,
};
}
pub fn add(v1: Vec3, v2: Vec3) Vec3 {
return Vec3{ .x = v1.x + v2.x, .y = v1.y + v2.y, .z = v1.z + v2.z };
}
pub fn sub(v1: Vec3, v2: Vec3) Vec3 {
return Vec3{ .x = v1.x - v2.x, .y = v1.y - v2.y, .z = v1.z - v2.z };
}
pub fn mul(v1: Vec3, v2: Vec3) Vec3 {
return Vec3{ .x = v1.x * v2.x, .y = v1.y * v2.y, .z = v1.z * v2.z };
}
pub fn div(v1: Vec3, v2: Vec3) Vec3 {
return Vec3{ .x = v1.x / v2.x, .y = v1.y / v2.y, .z = v1.z / v2.z };
}
pub fn len(v1: Vec3) f32 {
return math.sqrt(math.exp2(v1.x) + math.exp2(v1.y) + math.exp2(v1.z));
}
};
pub const Vec4 = struct {
x: f32,
y: f32,
z: f32,
w: f32,
pub fn init(x: f32, y: f32, z: f32, w: f32) Vec4 {
return Vec4{ .x = x, .y = y, .z = z, .w = w };
}
pub fn add(v1: Vec4, v2: Vec4) Vec4 {
return Vec4{ .x = v1.x + v2.x, .y = v1.y + v2.y, .z = v1.z + v2.z, .w = v1.w + v2.w };
}
pub fn sub(v1: Vec4, v2: Vec4) Vec4 {
return Vec4{ .x = v1.x - v2.x, .y = v1.y - v2.y, .z = v1.z - v2.z, .w = v1.w - v2.w };
}
pub fn mul(v1: Vec4, v2: Vec4) Vec4 {
return Vec4{ .x = v1.x * v2.x, .y = v1.y * v2.y, .z = v1.z * v2.z, .w = v1.w * v2.w };
}
pub fn div(v1: Vec4, v2: Vec4) Vec4 {
return Vec4{ .x = v1.x / v2.x, .y = v1.y / v2.y, .z = v1.z / v2.z, .w = v1.w / v2.w };
}
pub fn len(v1: Vec4) f32 {
return math.sqrt(math.exp2(v1.x) + math.exp2(v1.y) + math.exp2(v1.z) + math.exp2(v1.w));
}
};
// Matrix struct is based on https://github.com/andrewrk/tetris/blob/master/src/math3d.zig
//
pub const Mat44 = struct {
mat: [4][4]f32,
pub fn mulVec4(m: Mat44, v: Vec4) Vec4 {
return Vec4.init(m.mat[0][0] * v.x + m.mat[0][1] * v.y + m.mat[0][2] * v.z + m.mat[0][3] * v.w, m.mat[1][0] * v.x + m.mat[1][1] * v.y + m.mat[1][2] * v.z + m.mat[1][3] * v.w, m.mat[2][0] * v.x + m.mat[2][1] * v.y + m.mat[2][2] * v.z + m.mat[2][3] * v.w, m.mat[3][0] * v.x + m.mat[3][1] * v.y + m.mat[3][2] * v.z + m.mat[3][3] * v.w);
}
pub fn mulScal(m: Mat44, s: f32) Mat44 {
return Mat44{ .mat = [_][4]f32{
[_]f32{
m.mat[0][0] * s,
m.mat[0][1] * s,
m.mat[0][2] * s,
m.mat[0][3] * s,
},
[_]f32{
m.mat[1][0] * s,
m.mat[1][1] * s,
m.mat[1][2] * s,
m.mat[1][3] * s,
},
[_]f32{
m.mat[2][0] * s,
m.mat[2][1] * s,
m.mat[2][2] * s,
m.mat[2][3] * s,
},
[_]f32{
m.mat[3][0] * s,
m.mat[3][1] * s,
m.mat[3][2] * s,
m.mat[3][3] * s,
},
} };
}
pub fn add(m: Mat44, other: Mat44) Mat44 {
return Mat44{ .mat = [_][4]f32{
[_]f32{
m.mat[0][0] + other.mat[0][0],
m.mat[0][1] + other.mat[0][1],
m.mat[0][2] + other.mat[0][2],
m.mat[0][3] + other.mat[0][3],
},
[_]f32{
m.mat[1][0] + other.mat[1][0],
m.mat[1][1] + other.mat[1][1],
m.mat[1][2] + other.mat[1][2],
m.mat[1][3] + other.mat[1][3],
},
[_]f32{
m.mat[2][0] + other.mat[2][0],
m.mat[2][1] + other.mat[2][1],
m.mat[2][2] + other.mat[2][2],
m.mat[2][3] + other.mat[2][3],
},
[_]f32{
m.mat[3][0] + other.mat[3][0],
m.mat[3][1] + other.mat[3][1],
m.mat[3][2] + other.mat[3][2],
m.mat[3][3] + other.mat[3][3],
},
} };
}
pub fn mul(m: Mat44, other: Mat44) Mat44 {
return Mat44{ .mat = [_][4]f32{
[_]f32{
m.mat[0][0] * other.mat[0][0] + m.mat[0][1] * other.mat[1][0] + m.mat[0][2] * other.mat[2][0] + m.mat[0][3] * other.mat[3][0],
m.mat[0][0] * other.mat[0][1] + m.mat[0][1] * other.mat[1][1] + m.mat[0][2] * other.mat[2][1] + m.mat[0][3] * other.mat[3][1],
m.mat[0][0] * other.mat[0][2] + m.mat[0][1] * other.mat[1][2] + m.mat[0][2] * other.mat[2][2] + m.mat[0][3] * other.mat[3][2],
m.mat[0][0] * other.mat[0][3] + m.mat[0][1] * other.mat[1][3] + m.mat[0][2] * other.mat[2][3] + m.mat[0][3] * other.mat[3][3],
},
[_]f32{
m.mat[1][0] * other.mat[0][0] + m.mat[1][1] * other.mat[1][0] + m.mat[1][2] * other.mat[2][0] + m.mat[1][3] * other.mat[3][0],
m.mat[1][0] * other.mat[0][1] + m.mat[1][1] * other.mat[1][1] + m.mat[1][2] * other.mat[2][1] + m.mat[1][3] * other.mat[3][1],
m.mat[1][0] * other.mat[0][2] + m.mat[1][1] * other.mat[1][2] + m.mat[1][2] * other.mat[2][2] + m.mat[1][3] * other.mat[3][2],
m.mat[1][0] * other.mat[0][3] + m.mat[1][1] * other.mat[1][3] + m.mat[1][2] * other.mat[2][3] + m.mat[1][3] * other.mat[3][3],
},
[_]f32{
m.mat[2][0] * other.mat[0][0] + m.mat[2][1] * other.mat[1][0] + m.mat[2][2] * other.mat[2][0] + m.mat[2][3] * other.mat[3][0],
m.mat[2][0] * other.mat[0][1] + m.mat[2][1] * other.mat[1][1] + m.mat[2][2] * other.mat[2][1] + m.mat[2][3] * other.mat[3][1],
m.mat[2][0] * other.mat[0][2] + m.mat[2][1] * other.mat[1][2] + m.mat[2][2] * other.mat[2][2] + m.mat[2][3] * other.mat[3][2],
m.mat[2][0] * other.mat[0][3] + m.mat[2][1] * other.mat[1][3] + m.mat[2][2] * other.mat[2][3] + m.mat[2][3] * other.mat[3][3],
},
[_]f32{
m.mat[3][0] * other.mat[0][0] + m.mat[3][1] * other.mat[1][0] + m.mat[3][2] * other.mat[2][0] + m.mat[3][3] * other.mat[3][0],
m.mat[3][0] * other.mat[0][1] + m.mat[3][1] * other.mat[1][1] + m.mat[3][2] * other.mat[2][1] + m.mat[3][3] * other.mat[3][1],
m.mat[3][0] * other.mat[0][2] + m.mat[3][1] * other.mat[1][2] + m.mat[3][2] * other.mat[2][2] + m.mat[3][3] * other.mat[3][2],
m.mat[3][0] * other.mat[0][3] + m.mat[3][1] * other.mat[1][3] + m.mat[3][2] * other.mat[2][3] + m.mat[3][3] * other.mat[3][3],
},
} };
}
};
//-----------------------some tests.-------------------------
test "Adding 2 vec3 " {
const v1 = Vec3{
.x = 1.0,
.y = 2.0,
.z = 3.0,
};
const v2 = Vec3{
.x = 4.0,
.y = 5.0,
.z = 6.0,
};
const expected = Vec3{
.x = 5.0,
.y = 7.0,
.z = 9.0,
};
var ans = v1.add(v2);
try expect(expected.x == ans.x);
try expect(expected.y == ans.y);
try expect(expected.z == ans.z);
}
test "sub 2 vec3 " {
const v1 = Vec3{
.x = 1.0,
.y = 2.0,
.z = 3.0,
};
const v2 = Vec3{
.x = 4.0,
.y = 5.0,
.z = 6.0,
};
const expected = Vec3{
.x = -3.0,
.y = -3.0,
.z = -3.0,
};
var ans = v1.sub(v2);
try expect(expected.x == ans.x);
try expect(expected.y == ans.y);
try expect(expected.z == ans.z);
}
test "mul 2 vec3 " {
const v1 = Vec3{
.x = 1.0,
.y = 2.0,
.z = 3.0,
};
const v2 = Vec3{
.x = 4.0,
.y = 5.0,
.z = 6.0,
};
const expected = Vec3{
.x = 4.0,
.y = 10.0,
.z = 18.0,
};
var ans = v1.mul(v2);
try expect(expected.x == ans.x);
try expect(expected.y == ans.y);
try expect(expected.z == ans.z);
}
test "div 2 vec3 " {
const v1 = Vec3{
.x = 1.0,
.y = 2.0,
.z = 3.0,
};
const v2 = Vec3{
.x = 4.0,
.y = 5.0,
.z = 6.0,
};
const expected = Vec3{
.x = 4.0,
.y = 2.5,
.z = 2.0,
};
var ans = v2.div(v1);
try expect(expected.x == ans.x);
try expect(expected.y == ans.y);
try expect(expected.z == ans.z);
}
test "Adding 2 Vec4 " {
const v1 = Vec4{ .x = 1.0, .y = 2.0, .z = 3.0, .w = 4.0 };
const v2 = Vec4{ .x = 4.0, .y = 5.0, .z = 6.0, .w = 7.0 };
const expected = Vec4{ .x = 5.0, .y = 7.0, .z = 9.0, .w = 11.0 };
var ans = v1.add(v2);
try expect(expected.x == ans.x);
try expect(expected.y == ans.y);
try expect(expected.z == ans.z);
try expect(expected.w == ans.w);
}
test "sub 2 Vec4 " {
const v1 = Vec4{ .x = 1.0, .y = 2.0, .z = 3.0, .w = 4.0 };
const v2 = Vec4{ .x = 4.0, .y = 5.0, .z = 6.0, .w = 7.0 };
const expected = Vec4{
.x = -3.0,
.y = -3.0,
.z = -3.0,
.w = -3.0,
};
var ans = v1.sub(v2);
try expect(expected.x == ans.x);
try expect(expected.y == ans.y);
try expect(expected.z == ans.z);
try expect(expected.w == ans.w);
}
test "mul 2 Vec4 " {
const v1 = Vec4{
.x = 1.0,
.y = 2.0,
.z = 3.0,
.w = 4.0,
};
const v2 = Vec4{
.x = 4.0,
.y = 5.0,
.z = 6.0,
.w = 7.0,
};
const expected = Vec4{
.x = 4.0,
.y = 10.0,
.z = 18.0,
.w = 28.0,
};
var ans = v1.mul(v2);
try expect(expected.x == ans.x);
try expect(expected.y == ans.y);
try expect(expected.z == ans.z);
try expect(expected.w == ans.w);
}
test "div 2 Vec4 " {
const v1 = Vec4{ .x = 1.0, .y = 2.0, .z = 3.0, .w = 4.0 };
const v2 = Vec4{ .x = 4.0, .y = 5.0, .z = 6.0, .w = 8.0 };
const expected = Vec4{
.x = 4.0,
.y = 2.5,
.z = 2.0,
.w = 2.0,
};
var ans = v2.div(v1);
try expect(expected.x == ans.x);
try expect(expected.y == ans.y);
try expect(expected.z == ans.z);
try expect(expected.w == ans.w);
}
test "mul Mat44 Vec4 " {
const v1 = Vec4{ .x = 1.0, .y = 2.0, .z = 3.0, .w = 4.0 };
const mat = Mat44{ .mat = [_][4]f32{ [_]f32{ 1.0, 2.0, 3.0, 4.0 }, [_]f32{ 5.0, 6.0, 7.0, 8.0 }, [_]f32{ 9.0, 10.0, 11.0, 12.0 }, [_]f32{ 13.0, 14.0, 15.0, 16.0 } } };
const expected = Vec4{ .x = 30.0, .y = 70.0, .z = 110.0, .w = 150.0 };
const ans = mat.mulVec4(v1);
try expect(expected.x == ans.x);
try expect(expected.y == ans.y);
try expect(expected.z == ans.z);
try expect(expected.w == ans.w);
}
test "add 2 mat4" {
const mat1 = Mat44{ .mat = [_][4]f32{ [_]f32{ 1.0, 2.0, 3.0, 4.0 }, [_]f32{ 5.0, 6.0, 7.0, 8.0 }, [_]f32{ 9.0, 10.0, 11.0, 12.0 }, [_]f32{ 13.0, 14.0, 15.0, 16.0 } } };
const mat2 = Mat44{ .mat = [_][4]f32{ [_]f32{ 1.0, 2.0, 3.0, 4.0 }, [_]f32{ 5.0, 6.0, 7.0, 8.0 }, [_]f32{ 9.0, 10.0, 11.0, 12.0 }, [_]f32{ 13.0, 14.0, 15.0, 16.0 } } };
const expected = Mat44{ .mat = [_][4]f32{ [_]f32{ 2.0, 4.0, 6.0, 8.0 }, [_]f32{ 10.0, 12.0, 14.0, 16.0 }, [_]f32{ 18.0, 20.0, 22.0, 24.0 }, [_]f32{ 26.0, 28.0, 30.0, 32.0 } } };
const ans = mat1.add(mat2);
for (expected.mat) |row, i| {
for (row) |col, n| {
try expect(col == ans.mat[i][n]);
}
}
}
test "mul 2 mat4" {
const mat1 = Mat44{ .mat = [_][4]f32{ [_]f32{ 1.0, 2.0, 3.0, 4.0 }, [_]f32{ 5.0, 6.0, 7.0, 8.0 }, [_]f32{ 9.0, 10.0, 11.0, 12.0 }, [_]f32{ 13.0, 14.0, 15.0, 16.0 } } };
const mat2 = Mat44{ .mat = [_][4]f32{ [_]f32{ 1.0, 2.0, 3.0, 4.0 }, [_]f32{ 5.0, 6.0, 7.0, 8.0 }, [_]f32{ 9.0, 10.0, 11.0, 12.0 }, [_]f32{ 13.0, 14.0, 15.0, 16.0 } } };
const expected = Mat44{ .mat = [_][4]f32{ [_]f32{
90.0,
100.0,
110.0,
120.0,
}, [_]f32{ 202.0, 228.0, 254.0, 280.0 }, [_]f32{ 314.0, 356.0, 398.0, 440.0 }, [_]f32{ 426.0, 484.0, 542.0, 600.0 } } };
const ans = mat1.mul(mat2);
for (expected.mat) |row, i| {
for (row) |col, n| {
try expectEqual(col, ans.mat[i][n]);
}
}
}
test "mul mat4 & scalear" {
const mat1 = Mat44{ .mat = [_][4]f32{ [_]f32{ 1.0, 2.0, 3.0, 4.0 }, [_]f32{ 5.0, 6.0, 7.0, 8.0 }, [_]f32{ 9.0, 10.0, 11.0, 12.0 }, [_]f32{ 13.0, 14.0, 15.0, 16.0 } } };
const scal: f32 = 2.0;
const expected = Mat44{ .mat = [_][4]f32{ [_]f32{ 2.0 * 1.0, 2.0 * 2.0, 2.0 * 3.0, 2.0 * 4.0 }, [_]f32{ 2.0 * 5.0, 2.0 * 6.0, 2.0 * 7.0, 2.0 * 8.0 }, [_]f32{ 2.0 * 9.0, 2.0 * 10.0, 2.0 * 11.0, 2.0 * 12.0 }, [_]f32{ 2.0 * 13.0, 2.0 * 14.0, 2.0 * 15.0, 2.0 * 16.0 } } };
const ans = mat1.mulScal(scal);
for (expected.mat) |row, i| {
for (row) |col, n| {
try expectEqual(col, ans.mat[i][n]);
}
}
}
test "lenght of a vec4" {
var v1 = Vec4.init(5.0, 0, 0, 0);
var expected: f32 = 5.0;
var ans = v1.len();
try expectEqual(ans, ans);
v1 = Vec4.init(2, 2, 2, 2);
expected = 4.0;
ans = v1.len();
try expectEqual(ans, ans);
}
test "lenght of a vec3" {
var v1 = Vec3.init(5.0, 0, 0);
var expected: f32 = 5.0;
var ans = v1.len();
try expectEqual(ans, ans);
v1 = Vec3.init(2, 2, 1);
expected = 3.0;
ans = v1.len();
try expectEqual(ans, ans);
}
pub fn main() !void {
const stdout = std.io.getStdOut().writer();
try stdout.print("Hello, {s}!\n", .{"world"});
} | src/main.zig |
const std = @import("std");
const tools = @import("tools");
const with_trace = false;
const assert = std.debug.assert;
fn trace(comptime fmt: []const u8, args: anytype) void {
if (with_trace) std.debug.print(fmt, args);
}
const Chemical = []const u8;
const Chemicals = std.ArrayList(Chemical);
const Reaction = struct {
const Comp = struct {
chemical: usize,
quantity: u64,
};
reactives: []Comp,
product: Comp,
};
fn parseChemical(segment: []const u8, chemicals: *Chemicals) !Reaction.Comp {
var comp: Reaction.Comp = undefined;
var it = std.mem.tokenize(u8, segment, " ");
if (it.next()) |q| {
comp.quantity = try std.fmt.parseInt(u64, q, 10);
}
if (it.next()) |name| {
var found = false;
for (chemicals.items) |c, i| {
if (std.mem.eql(u8, c, name)) {
comp.chemical = i;
found = true;
break;
}
}
if (!found) {
try chemicals.append(name);
comp.chemical = chemicals.items.len - 1;
}
} else {
unreachable;
}
return comp;
}
fn parseline(line: []const u8, chemicals: *Chemicals, reactions: []?Reaction, allocator: std.mem.Allocator) !void {
const sep = std.mem.indexOf(u8, line, " => ").?;
var reaction: Reaction = undefined;
reaction.product = try parseChemical(line[sep + 4 ..], chemicals);
var reactives_count = blk: {
var count: u32 = 0;
var it = std.mem.tokenize(u8, line[0..sep], "\n,");
while (it.next()) |_| {
count += 1;
}
break :blk count;
};
reaction.reactives = try allocator.alloc(Reaction.Comp, reactives_count);
{
var i: u32 = 0;
var it = std.mem.tokenize(u8, line[0..sep], "\n,");
while (it.next()) |segment| {
reaction.reactives[i] = try parseChemical(segment, chemicals);
i += 1;
}
}
assert(reactions[reaction.product.chemical] == null);
reactions[reaction.product.chemical] = reaction;
}
pub fn run(input: []const u8, allocator: std.mem.Allocator) ![2][]const u8 {
var arena = std.heap.ArenaAllocator.init(allocator);
defer arena.deinit();
var grid = try allocator.alloc(u8, 1000 * 1000);
defer allocator.free(grid);
std.mem.set(u8, grid, 0);
var chemicals = Chemicals.init(arena.allocator());
var reactions: [1000]?Reaction = [1]?Reaction{null} ** 1000;
try chemicals.append("ORE");
try chemicals.append("FUEL");
{
var it = std.mem.split(u8, input, "\n");
while (it.next()) |line_full| {
const line = std.mem.trim(u8, line_full, " \n\r\t");
if (line.len == 0)
continue;
try parseline(line, &chemicals, &reactions, arena.allocator());
}
}
var reactions_count: u32 = 0;
for (reactions) |reacmaybe| {
if (reacmaybe) |reac| {
reactions_count += 1;
trace("{}: ", .{chemicals.items[reac.product.chemical]});
for (reac.reactives) |it| {
trace("{} {}, ", .{ it.quantity, chemicals.items[it.chemical] });
}
trace("\n", .{});
}
}
trace("chemicals={} reactions={} \n", .{ chemicals.items.len, reactions_count });
var chemicals_to_fuel = try allocator.alloc(u32, chemicals.items.len);
defer allocator.free(chemicals_to_fuel);
{
std.mem.set(u32, chemicals_to_fuel, 0);
chemicals_to_fuel[1] = 0;
var changed = true;
while (changed) {
changed = false;
for (reactions) |reacmaybe| {
if (reacmaybe) |reac| {
const d = chemicals_to_fuel[reac.product.chemical] + 1;
for (reac.reactives) |r| {
if (chemicals_to_fuel[r.chemical] < d) {
changed = true;
chemicals_to_fuel[r.chemical] = d;
}
}
}
}
}
for (chemicals_to_fuel) |d, i| {
trace(" {}: {}\n", .{ d, chemicals.items[i] });
}
}
const ore_for_one_fuel = part1: {
const fuel = 1;
var todo = std.ArrayList(Reaction.Comp).init(allocator);
defer todo.deinit();
try todo.append(Reaction.Comp{ .chemical = 1, .quantity = fuel });
while (todo.items.len > 1 or todo.items[0].chemical != 0) {
var next_products = try allocator.alloc(u64, chemicals.items.len);
defer allocator.free(next_products);
std.mem.set(u64, next_products, 0);
const smallest_dist = blk: {
trace("== step: ", .{});
var dist: u32 = 9999;
for (todo.items) |product| {
trace("{} {}, ", .{ product.quantity, chemicals.items[product.chemical] });
const d = chemicals_to_fuel[product.chemical];
if (d < dist) dist = d;
}
trace("\n", .{});
break :blk dist;
};
for (todo.items) |product| {
if (chemicals_to_fuel[product.chemical] == smallest_dist and product.chemical != 0) {
if (reactions[product.chemical]) |r| {
const repeats = ((product.quantity + r.product.quantity - 1) / r.product.quantity);
for (r.reactives) |reac| {
next_products[reac.chemical] += repeats * reac.quantity;
}
trace("{} times [{} {} <- {}]\n", .{ repeats, r.product.quantity, chemicals.items[r.product.chemical], r.reactives });
} else {
unreachable;
}
} else {
next_products[product.chemical] += product.quantity;
}
}
try todo.resize(0);
for (next_products) |q, c| {
if (q > 0) {
try todo.append(Reaction.Comp{ .chemical = c, .quantity = q });
}
}
}
trace("ore={} -> fuel:{}\n", .{ todo.items[0].quantity, fuel });
break :part1 todo.items[0].quantity;
};
const fuel = part2: {
const maxore: u64 = 1000000000000;
var minfuel: u64 = maxore / ore_for_one_fuel;
var maxfuel: u64 = 2 * minfuel;
while (minfuel + 1 < maxfuel) {
var todo = std.ArrayList(Reaction.Comp).init(allocator);
defer todo.deinit();
const fuel = (maxfuel + minfuel) / 2;
try todo.append(Reaction.Comp{ .chemical = 1, .quantity = fuel });
while (todo.items.len > 1 or todo.items[0].chemical != 0) {
var next_products = try allocator.alloc(u64, chemicals.items.len);
defer allocator.free(next_products);
std.mem.set(u64, next_products, 0);
const smallest_dist = blk: {
trace("== step: ", .{});
var dist: u32 = 9999;
for (todo.items) |product| {
trace("{} {}, ", .{ product.quantity, chemicals.items[product.chemical] });
const d = chemicals_to_fuel[product.chemical];
if (d < dist) dist = d;
}
trace("\n", .{});
break :blk dist;
};
for (todo.items) |product| {
if (chemicals_to_fuel[product.chemical] == smallest_dist and product.chemical != 0) {
if (reactions[product.chemical]) |r| {
const repeats = ((product.quantity + r.product.quantity - 1) / r.product.quantity);
for (r.reactives) |reac| {
next_products[reac.chemical] += repeats * reac.quantity;
}
trace("{} times [{} {} <- {}]\n", .{ repeats, r.product.quantity, chemicals.items[r.product.chemical], r.reactives });
} else {
unreachable;
}
} else {
next_products[product.chemical] += product.quantity;
}
}
try todo.resize(0);
for (next_products) |q, c| {
if (q > 0) {
try todo.append(Reaction.Comp{ .chemical = c, .quantity = q });
}
}
}
trace("ore={} -> fuel:{}<{}<{} \n", .{ todo.items[0].quantity, minfuel, fuel, maxfuel });
const over = (todo.items[0].quantity > maxore);
if (over) {
maxfuel = fuel;
} else {
minfuel = fuel;
}
}
break :part2 minfuel;
};
return [_][]const u8{
try std.fmt.allocPrint(allocator, "{}", .{ore_for_one_fuel}),
try std.fmt.allocPrint(allocator, "{}", .{fuel}),
};
}
pub const main = tools.defaultMain("2019/day14.txt", run); | 2019/day14.zig |
const std = @import("std");
const pokemon = @import("index.zig");
const nds = @import("../nds/index.zig");
const utils = @import("../utils/index.zig");
const common = @import("common.zig");
const fun = @import("../../lib/fun-with-zig/src/index.zig");
const mem = std.mem;
const Narc = nds.fs.Narc;
const Nitro = nds.fs.Nitro;
const lu16 = fun.platform.lu16;
const lu32 = fun.platform.lu32;
const lu128 = fun.platform.lu128;
pub const constants = @import("gen5-constants.zig");
pub const BasePokemon = packed struct {
stats: common.Stats,
types: [2]Type,
catch_rate: u8,
evs: [3]u8, // TODO: Figure out if common.EvYield fits in these 3 bytes
items: [3]lu16,
gender_ratio: u8,
egg_cycles: u8,
base_friendship: u8,
growth_rate: common.GrowthRate,
egg_group1: common.EggGroup,
egg_group1_pad: u4,
egg_group2: common.EggGroup,
egg_group2_pad: u4,
abilities: [3]u8,
// TODO: The three fields below are kinda unknown
flee_rate: u8,
form_stats_start: [2]u8,
form_sprites_start: [2]u8,
form_count: u8,
color: common.Color,
color_padding: bool,
base_exp_yield: u8,
height: lu16,
weight: lu16,
// Memory layout
// TMS 01-92, HMS 01-06, TMS 93-95
machine_learnset: lu128,
// TODO: Tutor data only exists in BW2
//special_tutors: lu32,
//driftveil_tutor: lu32,
//lentimas_tutor: lu32,
//humilau_tutor: lu32,
//nacrene_tutor: lu32,
};
/// All party members have this as the base.
/// * If trainer.party_type & 0b10 then there is an additional u16 after the base, which is the held
/// item.
/// * If trainer.party_type & 0b01 then there is an additional 4 * u16 after the base, which are
/// the party members moveset.
pub const PartyMember = packed struct {
iv: u8,
gender: u4,
ability: u4,
level: u8,
padding: u8,
species: lu16,
form: lu16,
};
pub const Trainer = packed struct {
const has_item = 0b10;
const has_moves = 0b01;
party_type: u8,
class: u8,
battle_type: u8, // TODO: This should probably be an enum
party_size: u8,
items: [4]lu16,
ai: lu32,
healer: bool,
healer_padding: u7,
cash: u8,
post_battle_item: lu16,
};
pub const Move = packed struct {
@"type": Type,
effect_category: u8,
category: common.MoveCategory,
power: u8,
accuracy: u8,
pp: u8,
priority: u8,
hits: u8,
min_hits: u4,
max_hits: u4,
crit_chance: u8,
flinch: u8,
effect: lu16,
target_hp: u8,
user_hp: u8,
target: u8,
stats_affected: [3]u8,
stats_affected_magnetude: [3]u8,
stats_affected_chance: [3]u8,
// TODO: Figure out if this is actually how the last fields are layed out.
padding: [2]u8,
flags: lu16,
};
pub const LevelUpMove = packed struct {
move_id: lu16,
level: lu16,
};
pub const Type = enum(u8) {
Normal = 0x00,
Fighting = 0x01,
Flying = 0x02,
Poison = 0x03,
Ground = 0x04,
Rock = 0x05,
Bug = 0x06,
Ghost = 0x07,
Steel = 0x08,
Fire = 0x09,
Water = 0x0A,
Grass = 0x0B,
Electric = 0x0C,
Psychic = 0x0D,
Ice = 0x0E,
Dragon = 0x0F,
Dark = 0x10,
};
pub const WildPokemon = packed struct {
species: lu16,
level_min: u8,
level_max: u8,
};
pub const WildPokemons = packed struct {
rates: [7]u8,
pad: u8,
grass: [12]WildPokemon,
dark_grass: [12]WildPokemon,
rustling_grass: [12]WildPokemon,
surf: [5]WildPokemon,
ripple_surf: [5]WildPokemon,
fishing: [5]WildPokemon,
ripple_fishing: [5]WildPokemon,
};
pub const Game = struct {
const legendaries = common.legendaries;
base: pokemon.BaseGame,
base_stats: *const nds.fs.Narc,
moves: *const nds.fs.Narc,
level_up_moves: *const nds.fs.Narc,
trainers: *const nds.fs.Narc,
parties: *const nds.fs.Narc,
wild_pokemons: *const nds.fs.Narc,
tms1: []lu16,
hms: []lu16,
tms2: []lu16,
pub fn fromRom(rom: nds.Rom) !Game {
const info = try getInfo(rom.header.gamecode);
const hm_tm_prefix_index = mem.indexOf(u8, rom.arm9, constants.hm_tm_prefix) orelse return error.CouldNotFindTmsOrHms;
const hm_tm_index = hm_tm_prefix_index + constants.hm_tm_prefix.len;
const hm_tm_len = (constants.tm_count + constants.hm_count) * @sizeOf(u16);
const hm_tms = @bytesToSlice(lu16, rom.arm9[hm_tm_index..][0..hm_tm_len]);
return Game{
.base = pokemon.BaseGame{ .version = info.version },
.base_stats = try common.getNarc(rom.root, info.base_stats),
.level_up_moves = try common.getNarc(rom.root, info.level_up_moves),
.moves = try common.getNarc(rom.root, info.moves),
.trainers = try common.getNarc(rom.root, info.trainers),
.parties = try common.getNarc(rom.root, info.parties),
.wild_pokemons = try common.getNarc(rom.root, info.wild_pokemons),
.tms1 = hm_tms[0..92],
.hms = hm_tms[92..98],
.tms2 = hm_tms[98..],
};
}
fn getInfo(gamecode: []const u8) !constants.Info {
for (constants.infos) |info| {
//if (!mem.eql(u8, info.game_title, game_title))
// continue;
if (!mem.eql(u8, info.gamecode, gamecode))
continue;
return info;
}
return error.NotGen5Game;
}
}; | src/pokemon/gen5.zig |
pub const mco_state = extern enum(c_int) {
Dead = 0,
Normal = 1,
Running = 2,
Suspended = 3,
_,
};
pub const mco_result = extern enum(c_int) {
Success = 0,
GenericError = 1,
InvalidPointer = 2,
InvalidCoroutine = 3,
NotSuspended = 4,
NotRunning = 5,
MakeContextError = 6,
SwitchcontextError = 7,
NotEnoughSpace = 8,
OutOfMemory = 9,
InvalidArguments = 10,
InvalidOperation = 11,
_,
};
pub const mco_coro = extern struct {
context: ?*c_void,
state: mco_state,
func: *fn (*mco_coro) callconv(.C) void,
prev_co: ?*mco_coro,
user_data: ?*c_void,
allocator_data: ?*c_void,
free_cb: ?fn (?*c_void, ?*c_void) callconv(.C) void,
stack_base: ?*c_void,
stack_size: usize,
storage: ?*u8,
bytes_stored: usize,
storage_size: usize,
asan_prev_stack: ?*c_void,
tsan_prev_fiber: ?*c_void,
tsan_fiber: ?*c_void,
};
pub const mco_desc = extern struct {
func: ?fn (*mco_coro) callconv(.C) void,
user_data: ?*c_void,
malloc_cb: ?fn (usize, ?*c_void) callconv(.C) ?*c_void,
free_cb: ?fn (?*c_void, ?*c_void) callconv(.C) void,
allocator_data: ?*c_void,
storage_size: usize,
coro_size: usize,
stack_size: usize,
};
pub extern "C" fn mco_desc_init(arg_func: fn (*mco_coro) callconv(.C) void, arg_stack_size: usize) mco_desc;
pub extern "C" fn mco_init(arg_co: *mco_coro, arg_desc: *mco_desc) mco_result;
pub extern "C" fn mco_uninit(arg_co: *mco_coro) mco_result;
pub extern "C" fn mco_create(arg_out_co: **mco_coro, arg_desc: *const mco_desc) mco_result;
pub extern "C" fn mco_destroy(arg_co: *mco_coro) mco_result;
pub extern "C" fn mco_resume(arg_co: *mco_coro) mco_result;
pub extern "C" fn mco_yield(arg_co: *mco_coro) mco_result;
pub extern "C" fn mco_status(arg_co: *mco_coro) mco_state;
pub extern "C" fn mco_get_user_data(arg_co: *mco_coro) ?*c_void;
pub extern "C" fn mco_push(arg_co: *mco_coro, arg_src: ?*const c_void, arg_len: usize) mco_result;
pub extern "C" fn mco_pop(arg_co: *mco_coro, arg_dest: ?*c_void, arg_len: usize) mco_result;
pub extern "C" fn mco_peek(arg_co: *mco_coro, arg_dest: ?*c_void, arg_len: usize) mco_result;
pub extern "C" fn mco_get_bytes_stored(arg_co: *mco_coro) usize;
pub extern "C" fn mco_get_storage_size(arg_co: *mco_coro) usize;
pub extern "C" fn mco_running() *mco_coro;
pub extern "C" fn mco_result_description(arg_res: mco_result) [*:0]const u8; | src/coro.zig |
const std = @import("std");
const match = @import("match.zig");
const Options = @import("Options.zig");
const Choices = @This();
const ScoredResult = struct {
score: match.Score,
str: []const u8,
};
const ResultList = std.ArrayList(ScoredResult);
const SearchJob = struct {
lock: std.Thread.Mutex = .{},
choices: []const []const u8,
search: []const u8,
workers: []Worker,
processed: usize = 0,
const BATCH_SIZE = 512;
fn getNextBatch(self: *SearchJob, start: *usize, end: *usize) void {
self.lock.lock();
defer self.lock.unlock();
start.* = self.processed;
self.processed += BATCH_SIZE;
if (self.processed > self.choices.len) {
self.processed = self.choices.len;
}
end.* = self.processed;
}
};
const Worker = struct {
thread: std.Thread,
job: *SearchJob,
options: *Options,
worker_num: usize,
results: ResultList,
};
allocator: std.mem.Allocator,
strings: std.ArrayList([]const u8),
results: ?ResultList = null,
selections: std.StringHashMap(void),
selection: usize = 0,
worker_count: usize = 0,
options: Options,
pub fn init(allocator: std.mem.Allocator, options: Options) !Choices {
var strings = std.ArrayList([]const u8).init(allocator);
errdefer strings.deinit();
const worker_count: usize = if (options.workers > 0)
options.workers
else
std.Thread.getCpuCount() catch unreachable;
return Choices{
.allocator = allocator,
.strings = strings,
.selections = std.StringHashMap(void).init(allocator),
.worker_count = worker_count,
.options = options,
};
}
pub fn deinit(self: *Choices) void {
for (self.strings.items) |s| {
self.allocator.free(s);
}
if (self.results) |results| results.deinit();
self.strings.deinit();
self.selections.deinit();
}
pub fn numChoices(self: Choices) usize {
return self.strings.items.len;
}
pub fn numResults(self: Choices) usize {
return if (self.results) |r| r.items.len else 0;
}
pub fn next(self: *Choices) void {
if (self.results) |results| if (results.items.len > 0) {
self.selection = (self.selection + 1) % results.items.len;
};
}
pub fn prev(self: *Choices) void {
if (self.results) |results| if (results.items.len > 0) {
self.selection = (self.selection + results.items.len - 1) % results.items.len;
};
}
pub fn read(self: *Choices, file: std.fs.File, input_delimiter: u8) !void {
var buffer = try file.reader().readAllAlloc(self.allocator, std.math.maxInt(usize));
defer self.allocator.free(buffer);
var it = std.mem.tokenize(u8, buffer, &[_]u8{input_delimiter});
var i: usize = 0;
while (it.next()) |line| : (i += 1) {
var new_line = try self.allocator.dupe(u8, line);
errdefer self.allocator.free(new_line);
try self.strings.append(new_line);
}
}
pub fn resetSearch(self: *Choices) void {
self.selection = 0;
self.selections.clearRetainingCapacity();
if (self.results) |results| {
results.deinit();
self.results = null;
}
}
pub fn select(self: *Choices, choice: []const u8) !void {
try self.selections.put(choice, {});
}
pub fn deselect(self: *Choices, choice: []const u8) void {
_ = self.selections.remove(choice);
}
pub fn getResult(self: Choices, i: usize) ?ScoredResult {
return if (self.results != null and i < self.results.?.items.len)
self.results.?.items[i]
else
null;
}
pub fn search(self: *Choices, query: []const u8) !void {
self.resetSearch();
if (query.len == 0) {
self.results = try ResultList.initCapacity(self.allocator, self.strings.items.len);
for (self.strings.items) |item| {
self.results.?.appendAssumeCapacity(.{
.str = item,
.score = match.SCORE_MIN,
});
}
return;
}
var workers = try self.allocator.alloc(Worker, self.worker_count);
defer self.allocator.free(workers);
var job = SearchJob{
.search = query,
.choices = self.strings.items,
.workers = workers,
};
var i = self.worker_count;
while (i > 0) {
i -= 1;
workers[i].job = &job;
workers[i].options = &self.options;
workers[i].worker_num = i;
workers[i].results = try ResultList.initCapacity(self.allocator, SearchJob.BATCH_SIZE);
workers[i].thread = try std.Thread.spawn(.{}, searchWorker, .{ self.allocator, &workers[i] });
}
workers[0].thread.join();
self.results = workers[0].results;
}
fn compareChoices(_: void, a: ScoredResult, b: ScoredResult) bool {
return a.score > b.score;
}
fn searchWorker(allocator: std.mem.Allocator, worker: *Worker) !void {
var job = worker.job;
var start: usize = undefined;
var end: usize = undefined;
while (true) {
job.getNextBatch(&start, &end);
if (start == end) break;
for (job.choices[start..end]) |item| {
if (match.hasMatch(job.search, item)) {
try worker.results.append(.{
.str = item,
.score = match.match(job.search, item),
});
}
}
}
if (worker.options.sort) {
std.sort.sort(ScoredResult, worker.results.items, {}, compareChoices);
}
var step: u6 = 0;
while (true) : (step += 1) {
if ((worker.worker_num % (@as(usize, 2) << step)) != 0) {
break;
}
const next_worker = worker.worker_num | (@as(usize, 1) << step);
if (next_worker >= job.workers.len) {
break;
}
job.workers[next_worker].thread.join();
worker.results = try merge2(allocator, worker.options.sort, worker.results, job.workers[next_worker].results);
}
}
fn merge2(allocator: std.mem.Allocator, sort: bool, list1: ResultList, list2: ResultList) !ResultList {
if (list2.items.len == 0) {
list2.deinit();
return list1;
}
if (list1.items.len == 0) {
list1.deinit();
return list2;
}
var result = try ResultList.initCapacity(allocator, list1.items.len + list2.items.len);
errdefer result.deinit();
var slice1 = list1.items;
var slice2 = list2.items;
while (sort and slice1.len > 0 and slice2.len > 0) {
if (compareChoices({}, slice1[0], slice2[0])) {
result.appendAssumeCapacity(slice1[0]);
slice1 = slice1[1..];
} else {
result.appendAssumeCapacity(slice2[0]);
slice2 = slice2[1..];
}
}
result.appendSliceAssumeCapacity(slice2);
result.appendSliceAssumeCapacity(slice1);
list1.deinit();
list2.deinit();
return result;
} | src/Choices.zig |
const std = @import("std");
usingnamespace @import("kira").log;
const kira_utils = @import("kira").utils;
const kira_glfw = @import("kira").glfw;
const kira_gl = @import("kira").gl;
const kira_renderer = @import("kira").renderer;
const kira_window = @import("kira").window;
const math = @import("kira").math;
const Mat4x4f = math.mat4x4.Generic(f32);
const Vec3f = math.vec3.Generic(f32);
const Vertex = comptime kira_renderer.VertexGeneric(false, Vec3f);
const Batch = kira_renderer.BatchGeneric(1024, 6, 4, Vertex);
const Colour = kira_renderer.ColourGeneric(f32);
var window_running = false;
var targetfps: f64 = 1.0 / 60.0;
const vertex_shader =
\\#version 330 core
\\layout (location = 0) in vec3 aPos;
\\layout (location = 1) in vec4 aColor;
\\out vec4 ourColor;
\\uniform mat4 MVP;
\\void main() {
\\ gl_Position = MVP * vec4(aPos, 1.0);
\\ ourColor = aColor;
\\}
;
const fragment_shader =
\\#version 330 core
\\out vec4 final;
\\in vec4 ourColor;
\\void main() {
\\ final = ourColor;
\\}
;
fn closeCallback(handle: ?*c_void) void {
window_running = false;
}
fn resizeCallback(handle: ?*c_void, w: i32, h: i32) void {
kira_gl.viewport(0, 0, w, h);
}
fn shaderAttribs() void {
const stride = @sizeOf(Vertex);
kira_gl.shaderProgramSetVertexAttribArray(0, true);
kira_gl.shaderProgramSetVertexAttribArray(1, true);
kira_gl.shaderProgramSetVertexAttribPointer(0, 3, f32, false, stride, @intToPtr(?*const c_void, @byteOffsetOf(Vertex, "position")));
kira_gl.shaderProgramSetVertexAttribPointer(1, 4, f32, false, stride, @intToPtr(?*const c_void, @byteOffsetOf(Vertex, "colour")));
}
fn submitFn(self: *Batch, vertex: [Batch.max_vertex_count]Vertex) kira_renderer.Error!void {
try self.submitVertex(self.submission_counter, 0, vertex[0]);
try self.submitVertex(self.submission_counter, 1, vertex[1]);
try self.submitVertex(self.submission_counter, 2, vertex[2]);
try self.submitVertex(self.submission_counter, 3, vertex[3]);
if (self.submission_counter == 0) {
try self.submitIndex(self.submission_counter, 0, 0);
try self.submitIndex(self.submission_counter, 1, 1);
try self.submitIndex(self.submission_counter, 2, 2);
try self.submitIndex(self.submission_counter, 3, 2);
try self.submitIndex(self.submission_counter, 4, 3);
try self.submitIndex(self.submission_counter, 5, 0);
} else {
const back = self.index_list[self.submission_counter - 1];
var i: u8 = 0;
while (i < Batch.max_index_count) : (i += 1) {
try self.submitIndex(self.submission_counter, i, back[i] + 4);
try self.submitIndex(self.submission_counter, i, back[i] + 4);
try self.submitIndex(self.submission_counter, i, back[i] + 4);
try self.submitIndex(self.submission_counter, i, back[i] + 4);
try self.submitIndex(self.submission_counter, i, back[i] + 4);
try self.submitIndex(self.submission_counter, i, back[i] + 4);
}
}
self.submission_counter += 1;
}
pub fn main() !void {
try kira_glfw.init();
defer kira_glfw.deinit();
kira_glfw.resizable(false);
kira_glfw.initGLProfile();
var window = kira_window.Info{};
var frametime = kira_window.FrameTime{};
var fps = kira_window.FpsDirect{};
window.title = "Primitive Renderer Example";
window.callbacks.close = closeCallback;
window.callbacks.resize = resizeCallback;
const sw = kira_glfw.getScreenWidth();
const sh = kira_glfw.getScreenHeight();
window.position.x = @divTrunc((sw - window.size.width), 2);
window.position.y = @divTrunc((sh - window.size.height), 2);
const ortho = Mat4x4f.ortho(0, @intToFloat(f32, window.size.width), @intToFloat(f32, window.size.height), 0, -1, 1);
var cam = math.Camera2D{};
cam.ortho = ortho;
try window.create(false);
defer window.destroy() catch unreachable;
kira_glfw.makeContext(window.handle);
kira_glfw.vsync(true);
kira_gl.init();
defer kira_gl.deinit();
var shaderprogram = try kira_gl.shaderProgramCreate(std.heap.page_allocator, vertex_shader, fragment_shader);
defer kira_gl.shaderProgramDelete(shaderprogram);
var batch = Batch{};
try batch.create(shaderprogram, shaderAttribs);
defer batch.destroy();
batch.submitfn = submitFn;
const posx2 = 100;
var posx: f32 = 400;
const posy = 100;
const w = 30;
const h = 30;
window_running = true;
while (window_running) {
frametime.start();
batch.cleanAll();
batch.submission_counter = 0;
posx += @floatCast(f32, targetfps) * 100;
try batch.submitDrawable([Batch.max_vertex_count]Vertex{
.{ .position = Vec3f{ .x = posx, .y = posy }, .colour = Colour.rgba(255, 255, 255, 255) },
.{ .position = Vec3f{ .x = posx + w, .y = posy }, .colour = Colour.rgba(255, 255, 255, 255) },
.{ .position = Vec3f{ .x = posx + w, .y = posy + h }, .colour = Colour.rgba(255, 255, 255, 255) },
.{ .position = Vec3f{ .x = posx, .y = posy + h }, .colour = Colour.rgba(255, 255, 255, 255) },
});
try batch.submitDrawable([Batch.max_vertex_count]Vertex{
.{ .position = Vec3f{ .x = posx2, .y = posy }, .colour = Colour.rgba(255, 255, 255, 255) },
.{ .position = Vec3f{ .x = posx2 + w, .y = posy }, .colour = Colour.rgba(255, 255, 255, 255) },
.{ .position = Vec3f{ .x = posx2 + w, .y = posy + h }, .colour = Colour.rgba(255, 255, 255, 255) },
.{ .position = Vec3f{ .x = posx2, .y = posy + h }, .colour = Colour.rgba(255, 255, 255, 255) },
});
kira_gl.clearColour(0.1, 0.1, 0.1, 1.0);
kira_gl.clearBuffers(kira_gl.BufferBit.colour);
kira_gl.shaderProgramUse(shaderprogram);
cam.attach();
kira_gl.shaderProgramSetMat4x4f(kira_gl.shaderProgramGetUniformLocation(shaderprogram, "MVP"), @ptrCast([*]const f32, &cam.view.toArray()));
try batch.draw(kira_gl.DrawMode.triangles);
cam.detach();
kira_glfw.sync(window.handle);
kira_glfw.processEvents();
frametime.stop();
frametime.sleep(targetfps);
fps = fps.calculate(frametime);
std.log.notice("FPS: {}", .{fps.fps});
}
} | examples/primitive-renderer.zig |
const c = @cImport({
@cInclude("X11/Xlib.h");
@cInclude("X11/cursorfont.h");
@cInclude("X11/Xft/Xft.h");
});
const std = @import("std");
const print = std.debug.warn;
const allocator = std.heap.c_allocator;
fn process_client_message(message: [20]u8, display: *c.Display) void {
print("Message arrived: {}\n ", .{message});
switch(message[0]){
'k' =>
_ = if (focus) |f| { _ = c.XKillClient(display, f.win);
print("Killing client {}\n", .{f.win});
},
else => {
print("Unknown message recived: {}\n", .{message});
},
}
}
fn OnWMDetected(display: ?*c.Display, e: [*c]c.XErrorEvent) callconv(.C) c_int {
print("\tError: Another window manager is running.", .{});
std.os.exit(1);
}
var xerrorxlib : fn(?*c.Display, [*c]c.XErrorEvent) callconv(.C) c_int = undefined;
var clients = std.ArrayList(*Client).init(allocator);
var focus : ?*Client = null;
const Cursor = enum { Normal, Resize, Move, Last };
const Dimension = struct {width: i32, height: i32};
const Position = struct {x: i32, y: i32};
const Client = struct {
name: [25]u8,
mina: f32, maxa: f32,
pos: Position,
dim: Dimension,
old_pos: Position,
old_dim: Dimension,
base_dim: Dimension,
inc_dim: Dimension,
max_dim: Dimension,
min_dim: Dimension,
border_width:i32, oldborderwidth:i32,
tags: u32,
isfixed: bool, isfloating: bool, isurgent: bool, neverfocus: i32, oldstate: i32, isfullscreen:i32,
isdecorated: bool,
win: c.Window,
pub fn init(self: *Client, wa: c.XWindowAttributes) *Client {
self.pos = Position {.x = wa.x, .y = wa.y};
self.old_pos = Position {.x = wa.x, .y = wa.y};
self.dim = Dimension {.width = wa.width, .height = wa.height};
self.old_dim = Dimension {.width = wa.width, .height = wa.height};
return self;
}
pub fn setDecorations(self : *Client) void {
self.*.isdecorated = true;
}
};
pub fn main() void {
print("\n\tZig Window Manager. Minimal version.\n\n", .{});
print(" 1. Open X display.\n", .{});
var display: *c.Display = c.XOpenDisplay(null)
orelse return print("\tError: Failed to open X display\n", .{});
defer _ = c.XCloseDisplay(display);
var root = c.XDefaultRootWindow(display);
var nofocus : c.Window = undefined;
{ // 1. Initialization.
// a. Select events on root window. Use a special error handler so we can
// exit gracefully if another window manager is already running.
xerrorxlib = c.XSetErrorHandler(OnWMDetected)
orelse return print("Error: Failed to set Error Handler\n", .{});
//causes an error if another window manager is running.
_ = c.XSelectInput(display, root, 0 // thanks to katriawm
| c.FocusChangeMask // FocusIn, FocusOut
// RandR protocol says: "Clients MAY select for
// ConfigureNotify on the root window to be
// informed of screen changes." Selecting for
// StructureNotifyMask creates such events. */
| c.StructureNotifyMask
// Manage creation and destruction of windows.
// SubstructureRedirectMask is also used by our IPC
// client and possibly EWMH clients, both sending us
// ClientMessages.
| c.SubstructureRedirectMask | c.SubstructureNotifyMask // Important ones!!
// DWM also sets this masks:
// ButtonPressMask | PointerMotionMask | EnterWindowMask
// LeaveWindowMaks | PropertyChangeMask
);
_ = c.XSync(display, c.False);
// b. Set Error Handler
_ = c.XSetErrorHandler(OnXError);
_ = c.XSync(display, c.False); // it is not necessary to run it now.
// init screen
var screen: i32 = c.XDefaultScreen(display); // TODO Document differece respect to XDefaultScreen / DefaultScreen.
// root = c.XRootWindow(display, screen); for multiple screens. otherwise is not necessary
var sw: i32 = c.XDisplayWidth(display, screen);
var sh: i32 = c.XDisplayHeight(display, screen);
print("Screen initialized\n", .{});
// c. Set default cursor on root window and center.
var cursor_normal = c.XCreateFontCursor(display, c.XC_left_ptr);
var cursor_resize = c.XCreateFontCursor(display, c.XC_sizing);
var cursor_move = c.XCreateFontCursor(display, c.XC_fleur);
_ = c.XDefineCursor(display, root, cursor_normal);
_ = c.XWarpPointer(display, c.None, root, 0, 0, 0, 0, @divTrunc(sw, 2), @divTrunc(sh,2)); // center pointer
print("Cursor initialized\n" , .{});
// TODO d. Set fonts. Initialize font and colors. - katriawm
// TODO Colors - catwm
// TODO decorations_load - katriawm
// katriawm
// Create a window which will receive input focus when no real
// window has focus. We do this to avoid any kind of "*PointerRoot"
// usage. Focusing the root window confuses applications and kind of
// returns to sloppy focus.
{
nofocus = c.XCreateSimpleWindow(display, root, -10, -10, 1, 1, 0, 0, 0);
var wa : c.XSetWindowAttributes = undefined;
wa.override_redirect = c.True;
_ = c.XChangeWindowAttributes(display, nofocus, c.CWOverrideRedirect, &wa);
_ = c.XMapWindow(display, nofocus);
_ = c.XSetInputFocus(display, nofocus, c.RevertToParent, c.CurrentTime); //focus(null); - katriawm
print ("nofocus window created.\n", .{});
}
print("SETUP complete\n", .{});
}
// SCAN OPENED WINDOWS
{
//Grab X server to prevent windows from changing under us.
_ = c.XGrabServer(display);
defer _ = c.XUngrabServer(display);
var returned_root: c.Window = undefined;
var returned_parent: c.Window = undefined;
var top_level_windows: [*c]c.Window = undefined;
defer _ = c.XFree(top_level_windows);
var num_top_level_windows: u32 = undefined;
// First, manage all top-level windows.
// Then manage transient windows.
// This is required because the windows pointed to by
// "transient_for" must already be managed by us
// attributes from the parents to their popups. */
if (c.XQueryTree(display, root, &returned_root, &returned_parent, &top_level_windows, &num_top_level_windows) != 0){
var i: u32 = 0;
var window_attrs: c.XWindowAttributes = undefined;
while (i < num_top_level_windows) : (i = i + 1) {
var window = top_level_windows[i];
// katriawm
if( c.XGetWindowAttributes(display, window, &window_attrs) == 0
or window_attrs.override_redirect != 0
or c.XGetTransientForHint(display, window, &returned_root) != 0 )
continue;
if (window_attrs.map_state == c.IsViewable) // dwm -> or getstate(window) == IconicState))
manageWindow(window, window_attrs, display);
}
i=0; // now the transients
while (i < num_top_level_windows): (i = i +1)
{
var window = top_level_windows[i];
if(c.XGetWindowAttributes(display, window, &window_attrs)==0 or window_attrs.override_redirect != 0)
continue;
if(c.XGetTransientForHint(display, window, &returned_root)!= 0
and window_attrs.map_state == c.IsViewable) // dwm - or getstate(window) == IconicState
manageWindow (window, window_attrs, display);
}
}
}
print(" 2. main event loop:\n\n", .{});
var e: c.XEvent = undefined;
while ( c.XNextEvent(display, &e)==0) {
print("recived event {}: ", .{e.type});
switch (e.type) {
// 2. Configuring a Newly Created Window
// Since the window is still invisible, the window manager doesn’t need to care.
c.ConfigureRequest => {
print("Configure Request\n",.{});
if (wintoclient(e.xconfigurerequest.window)) |client| {
} else {
}
},
c.ConfigureNotify => {
print("Configure Notify\n",.{});
if(e.xconfigure.window !=root)
continue;
},
// This is where we start managing a new window (unless it has been detected by scan() at startup).
// Note that windows might have existed before a MapRequest.
// Explicitly ignore windows with override_redirect being True to allow popups, bars, panels, ...
c.MapRequest => {
print("Map Request\n", .{});
var wa: c.XWindowAttributes = undefined;
if (c.XGetWindowAttributes(display, e.xmaprequest.window, &wa) == 0
or wa.override_redirect != 0)
continue;
manageWindow(e.xmaprequest.window, wa, display);
},
c.MappingNotify => {
print("Mapping Notify\n", .{});
_ =c.XRefreshKeyboardMapping(&e.xmapping);
//if(e.xmapping.request == c.MappingKeyboard)
// grabkeys(display, root);
},
c.UnmapNotify => {
print("Unmap Notify\n", .{});
var cl: *Client = wintoclient(e.xunmap.window) orelse continue;
if (e.xunmap.send_event != 0){
//set clientsstate ( c, WithdeawnState)
} else {
//unmanage(cl,0)
// detach(cl)
// detachstack(cl);
var window_changes : c.XWindowChanges = undefined;
_ = c.XGrabServer(display);
defer _ = c.XUngrabServer(display);
_ = c.XSetErrorHandler(xerrordummy);
_ = c.XConfigureWindow(display, cl.win, c.CWBorderWidth, &window_changes); // restore border
_ = c.XUngrabButton(display, c.AnyButton, c.AnyModifier, cl.win);
// TODO setclintstate(c,WithdrawnState);
_ = c.XSync(display, c.False);
//_ = c.SetErrorHandler(xerror);
}
},
c.DestroyNotify => {
print("Destroy Notify\n", .{});
var cl : *Client = wintoclient(e.xdestroywindow.window) orelse continue;
//unmanage(c,1)
},
c.EnterNotify => {
print("Enter Notify\n", .{});
var ev = e.xcrossing;
if ((ev.mode != c.NotifyNormal or ev.detail == c.NotifyInferior) and ev.window != root)
return;
var cl = wintoclient(ev.window) orelse {
continue; // no estic segur
};
// m = cl.mon
focus = cl;
},
c.Expose => { },
c.FocusIn => {
print("Focus In\n", .{});
},
c.ClientMessage => {
print("Client Message\n", .{});
var cme: *c.XClientMessageEvent = &e.xclient;
//var cl = wintoclient(cme.window) orelse {
// print("window: {}\n", .{cme.window});
// print("all clients:\n",.{});
// for (clients.items) |cl|
// print("client: {} - {}\n",.{cl.name, cl.win});
// continue;};
if (focus) |f| print("window: {}\n", .{f.win});
// All sorts of client messages arrive here, including our own IPC mechanism
if (cme.message_type == c.XInternAtom(display, "ZWM_CLIENT_COMMAND", c.False)){
process_client_message(cme.data.b, display);
continue;
}
},
c.PropertyNotify => {
var ev = &e.xproperty;
if (ev.window == root){ // and ev.atom == c.XA_WM_NAME){
//updatestatus
} else if (ev.state == c.PropertyDelete) {
}
},
c.FocusOut => print ("Focus Out\n", .{}),
else => print("Unhandeled event\n", .{}),
}
}
}
fn manageWindow(window: c.Window, window_attrs: c.XWindowAttributes, display: *c.Display) void {
print("Manage window {}\n", .{window});
if (wintoclient(window)) |_| {
print("Window {} already known.", .{window});
return;
}
const cl : *Client = allocator.create(Client) catch {return;};
//errdefer allocator.destroy(cl);
_ = cl.init(window_attrs);
cl.win = window;
cl.isdecorated = true;
_ = c.XSetWindowBorderWidth(display, window, 0);
{ // client update title
var tp : c.XTextProperty = undefined ;
defer _ = c.XFree(tp.value);
var AtomNetWMName = c.XInternAtom(display, "_NET_WM_NAME", c.False);
if (c.XGetTextProperty(display, window, &tp, AtomNetWMName) == 0){
print("Title of client could not be read from EWMH\n", .{});
var XA_WM_NAME: c.Atom = 39;
if (c.XGetTextProperty(display, window, &tp, XA_WM_NAME)!= 0)
print("Title of client could not be read from ICCCM\n", .{});
}
if (tp.nitems == 0)
std.mem.copy(u8, cl.name[0..25], "NAME UNKNOWN");
const XA_STRING : c.Atom = 31;
if (tp.encoding == XA_STRING){
std.mem.copy(u8, cl.name[0..25], tp.value[0..25]);
print ("Title of client {} read as verbatim string\n", .{cl.name});
}
print("Title of client is now {}\n", .{ cl.name});
}
_ = c.XSelectInput(display, window, 0
| c.FocusChangeMask // FocusIn, FocusOut */
| c.PropertyChangeMask // All kinds of properties, window titles, EWMH, ... */
);
// ICCCM says: "The WM_TRANSIENT_FOR property (of type WINDOW)
// contains the ID of another top-level window. The implication
// is that this window is a pop-up on behalf of the named
// window [...]"
//
// A popup window should always be floating. */
var transient_for: c.Window = undefined;
if (c.XGetTransientForHint(display, window, &transient_for) !=0 )
cl.isfloating = true; // katriawm also sets monitor and workspaces.
// katriawm - evaluate various hints
print("client.win {}, win {}\n", .{cl.win, window});
cl.win = window;
clients.append(cl) catch {
print("Error while saving client to list clients." , .{});
unreachable;
};
focus = cl;
_ = c.XMapWindow(display, cl.win);
}
/// There's no way to check accesses to destroyed windows, thus those cases are
/// ignored (especially on UnmapNotify's). Other types of errors call Xlibs
/// default error handler, which may call exit.
fn OnXError(display: ?*c.Display, ee: [*c]c.XErrorEvent) callconv(.C) c_int {
// if (ee.error_code == c.BadWindow
// or (ee.request_code == c.X_SetInputFocus and ee.error_code == c.BadMatch)
// or (ee.request_code == c.X_PolyText8 and ee.error_code == c.BadDrawable)
// or (ee.request_code == c.X_PolyFillRectangle and ee.error_code == c.BadDrawable)
// or (ee.request_code == c.X_PolySegment and ee.error_code == c.BadDrawable)
// or (ee.request_code == c.X_ConfigureWindow and ee.error_code == c.BadMatch)
// or (ee.request_code == c.X_GrabButton and ee.error_code == c.BadAccess)
// or (ee.request_code == c.X_GrabKey and ee.error_code == c.BadAccess)
// or (ee.request_code == c.X_CopyArea and ee.error_code == c.BadDrawable))
// return 0;
//print("zwm: fatal error: request code={}, error code={}\n", ee.requestcode, ee.error_code);
//TODO return xerrorxlib(dpy, ee); //may call exit
return 1;
}
fn OnConfigureRequest(e: c.XConfigureRequestEvent, display: *c.Display) void {
defer _ = c.XSync(display, c.False);
var client: *Client = wintoclient(e.window) orelse
{
var window_changes: c.XWindowChanges = undefined;
window_changes.x = e.x;
window_changes.y = e.y;
window_changes.width = e.width;
window_changes.height = e.height;
window_changes.border_width = e.border_width;
window_changes.sibling = e.above;
window_changes.stack_mode = e.detail;
// Grant request by calling XConfigureWindow().
_ = c.XConfigureWindow(display, e.window, @truncate(u32, e.value_mask), &window_changes);
return;
};
if (e.value_mask != 0){ // & cwborderwidth != 0){
client.border_width = e.border_width;
}
else if (client.isfloating) //or TODO
{
} else {}
//configure(client);
}
// There's no way to check accesses to destroyed windows, thus those cases are
// ignored (especially on UnmapNotify's). Other types of errors call Xlibs
// default error handler, which may call exit.
fn xerrordummy(display: ?*c.Display, ee: [*c]c.XErrorEvent) callconv(.C) c_int {
return 0;
}
fn wintoclient(w: c.Window) ?*Client {
print("Number of clients: {}. Searching for {}\n", .{clients.items.len, w});
print("Windows of clients listed:\n", .{});
for (clients.items) |client| {
print("{}\n", .{client.win});
if(client.win == w)
return client;
}
print("---------\n",.{});
return null;
} | src/main.zig |
const graph = @import("graph.zig").Graph;
const std = @import("std");
const ArrayList = std.ArrayList;
const graph_err = @import("graph.zig").GraphError;
const testing = std.testing;
const AutoArrayHashMap = std.AutoArrayHashMap;
const mem = std.mem;
const testing_alloc = std.testing.allocator;
pub fn DataGraph(comptime index_type: type, comptime node_type: type, comptime edge_type: type, directed: bool) type {
return struct {
const Self = @This();
graph: graph(index_type, directed),
node_data: AutoArrayHashMap(index_type, node_type),
edge_data: AutoArrayHashMap(index_type, edge_type),
allocator: *mem.Allocator,
pub fn init(alloc: *mem.Allocator) Self {
return Self{ .graph = graph(index_type, directed).init(alloc), .node_data = AutoArrayHashMap(index_type, node_type).init(alloc), .edge_data = AutoArrayHashMap(index_type, edge_type).init(alloc), .allocator = alloc };
}
pub fn deinit(self: *Self) !void {
try self.graph.deinit();
self.node_data.deinit();
self.edge_data.deinit();
}
//Adds a node given an index, and node data
pub fn addNode(self: *Self, node_index: index_type, node_data: node_type) !void {
try self.graph.addNode(node_index);
try self.node_data.put(node_index, node_data);
}
//Adds an edge given an index, the indices of the nodes being connected (order matters for directed), and an edge type
pub fn addEdge(self: *Self, id: index_type, n1: index_type, n2: index_type, edge_data: edge_type) !void {
try self.graph.addEdge(id, n1, n2);
try self.edge_data.put(id, edge_data);
}
//Removes an edge by its ID
pub fn removeEdgeByID(self: *Self, id: index_type) !void {
try self.graph.removeEdgeByID(id);
_ = self.edge_data.orderedRemove(id);
}
//Removes the edges between two nodes, note that for directed graphs order matters (only edges from n1 to n2 will be removed for directed)
pub fn removeEdgesBetween(self: *Self, n1: index_type, n2: index_type) !ArrayList(index_type) {
var removed_edges = try self.graph.removeEdgesBetween(n1, n2);
for (removed_edges.items) |edge| {
_ = self.edge_data.orderedRemove(edge);
}
return removed_edges;
}
//Removes a node with all of its edges
pub fn removeNodeWithEdges(self: *Self, id: index_type) !ArrayList(index_type) {
var removed_edges = try self.graph.removeNodeWithEdges(id);
for (removed_edges.items) |edge| {
_ = self.edge_data.orderedRemove(edge);
}
_ = self.node_data.orderedRemove(id);
return removed_edges;
}
//Gets the data of all nodes with indices given by an array list
pub fn getNodesData(self: *Self, ids: ArrayList(index_type)) !ArrayList(node_type) {
var data = ArrayList(node_type).init(self.allocator);
data.deinit();
for (ids.items) |id| {
if (!self.node_data.contains(id)) {
data.deinit();
return graph_err.NodesDoNotExist;
}
try data.append(self.node_data.get(id).?);
}
return data;
}
//Gets the data of all edges with indices given by an array list
pub fn getEdgesData(self: *Self, ids: ArrayList(index_type)) !ArrayList(edge_type) {
var data = ArrayList(edge_type).init(self.allocator);
data.deinit();
for (ids.items) |id| {
if (!self.edge_data.contains(id)) {
data.deinit();
return graph_err.EdgesDoNotExist;
}
try data.append(self.edge_data.get(id).?);
}
return data;
}
};
}
test "nominal-addNode" {
var data_graph = DataGraph(u32, u64, u64, true).init(testing_alloc);
try data_graph.addNode(3, 4);
try testing.expect(data_graph.graph.graph.count() == 1);
try testing.expect(data_graph.node_data.count() == 1);
try testing.expect(data_graph.node_data.get(3).? == 4);
try data_graph.deinit();
}
test "nominal-addEdge" {
var data_graph = DataGraph(u32, u64, u64, true).init(testing_alloc);
try data_graph.addNode(3, 4);
try data_graph.addNode(4, 5);
try data_graph.addEdge(1, 3, 4, 6);
try testing.expect(data_graph.edge_data.get(1).? == 6);
try data_graph.deinit();
}
test "offnominal-addNode" {
var data_graph = DataGraph(u32, u64, u64, true).init(testing_alloc);
try data_graph.addNode(3, 4);
try testing.expect(if (data_graph.addNode(3, 4)) |_| unreachable else |err| err == graph_err.NodeAlreadyExists);
try data_graph.deinit();
}
test "nominal-removeNodeWithEdges" {
var data_graph = DataGraph(u32, u64, u64, true).init(testing_alloc);
try data_graph.addNode(3, 4);
try data_graph.addNode(4, 4);
try data_graph.addEdge(1, 3, 4, 6);
var edges = try data_graph.removeNodeWithEdges(3);
try testing.expect(data_graph.graph.graph.count() == 1);
try testing.expect(data_graph.node_data.count() == 1);
try testing.expect(data_graph.edge_data.count() == 0);
try testing.expect(edges.items.len == 1);
edges.deinit();
try data_graph.deinit();
}
test "offnominal-removeNodeWithEdges" {
var data_graph = DataGraph(u32, u64, u64, true).init(testing_alloc);
try data_graph.addNode(3, 4);
try testing.expect(if (data_graph.removeNodeWithEdges(2)) |_| unreachable else |err| err == graph_err.NodesDoNotExist);
try data_graph.deinit();
}
test "nominal-removeEdgeByID" {
var data_graph = DataGraph(u32, u64, u64, true).init(testing_alloc);
try data_graph.addNode(3, 4);
try data_graph.addNode(4, 4);
try data_graph.addEdge(1, 3, 4, 6);
try data_graph.removeEdgeByID(1);
try testing.expect(data_graph.edge_data.count() == 0);
try data_graph.deinit();
}
test "offnominal-removeEdgeByID" {
var data_graph = DataGraph(u32, u64, u64, true).init(testing_alloc);
try data_graph.addNode(3, 4);
try data_graph.addNode(4, 4);
try data_graph.addEdge(1, 3, 4, 6);
try testing.expect(if (data_graph.removeEdgeByID(2)) |_| unreachable else |err| err == graph_err.EdgesDoNotExist);
try data_graph.deinit();
}
test "nominal-removeEdgesBetween" {
var data_graph = DataGraph(u32, u64, u64, true).init(testing_alloc);
try data_graph.addNode(3, 4);
try data_graph.addNode(4, 4);
try data_graph.addEdge(1, 3, 4, 6);
try data_graph.addEdge(2, 3, 4, 6);
var edges = try data_graph.removeEdgesBetween(3, 4);
try testing.expect(data_graph.edge_data.count() == 0);
try testing.expect(edges.items.len == 2);
edges.deinit();
try data_graph.deinit();
}
test "offnominal-removeEdgesBetween" {
var data_graph = DataGraph(u32, u64, u64, true).init(testing_alloc);
try data_graph.addNode(3, 4);
try data_graph.addNode(4, 4);
try data_graph.addEdge(1, 3, 4, 6);
try data_graph.addEdge(2, 3, 4, 6);
try testing.expect(if (data_graph.removeEdgesBetween(4, 5)) |_| unreachable else |err| err == graph_err.NodesDoNotExist);
try data_graph.deinit();
}
test "nominal-getNodesData" {
var data_graph = DataGraph(u32, u64, u64, true).init(testing_alloc);
try data_graph.addNode(3, 4);
try data_graph.addNode(4, 5);
var arr = ArrayList(u32).init(testing_alloc);
try arr.append(3);
try arr.append(4);
var node_data = try data_graph.getNodesData(arr);
try testing.expect(node_data.items[0] == 4);
try testing.expect(node_data.items[1] == 5);
node_data.deinit();
arr.deinit();
try data_graph.deinit();
}
test "offnominal-getNodesData" {
var data_graph = DataGraph(u32, u64, u64, true).init(testing_alloc);
try data_graph.addNode(3, 4);
try data_graph.addNode(4, 5);
var arr = ArrayList(u32).init(testing_alloc);
try arr.append(1);
try arr.append(7);
try testing.expect(if (data_graph.getNodesData(arr)) |_| unreachable else |err| err == graph_err.NodesDoNotExist);
arr.deinit();
try data_graph.deinit();
}
test "nominal-getEdgesData" {
var data_graph = DataGraph(u32, u64, u64, true).init(testing_alloc);
try data_graph.addNode(3, 4);
try data_graph.addNode(4, 5);
try data_graph.addEdge(1, 3, 4, 6);
try data_graph.addEdge(2, 3, 4, 7);
var arr = ArrayList(u32).init(testing_alloc);
try arr.append(1);
try arr.append(2);
var node_data = try data_graph.getEdgesData(arr);
try testing.expect(node_data.items[0] == 6);
try testing.expect(node_data.items[1] == 7);
node_data.deinit();
arr.deinit();
try data_graph.deinit();
}
test "offnominal-getEdgesData" {
var data_graph = DataGraph(u32, u64, u64, true).init(testing_alloc);
try data_graph.addNode(3, 4);
try data_graph.addNode(4, 5);
try data_graph.addEdge(1, 3, 4, 6);
try data_graph.addEdge(2, 3, 4, 7);
var arr = ArrayList(u32).init(testing_alloc);
try arr.append(1);
try arr.append(7);
try testing.expect(if (data_graph.getEdgesData(arr)) |_| unreachable else |err| err == graph_err.EdgesDoNotExist);
arr.deinit();
try data_graph.deinit();
} | src/data_graph.zig |
const std = @import("std");
const assert = std.debug.assert;
const ArrayList = std.ArrayList;
const c_allocator = std.heap.c_allocator;
const page_allocator = std.heap.page_allocator;
const Allocator = std.mem.Allocator;
// POSIX function
extern fn ffsll(c_longlong) c_int;
pub const OnAllocErrors = error{OnAllocError};
pub const CallbackErrors = error{GenericCallbackError};
pub fn ObjectPool(comptime T: type, comptime sub_pool_size: u32, comptime on_alloc: ?(fn ([]T) OnAllocErrors!void)) type {
if (sub_pool_size % 64 != 0) {
@compileError("sub_pool_size must be a multiple of 64");
}
return struct {
const Self = @This();
allocator_data: *Allocator,
pub const Subpool = struct {
bitmap: [sub_pool_size / 64]u64 = undefined, // call clear()
elements: []T,
pub fn init(elements: []T) Subpool {
var x = Subpool{ .elements = elements };
x.clear();
return x;
}
pub fn isEmpty(self: Subpool) bool {
for (self.bitmap) |b| {
if (b != 0) {
return false;
}
}
return true;
}
pub fn isFull(self: Subpool) bool {
for (self.bitmap) |b| {
if (b != 0xffffffffffffffff) {
return false;
}
}
return true;
}
pub fn clear(self: *Subpool) void {
std.mem.set(u8, std.mem.sliceAsBytes(self.bitmap[0..]), 0);
}
pub fn objectBelongs(self: Subpool, obj: *T) bool {
const o_ptr = @ptrToInt(obj);
const e0_ptr = @ptrToInt(&self.elements[0]);
return o_ptr >= e0_ptr and o_ptr < e0_ptr + sub_pool_size * @sizeOf(T);
}
pub fn objectAtIndex(self: *Subpool, i: u32) bool {
return self.bitmap[i / 64] & (@as(u64, 1) << @intCast(u6, i % 64)) != 0;
}
// Assumes that objectBelongs returned true for obj
pub fn freeObject(self: *Subpool, obj: *T) void {
const i = @intCast(u32, (@ptrToInt(obj) - @ptrToInt(&self.elements[0])) / @sizeOf(T));
assert(i >= 0 and i < sub_pool_size);
assert(self.objectAtIndex(i));
self.bitmap[i / 64] &= ~(@as(u64, 1) << @intCast(u6, i % 64));
}
// Assumes isFull() returned false
pub fn alloc(self: *Subpool) *T {
var i: u32 = 0; // bit/element index
for (self.bitmap) |*b| {
const first_bit_clear = @intCast(u32, ffsll(@bitCast(c_longlong, ~b.*)));
if (first_bit_clear > 0) {
b.* |= @as(u64, 1) << @intCast(u6, first_bit_clear - 1);
return &self.elements[i + first_bit_clear - 1];
}
i += 64;
}
unreachable;
}
};
subpools: ArrayList(Subpool),
pub fn init(allocator_list: *Allocator, allocator_data: *Allocator) Self {
return .{ .allocator_data = allocator_data, .subpools = ArrayList(Subpool).init(allocator_list) };
}
// Deallocated all objects. All pointers become invalid.
pub fn clear(self: *Self) void {
for (self.subpools.items) |*p| {
self.allocator_data.free(p.elements);
}
self.subpools.resize(0) catch unreachable;
}
pub fn deinit(self: *Self) void {
self.clear();
self.subpools.deinit();
}
pub fn addSubpool(self: *Self) !*Subpool {
var subpool = Subpool.init(try self.allocator_data.alloc(T, sub_pool_size));
errdefer self.allocator_data.free(subpool.elements);
if (on_alloc != null) {
try on_alloc.?(subpool.elements);
}
try self.subpools.append(subpool);
return &self.subpools.items[self.subpools.items.len - 1];
}
// Find first subpool that has 1 or more available objects (if there is one)
fn getSubPoolWithSpace(self: *Self) ?*Subpool {
for (self.subpools.items) |*p| {
if (!p.isFull()) {
return p;
}
}
return null;
}
pub fn alloc(self: *Self) !*T {
var subpool: *Subpool = self.getSubPoolWithSpace() orelse try self.addSubpool();
return subpool.alloc();
}
// alloc but don't create new objects
// If this function returns null then the next call to alloc() will allocate new objects
pub fn allocNotNew(self: *Self) ?*T {
// Find first subpool that has 1 or more available objects (if there is one)
var subpool_with_space = self.getSubPoolWithSpace();
if (subpool_with_space == null) {
return null;
}
return subpool_with_space.?.alloc();
}
pub fn free(self: *Self, o: *T) void {
for (self.subpools.items) |*p| {
if (p.objectBelongs(o)) {
p.freeObject(o);
}
}
}
pub fn forEach(self: *Self, f: fn (*T) CallbackErrors!void) CallbackErrors!void {
for (self.subpools.items) |*p| {
var i: u32 = 0;
while (i < sub_pool_size) : (i += 1) {
if (p.*.objectAtIndex(i)) {
try f(&p.*.elements[i]);
}
}
}
}
pub fn size(self: Self) usize {
return self.subpools.items.len * sub_pool_size;
}
};
}
const TestStruct = struct {
a: u32, b: u32, c: [32]u8
};
test "Object Subpools" {
var pool = ObjectPool(TestStruct, 128, null).init(c_allocator, page_allocator);
const test_struct_ptr_1 = try pool.alloc();
test_struct_ptr_1.*.a = 1;
const test_struct_ptr_2 = try pool.alloc();
pool.free(test_struct_ptr_2);
const test_struct_ptr_3 = try pool.alloc();
std.testing.expect(test_struct_ptr_2 == test_struct_ptr_3);
var i: u32 = 0;
while (i < 200) : (i += 1) {
_ = try pool.alloc();
}
std.testing.expect(pool.size() == 256);
pool.deinit();
i = 0;
while (i < 64) : (i += 1) {
std.testing.expect(ffsll(@bitCast(c_longlong, @as(u64, 1) << @intCast(u6, i))) == i + 1);
}
} | src/ObjectPool.zig |
const Unit = @import("./_utils.zig").Unit;
pub const GEORADIUS = struct {
key: []const u8,
longitude: f64,
latitude: f64,
radius: f64,
unit: Unit,
withcoord: bool,
withdist: bool,
withhash: bool,
count: ?u64,
ordering: ?Ordering,
store: ?[]const u8,
storedist: ?[]const u8,
pub const Ordering = enum {
Asc,
Desc,
};
pub fn init(
key: []const u8,
longitude: f64,
latitude: f64,
radius: f64,
unit: Unit,
withcoord: bool,
withdist: bool,
withhash: bool,
count: ?u64,
ordering: ?Ordering,
store: ?[]const u8,
storedist: ?[]const u8,
) GEORADIUS {
return .{
.key = key,
.longitude = longitude,
.latitude = latitude,
.radius = radius,
.unit = unit,
.withcoord = withcoord,
.withdist = withdist,
.withhash = withhash,
.count = count,
.ordering = ordering,
.store = store,
.storedist = storedist,
};
}
pub fn validate(_: GEORADIUS) !void {}
pub const RedisCommand = struct {
pub fn serialize(self: GEORADIUS, comptime rootSerializer: type, msg: anytype) !void {
return rootSerializer.serializeCommand(msg, .{
"GEORADIUS",
self.key,
self.longitude,
self.latitude,
self.radius,
self.unit,
self.withcoord,
self.withdist,
self.withhash,
self,
});
}
};
pub const RedisArguments = struct {
pub fn count(self: GEORADIUS) usize {
var total = 0;
if (self.count) |_| total += 2;
if (self.ordering) |_| total += 1;
if (self.store) |_| total += 2;
if (self.storedist) |_| total += 2;
return total;
}
pub fn serialize(self: GEORADIUS, comptime rootSerializer: type, msg: anytype) !void {
if (self.count) |c| {
try rootSerializer.serializeArgument(msg, []const u8, "COUNT");
try rootSerializer.serializeArgument(msg, u64, c);
}
if (self.ordering) |o| {
const ord = switch (o) {
.Asc => "ASC",
.Desc => "DESC",
};
try rootSerializer.serializeArgument(msg, []const u8, ord);
}
if (self.store) |s| {
try rootSerializer.serializeArgument(msg, []const u8, "STORE");
try rootSerializer.serializeArgument(msg, []const u8, s);
}
if (self.storedist) |sd| {
try rootSerializer.serializeArgument(msg, []const u8, "STOREDIST");
try rootSerializer.serializeArgument(msg, []const u8, sd);
}
}
};
};
test "basic usage" {
const cmd = GEORADIUS.init("mykey", 0.1, 0.2, 20, .meters, true, true, true, 10, null, null, null);
try cmd.validate();
} | src/commands/geo/georadius.zig |
// SPDX-License-Identifier: MIT
// This file is part of the Termelot project under the MIT license.
const std = @import("std");
pub const backend = @import("backend.zig");
pub const style = @import("style.zig");
usingnamespace style;
pub const event = @import("event.zig");
usingnamespace event;
pub const Backend = backend.backend.Backend;
pub const Buffer = @import("buffer.zig").Buffer;
pub const Rune = @import("rune.zig").Rune;
const termelot_log = std.log.scoped(.termelot);
// Overriding std implementation of log. This function does not actually override because this is only
// a library. Although, users of the library are encouraged to override the `log()` function themselves and
// only forward the arguments to this implementation, because it might make their lives easier.
pub fn log(
comptime level: std.log.Level,
comptime scope: @TypeOf(.EnumLiteral),
comptime format: []const u8,
args: anytype,
) void {
const prefix = "[" ++ @tagName(scope) ++ ":" ++ @tagName(level) ++ "] ";
var buf = [_]u8{' '} ** 1024; // Reserve array of 1024 bytes in stack
var exe_dir = std.fs.cwd().openDir(std.fs.selfExeDirPath(&buf) catch return, .{ .access_sub_paths = true }) catch return;
defer exe_dir.close();
var log_file = exe_dir.createFile(
"log.txt",
// TODO: we want to create an exclusive lock on file writing, but allow other processes to read,
// and not block the return of this function or logging (allow io to be blocked, not the program)
.{ .read = true, .truncate = false }, // We prefer to append to the log if it exists
) catch return;
defer log_file.close();
// Seek to end of file (to append data)
log_file.seekFromEnd(0) catch return;
const writer = log_file.writer();
nosuspend writer.print(prefix ++ format ++ "\n", args) catch return;
}
pub const Config = struct {
raw_mode: bool,
alternate_screen: bool,
initial_buffer_size: ?Size,
};
pub const SupportedFeatures = struct {
color_types: struct {
Named16: bool,
Bit8: bool,
Bit24: bool,
},
decorations: Decorations,
};
pub const Size = packed struct {
rows: u16,
cols: u16,
};
pub const Position = packed struct {
row: u16,
col: u16,
};
pub const Cell = struct {
rune: Rune,
style: Style,
};
pub const Termelot = struct {
config: Config,
supported_features: SupportedFeatures,
allocator: *std.mem.Allocator,
cursor_position: Position,
cursor_visible: bool,
screen_size: Size,
screen_buffer: Buffer,
backend: Backend,
const Self = @This();
pub fn init(
self: *Self,
allocator: *std.mem.Allocator,
config: Config,
) !Termelot {
var b = try Backend.init(allocator, config);
errdefer b.deinit();
if (config.raw_mode) {
try b.setRawMode(true);
}
if (config.alternate_screen) {
try b.setAlternateScreen(true);
}
_ = self;
return Termelot{
.config = config,
.supported_features = try b.getSupportedFeatures(),
.allocator = allocator,
.cursor_position = try b.getCursorPosition(),
.cursor_visible = try b.getCursorVisibility(),
.screen_size = try b.getScreenSize(),
.screen_buffer = try Buffer.init(
&b,
allocator,
config.initial_buffer_size,
),
.backend = b,
};
}
pub fn deinit(self: *Self) void {
if (self.config.raw_mode) {
self.backend.setRawMode(false) catch {};
}
if (self.config.alternate_screen) {
self.backend.setAlternateScreen(false) catch {};
}
self.screen_buffer.deinit();
self.backend.deinit();
}
/// Polls for an event. If the optional `timeout` parameter has a value greater than 0,
/// the function will not block and returns null whenever `timeout` milliseconds
/// has elapsed and no event could be fetched. Function returns immediately upon finding
/// an Event.
pub fn pollEvent(self: *Self, opt: struct { timeout: i32 = 0 }) !?event.Event {
return self.backend.pollEvent(opt.timeout);
}
/// Set the Termelot-aware screen size. This does NOT resize the physical
/// terminal screen, and should not be called by users in most cases. This
/// is intended for use primarily by the backend.
pub fn setScreenSize(self: *Self, screen_size: Size) void {
self.screen_size = screen_size;
}
pub fn setTitle(self: *Self, title: []const Rune) !void {
try self.backend.setTitle(title);
}
pub fn setCursorPosition(self: *Self, position: Position) !void {
try self.backend.setCursorPosition(position);
self.cursor_position = position;
}
pub fn setCursorVisibility(self: *Self, visible: bool) !void {
try self.backend.setCursorVisibility(visible);
self.cursor_visible = visible;
}
pub fn drawScreen(self: *Self) !void {
const orig_cursor_position = self.cursor_position;
try self.screen_buffer.draw(self.screen_size);
try self.setCursorPosition(orig_cursor_position);
}
/// Clears the screen buffer for next draw.
pub fn clearScreen(self: *Self) void {
self.screen_buffer.clear();
}
pub fn getCell(self: Self, position: Position) ?Cell {
return self.screen_buffer.getCell(position);
}
/// Get a slice of cells within the buffer. This slice cannot span across
/// rows. Results will be placed in provided "result", and the number of
/// cells filled will be returned (only less than the specified length if
/// the slice extends past the edges of the buffer). If position is outside
/// the buffer, `null` is returned instead.
///
/// `result` is a slice of at least length `length` to write the cells
/// into.
pub fn getCells(
self: Self,
position: Position,
length: u16,
result: []Cell,
) ?u16 {
return self.screen_buffer.getCells(position, length, result);
}
pub fn setCell(self: *Self, position: Position, new_cell: Cell) void {
self.screen_buffer.setCell(position, new_cell);
}
pub fn setCells(self: *Self, position: Position, new_cells: []Cell) void {
self.screen_buffer.setCells(position, new_cells);
}
pub fn fillCells(
self: *Self,
position: Position,
length: u16,
new_cell: Cell,
) void {
self.screen_buffer.fillCells(position, length, new_cell);
}
};
test "Termelot refAllDecls" {
std.testing.refAllDecls(Termelot);
} | src/termelot.zig |
pub const STDIN_FILENO = 0;
pub const STDOUT_FILENO = 1;
pub const STDERR_FILENO = 2;
pub const timespec = struct {
tv_sec: isize,
tv_nsec: isize,
};
pub const fd_t = usize;
pub const ino_t = u64;
pub const mode_t = u32;
pub const PATH_MAX = 1024;
pub const EPERM = 1; // Not super-user
pub const ENOENT = 2; // No such file or directory
pub const ESRCH = 3; // No such process
pub const EINTR = 4; // Interrupted system call
pub const EIO = 5; // I/O error
pub const ENXIO = 6; // No such device or address
pub const E2BIG = 7; // Arg list too long
pub const ENOEXEC = 8; // Exec format error
pub const EBADF = 9; // Bad file number
pub const ECHILD = 10; // No children
pub const EAGAIN = 11; // No more processes
pub const ENOMEM = 12; // Not enough core
pub const EACCES = 13; // Permission denied
pub const EFAULT = 14; // Bad address
pub const ENOTBLK = 15; // Block device required
pub const EBUSY = 16; // Mount device busy
pub const EEXIST = 17; // File exists
pub const EXDEV = 18; // Cross-device link
pub const ENODEV = 19; // No such device
pub const ENOTDIR = 20; // Not a directory
pub const EISDIR = 21; // Is a directory
pub const EINVAL = 22; // Invalid argument
pub const ENFILE = 23; // Too many open files in system
pub const EMFILE = 24; // Too many open files
pub const ENOTTY = 25; // Not a typewriter
pub const ETXTBSY = 26; // Text file busy
pub const EFBIG = 27; // File too large
pub const ENOSPC = 28; // No space left on device
pub const ESPIPE = 29; // Illegal seek
pub const EROFS = 30; // Read only file system
pub const EMLINK = 31; // Too many links
pub const EPIPE = 32; // Broken pipe
pub const EDOM = 33; // Math arg out of domain of func
pub const ERANGE = 34; // Math result not representable
pub const ENOMSG = 35; // No message of desired type
pub const EIDRM = 36; // Identifier removed
pub const ECHRNG = 37; // Channel number out of range
pub const EL2NSYNC = 38; // Level 2 not synchronized
pub const EL3HLT = 39; // Level 3 halted
pub const EL3RST = 40; // Level 3 reset
pub const ELNRNG = 41; // Link number out of range
pub const EUNATCH = 42; // Protocol driver not attached
pub const ENOCSI = 43; // No CSI structure available
pub const EL2HLT = 44; // Level 2 halted
pub const EDEADLK = 45; // Deadlock condition
pub const ENOLCK = 46; // No record locks available
pub const EBADE = 50; // Invalid exchange
pub const EBADR = 51; // Invalid request descriptor
pub const EXFULL = 52; // Exchange full
pub const ENOANO = 53; // No anode
pub const EBADRQC = 54; // Invalid request code
pub const EBADSLT = 55; // Invalid slot
pub const EDEADLOCK = 56; // File locking deadlock error
pub const EBFONT = 57; // Bad font file fmt
pub const ENOSTR = 60; // Device not a stream
pub const ENODATA = 61; // No data (for no delay io)
pub const ETIME = 62; // Timer expired
pub const ENOSR = 63; // Out of streams resources
pub const ENONET = 64; // Machine is not on the network
pub const ENOPKG = 65; // Package not installed
pub const EREMOTE = 66; // The object is remote
pub const ENOLINK = 67; // The link has been severed
pub const EADV = 68; // Advertise error
pub const ESRMNT = 69; // Srmount error
pub const ECOMM = 70; // Communication error on send
pub const EPROTO = 71; // Protocol error
pub const EMULTIHOP = 74; // Multihop attempted
pub const ELBIN = 75; // Inode is remote (not really error)
pub const EDOTDOT = 76; // Cross mount point (not really error)
pub const EBADMSG = 77; // Trying to read unreadable message
pub const EFTYPE = 79; // Inappropriate file type or format
pub const ENOTUNIQ = 80; // Given log. name not unique
pub const EBADFD = 81; // f.d. invalid for this operation
pub const EREMCHG = 82; // Remote address changed
pub const ELIBACC = 83; // Can't access a needed shared lib
pub const ELIBBAD = 84; // Accessing a corrupted shared lib
pub const ELIBSCN = 85; // .lib section in a.out corrupted
pub const ELIBMAX = 86; // Attempting to link in too many libs
pub const ELIBEXEC = 87; // Attempting to exec a shared library
pub const ENOSYS = 88; // Function not implemented
pub const ENMFILE = 89; // No more files
pub const ENOTEMPTY = 90; // Directory not empty
pub const ENAMETOOLONG = 91; // File or path name too long
pub const ELOOP = 92; // Too many symbolic links
pub const EOPNOTSUPP = 95; // Operation not supported on transport endpoint
pub const EPFNOSUPPORT = 96; // Protocol family not supported
pub const ECONNRESET = 104; // Connection reset by peer
pub const ENOBUFS = 105; // No buffer space available
pub const EAFNOSUPPORT = 106; // Address family not supported by protocol family
pub const EPROTOTYPE = 107; // Protocol wrong type for socket
pub const ENOTSOCK = 108; // Socket operation on non-socket
pub const ENOPROTOOPT = 109; // Protocol not available
pub const ESHUTDOWN = 110; // Can't send after socket shutdown
pub const ECONNREFUSED = 111; // Connection refused
pub const EADDRINUSE = 112; // Address already in use
pub const ECONNABORTED = 113; // Connection aborted
pub const ENETUNREACH = 114; // Network is unreachable
pub const ENETDOWN = 115; // Network interface is not configured
pub const ETIMEDOUT = 116; // Connection timed out
pub const EHOSTDOWN = 117; // Host is down
pub const EHOSTUNREACH = 118; // Host is unreachable
pub const EINPROGRESS = 119; // Connection already in progress
pub const EALREADY = 120; // Socket already connected
pub const EDESTADDRREQ = 121; // Destination address required
pub const EMSGSIZE = 122; // Message too long
pub const EPROTONOSUPPORT = 123; // Unknown protocol
pub const ESOCKTNOSUPPORT = 124; // Socket type not supported
pub const EADDRNOTAVAIL = 125; // Address not available
pub const ENETRESET = 126;
pub const EISCONN = 127; // Socket is already connected
pub const ENOTCONN = 128; // Socket is not connected
pub const ETOOMANYREFS = 129;
pub const EPROCLIM = 130;
pub const EUSERS = 131;
pub const EDQUOT = 132;
pub const ESTALE = 133;
pub const ENOTSUP = 134; // Not supported
pub const ENOMEDIUM = 135; // No medium (in tape drive)
pub const ENOSHARE = 136; // No such host or network path
pub const ECASECLASH = 137; // Filename exists with different case
pub const EILSEQ = 138;
pub const EOVERFLOW = 139; // Value too large for defined data type
// From cygwin32.
pub const EWOULDBLOCK = EAGAIN; // Operation would block
pub const __ELASTERROR = 2000; // Users can add values starting here
pub const CLOCK_REALTIME = 0;
pub const CLOCK_MONOTONIC = 1;
pub const CLOCK_PROCESS_CPUTIME_ID = 2;
pub const CLOCK_THREAD_CPUTIME_ID = 3;
pub const CLOCK_MONOTONIC_RAW = 4;
pub const CLOCK_REALTIME_COARSE = 5;
pub const CLOCK_MONOTONIC_COARSE = 6;
pub const CLOCK_BOOTTIME = 7;
pub const CLOCK_REALTIME_ALARM = 8;
pub const CLOCK_BOOTTIME_ALARM = 9;
pub const CLOCK_SGI_CYCLE = 10;
pub const CLOCK_TAI = 11;
pub const O_TRUNC = 0x0400;
pub const O_RDWR = O_RDONLY | O_WRONLY;
pub const SEEK_END = 2;
pub const O_EXCL = 0x0800;
pub const O_RDONLY = 0x0001;
pub const O_NBLOCK = 0x0004;
pub const SEEK_CUR = 1;
pub const O_DIROPEN = 0x0008;
pub const O_CREAT = 0x0200;
pub const O_WRONLY = 0x0002;
pub const O_NOWAIT = 0x8000;
pub const SEEK_SET = 0;
pub const O_APPEND = 0x0100;
pub const O_CLOEXEC = 0; //Don't do anything
pub const O_NOCTTY = 0; //Don't do anything
pub const R_OK = 1;
pub const W_OK = 1;
pub const F_OK = 1;
pub const X_OK = 1;
pub const LOCK_SH = 1;
pub const LOCK_EX = 2;
pub const LOCK_UN = 8;
pub const LOCK_NB = 4;
/// Special value used to indicate openat should use the current working directory
pub const AT_FDCWD = 0x1234;
/// Do not follow symbolic links
pub const AT_SYMLINK_NOFOLLOW = 0x100;
/// Remove directory instead of unlinking file
pub const AT_REMOVEDIR = 0x200;
/// Follow symbolic links.
pub const AT_SYMLINK_FOLLOW = 0x400;
/// Suppress terminal automount traversal
pub const AT_NO_AUTOMOUNT = 0x800;
/// Allow empty relative pathname
pub const AT_EMPTY_PATH = 0x1000;
/// Type of synchronisation required from statx()
pub const AT_STATX_SYNC_TYPE = 0x6000;
/// - Do whatever stat() does
pub const AT_STATX_SYNC_AS_STAT = 0x0000;
/// - Force the attributes to be sync'd with the server
pub const AT_STATX_FORCE_SYNC = 0x2000;
/// - Don't sync attributes with the server
pub const AT_STATX_DONT_SYNC = 0x4000;
/// Apply to the entire subtree
pub const AT_RECURSIVE = 0x8000;
usingnamespace @import("../sdk/pspiofilemgr.zig");
usingnamespace @import("../sdk/psptypes.zig");
pub const Stat = struct {
mode: u32,
st_attr: c_uint,
size: u64,
st_ctime: ScePspDateTime,
st_atime: ScePspDateTime,
st_mtime: ScePspDateTime,
st_private: [6]c_uint,
ino: ino_t,
pub fn atime(self: Stat) timespec {
return timespec{ .tv_sec = self.st_atime.second, .tv_nsec = @bitCast(isize, self.st_atime.microsecond) * 1000 };
}
pub fn mtime(self: Stat) timespec {
return timespec{ .tv_sec = self.st_mtime.second, .tv_nsec = @bitCast(isize, self.st_mtime.microsecond) * 1000 };
}
pub fn ctime(self: Stat) timespec {
return timespec{ .tv_sec = self.st_ctime.second, .tv_nsec = @bitCast(isize, self.st_ctime.microsecond) * 1000 };
}
};
pub const S_IFBLK = 524288;
pub const S_IFCHR = 262144;
pub const S_IFIFO = 131072;
pub const S_IFSOCK = 65536;
pub const S_IFMT = 61440;
pub const S_IFLNK = 16384;
pub const S_IFDIR = 4096;
pub const S_IFREG = 8192;
pub const S_ISUID = 2048;
pub const S_ISGID = 1024;
pub const S_ISVTX = 512;
pub const S_IRWXU = 448;
pub const S_IRUSR = 256;
pub const S_IWUSR = 128;
pub const S_IXUSR = 64;
pub const S_IRWXG = 56;
pub const S_IRGRP = 32;
pub const S_IWGRP = 16;
pub const S_IXGRP = 8;
pub const S_IRWXO = 7;
pub const S_IROTH = 4;
pub const S_IWOTH = 2;
pub const S_IXOTH = 1; | src/psp/os/bits.zig |
const std = @import("std");
const gl = @import("zig-opengl");
const log = std.log.scoped(.@"brucelib.graphics.opengl");
const common = @import("common.zig");
const VertexBufferHandle = common.VertexBufferHandle;
const VertexLayoutDesc = common.VertexLayoutDesc;
const VertexLayoutHandle = common.VertexLayoutHandle;
const TextureFormat = common.TextureFormat;
const TextureHandle = common.TextureHandle;
const ConstantBufferHandle = common.ConstantBufferHandle;
const RasteriserStateHandle = common.RasteriserStateHandle;
const BlendStateHandle = common.BlendStateHandle;
const ShaderProgramHandle = common.ShaderProgramHandle;
var allocator: std.mem.Allocator = undefined;
pub fn init(comptime platform: anytype, _allocator: std.mem.Allocator) !void {
allocator = _allocator;
var null_context: ?*anyopaque = null;
try gl.load(null_context, platform.getOpenGlProcAddress);
gl.enable(gl.MULTISAMPLE);
}
pub fn deinit() void {}
pub fn logDebugMessages() !void {}
pub fn setViewport(x: u16, y: u16, width: u16, height: u16) void {
gl.viewport(x, y, width, height);
}
pub fn clearWithColour(r: f32, g: f32, b: f32, a: f32) void {
gl.clearColor(r, g, b, a);
gl.clear(gl.COLOR_BUFFER_BIT);
}
pub fn draw(offset: u32, count: u32) void {
gl.drawArrays(
gl.TRIANGLES,
@intCast(gl.GLint, offset),
@intCast(gl.GLsizei, count),
);
}
pub fn createVertexBuffer(size: u32) !VertexBufferHandle {
var vbo: gl.GLuint = undefined;
gl.genBuffers(1, &vbo);
gl.bindBuffer(gl.ARRAY_BUFFER, @intCast(gl.GLenum, vbo));
gl.bufferStorage(
gl.ARRAY_BUFFER,
size,
null,
gl.MAP_WRITE_BIT | gl.MAP_PERSISTENT_BIT | gl.MAP_COHERENT_BIT,
);
return vbo;
}
pub fn destroyVertexBuffer(buffer_handle: VertexBufferHandle) !void {
const buffer = @intCast(gl.GLenum, buffer_handle);
gl.deleteBuffers(1, &buffer);
}
pub fn mapBuffer(
buffer_handle: VertexBufferHandle,
offset: usize,
size: usize,
comptime alignment: u7,
) ![]align(alignment) u8 {
const buffer = @intCast(gl.GLenum, buffer_handle);
gl.bindBuffer(gl.ARRAY_BUFFER, buffer);
const ptr = @ptrCast(
[*]u8,
gl.mapBuffer(gl.ARRAY_BUFFER, gl.WRITE_ONLY),
);
return @alignCast(alignment, ptr[offset..(offset + size)]);
}
pub fn unmapBuffer(buffer_handle: VertexBufferHandle) void {
const buffer = @intCast(gl.GLenum, buffer_handle);
gl.bindBuffer(gl.ARRAY_BUFFER, buffer);
_ = gl.unmapBuffer(gl.ARRAY_BUFFER);
}
pub fn createVertexLayout(layout_desc: VertexLayoutDesc) !VertexLayoutHandle {
var vao: gl.GLuint = undefined;
gl.genVertexArrays(1, &vao);
gl.bindVertexArray(@intCast(gl.GLuint, vao));
for (layout_desc.entries) |entry, i| {
gl.bindBuffer(gl.ARRAY_BUFFER, @intCast(gl.GLuint, entry.buffer_handle));
var attrib_offset: usize = 0;
for (entry.attributes) |attr, j| {
const num_components = attr.getNumComponents();
const component_type: gl.GLenum = switch (attr.format) {
.f32x2, .f32x3, .f32x4 => gl.FLOAT,
};
gl.enableVertexAttribArray(@intCast(gl.GLuint, j));
gl.vertexAttribPointer(
@intCast(gl.GLuint, j),
@intCast(gl.GLint, num_components),
component_type,
gl.FALSE,
@intCast(gl.GLsizei, entry.getStride()),
if (attrib_offset == 0) null else @intToPtr(*anyopaque, attrib_offset),
);
attrib_offset += attr.getSize();
}
gl.enableVertexAttribArray(@intCast(gl.GLuint, i));
}
return vao;
}
pub fn bindVertexLayout(layout_handle: VertexLayoutHandle) void {
gl.bindVertexArray(@intCast(gl.GLuint, layout_handle));
}
pub fn createTexture2dWithBytes(bytes: []const u8, width: u32, height: u32, format: TextureFormat) !TextureHandle {
var texture: gl.GLuint = undefined;
gl.genTextures(1, &texture);
gl.bindTexture(gl.TEXTURE_2D, texture);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.REPEAT);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.REPEAT);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
gl.pixelStorei(gl.UNPACK_ALIGNMENT, 1);
gl.texImage2D(
gl.TEXTURE_2D,
0,
formatToGlInternalFormat(format),
@intCast(gl.GLsizei, width),
@intCast(gl.GLsizei, height),
0,
formatToGlFormat(format),
formatToGlDataType(format),
bytes.ptr,
);
return texture;
}
pub fn bindTexture(slot: u32, texture_handle: TextureHandle) void {
// skip binding 0, which is used for the uniform block
const binding = 1 + switch (slot) {
0 => @as(gl.GLenum, gl.TEXTURE0),
1 => gl.TEXTURE1,
else => {
std.debug.assert(false);
return;
},
};
gl.activeTexture(@intCast(gl.GLenum, binding));
gl.bindTexture(gl.TEXTURE_2D, @intCast(gl.GLuint, texture_handle));
}
pub fn createConstantBuffer(size: usize) !ConstantBufferHandle {
var ubo: gl.GLuint = undefined;
gl.genBuffers(1, &ubo);
gl.bindBuffer(gl.UNIFORM_BUFFER, ubo);
gl.bufferData(gl.UNIFORM_BUFFER, @intCast(gl.GLsizeiptr, size), null, gl.DYNAMIC_DRAW);
return ubo;
}
pub fn updateShaderConstantBuffer(
buffer_handle: ConstantBufferHandle,
bytes: []const u8,
) !void {
const ubo = @intCast(gl.GLuint, buffer_handle);
gl.bindBuffer(gl.UNIFORM_BUFFER, ubo);
gl.bufferSubData(
gl.UNIFORM_BUFFER,
@intCast(gl.GLintptr, 0),
@intCast(gl.GLsizeiptr, bytes.len),
bytes.ptr,
);
gl.bindBufferBase(gl.UNIFORM_BUFFER, 0, ubo);
}
pub fn setConstantBuffer(buffer_handle: ConstantBufferHandle) void {
gl.bindBuffer(gl.UNIFORM_BUFFER, @intCast(gl.GLuint, buffer_handle));
}
pub fn createRasteriserState() !RasteriserStateHandle {
return 0;
}
pub fn setRasteriserState(_: RasteriserStateHandle) void {
gl.enable(gl.CULL_FACE);
gl.cullFace(gl.BACK);
}
pub fn createBlendState() !BlendStateHandle {
return 0;
}
pub fn setBlendState(_: BlendStateHandle) void {
gl.enable(gl.BLEND);
gl.blendFunc(gl.SRC_ALPHA, gl.ONE_MINUS_SRC_ALPHA);
}
pub fn setShaderProgram(program_handle: ShaderProgramHandle) void {
gl.useProgram(@intCast(gl.GLuint, program_handle));
}
pub fn createUniformColourShader() !ShaderProgramHandle {
const vert_shader_src = @embedFile("../data/uniform_colour_vs.glsl");
const frag_shader_src = @embedFile("../data/uniform_colour_fs.glsl");
const vertex_shader = try compileShaderSource(.vertex, vert_shader_src);
defer gl.deleteShader(vertex_shader);
const fragment_shader = try compileShaderSource(.fragment, frag_shader_src);
defer gl.deleteShader(fragment_shader);
return try createShaderProgram(vertex_shader, fragment_shader);
}
pub fn createTexturedVertsShader() !ShaderProgramHandle {
const vert_shader_src = @embedFile("../data/textured_verts_vs.glsl");
const frag_shader_src = @embedFile("../data/textured_verts_fs.glsl");
const vertex_shader = try compileShaderSource(.vertex, vert_shader_src);
defer gl.deleteShader(vertex_shader);
const fragment_shader = try compileShaderSource(.fragment, frag_shader_src);
defer gl.deleteShader(fragment_shader);
return try createShaderProgram(vertex_shader, fragment_shader);
}
pub fn createTexturedVertsMonoShader() !ShaderProgramHandle {
const vert_shader_src = @embedFile("../data/textured_verts_vs.glsl");
const frag_shader_src = @embedFile("../data/textured_verts_mono_fs.glsl");
const vertex_shader = try compileShaderSource(.vertex, vert_shader_src);
defer gl.deleteShader(vertex_shader);
const fragment_shader = try compileShaderSource(.fragment, frag_shader_src);
defer gl.deleteShader(fragment_shader);
return try createShaderProgram(vertex_shader, fragment_shader);
}
fn compileShaderSource(stage: enum { vertex, fragment }, source: [:0]const u8) !u32 {
var temp_arena = std.heap.ArenaAllocator.init(allocator);
defer temp_arena.deinit();
const shader = gl.createShader(switch (stage) {
.vertex => gl.VERTEX_SHADER,
.fragment => gl.FRAGMENT_SHADER,
});
errdefer gl.deleteShader(shader);
gl.shaderSource(shader, 1, @ptrCast([*c]const [*c]const u8, &source), null);
gl.compileShader(shader);
var compile_status: gl.GLint = undefined;
gl.getShaderiv(shader, gl.COMPILE_STATUS, &compile_status);
if (compile_status == 0) {
var log_len: gl.GLint = undefined;
gl.getShaderiv(shader, gl.INFO_LOG_LENGTH, &log_len);
if (log_len > 0) {
const log_buffer = try temp_arena.allocator().alloc(u8, @intCast(usize, log_len));
gl.getShaderInfoLog(shader, log_len, &log_len, @ptrCast([*c]u8, log_buffer));
log.err("{s}", .{log_buffer});
}
return error.ShaderCompilationFailed;
}
return shader;
}
fn createShaderProgram(vertex_shader_handle: u32, fragment_shader_handle: u32) !u32 {
var temp_arena = std.heap.ArenaAllocator.init(allocator);
defer temp_arena.deinit();
const program = gl.createProgram();
errdefer gl.deleteProgram(program);
gl.attachShader(program, vertex_shader_handle);
gl.attachShader(program, fragment_shader_handle);
gl.linkProgram(program);
var link_status: gl.GLint = undefined;
gl.getProgramiv(program, gl.LINK_STATUS, &link_status);
if (link_status == 0) {
var log_len: gl.GLint = undefined;
gl.getProgramiv(program, gl.INFO_LOG_LENGTH, &log_len);
if (log_len > 0) {
const log_buffer = try temp_arena.allocator().alloc(u8, @intCast(usize, log_len));
gl.getProgramInfoLog(program, log_len, &log_len, log_buffer.ptr);
log.err("{s}", .{log_buffer});
}
return error.FailedToLinkShaderProgram;
}
return program;
}
fn formatToGlInternalFormat(format: TextureFormat) gl.GLint {
return switch (format) {
.uint8 => gl.R8,
.rgba_u8 => gl.RGBA,
};
}
fn formatToGlFormat(format: TextureFormat) gl.GLenum {
return switch (format) {
.uint8 => gl.RED,
.rgba_u8 => gl.RGBA,
};
}
fn formatToGlDataType(format: TextureFormat) gl.GLenum {
return switch (format) {
.uint8 => gl.UNSIGNED_BYTE,
.rgba_u8 => gl.UNSIGNED_BYTE,
};
} | modules/graphics/src/opengl.zig |
const std = @import("std");
const windows = @import("windows.zig");
const d3d12 = @import("d3d12.zig");
const UINT = windows.UINT;
const UINT64 = windows.UINT64;
const FLOAT = windows.FLOAT;
const IUnknown = windows.IUnknown;
const HRESULT = windows.HRESULT;
const WINAPI = windows.WINAPI;
const GUID = windows.GUID;
const LPCWSTR = windows.LPCWSTR;
const LPCSTR = windows.LPCSTR;
const BOOL = windows.BOOL;
const L = std.unicode.utf8ToUtf16LeStringLiteral;
const assert = std.debug.assert;
//
// DirectML constants.
//
pub const TARGET_VERSION = 0x4100;
pub const TENSOR_DIMENSION_COUNT_MAX: UINT = 5;
pub const TENSOR_DIMENSION_COUNT_MAX1: UINT = 8;
pub const TEMPORARY_BUFFER_ALIGNMENT: UINT = 256;
pub const PERSISTENT_BUFFER_ALIGNMENT: UINT = 256;
pub const MINIMUM_BUFFER_TENSOR_ALIGNMENT: UINT = 16;
//
// Tensor descriptions.
//
pub const TENSOR_DATA_TYPE = enum(UINT) {
UNKNOWN,
FLOAT32,
FLOAT16,
UINT32,
UINT16,
UINT8,
INT32,
INT16,
INT8,
FLOAT64,
UINT64,
INT64,
};
pub const TENSOR_TYPE = enum(UINT) {
INVALID = 0,
BUFFER = 1,
};
pub const TENSOR_FLAGS = UINT;
pub const TENSOR_FLAG_NONE: TENSOR_FLAGS = 0x0;
pub const TENSOR_FLAG_OWNED_BY_DML: TENSOR_FLAGS = 0x1;
pub const BUFFER_TENSOR_DESC = extern struct {
DataType: TENSOR_DATA_TYPE,
Flags: TENSOR_FLAGS,
DimensionCount: UINT,
Sizes: [*]const UINT,
Strides: ?[*]const UINT,
TotalTensorSizeInBytes: UINT64,
GuaranteedBaseOffsetAlignment: UINT,
};
pub const TENSOR_DESC = extern struct {
Type: TENSOR_TYPE,
Desc: *const anyopaque,
};
//
// Operator types.
//
pub const OPERATOR_TYPE = enum(UINT) {
INVALID,
ELEMENT_WISE_IDENTITY,
ELEMENT_WISE_ABS,
ELEMENT_WISE_ACOS,
ELEMENT_WISE_ADD,
ELEMENT_WISE_ASIN,
ELEMENT_WISE_ATAN,
ELEMENT_WISE_CEIL,
ELEMENT_WISE_CLIP,
ELEMENT_WISE_COS,
ELEMENT_WISE_DIVIDE,
ELEMENT_WISE_EXP,
ELEMENT_WISE_FLOOR,
ELEMENT_WISE_LOG,
ELEMENT_WISE_LOGICAL_AND,
ELEMENT_WISE_LOGICAL_EQUALS,
ELEMENT_WISE_LOGICAL_GREATER_THAN,
ELEMENT_WISE_LOGICAL_LESS_THAN,
ELEMENT_WISE_LOGICAL_NOT,
ELEMENT_WISE_LOGICAL_OR,
ELEMENT_WISE_LOGICAL_XOR,
ELEMENT_WISE_MAX,
ELEMENT_WISE_MEAN,
ELEMENT_WISE_MIN,
ELEMENT_WISE_MULTIPLY,
ELEMENT_WISE_POW,
ELEMENT_WISE_CONSTANT_POW,
ELEMENT_WISE_RECIP,
ELEMENT_WISE_SIN,
ELEMENT_WISE_SQRT,
ELEMENT_WISE_SUBTRACT,
ELEMENT_WISE_TAN,
ELEMENT_WISE_THRESHOLD,
ELEMENT_WISE_QUANTIZE_LINEAR,
ELEMENT_WISE_DEQUANTIZE_LINEAR,
ACTIVATION_ELU,
ACTIVATION_HARDMAX,
ACTIVATION_HARD_SIGMOID,
ACTIVATION_IDENTITY,
ACTIVATION_LEAKY_RELU,
ACTIVATION_LINEAR,
ACTIVATION_LOG_SOFTMAX,
ACTIVATION_PARAMETERIZED_RELU,
ACTIVATION_PARAMETRIC_SOFTPLUS,
ACTIVATION_RELU,
ACTIVATION_SCALED_ELU,
ACTIVATION_SCALED_TANH,
ACTIVATION_SIGMOID,
ACTIVATION_SOFTMAX,
ACTIVATION_SOFTPLUS,
ACTIVATION_SOFTSIGN,
ACTIVATION_TANH,
ACTIVATION_THRESHOLDED_RELU,
CONVOLUTION,
GEMM,
REDUCE,
AVERAGE_POOLING,
LP_POOLING,
MAX_POOLING,
ROI_POOLING,
SLICE,
CAST,
SPLIT,
JOIN,
PADDING,
VALUE_SCALE_2D,
UPSAMPLE_2D,
GATHER,
SPACE_TO_DEPTH,
DEPTH_TO_SPACE,
TILE,
TOP_K,
BATCH_NORMALIZATION,
MEAN_VARIANCE_NORMALIZATION,
LOCAL_RESPONSE_NORMALIZATION,
LP_NORMALIZATION,
RNN,
LSTM,
GRU,
// TARGET_VERSION >= 0x2000
ELEMENT_WISE_SIGN,
ELEMENT_WISE_IS_NAN,
ELEMENT_WISE_ERF,
ELEMENT_WISE_SINH,
ELEMENT_WISE_COSH,
ELEMENT_WISE_TANH,
ELEMENT_WISE_ASINH,
ELEMENT_WISE_ACOSH,
ELEMENT_WISE_ATANH,
ELEMENT_WISE_IF,
ELEMENT_WISE_ADD1,
ACTIVATION_SHRINK,
MAX_POOLING1,
MAX_UNPOOLING,
DIAGONAL_MATRIX,
SCATTER_ELEMENTS,
ONE_HOT,
RESAMPLE,
// TARGET_VERSION >= 0x2000
// TARGET_VERSION >= 0x2100
ELEMENT_WISE_BIT_SHIFT_LEFT,
ELEMENT_WISE_BIT_SHIFT_RIGHT,
ELEMENT_WISE_ROUND,
ELEMENT_WISE_IS_INFINITY,
ELEMENT_WISE_MODULUS_TRUNCATE,
ELEMENT_WISE_MODULUS_FLOOR,
FILL_VALUE_CONSTANT,
FILL_VALUE_SEQUENCE,
CUMULATIVE_SUMMATION,
REVERSE_SUBSEQUENCES,
GATHER_ELEMENTS,
GATHER_ND,
SCATTER_ND,
MAX_POOLING2,
SLICE1,
TOP_K1,
DEPTH_TO_SPACE1,
SPACE_TO_DEPTH1,
MEAN_VARIANCE_NORMALIZATION1,
RESAMPLE1,
MATRIX_MULTIPLY_INTEGER,
QUANTIZED_LINEAR_MATRIX_MULTIPLY,
CONVOLUTION_INTEGER,
QUANTIZED_LINEAR_CONVOLUTION,
// TARGET_VERSION >= 0x2100
// TARGET_VERSION >= 0x3000
ELEMENT_WISE_BIT_AND,
ELEMENT_WISE_BIT_OR,
ELEMENT_WISE_BIT_XOR,
ELEMENT_WISE_BIT_NOT,
ELEMENT_WISE_BIT_COUNT,
ELEMENT_WISE_LOGICAL_GREATER_THAN_OR_EQUAL,
ELEMENT_WISE_LOGICAL_LESS_THAN_OR_EQUAL,
ACTIVATION_CELU,
ACTIVATION_RELU_GRAD,
AVERAGE_POOLING_GRAD,
MAX_POOLING_GRAD,
RANDOM_GENERATOR,
NONZERO_COORDINATES,
RESAMPLE_GRAD,
SLICE_GRAD,
ADAM_OPTIMIZER,
ARGMIN,
ARGMAX,
ROI_ALIGN,
GATHER_ND1,
// TARGET_VERSION >= 0x3000
// TARGET_VERSION >= 0x3100
ELEMENT_WISE_ATAN_YX,
ELEMENT_WISE_CLIP_GRAD,
ELEMENT_WISE_DIFFERENCE_SQUARE,
LOCAL_RESPONSE_NORMALIZATION_GRAD,
CUMULATIVE_PRODUCT,
BATCH_NORMALIZATION_GRAD,
// TARGET_VERSION >= 0x3100
// TARGET_VERSION >= 0x4000
ELEMENT_WISE_QUANTIZED_LINEAR_ADD,
DYNAMIC_QUANTIZE_LINEAR,
ROI_ALIGN1,
// TARGET_VERSION >= 0x4000
// TARGET_VERSION >= 0x4100
ROI_ALIGN_GRAD,
BATCH_NORMALIZATION_TRAINING,
BATCH_NORMALIZATION_TRAINING_GRAD,
// TARGET_VERSION >= 0x4100
};
//
// Operator enumerations and structures.
//
pub const CONVOLUTION_MODE = enum(UINT) {
CONVOLUTION,
CROSS_CORRELATION,
};
pub const CONVOLUTION_DIRECTION = enum(UINT) {
FORWARD,
BACKWARD,
};
pub const PADDING_MODE = enum(UINT) {
CONSTANT,
EDGE,
REFLECTION,
SYMMETRIC,
};
pub const INTERPOLATION_MODE = enum(UINT) {
NEAREST_NEIGHBOR,
LINEAR,
};
pub const SCALE_BIAS = extern struct {
Scale: FLOAT,
Bias: FLOAT,
};
pub const RANDOM_GENERATOR_TYPE = enum(UINT) {
PHILOX_4X32_10,
};
//
// Operator descriptions.
//
pub const OPERATOR_DESC = extern struct {
Type: OPERATOR_TYPE,
Desc: *const anyopaque,
};
pub const ELEMENT_WISE_IDENTITY_OPERATOR_DESC = extern struct {
InputTensor: *const TENSOR_DESC,
OutputTensor: *const TENSOR_DESC,
ScaleBias: ?*const SCALE_BIAS,
};
pub const RANDOM_GENERATOR_OPERATOR_DESC = extern struct {
InputStateTensor: *const TENSOR_DESC,
OutputTensor: *const TENSOR_DESC,
OutputStateTensor: ?*const TENSOR_DESC,
Type: RANDOM_GENERATOR_TYPE,
};
pub const CAST_OPERATOR_DESC = extern struct {
InputTensor: *const TENSOR_DESC,
OutputTensor: *const TENSOR_DESC,
};
pub const CONVOLUTION_OPERATOR_DESC = extern struct {
InputTensor: *const TENSOR_DESC,
FilterTensor: *const TENSOR_DESC,
BiasTensor: ?*const TENSOR_DESC,
OutputTensor: *const TENSOR_DESC,
Mode: CONVOLUTION_MODE,
Direction: CONVOLUTION_DIRECTION,
DimensionCount: UINT,
Strides: [*]const UINT,
Dilations: [*]const UINT,
StartPadding: [*]const UINT,
EndPadding: [*]const UINT,
OutputPadding: [*]const UINT,
GroupCount: UINT,
FusedActivation: ?*const OPERATOR_DESC,
};
//
// Interfaces.
//
pub const IID_IObject = GUID.parse("{c8263aac-9e0c-4a2d-9b8e-007521a3317c}");
pub const IObject = extern struct {
const Self = @This();
v: *const extern struct {
unknown: IUnknown.VTable(Self),
object: VTable(Self),
},
usingnamespace IUnknown.Methods(Self);
usingnamespace Methods(Self);
fn Methods(comptime T: type) type {
return extern struct {
pub inline fn GetPrivateData(self: *T, guid: *const GUID, data_size: *UINT, data: ?*anyopaque) HRESULT {
return self.v.object.GetPrivateData(self, guid, data_size, data);
}
pub inline fn SetPrivateData(self: *T, guid: *const GUID, data_size: UINT, data: ?*const anyopaque) HRESULT {
return self.v.object.SetPrivateData(self, guid, data_size, data);
}
pub inline fn SetPrivateDataInterface(self: *T, guid: *const GUID, data: ?*const IUnknown) HRESULT {
return self.v.object.SetPrivateDataInterface(self, guid, data);
}
pub inline fn SetName(self: *T, name: LPCWSTR) HRESULT {
return self.v.object.SetName(self, name);
}
};
}
fn VTable(comptime T: type) type {
return extern struct {
GetPrivateData: fn (*T, *const GUID, *UINT, ?*anyopaque) callconv(WINAPI) HRESULT,
SetPrivateData: fn (*T, *const GUID, UINT, ?*const anyopaque) callconv(WINAPI) HRESULT,
SetPrivateDataInterface: fn (*T, *const GUID, ?*const IUnknown) callconv(WINAPI) HRESULT,
SetName: fn (*T, LPCWSTR) callconv(WINAPI) HRESULT,
};
}
};
pub const IID_IDeviceChild = GUID.parse("{27e83142-8165-49e3-974e-2fd66e4cb69d}");
pub const IDeviceChild = extern struct {
const Self = @This();
v: *const extern struct {
unknown: IUnknown.VTable(Self),
object: IObject.VTable(Self),
devchild: VTable(Self),
},
usingnamespace IUnknown.Methods(Self);
usingnamespace IObject.Methods(Self);
usingnamespace Methods(Self);
fn Methods(comptime T: type) type {
return extern struct {
pub inline fn GetDevice(self: *T, guid: *const GUID, device: *?*anyopaque) HRESULT {
return self.v.devchild.GetDevice(self, guid, device);
}
};
}
fn VTable(comptime T: type) type {
return extern struct {
GetDevice: fn (*T, *const GUID, *?*anyopaque) callconv(WINAPI) HRESULT,
};
}
};
pub const IID_IPageable = GUID.parse("{b1ab0825-4542-4a4b-8617-6dde6e8f6201}");
pub const IPageable = extern struct {
const Self = @This();
v: *const extern struct {
unknown: IUnknown.VTable(Self),
object: IObject.VTable(Self),
devchild: IDeviceChild.VTable(Self),
pageable: VTable(Self),
},
usingnamespace IUnknown.Methods(Self);
usingnamespace IObject.Methods(Self);
usingnamespace IDeviceChild.Methods(Self);
usingnamespace Methods(Self);
fn Methods(comptime T: type) type {
_ = T;
return extern struct {};
}
fn VTable(comptime T: type) type {
_ = T;
return extern struct {};
}
};
pub const IID_IOperator = GUID.parse("{26caae7a-3081-4633-9581-226fbe57695d}");
pub const IOperator = extern struct {
const Self = @This();
v: *const extern struct {
unknown: IUnknown.VTable(Self),
object: IObject.VTable(Self),
devchild: IDeviceChild.VTable(Self),
operator: VTable(Self),
},
usingnamespace IUnknown.Methods(Self);
usingnamespace IObject.Methods(Self);
usingnamespace IDeviceChild.Methods(Self);
usingnamespace Methods(Self);
fn Methods(comptime T: type) type {
_ = T;
return extern struct {};
}
fn VTable(comptime T: type) type {
_ = T;
return extern struct {};
}
};
pub const BINDING_PROPERTIES = extern struct {
RequiredDescriptorCount: UINT,
TemporaryResourceSize: UINT64,
PersistentResourceSize: UINT64,
};
pub const IID_IDispatchable = GUID.parse("{dcb821a8-1039-441e-9f1c-b1759c2f3cec}");
pub const IDispatchable = extern struct {
const Self = @This();
v: *const extern struct {
unknown: IUnknown.VTable(Self),
object: IObject.VTable(Self),
devchild: IDeviceChild.VTable(Self),
pageable: IPageable.VTable(Self),
dispatchable: VTable(Self),
},
usingnamespace IUnknown.Methods(Self);
usingnamespace IObject.Methods(Self);
usingnamespace IDeviceChild.Methods(Self);
usingnamespace IPageable.Methods(Self);
usingnamespace Methods(Self);
fn Methods(comptime T: type) type {
return extern struct {
pub inline fn GetBindingProperties(self: *T) BINDING_PROPERTIES {
var properties: BINDING_PROPERTIES = undefined;
_ = self.v.dispatchable.GetBindingProperties(self, &properties);
return properties;
}
};
}
fn VTable(comptime T: type) type {
return extern struct {
GetBindingProperties: fn (*T, *BINDING_PROPERTIES) callconv(WINAPI) *BINDING_PROPERTIES,
};
}
};
pub const IID_ICompiledOperator = GUID.parse("{6b15e56a-bf5c-4902-92d8-da3a650afea4}");
pub const ICompiledOperator = extern struct {
const Self = @This();
v: *const extern struct {
unknown: IUnknown.VTable(Self),
object: IObject.VTable(Self),
devchild: IDeviceChild.VTable(Self),
pageable: IPageable.VTable(Self),
dispatchable: IDispatchable.VTable(Self),
coperator: VTable(Self),
},
usingnamespace IUnknown.Methods(Self);
usingnamespace IObject.Methods(Self);
usingnamespace IDeviceChild.Methods(Self);
usingnamespace IPageable.Methods(Self);
usingnamespace IDispatchable.Methods(Self);
usingnamespace Methods(Self);
fn Methods(comptime T: type) type {
_ = T;
return extern struct {};
}
fn VTable(comptime T: type) type {
_ = T;
return extern struct {};
}
};
pub const IID_IOperatorInitializer = GUID.parse("{427c1113-435c-469c-8676-4d5dd072f813}");
pub const IOperatorInitializer = extern struct {
const Self = @This();
v: *const extern struct {
unknown: IUnknown.VTable(Self),
object: IObject.VTable(Self),
devchild: IDeviceChild.VTable(Self),
pageable: IPageable.VTable(Self),
dispatchable: IDispatchable.VTable(Self),
init: VTable(Self),
},
usingnamespace IUnknown.Methods(Self);
usingnamespace IObject.Methods(Self);
usingnamespace IDeviceChild.Methods(Self);
usingnamespace IPageable.Methods(Self);
usingnamespace IDispatchable.Methods(Self);
usingnamespace Methods(Self);
fn Methods(comptime T: type) type {
return extern struct {
pub inline fn Reset(self: *T, num_operators: UINT, operators: [*]const *ICompiledOperator) HRESULT {
return self.v.init.Reset(self, num_operators, operators);
}
};
}
fn VTable(comptime T: type) type {
return extern struct {
Reset: fn (*T, UINT, [*]const *ICompiledOperator) callconv(WINAPI) HRESULT,
};
}
};
pub const BINDING_TYPE = enum(UINT) {
NONE,
BUFFER,
BUFFER_ARRAY,
};
pub const BINDING_DESC = extern struct {
Type: BINDING_TYPE,
Desc: ?*const anyopaque,
};
pub const BUFFER_BINDING = extern struct {
Buffer: ?*d3d12.IResource,
Offset: UINT64,
SizeInBytes: UINT64,
};
pub const BUFFER_ARRAY_BINDING = extern struct {
BindingCount: UINT,
Bindings: [*]const BUFFER_BINDING,
};
pub const IID_IBindingTable = GUID.parse("{29c687dc-de74-4e3b-ab00-1168f2fc3cfc}");
pub const IBindingTable = extern struct {
const Self = @This();
v: *const extern struct {
unknown: IUnknown.VTable(Self),
object: IObject.VTable(Self),
devchild: IDeviceChild.VTable(Self),
bindtable: VTable(Self),
},
usingnamespace IUnknown.Methods(Self);
usingnamespace IObject.Methods(Self);
usingnamespace IDeviceChild.Methods(Self);
usingnamespace Methods(Self);
fn Methods(comptime T: type) type {
return extern struct {
pub inline fn BindInputs(self: *T, num: UINT, bindings: ?[*]const BINDING_DESC) void {
self.v.bindtable.BindInputs(self, num, bindings);
}
pub inline fn BindOutputs(self: *T, num: UINT, bindings: ?[*]const BINDING_DESC) void {
self.v.bindtable.BindOutputs(self, num, bindings);
}
pub inline fn BindTemporaryResource(self: *T, binding: ?*const BINDING_DESC) void {
self.v.bindtable.BindTemporaryResource(self, binding);
}
pub inline fn BindPersistentResource(self: *T, binding: ?*const BINDING_DESC) void {
self.v.bindtable.BindPersistentResource(self, binding);
}
pub inline fn Reset(self: *T, desc: ?*const BINDING_TABLE_DESC) HRESULT {
return self.v.bindtable.Reset(self, desc);
}
};
}
fn VTable(comptime T: type) type {
return extern struct {
BindInputs: fn (*T, UINT, ?[*]const BINDING_DESC) callconv(WINAPI) void,
BindOutputs: fn (*T, UINT, ?[*]const BINDING_DESC) callconv(WINAPI) void,
BindTemporaryResource: fn (*T, ?*const BINDING_DESC) callconv(WINAPI) void,
BindPersistentResource: fn (*T, ?*const BINDING_DESC) callconv(WINAPI) void,
Reset: fn (*T, ?*const BINDING_TABLE_DESC) callconv(WINAPI) HRESULT,
};
}
};
pub const IID_ICommandRecorder = GUID.parse("{e6857a76-2e3e-4fdd-bff4-5d2ba10fb453}");
pub const ICommandRecorder = extern struct {
const Self = @This();
v: *const extern struct {
unknown: IUnknown.VTable(Self),
object: IObject.VTable(Self),
devchild: IDeviceChild.VTable(Self),
cmdrec: VTable(Self),
},
usingnamespace IUnknown.Methods(Self);
usingnamespace IObject.Methods(Self);
usingnamespace IDeviceChild.Methods(Self);
usingnamespace Methods(Self);
fn Methods(comptime T: type) type {
return extern struct {
pub inline fn RecordDispatch(
self: *T,
cmdlist: *d3d12.ICommandList,
dispatchable: *IDispatchable,
bindings: *IBindingTable,
) void {
self.v.cmdrec.RecordDispatch(self, cmdlist, dispatchable, bindings);
}
};
}
fn VTable(comptime T: type) type {
return extern struct {
RecordDispatch: fn (*T, *d3d12.ICommandList, *IDispatchable, *IBindingTable) callconv(WINAPI) void,
};
}
};
pub const IID_IDebugDevice = GUID.parse("{7d6f3ac9-394a-4ac3-92a7-390cc57a8217}");
pub const IDebugDevice = extern struct {
const Self = @This();
v: *const extern struct {
unknown: IUnknown.VTable(Self),
debugdev: VTable(Self),
},
usingnamespace IUnknown.Methods(Self);
usingnamespace Methods(Self);
fn Methods(comptime T: type) type {
return extern struct {
pub inline fn SetMuteDebugOutput(self: *T, mute: BOOL) void {
self.v.debugdev.SetMuteDebugOutput(self, mute);
}
};
}
fn VTable(comptime T: type) type {
return extern struct {
SetMuteDebugOutput: fn (*T, BOOL) callconv(WINAPI) void,
};
}
};
pub const IID_IDevice = GUID.parse("{6dbd6437-96fd-423f-a98c-ae5e7c2a573f}");
pub const IDevice = extern struct {
const Self = @This();
v: *const extern struct {
unknown: IUnknown.VTable(Self),
object: IObject.VTable(Self),
device: VTable(Self),
},
usingnamespace IUnknown.Methods(Self);
usingnamespace IObject.Methods(Self);
usingnamespace Methods(Self);
fn Methods(comptime T: type) type {
return extern struct {
pub inline fn CheckFeatureSupport(
self: *T,
feature: FEATURE,
feature_query_data_size: UINT,
feature_query_data: ?*const anyopaque,
feature_support_data_size: UINT,
feature_support_data: *anyopaque,
) HRESULT {
return self.v.device.CheckFeatureSupport(
self,
feature,
feature_query_data_size,
feature_query_data,
feature_support_data_size,
feature_support_data,
);
}
pub inline fn CreateOperator(self: *T, desc: *const OPERATOR_DESC, guid: *const GUID, ppv: ?*?*anyopaque) HRESULT {
return self.v.device.CreateOperator(self, desc, guid, ppv);
}
pub inline fn CompileOperator(
self: *T,
op: *IOperator,
flags: EXECUTION_FLAGS,
guid: *const GUID,
ppv: ?*?*anyopaque,
) HRESULT {
return self.v.device.CompileOperator(self, op, flags, guid, ppv);
}
pub inline fn CreateOperatorInitializer(
self: *T,
num_ops: UINT,
ops: ?[*]const *ICompiledOperator,
guid: *const GUID,
ppv: *?*anyopaque,
) HRESULT {
return self.v.device.CreateOperatorInitializer(self, num_ops, ops, guid, ppv);
}
pub inline fn CreateCommandRecorder(self: *T, guid: *const GUID, ppv: *?*anyopaque) HRESULT {
return self.v.device.CreateCommandRecorder(self, guid, ppv);
}
pub inline fn CreateBindingTable(
self: *T,
desc: ?*const BINDING_TABLE_DESC,
guid: *const GUID,
ppv: *?*anyopaque,
) HRESULT {
return self.v.device.CreateBindingTable(self, desc, guid, ppv);
}
pub inline fn Evict(self: *T, num: UINT, objs: [*]const *IPageable) HRESULT {
return self.v.device.Evict(self, num, objs);
}
pub inline fn MakeResident(self: *T, num: UINT, objs: [*]const *IPageable) HRESULT {
return self.v.device.MakeResident(self, num, objs);
}
pub inline fn GetDeviceRemovedReason(self: *T) HRESULT {
return self.v.device.GetDeviceRemovedReason(self);
}
pub inline fn GetParentDevice(self: *T, guid: *const GUID, ppv: *?*anyopaque) HRESULT {
return self.v.device.GetParentDevice(self, guid, ppv);
}
};
}
fn VTable(comptime T: type) type {
return extern struct {
CheckFeatureSupport: fn (*T, FEATURE, UINT, ?*const anyopaque, UINT, *anyopaque) callconv(WINAPI) HRESULT,
CreateOperator: fn (*T, *const OPERATOR_DESC, *const GUID, ?*?*anyopaque) callconv(WINAPI) HRESULT,
CompileOperator: fn (*T, *IOperator, EXECUTION_FLAGS, *const GUID, ?*?*anyopaque) callconv(WINAPI) HRESULT,
CreateOperatorInitializer: fn (
*T,
UINT,
?[*]const *ICompiledOperator,
*const GUID,
*?*anyopaque,
) callconv(WINAPI) HRESULT,
CreateCommandRecorder: fn (*T, *const GUID, *?*anyopaque) callconv(WINAPI) HRESULT,
CreateBindingTable: fn (*T, ?*const BINDING_TABLE_DESC, *const GUID, *?*anyopaque) callconv(WINAPI) HRESULT,
Evict: fn (*T, UINT, [*]const *IPageable) callconv(WINAPI) HRESULT,
MakeResident: fn (*T, UINT, [*]const *IPageable) callconv(WINAPI) HRESULT,
GetDeviceRemovedReason: fn (*T) callconv(WINAPI) HRESULT,
GetParentDevice: fn (*T, *const GUID, *?*anyopaque) callconv(WINAPI) HRESULT,
};
}
};
pub const GRAPH_EDGE_TYPE = enum(UINT) {
INVALID,
INPUT,
OUTPUT,
INTERMEDIATE,
};
pub const GRAPH_EDGE_DESC = extern struct {
Type: GRAPH_EDGE_TYPE,
Desc: *const anyopaque,
};
pub const INPUT_GRAPH_EDGE_DESC = extern struct {
GraphInputIndex: UINT,
ToNodeIndex: UINT,
ToNodeInputIndex: UINT,
Name: ?LPCSTR,
};
pub const OUTPUT_GRAPH_EDGE_DESC = extern struct {
FromNodeIndex: UINT,
FromNodeOutputIndex: UINT,
GraphOutputIndex: UINT,
Name: ?LPCSTR,
};
pub const INTERMEDIATE_GRAPH_EDGE_DESC = extern struct {
FromNodeIndex: UINT,
FromNodeOutputIndex: UINT,
ToNodeIndex: UINT,
ToNodeInputIndex: UINT,
Name: ?LPCSTR,
};
pub const GRAPH_NODE_TYPE = enum(UINT) {
INVALID,
OPERATOR,
};
pub const GRAPH_NODE_DESC = extern struct {
Type: GRAPH_NODE_TYPE,
Desc: *const anyopaque,
};
pub const OPERATOR_GRAPH_NODE_DESC = extern struct {
Operator: *IOperator,
Name: ?LPCSTR,
};
pub const GRAPH_DESC = extern struct {
InputCount: UINT,
OutputCount: UINT,
NodeCount: UINT,
Nodes: [*]const GRAPH_NODE_DESC,
InputEdgeCount: UINT,
InputEdges: ?[*]const GRAPH_EDGE_DESC,
OutputEdgeCount: UINT,
OutputEdges: [*]const GRAPH_EDGE_DESC,
IntermediateEdgeCount: UINT,
IntermediateEdges: ?[*]const GRAPH_EDGE_DESC,
};
pub const IID_IDevice1 = GUID.parse("{a0884f9a-d2be-4355-aa5d-5901281ad1d2}");
pub const IDevice1 = extern struct {
const Self = @This();
v: *const extern struct {
unknown: IUnknown.VTable(Self),
object: IObject.VTable(Self),
device: IDevice.VTable(Self),
device1: VTable(Self),
},
usingnamespace IUnknown.Methods(Self);
usingnamespace IObject.Methods(Self);
usingnamespace IDevice.Methods(Self);
usingnamespace Methods(Self);
fn Methods(comptime T: type) type {
return extern struct {
pub inline fn CompileGraph(
self: *T,
desc: *const GRAPH_DESC,
flags: EXECUTION_FLAGS,
guid: *const GUID,
ppv: ?*?*anyopaque,
) HRESULT {
return self.v.device1.CompileGraph(self, desc, flags, guid, ppv);
}
};
}
fn VTable(comptime T: type) type {
return extern struct {
CompileGraph: fn (*T, *const GRAPH_DESC, EXECUTION_FLAGS, *const GUID, ?*?*anyopaque) callconv(WINAPI) HRESULT,
};
}
};
//
// DML feature support queries.
//
pub const FEATURE_LEVEL = enum(UINT) {
FL_1_0 = 0x1000,
FL_2_0 = 0x2000,
FL_2_1 = 0x2100,
FL_3_0 = 0x3000,
FL_3_1 = 0x3100,
FL_4_0 = 0x4000,
FL_4_1 = 0x4100,
};
pub const FEATURE = enum(UINT) {
TENSOR_DATA_TYPE_SUPPORT,
FEATURE_LEVELS,
};
pub const FEATURE_QUERY_TENSOR_DATA_TYPE_SUPPORT = extern struct {
DataType: TENSOR_DATA_TYPE,
};
pub const FEATURE_DATA_TENSOR_DATA_TYPE_SUPPORT = extern struct {
IsSupported: BOOL,
};
pub const FEATURE_QUERY_FEATURE_LEVELS = extern struct {
RequestedFeatureLevelCount: UINT,
RequestedFeatureLevels: [*]const FEATURE_LEVEL,
};
pub const FEATURE_DATA_FEATURE_LEVELS = extern struct {
MaxSupportedFeatureLevel: FEATURE_LEVEL,
};
//
// DML device functions, enumerations, and structures.
//
pub const BINDING_TABLE_DESC = extern struct {
Dispatchable: *IDispatchable,
CPUDescriptorHandle: d3d12.CPU_DESCRIPTOR_HANDLE,
GPUDescriptorHandle: d3d12.GPU_DESCRIPTOR_HANDLE,
SizeInDescriptors: UINT,
};
pub const EXECUTION_FLAGS = UINT;
pub const EXECUTION_FLAG_NONE: EXECUTION_FLAGS = 0;
pub const EXECUTION_FLAG_ALLOW_HALF_PRECISION_COMPUTATION: EXECUTION_FLAGS = 0x1;
pub const EXECUTION_FLAG_DISABLE_META_COMMANDS: EXECUTION_FLAGS = 0x2;
pub const EXECUTION_FLAG_DESCRIPTORS_VOLATILE: EXECUTION_FLAGS = 0x4;
pub const CREATE_DEVICE_FLAGS = UINT;
pub const CREATE_DEVICE_FLAG_NONE: CREATE_DEVICE_FLAGS = 0;
pub const CREATE_DEVICE_FLAG_DEBUG: CREATE_DEVICE_FLAGS = 0x1;
pub fn createDevice(
d3d12_device: *d3d12.IDevice,
flags: CREATE_DEVICE_FLAGS,
min_feature_level: FEATURE_LEVEL,
guid: *const GUID,
ppv: ?*?*anyopaque,
) HRESULT {
var DMLCreateDevice1: fn (
*d3d12.IDevice,
CREATE_DEVICE_FLAGS,
FEATURE_LEVEL,
*const GUID,
?*?*anyopaque,
) callconv(WINAPI) HRESULT = undefined;
var directml_dll = windows.kernel32.GetModuleHandleW(L("DirectML.dll"));
if (directml_dll == null) {
directml_dll = (std.DynLib.openZ("DirectML.dll") catch unreachable).dll;
}
DMLCreateDevice1 = @ptrCast(
@TypeOf(DMLCreateDevice1),
windows.kernel32.GetProcAddress(directml_dll.?, "DMLCreateDevice1").?,
);
return DMLCreateDevice1(d3d12_device, flags, min_feature_level, guid, ppv);
}
pub fn calcBufferTensorSize(data_type: TENSOR_DATA_TYPE, sizes: []const UINT, strides: ?[]const UINT) UINT64 {
if (strides != null) assert(sizes.len == strides.?.len);
const element_size_in_bytes: UINT = switch (data_type) {
.FLOAT32, .UINT32, .INT32 => 4,
.FLOAT16, .UINT16, .INT16 => 2,
.UINT8, .INT8 => 1,
.UNKNOWN, .FLOAT64, .UINT64, .INT64 => unreachable,
};
const min_implied_size_in_bytes = blk: {
if (strides == null) {
var size: UINT = 1;
for (sizes) |s| size *= s;
break :blk size * element_size_in_bytes;
} else {
var index_of_last_element: UINT = 0;
for (sizes) |_, i| {
index_of_last_element += (sizes[i] - 1) * strides.?[i];
}
break :blk (index_of_last_element + 1) * element_size_in_bytes;
}
};
return (min_implied_size_in_bytes + 3) & ~@as(UINT64, 3);
} | modules/platform/vendored/zwin32/src/directml.zig |
const std = @import("std");
const mem = std.mem;
const Allocator = mem.Allocator;
const bog = @import("bog.zig");
const Op = bog.Op;
const Value = bog.Value;
const RegRef = bog.RegRef;
const Module = bog.Module;
const Gc = bog.Gc;
const Errors = bog.Errors;
const max_params = @import("compiler.zig").max_params;
pub const Vm = struct {
/// Instruction pointer
ip: usize,
/// Stack pointer
sp: usize,
call_stack: std.ArrayListUnmanaged(FunctionFrame) = .{},
gc: Gc,
errors: Errors,
// TODO come up with better debug info
line_loc: u32 = 0,
imports: std.StringHashMapUnmanaged(fn (*Vm) Vm.Error!*bog.Value) = .{},
/// all currently loaded packages and files
imported_modules: std.StringHashMapUnmanaged(*Module) = .{},
options: Options,
last_get: *Value = &Value.None,
const max_depth = 512;
pub const Options = struct {
/// can files be imported
import_files: bool = false,
/// run vm in repl mode
repl: bool = false,
/// maximum size of imported files
max_import_size: u32 = 1024 * 1024,
/// maximum amount of pages gc may allocate.
/// 1 page == 1 MiB.
/// default 2 GiB.
page_limit: u32 = 2048,
};
const FunctionFrame = struct {
ip: usize,
sp: usize,
line_loc: u32,
ret_reg: RegRef,
module: *Module,
// this points to the Fn values captures so the gc can see them
captures: []*Value,
this: ?*Value = null,
};
pub const Error = error{
RuntimeError,
MalformedByteCode,
} || Allocator.Error;
pub fn init(allocator: *Allocator, options: Options) Vm {
return .{
.ip = 0,
.sp = 0,
.gc = Gc.init(allocator, options.page_limit),
.errors = Errors.init(allocator),
.options = options,
};
}
pub fn deinit(vm: *Vm) void {
vm.call_stack.deinit(vm.gc.gpa);
vm.errors.deinit();
vm.gc.deinit();
vm.imports.deinit(vm.gc.gpa);
var it = vm.imported_modules.iterator();
while (it.next()) |mod| {
mod.value.deinit(vm.gc.gpa);
}
vm.imported_modules.deinit(vm.gc.gpa);
}
// TODO we might not want to require `importable` to be comptime
pub fn addPackage(vm: *Vm, name: []const u8, comptime importable: anytype) Allocator.Error!void {
try vm.imports.putNoClobber(vm.gc.gpa, name, struct {
fn func(_vm: *Vm) Vm.Error!*bog.Value {
return bog.Value.zigToBog(_vm, importable);
}
}.func);
}
pub fn addStd(vm: *Vm) Allocator.Error!void {
try vm.addStdNoIo();
try vm.addPackage("std.io", bog.std.io);
try vm.addPackage("std.os", bog.std.os);
}
pub fn addStdNoIo(vm: *Vm) Allocator.Error!void {
try vm.addPackage("std.math", bog.std.math);
try vm.addPackage("std.map", bog.std.map);
try vm.addPackage("std.debug", bog.std.debug);
try vm.addPackage("std.json", bog.std.json);
try vm.addPackage("std.gc", bog.std.gc);
}
/// Compiles and executes `source`.
pub fn run(vm: *Vm, source: []const u8) !*bog.Value {
var module = try bog.compile(vm.gc.gpa, source, &vm.errors);
defer module.deinit(vm.gc.gpa);
vm.ip = module.entry;
return try vm.exec(module);
}
/// Continues execution from current instruction pointer.
pub fn exec(vm: *Vm, mod: *Module) Error!*Value {
if (vm.gc.stack_protect_start == 0) {
vm.gc.stack_protect_start = @frameAddress();
}
const start_len = vm.call_stack.items.len;
var module = mod;
while (vm.ip < module.code.len) {
const inst = module.code[vm.ip];
vm.ip += 1;
switch (inst.op.op) {
.const_int => {
const res = try vm.getNewVal(inst.int.res);
res.* = .{
.int = if (inst.int.long) try vm.getLong(module, i64) else inst.int.arg,
};
},
.const_num => {
const res = try vm.getNewVal(inst.single.arg);
res.* = .{
.num = try vm.getLong(module, f64),
};
},
.const_primitive => {
const res = try vm.getRef(inst.primitive.res);
res.* = switch (inst.primitive.kind) {
.none => &Value.None,
.True => &Value.True,
.False => &Value.False,
_ => return error.MalformedByteCode,
};
},
.const_string_off => {
const res = try vm.getNewVal(inst.off.res);
const str = try vm.getString(module, inst);
res.* = Value.string(str);
},
.add_triple => {
const res = try vm.getNewVal(inst.triple.res);
const lhs = try vm.getNum(inst.triple.lhs);
const rhs = try vm.getNum(inst.triple.rhs);
// TODO https://github.com/ziglang/zig/issues/3234 on all of these
const copy: Value = if (needNum(lhs, rhs))
.{ .num = asNum(lhs) + asNum(rhs) }
else
.{ .int = lhs.int + rhs.int };
res.* = copy;
},
.sub_triple => {
const res = try vm.getNewVal(inst.triple.res);
const lhs = try vm.getNum(inst.triple.lhs);
const rhs = try vm.getNum(inst.triple.rhs);
const copy: Value = if (needNum(lhs, rhs))
.{ .num = asNum(lhs) - asNum(rhs) }
else
.{ .int = lhs.int - rhs.int };
res.* = copy;
},
.mul_triple => {
const res = try vm.getNewVal(inst.triple.res);
const lhs = try vm.getNum(inst.triple.lhs);
const rhs = try vm.getNum(inst.triple.rhs);
const copy: Value = if (needNum(lhs, rhs))
.{ .num = asNum(lhs) * asNum(rhs) }
else
.{ .int = lhs.int * rhs.int };
res.* = copy;
},
.pow_triple => {
const res = try vm.getNewVal(inst.triple.res);
const lhs = try vm.getNum(inst.triple.lhs);
const rhs = try vm.getNum(inst.triple.rhs);
const copy: Value = if (needNum(lhs, rhs))
.{ .num = std.math.pow(f64, asNum(lhs), asNum(rhs)) }
else
.{ .int = std.math.powi(i64, lhs.int, rhs.int) catch @panic("TODO: overflow") };
res.* = copy;
},
.div_floor_triple => {
const res = try vm.getNewVal(inst.triple.res);
const lhs = try vm.getNum(inst.triple.lhs);
const rhs = try vm.getNum(inst.triple.rhs);
const copy: Value = if (needNum(lhs, rhs))
.{ .int = @floatToInt(i64, @divFloor(asNum(lhs), asNum(rhs))) }
else
.{ .int = @divFloor(lhs.int, rhs.int) };
res.* = copy;
},
.div_triple => {
const res = try vm.getNewVal(inst.triple.res);
const lhs = try vm.getNum(inst.triple.lhs);
const rhs = try vm.getNum(inst.triple.rhs);
const copy = Value{ .num = asNum(lhs) / asNum(rhs) };
res.* = copy;
},
.mod_triple => {
const res = try vm.getNewVal(inst.triple.res);
const lhs = try vm.getNum(inst.triple.lhs);
const rhs = try vm.getNum(inst.triple.rhs);
const copy: Value = if (needNum(lhs, rhs))
.{ .num = @rem(asNum(lhs), asNum(rhs)) }
else
.{ .int = std.math.rem(i64, lhs.int, rhs.int) catch @panic("TODO: overflow") };
res.* = copy;
},
.bool_and_triple => {
const res = try vm.getRef(inst.triple.res);
const lhs = try vm.getBool(inst.triple.lhs);
const rhs = try vm.getBool(inst.triple.rhs);
res.* = if (lhs and rhs) &Value.True else &Value.False;
},
.bool_or_triple => {
const res = try vm.getRef(inst.triple.res);
const lhs = try vm.getBool(inst.triple.lhs);
const rhs = try vm.getBool(inst.triple.rhs);
res.* = if (lhs or rhs) &Value.True else &Value.False;
},
.move_double => {
const res = try vm.getRef(inst.double.res);
const arg = try vm.getVal(inst.double.arg);
res.* = arg;
},
.copy_double => {
const res = try vm.getRef(inst.double.res);
const arg = try vm.getVal(inst.double.arg);
res.* = try vm.gc.dupe(arg);
},
.bool_not_double => {
const res = try vm.getRef(inst.double.res);
const arg = try vm.getBool(inst.double.arg);
res.* = if (arg) &Value.False else &Value.True;
},
.bit_not_double => {
const res = try vm.getNewVal(inst.double.res);
const arg = try vm.getInt(inst.double.arg);
res.* = .{
.int = ~arg,
};
},
.bit_and_triple => {
const res = try vm.getNewVal(inst.triple.res);
const lhs = try vm.getInt(inst.triple.lhs);
const rhs = try vm.getInt(inst.triple.rhs);
res.* = .{
.int = lhs & rhs,
};
},
.bit_or_triple => {
const res = try vm.getNewVal(inst.triple.res);
const lhs = try vm.getInt(inst.triple.lhs);
const rhs = try vm.getInt(inst.triple.rhs);
res.* = .{
.int = lhs | rhs,
};
},
.bit_xor_triple => {
const res = try vm.getNewVal(inst.triple.res);
const lhs = try vm.getInt(inst.triple.lhs);
const rhs = try vm.getInt(inst.triple.rhs);
res.* = .{
.int = lhs ^ rhs,
};
},
.equal_triple => {
const res = try vm.getRef(inst.triple.res);
const lhs = try vm.getVal(inst.triple.lhs);
const rhs = try vm.getVal(inst.triple.rhs);
res.* = if (lhs.eql(rhs)) &Value.True else &Value.False;
},
.not_equal_triple => {
const res = try vm.getRef(inst.triple.res);
const lhs = try vm.getVal(inst.triple.lhs);
const rhs = try vm.getVal(inst.triple.rhs);
res.* = if (lhs.eql(rhs)) &Value.False else &Value.True;
},
.less_than_triple => {
const res = try vm.getRef(inst.triple.res);
const lhs = try vm.getNum(inst.triple.lhs);
const rhs = try vm.getNum(inst.triple.rhs);
const bool_val = if (needNum(lhs, rhs))
asNum(lhs) < asNum(rhs)
else
lhs.int < rhs.int;
res.* = if (bool_val) &Value.True else &Value.False;
},
.less_than_equal_triple => {
const res = try vm.getRef(inst.triple.res);
const lhs = try vm.getNum(inst.triple.lhs);
const rhs = try vm.getNum(inst.triple.rhs);
const bool_val = if (needNum(lhs, rhs))
asNum(lhs) <= asNum(rhs)
else
lhs.int <= rhs.int;
res.* = if (bool_val) &Value.True else &Value.False;
},
.greater_than_triple => {
const res = try vm.getRef(inst.triple.res);
const lhs = try vm.getNum(inst.triple.lhs);
const rhs = try vm.getNum(inst.triple.rhs);
const bool_val = if (needNum(lhs, rhs))
asNum(lhs) > asNum(rhs)
else
lhs.int > rhs.int;
res.* = if (bool_val) &Value.True else &Value.False;
},
.greater_than_equal_triple => {
const res = try vm.getRef(inst.triple.res);
const lhs = try vm.getNum(inst.triple.lhs);
const rhs = try vm.getNum(inst.triple.rhs);
const bool_val = if (needNum(lhs, rhs))
asNum(lhs) >= asNum(rhs)
else
lhs.int >= rhs.int;
res.* = if (bool_val) &Value.True else &Value.False;
},
.in_triple => {
const res = try vm.getRef(inst.triple.res);
const lhs = try vm.getVal(inst.triple.lhs);
const rhs = try vm.getVal(inst.triple.rhs);
switch (rhs.*) {
.str, .tuple, .list, .map, .range => {},
else => return vm.fatal("invalid type for 'in'"),
}
res.* = if (lhs.in(rhs)) &Value.True else &Value.False;
},
.l_shift_triple => {
const res = try vm.getNewVal(inst.triple.res);
const lhs = try vm.getInt(inst.triple.lhs);
const rhs = try vm.getInt(inst.triple.rhs);
if (rhs < 0)
return vm.fatal("shift by negative amount");
const val = if (rhs > std.math.maxInt(u6)) 0 else lhs << @intCast(u6, rhs);
res.* = .{
.int = val,
};
},
.r_shift_triple => {
const res = try vm.getNewVal(inst.triple.res);
const lhs = try vm.getInt(inst.triple.lhs);
const rhs = try vm.getInt(inst.triple.rhs);
if (rhs < 0)
return vm.fatal("shift by negative amount");
const val = if (rhs > std.math.maxInt(u6)) 0 else lhs >> @intCast(u6, rhs);
res.* = .{
.int = val,
};
},
.negate_double => {
const res = try vm.getNewVal(inst.double.res);
const arg = try vm.getNum(inst.double.arg);
const copy: Value = if (arg.* == .num)
.{ .num = -arg.num }
else
.{ .int = -arg.int };
res.* = copy;
},
.try_double => {
const res = try vm.getRef(inst.double.res);
const arg = try vm.getVal(inst.double.arg);
if (arg.* != .err) {
res.* = arg;
continue;
}
if (vm.call_stack.items.len == start_len) {
if (start_len == 0) {
vm.gc.stackShrink(0);
}
// module result
return arg;
}
const frame = vm.call_stack.pop();
module = frame.module;
vm.gc.stackShrink(vm.sp);
vm.ip = frame.ip;
vm.sp = frame.sp;
vm.line_loc = frame.line_loc;
const ret_val = try vm.gc.stackAlloc(vm.sp + frame.ret_reg);
ret_val.* = arg.*;
},
.jump => {
const base = vm.ip;
const offset = @bitCast(i32, try vm.getSingle(module));
vm.ip = @intCast(usize, @intCast(isize, base) + offset);
},
.jump_false => {
const base = vm.ip;
const arg = try vm.getBool(inst.jump.arg);
const offset = try vm.getSingle(module);
if (arg == false) {
vm.ip = base + offset;
}
},
.jump_true => {
const base = vm.ip;
const arg = try vm.getBool(inst.jump.arg);
const offset = try vm.getSingle(module);
if (arg == true) {
vm.ip = base + offset;
}
},
.jump_error => {
const base = vm.ip;
const arg = try vm.getVal(inst.jump.arg);
const offset = try vm.getSingle(module);
if (arg.* == .err) {
vm.ip = base + offset;
}
},
.jump_not_error => {
const base = vm.ip;
const arg = try vm.getVal(inst.jump.arg);
const offset = try vm.getSingle(module);
if (arg.* != .err) {
vm.ip = base + offset;
}
},
.jump_none => {
const base = vm.ip;
const arg = try vm.getVal(inst.jump.arg);
const offset = try vm.getSingle(module);
if (arg.* == .none) {
vm.ip = base + offset;
}
},
.iter_init_double => {
const res = try vm.getRef(inst.double.res);
const arg = try vm.getVal(inst.double.arg);
res.* = try Value.iterator(arg, vm);
},
.iter_next_double => {
const base = vm.ip;
const res = try vm.getRef(inst.double.res);
const arg = try vm.getVal(inst.double.arg);
const offset = try vm.getSingle(module);
if (arg.* != .iterator)
return error.MalformedByteCode;
try arg.iterator.next(vm, res);
if (res.*.?.* == .none) {
vm.ip = base + offset;
}
},
.unwrap_error_double => {
const res = try vm.getRef(inst.double.res);
const arg = try vm.getVal(inst.double.arg);
if (arg.* != .err)
return vm.fatal("expected an error");
res.* = try vm.gc.dupe(arg.err);
},
.unwrap_tagged => {
const res = try vm.getRef(inst.double.res);
const arg = try vm.getVal(inst.double.arg);
const offset = try vm.getSingle(module);
const len = @ptrCast(*align(1) const u32, module.strings[offset..].ptr).*;
const name = module.strings[offset + @sizeOf(u32) ..][0..len];
if (arg.* != .tagged)
return vm.fatal("expected a tagged value");
if (!mem.eql(u8, arg.tagged.name, name))
return vm.fatal("invalid tag");
res.* = arg.tagged.value;
},
.import_off => {
const res = try vm.getRef(inst.off.res);
const str = try vm.getString(module, inst);
res.* = try vm.import(str);
},
.discard_single => {
const arg = try vm.getVal(inst.single.arg);
if (arg.* == .err) {
return vm.fatal("error discarded");
}
if (vm.options.repl and vm.call_stack.items.len == 0) {
return arg;
}
},
.build_tuple_off => {
const res = try vm.getNewVal(inst.off.res);
const size = if (inst.off.isArg())
try vm.getSingle(module)
else
inst.off.off;
res.* = .{ .tuple = try vm.gc.gpa.alloc(*Value, size) };
},
.build_list_off => {
const res = try vm.getNewVal(inst.off.res);
const size = if (inst.off.isArg())
try vm.getSingle(module)
else
inst.off.off;
res.* = .{ .list = .{} };
try res.list.resize(vm.gc.gpa, size);
},
.build_map_off => {
const res = try vm.getNewVal(inst.off.res);
const size = if (inst.off.isArg())
try vm.getSingle(module)
else
inst.off.off;
res.* = .{ .map = .{} };
try res.map.ensureCapacity(vm.gc.gpa, size);
},
.build_error_double => {
const res = try vm.getNewVal(inst.double.res);
const arg = try vm.getVal(inst.double.arg);
res.* = .{
.err = try vm.gc.dupe(arg),
};
},
.build_func => {
const res = try vm.getNewVal(inst.func.res);
if (inst.func.arg_count > max_params)
return error.MalformedByteCode;
res.* = .{
.func = .{
.arg_count = inst.func.arg_count,
.offset = try vm.getSingle(module),
.module = module,
.captures = try vm.gc.gpa.alloc(*Value, inst.func.capture_count),
},
};
},
.build_tagged => {
const res = try vm.getNewVal(inst.tagged.res);
const arg = switch (inst.tagged.kind) {
.none => &Value.None,
.some => try vm.gc.dupe(try vm.getVal(inst.tagged.arg)),
_ => return error.MalformedByteCode,
};
const offset = try vm.getSingle(module);
const len = @ptrCast(*align(1) const u32, module.strings[offset..].ptr).*;
const name = module.strings[offset + @sizeOf(u32) ..][0..len];
res.* = .{
.tagged = .{
.name = name,
.value = arg,
},
};
},
.build_range => {
const res = try vm.getNewVal(inst.range.res);
{
if (vm.ip + 1 > module.code.len)
return error.MalformedByteCode;
vm.ip += 1;
}
const cont = module.code[vm.ip - 1].range_cont;
res.* = .{
.range = .{},
};
const range = &res.range;
switch (cont.start_kind) {
.reg => range.start = try vm.getInt(inst.range.start),
.value => range.start = inst.range.start,
.default => {},
_ => return error.MalformedByteCode,
}
switch (cont.end_kind) {
.reg => range.end = try vm.getInt(inst.range.end),
.value => range.end = inst.range.end,
.default => {},
_ => return error.MalformedByteCode,
}
switch (cont.step_kind) {
.reg => range.step = try vm.getInt(inst.range_cont.step),
.value => range.step = cont.step,
.default => {},
_ => return error.MalformedByteCode,
}
},
.get_triple => {
const res = try vm.getRef(inst.triple.res);
const container = try vm.getVal(inst.triple.lhs);
const index = try vm.getVal(inst.triple.rhs);
try container.get(vm, index, res);
// this will become the value of `this` for the next function call
vm.last_get = container;
},
.set_triple => {
const container = try vm.getVal(inst.triple.res);
const index = try vm.getVal(inst.triple.lhs);
const val = try vm.getVal(inst.triple.rhs);
try container.set(vm, index, val);
},
.as_type_id => {
const res = try vm.getRef(inst.type_id.res);
const arg = try vm.getVal(inst.type_id.arg);
// Value.as will hit unreachable on invalid type_id
switch (inst.type_id.type_id) {
.none, .int, .num, .bool, .str, .tuple, .map, .list => {},
else => return error.MalformedByteCode,
}
res.* = try arg.as(vm, inst.type_id.type_id);
},
.is_type_id => {
const res = try vm.getRef(inst.type_id.res);
const arg = try vm.getVal(inst.type_id.arg);
switch (inst.type_id.type_id) {
.none, .int, .num, .bool, .str, .tuple, .map, .list, .err, .range, .func, .tagged => {},
else => return error.MalformedByteCode,
}
res.* = if (arg.is(inst.type_id.type_id)) &Value.True else &Value.False;
},
.call => {
const res = inst.call.res;
const func = try vm.getVal(inst.call.func);
const first = inst.call.first;
const arg_count = try vm.getSingle(module);
if (arg_count > max_params)
return error.MalformedByteCode;
if (func.* == .native) {
if (func.native.arg_count != arg_count) {
return vm.fatalExtra(try Value.String.init(vm.gc.gpa, "expected {} args, got {}", .{ func.native.arg_count, arg_count }));
}
const args = vm.gc.stack.items[vm.sp + first ..][0..arg_count];
for (args) |arg| {
if (arg == null)
return error.MalformedByteCode;
}
const ret_val = try func.native.func(vm, @bitCast([]*Value, args));
const ret_ref = try vm.getRef(res);
ret_ref.* = ret_val;
continue;
}
if (func.* != .func) {
const ret_ref = try vm.getRef(res);
ret_ref.* = try vm.typeError(.func, func.*);
continue;
}
if (func.func.arg_count != arg_count) {
return vm.fatalExtra(try Value.String.init(vm.gc.gpa, "expected {} args, got {}", .{ func.func.arg_count, arg_count }));
}
if (vm.call_stack.items.len > max_depth) {
return vm.fatal("maximum depth exceeded");
}
try vm.call_stack.append(vm.gc.gpa, .{
.sp = vm.sp,
.ip = vm.ip,
.line_loc = vm.line_loc,
.ret_reg = res,
.module = mod,
.captures = func.func.captures,
.this = vm.last_get,
});
vm.sp += first;
vm.ip = func.func.offset;
module = func.func.module;
},
.return_single => {
const arg = try vm.getVal(inst.single.arg);
if (vm.call_stack.items.len == start_len) {
if (start_len == 0) {
vm.gc.stackShrink(0);
}
// module result
return arg;
}
const frame = vm.call_stack.pop();
module = frame.module;
vm.gc.stackShrink(vm.sp);
vm.ip = frame.ip;
vm.sp = frame.sp;
vm.line_loc = frame.line_loc;
const ret_val = try vm.getRef(frame.ret_reg);
ret_val.* = arg;
},
.return_none => {
if (vm.call_stack.items.len == start_len) {
if (start_len == 0) {
vm.gc.stackShrink(0);
}
// module result
return &Value.None;
}
const frame = vm.call_stack.pop();
module = frame.module;
vm.gc.stackShrink(vm.sp);
vm.ip = frame.ip;
vm.sp = frame.sp;
vm.line_loc = frame.line_loc;
const ret_val = try vm.getRef(frame.ret_reg);
ret_val.* = &Value.None;
},
.load_capture_double => {
const res = try vm.getRef(inst.double.res);
const arg = inst.double.arg;
const frame = vm.call_stack.items[vm.call_stack.items.len - 1];
if (arg >= frame.captures.len) return error.MalformedByteCode;
res.* = frame.captures[arg];
},
.store_capture_triple => {
const res = try vm.getVal(inst.triple.res);
const lhs = try vm.getVal(inst.triple.lhs);
const rhs = inst.triple.rhs;
if (res.* != .func) return error.MalformedByteCode;
if (rhs >= res.func.captures.len) return error.MalformedByteCode;
res.func.captures[rhs] = lhs;
},
.load_this_single => {
const res = try vm.getRef(inst.single.arg);
const frame = vm.call_stack.items[vm.call_stack.items.len - 1];
res.* = frame.this orelse
return vm.fatal("this has not been set");
},
.append_double => {
const lhs = try vm.getVal(inst.double.res);
const rhs = try vm.getVal(inst.double.arg);
switch (lhs.*) {
.list => |*list| try list.append(vm.gc.gpa, try vm.gc.dupe(rhs)),
.str => |*str| {
if (rhs.* != .str) {
return vm.fatal("expected a string");
}
try str.append(vm.gc.gpa, rhs.str.data);
},
else => return vm.fatal("expected a string or a list"),
}
},
.line_info => {
vm.line_loc = try vm.getSingle(module);
},
_ => {
return error.MalformedByteCode;
},
}
}
return &Value.None;
}
fn import(vm: *Vm, id: []const u8) !*Value {
var mod = vm.imported_modules.get(id) orelse if (mem.endsWith(u8, id, bog.extension)) blk: {
if (!vm.options.import_files) {
return vm.fatal("import failed");
}
const source = std.fs.cwd().readFileAlloc(vm.gc.gpa, id, vm.options.max_import_size) catch |e| switch (e) {
error.OutOfMemory => return error.OutOfMemory,
else => return vm.fatal("import failed"),
};
defer vm.gc.gpa.free(source);
const mod = bog.compile(vm.gc.gpa, source, &vm.errors) catch
return vm.fatal("import failed");
mod.name = try mem.dupe(vm.gc.gpa, u8, id);
_ = try vm.imported_modules.put(vm.gc.gpa, id, mod);
break :blk mod;
} else if (mem.endsWith(u8, id, bog.bytecode_extension)) blk: {
if (!vm.options.import_files) {
return vm.fatal("import failed");
}
const source = std.fs.cwd().readFileAlloc(vm.gc.gpa, id, vm.options.max_import_size) catch |e| switch (e) {
error.OutOfMemory => return error.OutOfMemory,
else => return vm.fatal("import failed"),
};
defer vm.gc.gpa.free(source);
const read_module = Module.read(source) catch
return vm.fatal("import failed");
const mod = try vm.gc.gpa.create(Module);
mod.* = .{
.name = try mem.dupe(vm.gc.gpa, u8, id),
.code = try mem.dupe(vm.gc.gpa, bog.Instruction, read_module.code),
.strings = try mem.dupe(vm.gc.gpa, u8, read_module.strings),
.entry = read_module.entry,
};
_ = try vm.imported_modules.put(vm.gc.gpa, id, mod);
break :blk mod;
} else {
if (vm.imports.get(id)) |some| {
return some(vm);
}
return vm.fatal("no such package");
};
const saved_sp = vm.sp;
const saved_ip = vm.ip;
const saved_line_loc = vm.line_loc;
const saved_stack_len = vm.gc.stack.items.len;
vm.sp = vm.gc.stack.items.len;
vm.ip = mod.entry;
const res = try vm.exec(mod);
vm.gc.stackShrink(saved_stack_len);
vm.ip = saved_ip;
vm.sp = saved_sp;
vm.line_loc = saved_line_loc;
return res;
}
fn getSingle(vm: *Vm, module: *Module) !u32 {
if (vm.ip + 1 > module.code.len)
return error.MalformedByteCode;
defer vm.ip += 1;
return module.code[vm.ip].bare;
}
fn getLong(vm: *Vm, module: *Module, comptime T: type) !T {
if (vm.ip + 2 > module.code.len)
return error.MalformedByteCode;
var arr: [2]bog.Instruction = undefined;
arr[0] = module.code[vm.ip];
arr[1] = module.code[vm.ip + 1];
vm.ip += 2;
return @bitCast(T, arr);
}
fn getVal(vm: *Vm, reg: RegRef) !*Value {
return vm.gc.stackGet(vm.sp + reg) catch
return error.MalformedByteCode;
}
fn getRef(vm: *Vm, reg: RegRef) !*?*Value {
return try vm.gc.stackRef(vm.sp + reg);
}
fn getNewVal(vm: *Vm, reg: RegRef) !*Value {
return try vm.gc.stackAlloc(vm.sp + reg);
}
fn getString(vm: *Vm, module: *Module, inst: bog.Instruction) ![]const u8 {
const offset = if (inst.off.isArg())
try vm.getSingle(module)
else
inst.off.off;
const len = @ptrCast(*align(1) const u32, module.strings[offset..].ptr).*;
return module.strings[offset + @sizeOf(u32) ..][0..len];
}
fn getBool(vm: *Vm, reg: RegRef) !bool {
const val = try vm.getVal(reg);
if (val.* != .bool) {
return vm.fatal("expected a boolean");
}
return val.bool;
}
fn getInt(vm: *Vm, reg: RegRef) !i64 {
const val = try vm.getVal(reg);
if (val.* != .int) {
return vm.fatal("expected an integer");
}
return val.int;
}
fn getIntRef(vm: *Vm, reg: RegRef) !*Value {
const val = try vm.getVal(reg);
if (val.* != .int) {
return vm.fatal("expected an integer");
}
return val;
}
fn getNum(vm: *Vm, reg: RegRef) !*Value {
const val = try vm.getVal(reg);
if (val.* != .int and val.* != .num) {
return vm.fatal("expected a number");
}
return val;
}
inline fn needNum(a: *Value, b: *Value) bool {
return a.* == .num or b.* == .num;
}
inline fn asNum(val: *Value) f64 {
return switch (val.*) {
.int => |v| @intToFloat(f64, v),
.num => |v| v,
else => unreachable,
};
}
pub fn errorFmt(vm: *Vm, comptime fmt: []const u8, args: anytype) Vm.Error!*Value {
const str = try vm.gc.alloc();
str.* = .{ .str = try Value.String.init(vm.gc.gpa, fmt, args) };
const err = try vm.gc.alloc();
err.* = .{ .err = str };
return err;
}
pub fn typeError(vm: *Vm, expected: bog.Type, got: bog.Type) Vm.Error!*Value {
return vm.errorFmt("expected {}, got {}", .{ @tagName(expected), @tagName(got) });
}
pub fn errorVal(vm: *Vm, msg: []const u8) !*Value {
const str = try vm.gc.alloc();
str.* = Value.string(msg);
const err = try vm.gc.alloc();
err.* = .{ .err = str };
return err;
}
pub fn fatal(vm: *Vm, msg: []const u8) Error {
@setCold(true);
return vm.fatalExtra(.{ .data = msg });
}
pub fn fatalExtra(vm: *Vm, str: Value.String) Error {
@setCold(true);
try vm.errors.add(str, vm.line_loc, .err);
var i: u8 = 0;
while (vm.call_stack.popOrNull()) |frame| {
try vm.errors.add(.{ .data = "called here" }, frame.line_loc, .trace);
i += 1;
if (i > 32) {
try vm.errors.add(.{ .data = "too many calls, stopping now" }, frame.line_loc, .note);
break;
}
}
return error.RuntimeError;
}
/// Gets function `func_name` from map and calls it with `args`.
pub fn call(vm: *Vm, val: *Value, func_name: []const u8, args: anytype) !*Value {
std.debug.assert(vm.call_stack.items.len == 0); // vm must be in a callable state
if (val.* != .map) return error.NotAMap;
const index = Value.string(func_name);
const member = val.map.get(&index) orelse
return error.NoSuchMember;
switch (member.*) {
.func => |*func| {
if (func.arg_count != args.len) {
// TODO improve this error message to tell the expected and given counts
return error.InvalidArgCount;
}
// prepare arguments
inline for (args) |arg, i| {
const loc = try vm.gc.stackRef(i);
loc.* = try Value.zigToBog(vm, arg);
}
var frame: FunctionFrame = undefined;
frame.this = val;
try vm.call_stack.append(vm.gc.gpa, frame);
vm.sp = 0;
vm.ip = func.offset;
return try vm.exec(func.module);
},
.native => return error.NativeFunctionsUnsupported, // TODO
else => return error.NotAFunction,
}
}
}; | src/vm.zig |
const aoc = @import("../aoc.zig");
const std = @import("std");
const HeightMap = std.AutoHashMap(aoc.Coord, u8);
pub fn run(problem: *aoc.Problem) !aoc.Solution {
var heights = HeightMap.init(problem.allocator);
defer heights.deinit();
var row: isize = 0;
while (problem.line()) |line| {
var col: isize = 0;
for (line) |h| {
try heights.putNoClobber(aoc.Coord.init(.{row, col}), h - '0');
col += 1;
}
row += 1;
}
var risk_level: usize = 0;
var basin_sizes = std.ArrayList(usize).init(problem.allocator);
defer basin_sizes.deinit();
var iter = heights.iterator();
blk: while (iter.next()) |kv| {
for (getNeighbors(kv.key_ptr.*)) |neighbor| {
if (heights.get(neighbor)) |h| {
if (h <= kv.value_ptr.*) {
continue :blk;
}
}
}
risk_level += kv.value_ptr.* + 1;
try basin_sizes.append(try calcBasinSize(problem.allocator, &heights, kv.key_ptr.*));
}
std.sort.sort(usize, basin_sizes.items, {}, comptime std.sort.desc(usize));
const basin_product = basin_sizes.items[0] * basin_sizes.items[1] * basin_sizes.items[2];
return problem.solution(risk_level, basin_product);
}
fn getNeighbors(coord: aoc.Coord) [4]aoc.Coord {
return [_] aoc.Coord {
coord.add(aoc.PredefinedCoord.UP),
coord.add(aoc.PredefinedCoord.DOWN),
coord.add(aoc.PredefinedCoord.LEFT),
coord.add(aoc.PredefinedCoord.RIGHT),
};
}
fn calcBasinSize(allocator: std.mem.Allocator, heights: *const HeightMap, low_point: aoc.Coord) !usize {
var basin_points = std.AutoHashMap(aoc.Coord, void).init(allocator);
defer basin_points.deinit();
var unprocessed_points = std.ArrayList(aoc.Coord).init(allocator);
defer unprocessed_points.deinit();
try unprocessed_points.append(low_point);
while (unprocessed_points.items.len != 0) {
const coord = unprocessed_points.pop();
if ((try basin_points.fetchPut(coord, {})) != null) {
continue;
}
for (getNeighbors(coord)) |neighbor| {
if (heights.get(neighbor)) |h| {
if (h < 9) {
try unprocessed_points.append(neighbor);
}
}
}
}
return basin_points.count();
} | src/main/zig/2021/day09.zig |
const std = @import("std");
const Allocator = std.mem.Allocator;
pub const LineIterator = struct {
buffer: []u8,
index: usize,
const Self = @This();
/// Returns the next line
pub fn next(self: *Self) ?[]u8 {
if (self.index == self.buffer.len) {
return null;
}
const start = self.index;
while (
self.index < self.buffer.len and
self.buffer[self.index] != '\r' and
self.buffer[self.index] != '\n'
) : (self.index += 1) {}
const end = self.index;
if (self.index < self.buffer.len and self.buffer[self.index] == '\r') {
self.index += 1;
}
if (self.index < self.buffer.len and self.buffer[self.index] == '\n') {
self.index += 1;
}
return self.buffer[start..end];
}
};
pub fn iterate_lines(buffer: []u8) LineIterator {
return .{
.index = 0,
.buffer = buffer,
};
}
pub const InputError = error{
ReadFail,
};
pub const FileLineIterator = struct {
allocator: *Allocator,
buffer: []u8,
lines_it: LineIterator,
const Self = @This();
/// Returns the next line
pub fn next(self: *Self) ?[]u8 {
return self.lines_it.next();
}
pub fn deinit(self: *Self) void {
self.allocator.free(self.buffer);
}
};
pub fn iterateLinesInFile(allocator: *Allocator, file_path: []const u8) anyerror!FileLineIterator {
const file = try std.fs.cwd().openFile(file_path, .{});
defer file.close();
const buffer_size = 1024 * 1024;
const buffer = try allocator.alloc(u8, buffer_size);
const bytes_read = try file.readAll(buffer);
if (bytes_read == buffer_size) {
std.log.err("File too large :(", .{});
return error.ReadFail;
}
const data = buffer[0..bytes_read];
var lines_it = iterate_lines(data);
return FileLineIterator {
.allocator = allocator,
.buffer = buffer,
.lines_it = lines_it
};
}
const writer = std.io.getStdOut().writer();
pub fn print(comptime format: []const u8, args: anytype) void {
writer.print(format, args) catch return;
_ = writer.write("\n") catch return;
} | shared/utils.zig |
const std = @import("std");
const math = std.math;
const data = @embedFile("input.txt");
const STEPS = std.math.maxInt(i32);
// const STEPS = 1000;
const Node = struct {
height: u16 = 9,
on_path: bool = false,
};
const Point = struct {
x: i32 = 0,
y: i32 = 0,
fn equal(self: *const Point, other: *const Point) bool {
return self.x == other.x and self.y == other.y;
}
fn neighbours(self: *Point) [4]Point {
return [4]Point{
Point{ .x = self.x, .y = self.y - 1 },
Point{ .x = self.x + 1, .y = self.y },
Point{ .x = self.x, .y = self.y + 1 },
Point{ .x = self.x - 1, .y = self.y },
};
}
fn distance(self: *const Point, other: *Point) i32 {
return abs(self.x - other.x) + abs(self.y - other.y);
}
};
const PathNode = struct {
point: Point = Point{},
f: i32 = 0,
parent: ?*PathNode = null,
};
const Map = struct {
nodes: [16384]Node,
len: usize,
w: usize,
h: usize,
fn inBounds(self: *Map, point: Point) bool {
return point.x >= 0 and point.x < self.w and point.y >= 0 and point.y < self.h;
}
fn getNode(self: *Map, point: Point) *Node {
return &self.nodes[@intCast(usize, point.x) + (@intCast(usize, point.y) * self.w)];
}
fn getNodeBounded(self: *Map, point: Point) ?*Node {
if (!inBounds(self, point)) return null;
return &self.nodes[@intCast(usize, point.x) + (@intCast(usize, point.y) * self.w)];
}
};
inline fn collectMap() Map {
var map = Map{
.nodes = [_]Node{Node{}} ** 16384,
.len = 0,
.w = 0,
.h = 0,
};
var line_iter = std.mem.split(data, "\n");
while(line_iter.next()) |line| {
if (line.len > 0) {
map.w = line.len;
map.h += 1;
for(line) |c| {
map.nodes[map.len].height = c - '0';
map.len += 1;
}
}
}
return map;
}
inline fn find(arr: *std.ArrayListUnmanaged(*Cell), p: *const Cell) ?*const Cell {
for(arr.*.items) |it| {
if (it.*.point.x == p.*.point.x and it.*.point.y == p.*.point.y) return it;
}
return null;
}
inline fn abs(a: i32) i32 {
return (math.absInt(a) catch unreachable);
}
fn neighbours(map: *Map, q: *Cell) [4]?Cell {
var i: usize = 0;
var result = [_]?Cell{null} ** 4;
var dirs = directions(q.*.point.x, q.*.point.y);
while(i < 4) : (i += 1) {
var point = dirs[i];
if (q.parent) |p| {
if (eqlPoint(p.point, point)) continue;
}
if (in_bounds(point.x, point.y, map.*.w, map.*.h)) {
result[i] = Cell{
.node = &map.*.nodes[i_xy(point.x, point.y, map.*.w)],
.point = point,
.parent = q
};
}
}
return result;
}
inline fn heuristic(f: i32, h: i32, p: *const Point, start: *Point, goal: *Point) i32 {
return f + h; //Dijkstra
// return f + h + p.distance(start) + p.distance(goal); // A*
}
fn compareF(a: *PathNode, b: *PathNode) std.math.Order {
return std.math.order(a.f, b.f);
}
const EvalNode = struct {
f: i32,
closed: bool,
};
fn path02(alloc: *std.mem.Allocator, map: *Map, start: *Point, goal: *Point) !usize {
var open = std.PriorityQueue(*PathNode).init(alloc, compareF);
var evalNodes = std.AutoHashMap(Point, EvalNode).init(alloc);
var begin = PathNode{ .point = start.* };
try open.add(&begin);
var end = eval: {
var step: i32 = 0;
while (open.len > 0 and step < STEPS) {
var q = open.remove();
// std.debug.print("{any}, F{d}\n", .{q.point, q.f});
for (q.point.neighbours()) |p| {
if (p.equal(goal)) {
break :eval PathNode{.point = p, .parent = q};
}
if (q.parent) |parent| {
if (p.equal(&parent.point)) continue;
}
if (map.getNodeBounded(p)) |n| {
var f = heuristic(q.f, n.height, &p, start, goal);
if (!evalNodes.contains(p)) {
try evalNodes.put(p, .{.f = f, .closed = false});
} else {
var ptr = evalNodes.getPtr(p).?;
if (ptr.f <= f) continue;
if (!ptr.closed) {
ptr.f = f;
}
}
var np = try alloc.create(PathNode);
np.point = p;
np.f = f;
np.parent = q;
// std.debug.print(" -> {any}, F{d}\n", .{np.point, np.f});
try open.add(np);
}
}
if (!evalNodes.contains(q.point)) {
try evalNodes.put(q.point, .{.f = q.f, .closed = true});
} else {
evalNodes.getPtr(q.point).?.closed = true;
}
step += 1;
}
std.debug.print("EVERYTHING'S FUCKED\n", .{});
break :eval begin;
};
var total_risk: usize = 0;
var cur: ?*PathNode = &end;
while(cur) |p| {
std.debug.print("{any}\n", .{ p });
var n = map.getNode(p.point);
total_risk += n.height;
n.on_path = true;
cur = p.parent;
}
total_risk -= map.nodes[0].height;
return total_risk;
}
pub fn main() !void {
var arena = std.heap.ArenaAllocator.init(std.heap.page_allocator);
var alloc = &arena.allocator;
defer arena.deinit();
var map = collectMap();
var start = Point{};
var goal = Point{.x = @intCast(i32, map.w - 1), .y = @intCast(i32, map.h - 1)};
var total_risk = try path02(alloc, &map, &start, &goal);
var stdout = std.io.getStdOut();
var i: usize = 0;
var len = map.w * map.h;
while(i < len) : (i += 1) {
if (i % map.w == 0)
std.debug.print("\n", .{});
if (map.nodes[i].on_path) {
std.debug.print("\x1b[31;1m{d}\x1b[0m ", .{map.nodes[i].height});
} else {
std.debug.print("{d} ", .{map.nodes[i].height});
}
}
std.debug.print("\nTotal risk: {d}\n", .{total_risk});
} | day15/main.zig |
const MMIO = @import("mmio.zig").MMIO;
pub const PINB = MMIO(0x23, u8, packed struct {
PINB0: u1 = 0,
PINB1: u1 = 0,
PINB2: u1 = 0,
PINB3: u1 = 0,
PINB4: u1 = 0,
PINB5: u1 = 0,
PINB6: u1 = 0,
PINB7: u1 = 0,
});
pub const DDRB = MMIO(0x24, u8, packed struct {
DDB0: u1 = 0,
DDB1: u1 = 0,
DDB2: u1 = 0,
DDB3: u1 = 0,
DDB4: u1 = 0,
DDB5: u1 = 0,
DDB6: u1 = 0,
DDB7: u1 = 0,
});
pub const PORTB = MMIO(0x25, u8, packed struct {
PORTB0: u1 = 0,
PORTB1: u1 = 0,
PORTB2: u1 = 0,
PORTB3: u1 = 0,
PORTB4: u1 = 0,
PORTB5: u1 = 0,
PORTB6: u1 = 0,
PORTB7: u1 = 0,
});
pub const PINC = MMIO(0x26, u8, packed struct {
PINC0: u1 = 0,
PINC1: u1 = 0,
PINC2: u1 = 0,
PINC3: u1 = 0,
PINC4: u1 = 0,
PINC5: u1 = 0,
PINC6: u1 = 0,
PINC7: u1 = 0,
});
pub const DDRC = MMIO(0x27, u8, packed struct {
DDC0: u1 = 0,
DDC1: u1 = 0,
DDC2: u1 = 0,
DDC3: u1 = 0,
DDC4: u1 = 0,
DDC5: u1 = 0,
DDC6: u1 = 0,
DDC7: u1 = 0,
});
pub const PORTC = MMIO(0x28, u8, packed struct {
PORTC0: u1 = 0,
PORTC1: u1 = 0,
PORTC2: u1 = 0,
PORTC3: u1 = 0,
PORTC4: u1 = 0,
PORTC5: u1 = 0,
PORTC6: u1 = 0,
PORTC7: u1 = 0,
});
pub const PIND = MMIO(0x29, u8, packed struct {
PIND0: u1 = 0,
PIND1: u1 = 0,
PIND2: u1 = 0,
PIND3: u1 = 0,
PIND4: u1 = 0,
PIND5: u1 = 0,
PIND6: u1 = 0,
PIND7: u1 = 0,
});
pub const DDRD = MMIO(0x2A, u8, packed struct {
DDD0: u1 = 0,
DDD1: u1 = 0,
DDD2: u1 = 0,
DDD3: u1 = 0,
DDD4: u1 = 0,
DDD5: u1 = 0,
DDD6: u1 = 0,
DDD7: u1 = 0,
});
pub const PORTD = MMIO(0x2B, u8, packed struct {
PORTD0: u1 = 0,
PORTD1: u1 = 0,
PORTD2: u1 = 0,
PORTD3: u1 = 0,
PORTD4: u1 = 0,
PORTD5: u1 = 0,
PORTD6: u1 = 0,
PORTD7: u1 = 0,
});
//Timers
pub const TCCR2B = MMIO(0xB1, u8, packed struct {
CS20: u1 = 0,
CS21: u1 = 0,
CS22: u1 = 0,
WGM22: u1 = 0,
_1: u1 = 0,
_2: u1 = 0,
FOC2B: u1 = 0,
FOC2A: u1 = 0,
});
pub const TCCR2A = MMIO(0xB0, u8, packed struct {
WGM20: u1 = 0,
WGM21: u1 = 0,
_1: u1 = 0,
_2: u1 = 0,
COM2B0: u1 = 0,
COM2B1: u1 = 0,
COM2A0: u1 = 0,
COM2A1: u1 = 0,
});
//Timer counter 1 16-bit
pub const TCCR1C = MMIO(0x82, u8, packed struct {
FOC1A: u1 = 0,
FOC1B: u1 = 0,
_1: u1 = 0,
_2: u1 = 0,
_3: u1 = 0,
_4: u1 = 0,
_5: u1 = 0,
_6: u1 = 0,
});
pub const TCCR1B = MMIO(0x81, u16, packed struct {
ICNC1: u1 = 0,
ICES1: u1 = 0,
_1: u1 = 0,
WGM13: u1 = 0,
WGM12: u1 = 0,
CS12: u1 = 0,
CS11: u1 = 0,
CS10: u1 = 0,
});
pub const TCCR1A = MMIO(0x80, u16, packed struct {
COM1A1: u1 = 0,
COM1A0: u1 = 0,
COM1B1: u1 = 0,
COM1B0: u1 = 0,
_1: u1 = 0,
_2: u1 = 0,
WGM11: u1 = 0,
WGM10: u1 = 0,
});
//Timer counter 2 8-bit
pub const TCNT2 = @intToPtr(*volatile u8, 0xB2);
// Compare registers
pub const OCR2B = @intToPtr(*volatile u8, 0xB4);
pub const OCR2A = @intToPtr(*volatile u8, 0xB3);
//Timer counter 0 8-bit
pub const TCNT0 = @intToPtr(*volatile u8, 0x46);
// Compare Registers
pub const OCR0B = @intToPtr(*volatile u8, 0x47);
pub const OCR0A = @intToPtr(*volatile u8, 0x46);
//Timer counter 1 16-bit
pub const OCR1BH = @intToPtr(*volatile u16, 0x8B);
pub const OCR1BL = @intToPtr(*volatile u16, 0x8A);
pub const OCR1AH = @intToPtr(*volatile u16, 0x89);
pub const OCR1AL = @intToPtr(*volatile u16, 0x88);
pub const ICR1H = @intToPtr(*volatile u16, 0x87);
pub const ICR1L = @intToPtr(*volatile u16, 0x86);
pub const TCNT1H = @intToPtr(*volatile u16, 0x85);
pub const TCNT1L = @intToPtr(*volatile u16, 0x84);
pub fn pinMode(comptime pin: comptime_int, comptime mode: enum { input, output, input_pullup }) void {
switch (pin) {
0...7 => {
var val = DDRD.readInt();
if (mode == .output) {
val |= 1 << (pin - 0);
} else {
val &= ~@as(u8, 1 << (pin - 0));
}
DDRD.writeInt(val);
},
8...13 => {
var val = DDRB.readInt();
if (mode == .output) {
val |= 1 << (pin - 8);
} else {
val &= ~@as(u8, 1 << (pin - 8));
}
DDRB.writeInt(val);
},
14...19 => {
var val = DDRC.readInt();
if (mode == .output) {
val |= 1 << (pin - 14);
} else {
val &= ~@as(u8, 1 << (pin - 14));
}
DDRC.writeInt(val);
},
else => @compileError("Only port B, C and D are available yet (arduino pins 0 through 19)."),
}
if (mode == .input_pullup) {
digitalWrite(pin, .high);
} else {
digitalWrite(pin, .low);
}
}
pub fn digitalWrite(comptime pin: comptime_int, comptime value: enum { low, high }) void {
switch (pin) {
0...7 => {
var val = PORTD.readInt();
if (value == .high) {
val |= 1 << (pin - 0);
} else {
val &= ~@as(u8, 1 << (pin - 0));
}
PORTD.writeInt(val);
},
8...13 => {
var val = PORTB.readInt();
if (value == .high) {
val |= 1 << (pin - 8);
} else {
val &= ~@as(u8, 1 << (pin - 8));
}
PORTB.writeInt(val);
},
14...19 => {
var val = PORTC.readInt();
if (value == .high) {
val |= 1 << (pin - 14);
} else {
val &= ~@as(u8, 1 << (pin - 14));
}
PORTC.writeInt(val);
},
else => @compileError("Only port B, C and D are available yet (arduino pins 0 through 19)."),
}
}
pub fn digitalRead(comptime pin: comptime_int) bool {
switch (pin) {
0...7 => {
var val: u8 = PIND.readInt();
return (val & (1 << (pin - 0))) != 0;
},
8...13 => {
var val = PINB.readInt();
return (val & (1 << (pin - 8))) != 0;
},
14...19 => {
var val = PINC.readInt();
return (val & (1 << (pin - 14))) != 0;
},
else => @compileError("Only port B, C and D are available yet (arduino pins 0 through 19)."),
}
}
pub fn analogWrite(comptime pin: comptime_int, value: u8) void {
pinMode(pin, .output);
TCCR1A.writeInt(0b10000010);
TCCR1B.writeInt(0b00010001);
if (value == 0) {
digitalWrite(pin, .low);
} else if (value == 255) {
digitalWrite(pin, .high);
}
switch (pin) {
3 => {
//Timer 2
OCR0A.* = value;
},
11 => {
//Timer 2
OCR0B.* = value;
},
5 => {
//Timer 0
OCR2A.* = value;
},
6 => {
//Timer 0
OCR2B.* = value;
},
9 => {
//Timer 1
ICR1L.* = 255;
OCR1AL.* = value;
},
10 => {
//Timer 1
ICR1L.* = 255;
OCR1BL.* = value;
},
else => @compileError("Not valid PWM pin (allowed pins 3,5,6,9,10,11)."),
}
}
pub fn delayCycles(cycles: u32) void {
var count: u32 = 0;
while (count < cycles) : (count += 1) {
asm volatile ("nop");
}
}
pub fn delay(ms: u32) void {
var i: u32 = ms << 4;
while (i > 0) {
var c: u8 = 255;
// We decrement c to 0.
// This takes cycles * 256 / F_CPU miliseconds.
asm volatile (
\\1:
\\ dec %[c]
\\ nop
\\ brne 1b
:
: [c] "r" (c)
);
i -= 1;
}
} | boilerplate/gpio.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/day06.txt", run);
pub fn run(input: []const u8, gpa: std.mem.Allocator) tools.RunError![2][]const u8 {
// var arena = std.heap.ArenaAllocator.init(gpa);
//defer arena.deinit();
//const allocator = arena.allocator();
const LanternFishList = std.ArrayList(u4);
var list0 = LanternFishList.init(gpa);
defer list0.deinit();
{
try list0.ensureTotalCapacity(input.len / 2);
var it = std.mem.tokenize(u8, input, ", \t\n\r");
while (it.next()) |num| {
try list0.append(try std.fmt.parseInt(u4, num, 10));
}
}
// descendants = f([generation][age])
const descendants = blk: {
var _descendants: [257][9]u64 = undefined;
std.mem.set(u64, &_descendants[0], 1);
var gen: u32 = 1;
while (gen <= 256) : (gen += 1) {
for (_descendants[gen]) |*pop, age| {
pop.* = switch (age) {
0 => _descendants[gen - 1][6] + _descendants[gen - 1][8],
else => _descendants[gen - 1][age - 1],
};
}
}
break :blk _descendants;
};
const ans = ans: {
var list1 = LanternFishList.init(gpa);
defer list1.deinit();
var list2 = LanternFishList.init(gpa);
defer list2.deinit();
try list1.appendSlice(list0.items);
const pinpong = [2]*LanternFishList{ &list1, &list2 };
var gen: u32 = 0;
while (gen < 80) : (gen += 1) {
const cur = pinpong[gen % 2];
const next = pinpong[1 - gen % 2];
{
var total: u64 = 0;
for (list0.items) |it| {
total += descendants[gen][it];
}
assert(total == cur.items.len);
}
next.clearRetainingCapacity();
for (cur.items) |it| {
switch (it) {
0 => {
try next.append(6);
try next.append(8);
},
else => {
try next.append(it - 1);
},
}
}
// trace("gen #{} : {} [", .{gen,next.items.len} );
// for (next.items) |it| {
// trace("{},", .{it});
// }
// trace("]\n", .{});
}
break :ans pinpong[gen % 2].items.len;
};
const ans2 = ans: {
var total: u64 = 0;
for (list0.items) |it| {
total += descendants[256][it];
}
break :ans total;
};
return [_][]const u8{
try std.fmt.allocPrint(gpa, "{}", .{ans}),
try std.fmt.allocPrint(gpa, "{}", .{ans2}),
};
}
test {
const res = try run("3,4,3,1,2", std.testing.allocator);
defer std.testing.allocator.free(res[0]);
defer std.testing.allocator.free(res[1]);
try std.testing.expectEqualStrings("5934", res[0]);
try std.testing.expectEqualStrings("26984457539", res[1]);
} | 2021/day06.zig |
const std = @import("std");
const tools = @import("tools");
const with_trace = true;
const assert = std.debug.assert;
fn trace(comptime fmt: []const u8, args: anytype) void {
if (with_trace) std.debug.print(fmt, args);
}
fn regIndex(name: []const u8) u32 {
var num: u32 = 0;
for (name) |c| {
num = (num * 27) + c - 'a';
}
return num;
}
pub fn main() anyerror!void {
const stdout = std.io.getStdOut().writer();
var arena = std.heap.ArenaAllocator.init(std.heap.page_allocator);
defer arena.deinit();
const allocator = arena.allocator();
//const limit = 1 * 1024 * 1024 * 1024;
//const text = try std.fs.cwd().readFileAlloc(allocator, "day9.txt", limit);
//defer allocator.free(text);
const lengths1 = [_]u32{ 18, 1, 0, 161, 255, 137, 254, 252, 14, 95, 165, 33, 181, 168, 2, 188 };
//const lengths2 = "AoC 2017" ++ [_]u8{ 17, 31, 73, 47, 23 };
const lengths2 = "18,1,0,161,255,137,254,252,14,95,165,33,181,168,2,188" ++ [_]u8{ 17, 31, 73, 47, 23 };
const mod = 256;
var list = comptime blk: {
var l: [mod]u8 = undefined;
for (l) |*e, i| {
e.* = @intCast(u8, i);
}
break :blk l;
};
var skip: u32 = 0;
var cursor: u32 = 0;
var round: u32 = 0;
while (round < 64) : (round += 1) {
for (lengths2) |l| {
// reverse list[cursor..cursor+l%mod]
var i: u32 = 0;
while (i < l / 2) : (i += 1) {
const t = list[(cursor + i) % mod];
list[(cursor + i) % mod] = list[(cursor + ((l - 1) - i)) % mod];
list[(cursor + ((l - 1) - i)) % mod] = t;
}
// cursor %+= l+skip %mod
cursor = (cursor + l + skip) % mod;
// skip ++
skip += 1;
}
}
const hextochar = "0123456789abcdef";
var hash: [32]u8 = undefined;
var accu: u8 = 0;
for (list) |l, i| {
accu ^= l;
if ((i + 1) % 16 == 0) {
hash[2 * (i / 16) + 0] = hextochar[(accu / 16) % 16];
hash[2 * (i / 16) + 1] = hextochar[accu % 16];
accu = 0;
}
}
try stdout.print("list={}, {}, {}, ... -> {}\nhash={}\n", .{ list[0], list[1], list[2], @intCast(u32, list[0]) * @intCast(u32, list[1]), hash });
} | 2017/day10.zig |
const std = @import("std");
const strings = @import("strings.zig");
const math = std.math;
const testing = std.testing;
const warn = std.debug.warn;
test "StringFinder.next" {
var a = std.debug.global_allocator;
const TestCase = struct {
pattern: []const u8,
text: []const u8,
index: ?usize,
const Self = @This();
fn init(pattern: []const u8, text: []const u8, index: ?usize) Self {
return Self{
.pattern = pattern,
.text = text,
.index = index,
};
}
};
const sample = [_]TestCase{
TestCase.init("", "", 0),
TestCase.init("", "abc", 0),
TestCase.init("abc", "", null),
TestCase.init("abc", "abc", 0),
TestCase.init("d", "abcdefg", 3),
TestCase.init("nan", "banana", 2),
TestCase.init("pan", "anpanman", 2),
TestCase.init("nnaaman", "anpanmanam", null),
TestCase.init("abcd", "abc", null),
TestCase.init("abcd", "bcd", null),
TestCase.init("bcd", "abcd", 1),
TestCase.init("abc", "acca", null),
TestCase.init("aa", "aaa", 0),
TestCase.init("baa", "aaaaa", null),
TestCase.init("at that", "which finally halts. at that point", 22),
};
for (sample) |ts, i| {
if (i != 4) {
continue;
}
const idx = try strings.stringFind(a, ts.pattern, ts.text);
std.testing.expectEqual(ts.index, idx);
}
}
test "StringFinder.init" {
var a = std.debug.global_allocator;
const TestCase = struct {
pattern: []const u8,
bad: [256]usize,
suf: []const usize,
const Self = @This();
fn init(pattern: []const u8, bad: [256]usize, suf: []const usize) Self {
return Self{
.pattern = pattern,
.bad = bad,
.suf = suf,
};
}
};
const sample = [_]TestCase{
TestCase.init("abc", bad1, [_]usize{ 5, 4, 1 }),
TestCase.init("mississi", bad2, [_]usize{ 5, 14, 13, 7, 11, 10, 7, 1 }),
TestCase.init("abcxxxabc", bad3, [_]usize{ 14, 13, 12, 11, 10, 9, 11, 10, 1 }),
TestCase.init("abyxcdeyx", bad4, [_]usize{ 7, 16, 15, 14, 13, 12, 7, 10, 1 }),
};
for (sample) |ts, idx| {
var f = &try strings.StringFinder.init(a, ts.pattern);
for (f.bad_char_skip) |c, i| {
var want = ts.bad[i];
if (want == 0) {
want = ts.pattern.len;
}
testing.expectEqual(c, want);
}
f.deinit();
}
}
const bad1 = blk: {
var a: [256]usize = undefined;
a['a'] = 2;
a['b'] = 1;
a['c'] = 3;
break :blk a;
};
const bad2 = blk: {
var a: [256]usize = undefined;
a['i'] = 3;
a['m'] = 7;
a['s'] = 1;
break :blk a;
};
const bad3 = blk: {
var a: [256]usize = undefined;
a['a'] = 2;
a['b'] = 1;
a['c'] = 6;
a['x'] = 3;
break :blk a;
};
const bad4 = blk: {
var a: [256]usize = undefined;
a['a'] = 8;
a['b'] = 7;
a['c'] = 4;
a['d'] = 3;
a['e'] = 2;
a['y'] = 1;
a['x'] = 5;
break :blk a;
};
fn testReplacer(buf: *std.Buffer, r: *strings.StringReplacer, text: []const u8, final: []const u8) !void {
try buf.resize(0);
try r.replace(text, buf);
if (!buf.eql(final)) {
warn("expectt {} got {}\n", final, buf.toSlice());
}
testing.expect(buf.eql(final));
}
test "Replacer" {
var a = std.heap.direct_allocator;
var html_escaper = &try strings.StringReplacer.init(a, [_][]const u8{
"&", "&",
"<", "<",
">", ">",
"\"", """,
"'", "'",
});
defer html_escaper.deinit();
var html_unescaper = &try strings.StringReplacer.init(a, [_][]const u8{
"&", "&",
"<", "<",
">", ">",
""", "\"",
"'", "'",
});
defer html_unescaper.deinit();
var capital_letters = &try strings.StringReplacer.init(a, [_][]const u8{
"a", "A",
"b", "B",
});
defer capital_letters.deinit();
var buf = &try std.Buffer.init(a, "");
defer buf.deinit();
const s = [_][]const u8{
[_]u8{0x0}, [_]u8{0x1}, [_]u8{0x1},
[_]u8{0x2}, [_]u8{0x2}, [_]u8{0x3},
[_]u8{0x3}, [_]u8{0x4}, [_]u8{0x4},
[_]u8{0x5}, [_]u8{0x5}, [_]u8{0x6},
[_]u8{0x6}, [_]u8{0x7}, [_]u8{0x7},
[_]u8{0x8}, [_]u8{0x8}, [_]u8{0x9},
[_]u8{0x9}, [_]u8{0xa}, [_]u8{0xa},
[_]u8{0xb}, [_]u8{0xb}, [_]u8{0xc},
[_]u8{0xc}, [_]u8{0xd}, [_]u8{0xd},
[_]u8{0xe}, [_]u8{0xe}, [_]u8{0xf},
[_]u8{0xf}, [_]u8{0x10}, [_]u8{0x10},
[_]u8{0x11}, [_]u8{0x11}, [_]u8{0x12},
[_]u8{0x12}, [_]u8{0x13}, [_]u8{0x13},
[_]u8{0x14}, [_]u8{0x14}, [_]u8{0x15},
[_]u8{0x15}, [_]u8{0x16}, [_]u8{0x16},
[_]u8{0x17}, [_]u8{0x17}, [_]u8{0x18},
[_]u8{0x18}, [_]u8{0x19}, [_]u8{0x19},
[_]u8{0x1a}, [_]u8{0x1a}, [_]u8{0x1b},
[_]u8{0x1b}, [_]u8{0x1c}, [_]u8{0x1c},
[_]u8{0x1d}, [_]u8{0x1d}, [_]u8{0x1e},
[_]u8{0x1e}, [_]u8{0x1f}, [_]u8{0x1f},
[_]u8{0x20}, [_]u8{0x20}, [_]u8{0x21},
[_]u8{0x21}, [_]u8{0x22}, [_]u8{0x22},
[_]u8{0x23}, [_]u8{0x23}, [_]u8{0x24},
[_]u8{0x24}, [_]u8{0x25}, [_]u8{0x25},
[_]u8{0x26}, [_]u8{0x26}, [_]u8{0x27},
[_]u8{0x27}, [_]u8{0x28}, [_]u8{0x28},
[_]u8{0x29}, [_]u8{0x29}, [_]u8{0x2a},
[_]u8{0x2a}, [_]u8{0x2b}, [_]u8{0x2b},
[_]u8{0x2c}, [_]u8{0x2c}, [_]u8{0x2d},
[_]u8{0x2d}, [_]u8{0x2e}, [_]u8{0x2e},
[_]u8{0x2f}, [_]u8{0x2f}, [_]u8{0x30},
[_]u8{0x30}, [_]u8{0x31}, [_]u8{0x31},
[_]u8{0x32}, [_]u8{0x32}, [_]u8{0x33},
[_]u8{0x33}, [_]u8{0x34}, [_]u8{0x34},
[_]u8{0x35}, [_]u8{0x35}, [_]u8{0x36},
[_]u8{0x36}, [_]u8{0x37}, [_]u8{0x37},
[_]u8{0x38}, [_]u8{0x38}, [_]u8{0x39},
[_]u8{0x39}, [_]u8{0x3a}, [_]u8{0x3a},
[_]u8{0x3b}, [_]u8{0x3b}, [_]u8{0x3c},
[_]u8{0x3c}, [_]u8{0x3d}, [_]u8{0x3d},
[_]u8{0x3e}, [_]u8{0x3e}, [_]u8{0x3f},
[_]u8{0x3f}, [_]u8{0x40}, [_]u8{0x40},
[_]u8{0x41}, [_]u8{0x41}, [_]u8{0x42},
[_]u8{0x42}, [_]u8{0x43}, [_]u8{0x43},
[_]u8{0x44}, [_]u8{0x44}, [_]u8{0x45},
[_]u8{0x45}, [_]u8{0x46}, [_]u8{0x46},
[_]u8{0x47}, [_]u8{0x47}, [_]u8{0x48},
[_]u8{0x48}, [_]u8{0x49}, [_]u8{0x49},
[_]u8{0x4a}, [_]u8{0x4a}, [_]u8{0x4b},
[_]u8{0x4b}, [_]u8{0x4c}, [_]u8{0x4c},
[_]u8{0x4d}, [_]u8{0x4d}, [_]u8{0x4e},
[_]u8{0x4e}, [_]u8{0x4f}, [_]u8{0x4f},
[_]u8{0x50}, [_]u8{0x50}, [_]u8{0x51},
[_]u8{0x51}, [_]u8{0x52}, [_]u8{0x52},
[_]u8{0x53}, [_]u8{0x53}, [_]u8{0x54},
[_]u8{0x54}, [_]u8{0x55}, [_]u8{0x55},
[_]u8{0x56}, [_]u8{0x56}, [_]u8{0x57},
[_]u8{0x57}, [_]u8{0x58}, [_]u8{0x58},
[_]u8{0x59}, [_]u8{0x59}, [_]u8{0x5a},
[_]u8{0x5a}, [_]u8{0x5b}, [_]u8{0x5b},
[_]u8{0x5c}, [_]u8{0x5c}, [_]u8{0x5d},
[_]u8{0x5d}, [_]u8{0x5e}, [_]u8{0x5e},
[_]u8{0x5f}, [_]u8{0x5f}, [_]u8{0x60},
[_]u8{0x60}, [_]u8{0x61}, [_]u8{0x61},
[_]u8{0x62}, [_]u8{0x62}, [_]u8{0x63},
[_]u8{0x63}, [_]u8{0x64}, [_]u8{0x64},
[_]u8{0x65}, [_]u8{0x65}, [_]u8{0x66},
[_]u8{0x66}, [_]u8{0x67}, [_]u8{0x67},
[_]u8{0x68}, [_]u8{0x68}, [_]u8{0x69},
[_]u8{0x69}, [_]u8{0x6a}, [_]u8{0x6a},
[_]u8{0x6b}, [_]u8{0x6b}, [_]u8{0x6c},
[_]u8{0x6c}, [_]u8{0x6d}, [_]u8{0x6d},
[_]u8{0x6e}, [_]u8{0x6e}, [_]u8{0x6f},
[_]u8{0x6f}, [_]u8{0x70}, [_]u8{0x70},
[_]u8{0x71}, [_]u8{0x71}, [_]u8{0x72},
[_]u8{0x72}, [_]u8{0x73}, [_]u8{0x73},
[_]u8{0x74}, [_]u8{0x74}, [_]u8{0x75},
[_]u8{0x75}, [_]u8{0x76}, [_]u8{0x76},
[_]u8{0x77}, [_]u8{0x77}, [_]u8{0x78},
[_]u8{0x78}, [_]u8{0x79}, [_]u8{0x79},
[_]u8{0x7a}, [_]u8{0x7a}, [_]u8{0x7b},
[_]u8{0x7b}, [_]u8{0x7c}, [_]u8{0x7c},
[_]u8{0x7d}, [_]u8{0x7d}, [_]u8{0x7e},
[_]u8{0x7e}, [_]u8{0x7f}, [_]u8{0x7f},
[_]u8{0x80}, [_]u8{0x80}, [_]u8{0x81},
[_]u8{0x81}, [_]u8{0x82}, [_]u8{0x82},
[_]u8{0x83}, [_]u8{0x83}, [_]u8{0x84},
[_]u8{0x84}, [_]u8{0x85}, [_]u8{0x85},
[_]u8{0x86}, [_]u8{0x86}, [_]u8{0x87},
[_]u8{0x87}, [_]u8{0x88}, [_]u8{0x88},
[_]u8{0x89}, [_]u8{0x89}, [_]u8{0x8a},
[_]u8{0x8a}, [_]u8{0x8b}, [_]u8{0x8b},
[_]u8{0x8c}, [_]u8{0x8c}, [_]u8{0x8d},
[_]u8{0x8d}, [_]u8{0x8e}, [_]u8{0x8e},
[_]u8{0x8f}, [_]u8{0x8f}, [_]u8{0x90},
[_]u8{0x90}, [_]u8{0x91}, [_]u8{0x91},
[_]u8{0x92}, [_]u8{0x92}, [_]u8{0x93},
[_]u8{0x93}, [_]u8{0x94}, [_]u8{0x94},
[_]u8{0x95}, [_]u8{0x95}, [_]u8{0x96},
[_]u8{0x96}, [_]u8{0x97}, [_]u8{0x97},
[_]u8{0x98}, [_]u8{0x98}, [_]u8{0x99},
[_]u8{0x99}, [_]u8{0x9a}, [_]u8{0x9a},
[_]u8{0x9b}, [_]u8{0x9b}, [_]u8{0x9c},
[_]u8{0x9c}, [_]u8{0x9d}, [_]u8{0x9d},
[_]u8{0x9e}, [_]u8{0x9e}, [_]u8{0x9f},
[_]u8{0x9f}, [_]u8{0xa0}, [_]u8{0xa0},
[_]u8{0xa1}, [_]u8{0xa1}, [_]u8{0xa2},
[_]u8{0xa2}, [_]u8{0xa3}, [_]u8{0xa3},
[_]u8{0xa4}, [_]u8{0xa4}, [_]u8{0xa5},
[_]u8{0xa5}, [_]u8{0xa6}, [_]u8{0xa6},
[_]u8{0xa7}, [_]u8{0xa7}, [_]u8{0xa8},
[_]u8{0xa8}, [_]u8{0xa9}, [_]u8{0xa9},
[_]u8{0xaa}, [_]u8{0xaa}, [_]u8{0xab},
[_]u8{0xab}, [_]u8{0xac}, [_]u8{0xac},
[_]u8{0xad}, [_]u8{0xad}, [_]u8{0xae},
[_]u8{0xae}, [_]u8{0xaf}, [_]u8{0xaf},
[_]u8{0xb0}, [_]u8{0xb0}, [_]u8{0xb1},
[_]u8{0xb1}, [_]u8{0xb2}, [_]u8{0xb2},
[_]u8{0xb3}, [_]u8{0xb3}, [_]u8{0xb4},
[_]u8{0xb4}, [_]u8{0xb5}, [_]u8{0xb5},
[_]u8{0xb6}, [_]u8{0xb6}, [_]u8{0xb7},
[_]u8{0xb7}, [_]u8{0xb8}, [_]u8{0xb8},
[_]u8{0xb9}, [_]u8{0xb9}, [_]u8{0xba},
[_]u8{0xba}, [_]u8{0xbb}, [_]u8{0xbb},
[_]u8{0xbc}, [_]u8{0xbc}, [_]u8{0xbd},
[_]u8{0xbd}, [_]u8{0xbe}, [_]u8{0xbe},
[_]u8{0xbf}, [_]u8{0xbf}, [_]u8{0xc0},
[_]u8{0xc0}, [_]u8{0xc1}, [_]u8{0xc1},
[_]u8{0xc2}, [_]u8{0xc2}, [_]u8{0xc3},
[_]u8{0xc3}, [_]u8{0xc4}, [_]u8{0xc4},
[_]u8{0xc5}, [_]u8{0xc5}, [_]u8{0xc6},
[_]u8{0xc6}, [_]u8{0xc7}, [_]u8{0xc7},
[_]u8{0xc8}, [_]u8{0xc8}, [_]u8{0xc9},
[_]u8{0xc9}, [_]u8{0xca}, [_]u8{0xca},
[_]u8{0xcb}, [_]u8{0xcb}, [_]u8{0xcc},
[_]u8{0xcc}, [_]u8{0xcd}, [_]u8{0xcd},
[_]u8{0xce}, [_]u8{0xce}, [_]u8{0xcf},
[_]u8{0xcf}, [_]u8{0xd0}, [_]u8{0xd0},
[_]u8{0xd1}, [_]u8{0xd1}, [_]u8{0xd2},
[_]u8{0xd2}, [_]u8{0xd3}, [_]u8{0xd3},
[_]u8{0xd4}, [_]u8{0xd4}, [_]u8{0xd5},
[_]u8{0xd5}, [_]u8{0xd6}, [_]u8{0xd6},
[_]u8{0xd7}, [_]u8{0xd7}, [_]u8{0xd8},
[_]u8{0xd8}, [_]u8{0xd9}, [_]u8{0xd9},
[_]u8{0xda}, [_]u8{0xda}, [_]u8{0xdb},
[_]u8{0xdb}, [_]u8{0xdc}, [_]u8{0xdc},
[_]u8{0xdd}, [_]u8{0xdd}, [_]u8{0xde},
[_]u8{0xde}, [_]u8{0xdf}, [_]u8{0xdf},
[_]u8{0xe0}, [_]u8{0xe0}, [_]u8{0xe1},
[_]u8{0xe1}, [_]u8{0xe2}, [_]u8{0xe2},
[_]u8{0xe3}, [_]u8{0xe3}, [_]u8{0xe4},
[_]u8{0xe4}, [_]u8{0xe5}, [_]u8{0xe5},
[_]u8{0xe6}, [_]u8{0xe6}, [_]u8{0xe7},
[_]u8{0xe7}, [_]u8{0xe8}, [_]u8{0xe8},
[_]u8{0xe9}, [_]u8{0xe9}, [_]u8{0xea},
[_]u8{0xea}, [_]u8{0xeb}, [_]u8{0xeb},
[_]u8{0xec}, [_]u8{0xec}, [_]u8{0xed},
[_]u8{0xed}, [_]u8{0xee}, [_]u8{0xee},
[_]u8{0xef}, [_]u8{0xef}, [_]u8{0xf0},
[_]u8{0xf0}, [_]u8{0xf1}, [_]u8{0xf1},
[_]u8{0xf2}, [_]u8{0xf2}, [_]u8{0xf3},
[_]u8{0xf3}, [_]u8{0xf4}, [_]u8{0xf4},
[_]u8{0xf5}, [_]u8{0xf5}, [_]u8{0xf6},
[_]u8{0xf6}, [_]u8{0xf7}, [_]u8{0xf7},
[_]u8{0xf8}, [_]u8{0xf8}, [_]u8{0xf9},
[_]u8{0xf9}, [_]u8{0xfa}, [_]u8{0xfa},
[_]u8{0xfb}, [_]u8{0xfb}, [_]u8{0xfc},
[_]u8{0xfc}, [_]u8{0xfd}, [_]u8{0xfd},
[_]u8{0xfe}, [_]u8{0xfe}, [_]u8{0xff},
[_]u8{0xff}, [_]u8{0x0},
};
var incl = &try strings.StringReplacer.init(a, s);
defer incl.deinit();
var simple = &try strings.StringReplacer.init(a, [_][]const u8{
"a", "1",
"a", "2",
});
defer simple.deinit();
var simple2 = &try strings.StringReplacer.init(a, [_][]const u8{
"a", "11",
"a", "22",
});
defer simple2.deinit();
const s2 = @import("sample.zig").sample;
var repeat = &try strings.StringReplacer.init(a, s2);
defer repeat.deinit();
try testReplacer(buf, html_escaper, "No changes", "No changes");
try testReplacer(buf, html_escaper, "I <3 escaping & stuff", "I <3 escaping & stuff");
try testReplacer(buf, html_escaper, "&&&", "&&&");
try testReplacer(buf, html_escaper, "", "");
try testReplacer(buf, capital_letters, "brad", "BrAd");
try testReplacer(buf, capital_letters, "", "");
try testReplacer(buf, incl, "brad", "csbe");
try testReplacer(buf, incl, "\x00\xff", "\x01\x00");
try testReplacer(buf, incl, "", "");
try testReplacer(buf, simple, "brad", "br1d");
try testReplacer(buf, repeat, "brad", "bbrrrrrrrrrrrrrrrrrradddd");
try testReplacer(buf, repeat, "abba", "abbbba");
try testReplacer(buf, repeat, "", "");
try testReplacer(buf, simple2, "brad", "br11d");
// try testReplacer(buf, html_unescaper, "&amp;", "&");
} | src/strings/strings_test.zig |
const std = @import("std");
const mem = std.mem;
const meta = std.meta;
const net = std.net;
const ArrayList = std.ArrayList;
usingnamespace @import("../frame.zig");
usingnamespace @import("../primitive_types.zig");
const testing = @import("../testing.zig");
/// AUTHENTICATE is sent by a node in response to a STARTUP frame if authentication is required.
///
/// Described in the protocol spec at §4.2.3.
pub const AuthenticateFrame = struct {
authenticator: []const u8,
pub fn read(allocator: *mem.Allocator, pr: *PrimitiveReader) !AuthenticateFrame {
return AuthenticateFrame{
.authenticator = try pr.readString(allocator),
};
}
};
/// AUTH_RESPONSE is sent to a node to answser a authentication challenge.
///
/// Described in the protocol spec at §4.1.2.
pub const AuthResponseFrame = struct {
token: ?[]const u8,
pub fn write(self: @This(), pw: *PrimitiveWriter) !void {
return pw.writeBytes(self.token);
}
pub fn read(allocator: *mem.Allocator, pr: *PrimitiveReader) !AuthResponseFrame {
return AuthResponseFrame{
.token = try pr.readBytes(allocator),
};
}
};
/// AUTH_CHALLENGE is a server authentication challenge.
///
/// Described in the protocol spec at §4.2.7.
pub const AuthChallengeFrame = struct {
token: ?[]const u8,
pub fn read(allocator: *mem.Allocator, pr: *PrimitiveReader) !AuthChallengeFrame {
return AuthChallengeFrame{
.token = try pr.readBytes(allocator),
};
}
};
/// AUTH_SUCCESS indicates the success of the authentication phase.
///
/// Described in the protocol spec at §4.2.8.
pub const AuthSuccessFrame = struct {
token: ?[]const u8,
pub fn read(allocator: *mem.Allocator, pr: *PrimitiveReader) !AuthSuccessFrame {
return AuthSuccessFrame{
.token = try pr.readBytes(allocator),
};
}
};
test "authenticate frame" {
var arena = testing.arenaAllocator();
defer arena.deinit();
// read
const exp = "\x84\x00\x00\x00\x03\x00\x00\x00\x31\x00\x2f\x6f\x72\x67\x2e\x61\x70\x61\x63\x68\x65\x2e\x63\x61\x73\x73\x61\x6e\x64\x72\x61\x2e\x61\x75\x74\x68\x2e\x50\x61\x73\x73\x77\x6f\x72\x64\x41\x75\x74\x68\x65\x6e\x74\x69\x63\x61\x74\x6f\x72";
const raw_frame = try testing.readRawFrame(&arena.allocator, exp);
checkHeader(Opcode.Authenticate, exp.len, raw_frame.header);
var pr = PrimitiveReader.init();
pr.reset(raw_frame.body);
const frame = try AuthenticateFrame.read(&arena.allocator, &pr);
testing.expectEqualStrings("org.apache.cassandra.auth.PasswordAuthenticator", frame.authenticator);
}
test "auth challenge frame" {
// TODO(vincent): how do I get one of these frame ?
}
test "auth response frame" {
var arena = testing.arenaAllocator();
defer arena.deinit();
// read
const exp = "\x04\x00\x00\x02\x0f\x00\x00\x00\x18\x00\x00\x00\x14\x00\x63\x61\x73\x73\x61\x6e\x64\x72\x61\x00\x63\x61\x73\x73\x61\x6e\x64\x72\x61";
const raw_frame = try testing.readRawFrame(&arena.allocator, exp);
checkHeader(Opcode.AuthResponse, exp.len, raw_frame.header);
var pr = PrimitiveReader.init();
pr.reset(raw_frame.body);
const frame = try AuthResponseFrame.read(&arena.allocator, &pr);
const exp_token = "\x00cassandra\x00cassandra";
testing.expectEqualSlices(u8, exp_token, frame.token.?);
// write
testing.expectSameRawFrame(frame, raw_frame.header, exp);
}
test "auth success frame" {
var arena = testing.arenaAllocator();
defer arena.deinit();
// read
const exp = "\x84\x00\x00\x02\x10\x00\x00\x00\x04\xff\xff\xff\xff";
const raw_frame = try testing.readRawFrame(&arena.allocator, exp);
checkHeader(Opcode.AuthSuccess, exp.len, raw_frame.header);
var pr = PrimitiveReader.init();
pr.reset(raw_frame.body);
const frame = try AuthSuccessFrame.read(&arena.allocator, &pr);
testing.expect(frame.token == null);
} | src/frames/auth.zig |
const std = @import("std");
const expect = std.testing.expect;
const expectError = std.testing.expectError;
/// Value that serializes a !T
/// The T value is memset to all zeros.
pub fn ErrorVal(comptime T: type) type {
return packed struct {
const Self = @This();
err: u32,
val: T,
pub fn init() Self {
var ret = Self{ .err = 0, .val = undefined };
@memset(@ptrCast([*]u8, &ret.val), 0, @sizeOf(T));
return ret;
}
};
}
/// Hash an error value string; is a simple sum hash.
/// Must be the actual error name, not one from a ErrorSet
/// i.e "error.<whatever>"
pub fn errorHash(comptime err: anyerror) u32 {
const errname = @errorName(err);
comptime var ret: u32 = 0;
comptime {
for (errname) |c| {
ret += c;
ret += @truncate(u8, ret);
}
}
return ret;
}
/// Given an ErrorSet, a return type, and an ErrorVal of the same return type
/// This fn will deduce if the result has an error, if not return the value
/// if so, return the actual error.
/// If the error that was returned is unknown, then returns error.UnknownExternalError.
pub fn errorUnwrap(comptime errset: type, comptime T: type, result: ErrorVal(T)) !T {
comptime checkForCollisions(errset);
if (result.err == 0) {
return result.val;
}
const errs = comptime std.meta.fields(errset);
inline for (errs) |err| {
const err_val = @intToError(err.value);
if (errorHash(err_val) == result.err) {
return err_val;
}
}
return error.UnknownExternalError;
}
/// Wraps a result from a fn that can error and returns a errorval
pub fn errorWrap(comptime errset: type, comptime T: type, val: errset!T) ErrorVal(T) {
comptime checkForCollisions(errset);
var res = ErrorVal(T).init();
if (val) |actual_val| {
res.val = actual_val;
} else |thiserr| {
inline for (comptime std.meta.fields(errset)) |err| {
const err_val = @intToError(err.value);
if (thiserr == err_val) {
res.err = errorHash(err_val);
break;
}
}
}
return res;
}
fn checkForCollisions(comptime errset: type) void {
comptime {
const errs = std.meta.fields(errset);
for (errs) |err1, i| {
const errval1 = @intToError(err1.value);
for (errs) |err2, j| {
if (i == j) continue;
const errval2 = @intToError(err2.value);
if (errorHash(errval1) == errorHash(errval2)) {
const msg = "Hash collision of error." ++ err1.name ++ " and error." ++ err2.name;
@compileError(msg);
}
}
}
}
}
// Error set to test with
const TestingErrors = error{
LameError,
WackError,
};
// exported fn to test with
// add export to test this fn as exported, removed to not export in importing projects
fn testexport(err: bool) ErrorVal(u32) {
var res = errorWrap(TestingErrors, u32, dummyfn(err));
return res;
}
// test fn that may return an error
fn dummyfn(err: bool) !u32 {
if (err) return error.WackError;
return 1;
}
test "exported error" {
var ret = ErrorVal(u32).init();
expect(ret.err == 0);
expect(ret.val == 0);
}
const Collisions = error{
abcd,
abdc,
dcba,
cdba,
};
test "errorHash and collisions" {
const hash = errorHash(error.LameError);
expect(hash == 1968);
checkForCollisions(Collisions);
expect(errorHash(error.abcd) != errorHash(error.abdc));
expect(errorHash(error.abcd) != errorHash(error.dcba));
expect(errorHash(error.abcd) != errorHash(error.cdba));
}
test "errorWrap/errorUnwrap" {
var result = errorWrap(TestingErrors, u32, error.LameError);
expectError(error.LameError, errorUnwrap(TestingErrors, u32, result));
result.err = errorHash(error.OutOfMemory);
expectError(error.UnknownExternalError, errorUnwrap(TestingErrors, u32, result));
expect(1 == try errorUnwrap(TestingErrors, u32, testexport(false)));
expectError(error.WackError, errorUnwrap(TestingErrors, u32, testexport(true)));
} | error_abi.zig |
const std = @import("std");
const Allocator = std.mem.Allocator;
const Value = @import("Value.zig");
const Vm = @import("vm.zig").Vm;
const root = @import("root");
//! Mark-and-sweep based garbage collector
//! defining `gc_trigger_size` within the root file of your
//! program will allow to set the byte size of the new allocations before
//! the garbage collector is ran
const Gc = @This();
const default_gc_trigger_size = 1024 * 1024;
const gc_trigger = if (@hasDecl(root, "gc_trigger_size"))
std.math.max(root.gc_trigger_size, default_gc_trigger_size)
else
default_gc_trigger_size;
/// The allocator used to allocate and free memory of the stack
gpa: *Allocator,
/// The stack that contains each allocated Value, used to track and then free its memory
/// `stack` is a linked list to other Values
stack: ?*Value,
/// Reference to the Vm, used to retrieve the current stack and globals so we can
/// mark the correct values before sweeping
vm: *Vm,
/// Size of currently allocated stack
newly_allocated: usize,
/// Amount of bytes allowed before the garbage collector is triggered for sweeping
/// Default is 1MB. Can be changed by defining `gc_trigger_size` in root
trigger_size: usize = gc_trigger,
/// Initializes a new `GarbageCollector`, calling deinit() will ensure all memory is freed
pub fn init(allocator: *Allocator) Gc {
return .{
.gpa = allocator,
.stack = null,
.vm = undefined,
.newly_allocated = 0,
};
}
/// Inserts a new `Value` onto the stack and allocates `T` on the heap
pub fn newValue(self: *Gc, comptime T: type, val: T) !*Value {
const typed = try self.gpa.create(T);
typed.* = val;
typed.base.next = self.stack;
self.stack = &typed.base;
// In the future we could implement the Allocator interface so we get
// direct access to the bytes being allocated, which will also allow tracking
// of other allocations such as strings, lists, etc
self.newly_allocated += @sizeOf(T);
if (self.newly_allocated >= self.trigger_size) {
//also mark currently created so it doesn't get sweeped instantly
self.mark(&typed.base);
self.markAndSweep();
}
return &typed.base;
}
/// Marks an object so it will not be sweeped by the gc.
pub fn mark(self: *Gc, val: *Value) void {
if (val.is_marked) return;
val.is_marked = true;
switch (val.ty) {
.iterable => self.mark(val.toIterable().value),
.list => for (val.toList().value.items) |item| self.mark(item),
.map => {
for (val.toMap().value.items()) |entry| {
self.mark(entry.key);
self.mark(entry.value);
}
},
else => {},
}
}
/// Destroys all values not marked by the garbage collector
pub fn sweep(self: *Gc) void {
if (self.stack == null) return;
var prev: ?*Value = null;
var next: ?*Value = self.stack;
while (next) |val| {
next = val.next;
if (!val.is_marked) {
if (prev) |p| p.next = next else self.stack = next;
val.destroy(self.gpa);
} else {
val.is_marked = false;
prev = val;
}
}
}
/// Finds all referenced values in the vm, marks them and finally sweeps unreferenced values
fn markAndSweep(self: *Gc) void {
for (self.vm.globals.items) |global| self.mark(global);
for (self.vm.call_stack.items) |cs| if (cs.fp) |func| self.mark(func);
for (self.vm.locals.items) |local| self.mark(local);
for (self.vm.stack[0..self.vm.sp]) |stack| self.mark(stack);
for (self.vm.libs.items()) |lib_entry| self.mark(lib_entry.value);
self.sweep();
self.newly_allocated = 0;
}
/// Frees the `stack` that still exist on exit
pub fn deinit(self: *Gc) void {
while (self.stack) |next| {
const temp = next.next;
next.destroy(self.gpa);
self.stack = temp;
}
self.* = undefined;
} | src/Gc.zig |
const psp = @import("psp/pspsdk.zig");
pub const panic = psp.debug.panic;
comptime {
asm (psp.module_info("Zig PSP App", 0, 1, 0));
}
var display_list: [0x40000]u32 align(16) = [_]u32{0} ** 0x40000;
const Vertex = packed struct {
u: f32,
v: f32,
c: u32,
x: f32,
y: f32,
z: f32,
};
var vertices: [36]Vertex = [_]Vertex{
Vertex{ .u = 0, .v = 0, .c = 0xff7f0000, .x = -1, .y = -1, .z = 1 }, // 0
Vertex{ .u = 1, .v = 0, .c = 0xff7f0000, .x = -1, .y = 1, .z = 1 }, // 4
Vertex{ .u = 1, .v = 1, .c = 0xff7f0000, .x = 1, .y = 1, .z = 1 }, // 5
Vertex{ .u = 0, .v = 0, .c = 0xff7f0000, .x = -1, .y = -1, .z = 1 }, // 0
Vertex{ .u = 1, .v = 1, .c = 0xff7f0000, .x = 1, .y = 1, .z = 1 }, // 5
Vertex{ .u = 0, .v = 1, .c = 0xff7f0000, .x = 1, .y = -1, .z = 1 }, // 1
Vertex{ .u = 0, .v = 0, .c = 0xff7f0000, .x = -1, .y = -1, .z = -1 }, // 3
Vertex{ .u = 1, .v = 0, .c = 0xff7f0000, .x = 1, .y = -1, .z = -1 }, // 2
Vertex{ .u = 1, .v = 1, .c = 0xff7f0000, .x = 1, .y = 1, .z = -1 }, // 6
Vertex{ .u = 0, .v = 0, .c = 0xff7f0000, .x = -1, .y = -1, .z = -1 }, // 3
Vertex{ .u = 1, .v = 1, .c = 0xff7f0000, .x = 1, .y = 1, .z = -1 }, // 6
Vertex{ .u = 0, .v = 1, .c = 0xff7f0000, .x = -1, .y = 1, .z = -1 }, // 7
Vertex{ .u = 0, .v = 0, .c = 0xff007f00, .x = 1, .y = -1, .z = -1 }, // 0
Vertex{ .u = 1, .v = 0, .c = 0xff007f00, .x = 1, .y = -1, .z = 1 }, // 3
Vertex{ .u = 1, .v = 1, .c = 0xff007f00, .x = 1, .y = 1, .z = 1 }, // 7
Vertex{ .u = 0, .v = 0, .c = 0xff007f00, .x = 1, .y = -1, .z = -1 }, // 0
Vertex{ .u = 1, .v = 1, .c = 0xff007f00, .x = 1, .y = 1, .z = 1 }, // 7
Vertex{ .u = 0, .v = 1, .c = 0xff007f00, .x = 1, .y = 1, .z = -1 }, // 4
Vertex{ .u = 0, .v = 0, .c = 0xff007f00, .x = -1, .y = -1, .z = -1 }, // 0
Vertex{ .u = 1, .v = 0, .c = 0xff007f00, .x = -1, .y = 1, .z = -1 }, // 3
Vertex{ .u = 1, .v = 1, .c = 0xff007f00, .x = -1, .y = 1, .z = 1 }, // 7
Vertex{ .u = 0, .v = 0, .c = 0xff007f00, .x = -1, .y = -1, .z = -1 }, // 0
Vertex{ .u = 1, .v = 1, .c = 0xff007f00, .x = -1, .y = 1, .z = 1 }, // 7
Vertex{ .u = 0, .v = 1, .c = 0xff007f00, .x = -1, .y = -1, .z = 1 }, // 4
Vertex{ .u = 0, .v = 0, .c = 0xff00007f, .x = -1, .y = 1, .z = -1 }, // 0
Vertex{ .u = 1, .v = 0, .c = 0xff00007f, .x = 1, .y = 1, .z = -1 }, // 1
Vertex{ .u = 1, .v = 1, .c = 0xff00007f, .x = 1, .y = 1, .z = 1 }, // 2
Vertex{ .u = 0, .v = 0, .c = 0xff00007f, .x = -1, .y = 1, .z = -1 }, // 0
Vertex{ .u = 1, .v = 1, .c = 0xff00007f, .x = 1, .y = 1, .z = 1 }, // 2
Vertex{ .u = 0, .v = 1, .c = 0xff00007f, .x = -1, .y = 1, .z = 1 }, // 3
Vertex{ .u = 0, .v = 0, .c = 0xff00007f, .x = -1, .y = -1, .z = -1 }, // 4
Vertex{ .u = 1, .v = 0, .c = 0xff00007f, .x = -1, .y = -1, .z = 1 }, // 7
Vertex{ .u = 1, .v = 1, .c = 0xff00007f, .x = 1, .y = -1, .z = 1 }, // 6
Vertex{ .u = 0, .v = 0, .c = 0xff00007f, .x = -1, .y = -1, .z = -1 }, // 4
Vertex{ .u = 1, .v = 1, .c = 0xff00007f, .x = 1, .y = -1, .z = 1 }, // 6
Vertex{ .u = 0, .v = 1, .c = 0xff00007f, .x = 1, .y = -1, .z = -1 }, // 5
};
pub fn main() !void {
psp.utils.enableHBCB();
psp.debug.screenInit();
var fbp0 = psp.vram.allocVramRelative(psp.SCR_BUF_WIDTH, psp.SCREEN_HEIGHT, psp.GuPixelMode.Psm8888);
var fbp1 = psp.vram.allocVramRelative(psp.SCR_BUF_WIDTH, psp.SCREEN_HEIGHT, psp.GuPixelMode.Psm8888);
var zbp = psp.vram.allocVramRelative(psp.SCR_BUF_WIDTH, psp.SCREEN_HEIGHT, psp.GuPixelMode.Psm4444);
psp.sceGuInit();
psp.sceGuStart(psp.GuContextType.Direct, @ptrCast(*c_void, &display_list));
psp.sceGuDrawBuffer(psp.GuPixelMode.Psm8888, fbp0, psp.SCR_BUF_WIDTH);
psp.sceGuDispBuffer(psp.SCREEN_WIDTH, psp.SCREEN_HEIGHT, fbp1, psp.SCR_BUF_WIDTH);
psp.sceGuDepthBuffer(zbp, psp.SCR_BUF_WIDTH);
psp.sceGuOffset(2048 - (psp.SCREEN_WIDTH / 2), 2048 - (psp.SCREEN_HEIGHT / 2));
psp.sceGuViewport(2048, 2048, psp.SCREEN_WIDTH, psp.SCREEN_HEIGHT);
psp.sceGuDepthRange(65535, 0);
psp.sceGuScissor(0, 0, psp.SCREEN_WIDTH, psp.SCREEN_HEIGHT);
psp.sceGuEnable(psp.GuState.ScissorTest);
psp.sceGuDepthFunc(psp.DepthFunc.GreaterOrEqual);
psp.sceGuEnable(psp.GuState.DepthTest);
psp.sceGuShadeModel(psp.ShadeModel.Smooth);
psp.sceGuFrontFace(psp.FrontFaceDirection.Clockwise);
psp.sceGuEnable(psp.GuState.CullFace);
psp.sceGuDisable(psp.GuState.ClipPlanes);
psp.sceGuEnable(psp.GuState.Texture2D);
psp.guFinish();
psp.guSync(psp.GuSyncMode.Finish, psp.GuSyncBehavior.Wait);
psp.displayWaitVblankStart();
psp.sceGuDisplay(true);
var i: u32 = 0;
while (true) : (i += 1) {
psp.sceGuStart(psp.GuContextType.Direct, @ptrCast(*c_void, &display_list));
psp.sceGuClearColor(psp.rgba(32, 32, 32, 0xFF));
psp.sceGuClearDepth(0);
psp.sceGuClear(@enumToInt(psp.ClearBitFlags.ColorBuffer) |
@enumToInt(psp.ClearBitFlags.DepthBuffer));
psp.sceGumMatrixMode(psp.MatrixMode.Projection);
psp.sceGumLoadIdentity();
psp.sceGumPerspective(90.0, 16.0 / 9.0, 0.2, 10.0);
psp.sceGumMatrixMode(psp.MatrixMode.View);
psp.sceGumLoadIdentity();
psp.sceGumMatrixMode(psp.MatrixMode.Model);
psp.sceGumLoadIdentity();
//Rotate
var pos: psp.ScePspFVector3 = psp.ScePspFVector3{ .x = 0, .y = 0, .z = -2.5 };
var rot: psp.ScePspFVector3 = psp.ScePspFVector3{ .x = @intToFloat(f32, i) * 0.79 * (3.14159 / 180.0), .y = @intToFloat(f32, i) * 0.98 * (3.14159 / 180.0), .z = @intToFloat(f32, i) * 1.32 * (3.14159 / 180.0) };
psp.sceGumTranslate(&pos);
psp.sceGumRotateXYZ(&rot);
psp.sceGuTexMode(psp.GuPixelMode.Psm8888, 0, 0, 0);
psp.sceGuTexImage(0, 128, 128, 128, &logo_start);
psp.sceGuTexFunc(psp.TextureEffect.Replace, psp.TextureColorComponent.Rgba);
psp.sceGuTexFilter(psp.TextureFilter.Linear, psp.TextureFilter.Linear);
psp.sceGuTexScale(1.0, 1.0);
psp.sceGuTexOffset(0.0, 0.0);
psp.sceGuAmbientColor(0xffffffff);
// draw cube
psp.sceGumDrawArray(psp.GuPrimitive.Triangles, @enumToInt(psp.VertexTypeFlags.Texture32Bitf) | @enumToInt(psp.VertexTypeFlags.Color8888) | @enumToInt(psp.VertexTypeFlags.Vertex32Bitf) | @enumToInt(psp.VertexTypeFlags.Transform3D), 12 * 3, null, @ptrCast(*c_void, &vertices));
psp.guFinish();
psp.guSync(psp.GuSyncMode.Finish, psp.GuSyncBehavior.Wait);
psp.displayWaitVblankStart();
psp.guSwapBuffers();
}
}
const logo_start align(16) = @embedFile("ziggy.bin").*; | src/main.zig |
const std = @import("std");
const hzzp = @import("hzzp");
const tls = @import("iguanaTLS");
const build_opts = @import("build_options");
const hostname = "id.twitch.tv";
pub fn checkTokenValidity(allocator: std.mem.Allocator, token: []const u8) !bool {
if (build_opts.local) return true;
const TLSStream = tls.Client(std.net.Stream.Reader, std.net.Stream.Writer, tls.ciphersuites.all, true);
const HttpClient = hzzp.base.client.BaseClient(TLSStream.Reader, TLSStream.Writer);
var sock = try std.net.tcpConnectToHost(allocator, hostname, 443);
defer sock.close();
var randBuf: [32]u8 = undefined;
try std.os.getrandom(&randBuf);
var defaultCsprng = blk: {
var seed: [std.rand.DefaultCsprng.secret_seed_length]u8 = undefined;
try std.os.getrandom(&seed);
break :blk std.rand.DefaultCsprng.init(seed);
};
var rand = defaultCsprng.random();
var tls_sock = try tls.client_connect(.{
.rand = rand,
.temp_allocator = allocator,
.reader = sock.reader(),
.writer = sock.writer(),
.cert_verifier = .none,
.ciphersuites = tls.ciphersuites.all,
.protocols = &[_][]const u8{"http/1.1"},
}, hostname);
defer tls_sock.close_notify() catch {};
var buf: [1024]u8 = undefined;
var client = HttpClient.init(
&buf,
tls_sock.reader(),
tls_sock.writer(),
);
var it = std.mem.tokenize(u8, token, ":");
_ = it.next();
const header_oauth = try std.fmt.allocPrint(allocator, "OAuth {s}", .{it.next().?});
defer allocator.free(header_oauth);
client.writeStatusLine("GET", "/oauth2/validate") catch {
return error.Error;
};
client.writeHeaderValue("Host", hostname) catch unreachable;
client.writeHeaderValue("User-Agent", "Bork") catch unreachable;
client.writeHeaderValue("Accept", "*/*") catch unreachable;
client.writeHeaderValue("Authorization", header_oauth) catch unreachable;
client.finishHeaders() catch unreachable;
// Consume headers
while (try client.next()) |event| {
switch (event) {
.status => |status| switch (status.code) {
200 => {},
else => |code| {
std.log.debug("token is not good: {d}", .{code});
return false;
},
},
.header => {},
.head_done => {
break;
},
else => |val| {
std.log.debug("got other: {}", .{val});
return error.HttpFailed;
},
}
}
return true;
} | src/network/auth.zig |
pub const __builtin_bswap16 = @import("std").zig.c_builtins.__builtin_bswap16;
pub const __builtin_bswap32 = @import("std").zig.c_builtins.__builtin_bswap32;
pub const __builtin_bswap64 = @import("std").zig.c_builtins.__builtin_bswap64;
pub const __builtin_signbit = @import("std").zig.c_builtins.__builtin_signbit;
pub const __builtin_signbitf = @import("std").zig.c_builtins.__builtin_signbitf;
pub const __builtin_popcount = @import("std").zig.c_builtins.__builtin_popcount;
pub const __builtin_ctz = @import("std").zig.c_builtins.__builtin_ctz;
pub const __builtin_clz = @import("std").zig.c_builtins.__builtin_clz;
pub const __builtin_sqrt = @import("std").zig.c_builtins.__builtin_sqrt;
pub const __builtin_sqrtf = @import("std").zig.c_builtins.__builtin_sqrtf;
pub const __builtin_sin = @import("std").zig.c_builtins.__builtin_sin;
pub const __builtin_sinf = @import("std").zig.c_builtins.__builtin_sinf;
pub const __builtin_cos = @import("std").zig.c_builtins.__builtin_cos;
pub const __builtin_cosf = @import("std").zig.c_builtins.__builtin_cosf;
pub const __builtin_exp = @import("std").zig.c_builtins.__builtin_exp;
pub const __builtin_expf = @import("std").zig.c_builtins.__builtin_expf;
pub const __builtin_exp2 = @import("std").zig.c_builtins.__builtin_exp2;
pub const __builtin_exp2f = @import("std").zig.c_builtins.__builtin_exp2f;
pub const __builtin_log = @import("std").zig.c_builtins.__builtin_log;
pub const __builtin_logf = @import("std").zig.c_builtins.__builtin_logf;
pub const __builtin_log2 = @import("std").zig.c_builtins.__builtin_log2;
pub const __builtin_log2f = @import("std").zig.c_builtins.__builtin_log2f;
pub const __builtin_log10 = @import("std").zig.c_builtins.__builtin_log10;
pub const __builtin_log10f = @import("std").zig.c_builtins.__builtin_log10f;
pub const __builtin_abs = @import("std").zig.c_builtins.__builtin_abs;
pub const __builtin_fabs = @import("std").zig.c_builtins.__builtin_fabs;
pub const __builtin_fabsf = @import("std").zig.c_builtins.__builtin_fabsf;
pub const __builtin_floor = @import("std").zig.c_builtins.__builtin_floor;
pub const __builtin_floorf = @import("std").zig.c_builtins.__builtin_floorf;
pub const __builtin_ceil = @import("std").zig.c_builtins.__builtin_ceil;
pub const __builtin_ceilf = @import("std").zig.c_builtins.__builtin_ceilf;
pub const __builtin_trunc = @import("std").zig.c_builtins.__builtin_trunc;
pub const __builtin_truncf = @import("std").zig.c_builtins.__builtin_truncf;
pub const __builtin_round = @import("std").zig.c_builtins.__builtin_round;
pub const __builtin_roundf = @import("std").zig.c_builtins.__builtin_roundf;
pub const __builtin_strlen = @import("std").zig.c_builtins.__builtin_strlen;
pub const __builtin_strcmp = @import("std").zig.c_builtins.__builtin_strcmp;
pub const __builtin_object_size = @import("std").zig.c_builtins.__builtin_object_size;
pub const __builtin___memset_chk = @import("std").zig.c_builtins.__builtin___memset_chk;
pub const __builtin_memset = @import("std").zig.c_builtins.__builtin_memset;
pub const __builtin___memcpy_chk = @import("std").zig.c_builtins.__builtin___memcpy_chk;
pub const __builtin_memcpy = @import("std").zig.c_builtins.__builtin_memcpy;
pub const __builtin_expect = @import("std").zig.c_builtins.__builtin_expect;
pub const __builtin_nanf = @import("std").zig.c_builtins.__builtin_nanf;
pub const __builtin_huge_valf = @import("std").zig.c_builtins.__builtin_huge_valf;
pub const __builtin_inff = @import("std").zig.c_builtins.__builtin_inff;
pub const __builtin_isnan = @import("std").zig.c_builtins.__builtin_isnan;
pub const __builtin_isinf = @import("std").zig.c_builtins.__builtin_isinf;
pub const __builtin_isinf_sign = @import("std").zig.c_builtins.__builtin_isinf_sign;
pub const NULL = @import("std").zig.c_translation.cast(?*anyopaque, @as(c_int, 0)); | modules/platform/src/linux/X11/c.zig |
const std = @import("std");
const stdx = @import("stdx");
const v8 = @import("v8");
const log = stdx.log.scoped(.v8x);
pub const ExecuteResult = struct {
const Self = @This();
alloc: std.mem.Allocator,
result: ?[]const u8,
err: ?[]const u8,
success: bool,
pub fn deinit(self: Self) void {
if (self.result) |result| {
self.alloc.free(result);
}
if (self.err) |err| {
self.alloc.free(err);
}
}
};
/// Executes a string within the current v8 context.
pub fn executeString(alloc: std.mem.Allocator, iso: v8.Isolate, ctx: v8.Context, src: []const u8, src_origin: v8.String, result: *ExecuteResult) void {
var hscope: v8.HandleScope = undefined;
hscope.init(iso);
defer hscope.deinit();
var try_catch: v8.TryCatch = undefined;
try_catch.init(iso);
defer try_catch.deinit();
var origin = v8.ScriptOrigin.initDefault(iso, src_origin.toValue());
var context = iso.getCurrentContext();
// TODO: Since, only init scripts are executed as non esm scripts, we are currently prepending "use strict"; manually.
// If we do turn this back on, we'd need to compile with a detailed source param that specifies a line offset
// or the stack traces will be off by one.
// Since es modules are in strict mode it makes sense that everything else should also be in strict mode.
// Append 'use strict'; There isn't an internal api to enable it.
// Append void 0 so empty source still evaluates to undefined.
// const final_src = stdx.string.concat(alloc, &[_][]const u8{ "'use strict';void 0;\n", src }) catch unreachable;
// defer alloc.free(final_src);
const final_src = src;
const js_src = v8.String.initUtf8(iso, final_src);
// TODO: Use ScriptCompiler.compile to take a ScriptCompilerSource option that can account for the extra line offset.
const script = v8.Script.compile(context, js_src, origin) catch {
setResultError(alloc, iso, ctx, try_catch, result);
return;
};
const script_res = script.run(context) catch {
setResultError(alloc, iso, ctx, try_catch, result);
return;
};
result.* = .{
.alloc = alloc,
.result = allocValueAsUtf8(alloc, iso, context, script_res),
.err = null,
.success = true,
};
}
pub fn allocPrintMessageStackTrace(alloc: std.mem.Allocator, iso: v8.Isolate, ctx: v8.Context, message: v8.Message, default_msg: []const u8) []const u8 {
// TODO: Use default message if getMessage is null.
_ = default_msg;
var buf = std.ArrayList(u8).init(alloc);
const writer = buf.writer();
var hscope: v8.HandleScope = undefined;
hscope.init(iso);
defer hscope.deinit();
// Some exceptions don't have a line mapping by default. eg. Exceptions thrown in native callbacks.
if (message.getLineNumber(ctx) != null) {
// Append source line.
const source_line = message.getSourceLine(ctx).?;
_ = appendValueAsUtf8(&buf, iso, ctx, source_line);
writer.writeAll("\n") catch unreachable;
// Print wavy underline.
const col_start = message.getStartColumn().?;
const col_end = message.getEndColumn().?;
var i: u32 = 0;
while (i < col_start) : (i += 1) {
writer.writeByte(' ') catch unreachable;
}
// Sometimes a syntax error gives back the same start and end column which means the end column should be inclusive.
if (col_end == col_start) {
writer.writeByte('^') catch unreachable;
} else {
while (i < col_end) : (i += 1) {
writer.writeByte('^') catch unreachable;
}
}
writer.writeAll("\n") catch unreachable;
}
// Exception message.
appendStringAsUtf8(&buf, iso, message.getMessage());
writer.writeAll("\n") catch unreachable;
if (message.getStackTrace()) |trace| {
if (trace.getFrameCount() == 0 and message.getLineNumber(ctx) != null) {
// Syntax errors don't have a stack trace, so just print the message location.
const name = allocValueAsUtf8(alloc, iso, ctx, message.getScriptResourceName());
defer alloc.free(name);
const line = message.getLineNumber(ctx).?;
const col = message.getStartColumn().?;
writer.print(" at {s}:{}:{}\n", .{ name, line, col }) catch unreachable;
} else {
appendStackTraceString(&buf, iso, trace);
}
}
return buf.toOwnedSlice();
}
pub fn appendStackTraceString(buf: *std.ArrayList(u8), iso: v8.Isolate, trace: v8.StackTrace) void {
const writer = buf.writer();
const num_frames = trace.getFrameCount();
var i: u32 = 0;
while (i < num_frames) : (i += 1) {
const frame = trace.getFrame(iso, i);
writer.writeAll(" at ") catch unreachable;
if (frame.getFunctionName()) |name| {
appendStringAsUtf8(buf, iso, name);
writer.writeAll(" ") catch unreachable;
}
appendStringAsUtf8(buf, iso, frame.getScriptNameOrSourceUrl());
writer.print(":{}:{}", .{frame.getLineNumber(), frame.getColumn()}) catch unreachable;
writer.writeAll("\n") catch unreachable;
}
}
pub fn allocExceptionStackTraceString(alloc: std.mem.Allocator, iso: v8.Isolate, ctx: v8.Context, exception: v8.Value) []const u8 {
var hscope: v8.HandleScope = undefined;
hscope.init(iso);
defer hscope.deinit();
var buf = std.ArrayList(u8).init(alloc);
const writer = buf.writer();
_ = appendValueAsUtf8(&buf, iso, ctx, exception);
writer.writeAll("\n") catch unreachable;
if (v8.Exception.getStackTrace(exception)) |trace| {
appendStackTraceString(&buf, iso, trace);
}
return buf.toOwnedSlice();
}
pub fn allocPrintTryCatchStackTrace(alloc: std.mem.Allocator, iso: v8.Isolate, ctx: v8.Context, try_catch: v8.TryCatch) ?[]const u8 {
if (!try_catch.hasCaught()) {
return null;
}
var hscope: v8.HandleScope = undefined;
hscope.init(iso);
defer hscope.deinit();
if (try_catch.getMessage()) |message| {
const exception = try_catch.getException().?;
const exception_str = allocValueAsUtf8(alloc, iso, ctx, exception);
defer alloc.free(exception_str);
return allocPrintMessageStackTrace(alloc, iso, ctx, message, exception_str);
} else {
// V8 didn't provide any extra information about this error, just get exception str.
const exception = try_catch.getException().?;
return allocValueAsUtf8(alloc, iso, ctx, exception);
}
}
fn setResultError(alloc: std.mem.Allocator, iso: v8.Isolate, ctx: v8.Context, try_catch: v8.TryCatch, result: *ExecuteResult) void {
result.* = .{
.alloc = alloc,
.result = null,
.err = allocPrintTryCatchStackTrace(alloc, iso, ctx, try_catch),
.success = false,
};
}
fn appendStringAsUtf8(arr: *std.ArrayList(u8), iso: v8.Isolate, str: v8.String) void {
const len = str.lenUtf8(iso);
const start = arr.items.len;
arr.resize(start + len) catch unreachable;
_ = str.writeUtf8(iso, arr.items[start..arr.items.len]);
}
pub fn appendValueAsUtf8Lower(arr: *std.ArrayList(u8), isolate: v8.Isolate, ctx: v8.Context, any_value: anytype) []const u8 {
const val = v8.getValue(any_value);
const str = val.toString(ctx) catch unreachable;
const len = str.lenUtf8(isolate);
const start = arr.items.len;
arr.resize(start + len) catch unreachable;
_ = str.writeUtf8(isolate, arr.items[start..arr.items.len]);
return std.ascii.lowerString(arr.items[start..], arr.items[start..]);
}
pub fn appendValueAsUtf8(arr: *std.ArrayList(u8), isolate: v8.Isolate, ctx: v8.Context, any_value: anytype) []const u8 {
const val = v8.getValue(any_value);
const str = val.toString(ctx) catch unreachable;
const len = str.lenUtf8(isolate);
const start = arr.items.len;
arr.resize(start + len) catch unreachable;
_ = str.writeUtf8(isolate, arr.items[start..arr.items.len]);
return arr.items[start..];
}
pub fn allocStringAsUtf8(alloc: std.mem.Allocator, iso: v8.Isolate, str: v8.String) []const u8 {
const len = str.lenUtf8(iso);
const buf = alloc.alloc(u8, len) catch unreachable;
_ = str.writeUtf8(iso, buf);
return buf;
}
/// Custom dump format that shows top 2 level children.
pub fn allocValueDump(alloc: std.mem.Allocator, iso: v8.Isolate, ctx: v8.Context, val: v8.Value) []const u8 {
var buf = std.ArrayList(u8).init(alloc);
allocValueDump2(alloc, &buf, iso, ctx, val, 0, 2);
return buf.toOwnedSlice();
}
fn allocValueDump2(alloc: std.mem.Allocator, buf: *std.ArrayList(u8), iso: v8.Isolate, ctx: v8.Context, val: v8.Value, level: u32, level_max: u32) void {
if (val.isString()) {
const writer = buf.writer();
writer.writeAll("\"") catch unreachable;
_ = appendStringAsUtf8(buf, iso, val.castTo(v8.String));
writer.writeAll("\"") catch unreachable;
} else if (val.isArray()) {
if (level < level_max) {
const writer = buf.writer();
const arr = val.castTo(v8.Array);
const num_elems = arr.length();
if (num_elems > 0) {
writer.writeAll("[ ") catch unreachable;
var i: u32 = 0;
while (i < num_elems) : (i += 1) {
if (val.castTo(v8.Object).getAtIndex(ctx, i)) |elem| {
allocValueDump2(alloc, buf, iso, ctx, elem, level + 1, level_max);
} else |_| {
writer.writeAll("(error)") catch unreachable;
}
if (i + 1 < num_elems) {
writer.writeAll(", ") catch unreachable;
}
}
writer.writeAll(" ]") catch unreachable;
} else writer.writeAll("[]") catch unreachable;
} else buf.writer().writeAll("(Array)") catch unreachable;
} else if (val.isObject()) {
if (val.isFunction()) {
const func = val.castTo(v8.Function);
const name = allocValueAsUtf8(alloc, iso, ctx, func.getName());
defer alloc.free(name);
if (name.len == 0) {
buf.appendSlice("(Function)") catch unreachable;
} else {
buf.appendSlice("(Function: ") catch unreachable;
buf.appendSlice(name) catch unreachable;
buf.appendSlice(")") catch unreachable;
}
return;
}
if (level < level_max) {
const writer = buf.writer();
const obj = val.castTo(v8.Object);
const props = obj.getOwnPropertyNames(ctx);
const num_props = props.length();
if (num_props > 0) {
writer.writeAll("{ ") catch unreachable;
var i: u32 = 0;
while (i < num_props) : (i += 1) {
const prop = props.castTo(v8.Object).getAtIndex(ctx, i) catch continue;
_ = appendValueAsUtf8(buf, iso, ctx, prop);
writer.writeAll(": ") catch unreachable;
if (obj.getValue(ctx, prop)) |value| {
allocValueDump2(alloc, buf, iso, ctx, value, level + 1, level_max);
} else |_| {
writer.writeAll("(error)") catch unreachable;
}
if (i + 1 < num_props) {
writer.writeAll(", ") catch unreachable;
}
}
writer.writeAll(" }") catch unreachable;
} else writer.writeAll("{}") catch unreachable;
} else buf.writer().writeAll("(Object)") catch unreachable;
} else {
_ = appendValueAsUtf8(buf, iso, ctx, val);
}
}
pub fn allocValueAsUtf8(alloc: std.mem.Allocator, iso: v8.Isolate, ctx: v8.Context, any_value: anytype) []const u8 {
const val = v8.getValue(any_value);
const str = val.toString(ctx) catch unreachable;
const len = str.lenUtf8(iso);
const buf = alloc.alloc(u8, len) catch unreachable;
_ = str.writeUtf8(iso, buf);
return buf;
}
/// Throws an exception with a stack trace.
pub fn throwErrorException(iso: v8.Isolate, msg: []const u8) void {
_ = iso.throwException(v8.Exception.initError(iso.initStringUtf8(msg)));
}
pub fn throwErrorExceptionFmt(alloc: std.mem.Allocator, isolate: v8.Isolate, comptime format: []const u8, args: anytype) void {
const str = std.fmt.allocPrint(alloc, format, args) catch unreachable;
defer alloc.free(str);
throwErrorException(isolate, str);
}
/// Updates an existing persistent handle from a js value.
pub fn updateOptionalPersistent(comptime T: type, iso: v8.Isolate, existing: *?v8.Persistent(T), mb_val: ?T) void {
if (mb_val) |val| {
if (existing.* != null) {
const existing_addr = stdx.mem.ptrCastAlign(*const v8.C_InternalAddress, existing.*.?.inner.handle);
const val_addr = stdx.mem.ptrCastAlign(*const v8.C_InternalAddress, val.handle);
if (existing_addr.* != val_addr.*) {
// Internal addresses doesn't match, deinit existing persistent.
existing.*.?.deinit();
} else {
// Internal addresses match.
return;
}
}
existing.* = v8.Persistent(T).init(iso, val);
} else {
if (existing.* != null) {
existing.*.?.deinit();
existing.* = null;
}
}
} | runtime/v8x.zig |
const builtin = @import("builtin");
const std = @import("../std.zig");
const math = std.math;
const expect = std.testing.expect;
const expo2 = @import("expo2.zig").expo2;
const maxInt = std.math.maxInt;
/// Returns the hyperbolic tangent of x.
///
/// Special Cases:
/// - sinh(+-0) = +-0
/// - sinh(+-inf) = +-1
/// - sinh(nan) = nan
pub fn tanh(x: anytype) @TypeOf(x) {
const T = @TypeOf(x);
return switch (T) {
f32 => tanh32(x),
f64 => tanh64(x),
else => @compileError("tanh not implemented for " ++ @typeName(T)),
};
}
// tanh(x) = (exp(x) - exp(-x)) / (exp(x) + exp(-x))
// = (exp(2x) - 1) / (exp(2x) - 1 + 2)
// = (1 - exp(-2x)) / (exp(-2x) - 1 + 2)
fn tanh32(x: f32) f32 {
const u = @bitCast(u32, x);
const ux = u & 0x7FFFFFFF;
const ax = @bitCast(f32, ux);
var t: f32 = undefined;
if (x == 0.0 or math.isNan(x)) {
return x;
}
// |x| < log(3) / 2 ~= 0.5493 or nan
if (ux > 0x3F0C9F54) {
// |x| > 10
if (ux > 0x41200000) {
t = 1.0;
} else {
t = math.expm1(2 * x);
t = 1 - 2 / (t + 2);
}
}
// |x| > log(5 / 3) / 2 ~= 0.2554
else if (ux > 0x3E82C578) {
t = math.expm1(2 * x);
t = t / (t + 2);
}
// |x| >= 0x1.0p-126
else if (ux >= 0x00800000) {
t = math.expm1(-2 * x);
t = -t / (t + 2);
}
// |x| is subnormal
else {
math.doNotOptimizeAway(x * x);
t = x;
}
if (u >> 31 != 0) {
return -t;
} else {
return t;
}
}
fn tanh64(x: f64) f64 {
const u = @bitCast(u64, x);
const w = @intCast(u32, u >> 32);
const ax = @bitCast(f64, u & (maxInt(u64) >> 1));
var t: f64 = undefined;
// TODO: Shouldn't need these checks.
if (x == 0.0 or math.isNan(x)) {
return x;
}
// |x| < log(3) / 2 ~= 0.5493 or nan
if (w > 0x3FE193EA) {
// |x| > 20 or nan
if (w > 0x40340000) {
t = 1.0;
} else {
t = math.expm1(2 * x);
t = 1 - 2 / (t + 2);
}
}
// |x| > log(5 / 3) / 2 ~= 0.2554
else if (w > 0x3FD058AE) {
t = math.expm1(2 * x);
t = t / (t + 2);
}
// |x| >= 0x1.0p-1022
else if (w >= 0x00100000) {
t = math.expm1(-2 * x);
t = -t / (t + 2);
}
// |x| is subnormal
else {
math.doNotOptimizeAway(@floatCast(f32, x));
t = x;
}
if (u >> 63 != 0) {
return -t;
} else {
return t;
}
}
test "math.tanh" {
expect(tanh(@as(f32, 1.5)) == tanh32(1.5));
expect(tanh(@as(f64, 1.5)) == tanh64(1.5));
}
test "math.tanh32" {
const epsilon = 0.000001;
expect(math.approxEqAbs(f32, tanh32(0.0), 0.0, epsilon));
expect(math.approxEqAbs(f32, tanh32(0.2), 0.197375, epsilon));
expect(math.approxEqAbs(f32, tanh32(0.8923), 0.712528, epsilon));
expect(math.approxEqAbs(f32, tanh32(1.5), 0.905148, epsilon));
expect(math.approxEqAbs(f32, tanh32(37.45), 1.0, epsilon));
}
test "math.tanh64" {
const epsilon = 0.000001;
expect(math.approxEqAbs(f64, tanh64(0.0), 0.0, epsilon));
expect(math.approxEqAbs(f64, tanh64(0.2), 0.197375, epsilon));
expect(math.approxEqAbs(f64, tanh64(0.8923), 0.712528, epsilon));
expect(math.approxEqAbs(f64, tanh64(1.5), 0.905148, epsilon));
expect(math.approxEqAbs(f64, tanh64(37.45), 1.0, epsilon));
}
test "math.tanh32.special" {
expect(tanh32(0.0) == 0.0);
expect(tanh32(-0.0) == -0.0);
expect(tanh32(math.inf(f32)) == 1.0);
expect(tanh32(-math.inf(f32)) == -1.0);
expect(math.isNan(tanh32(math.nan(f32))));
}
test "math.tanh64.special" {
expect(tanh64(0.0) == 0.0);
expect(tanh64(-0.0) == -0.0);
expect(tanh64(math.inf(f64)) == 1.0);
expect(tanh64(-math.inf(f64)) == -1.0);
expect(math.isNan(tanh64(math.nan(f64))));
} | lib/std/math/tanh.zig |
const std = @import("std");
const Type = @import("type.zig").Type;
const log2 = std.math.log2;
const assert = std.debug.assert;
const BigIntConst = std.math.big.int.Const;
const BigIntMutable = std.math.big.int.Mutable;
const Target = std.Target;
const Allocator = std.mem.Allocator;
const Module = @import("Module.zig");
const Air = @import("Air.zig");
/// This is the raw data, with no bookkeeping, no memory awareness,
/// no de-duplication, and no type system awareness.
/// It's important for this type to be small.
/// This union takes advantage of the fact that the first page of memory
/// is unmapped, giving us 4096 possible enum tags that have no payload.
pub const Value = extern union {
/// If the tag value is less than Tag.no_payload_count, then no pointer
/// dereference is needed.
tag_if_small_enough: Tag,
ptr_otherwise: *Payload,
// Keep in sync with tools/zig-gdb.py
pub const Tag = enum(usize) {
// The first section of this enum are tags that require no payload.
u1_type,
u8_type,
i8_type,
u16_type,
i16_type,
u32_type,
i32_type,
u64_type,
i64_type,
u128_type,
i128_type,
usize_type,
isize_type,
c_short_type,
c_ushort_type,
c_int_type,
c_uint_type,
c_long_type,
c_ulong_type,
c_longlong_type,
c_ulonglong_type,
c_longdouble_type,
f16_type,
f32_type,
f64_type,
f80_type,
f128_type,
anyopaque_type,
bool_type,
void_type,
type_type,
anyerror_type,
comptime_int_type,
comptime_float_type,
noreturn_type,
anyframe_type,
null_type,
undefined_type,
enum_literal_type,
atomic_order_type,
atomic_rmw_op_type,
calling_convention_type,
address_space_type,
float_mode_type,
reduce_op_type,
call_options_type,
prefetch_options_type,
export_options_type,
extern_options_type,
type_info_type,
manyptr_u8_type,
manyptr_const_u8_type,
manyptr_const_u8_sentinel_0_type,
fn_noreturn_no_args_type,
fn_void_no_args_type,
fn_naked_noreturn_no_args_type,
fn_ccc_void_no_args_type,
single_const_pointer_to_comptime_int_type,
const_slice_u8_type,
const_slice_u8_sentinel_0_type,
anyerror_void_error_union_type,
generic_poison_type,
undef,
zero,
one,
void_value,
unreachable_value,
/// The only possible value for a particular type, which is stored externally.
the_only_possible_value,
null_value,
bool_true,
bool_false,
generic_poison,
empty_struct_value,
empty_array, // See last_no_payload_tag below.
// After this, the tag requires a payload.
ty,
int_type,
int_u64,
int_i64,
int_big_positive,
int_big_negative,
function,
extern_fn,
variable,
/// Represents a pointer to a Decl.
/// When machine codegen backend sees this, it must set the Decl's `alive` field to true.
decl_ref,
/// Pointer to a Decl, but allows comptime code to mutate the Decl's Value.
/// This Tag will never be seen by machine codegen backends. It is changed into a
/// `decl_ref` when a comptime variable goes out of scope.
decl_ref_mut,
/// Pointer to a specific element of an array, vector or slice.
elem_ptr,
/// Pointer to a specific field of a struct or union.
field_ptr,
/// A slice of u8 whose memory is managed externally.
bytes,
/// This value is repeated some number of times. The amount of times to repeat
/// is stored externally.
repeated,
/// An array with length 0 but it has a sentinel.
empty_array_sentinel,
/// Pointer and length as sub `Value` objects.
slice,
float_16,
float_32,
float_64,
float_80,
float_128,
enum_literal,
/// A specific enum tag, indicated by the field index (declaration order).
enum_field_index,
@"error",
/// When the type is error union:
/// * If the tag is `.@"error"`, the error union is an error.
/// * If the tag is `.eu_payload`, the error union is a payload.
/// * A nested error such as `anyerror!(anyerror!T)` in which the the outer error union
/// is non-error, but the inner error union is an error, is represented as
/// a tag of `.eu_payload`, with a sub-tag of `.@"error"`.
eu_payload,
/// A pointer to the payload of an error union, based on a pointer to an error union.
eu_payload_ptr,
/// When the type is optional:
/// * If the tag is `.null_value`, the optional is null.
/// * If the tag is `.opt_payload`, the optional is a payload.
/// * A nested optional such as `??T` in which the the outer optional
/// is non-null, but the inner optional is null, is represented as
/// a tag of `.opt_payload`, with a sub-tag of `.null_value`.
opt_payload,
/// A pointer to the payload of an optional, based on a pointer to an optional.
opt_payload_ptr,
/// An instance of a struct, array, or vector.
/// Each element/field stored as a `Value`.
/// In the case of sentinel-terminated arrays, the sentinel value *is* stored,
/// so the slice length will be one more than the type's array length.
aggregate,
/// An instance of a union.
@"union",
/// This is a special value that tracks a set of types that have been stored
/// to an inferred allocation. It does not support any of the normal value queries.
inferred_alloc,
/// Used to coordinate alloc_inferred, store_to_inferred_ptr, and resolve_inferred_alloc
/// instructions for comptime code.
inferred_alloc_comptime,
/// Used sometimes as the result of field_call_bind. This value is always temporary,
/// and refers directly to the air. It will never be referenced by the air itself.
/// TODO: This is probably a bad encoding, maybe put temp data in the sema instead.
bound_fn,
pub const last_no_payload_tag = Tag.empty_array;
pub const no_payload_count = @enumToInt(last_no_payload_tag) + 1;
pub fn Type(comptime t: Tag) type {
return switch (t) {
.u1_type,
.u8_type,
.i8_type,
.u16_type,
.i16_type,
.u32_type,
.i32_type,
.u64_type,
.i64_type,
.u128_type,
.i128_type,
.usize_type,
.isize_type,
.c_short_type,
.c_ushort_type,
.c_int_type,
.c_uint_type,
.c_long_type,
.c_ulong_type,
.c_longlong_type,
.c_ulonglong_type,
.c_longdouble_type,
.f16_type,
.f32_type,
.f64_type,
.f80_type,
.f128_type,
.anyopaque_type,
.bool_type,
.void_type,
.type_type,
.anyerror_type,
.comptime_int_type,
.comptime_float_type,
.noreturn_type,
.null_type,
.undefined_type,
.fn_noreturn_no_args_type,
.fn_void_no_args_type,
.fn_naked_noreturn_no_args_type,
.fn_ccc_void_no_args_type,
.single_const_pointer_to_comptime_int_type,
.anyframe_type,
.const_slice_u8_type,
.const_slice_u8_sentinel_0_type,
.anyerror_void_error_union_type,
.generic_poison_type,
.enum_literal_type,
.undef,
.zero,
.one,
.void_value,
.unreachable_value,
.the_only_possible_value,
.empty_struct_value,
.empty_array,
.null_value,
.bool_true,
.bool_false,
.manyptr_u8_type,
.manyptr_const_u8_type,
.manyptr_const_u8_sentinel_0_type,
.atomic_order_type,
.atomic_rmw_op_type,
.calling_convention_type,
.address_space_type,
.float_mode_type,
.reduce_op_type,
.call_options_type,
.prefetch_options_type,
.export_options_type,
.extern_options_type,
.type_info_type,
.generic_poison,
=> @compileError("Value Tag " ++ @tagName(t) ++ " has no payload"),
.int_big_positive,
.int_big_negative,
=> Payload.BigInt,
.extern_fn => Payload.ExternFn,
.decl_ref => Payload.Decl,
.repeated,
.eu_payload,
.opt_payload,
.empty_array_sentinel,
=> Payload.SubValue,
.eu_payload_ptr,
.opt_payload_ptr,
=> Payload.PayloadPtr,
.bytes,
.enum_literal,
=> Payload.Bytes,
.slice => Payload.Slice,
.enum_field_index => Payload.U32,
.ty => Payload.Ty,
.int_type => Payload.IntType,
.int_u64 => Payload.U64,
.int_i64 => Payload.I64,
.function => Payload.Function,
.variable => Payload.Variable,
.decl_ref_mut => Payload.DeclRefMut,
.elem_ptr => Payload.ElemPtr,
.field_ptr => Payload.FieldPtr,
.float_16 => Payload.Float_16,
.float_32 => Payload.Float_32,
.float_64 => Payload.Float_64,
.float_80 => Payload.Float_80,
.float_128 => Payload.Float_128,
.@"error" => Payload.Error,
.inferred_alloc => Payload.InferredAlloc,
.inferred_alloc_comptime => Payload.InferredAllocComptime,
.aggregate => Payload.Aggregate,
.@"union" => Payload.Union,
.bound_fn => Payload.BoundFn,
};
}
pub fn create(comptime t: Tag, ally: Allocator, data: Data(t)) error{OutOfMemory}!Value {
const ptr = try ally.create(t.Type());
ptr.* = .{
.base = .{ .tag = t },
.data = data,
};
return Value{ .ptr_otherwise = &ptr.base };
}
pub fn Data(comptime t: Tag) type {
return std.meta.fieldInfo(t.Type(), .data).field_type;
}
};
pub fn initTag(small_tag: Tag) Value {
assert(@enumToInt(small_tag) < Tag.no_payload_count);
return .{ .tag_if_small_enough = small_tag };
}
pub fn initPayload(payload: *Payload) Value {
assert(@enumToInt(payload.tag) >= Tag.no_payload_count);
return .{ .ptr_otherwise = payload };
}
pub fn tag(self: Value) Tag {
if (@enumToInt(self.tag_if_small_enough) < Tag.no_payload_count) {
return self.tag_if_small_enough;
} else {
return self.ptr_otherwise.tag;
}
}
/// Prefer `castTag` to this.
pub fn cast(self: Value, comptime T: type) ?*T {
if (@hasField(T, "base_tag")) {
return self.castTag(T.base_tag);
}
if (@enumToInt(self.tag_if_small_enough) < Tag.no_payload_count) {
return null;
}
inline for (@typeInfo(Tag).Enum.fields) |field| {
if (field.value < Tag.no_payload_count)
continue;
const t = @intToEnum(Tag, field.value);
if (self.ptr_otherwise.tag == t) {
if (T == t.Type()) {
return @fieldParentPtr(T, "base", self.ptr_otherwise);
}
return null;
}
}
unreachable;
}
pub fn castTag(self: Value, comptime t: Tag) ?*t.Type() {
if (@enumToInt(self.tag_if_small_enough) < Tag.no_payload_count)
return null;
if (self.ptr_otherwise.tag == t)
return @fieldParentPtr(t.Type(), "base", self.ptr_otherwise);
return null;
}
/// It's intentional that this function is not passed a corresponding Type, so that
/// a Value can be copied from a Sema to a Decl prior to resolving struct/union field types.
pub fn copy(self: Value, arena: Allocator) error{OutOfMemory}!Value {
if (@enumToInt(self.tag_if_small_enough) < Tag.no_payload_count) {
return Value{ .tag_if_small_enough = self.tag_if_small_enough };
} else switch (self.ptr_otherwise.tag) {
.u1_type,
.u8_type,
.i8_type,
.u16_type,
.i16_type,
.u32_type,
.i32_type,
.u64_type,
.i64_type,
.u128_type,
.i128_type,
.usize_type,
.isize_type,
.c_short_type,
.c_ushort_type,
.c_int_type,
.c_uint_type,
.c_long_type,
.c_ulong_type,
.c_longlong_type,
.c_ulonglong_type,
.c_longdouble_type,
.f16_type,
.f32_type,
.f64_type,
.f80_type,
.f128_type,
.anyopaque_type,
.bool_type,
.void_type,
.type_type,
.anyerror_type,
.comptime_int_type,
.comptime_float_type,
.noreturn_type,
.null_type,
.undefined_type,
.fn_noreturn_no_args_type,
.fn_void_no_args_type,
.fn_naked_noreturn_no_args_type,
.fn_ccc_void_no_args_type,
.single_const_pointer_to_comptime_int_type,
.anyframe_type,
.const_slice_u8_type,
.const_slice_u8_sentinel_0_type,
.anyerror_void_error_union_type,
.generic_poison_type,
.enum_literal_type,
.undef,
.zero,
.one,
.void_value,
.unreachable_value,
.the_only_possible_value,
.empty_array,
.null_value,
.bool_true,
.bool_false,
.empty_struct_value,
.manyptr_u8_type,
.manyptr_const_u8_type,
.manyptr_const_u8_sentinel_0_type,
.atomic_order_type,
.atomic_rmw_op_type,
.calling_convention_type,
.address_space_type,
.float_mode_type,
.reduce_op_type,
.call_options_type,
.prefetch_options_type,
.export_options_type,
.extern_options_type,
.type_info_type,
.generic_poison,
.bound_fn,
=> unreachable,
.ty => {
const payload = self.castTag(.ty).?;
const new_payload = try arena.create(Payload.Ty);
new_payload.* = .{
.base = payload.base,
.data = try payload.data.copy(arena),
};
return Value{ .ptr_otherwise = &new_payload.base };
},
.int_type => return self.copyPayloadShallow(arena, Payload.IntType),
.int_u64 => return self.copyPayloadShallow(arena, Payload.U64),
.int_i64 => return self.copyPayloadShallow(arena, Payload.I64),
.int_big_positive, .int_big_negative => {
const old_payload = self.cast(Payload.BigInt).?;
const new_payload = try arena.create(Payload.BigInt);
new_payload.* = .{
.base = .{ .tag = self.ptr_otherwise.tag },
.data = try arena.dupe(std.math.big.Limb, old_payload.data),
};
return Value{ .ptr_otherwise = &new_payload.base };
},
.function => return self.copyPayloadShallow(arena, Payload.Function),
.extern_fn => return self.copyPayloadShallow(arena, Payload.ExternFn),
.variable => return self.copyPayloadShallow(arena, Payload.Variable),
.decl_ref => return self.copyPayloadShallow(arena, Payload.Decl),
.decl_ref_mut => return self.copyPayloadShallow(arena, Payload.DeclRefMut),
.eu_payload_ptr,
.opt_payload_ptr,
=> {
const payload = self.cast(Payload.PayloadPtr).?;
const new_payload = try arena.create(Payload.PayloadPtr);
new_payload.* = .{
.base = payload.base,
.data = .{
.container_ptr = try payload.data.container_ptr.copy(arena),
.container_ty = try payload.data.container_ty.copy(arena),
},
};
return Value{ .ptr_otherwise = &new_payload.base };
},
.elem_ptr => {
const payload = self.castTag(.elem_ptr).?;
const new_payload = try arena.create(Payload.ElemPtr);
new_payload.* = .{
.base = payload.base,
.data = .{
.array_ptr = try payload.data.array_ptr.copy(arena),
.elem_ty = try payload.data.elem_ty.copy(arena),
.index = payload.data.index,
},
};
return Value{ .ptr_otherwise = &new_payload.base };
},
.field_ptr => {
const payload = self.castTag(.field_ptr).?;
const new_payload = try arena.create(Payload.FieldPtr);
new_payload.* = .{
.base = payload.base,
.data = .{
.container_ptr = try payload.data.container_ptr.copy(arena),
.container_ty = try payload.data.container_ty.copy(arena),
.field_index = payload.data.field_index,
},
};
return Value{ .ptr_otherwise = &new_payload.base };
},
.bytes => return self.copyPayloadShallow(arena, Payload.Bytes),
.repeated,
.eu_payload,
.opt_payload,
.empty_array_sentinel,
=> {
const payload = self.cast(Payload.SubValue).?;
const new_payload = try arena.create(Payload.SubValue);
new_payload.* = .{
.base = payload.base,
.data = try payload.data.copy(arena),
};
return Value{ .ptr_otherwise = &new_payload.base };
},
.slice => {
const payload = self.castTag(.slice).?;
const new_payload = try arena.create(Payload.Slice);
new_payload.* = .{
.base = payload.base,
.data = .{
.ptr = try payload.data.ptr.copy(arena),
.len = try payload.data.len.copy(arena),
},
};
return Value{ .ptr_otherwise = &new_payload.base };
},
.float_16 => return self.copyPayloadShallow(arena, Payload.Float_16),
.float_32 => return self.copyPayloadShallow(arena, Payload.Float_32),
.float_64 => return self.copyPayloadShallow(arena, Payload.Float_64),
.float_80 => return self.copyPayloadShallow(arena, Payload.Float_80),
.float_128 => return self.copyPayloadShallow(arena, Payload.Float_128),
.enum_literal => {
const payload = self.castTag(.enum_literal).?;
const new_payload = try arena.create(Payload.Bytes);
new_payload.* = .{
.base = payload.base,
.data = try arena.dupe(u8, payload.data),
};
return Value{ .ptr_otherwise = &new_payload.base };
},
.enum_field_index => return self.copyPayloadShallow(arena, Payload.U32),
.@"error" => return self.copyPayloadShallow(arena, Payload.Error),
.aggregate => {
const payload = self.castTag(.aggregate).?;
const new_payload = try arena.create(Payload.Aggregate);
new_payload.* = .{
.base = payload.base,
.data = try arena.alloc(Value, payload.data.len),
};
for (new_payload.data) |*elem, i| {
elem.* = try payload.data[i].copy(arena);
}
return Value{ .ptr_otherwise = &new_payload.base };
},
.@"union" => {
const tag_and_val = self.castTag(.@"union").?.data;
const new_payload = try arena.create(Payload.Union);
new_payload.* = .{
.base = .{ .tag = .@"union" },
.data = .{
.tag = try tag_and_val.tag.copy(arena),
.val = try tag_and_val.val.copy(arena),
},
};
return Value{ .ptr_otherwise = &new_payload.base };
},
.inferred_alloc => unreachable,
.inferred_alloc_comptime => unreachable,
}
}
fn copyPayloadShallow(self: Value, arena: Allocator, comptime T: type) error{OutOfMemory}!Value {
const payload = self.cast(T).?;
const new_payload = try arena.create(T);
new_payload.* = payload.*;
return Value{ .ptr_otherwise = &new_payload.base };
}
pub fn format(val: Value, comptime fmt: []const u8, options: std.fmt.FormatOptions, writer: anytype) !void {
_ = val;
_ = fmt;
_ = options;
_ = writer;
@compileError("do not use format values directly; use either fmtDebug or fmtValue");
}
/// TODO this should become a debug dump() function. In order to print values in a meaningful way
/// we also need access to the type.
pub fn dump(
start_val: Value,
comptime fmt: []const u8,
options: std.fmt.FormatOptions,
out_stream: anytype,
) !void {
comptime assert(fmt.len == 0);
var val = start_val;
while (true) switch (val.tag()) {
.u1_type => return out_stream.writeAll("u1"),
.u8_type => return out_stream.writeAll("u8"),
.i8_type => return out_stream.writeAll("i8"),
.u16_type => return out_stream.writeAll("u16"),
.i16_type => return out_stream.writeAll("i16"),
.u32_type => return out_stream.writeAll("u32"),
.i32_type => return out_stream.writeAll("i32"),
.u64_type => return out_stream.writeAll("u64"),
.i64_type => return out_stream.writeAll("i64"),
.u128_type => return out_stream.writeAll("u128"),
.i128_type => return out_stream.writeAll("i128"),
.isize_type => return out_stream.writeAll("isize"),
.usize_type => return out_stream.writeAll("usize"),
.c_short_type => return out_stream.writeAll("c_short"),
.c_ushort_type => return out_stream.writeAll("c_ushort"),
.c_int_type => return out_stream.writeAll("c_int"),
.c_uint_type => return out_stream.writeAll("c_uint"),
.c_long_type => return out_stream.writeAll("c_long"),
.c_ulong_type => return out_stream.writeAll("c_ulong"),
.c_longlong_type => return out_stream.writeAll("c_longlong"),
.c_ulonglong_type => return out_stream.writeAll("c_ulonglong"),
.c_longdouble_type => return out_stream.writeAll("c_longdouble"),
.f16_type => return out_stream.writeAll("f16"),
.f32_type => return out_stream.writeAll("f32"),
.f64_type => return out_stream.writeAll("f64"),
.f80_type => return out_stream.writeAll("f80"),
.f128_type => return out_stream.writeAll("f128"),
.anyopaque_type => return out_stream.writeAll("anyopaque"),
.bool_type => return out_stream.writeAll("bool"),
.void_type => return out_stream.writeAll("void"),
.type_type => return out_stream.writeAll("type"),
.anyerror_type => return out_stream.writeAll("anyerror"),
.comptime_int_type => return out_stream.writeAll("comptime_int"),
.comptime_float_type => return out_stream.writeAll("comptime_float"),
.noreturn_type => return out_stream.writeAll("noreturn"),
.null_type => return out_stream.writeAll("@Type(.Null)"),
.undefined_type => return out_stream.writeAll("@Type(.Undefined)"),
.fn_noreturn_no_args_type => return out_stream.writeAll("fn() noreturn"),
.fn_void_no_args_type => return out_stream.writeAll("fn() void"),
.fn_naked_noreturn_no_args_type => return out_stream.writeAll("fn() callconv(.Naked) noreturn"),
.fn_ccc_void_no_args_type => return out_stream.writeAll("fn() callconv(.C) void"),
.single_const_pointer_to_comptime_int_type => return out_stream.writeAll("*const comptime_int"),
.anyframe_type => return out_stream.writeAll("anyframe"),
.const_slice_u8_type => return out_stream.writeAll("[]const u8"),
.const_slice_u8_sentinel_0_type => return out_stream.writeAll("[:0]const u8"),
.anyerror_void_error_union_type => return out_stream.writeAll("anyerror!void"),
.generic_poison_type => return out_stream.writeAll("(generic poison type)"),
.generic_poison => return out_stream.writeAll("(generic poison)"),
.enum_literal_type => return out_stream.writeAll("@Type(.EnumLiteral)"),
.manyptr_u8_type => return out_stream.writeAll("[*]u8"),
.manyptr_const_u8_type => return out_stream.writeAll("[*]const u8"),
.manyptr_const_u8_sentinel_0_type => return out_stream.writeAll("[*:0]const u8"),
.atomic_order_type => return out_stream.writeAll("std.builtin.AtomicOrder"),
.atomic_rmw_op_type => return out_stream.writeAll("std.builtin.AtomicRmwOp"),
.calling_convention_type => return out_stream.writeAll("std.builtin.CallingConvention"),
.address_space_type => return out_stream.writeAll("std.builtin.AddressSpace"),
.float_mode_type => return out_stream.writeAll("std.builtin.FloatMode"),
.reduce_op_type => return out_stream.writeAll("std.builtin.ReduceOp"),
.call_options_type => return out_stream.writeAll("std.builtin.CallOptions"),
.prefetch_options_type => return out_stream.writeAll("std.builtin.PrefetchOptions"),
.export_options_type => return out_stream.writeAll("std.builtin.ExportOptions"),
.extern_options_type => return out_stream.writeAll("std.builtin.ExternOptions"),
.type_info_type => return out_stream.writeAll("std.builtin.Type"),
.empty_struct_value => return out_stream.writeAll("struct {}{}"),
.aggregate => {
return out_stream.writeAll("(aggregate)");
},
.@"union" => {
return out_stream.writeAll("(union value)");
},
.null_value => return out_stream.writeAll("null"),
.undef => return out_stream.writeAll("undefined"),
.zero => return out_stream.writeAll("0"),
.one => return out_stream.writeAll("1"),
.void_value => return out_stream.writeAll("{}"),
.unreachable_value => return out_stream.writeAll("unreachable"),
.the_only_possible_value => return out_stream.writeAll("(the only possible value)"),
.bool_true => return out_stream.writeAll("true"),
.bool_false => return out_stream.writeAll("false"),
.ty => return val.castTag(.ty).?.data.format("", options, out_stream),
.int_type => {
const int_type = val.castTag(.int_type).?.data;
return out_stream.print("{s}{d}", .{
if (int_type.signed) "s" else "u",
int_type.bits,
});
},
.int_u64 => return std.fmt.formatIntValue(val.castTag(.int_u64).?.data, "", options, out_stream),
.int_i64 => return std.fmt.formatIntValue(val.castTag(.int_i64).?.data, "", options, out_stream),
.int_big_positive => return out_stream.print("{}", .{val.castTag(.int_big_positive).?.asBigInt()}),
.int_big_negative => return out_stream.print("{}", .{val.castTag(.int_big_negative).?.asBigInt()}),
.function => return out_stream.print("(function '{s}')", .{val.castTag(.function).?.data.owner_decl.name}),
.extern_fn => return out_stream.writeAll("(extern function)"),
.variable => return out_stream.writeAll("(variable)"),
.decl_ref_mut => {
const decl = val.castTag(.decl_ref_mut).?.data.decl;
return out_stream.print("(decl_ref_mut '{s}')", .{decl.name});
},
.decl_ref => {
const decl = val.castTag(.decl_ref).?.data;
return out_stream.print("(decl ref '{s}')", .{decl.name});
},
.elem_ptr => {
const elem_ptr = val.castTag(.elem_ptr).?.data;
try out_stream.print("&[{}] ", .{elem_ptr.index});
val = elem_ptr.array_ptr;
},
.field_ptr => {
const field_ptr = val.castTag(.field_ptr).?.data;
try out_stream.print("fieldptr({d}) ", .{field_ptr.field_index});
val = field_ptr.container_ptr;
},
.empty_array => return out_stream.writeAll(".{}"),
.enum_literal => return out_stream.print(".{}", .{std.zig.fmtId(val.castTag(.enum_literal).?.data)}),
.enum_field_index => return out_stream.print("(enum field {d})", .{val.castTag(.enum_field_index).?.data}),
.bytes => return out_stream.print("\"{}\"", .{std.zig.fmtEscapes(val.castTag(.bytes).?.data)}),
.repeated => {
try out_stream.writeAll("(repeated) ");
val = val.castTag(.repeated).?.data;
},
.empty_array_sentinel => return out_stream.writeAll("(empty array with sentinel)"),
.slice => return out_stream.writeAll("(slice)"),
.float_16 => return out_stream.print("{}", .{val.castTag(.float_16).?.data}),
.float_32 => return out_stream.print("{}", .{val.castTag(.float_32).?.data}),
.float_64 => return out_stream.print("{}", .{val.castTag(.float_64).?.data}),
.float_80 => return out_stream.print("{}", .{val.castTag(.float_80).?.data}),
.float_128 => return out_stream.print("{}", .{val.castTag(.float_128).?.data}),
.@"error" => return out_stream.print("error.{s}", .{val.castTag(.@"error").?.data.name}),
// TODO to print this it should be error{ Set, Items }!T(val), but we need the type for that
.eu_payload => {
try out_stream.writeAll("(eu_payload) ");
val = val.castTag(.eu_payload).?.data;
},
.opt_payload => {
try out_stream.writeAll("(opt_payload) ");
val = val.castTag(.opt_payload).?.data;
},
.inferred_alloc => return out_stream.writeAll("(inferred allocation value)"),
.inferred_alloc_comptime => return out_stream.writeAll("(inferred comptime allocation value)"),
.eu_payload_ptr => {
try out_stream.writeAll("(eu_payload_ptr)");
val = val.castTag(.eu_payload_ptr).?.data.container_ptr;
},
.opt_payload_ptr => {
try out_stream.writeAll("(opt_payload_ptr)");
val = val.castTag(.opt_payload_ptr).?.data.container_ptr;
},
.bound_fn => {
const bound_func = val.castTag(.bound_fn).?.data;
return out_stream.print("(bound_fn %{}(%{})", .{ bound_func.func_inst, bound_func.arg0_inst });
},
};
}
pub fn fmtDebug(val: Value) std.fmt.Formatter(dump) {
return .{ .data = val };
}
const TypedValue = @import("TypedValue.zig");
pub fn fmtValue(val: Value, ty: Type) std.fmt.Formatter(TypedValue.format) {
return .{ .data = .{ .ty = ty, .val = val } };
}
/// Asserts that the value is representable as an array of bytes.
/// Copies the value into a freshly allocated slice of memory, which is owned by the caller.
pub fn toAllocatedBytes(val: Value, ty: Type, allocator: Allocator) ![]u8 {
switch (val.tag()) {
.bytes => {
const bytes = val.castTag(.bytes).?.data;
const adjusted_len = bytes.len - @boolToInt(ty.sentinel() != null);
const adjusted_bytes = bytes[0..adjusted_len];
return allocator.dupe(u8, adjusted_bytes);
},
.enum_literal => return allocator.dupe(u8, val.castTag(.enum_literal).?.data),
.repeated => {
const byte = @intCast(u8, val.castTag(.repeated).?.data.toUnsignedInt());
const result = try allocator.alloc(u8, @intCast(usize, ty.arrayLen()));
std.mem.set(u8, result, byte);
return result;
},
.decl_ref => {
const decl = val.castTag(.decl_ref).?.data;
const decl_val = try decl.value();
return decl_val.toAllocatedBytes(decl.ty, allocator);
},
.the_only_possible_value => return &[_]u8{},
.slice => {
const slice = val.castTag(.slice).?.data;
return arrayToAllocatedBytes(slice.ptr, slice.len.toUnsignedInt(), allocator);
},
else => return arrayToAllocatedBytes(val, ty.arrayLen(), allocator),
}
}
fn arrayToAllocatedBytes(val: Value, len: u64, allocator: Allocator) ![]u8 {
const result = try allocator.alloc(u8, @intCast(usize, len));
var elem_value_buf: ElemValueBuffer = undefined;
for (result) |*elem, i| {
const elem_val = val.elemValueBuffer(i, &elem_value_buf);
elem.* = @intCast(u8, elem_val.toUnsignedInt());
}
return result;
}
pub const ToTypeBuffer = Type.Payload.Bits;
/// Asserts that the value is representable as a type.
pub fn toType(self: Value, buffer: *ToTypeBuffer) Type {
return switch (self.tag()) {
.ty => self.castTag(.ty).?.data,
.u1_type => Type.initTag(.u1),
.u8_type => Type.initTag(.u8),
.i8_type => Type.initTag(.i8),
.u16_type => Type.initTag(.u16),
.i16_type => Type.initTag(.i16),
.u32_type => Type.initTag(.u32),
.i32_type => Type.initTag(.i32),
.u64_type => Type.initTag(.u64),
.i64_type => Type.initTag(.i64),
.u128_type => Type.initTag(.u128),
.i128_type => Type.initTag(.i128),
.usize_type => Type.initTag(.usize),
.isize_type => Type.initTag(.isize),
.c_short_type => Type.initTag(.c_short),
.c_ushort_type => Type.initTag(.c_ushort),
.c_int_type => Type.initTag(.c_int),
.c_uint_type => Type.initTag(.c_uint),
.c_long_type => Type.initTag(.c_long),
.c_ulong_type => Type.initTag(.c_ulong),
.c_longlong_type => Type.initTag(.c_longlong),
.c_ulonglong_type => Type.initTag(.c_ulonglong),
.c_longdouble_type => Type.initTag(.c_longdouble),
.f16_type => Type.initTag(.f16),
.f32_type => Type.initTag(.f32),
.f64_type => Type.initTag(.f64),
.f80_type => Type.initTag(.f80),
.f128_type => Type.initTag(.f128),
.anyopaque_type => Type.initTag(.anyopaque),
.bool_type => Type.initTag(.bool),
.void_type => Type.initTag(.void),
.type_type => Type.initTag(.type),
.anyerror_type => Type.initTag(.anyerror),
.comptime_int_type => Type.initTag(.comptime_int),
.comptime_float_type => Type.initTag(.comptime_float),
.noreturn_type => Type.initTag(.noreturn),
.null_type => Type.initTag(.@"null"),
.undefined_type => Type.initTag(.@"undefined"),
.fn_noreturn_no_args_type => Type.initTag(.fn_noreturn_no_args),
.fn_void_no_args_type => Type.initTag(.fn_void_no_args),
.fn_naked_noreturn_no_args_type => Type.initTag(.fn_naked_noreturn_no_args),
.fn_ccc_void_no_args_type => Type.initTag(.fn_ccc_void_no_args),
.single_const_pointer_to_comptime_int_type => Type.initTag(.single_const_pointer_to_comptime_int),
.anyframe_type => Type.initTag(.@"anyframe"),
.const_slice_u8_type => Type.initTag(.const_slice_u8),
.const_slice_u8_sentinel_0_type => Type.initTag(.const_slice_u8_sentinel_0),
.anyerror_void_error_union_type => Type.initTag(.anyerror_void_error_union),
.generic_poison_type => Type.initTag(.generic_poison),
.enum_literal_type => Type.initTag(.enum_literal),
.manyptr_u8_type => Type.initTag(.manyptr_u8),
.manyptr_const_u8_type => Type.initTag(.manyptr_const_u8),
.manyptr_const_u8_sentinel_0_type => Type.initTag(.manyptr_const_u8_sentinel_0),
.atomic_order_type => Type.initTag(.atomic_order),
.atomic_rmw_op_type => Type.initTag(.atomic_rmw_op),
.calling_convention_type => Type.initTag(.calling_convention),
.address_space_type => Type.initTag(.address_space),
.float_mode_type => Type.initTag(.float_mode),
.reduce_op_type => Type.initTag(.reduce_op),
.call_options_type => Type.initTag(.call_options),
.prefetch_options_type => Type.initTag(.prefetch_options),
.export_options_type => Type.initTag(.export_options),
.extern_options_type => Type.initTag(.extern_options),
.type_info_type => Type.initTag(.type_info),
.int_type => {
const payload = self.castTag(.int_type).?.data;
buffer.* = .{
.base = .{
.tag = if (payload.signed) .int_signed else .int_unsigned,
},
.data = payload.bits,
};
return Type.initPayload(&buffer.base);
},
else => unreachable,
};
}
/// Asserts the type is an enum type.
pub fn toEnum(val: Value, comptime E: type) E {
switch (val.tag()) {
.enum_field_index => {
const field_index = val.castTag(.enum_field_index).?.data;
// TODO should `@intToEnum` do this `@intCast` for you?
return @intToEnum(E, @intCast(@typeInfo(E).Enum.tag_type, field_index));
},
.the_only_possible_value => {
const fields = std.meta.fields(E);
assert(fields.len == 1);
return @intToEnum(E, fields[0].value);
},
else => unreachable,
}
}
pub fn enumToInt(val: Value, ty: Type, buffer: *Payload.U64) Value {
const field_index = switch (val.tag()) {
.enum_field_index => val.castTag(.enum_field_index).?.data,
.the_only_possible_value => blk: {
assert(ty.enumFieldCount() == 1);
break :blk 0;
},
// Assume it is already an integer and return it directly.
else => return val,
};
switch (ty.tag()) {
.enum_full, .enum_nonexhaustive => {
const enum_full = ty.cast(Type.Payload.EnumFull).?.data;
if (enum_full.values.count() != 0) {
return enum_full.values.keys()[field_index];
} else {
// Field index and integer values are the same.
buffer.* = .{
.base = .{ .tag = .int_u64 },
.data = field_index,
};
return Value.initPayload(&buffer.base);
}
},
.enum_numbered => {
const enum_obj = ty.castTag(.enum_numbered).?.data;
if (enum_obj.values.count() != 0) {
return enum_obj.values.keys()[field_index];
} else {
// Field index and integer values are the same.
buffer.* = .{
.base = .{ .tag = .int_u64 },
.data = field_index,
};
return Value.initPayload(&buffer.base);
}
},
.enum_simple => {
// Field index and integer values are the same.
buffer.* = .{
.base = .{ .tag = .int_u64 },
.data = field_index,
};
return Value.initPayload(&buffer.base);
},
else => unreachable,
}
}
/// Asserts the value is an integer.
pub fn toBigInt(self: Value, space: *BigIntSpace) BigIntConst {
switch (self.tag()) {
.zero,
.bool_false,
.the_only_possible_value, // i0, u0
=> return BigIntMutable.init(&space.limbs, 0).toConst(),
.one,
.bool_true,
=> return BigIntMutable.init(&space.limbs, 1).toConst(),
.int_u64 => return BigIntMutable.init(&space.limbs, self.castTag(.int_u64).?.data).toConst(),
.int_i64 => return BigIntMutable.init(&space.limbs, self.castTag(.int_i64).?.data).toConst(),
.int_big_positive => return self.castTag(.int_big_positive).?.asBigInt(),
.int_big_negative => return self.castTag(.int_big_negative).?.asBigInt(),
.undef => unreachable,
else => unreachable,
}
}
/// If the value fits in a u64, return it, otherwise null.
/// Asserts not undefined.
pub fn getUnsignedInt(val: Value) ?u64 {
switch (val.tag()) {
.zero,
.bool_false,
.the_only_possible_value, // i0, u0
=> return 0,
.one,
.bool_true,
=> return 1,
.int_u64 => return val.castTag(.int_u64).?.data,
.int_i64 => return @intCast(u64, val.castTag(.int_i64).?.data),
.int_big_positive => return val.castTag(.int_big_positive).?.asBigInt().to(u64) catch null,
.int_big_negative => return val.castTag(.int_big_negative).?.asBigInt().to(u64) catch null,
.undef => unreachable,
else => return null,
}
}
/// Asserts the value is an integer and it fits in a u64
pub fn toUnsignedInt(val: Value) u64 {
return getUnsignedInt(val).?;
}
/// Asserts the value is an integer and it fits in a i64
pub fn toSignedInt(self: Value) i64 {
switch (self.tag()) {
.zero,
.bool_false,
.the_only_possible_value, // i0, u0
=> return 0,
.one,
.bool_true,
=> return 1,
.int_u64 => return @intCast(i64, self.castTag(.int_u64).?.data),
.int_i64 => return self.castTag(.int_i64).?.data,
.int_big_positive => return self.castTag(.int_big_positive).?.asBigInt().to(i64) catch unreachable,
.int_big_negative => return self.castTag(.int_big_negative).?.asBigInt().to(i64) catch unreachable,
.undef => unreachable,
else => unreachable,
}
}
pub fn toBool(self: Value) bool {
return switch (self.tag()) {
.bool_true, .one => true,
.bool_false, .zero => false,
else => unreachable,
};
}
pub fn writeToMemory(val: Value, ty: Type, mod: *Module, buffer: []u8) void {
const target = mod.getTarget();
if (val.isUndef()) {
const size = @intCast(usize, ty.abiSize(target));
std.mem.set(u8, buffer[0..size], 0xaa);
return;
}
switch (ty.zigTypeTag()) {
.Int => {
var bigint_buffer: BigIntSpace = undefined;
const bigint = val.toBigInt(&bigint_buffer);
const bits = ty.intInfo(target).bits;
const abi_size = @intCast(usize, ty.abiSize(target));
bigint.writeTwosComplement(buffer, bits, abi_size, target.cpu.arch.endian());
},
.Enum => {
var enum_buffer: Payload.U64 = undefined;
const int_val = val.enumToInt(ty, &enum_buffer);
var bigint_buffer: BigIntSpace = undefined;
const bigint = int_val.toBigInt(&bigint_buffer);
const bits = ty.intInfo(target).bits;
const abi_size = @intCast(usize, ty.abiSize(target));
bigint.writeTwosComplement(buffer, bits, abi_size, target.cpu.arch.endian());
},
.Float => switch (ty.floatBits(target)) {
16 => return floatWriteToMemory(f16, val.toFloat(f16), target, buffer),
32 => return floatWriteToMemory(f32, val.toFloat(f32), target, buffer),
64 => return floatWriteToMemory(f64, val.toFloat(f64), target, buffer),
128 => return floatWriteToMemory(f128, val.toFloat(f128), target, buffer),
else => unreachable,
},
.Array, .Vector => {
const len = ty.arrayLen();
const elem_ty = ty.childType();
const elem_size = @intCast(usize, elem_ty.abiSize(target));
var elem_i: usize = 0;
var elem_value_buf: ElemValueBuffer = undefined;
var buf_off: usize = 0;
while (elem_i < len) : (elem_i += 1) {
const elem_val = val.elemValueBuffer(elem_i, &elem_value_buf);
writeToMemory(elem_val, elem_ty, mod, buffer[buf_off..]);
buf_off += elem_size;
}
},
.Struct => switch (ty.containerLayout()) {
.Auto => unreachable, // Sema is supposed to have emitted a compile error already
.Extern => {
const fields = ty.structFields().values();
const field_vals = val.castTag(.aggregate).?.data;
for (fields) |field, i| {
const off = @intCast(usize, ty.structFieldOffset(i, target));
writeToMemory(field_vals[i], field.ty, mod, buffer[off..]);
}
},
.Packed => {
// TODO allocate enough heap space instead of using this buffer
// on the stack.
var buf: [16]std.math.big.Limb = undefined;
const host_int = packedStructToInt(val, ty, target, &buf);
const abi_size = @intCast(usize, ty.abiSize(target));
const bit_size = @intCast(usize, ty.bitSize(target));
host_int.writeTwosComplement(buffer, bit_size, abi_size, target.cpu.arch.endian());
},
},
.ErrorSet => {
// TODO revisit this when we have the concept of the error tag type
const Int = u16;
const int = mod.global_error_set.get(val.castTag(.@"error").?.data.name).?;
std.mem.writeInt(Int, buffer[0..@sizeOf(Int)], @intCast(Int, int), target.cpu.arch.endian());
},
else => @panic("TODO implement writeToMemory for more types"),
}
}
fn packedStructToInt(val: Value, ty: Type, target: Target, buf: []std.math.big.Limb) BigIntConst {
var bigint = BigIntMutable.init(buf, 0);
const fields = ty.structFields().values();
const field_vals = val.castTag(.aggregate).?.data;
var bits: u16 = 0;
// TODO allocate enough heap space instead of using this buffer
// on the stack.
var field_buf: [16]std.math.big.Limb = undefined;
var field_space: BigIntSpace = undefined;
var field_buf2: [16]std.math.big.Limb = undefined;
for (fields) |field, i| {
const field_val = field_vals[i];
const field_bigint_const = switch (field.ty.zigTypeTag()) {
.Float => switch (field.ty.floatBits(target)) {
16 => bitcastFloatToBigInt(f16, val.toFloat(f16), &field_buf),
32 => bitcastFloatToBigInt(f32, val.toFloat(f32), &field_buf),
64 => bitcastFloatToBigInt(f64, val.toFloat(f64), &field_buf),
80 => bitcastFloatToBigInt(f80, val.toFloat(f80), &field_buf),
128 => bitcastFloatToBigInt(f128, val.toFloat(f128), &field_buf),
else => unreachable,
},
.Int, .Bool => field_val.toBigInt(&field_space),
.Struct => packedStructToInt(field_val, field.ty, target, &field_buf),
else => unreachable,
};
var field_bigint = BigIntMutable.init(&field_buf2, 0);
field_bigint.shiftLeft(field_bigint_const, bits);
bits += @intCast(u16, field.ty.bitSize(target));
bigint.bitOr(bigint.toConst(), field_bigint.toConst());
}
return bigint.toConst();
}
fn bitcastFloatToBigInt(comptime F: type, f: F, buf: []std.math.big.Limb) BigIntConst {
const Int = @Type(.{ .Int = .{
.signedness = .unsigned,
.bits = @typeInfo(F).Float.bits,
} });
const int = @bitCast(Int, f);
return BigIntMutable.init(buf, int).toConst();
}
pub fn readFromMemory(
ty: Type,
mod: *Module,
buffer: []const u8,
arena: Allocator,
) Allocator.Error!Value {
const target = mod.getTarget();
switch (ty.zigTypeTag()) {
.Int => {
if (buffer.len == 0) return Value.zero;
const int_info = ty.intInfo(target);
const endian = target.cpu.arch.endian();
const Limb = std.math.big.Limb;
const limb_count = (buffer.len + @sizeOf(Limb) - 1) / @sizeOf(Limb);
const limbs_buffer = try arena.alloc(Limb, limb_count);
const abi_size = @intCast(usize, ty.abiSize(target));
var bigint = BigIntMutable.init(limbs_buffer, 0);
bigint.readTwosComplement(buffer, int_info.bits, abi_size, endian, int_info.signedness);
return fromBigInt(arena, bigint.toConst());
},
.Float => switch (ty.floatBits(target)) {
16 => return Value.Tag.float_16.create(arena, floatReadFromMemory(f16, target, buffer)),
32 => return Value.Tag.float_32.create(arena, floatReadFromMemory(f32, target, buffer)),
64 => return Value.Tag.float_64.create(arena, floatReadFromMemory(f64, target, buffer)),
80 => return Value.Tag.float_80.create(arena, floatReadFromMemory(f80, target, buffer)),
128 => return Value.Tag.float_128.create(arena, floatReadFromMemory(f128, target, buffer)),
else => unreachable,
},
.Array => {
const elem_ty = ty.childType();
const elem_size = elem_ty.abiSize(target);
const elems = try arena.alloc(Value, @intCast(usize, ty.arrayLen()));
var offset: usize = 0;
for (elems) |*elem| {
elem.* = try readFromMemory(elem_ty, mod, buffer[offset..], arena);
offset += @intCast(usize, elem_size);
}
return Tag.aggregate.create(arena, elems);
},
.Struct => switch (ty.containerLayout()) {
.Auto => unreachable, // Sema is supposed to have emitted a compile error already
.Extern => {
const fields = ty.structFields().values();
const field_vals = try arena.alloc(Value, fields.len);
for (fields) |field, i| {
const off = @intCast(usize, ty.structFieldOffset(i, target));
field_vals[i] = try readFromMemory(field.ty, mod, buffer[off..], arena);
}
return Tag.aggregate.create(arena, field_vals);
},
.Packed => {
const endian = target.cpu.arch.endian();
const Limb = std.math.big.Limb;
const abi_size = @intCast(usize, ty.abiSize(target));
const bit_size = @intCast(usize, ty.bitSize(target));
const limb_count = (buffer.len + @sizeOf(Limb) - 1) / @sizeOf(Limb);
const limbs_buffer = try arena.alloc(Limb, limb_count);
var bigint = BigIntMutable.init(limbs_buffer, 0);
bigint.readTwosComplement(buffer, bit_size, abi_size, endian, .unsigned);
return intToPackedStruct(ty, target, bigint.toConst(), arena);
},
},
.ErrorSet => {
// TODO revisit this when we have the concept of the error tag type
const Int = u16;
const int = std.mem.readInt(Int, buffer[0..@sizeOf(Int)], target.cpu.arch.endian());
const payload = try arena.create(Value.Payload.Error);
payload.* = .{
.base = .{ .tag = .@"error" },
.data = .{ .name = mod.error_name_list.items[@intCast(usize, int)] },
};
return Value.initPayload(&payload.base);
},
else => @panic("TODO implement readFromMemory for more types"),
}
}
fn intToPackedStruct(
ty: Type,
target: Target,
bigint: BigIntConst,
arena: Allocator,
) Allocator.Error!Value {
const limbs_buffer = try arena.alloc(std.math.big.Limb, bigint.limbs.len);
var bigint_mut = bigint.toMutable(limbs_buffer);
const fields = ty.structFields().values();
const field_vals = try arena.alloc(Value, fields.len);
var bits: u16 = 0;
for (fields) |field, i| {
const field_bits = @intCast(u16, field.ty.bitSize(target));
bigint_mut.shiftRight(bigint, bits);
bigint_mut.truncate(bigint_mut.toConst(), .unsigned, field_bits);
bits += field_bits;
const field_bigint = bigint_mut.toConst();
field_vals[i] = switch (field.ty.zigTypeTag()) {
.Float => switch (field.ty.floatBits(target)) {
16 => try bitCastBigIntToFloat(f16, .float_16, field_bigint, arena),
32 => try bitCastBigIntToFloat(f32, .float_32, field_bigint, arena),
64 => try bitCastBigIntToFloat(f64, .float_64, field_bigint, arena),
80 => try bitCastBigIntToFloat(f80, .float_80, field_bigint, arena),
128 => try bitCastBigIntToFloat(f128, .float_128, field_bigint, arena),
else => unreachable,
},
.Bool => makeBool(!field_bigint.eqZero()),
.Int => try Tag.int_big_positive.create(
arena,
try arena.dupe(std.math.big.Limb, field_bigint.limbs),
),
.Struct => try intToPackedStruct(field.ty, target, field_bigint, arena),
else => unreachable,
};
}
return Tag.aggregate.create(arena, field_vals);
}
fn bitCastBigIntToFloat(
comptime F: type,
comptime float_tag: Tag,
bigint: BigIntConst,
arena: Allocator,
) !Value {
const Int = @Type(.{ .Int = .{
.signedness = .unsigned,
.bits = @typeInfo(F).Float.bits,
} });
const int = bigint.to(Int) catch |err| switch (err) {
error.NegativeIntoUnsigned => unreachable,
error.TargetTooSmall => unreachable,
};
const f = @bitCast(F, int);
return float_tag.create(arena, f);
}
fn floatWriteToMemory(comptime F: type, f: F, target: Target, buffer: []u8) void {
if (F == f80) {
switch (target.cpu.arch) {
.i386, .x86_64 => {
const repr = std.math.break_f80(f);
std.mem.writeIntLittle(u64, buffer[0..8], repr.fraction);
std.mem.writeIntLittle(u16, buffer[8..10], repr.exp);
// TODO set the rest of the bytes to undefined. should we use 0xaa
// or is there a different way?
return;
},
else => {},
}
}
const Int = @Type(.{ .Int = .{
.signedness = .unsigned,
.bits = @typeInfo(F).Float.bits,
} });
const int = @bitCast(Int, f);
std.mem.writeInt(Int, buffer[0..@sizeOf(Int)], int, target.cpu.arch.endian());
}
fn floatReadFromMemory(comptime F: type, target: Target, buffer: []const u8) F {
if (F == f80) {
switch (target.cpu.arch) {
.i386, .x86_64 => return std.math.make_f80(.{
.fraction = std.mem.readIntLittle(u64, buffer[0..8]),
.exp = std.mem.readIntLittle(u16, buffer[8..10]),
}),
else => {},
}
}
const Int = @Type(.{ .Int = .{
.signedness = .unsigned,
.bits = @typeInfo(F).Float.bits,
} });
const int = readInt(Int, buffer[0..@sizeOf(Int)], target.cpu.arch.endian());
return @bitCast(F, int);
}
fn readInt(comptime Int: type, buffer: *const [@sizeOf(Int)]u8, endian: std.builtin.Endian) Int {
var result: Int = 0;
switch (endian) {
.Big => {
for (buffer) |byte| {
result <<= 8;
result |= byte;
}
},
.Little => {
var i: usize = buffer.len;
while (i != 0) {
i -= 1;
result <<= 8;
result |= buffer[i];
}
},
}
return result;
}
/// Asserts that the value is a float or an integer.
pub fn toFloat(val: Value, comptime T: type) T {
return switch (val.tag()) {
.float_16 => @floatCast(T, val.castTag(.float_16).?.data),
.float_32 => @floatCast(T, val.castTag(.float_32).?.data),
.float_64 => @floatCast(T, val.castTag(.float_64).?.data),
.float_80 => @floatCast(T, val.castTag(.float_80).?.data),
.float_128 => @floatCast(T, val.castTag(.float_128).?.data),
.zero => 0,
.one => 1,
.int_u64 => {
if (T == f80) {
@panic("TODO we can't lower this properly on non-x86 llvm backend yet");
}
return @intToFloat(T, val.castTag(.int_u64).?.data);
},
.int_i64 => {
if (T == f80) {
@panic("TODO we can't lower this properly on non-x86 llvm backend yet");
}
return @intToFloat(T, val.castTag(.int_i64).?.data);
},
.int_big_positive => @floatCast(T, bigIntToFloat(val.castTag(.int_big_positive).?.data, true)),
.int_big_negative => @floatCast(T, bigIntToFloat(val.castTag(.int_big_negative).?.data, false)),
else => unreachable,
};
}
/// TODO move this to std lib big int code
fn bigIntToFloat(limbs: []const std.math.big.Limb, positive: bool) f128 {
if (limbs.len == 0) return 0;
const base = std.math.maxInt(std.math.big.Limb) + 1;
var result: f128 = 0;
var i: usize = limbs.len;
while (i != 0) {
i -= 1;
const limb: f128 = @intToFloat(f128, limbs[i]);
result = @mulAdd(f128, base, limb, result);
}
if (positive) {
return result;
} else {
return -result;
}
}
pub fn clz(val: Value, ty: Type, target: Target) u64 {
const ty_bits = ty.intInfo(target).bits;
switch (val.tag()) {
.zero, .bool_false => return ty_bits,
.one, .bool_true => return ty_bits - 1,
.int_u64 => {
const big = @clz(u64, val.castTag(.int_u64).?.data);
return big + ty_bits - 64;
},
.int_i64 => {
@panic("TODO implement i64 Value clz");
},
.int_big_positive => {
// TODO: move this code into std lib big ints
const bigint = val.castTag(.int_big_positive).?.asBigInt();
// Limbs are stored in little-endian order but we need
// to iterate big-endian.
var total_limb_lz: u64 = 0;
var i: usize = bigint.limbs.len;
const bits_per_limb = @sizeOf(std.math.big.Limb) * 8;
while (i != 0) {
i -= 1;
const limb = bigint.limbs[i];
const this_limb_lz = @clz(std.math.big.Limb, limb);
total_limb_lz += this_limb_lz;
if (this_limb_lz != bits_per_limb) break;
}
const total_limb_bits = bigint.limbs.len * bits_per_limb;
return total_limb_lz + ty_bits - total_limb_bits;
},
.int_big_negative => {
@panic("TODO implement int_big_negative Value clz");
},
.the_only_possible_value => {
assert(ty_bits == 0);
return ty_bits;
},
else => unreachable,
}
}
pub fn ctz(val: Value, ty: Type, target: Target) u64 {
const ty_bits = ty.intInfo(target).bits;
switch (val.tag()) {
.zero, .bool_false => return ty_bits,
.one, .bool_true => return 0,
.int_u64 => {
const big = @ctz(u64, val.castTag(.int_u64).?.data);
return if (big == 64) ty_bits else big;
},
.int_i64 => {
@panic("TODO implement i64 Value ctz");
},
.int_big_positive => {
// TODO: move this code into std lib big ints
const bigint = val.castTag(.int_big_positive).?.asBigInt();
// Limbs are stored in little-endian order.
var result: u64 = 0;
for (bigint.limbs) |limb| {
const limb_tz = @ctz(std.math.big.Limb, limb);
result += limb_tz;
if (limb_tz != @sizeOf(std.math.big.Limb) * 8) break;
}
return result;
},
.int_big_negative => {
@panic("TODO implement int_big_negative Value ctz");
},
.the_only_possible_value => {
assert(ty_bits == 0);
return ty_bits;
},
else => unreachable,
}
}
pub fn popCount(val: Value, ty: Type, target: Target) u64 {
assert(!val.isUndef());
switch (val.tag()) {
.zero, .bool_false => return 0,
.one, .bool_true => return 1,
.int_u64 => return @popCount(u64, val.castTag(.int_u64).?.data),
else => {
const info = ty.intInfo(target);
var buffer: Value.BigIntSpace = undefined;
const operand_bigint = val.toBigInt(&buffer);
var limbs_buffer: [4]std.math.big.Limb = undefined;
var result_bigint = BigIntMutable{
.limbs = &limbs_buffer,
.positive = undefined,
.len = undefined,
};
result_bigint.popCount(operand_bigint, info.bits);
return result_bigint.toConst().to(u64) catch unreachable;
},
}
}
pub fn bitReverse(val: Value, ty: Type, target: Target, arena: Allocator) !Value {
assert(!val.isUndef());
const info = ty.intInfo(target);
var buffer: Value.BigIntSpace = undefined;
const operand_bigint = val.toBigInt(&buffer);
const limbs = try arena.alloc(
std.math.big.Limb,
std.math.big.int.calcTwosCompLimbCount(info.bits),
);
var result_bigint = BigIntMutable{ .limbs = limbs, .positive = undefined, .len = undefined };
result_bigint.bitReverse(operand_bigint, info.signedness, info.bits);
return fromBigInt(arena, result_bigint.toConst());
}
pub fn byteSwap(val: Value, ty: Type, target: Target, arena: Allocator) !Value {
assert(!val.isUndef());
const info = ty.intInfo(target);
// Bit count must be evenly divisible by 8
assert(info.bits % 8 == 0);
var buffer: Value.BigIntSpace = undefined;
const operand_bigint = val.toBigInt(&buffer);
const limbs = try arena.alloc(
std.math.big.Limb,
std.math.big.int.calcTwosCompLimbCount(info.bits),
);
var result_bigint = BigIntMutable{ .limbs = limbs, .positive = undefined, .len = undefined };
result_bigint.byteSwap(operand_bigint, info.signedness, info.bits / 8);
return fromBigInt(arena, result_bigint.toConst());
}
/// Asserts the value is an integer and not undefined.
/// Returns the number of bits the value requires to represent stored in twos complement form.
pub fn intBitCountTwosComp(self: Value, target: Target) usize {
switch (self.tag()) {
.zero,
.bool_false,
.the_only_possible_value,
=> return 0,
.one,
.bool_true,
=> return 1,
.int_u64 => {
const x = self.castTag(.int_u64).?.data;
if (x == 0) return 0;
return @intCast(usize, std.math.log2(x) + 1);
},
.int_big_positive => return self.castTag(.int_big_positive).?.asBigInt().bitCountTwosComp(),
.int_big_negative => return self.castTag(.int_big_negative).?.asBigInt().bitCountTwosComp(),
.decl_ref_mut,
.extern_fn,
.decl_ref,
.function,
.variable,
.eu_payload_ptr,
.opt_payload_ptr,
=> return target.cpu.arch.ptrBitWidth(),
else => {
var buffer: BigIntSpace = undefined;
return self.toBigInt(&buffer).bitCountTwosComp();
},
}
}
/// Asserts the value is an integer, and the destination type is ComptimeInt or Int.
pub fn intFitsInType(self: Value, ty: Type, target: Target) bool {
switch (self.tag()) {
.zero,
.undef,
.bool_false,
=> return true,
.one,
.bool_true,
=> switch (ty.zigTypeTag()) {
.Int => {
const info = ty.intInfo(target);
return switch (info.signedness) {
.signed => info.bits >= 2,
.unsigned => info.bits >= 1,
};
},
.ComptimeInt => return true,
else => unreachable,
},
.int_u64 => switch (ty.zigTypeTag()) {
.Int => {
const x = self.castTag(.int_u64).?.data;
if (x == 0) return true;
const info = ty.intInfo(target);
const needed_bits = std.math.log2(x) + 1 + @boolToInt(info.signedness == .signed);
return info.bits >= needed_bits;
},
.ComptimeInt => return true,
else => unreachable,
},
.int_i64 => switch (ty.zigTypeTag()) {
.Int => {
const x = self.castTag(.int_i64).?.data;
if (x == 0) return true;
const info = ty.intInfo(target);
if (info.signedness == .unsigned and x < 0)
return false;
var buffer: BigIntSpace = undefined;
return self.toBigInt(&buffer).fitsInTwosComp(info.signedness, info.bits);
},
.ComptimeInt => return true,
else => unreachable,
},
.int_big_positive => switch (ty.zigTypeTag()) {
.Int => {
const info = ty.intInfo(target);
return self.castTag(.int_big_positive).?.asBigInt().fitsInTwosComp(info.signedness, info.bits);
},
.ComptimeInt => return true,
else => unreachable,
},
.int_big_negative => switch (ty.zigTypeTag()) {
.Int => {
const info = ty.intInfo(target);
return self.castTag(.int_big_negative).?.asBigInt().fitsInTwosComp(info.signedness, info.bits);
},
.ComptimeInt => return true,
else => unreachable,
},
.the_only_possible_value => {
assert(ty.intInfo(target).bits == 0);
return true;
},
.decl_ref_mut,
.extern_fn,
.decl_ref,
.function,
.variable,
=> switch (ty.zigTypeTag()) {
.Int => {
const info = ty.intInfo(target);
const ptr_bits = target.cpu.arch.ptrBitWidth();
return switch (info.signedness) {
.signed => info.bits > ptr_bits,
.unsigned => info.bits >= ptr_bits,
};
},
.ComptimeInt => return true,
else => unreachable,
},
else => unreachable,
}
}
/// Converts an integer or a float to a float. May result in a loss of information.
/// Caller can find out by equality checking the result against the operand.
pub fn floatCast(self: Value, arena: Allocator, dest_ty: Type, target: Target) !Value {
switch (dest_ty.floatBits(target)) {
16 => return Value.Tag.float_16.create(arena, self.toFloat(f16)),
32 => return Value.Tag.float_32.create(arena, self.toFloat(f32)),
64 => return Value.Tag.float_64.create(arena, self.toFloat(f64)),
80 => return Value.Tag.float_80.create(arena, self.toFloat(f80)),
128 => return Value.Tag.float_128.create(arena, self.toFloat(f128)),
else => unreachable,
}
}
/// Asserts the value is a float
pub fn floatHasFraction(self: Value) bool {
return switch (self.tag()) {
.zero,
.one,
=> false,
.float_16 => @rem(self.castTag(.float_16).?.data, 1) != 0,
.float_32 => @rem(self.castTag(.float_32).?.data, 1) != 0,
.float_64 => @rem(self.castTag(.float_64).?.data, 1) != 0,
//.float_80 => @rem(self.castTag(.float_80).?.data, 1) != 0,
.float_80 => @panic("TODO implement __remx in compiler-rt"),
.float_128 => @rem(self.castTag(.float_128).?.data, 1) != 0,
else => unreachable,
};
}
/// Asserts the value is numeric
pub fn isZero(self: Value) bool {
return switch (self.tag()) {
.zero, .the_only_possible_value => true,
.one => false,
.int_u64 => self.castTag(.int_u64).?.data == 0,
.int_i64 => self.castTag(.int_i64).?.data == 0,
.float_16 => self.castTag(.float_16).?.data == 0,
.float_32 => self.castTag(.float_32).?.data == 0,
.float_64 => self.castTag(.float_64).?.data == 0,
.float_80 => self.castTag(.float_80).?.data == 0,
.float_128 => self.castTag(.float_128).?.data == 0,
.int_big_positive => self.castTag(.int_big_positive).?.asBigInt().eqZero(),
.int_big_negative => self.castTag(.int_big_negative).?.asBigInt().eqZero(),
else => unreachable,
};
}
pub fn orderAgainstZero(lhs: Value) std.math.Order {
return switch (lhs.tag()) {
.zero,
.bool_false,
.the_only_possible_value,
=> .eq,
.one,
.bool_true,
.decl_ref,
.decl_ref_mut,
.extern_fn,
.function,
.variable,
=> .gt,
.int_u64 => std.math.order(lhs.castTag(.int_u64).?.data, 0),
.int_i64 => std.math.order(lhs.castTag(.int_i64).?.data, 0),
.int_big_positive => lhs.castTag(.int_big_positive).?.asBigInt().orderAgainstScalar(0),
.int_big_negative => lhs.castTag(.int_big_negative).?.asBigInt().orderAgainstScalar(0),
.float_16 => std.math.order(lhs.castTag(.float_16).?.data, 0),
.float_32 => std.math.order(lhs.castTag(.float_32).?.data, 0),
.float_64 => std.math.order(lhs.castTag(.float_64).?.data, 0),
.float_80 => std.math.order(lhs.castTag(.float_80).?.data, 0),
.float_128 => std.math.order(lhs.castTag(.float_128).?.data, 0),
else => unreachable,
};
}
/// Asserts the value is comparable.
pub fn order(lhs: Value, rhs: Value) std.math.Order {
const lhs_tag = lhs.tag();
const rhs_tag = rhs.tag();
const lhs_against_zero = lhs.orderAgainstZero();
const rhs_against_zero = rhs.orderAgainstZero();
switch (lhs_against_zero) {
.lt => if (rhs_against_zero != .lt) return .lt,
.eq => return rhs_against_zero.invert(),
.gt => {},
}
switch (rhs_against_zero) {
.lt => if (lhs_against_zero != .lt) return .gt,
.eq => return lhs_against_zero,
.gt => {},
}
const lhs_float = lhs.isFloat();
const rhs_float = rhs.isFloat();
if (lhs_float and rhs_float) {
if (lhs_tag == rhs_tag) {
return switch (lhs.tag()) {
.float_16 => return std.math.order(lhs.castTag(.float_16).?.data, rhs.castTag(.float_16).?.data),
.float_32 => return std.math.order(lhs.castTag(.float_32).?.data, rhs.castTag(.float_32).?.data),
.float_64 => return std.math.order(lhs.castTag(.float_64).?.data, rhs.castTag(.float_64).?.data),
.float_80 => return std.math.order(lhs.castTag(.float_80).?.data, rhs.castTag(.float_80).?.data),
.float_128 => return std.math.order(lhs.castTag(.float_128).?.data, rhs.castTag(.float_128).?.data),
else => unreachable,
};
}
}
if (lhs_float or rhs_float) {
const lhs_f128 = lhs.toFloat(f128);
const rhs_f128 = rhs.toFloat(f128);
return std.math.order(lhs_f128, rhs_f128);
}
var lhs_bigint_space: BigIntSpace = undefined;
var rhs_bigint_space: BigIntSpace = undefined;
const lhs_bigint = lhs.toBigInt(&lhs_bigint_space);
const rhs_bigint = rhs.toBigInt(&rhs_bigint_space);
return lhs_bigint.order(rhs_bigint);
}
/// Asserts the value is comparable. Does not take a type parameter because it supports
/// comparisons between heterogeneous types.
pub fn compareHetero(lhs: Value, op: std.math.CompareOperator, rhs: Value) bool {
if (lhs.pointerDecl()) |lhs_decl| {
if (rhs.pointerDecl()) |rhs_decl| {
switch (op) {
.eq => return lhs_decl == rhs_decl,
.neq => return lhs_decl != rhs_decl,
else => {},
}
} else {
switch (op) {
.eq => return false,
.neq => return true,
else => {},
}
}
} else if (rhs.pointerDecl()) |_| {
switch (op) {
.eq => return false,
.neq => return true,
else => {},
}
}
return order(lhs, rhs).compare(op);
}
/// Asserts the value is comparable. Both operands have type `ty`.
pub fn compare(lhs: Value, op: std.math.CompareOperator, rhs: Value, ty: Type) bool {
return switch (op) {
.eq => lhs.eql(rhs, ty),
.neq => !lhs.eql(rhs, ty),
else => compareHetero(lhs, op, rhs),
};
}
/// Asserts the value is comparable.
/// For vectors this is only valid with op == .eq.
pub fn compareWithZero(lhs: Value, op: std.math.CompareOperator) bool {
switch (lhs.tag()) {
.repeated => {
assert(op == .eq);
return lhs.castTag(.repeated).?.data.compareWithZero(.eq);
},
.aggregate => {
assert(op == .eq);
for (lhs.castTag(.aggregate).?.data) |elem_val| {
if (!elem_val.compareWithZero(.eq)) return false;
}
return true;
},
else => {},
}
return orderAgainstZero(lhs).compare(op);
}
/// This function is used by hash maps and so treats floating-point NaNs as equal
/// to each other, and not equal to other floating-point values.
pub fn eql(a: Value, b: Value, ty: Type) bool {
const a_tag = a.tag();
const b_tag = b.tag();
assert(a_tag != .undef);
assert(b_tag != .undef);
if (a_tag == b_tag) switch (a_tag) {
.void_value, .null_value, .the_only_possible_value, .empty_struct_value => return true,
.enum_literal => {
const a_name = a.castTag(.enum_literal).?.data;
const b_name = b.castTag(.enum_literal).?.data;
return std.mem.eql(u8, a_name, b_name);
},
.enum_field_index => {
const a_field_index = a.castTag(.enum_field_index).?.data;
const b_field_index = b.castTag(.enum_field_index).?.data;
return a_field_index == b_field_index;
},
.opt_payload => {
const a_payload = a.castTag(.opt_payload).?.data;
const b_payload = b.castTag(.opt_payload).?.data;
var buffer: Type.Payload.ElemType = undefined;
return eql(a_payload, b_payload, ty.optionalChild(&buffer));
},
.slice => {
const a_payload = a.castTag(.slice).?.data;
const b_payload = b.castTag(.slice).?.data;
if (!eql(a_payload.len, b_payload.len, Type.usize)) return false;
var ptr_buf: Type.SlicePtrFieldTypeBuffer = undefined;
const ptr_ty = ty.slicePtrFieldType(&ptr_buf);
return eql(a_payload.ptr, b_payload.ptr, ptr_ty);
},
.elem_ptr => {
const a_payload = a.castTag(.elem_ptr).?.data;
const b_payload = b.castTag(.elem_ptr).?.data;
if (a_payload.index != b_payload.index) return false;
return eql(a_payload.array_ptr, b_payload.array_ptr, ty);
},
.field_ptr => {
const a_payload = a.castTag(.field_ptr).?.data;
const b_payload = b.castTag(.field_ptr).?.data;
if (a_payload.field_index != b_payload.field_index) return false;
return eql(a_payload.container_ptr, b_payload.container_ptr, ty);
},
.@"error" => {
const a_name = a.castTag(.@"error").?.data.name;
const b_name = b.castTag(.@"error").?.data.name;
return std.mem.eql(u8, a_name, b_name);
},
.eu_payload => {
const a_payload = a.castTag(.eu_payload).?.data;
const b_payload = b.castTag(.eu_payload).?.data;
return eql(a_payload, b_payload, ty.errorUnionPayload());
},
.eu_payload_ptr => @panic("TODO: Implement more pointer eql cases"),
.opt_payload_ptr => @panic("TODO: Implement more pointer eql cases"),
.function => {
const a_payload = a.castTag(.function).?.data;
const b_payload = b.castTag(.function).?.data;
return a_payload == b_payload;
},
.aggregate => {
const a_field_vals = a.castTag(.aggregate).?.data;
const b_field_vals = b.castTag(.aggregate).?.data;
assert(a_field_vals.len == b_field_vals.len);
if (ty.isTupleOrAnonStruct()) {
const types = ty.tupleFields().types;
assert(types.len == a_field_vals.len);
for (types) |field_ty, i| {
if (!eql(a_field_vals[i], b_field_vals[i], field_ty)) return false;
}
return true;
}
if (ty.zigTypeTag() == .Struct) {
const fields = ty.structFields().values();
assert(fields.len == a_field_vals.len);
for (fields) |field, i| {
if (!eql(a_field_vals[i], b_field_vals[i], field.ty)) return false;
}
return true;
}
const elem_ty = ty.childType();
for (a_field_vals) |a_elem, i| {
const b_elem = b_field_vals[i];
if (!eql(a_elem, b_elem, elem_ty)) return false;
}
return true;
},
.@"union" => {
const a_union = a.castTag(.@"union").?.data;
const b_union = b.castTag(.@"union").?.data;
switch (ty.containerLayout()) {
.Packed, .Extern => {
// In this case, we must disregard mismatching tags and compare
// based on the in-memory bytes of the payloads.
@panic("TODO implement comparison of extern union values");
},
.Auto => {
const tag_ty = ty.unionTagTypeHypothetical();
if (!a_union.tag.eql(b_union.tag, tag_ty)) {
return false;
}
const active_field_ty = ty.unionFieldType(a_union.tag);
return a_union.val.eql(b_union.val, active_field_ty);
},
}
},
else => {},
} else if (a_tag == .null_value or b_tag == .null_value) {
return false;
}
if (a.pointerDecl()) |a_decl| {
if (b.pointerDecl()) |b_decl| {
return a_decl == b_decl;
} else {
return false;
}
} else if (b.pointerDecl()) |_| {
return false;
}
switch (ty.zigTypeTag()) {
.Type => {
var buf_a: ToTypeBuffer = undefined;
var buf_b: ToTypeBuffer = undefined;
const a_type = a.toType(&buf_a);
const b_type = b.toType(&buf_b);
return a_type.eql(b_type);
},
.Enum => {
var buf_a: Payload.U64 = undefined;
var buf_b: Payload.U64 = undefined;
const a_val = a.enumToInt(ty, &buf_a);
const b_val = b.enumToInt(ty, &buf_b);
var buf_ty: Type.Payload.Bits = undefined;
const int_ty = ty.intTagType(&buf_ty);
return eql(a_val, b_val, int_ty);
},
.Array, .Vector => {
const len = ty.arrayLen();
const elem_ty = ty.childType();
var i: usize = 0;
var a_buf: ElemValueBuffer = undefined;
var b_buf: ElemValueBuffer = undefined;
while (i < len) : (i += 1) {
const a_elem = elemValueBuffer(a, i, &a_buf);
const b_elem = elemValueBuffer(b, i, &b_buf);
if (!eql(a_elem, b_elem, elem_ty)) return false;
}
return true;
},
.Struct => {
// A tuple can be represented with .empty_struct_value,
// the_one_possible_value, .aggregate in which case we could
// end up here and the values are equal if the type has zero fields.
return ty.structFieldCount() != 0;
},
.Float => {
const a_nan = a.isNan();
const b_nan = b.isNan();
if (a_nan or b_nan) {
return a_nan and b_nan;
}
return order(a, b).compare(.eq);
},
else => return order(a, b).compare(.eq),
}
}
/// This function is used by hash maps and so treats floating-point NaNs as equal
/// to each other, and not equal to other floating-point values.
pub fn hash(val: Value, ty: Type, hasher: *std.hash.Wyhash) void {
const zig_ty_tag = ty.zigTypeTag();
std.hash.autoHash(hasher, zig_ty_tag);
if (val.isUndef()) return;
switch (zig_ty_tag) {
.BoundFn => unreachable, // TODO remove this from the language
.Opaque => unreachable, // Cannot hash opaque types
.Void,
.NoReturn,
.Undefined,
.Null,
=> {},
.Type => {
var buf: ToTypeBuffer = undefined;
return val.toType(&buf).hashWithHasher(hasher);
},
.Float, .ComptimeFloat => {
// Normalize the float here because this hash must match eql semantics.
// These functions are used for hash maps so we want NaN to equal itself,
// and -0.0 to equal +0.0.
const float = val.toFloat(f128);
if (std.math.isNan(float)) {
std.hash.autoHash(hasher, std.math.nan_u128);
} else if (float == 0.0) {
var normalized_zero: f128 = 0.0;
std.hash.autoHash(hasher, @bitCast(u128, normalized_zero));
} else {
std.hash.autoHash(hasher, @bitCast(u128, float));
}
},
.Bool, .Int, .ComptimeInt, .Pointer => switch (val.tag()) {
.slice => {
const slice = val.castTag(.slice).?.data;
var ptr_buf: Type.SlicePtrFieldTypeBuffer = undefined;
const ptr_ty = ty.slicePtrFieldType(&ptr_buf);
hash(slice.ptr, ptr_ty, hasher);
hash(slice.len, Type.usize, hasher);
},
else => return hashPtr(val, hasher),
},
.Array, .Vector => {
const len = ty.arrayLen();
const elem_ty = ty.childType();
var index: usize = 0;
var elem_value_buf: ElemValueBuffer = undefined;
while (index < len) : (index += 1) {
const elem_val = val.elemValueBuffer(index, &elem_value_buf);
elem_val.hash(elem_ty, hasher);
}
},
.Struct => {
if (ty.isTupleOrAnonStruct()) {
const fields = ty.tupleFields();
for (fields.values) |field_val, i| {
field_val.hash(fields.types[i], hasher);
}
return;
}
const fields = ty.structFields().values();
if (fields.len == 0) return;
switch (val.tag()) {
.empty_struct_value => {
for (fields) |field| {
field.default_val.hash(field.ty, hasher);
}
},
.aggregate => {
const field_values = val.castTag(.aggregate).?.data;
for (field_values) |field_val, i| {
field_val.hash(fields[i].ty, hasher);
}
},
else => unreachable,
}
},
.Optional => {
if (val.castTag(.opt_payload)) |payload| {
std.hash.autoHash(hasher, true); // non-null
const sub_val = payload.data;
var buffer: Type.Payload.ElemType = undefined;
const sub_ty = ty.optionalChild(&buffer);
sub_val.hash(sub_ty, hasher);
} else {
std.hash.autoHash(hasher, false); // non-null
}
},
.ErrorUnion => {
if (val.tag() == .@"error") {
std.hash.autoHash(hasher, false); // error
const sub_ty = ty.errorUnionSet();
val.hash(sub_ty, hasher);
return;
}
if (val.castTag(.eu_payload)) |payload| {
std.hash.autoHash(hasher, true); // payload
const sub_ty = ty.errorUnionPayload();
payload.data.hash(sub_ty, hasher);
return;
} else unreachable;
},
.ErrorSet => {
// just hash the literal error value. this is the most stable
// thing between compiler invocations. we can't use the error
// int cause (1) its not stable and (2) we don't have access to mod.
hasher.update(val.getError().?);
},
.Enum => {
var enum_space: Payload.U64 = undefined;
const int_val = val.enumToInt(ty, &enum_space);
hashInt(int_val, hasher);
},
.Union => {
const union_obj = val.cast(Payload.Union).?.data;
if (ty.unionTagType()) |tag_ty| {
union_obj.tag.hash(tag_ty, hasher);
}
const active_field_ty = ty.unionFieldType(union_obj.tag);
union_obj.val.hash(active_field_ty, hasher);
},
.Fn => {
const func: *Module.Fn = val.castTag(.function).?.data;
// Note that his hashes the *Fn rather than the *Decl. This is
// to differentiate function bodies from function pointers.
// This is currently redundant since we already hash the zig type tag
// at the top of this function.
std.hash.autoHash(hasher, func);
},
.Frame => {
@panic("TODO implement hashing frame values");
},
.AnyFrame => {
@panic("TODO implement hashing anyframe values");
},
.EnumLiteral => {
const bytes = val.castTag(.enum_literal).?.data;
hasher.update(bytes);
},
}
}
pub const ArrayHashContext = struct {
ty: Type,
pub fn hash(self: @This(), val: Value) u32 {
const other_context: HashContext = .{ .ty = self.ty };
return @truncate(u32, other_context.hash(val));
}
pub fn eql(self: @This(), a: Value, b: Value, b_index: usize) bool {
_ = b_index;
return a.eql(b, self.ty);
}
};
pub const HashContext = struct {
ty: Type,
pub fn hash(self: @This(), val: Value) u64 {
var hasher = std.hash.Wyhash.init(0);
val.hash(self.ty, &hasher);
return hasher.final();
}
pub fn eql(self: @This(), a: Value, b: Value) bool {
return a.eql(b, self.ty);
}
};
pub fn isComptimeMutablePtr(val: Value) bool {
return switch (val.tag()) {
.decl_ref_mut => true,
.elem_ptr => isComptimeMutablePtr(val.castTag(.elem_ptr).?.data.array_ptr),
.field_ptr => isComptimeMutablePtr(val.castTag(.field_ptr).?.data.container_ptr),
.eu_payload_ptr => isComptimeMutablePtr(val.castTag(.eu_payload_ptr).?.data.container_ptr),
.opt_payload_ptr => isComptimeMutablePtr(val.castTag(.opt_payload_ptr).?.data.container_ptr),
else => false,
};
}
pub fn canMutateComptimeVarState(val: Value) bool {
if (val.isComptimeMutablePtr()) return true;
switch (val.tag()) {
.repeated => return val.castTag(.repeated).?.data.canMutateComptimeVarState(),
.eu_payload => return val.castTag(.eu_payload).?.data.canMutateComptimeVarState(),
.eu_payload_ptr => return val.castTag(.eu_payload_ptr).?.data.container_ptr.canMutateComptimeVarState(),
.opt_payload => return val.castTag(.opt_payload).?.data.canMutateComptimeVarState(),
.opt_payload_ptr => return val.castTag(.opt_payload_ptr).?.data.container_ptr.canMutateComptimeVarState(),
.aggregate => {
const fields = val.castTag(.aggregate).?.data;
for (fields) |field| {
if (field.canMutateComptimeVarState()) return true;
}
return false;
},
.@"union" => return val.cast(Payload.Union).?.data.val.canMutateComptimeVarState(),
else => return false,
}
}
/// Gets the decl referenced by this pointer. If the pointer does not point
/// to a decl, or if it points to some part of a decl (like field_ptr or element_ptr),
/// this function returns null.
pub fn pointerDecl(val: Value) ?*Module.Decl {
return switch (val.tag()) {
.decl_ref_mut => val.castTag(.decl_ref_mut).?.data.decl,
.extern_fn => val.castTag(.extern_fn).?.data.owner_decl,
.function => val.castTag(.function).?.data.owner_decl,
.variable => val.castTag(.variable).?.data.owner_decl,
.decl_ref => val.cast(Payload.Decl).?.data,
else => null,
};
}
fn hashInt(int_val: Value, hasher: *std.hash.Wyhash) void {
var buffer: BigIntSpace = undefined;
const big = int_val.toBigInt(&buffer);
std.hash.autoHash(hasher, big.positive);
for (big.limbs) |limb| {
std.hash.autoHash(hasher, limb);
}
}
fn hashPtr(ptr_val: Value, hasher: *std.hash.Wyhash) void {
switch (ptr_val.tag()) {
.decl_ref,
.decl_ref_mut,
.extern_fn,
.function,
.variable,
=> {
const decl: *Module.Decl = ptr_val.pointerDecl().?;
std.hash.autoHash(hasher, decl);
},
.elem_ptr => {
const elem_ptr = ptr_val.castTag(.elem_ptr).?.data;
hashPtr(elem_ptr.array_ptr, hasher);
std.hash.autoHash(hasher, Value.Tag.elem_ptr);
std.hash.autoHash(hasher, elem_ptr.index);
},
.field_ptr => {
const field_ptr = ptr_val.castTag(.field_ptr).?.data;
std.hash.autoHash(hasher, Value.Tag.field_ptr);
hashPtr(field_ptr.container_ptr, hasher);
std.hash.autoHash(hasher, field_ptr.field_index);
},
.eu_payload_ptr => {
const err_union_ptr = ptr_val.castTag(.eu_payload_ptr).?.data;
std.hash.autoHash(hasher, Value.Tag.eu_payload_ptr);
hashPtr(err_union_ptr.container_ptr, hasher);
},
.opt_payload_ptr => {
const opt_ptr = ptr_val.castTag(.opt_payload_ptr).?.data;
std.hash.autoHash(hasher, Value.Tag.opt_payload_ptr);
hashPtr(opt_ptr.container_ptr, hasher);
},
.zero,
.one,
.int_u64,
.int_i64,
.int_big_positive,
.int_big_negative,
.bool_false,
.bool_true,
.the_only_possible_value,
=> return hashInt(ptr_val, hasher),
else => unreachable,
}
}
pub fn markReferencedDeclsAlive(val: Value) void {
switch (val.tag()) {
.decl_ref_mut => return val.castTag(.decl_ref_mut).?.data.decl.markAlive(),
.extern_fn => return val.castTag(.extern_fn).?.data.owner_decl.markAlive(),
.function => return val.castTag(.function).?.data.owner_decl.markAlive(),
.variable => return val.castTag(.variable).?.data.owner_decl.markAlive(),
.decl_ref => return val.cast(Payload.Decl).?.data.markAlive(),
.repeated,
.eu_payload,
.opt_payload,
.empty_array_sentinel,
=> return markReferencedDeclsAlive(val.cast(Payload.SubValue).?.data),
.eu_payload_ptr,
.opt_payload_ptr,
=> return markReferencedDeclsAlive(val.cast(Payload.PayloadPtr).?.data.container_ptr),
.slice => {
const slice = val.cast(Payload.Slice).?.data;
markReferencedDeclsAlive(slice.ptr);
markReferencedDeclsAlive(slice.len);
},
.elem_ptr => {
const elem_ptr = val.cast(Payload.ElemPtr).?.data;
return markReferencedDeclsAlive(elem_ptr.array_ptr);
},
.field_ptr => {
const field_ptr = val.cast(Payload.FieldPtr).?.data;
return markReferencedDeclsAlive(field_ptr.container_ptr);
},
.aggregate => {
for (val.castTag(.aggregate).?.data) |field_val| {
markReferencedDeclsAlive(field_val);
}
},
.@"union" => {
const data = val.cast(Payload.Union).?.data;
markReferencedDeclsAlive(data.tag);
markReferencedDeclsAlive(data.val);
},
else => {},
}
}
pub fn slicePtr(val: Value) Value {
return switch (val.tag()) {
.slice => val.castTag(.slice).?.data.ptr,
// TODO this should require being a slice tag, and not allow decl_ref, field_ptr, etc.
.decl_ref, .decl_ref_mut, .field_ptr, .elem_ptr => val,
else => unreachable,
};
}
pub fn sliceLen(val: Value) u64 {
return switch (val.tag()) {
.slice => val.castTag(.slice).?.data.len.toUnsignedInt(),
.decl_ref => {
const decl = val.castTag(.decl_ref).?.data;
if (decl.ty.zigTypeTag() == .Array) {
return decl.ty.arrayLen();
} else {
return 1;
}
},
else => unreachable,
};
}
/// Asserts the value is a single-item pointer to an array, or an array,
/// or an unknown-length pointer, and returns the element value at the index.
pub fn elemValue(val: Value, arena: Allocator, index: usize) !Value {
return elemValueAdvanced(val, index, arena, undefined);
}
pub const ElemValueBuffer = Payload.U64;
pub fn elemValueBuffer(val: Value, index: usize, buffer: *ElemValueBuffer) Value {
return elemValueAdvanced(val, index, null, buffer) catch unreachable;
}
pub fn elemValueAdvanced(
val: Value,
index: usize,
arena: ?Allocator,
buffer: *ElemValueBuffer,
) error{OutOfMemory}!Value {
switch (val.tag()) {
// This is the case of accessing an element of an undef array.
.undef => return Value.undef,
.empty_array => unreachable, // out of bounds array index
.empty_struct_value => unreachable, // out of bounds array index
.empty_array_sentinel => {
assert(index == 0); // The only valid index for an empty array with sentinel.
return val.castTag(.empty_array_sentinel).?.data;
},
.bytes => {
const byte = val.castTag(.bytes).?.data[index];
if (arena) |a| {
return Tag.int_u64.create(a, byte);
} else {
buffer.* = .{
.base = .{ .tag = .int_u64 },
.data = byte,
};
return initPayload(&buffer.base);
}
},
// No matter the index; all the elements are the same!
.repeated => return val.castTag(.repeated).?.data,
.aggregate => return val.castTag(.aggregate).?.data[index],
.slice => return val.castTag(.slice).?.data.ptr.elemValueAdvanced(index, arena, buffer),
.decl_ref => return val.castTag(.decl_ref).?.data.val.elemValueAdvanced(index, arena, buffer),
.decl_ref_mut => return val.castTag(.decl_ref_mut).?.data.decl.val.elemValueAdvanced(index, arena, buffer),
.elem_ptr => {
const data = val.castTag(.elem_ptr).?.data;
return data.array_ptr.elemValueAdvanced(index + data.index, arena, buffer);
},
// The child type of arrays which have only one possible value need
// to have only one possible value itself.
.the_only_possible_value => return val,
else => unreachable,
}
}
// Asserts that the provided start/end are in-bounds.
pub fn sliceArray(val: Value, arena: Allocator, start: usize, end: usize) error{OutOfMemory}!Value {
return switch (val.tag()) {
.empty_array_sentinel => if (start == 0 and end == 1) val else Value.initTag(.empty_array),
.bytes => Tag.bytes.create(arena, val.castTag(.bytes).?.data[start..end]),
.aggregate => Tag.aggregate.create(arena, val.castTag(.aggregate).?.data[start..end]),
.slice => sliceArray(val.castTag(.slice).?.data.ptr, arena, start, end),
.decl_ref => sliceArray(val.castTag(.decl_ref).?.data.val, arena, start, end),
.decl_ref_mut => sliceArray(val.castTag(.decl_ref_mut).?.data.decl.val, arena, start, end),
.elem_ptr => blk: {
const elem_ptr = val.castTag(.elem_ptr).?.data;
break :blk sliceArray(elem_ptr.array_ptr, arena, start + elem_ptr.index, end + elem_ptr.index);
},
.repeated,
.the_only_possible_value,
=> val,
else => unreachable,
};
}
pub fn fieldValue(val: Value, allocator: Allocator, index: usize) error{OutOfMemory}!Value {
_ = allocator;
switch (val.tag()) {
.aggregate => {
const field_values = val.castTag(.aggregate).?.data;
return field_values[index];
},
.@"union" => {
const payload = val.castTag(.@"union").?.data;
// TODO assert the tag is correct
return payload.val;
},
// Structs which have only one possible value need to consist of members which have only one possible value.
.the_only_possible_value => return val,
else => unreachable,
}
}
pub fn unionTag(val: Value) Value {
switch (val.tag()) {
.undef, .enum_field_index => return val,
.@"union" => return val.castTag(.@"union").?.data.tag,
else => unreachable,
}
}
/// Returns a pointer to the element value at the index.
pub fn elemPtr(val: Value, ty: Type, arena: Allocator, index: usize) Allocator.Error!Value {
const elem_ty = ty.elemType2();
const ptr_val = switch (val.tag()) {
.slice => val.castTag(.slice).?.data.ptr,
else => val,
};
if (ptr_val.tag() == .elem_ptr) {
const elem_ptr = ptr_val.castTag(.elem_ptr).?.data;
if (elem_ptr.elem_ty.eql(elem_ty)) {
return Tag.elem_ptr.create(arena, .{
.array_ptr = elem_ptr.array_ptr,
.elem_ty = elem_ptr.elem_ty,
.index = elem_ptr.index + index,
});
}
}
return Tag.elem_ptr.create(arena, .{
.array_ptr = ptr_val,
.elem_ty = elem_ty,
.index = index,
});
}
pub fn isUndef(self: Value) bool {
return self.tag() == .undef;
}
/// TODO: check for cases such as array that is not marked undef but all the element
/// values are marked undef, or struct that is not marked undef but all fields are marked
/// undef, etc.
pub fn isUndefDeep(self: Value) bool {
return self.isUndef();
}
/// Asserts the value is not undefined and not unreachable.
/// Integer value 0 is considered null because of C pointers.
pub fn isNull(self: Value) bool {
return switch (self.tag()) {
.null_value => true,
.opt_payload => false,
// If it's not one of those two tags then it must be a C pointer value,
// in which case the value 0 is null and other values are non-null.
.zero,
.bool_false,
.the_only_possible_value,
=> true,
.one,
.bool_true,
=> false,
.int_u64,
.int_i64,
.int_big_positive,
.int_big_negative,
=> compareWithZero(self, .eq),
.undef => unreachable,
.unreachable_value => unreachable,
.inferred_alloc => unreachable,
.inferred_alloc_comptime => unreachable,
else => false,
};
}
/// Valid for all types. Asserts the value is not undefined and not unreachable.
/// Prefer `errorUnionIsPayload` to find out whether something is an error or not
/// because it works without having to figure out the string.
pub fn getError(self: Value) ?[]const u8 {
return switch (self.tag()) {
.@"error" => self.castTag(.@"error").?.data.name,
.int_u64 => @panic("TODO"),
.int_i64 => @panic("TODO"),
.int_big_positive => @panic("TODO"),
.int_big_negative => @panic("TODO"),
.one => @panic("TODO"),
.undef => unreachable,
.unreachable_value => unreachable,
.inferred_alloc => unreachable,
.inferred_alloc_comptime => unreachable,
else => null,
};
}
/// Assumes the type is an error union. Returns true if and only if the value is
/// the error union payload, not an error.
pub fn errorUnionIsPayload(val: Value) bool {
return switch (val.tag()) {
.eu_payload => true,
else => false,
.undef => unreachable,
.inferred_alloc => unreachable,
.inferred_alloc_comptime => unreachable,
};
}
/// Value of the optional, null if optional has no payload.
pub fn optionalValue(val: Value) ?Value {
if (val.isNull()) return null;
// Valid for optional representation to be the direct value
// and not use opt_payload.
return if (val.castTag(.opt_payload)) |p| p.data else val;
}
/// Valid for all types. Asserts the value is not undefined.
pub fn isFloat(self: Value) bool {
return switch (self.tag()) {
.undef => unreachable,
.inferred_alloc => unreachable,
.inferred_alloc_comptime => unreachable,
.float_16,
.float_32,
.float_64,
.float_80,
.float_128,
=> true,
else => false,
};
}
pub fn intToFloat(val: Value, arena: Allocator, dest_ty: Type, target: Target) !Value {
switch (val.tag()) {
.undef, .zero, .one => return val,
.the_only_possible_value => return Value.initTag(.zero), // for i0, u0
.int_u64 => {
return intToFloatInner(val.castTag(.int_u64).?.data, arena, dest_ty, target);
},
.int_i64 => {
return intToFloatInner(val.castTag(.int_i64).?.data, arena, dest_ty, target);
},
.int_big_positive => {
const limbs = val.castTag(.int_big_positive).?.data;
const float = bigIntToFloat(limbs, true);
return floatToValue(float, arena, dest_ty, target);
},
.int_big_negative => {
const limbs = val.castTag(.int_big_negative).?.data;
const float = bigIntToFloat(limbs, false);
return floatToValue(float, arena, dest_ty, target);
},
else => unreachable,
}
}
fn intToFloatInner(x: anytype, arena: Allocator, dest_ty: Type, target: Target) !Value {
switch (dest_ty.floatBits(target)) {
16 => return Value.Tag.float_16.create(arena, @intToFloat(f16, x)),
32 => return Value.Tag.float_32.create(arena, @intToFloat(f32, x)),
64 => return Value.Tag.float_64.create(arena, @intToFloat(f64, x)),
// We can't lower this properly on non-x86 llvm backends yet
//80 => return Value.Tag.float_80.create(arena, @intToFloat(f80, x)),
80 => @panic("TODO f80 intToFloat"),
128 => return Value.Tag.float_128.create(arena, @intToFloat(f128, x)),
else => unreachable,
}
}
fn floatToValue(float: f128, arena: Allocator, dest_ty: Type, target: Target) !Value {
switch (dest_ty.floatBits(target)) {
16 => return Value.Tag.float_16.create(arena, @floatCast(f16, float)),
32 => return Value.Tag.float_32.create(arena, @floatCast(f32, float)),
64 => return Value.Tag.float_64.create(arena, @floatCast(f64, float)),
80 => return Value.Tag.float_80.create(arena, @floatCast(f80, float)),
128 => return Value.Tag.float_128.create(arena, float),
else => unreachable,
}
}
pub fn floatToInt(val: Value, arena: Allocator, dest_ty: Type, target: Target) error{ FloatCannotFit, OutOfMemory }!Value {
const Limb = std.math.big.Limb;
var value = val.toFloat(f64); // TODO: f128 ?
if (std.math.isNan(value) or std.math.isInf(value)) {
return error.FloatCannotFit;
}
const isNegative = std.math.signbit(value);
value = std.math.fabs(value);
const floored = std.math.floor(value);
var rational = try std.math.big.Rational.init(arena);
defer rational.deinit();
rational.setFloat(f64, floored) catch |err| switch (err) {
error.NonFiniteFloat => unreachable,
error.OutOfMemory => return error.OutOfMemory,
};
// The float is reduced in rational.setFloat, so we assert that denominator is equal to one
const bigOne = std.math.big.int.Const{ .limbs = &.{1}, .positive = true };
assert(rational.q.toConst().eqAbs(bigOne));
const result_limbs = try arena.dupe(Limb, rational.p.toConst().limbs);
const result = if (isNegative)
try Value.Tag.int_big_negative.create(arena, result_limbs)
else
try Value.Tag.int_big_positive.create(arena, result_limbs);
if (result.intFitsInType(dest_ty, target)) {
return result;
} else {
return error.FloatCannotFit;
}
}
fn calcLimbLenFloat(scalar: anytype) usize {
if (scalar == 0) {
return 1;
}
const w_value = std.math.fabs(scalar);
return @divFloor(@floatToInt(std.math.big.Limb, std.math.log2(w_value)), @typeInfo(std.math.big.Limb).Int.bits) + 1;
}
pub const OverflowArithmeticResult = struct {
overflowed: bool,
wrapped_result: Value,
};
pub fn intAddWithOverflow(
lhs: Value,
rhs: Value,
ty: Type,
arena: Allocator,
target: Target,
) !OverflowArithmeticResult {
const info = ty.intInfo(target);
var lhs_space: Value.BigIntSpace = undefined;
var rhs_space: Value.BigIntSpace = undefined;
const lhs_bigint = lhs.toBigInt(&lhs_space);
const rhs_bigint = rhs.toBigInt(&rhs_space);
const limbs = try arena.alloc(
std.math.big.Limb,
std.math.big.int.calcTwosCompLimbCount(info.bits),
);
var result_bigint = BigIntMutable{ .limbs = limbs, .positive = undefined, .len = undefined };
const overflowed = result_bigint.addWrap(lhs_bigint, rhs_bigint, info.signedness, info.bits);
const result = try fromBigInt(arena, result_bigint.toConst());
return OverflowArithmeticResult{
.overflowed = overflowed,
.wrapped_result = result,
};
}
/// Supports both floats and ints; handles undefined.
pub fn numberAddWrap(
lhs: Value,
rhs: Value,
ty: Type,
arena: Allocator,
target: Target,
) !Value {
if (lhs.isUndef() or rhs.isUndef()) return Value.initTag(.undef);
if (ty.zigTypeTag() == .ComptimeInt) {
return intAdd(lhs, rhs, arena);
}
if (ty.isAnyFloat()) {
return floatAdd(lhs, rhs, ty, arena, target);
}
const overflow_result = try intAddWithOverflow(lhs, rhs, ty, arena, target);
return overflow_result.wrapped_result;
}
fn fromBigInt(arena: Allocator, big_int: BigIntConst) !Value {
if (big_int.positive) {
if (big_int.to(u64)) |x| {
return Value.Tag.int_u64.create(arena, x);
} else |_| {
return Value.Tag.int_big_positive.create(arena, big_int.limbs);
}
} else {
if (big_int.to(i64)) |x| {
return Value.Tag.int_i64.create(arena, x);
} else |_| {
return Value.Tag.int_big_negative.create(arena, big_int.limbs);
}
}
}
/// Supports integers only; asserts neither operand is undefined.
pub fn intAddSat(
lhs: Value,
rhs: Value,
ty: Type,
arena: Allocator,
target: Target,
) !Value {
assert(!lhs.isUndef());
assert(!rhs.isUndef());
const info = ty.intInfo(target);
var lhs_space: Value.BigIntSpace = undefined;
var rhs_space: Value.BigIntSpace = undefined;
const lhs_bigint = lhs.toBigInt(&lhs_space);
const rhs_bigint = rhs.toBigInt(&rhs_space);
const limbs = try arena.alloc(
std.math.big.Limb,
std.math.big.int.calcTwosCompLimbCount(info.bits),
);
var result_bigint = BigIntMutable{ .limbs = limbs, .positive = undefined, .len = undefined };
result_bigint.addSat(lhs_bigint, rhs_bigint, info.signedness, info.bits);
return fromBigInt(arena, result_bigint.toConst());
}
pub fn intSubWithOverflow(
lhs: Value,
rhs: Value,
ty: Type,
arena: Allocator,
target: Target,
) !OverflowArithmeticResult {
const info = ty.intInfo(target);
var lhs_space: Value.BigIntSpace = undefined;
var rhs_space: Value.BigIntSpace = undefined;
const lhs_bigint = lhs.toBigInt(&lhs_space);
const rhs_bigint = rhs.toBigInt(&rhs_space);
const limbs = try arena.alloc(
std.math.big.Limb,
std.math.big.int.calcTwosCompLimbCount(info.bits),
);
var result_bigint = BigIntMutable{ .limbs = limbs, .positive = undefined, .len = undefined };
const overflowed = result_bigint.subWrap(lhs_bigint, rhs_bigint, info.signedness, info.bits);
const wrapped_result = try fromBigInt(arena, result_bigint.toConst());
return OverflowArithmeticResult{
.overflowed = overflowed,
.wrapped_result = wrapped_result,
};
}
/// Supports both floats and ints; handles undefined.
pub fn numberSubWrap(
lhs: Value,
rhs: Value,
ty: Type,
arena: Allocator,
target: Target,
) !Value {
if (lhs.isUndef() or rhs.isUndef()) return Value.initTag(.undef);
if (ty.zigTypeTag() == .ComptimeInt) {
return intSub(lhs, rhs, arena);
}
if (ty.isAnyFloat()) {
return floatSub(lhs, rhs, ty, arena, target);
}
const overflow_result = try intSubWithOverflow(lhs, rhs, ty, arena, target);
return overflow_result.wrapped_result;
}
/// Supports integers only; asserts neither operand is undefined.
pub fn intSubSat(
lhs: Value,
rhs: Value,
ty: Type,
arena: Allocator,
target: Target,
) !Value {
assert(!lhs.isUndef());
assert(!rhs.isUndef());
const info = ty.intInfo(target);
var lhs_space: Value.BigIntSpace = undefined;
var rhs_space: Value.BigIntSpace = undefined;
const lhs_bigint = lhs.toBigInt(&lhs_space);
const rhs_bigint = rhs.toBigInt(&rhs_space);
const limbs = try arena.alloc(
std.math.big.Limb,
std.math.big.int.calcTwosCompLimbCount(info.bits),
);
var result_bigint = BigIntMutable{ .limbs = limbs, .positive = undefined, .len = undefined };
result_bigint.subSat(lhs_bigint, rhs_bigint, info.signedness, info.bits);
return fromBigInt(arena, result_bigint.toConst());
}
pub fn intMulWithOverflow(
lhs: Value,
rhs: Value,
ty: Type,
arena: Allocator,
target: Target,
) !OverflowArithmeticResult {
const info = ty.intInfo(target);
var lhs_space: Value.BigIntSpace = undefined;
var rhs_space: Value.BigIntSpace = undefined;
const lhs_bigint = lhs.toBigInt(&lhs_space);
const rhs_bigint = rhs.toBigInt(&rhs_space);
const limbs = try arena.alloc(
std.math.big.Limb,
lhs_bigint.limbs.len + rhs_bigint.limbs.len,
);
var result_bigint = BigIntMutable{ .limbs = limbs, .positive = undefined, .len = undefined };
var limbs_buffer = try arena.alloc(
std.math.big.Limb,
std.math.big.int.calcMulLimbsBufferLen(lhs_bigint.limbs.len, rhs_bigint.limbs.len, 1),
);
result_bigint.mul(lhs_bigint, rhs_bigint, limbs_buffer, arena);
const overflowed = !result_bigint.toConst().fitsInTwosComp(info.signedness, info.bits);
if (overflowed) {
result_bigint.truncate(result_bigint.toConst(), info.signedness, info.bits);
}
return OverflowArithmeticResult{
.overflowed = overflowed,
.wrapped_result = try fromBigInt(arena, result_bigint.toConst()),
};
}
/// Supports both floats and ints; handles undefined.
pub fn numberMulWrap(
lhs: Value,
rhs: Value,
ty: Type,
arena: Allocator,
target: Target,
) !Value {
if (lhs.isUndef() or rhs.isUndef()) return Value.initTag(.undef);
if (ty.zigTypeTag() == .ComptimeInt) {
return intMul(lhs, rhs, arena);
}
if (ty.isAnyFloat()) {
return floatMul(lhs, rhs, ty, arena, target);
}
const overflow_result = try intMulWithOverflow(lhs, rhs, ty, arena, target);
return overflow_result.wrapped_result;
}
/// Supports integers only; asserts neither operand is undefined.
pub fn intMulSat(
lhs: Value,
rhs: Value,
ty: Type,
arena: Allocator,
target: Target,
) !Value {
assert(!lhs.isUndef());
assert(!rhs.isUndef());
const info = ty.intInfo(target);
var lhs_space: Value.BigIntSpace = undefined;
var rhs_space: Value.BigIntSpace = undefined;
const lhs_bigint = lhs.toBigInt(&lhs_space);
const rhs_bigint = rhs.toBigInt(&rhs_space);
const limbs = try arena.alloc(
std.math.big.Limb,
std.math.max(
// For the saturate
std.math.big.int.calcTwosCompLimbCount(info.bits),
lhs_bigint.limbs.len + rhs_bigint.limbs.len,
),
);
var result_bigint = BigIntMutable{ .limbs = limbs, .positive = undefined, .len = undefined };
var limbs_buffer = try arena.alloc(
std.math.big.Limb,
std.math.big.int.calcMulLimbsBufferLen(lhs_bigint.limbs.len, rhs_bigint.limbs.len, 1),
);
result_bigint.mul(lhs_bigint, rhs_bigint, limbs_buffer, arena);
result_bigint.saturate(result_bigint.toConst(), info.signedness, info.bits);
return fromBigInt(arena, result_bigint.toConst());
}
/// Supports both floats and ints; handles undefined.
pub fn numberMax(lhs: Value, rhs: Value) Value {
if (lhs.isUndef() or rhs.isUndef()) return undef;
if (lhs.isNan()) return rhs;
if (rhs.isNan()) return lhs;
return switch (order(lhs, rhs)) {
.lt => rhs,
.gt, .eq => lhs,
};
}
/// Supports both floats and ints; handles undefined.
pub fn numberMin(lhs: Value, rhs: Value) Value {
if (lhs.isUndef() or rhs.isUndef()) return undef;
if (lhs.isNan()) return rhs;
if (rhs.isNan()) return lhs;
return switch (order(lhs, rhs)) {
.lt => lhs,
.gt, .eq => rhs,
};
}
/// operands must be integers; handles undefined.
pub fn bitwiseNot(val: Value, ty: Type, arena: Allocator, target: Target) !Value {
if (val.isUndef()) return Value.initTag(.undef);
const info = ty.intInfo(target);
if (info.bits == 0) {
assert(val.isZero()); // Sema should guarantee
return val;
}
// TODO is this a performance issue? maybe we should try the operation without
// resorting to BigInt first.
var val_space: Value.BigIntSpace = undefined;
const val_bigint = val.toBigInt(&val_space);
const limbs = try arena.alloc(
std.math.big.Limb,
std.math.big.int.calcTwosCompLimbCount(info.bits),
);
var result_bigint = BigIntMutable{ .limbs = limbs, .positive = undefined, .len = undefined };
result_bigint.bitNotWrap(val_bigint, info.signedness, info.bits);
return fromBigInt(arena, result_bigint.toConst());
}
/// operands must be integers; handles undefined.
pub fn bitwiseAnd(lhs: Value, rhs: Value, arena: Allocator) !Value {
if (lhs.isUndef() or rhs.isUndef()) return Value.initTag(.undef);
// TODO is this a performance issue? maybe we should try the operation without
// resorting to BigInt first.
var lhs_space: Value.BigIntSpace = undefined;
var rhs_space: Value.BigIntSpace = undefined;
const lhs_bigint = lhs.toBigInt(&lhs_space);
const rhs_bigint = rhs.toBigInt(&rhs_space);
const limbs = try arena.alloc(
std.math.big.Limb,
// + 1 for negatives
std.math.max(lhs_bigint.limbs.len, rhs_bigint.limbs.len) + 1,
);
var result_bigint = BigIntMutable{ .limbs = limbs, .positive = undefined, .len = undefined };
result_bigint.bitAnd(lhs_bigint, rhs_bigint);
return fromBigInt(arena, result_bigint.toConst());
}
/// operands must be integers; handles undefined.
pub fn bitwiseNand(lhs: Value, rhs: Value, ty: Type, arena: Allocator, target: Target) !Value {
if (lhs.isUndef() or rhs.isUndef()) return Value.initTag(.undef);
const anded = try bitwiseAnd(lhs, rhs, arena);
const all_ones = if (ty.isSignedInt())
try Value.Tag.int_i64.create(arena, -1)
else
try ty.maxInt(arena, target);
return bitwiseXor(anded, all_ones, arena);
}
/// operands must be integers; handles undefined.
pub fn bitwiseOr(lhs: Value, rhs: Value, arena: Allocator) !Value {
if (lhs.isUndef() or rhs.isUndef()) return Value.initTag(.undef);
// TODO is this a performance issue? maybe we should try the operation without
// resorting to BigInt first.
var lhs_space: Value.BigIntSpace = undefined;
var rhs_space: Value.BigIntSpace = undefined;
const lhs_bigint = lhs.toBigInt(&lhs_space);
const rhs_bigint = rhs.toBigInt(&rhs_space);
const limbs = try arena.alloc(
std.math.big.Limb,
std.math.max(lhs_bigint.limbs.len, rhs_bigint.limbs.len),
);
var result_bigint = BigIntMutable{ .limbs = limbs, .positive = undefined, .len = undefined };
result_bigint.bitOr(lhs_bigint, rhs_bigint);
return fromBigInt(arena, result_bigint.toConst());
}
/// operands must be integers; handles undefined.
pub fn bitwiseXor(lhs: Value, rhs: Value, arena: Allocator) !Value {
if (lhs.isUndef() or rhs.isUndef()) return Value.initTag(.undef);
// TODO is this a performance issue? maybe we should try the operation without
// resorting to BigInt first.
var lhs_space: Value.BigIntSpace = undefined;
var rhs_space: Value.BigIntSpace = undefined;
const lhs_bigint = lhs.toBigInt(&lhs_space);
const rhs_bigint = rhs.toBigInt(&rhs_space);
const limbs = try arena.alloc(
std.math.big.Limb,
// + 1 for negatives
std.math.max(lhs_bigint.limbs.len, rhs_bigint.limbs.len) + 1,
);
var result_bigint = BigIntMutable{ .limbs = limbs, .positive = undefined, .len = undefined };
result_bigint.bitXor(lhs_bigint, rhs_bigint);
return fromBigInt(arena, result_bigint.toConst());
}
pub fn intAdd(lhs: Value, rhs: Value, allocator: Allocator) !Value {
// TODO is this a performance issue? maybe we should try the operation without
// resorting to BigInt first.
var lhs_space: Value.BigIntSpace = undefined;
var rhs_space: Value.BigIntSpace = undefined;
const lhs_bigint = lhs.toBigInt(&lhs_space);
const rhs_bigint = rhs.toBigInt(&rhs_space);
const limbs = try allocator.alloc(
std.math.big.Limb,
std.math.max(lhs_bigint.limbs.len, rhs_bigint.limbs.len) + 1,
);
var result_bigint = BigIntMutable{ .limbs = limbs, .positive = undefined, .len = undefined };
result_bigint.add(lhs_bigint, rhs_bigint);
return fromBigInt(allocator, result_bigint.toConst());
}
pub fn intSub(lhs: Value, rhs: Value, allocator: Allocator) !Value {
// TODO is this a performance issue? maybe we should try the operation without
// resorting to BigInt first.
var lhs_space: Value.BigIntSpace = undefined;
var rhs_space: Value.BigIntSpace = undefined;
const lhs_bigint = lhs.toBigInt(&lhs_space);
const rhs_bigint = rhs.toBigInt(&rhs_space);
const limbs = try allocator.alloc(
std.math.big.Limb,
std.math.max(lhs_bigint.limbs.len, rhs_bigint.limbs.len) + 1,
);
var result_bigint = BigIntMutable{ .limbs = limbs, .positive = undefined, .len = undefined };
result_bigint.sub(lhs_bigint, rhs_bigint);
return fromBigInt(allocator, result_bigint.toConst());
}
pub fn intDiv(lhs: Value, rhs: Value, allocator: Allocator) !Value {
// TODO is this a performance issue? maybe we should try the operation without
// resorting to BigInt first.
var lhs_space: Value.BigIntSpace = undefined;
var rhs_space: Value.BigIntSpace = undefined;
const lhs_bigint = lhs.toBigInt(&lhs_space);
const rhs_bigint = rhs.toBigInt(&rhs_space);
const limbs_q = try allocator.alloc(
std.math.big.Limb,
lhs_bigint.limbs.len,
);
const limbs_r = try allocator.alloc(
std.math.big.Limb,
rhs_bigint.limbs.len,
);
const limbs_buffer = try allocator.alloc(
std.math.big.Limb,
std.math.big.int.calcDivLimbsBufferLen(lhs_bigint.limbs.len, rhs_bigint.limbs.len),
);
var result_q = BigIntMutable{ .limbs = limbs_q, .positive = undefined, .len = undefined };
var result_r = BigIntMutable{ .limbs = limbs_r, .positive = undefined, .len = undefined };
result_q.divTrunc(&result_r, lhs_bigint, rhs_bigint, limbs_buffer);
return fromBigInt(allocator, result_q.toConst());
}
pub fn intDivFloor(lhs: Value, rhs: Value, allocator: Allocator) !Value {
// TODO is this a performance issue? maybe we should try the operation without
// resorting to BigInt first.
var lhs_space: Value.BigIntSpace = undefined;
var rhs_space: Value.BigIntSpace = undefined;
const lhs_bigint = lhs.toBigInt(&lhs_space);
const rhs_bigint = rhs.toBigInt(&rhs_space);
const limbs_q = try allocator.alloc(
std.math.big.Limb,
lhs_bigint.limbs.len,
);
const limbs_r = try allocator.alloc(
std.math.big.Limb,
rhs_bigint.limbs.len,
);
const limbs_buffer = try allocator.alloc(
std.math.big.Limb,
std.math.big.int.calcDivLimbsBufferLen(lhs_bigint.limbs.len, rhs_bigint.limbs.len),
);
var result_q = BigIntMutable{ .limbs = limbs_q, .positive = undefined, .len = undefined };
var result_r = BigIntMutable{ .limbs = limbs_r, .positive = undefined, .len = undefined };
result_q.divFloor(&result_r, lhs_bigint, rhs_bigint, limbs_buffer);
return fromBigInt(allocator, result_q.toConst());
}
pub fn intRem(lhs: Value, rhs: Value, allocator: Allocator) !Value {
// TODO is this a performance issue? maybe we should try the operation without
// resorting to BigInt first.
var lhs_space: Value.BigIntSpace = undefined;
var rhs_space: Value.BigIntSpace = undefined;
const lhs_bigint = lhs.toBigInt(&lhs_space);
const rhs_bigint = rhs.toBigInt(&rhs_space);
const limbs_q = try allocator.alloc(
std.math.big.Limb,
lhs_bigint.limbs.len,
);
const limbs_r = try allocator.alloc(
std.math.big.Limb,
// TODO: consider reworking Sema to re-use Values rather than
// always producing new Value objects.
rhs_bigint.limbs.len,
);
const limbs_buffer = try allocator.alloc(
std.math.big.Limb,
std.math.big.int.calcDivLimbsBufferLen(lhs_bigint.limbs.len, rhs_bigint.limbs.len),
);
var result_q = BigIntMutable{ .limbs = limbs_q, .positive = undefined, .len = undefined };
var result_r = BigIntMutable{ .limbs = limbs_r, .positive = undefined, .len = undefined };
result_q.divTrunc(&result_r, lhs_bigint, rhs_bigint, limbs_buffer);
return fromBigInt(allocator, result_r.toConst());
}
pub fn intMod(lhs: Value, rhs: Value, allocator: Allocator) !Value {
// TODO is this a performance issue? maybe we should try the operation without
// resorting to BigInt first.
var lhs_space: Value.BigIntSpace = undefined;
var rhs_space: Value.BigIntSpace = undefined;
const lhs_bigint = lhs.toBigInt(&lhs_space);
const rhs_bigint = rhs.toBigInt(&rhs_space);
const limbs_q = try allocator.alloc(
std.math.big.Limb,
lhs_bigint.limbs.len,
);
const limbs_r = try allocator.alloc(
std.math.big.Limb,
rhs_bigint.limbs.len,
);
const limbs_buffer = try allocator.alloc(
std.math.big.Limb,
std.math.big.int.calcDivLimbsBufferLen(lhs_bigint.limbs.len, rhs_bigint.limbs.len),
);
var result_q = BigIntMutable{ .limbs = limbs_q, .positive = undefined, .len = undefined };
var result_r = BigIntMutable{ .limbs = limbs_r, .positive = undefined, .len = undefined };
result_q.divFloor(&result_r, lhs_bigint, rhs_bigint, limbs_buffer);
return fromBigInt(allocator, result_r.toConst());
}
/// Returns true if the value is a floating point type and is NaN. Returns false otherwise.
pub fn isNan(val: Value) bool {
return switch (val.tag()) {
.float_16 => std.math.isNan(val.castTag(.float_16).?.data),
.float_32 => std.math.isNan(val.castTag(.float_32).?.data),
.float_64 => std.math.isNan(val.castTag(.float_64).?.data),
.float_80 => std.math.isNan(val.castTag(.float_80).?.data),
.float_128 => std.math.isNan(val.castTag(.float_128).?.data),
else => false,
};
}
pub fn floatRem(lhs: Value, rhs: Value, float_type: Type, arena: Allocator, target: Target) !Value {
switch (float_type.floatBits(target)) {
16 => {
const lhs_val = lhs.toFloat(f16);
const rhs_val = rhs.toFloat(f16);
return Value.Tag.float_16.create(arena, @rem(lhs_val, rhs_val));
},
32 => {
const lhs_val = lhs.toFloat(f32);
const rhs_val = rhs.toFloat(f32);
return Value.Tag.float_32.create(arena, @rem(lhs_val, rhs_val));
},
64 => {
const lhs_val = lhs.toFloat(f64);
const rhs_val = rhs.toFloat(f64);
return Value.Tag.float_64.create(arena, @rem(lhs_val, rhs_val));
},
80 => {
if (true) {
@panic("TODO implement compiler_rt __remx");
}
const lhs_val = lhs.toFloat(f80);
const rhs_val = rhs.toFloat(f80);
return Value.Tag.float_80.create(arena, @rem(lhs_val, rhs_val));
},
128 => {
const lhs_val = lhs.toFloat(f128);
const rhs_val = rhs.toFloat(f128);
return Value.Tag.float_128.create(arena, @rem(lhs_val, rhs_val));
},
else => unreachable,
}
}
pub fn floatMod(lhs: Value, rhs: Value, float_type: Type, arena: Allocator, target: Target) !Value {
switch (float_type.floatBits(target)) {
16 => {
const lhs_val = lhs.toFloat(f16);
const rhs_val = rhs.toFloat(f16);
return Value.Tag.float_16.create(arena, @mod(lhs_val, rhs_val));
},
32 => {
const lhs_val = lhs.toFloat(f32);
const rhs_val = rhs.toFloat(f32);
return Value.Tag.float_32.create(arena, @mod(lhs_val, rhs_val));
},
64 => {
const lhs_val = lhs.toFloat(f64);
const rhs_val = rhs.toFloat(f64);
return Value.Tag.float_64.create(arena, @mod(lhs_val, rhs_val));
},
80 => {
if (true) {
@panic("TODO implement compiler_rt __modx");
}
const lhs_val = lhs.toFloat(f80);
const rhs_val = rhs.toFloat(f80);
return Value.Tag.float_80.create(arena, @mod(lhs_val, rhs_val));
},
128 => {
const lhs_val = lhs.toFloat(f128);
const rhs_val = rhs.toFloat(f128);
return Value.Tag.float_128.create(arena, @mod(lhs_val, rhs_val));
},
else => unreachable,
}
}
pub fn intMul(lhs: Value, rhs: Value, allocator: Allocator) !Value {
// TODO is this a performance issue? maybe we should try the operation without
// resorting to BigInt first.
var lhs_space: Value.BigIntSpace = undefined;
var rhs_space: Value.BigIntSpace = undefined;
const lhs_bigint = lhs.toBigInt(&lhs_space);
const rhs_bigint = rhs.toBigInt(&rhs_space);
const limbs = try allocator.alloc(
std.math.big.Limb,
lhs_bigint.limbs.len + rhs_bigint.limbs.len,
);
var result_bigint = BigIntMutable{ .limbs = limbs, .positive = undefined, .len = undefined };
var limbs_buffer = try allocator.alloc(
std.math.big.Limb,
std.math.big.int.calcMulLimbsBufferLen(lhs_bigint.limbs.len, rhs_bigint.limbs.len, 1),
);
defer allocator.free(limbs_buffer);
result_bigint.mul(lhs_bigint, rhs_bigint, limbs_buffer, allocator);
return fromBigInt(allocator, result_bigint.toConst());
}
pub fn intTrunc(val: Value, allocator: Allocator, signedness: std.builtin.Signedness, bits: u16) !Value {
var val_space: Value.BigIntSpace = undefined;
const val_bigint = val.toBigInt(&val_space);
const limbs = try allocator.alloc(
std.math.big.Limb,
std.math.big.int.calcTwosCompLimbCount(bits),
);
var result_bigint = BigIntMutable{ .limbs = limbs, .positive = undefined, .len = undefined };
result_bigint.truncate(val_bigint, signedness, bits);
return fromBigInt(allocator, result_bigint.toConst());
}
pub fn shl(lhs: Value, rhs: Value, allocator: Allocator) !Value {
// TODO is this a performance issue? maybe we should try the operation without
// resorting to BigInt first.
var lhs_space: Value.BigIntSpace = undefined;
const lhs_bigint = lhs.toBigInt(&lhs_space);
const shift = @intCast(usize, rhs.toUnsignedInt());
const limbs = try allocator.alloc(
std.math.big.Limb,
lhs_bigint.limbs.len + (shift / (@sizeOf(std.math.big.Limb) * 8)) + 1,
);
var result_bigint = BigIntMutable{
.limbs = limbs,
.positive = undefined,
.len = undefined,
};
result_bigint.shiftLeft(lhs_bigint, shift);
return fromBigInt(allocator, result_bigint.toConst());
}
pub fn shlWithOverflow(
lhs: Value,
rhs: Value,
ty: Type,
allocator: Allocator,
target: Target,
) !OverflowArithmeticResult {
const info = ty.intInfo(target);
var lhs_space: Value.BigIntSpace = undefined;
const lhs_bigint = lhs.toBigInt(&lhs_space);
const shift = @intCast(usize, rhs.toUnsignedInt());
const limbs = try allocator.alloc(
std.math.big.Limb,
lhs_bigint.limbs.len + (shift / (@sizeOf(std.math.big.Limb) * 8)) + 1,
);
var result_bigint = BigIntMutable{
.limbs = limbs,
.positive = undefined,
.len = undefined,
};
result_bigint.shiftLeft(lhs_bigint, shift);
const overflowed = !result_bigint.toConst().fitsInTwosComp(info.signedness, info.bits);
if (overflowed) {
result_bigint.truncate(result_bigint.toConst(), info.signedness, info.bits);
}
return OverflowArithmeticResult{
.overflowed = overflowed,
.wrapped_result = try fromBigInt(allocator, result_bigint.toConst()),
};
}
pub fn shlSat(
lhs: Value,
rhs: Value,
ty: Type,
arena: Allocator,
target: Target,
) !Value {
// TODO is this a performance issue? maybe we should try the operation without
// resorting to BigInt first.
const info = ty.intInfo(target);
var lhs_space: Value.BigIntSpace = undefined;
const lhs_bigint = lhs.toBigInt(&lhs_space);
const shift = @intCast(usize, rhs.toUnsignedInt());
const limbs = try arena.alloc(
std.math.big.Limb,
std.math.big.int.calcTwosCompLimbCount(info.bits),
);
var result_bigint = BigIntMutable{
.limbs = limbs,
.positive = undefined,
.len = undefined,
};
result_bigint.shiftLeftSat(lhs_bigint, shift, info.signedness, info.bits);
return fromBigInt(arena, result_bigint.toConst());
}
pub fn shlTrunc(
lhs: Value,
rhs: Value,
ty: Type,
arena: Allocator,
target: Target,
) !Value {
const shifted = try lhs.shl(rhs, arena);
const int_info = ty.intInfo(target);
const truncated = try shifted.intTrunc(arena, int_info.signedness, int_info.bits);
return truncated;
}
pub fn shr(lhs: Value, rhs: Value, allocator: Allocator) !Value {
// TODO is this a performance issue? maybe we should try the operation without
// resorting to BigInt first.
var lhs_space: Value.BigIntSpace = undefined;
const lhs_bigint = lhs.toBigInt(&lhs_space);
const shift = @intCast(usize, rhs.toUnsignedInt());
const result_limbs = lhs_bigint.limbs.len -| (shift / (@sizeOf(std.math.big.Limb) * 8));
if (result_limbs == 0) {
// The shift is enough to remove all the bits from the number, which means the
// result is zero.
return Value.zero;
}
const limbs = try allocator.alloc(
std.math.big.Limb,
result_limbs,
);
var result_bigint = BigIntMutable{
.limbs = limbs,
.positive = undefined,
.len = undefined,
};
result_bigint.shiftRight(lhs_bigint, shift);
return fromBigInt(allocator, result_bigint.toConst());
}
pub fn floatAdd(
lhs: Value,
rhs: Value,
float_type: Type,
arena: Allocator,
target: Target,
) !Value {
switch (float_type.floatBits(target)) {
16 => {
const lhs_val = lhs.toFloat(f16);
const rhs_val = rhs.toFloat(f16);
return Value.Tag.float_16.create(arena, lhs_val + rhs_val);
},
32 => {
const lhs_val = lhs.toFloat(f32);
const rhs_val = rhs.toFloat(f32);
return Value.Tag.float_32.create(arena, lhs_val + rhs_val);
},
64 => {
const lhs_val = lhs.toFloat(f64);
const rhs_val = rhs.toFloat(f64);
return Value.Tag.float_64.create(arena, lhs_val + rhs_val);
},
80 => {
const lhs_val = lhs.toFloat(f80);
const rhs_val = rhs.toFloat(f80);
return Value.Tag.float_80.create(arena, lhs_val + rhs_val);
},
128 => {
const lhs_val = lhs.toFloat(f128);
const rhs_val = rhs.toFloat(f128);
return Value.Tag.float_128.create(arena, lhs_val + rhs_val);
},
else => unreachable,
}
}
pub fn floatSub(
lhs: Value,
rhs: Value,
float_type: Type,
arena: Allocator,
target: Target,
) !Value {
switch (float_type.floatBits(target)) {
16 => {
const lhs_val = lhs.toFloat(f16);
const rhs_val = rhs.toFloat(f16);
return Value.Tag.float_16.create(arena, lhs_val - rhs_val);
},
32 => {
const lhs_val = lhs.toFloat(f32);
const rhs_val = rhs.toFloat(f32);
return Value.Tag.float_32.create(arena, lhs_val - rhs_val);
},
64 => {
const lhs_val = lhs.toFloat(f64);
const rhs_val = rhs.toFloat(f64);
return Value.Tag.float_64.create(arena, lhs_val - rhs_val);
},
80 => {
const lhs_val = lhs.toFloat(f80);
const rhs_val = rhs.toFloat(f80);
return Value.Tag.float_80.create(arena, lhs_val - rhs_val);
},
128 => {
const lhs_val = lhs.toFloat(f128);
const rhs_val = rhs.toFloat(f128);
return Value.Tag.float_128.create(arena, lhs_val - rhs_val);
},
else => unreachable,
}
}
pub fn floatDiv(
lhs: Value,
rhs: Value,
float_type: Type,
arena: Allocator,
target: Target,
) !Value {
switch (float_type.floatBits(target)) {
16 => {
const lhs_val = lhs.toFloat(f16);
const rhs_val = rhs.toFloat(f16);
return Value.Tag.float_16.create(arena, lhs_val / rhs_val);
},
32 => {
const lhs_val = lhs.toFloat(f32);
const rhs_val = rhs.toFloat(f32);
return Value.Tag.float_32.create(arena, lhs_val / rhs_val);
},
64 => {
const lhs_val = lhs.toFloat(f64);
const rhs_val = rhs.toFloat(f64);
return Value.Tag.float_64.create(arena, lhs_val / rhs_val);
},
80 => {
if (true) {
@panic("TODO implement compiler_rt __divxf3");
}
const lhs_val = lhs.toFloat(f80);
const rhs_val = rhs.toFloat(f80);
return Value.Tag.float_80.create(arena, lhs_val / rhs_val);
},
128 => {
const lhs_val = lhs.toFloat(f128);
const rhs_val = rhs.toFloat(f128);
return Value.Tag.float_128.create(arena, lhs_val / rhs_val);
},
else => unreachable,
}
}
pub fn floatDivFloor(
lhs: Value,
rhs: Value,
float_type: Type,
arena: Allocator,
target: Target,
) !Value {
switch (float_type.floatBits(target)) {
16 => {
const lhs_val = lhs.toFloat(f16);
const rhs_val = rhs.toFloat(f16);
return Value.Tag.float_16.create(arena, @divFloor(lhs_val, rhs_val));
},
32 => {
const lhs_val = lhs.toFloat(f32);
const rhs_val = rhs.toFloat(f32);
return Value.Tag.float_32.create(arena, @divFloor(lhs_val, rhs_val));
},
64 => {
const lhs_val = lhs.toFloat(f64);
const rhs_val = rhs.toFloat(f64);
return Value.Tag.float_64.create(arena, @divFloor(lhs_val, rhs_val));
},
80 => {
if (true) {
@panic("TODO implement compiler_rt __floorx");
}
const lhs_val = lhs.toFloat(f80);
const rhs_val = rhs.toFloat(f80);
return Value.Tag.float_80.create(arena, @divFloor(lhs_val, rhs_val));
},
128 => {
const lhs_val = lhs.toFloat(f128);
const rhs_val = rhs.toFloat(f128);
return Value.Tag.float_128.create(arena, @divFloor(lhs_val, rhs_val));
},
else => unreachable,
}
}
pub fn floatDivTrunc(
lhs: Value,
rhs: Value,
float_type: Type,
arena: Allocator,
target: Target,
) !Value {
switch (float_type.floatBits(target)) {
16 => {
const lhs_val = lhs.toFloat(f16);
const rhs_val = rhs.toFloat(f16);
return Value.Tag.float_16.create(arena, @divTrunc(lhs_val, rhs_val));
},
32 => {
const lhs_val = lhs.toFloat(f32);
const rhs_val = rhs.toFloat(f32);
return Value.Tag.float_32.create(arena, @divTrunc(lhs_val, rhs_val));
},
64 => {
const lhs_val = lhs.toFloat(f64);
const rhs_val = rhs.toFloat(f64);
return Value.Tag.float_64.create(arena, @divTrunc(lhs_val, rhs_val));
},
80 => {
if (true) {
@panic("TODO implement compiler_rt __truncx");
}
const lhs_val = lhs.toFloat(f80);
const rhs_val = rhs.toFloat(f80);
return Value.Tag.float_80.create(arena, @divTrunc(lhs_val, rhs_val));
},
128 => {
const lhs_val = lhs.toFloat(f128);
const rhs_val = rhs.toFloat(f128);
return Value.Tag.float_128.create(arena, @divTrunc(lhs_val, rhs_val));
},
else => unreachable,
}
}
pub fn floatMul(
lhs: Value,
rhs: Value,
float_type: Type,
arena: Allocator,
target: Target,
) !Value {
switch (float_type.floatBits(target)) {
16 => {
const lhs_val = lhs.toFloat(f16);
const rhs_val = rhs.toFloat(f16);
return Value.Tag.float_16.create(arena, lhs_val * rhs_val);
},
32 => {
const lhs_val = lhs.toFloat(f32);
const rhs_val = rhs.toFloat(f32);
return Value.Tag.float_32.create(arena, lhs_val * rhs_val);
},
64 => {
const lhs_val = lhs.toFloat(f64);
const rhs_val = rhs.toFloat(f64);
return Value.Tag.float_64.create(arena, lhs_val * rhs_val);
},
80 => {
if (true) {
@panic("TODO implement compiler_rt __mulxf3");
}
const lhs_val = lhs.toFloat(f80);
const rhs_val = rhs.toFloat(f80);
return Value.Tag.float_80.create(arena, lhs_val * rhs_val);
},
128 => {
const lhs_val = lhs.toFloat(f128);
const rhs_val = rhs.toFloat(f128);
return Value.Tag.float_128.create(arena, lhs_val * rhs_val);
},
else => unreachable,
}
}
pub fn sqrt(val: Value, float_type: Type, arena: Allocator, target: Target) Allocator.Error!Value {
switch (float_type.floatBits(target)) {
16 => {
const f = val.toFloat(f16);
return Value.Tag.float_16.create(arena, @sqrt(f));
},
32 => {
const f = val.toFloat(f32);
return Value.Tag.float_32.create(arena, @sqrt(f));
},
64 => {
const f = val.toFloat(f64);
return Value.Tag.float_64.create(arena, @sqrt(f));
},
80 => {
if (true) {
@panic("TODO implement compiler_rt __sqrtx");
}
const f = val.toFloat(f80);
return Value.Tag.float_80.create(arena, @sqrt(f));
},
128 => {
if (true) {
@panic("TODO implement compiler_rt sqrtq");
}
const f = val.toFloat(f128);
return Value.Tag.float_128.create(arena, @sqrt(f));
},
else => unreachable,
}
}
pub fn sin(val: Value, float_type: Type, arena: Allocator, target: Target) Allocator.Error!Value {
switch (float_type.floatBits(target)) {
16 => {
const f = val.toFloat(f16);
return Value.Tag.float_16.create(arena, @sin(f));
},
32 => {
const f = val.toFloat(f32);
return Value.Tag.float_32.create(arena, @sin(f));
},
64 => {
const f = val.toFloat(f64);
return Value.Tag.float_64.create(arena, @sin(f));
},
80 => {
if (true) {
@panic("TODO implement compiler_rt sin for f80");
}
const f = val.toFloat(f80);
return Value.Tag.float_80.create(arena, @sin(f));
},
128 => {
if (true) {
@panic("TODO implement compiler_rt sin for f128");
}
const f = val.toFloat(f128);
return Value.Tag.float_128.create(arena, @sin(f));
},
else => unreachable,
}
}
pub fn cos(val: Value, float_type: Type, arena: Allocator, target: Target) Allocator.Error!Value {
switch (float_type.floatBits(target)) {
16 => {
const f = val.toFloat(f16);
return Value.Tag.float_16.create(arena, @cos(f));
},
32 => {
const f = val.toFloat(f32);
return Value.Tag.float_32.create(arena, @cos(f));
},
64 => {
const f = val.toFloat(f64);
return Value.Tag.float_64.create(arena, @cos(f));
},
80 => {
if (true) {
@panic("TODO implement compiler_rt cos for f80");
}
const f = val.toFloat(f80);
return Value.Tag.float_80.create(arena, @cos(f));
},
128 => {
if (true) {
@panic("TODO implement compiler_rt cos for f128");
}
const f = val.toFloat(f128);
return Value.Tag.float_128.create(arena, @cos(f));
},
else => unreachable,
}
}
pub fn exp(val: Value, float_type: Type, arena: Allocator, target: Target) Allocator.Error!Value {
switch (float_type.floatBits(target)) {
16 => {
const f = val.toFloat(f16);
return Value.Tag.float_16.create(arena, @exp(f));
},
32 => {
const f = val.toFloat(f32);
return Value.Tag.float_32.create(arena, @exp(f));
},
64 => {
const f = val.toFloat(f64);
return Value.Tag.float_64.create(arena, @exp(f));
},
80 => {
if (true) {
@panic("TODO implement compiler_rt exp for f80");
}
const f = val.toFloat(f80);
return Value.Tag.float_80.create(arena, @exp(f));
},
128 => {
if (true) {
@panic("TODO implement compiler_rt exp for f128");
}
const f = val.toFloat(f128);
return Value.Tag.float_128.create(arena, @exp(f));
},
else => unreachable,
}
}
pub fn exp2(val: Value, float_type: Type, arena: Allocator, target: Target) Allocator.Error!Value {
switch (float_type.floatBits(target)) {
16 => {
const f = val.toFloat(f16);
return Value.Tag.float_16.create(arena, @exp2(f));
},
32 => {
const f = val.toFloat(f32);
return Value.Tag.float_32.create(arena, @exp2(f));
},
64 => {
const f = val.toFloat(f64);
return Value.Tag.float_64.create(arena, @exp2(f));
},
80 => {
if (true) {
@panic("TODO implement compiler_rt exp2 for f80");
}
const f = val.toFloat(f80);
return Value.Tag.float_80.create(arena, @exp2(f));
},
128 => {
if (true) {
@panic("TODO implement compiler_rt exp2 for f128");
}
const f = val.toFloat(f128);
return Value.Tag.float_128.create(arena, @exp2(f));
},
else => unreachable,
}
}
pub fn log(val: Value, float_type: Type, arena: Allocator, target: Target) Allocator.Error!Value {
switch (float_type.floatBits(target)) {
16 => {
const f = val.toFloat(f16);
return Value.Tag.float_16.create(arena, @log(f));
},
32 => {
const f = val.toFloat(f32);
return Value.Tag.float_32.create(arena, @log(f));
},
64 => {
const f = val.toFloat(f64);
return Value.Tag.float_64.create(arena, @log(f));
},
80 => {
if (true) {
@panic("TODO implement compiler_rt log for f80");
}
const f = val.toFloat(f80);
return Value.Tag.float_80.create(arena, @log(f));
},
128 => {
if (true) {
@panic("TODO implement compiler_rt log for f128");
}
const f = val.toFloat(f128);
return Value.Tag.float_128.create(arena, @log(f));
},
else => unreachable,
}
}
pub fn log2(val: Value, float_type: Type, arena: Allocator, target: Target) Allocator.Error!Value {
switch (float_type.floatBits(target)) {
16 => {
const f = val.toFloat(f16);
return Value.Tag.float_16.create(arena, @log2(f));
},
32 => {
const f = val.toFloat(f32);
return Value.Tag.float_32.create(arena, @log2(f));
},
64 => {
const f = val.toFloat(f64);
return Value.Tag.float_64.create(arena, @log2(f));
},
80 => {
if (true) {
@panic("TODO implement compiler_rt log2 for f80");
}
const f = val.toFloat(f80);
return Value.Tag.float_80.create(arena, @log2(f));
},
128 => {
if (true) {
@panic("TODO implement compiler_rt log2 for f128");
}
const f = val.toFloat(f128);
return Value.Tag.float_128.create(arena, @log2(f));
},
else => unreachable,
}
}
pub fn log10(val: Value, float_type: Type, arena: Allocator, target: Target) Allocator.Error!Value {
switch (float_type.floatBits(target)) {
16 => {
const f = val.toFloat(f16);
return Value.Tag.float_16.create(arena, @log10(f));
},
32 => {
const f = val.toFloat(f32);
return Value.Tag.float_32.create(arena, @log10(f));
},
64 => {
const f = val.toFloat(f64);
return Value.Tag.float_64.create(arena, @log10(f));
},
80 => {
if (true) {
@panic("TODO implement compiler_rt log10 for f80");
}
const f = val.toFloat(f80);
return Value.Tag.float_80.create(arena, @log10(f));
},
128 => {
if (true) {
@panic("TODO implement compiler_rt log10 for f128");
}
const f = val.toFloat(f128);
return Value.Tag.float_128.create(arena, @log10(f));
},
else => unreachable,
}
}
pub fn fabs(val: Value, float_type: Type, arena: Allocator, target: Target) Allocator.Error!Value {
switch (float_type.floatBits(target)) {
16 => {
const f = val.toFloat(f16);
return Value.Tag.float_16.create(arena, @fabs(f));
},
32 => {
const f = val.toFloat(f32);
return Value.Tag.float_32.create(arena, @fabs(f));
},
64 => {
const f = val.toFloat(f64);
return Value.Tag.float_64.create(arena, @fabs(f));
},
80 => {
if (true) {
@panic("TODO implement compiler_rt fabs for f80 (__fabsx)");
}
const f = val.toFloat(f80);
return Value.Tag.float_80.create(arena, @fabs(f));
},
128 => {
const f = val.toFloat(f128);
return Value.Tag.float_128.create(arena, @fabs(f));
},
else => unreachable,
}
}
pub fn floor(val: Value, float_type: Type, arena: Allocator, target: Target) Allocator.Error!Value {
switch (float_type.floatBits(target)) {
16 => {
const f = val.toFloat(f16);
return Value.Tag.float_16.create(arena, @floor(f));
},
32 => {
const f = val.toFloat(f32);
return Value.Tag.float_32.create(arena, @floor(f));
},
64 => {
const f = val.toFloat(f64);
return Value.Tag.float_64.create(arena, @floor(f));
},
80 => {
if (true) {
@panic("TODO implement compiler_rt floor for f80 (__floorx)");
}
const f = val.toFloat(f80);
return Value.Tag.float_80.create(arena, @floor(f));
},
128 => {
const f = val.toFloat(f128);
return Value.Tag.float_128.create(arena, @floor(f));
},
else => unreachable,
}
}
pub fn ceil(val: Value, float_type: Type, arena: Allocator, target: Target) Allocator.Error!Value {
switch (float_type.floatBits(target)) {
16 => {
const f = val.toFloat(f16);
return Value.Tag.float_16.create(arena, @ceil(f));
},
32 => {
const f = val.toFloat(f32);
return Value.Tag.float_32.create(arena, @ceil(f));
},
64 => {
const f = val.toFloat(f64);
return Value.Tag.float_64.create(arena, @ceil(f));
},
80 => {
if (true) {
@panic("TODO implement compiler_rt ceil for f80");
}
const f = val.toFloat(f80);
return Value.Tag.float_80.create(arena, @ceil(f));
},
128 => {
const f = val.toFloat(f128);
return Value.Tag.float_128.create(arena, @ceil(f));
},
else => unreachable,
}
}
pub fn round(val: Value, float_type: Type, arena: Allocator, target: Target) Allocator.Error!Value {
switch (float_type.floatBits(target)) {
16 => {
const f = val.toFloat(f16);
return Value.Tag.float_16.create(arena, @round(f));
},
32 => {
const f = val.toFloat(f32);
return Value.Tag.float_32.create(arena, @round(f));
},
64 => {
const f = val.toFloat(f64);
return Value.Tag.float_64.create(arena, @round(f));
},
80 => {
if (true) {
@panic("TODO implement compiler_rt round for f80");
}
const f = val.toFloat(f80);
return Value.Tag.float_80.create(arena, @round(f));
},
128 => {
const f = val.toFloat(f128);
return Value.Tag.float_128.create(arena, @round(f));
},
else => unreachable,
}
}
pub fn trunc(val: Value, float_type: Type, arena: Allocator, target: Target) Allocator.Error!Value {
switch (float_type.floatBits(target)) {
16 => {
const f = val.toFloat(f16);
return Value.Tag.float_16.create(arena, @trunc(f));
},
32 => {
const f = val.toFloat(f32);
return Value.Tag.float_32.create(arena, @trunc(f));
},
64 => {
const f = val.toFloat(f64);
return Value.Tag.float_64.create(arena, @trunc(f));
},
80 => {
if (true) {
@panic("TODO implement compiler_rt trunc for f80");
}
const f = val.toFloat(f80);
return Value.Tag.float_80.create(arena, @trunc(f));
},
128 => {
const f = val.toFloat(f128);
return Value.Tag.float_128.create(arena, @trunc(f));
},
else => unreachable,
}
}
pub fn mulAdd(
float_type: Type,
mulend1: Value,
mulend2: Value,
addend: Value,
arena: Allocator,
target: Target,
) Allocator.Error!Value {
switch (float_type.floatBits(target)) {
16 => {
const m1 = mulend1.toFloat(f16);
const m2 = mulend2.toFloat(f16);
const a = addend.toFloat(f16);
return Value.Tag.float_16.create(arena, @mulAdd(f16, m1, m2, a));
},
32 => {
const m1 = mulend1.toFloat(f32);
const m2 = mulend2.toFloat(f32);
const a = addend.toFloat(f32);
return Value.Tag.float_32.create(arena, @mulAdd(f32, m1, m2, a));
},
64 => {
const m1 = mulend1.toFloat(f64);
const m2 = mulend2.toFloat(f64);
const a = addend.toFloat(f64);
return Value.Tag.float_64.create(arena, @mulAdd(f64, m1, m2, a));
},
80 => {
const m1 = mulend1.toFloat(f80);
const m2 = mulend2.toFloat(f80);
const a = addend.toFloat(f80);
return Value.Tag.float_80.create(arena, @mulAdd(f80, m1, m2, a));
},
128 => {
const m1 = mulend1.toFloat(f128);
const m2 = mulend2.toFloat(f128);
const a = addend.toFloat(f128);
return Value.Tag.float_128.create(arena, @mulAdd(f128, m1, m2, a));
},
else => unreachable,
}
}
/// This type is not copyable since it may contain pointers to its inner data.
pub const Payload = struct {
tag: Tag,
pub const U32 = struct {
base: Payload,
data: u32,
};
pub const U64 = struct {
base: Payload,
data: u64,
};
pub const I64 = struct {
base: Payload,
data: i64,
};
pub const BigInt = struct {
base: Payload,
data: []const std.math.big.Limb,
pub fn asBigInt(self: BigInt) BigIntConst {
const positive = switch (self.base.tag) {
.int_big_positive => true,
.int_big_negative => false,
else => unreachable,
};
return BigIntConst{ .limbs = self.data, .positive = positive };
}
};
pub const Function = struct {
base: Payload,
data: *Module.Fn,
};
pub const ExternFn = struct {
base: Payload,
data: *Module.ExternFn,
};
pub const Decl = struct {
base: Payload,
data: *Module.Decl,
};
pub const Variable = struct {
base: Payload,
data: *Module.Var,
};
pub const SubValue = struct {
base: Payload,
data: Value,
};
pub const DeclRefMut = struct {
pub const base_tag = Tag.decl_ref_mut;
base: Payload = Payload{ .tag = base_tag },
data: Data,
pub const Data = struct {
decl: *Module.Decl,
runtime_index: u32,
};
};
pub const PayloadPtr = struct {
base: Payload,
data: struct {
container_ptr: Value,
container_ty: Type,
},
};
pub const ElemPtr = struct {
pub const base_tag = Tag.elem_ptr;
base: Payload = Payload{ .tag = base_tag },
data: struct {
array_ptr: Value,
elem_ty: Type,
index: usize,
},
};
pub const FieldPtr = struct {
pub const base_tag = Tag.field_ptr;
base: Payload = Payload{ .tag = base_tag },
data: struct {
container_ptr: Value,
container_ty: Type,
field_index: usize,
},
};
pub const Bytes = struct {
base: Payload,
/// Includes the sentinel, if any.
data: []const u8,
};
pub const Aggregate = struct {
base: Payload,
/// Field values. The types are according to the struct or array type.
/// The length is provided here so that copying a Value does not depend on the Type.
data: []Value,
};
pub const Slice = struct {
base: Payload,
data: struct {
ptr: Value,
len: Value,
},
};
pub const Ty = struct {
base: Payload,
data: Type,
};
pub const IntType = struct {
pub const base_tag = Tag.int_type;
base: Payload = Payload{ .tag = base_tag },
data: struct {
bits: u16,
signed: bool,
},
};
pub const Float_16 = struct {
pub const base_tag = Tag.float_16;
base: Payload = .{ .tag = base_tag },
data: f16,
};
pub const Float_32 = struct {
pub const base_tag = Tag.float_32;
base: Payload = .{ .tag = base_tag },
data: f32,
};
pub const Float_64 = struct {
pub const base_tag = Tag.float_64;
base: Payload = .{ .tag = base_tag },
data: f64,
};
pub const Float_80 = struct {
pub const base_tag = Tag.float_80;
base: Payload = .{ .tag = base_tag },
data: f80,
};
pub const Float_128 = struct {
pub const base_tag = Tag.float_128;
base: Payload = .{ .tag = base_tag },
data: f128,
};
pub const Error = struct {
base: Payload = .{ .tag = .@"error" },
data: struct {
/// `name` is owned by `Module` and will be valid for the entire
/// duration of the compilation.
/// TODO revisit this when we have the concept of the error tag type
name: []const u8,
},
};
pub const InferredAlloc = struct {
pub const base_tag = Tag.inferred_alloc;
base: Payload = .{ .tag = base_tag },
data: struct {
/// The value stored in the inferred allocation. This will go into
/// peer type resolution. This is stored in a separate list so that
/// the items are contiguous in memory and thus can be passed to
/// `Module.resolvePeerTypes`.
stored_inst_list: std.ArrayListUnmanaged(Air.Inst.Ref) = .{},
/// 0 means ABI-aligned.
alignment: u16,
},
};
pub const InferredAllocComptime = struct {
pub const base_tag = Tag.inferred_alloc_comptime;
base: Payload = .{ .tag = base_tag },
data: struct {
decl: *Module.Decl,
/// 0 means ABI-aligned.
alignment: u16,
},
};
pub const Union = struct {
pub const base_tag = Tag.@"union";
base: Payload = .{ .tag = base_tag },
data: struct {
tag: Value,
val: Value,
},
};
pub const BoundFn = struct {
pub const base_tag = Tag.bound_fn;
base: Payload = Payload{ .tag = base_tag },
data: struct {
func_inst: Air.Inst.Ref,
arg0_inst: Air.Inst.Ref,
},
};
};
/// Big enough to fit any non-BigInt value
pub const BigIntSpace = struct {
/// The +1 is headroom so that operations such as incrementing once or decrementing once
/// are possible without using an allocator.
limbs: [(@sizeOf(u64) / @sizeOf(std.math.big.Limb)) + 1]std.math.big.Limb,
};
pub const zero = initTag(.zero);
pub const one = initTag(.one);
pub const negative_one: Value = .{ .ptr_otherwise = &negative_one_payload.base };
pub const undef = initTag(.undef);
pub const @"void" = initTag(.void_value);
pub const @"null" = initTag(.null_value);
pub const @"false" = initTag(.bool_false);
pub const @"true" = initTag(.bool_true);
pub fn makeBool(x: bool) Value {
return if (x) Value.@"true" else Value.@"false";
}
};
var negative_one_payload: Value.Payload.I64 = .{
.base = .{ .tag = .int_i64 },
.data = -1,
}; | src/value.zig |
const std = @import("std");
const argsParser = @import("zig-args");
const glob = @import("glob");
var allocator: std.mem.Allocator = undefined;
pub fn main() !u8 {
const stdout = std.io.getStdOut().writer();
var stderr = std.io.bufferedWriter(std.io.getStdErr().writer());
var gpa = std.heap.GeneralPurposeAllocator(.{}){};
defer _ = gpa.deinit();
allocator = gpa.allocator();
const args = try argsParser.parseForCurrentProcess(struct {
buffer: u6 = 0,
fps: u64 = 10,
window: u64 = 60,
help: bool = false,
pub const shorthands = .{
.b = "buffer",
.f = "fps",
.w = "window",
.h = "help",
};
}, allocator, .print);
defer args.deinit();
if (args.options.help) {
try stdout.print("Usage: {s} [options] globs...\n\nOptions:\n", .{std.fs.path.basename(args.executable_name.?)});
try stdout.writeAll(" --buffer, -b Buffer size as power of two (e.g. 20 = 1MiB) (default: 0 - autodetect)\n");
try stdout.writeAll(" --fps, -f Progress updates per second (default: 10)\n");
try stdout.writeAll(" --window, -w ETA window in seconds (default: 60)\n");
return 1;
}
var dir = try std.fs.cwd().openDir(".", .{
.access_sub_paths = true,
.iterate = true,
});
defer dir.close();
var files = std.ArrayList(FileInfo).init(allocator);
defer {
for (files.items) |info| {
allocator.free(info.path);
info.file.close();
}
files.deinit();
}
var total_size: usize = 0;
for (args.positionals) |pattern| {
var globber = try glob.Iterator.init(allocator, dir, pattern);
defer globber.deinit();
while (try globber.next()) |path| {
const file = try dir.openFile(path, .{ .mode = .read_only });
errdefer file.close();
const stat = try file.stat();
try files.append(.{
.path = try allocator.dupe(u8, path),
.file = file,
.size = stat.size,
});
total_size += stat.size;
}
}
var total_copied: usize = 0;
const buffer_size = if (args.options.buffer > 0)
@as(usize, 1) << args.options.buffer
else
std.math.max(std.mem.page_size, std.math.min(std.math.floorPowerOfTwo(usize, total_size / 1000), 1 << 21));
const buffer = try allocator.alloc(u8, buffer_size);
defer allocator.free(buffer);
var fifo = std.fifo.LinearFifo(u8, .Slice).init(buffer);
var progress = try Progress(@TypeOf(stderr)).init(total_size, stderr, .{
.fps = args.options.fps,
.window = args.options.window,
});
for (files.items) |info| {
// LinearFifo.pump with status
while (true) {
if (fifo.writableLength() > 0) {
const nr = try info.file.read(fifo.writableSlice(0));
if (nr == 0) break;
fifo.update(nr);
}
const nw = try stdout.write(fifo.readableSlice(0));
total_copied += nw;
fifo.discard(nw);
try progress.update(total_copied);
}
while (fifo.readableLength() > 0) {
const nw = try stderr.write(fifo.readableSlice(0));
total_copied += nw;
fifo.discard(nw);
try progress.update(total_copied);
}
}
return 0;
}
const FileInfo = struct {
path: []const u8,
file: std.fs.File,
size: u64,
};
fn Progress(comptime Writer: type) type {
return struct {
const Self = @This();
pub const Options = struct {
fps: u64 = 10,
window: u64 = 60,
};
total: usize,
writer: Writer,
frame_ns: u64,
weight_base: f64,
timer: std.time.Timer,
last_value: u64 = 0,
last_ns: u64 = 0,
ns_rate: f64 = 0,
pub fn init(total: usize, writer: Writer, options: Options) !Self {
const alpha = 2.0 / (1.0 + @intToFloat(f64, options.window * std.time.ns_per_s));
var progress = Self{
.total = total,
.writer = writer,
.frame_ns = std.time.ns_per_s / options.fps,
.weight_base = 1 - alpha,
.timer = try std.time.Timer.start(),
};
try progress.print(0, 0);
return progress;
}
pub fn update(self: *Self, value: usize) !void {
const now = self.timer.read();
const last_frame_num = self.last_ns / self.frame_ns;
const curr_frame_num = now / self.frame_ns;
if (curr_frame_num > last_frame_num or value >= self.total) {
if (value >= self.total) {
self.ns_rate = @intToFloat(f64, self.total) / @intToFloat(f64, now);
} else {
self.estimateRate(value, now);
}
try self.print(value, now);
self.last_value = value;
self.last_ns = now;
}
}
fn estimateRate(self: *Self, value: usize, now: u64) void {
const value_diff = @intToFloat(f64, value - self.last_value);
const ns_diff = @intToFloat(f64, now - self.last_ns);
const ns_rate = value_diff / ns_diff;
const weight = 1.0 - std.math.pow(f64, self.weight_base, ns_diff);
if (self.ns_rate == 0) {
self.ns_rate = ns_rate;
} else {
self.ns_rate += weight * (ns_rate - self.ns_rate);
}
}
fn print(self: *Self, value: usize, now: u64) !void {
const writer = self.writer.writer();
const progress = @intToFloat(f64, value) / @intToFloat(f64, self.total);
try writer.print("\x1b[G{:.2} / {:.2} ({:.2}%)", .{
fmtIntSizeBin(@truncate(u64, value)),
fmtIntSizeBin(@truncate(u64, self.total)),
fmtPrecision(100 * progress),
});
if (now > 0) {
try writer.print(" in {:.2} ({:.2}/s)", .{
fmtDuration(now),
fmtIntSizeBin(@floatToInt(u64, self.ns_rate * std.time.ns_per_s)),
});
}
if (value >= self.total) {
try writer.writeAll("\x1b[K");
} else if (self.ns_rate > 0) {
const bytes_remaining = self.total - value;
const ns_remaining = @floatToInt(u64, @intToFloat(f64, bytes_remaining) / self.ns_rate);
try writer.print(", ETA {:.2}\x1b[K", .{fmtDuration(ns_remaining)});
}
try self.writer.flush();
}
};
}
fn formatDuration(ns: u64, comptime fmt: []const u8, options: std.fmt.FormatOptions, writer: anytype) !void {
_ = fmt;
const odd_units = [_]struct { ns: u64, suffix: u8 }{
.{ .ns = 365 * std.time.ns_per_day, .suffix = 'y' },
.{ .ns = 365 * std.time.ns_per_day / 12, .suffix = 'm' },
.{ .ns = std.time.ns_per_week, .suffix = 'w' },
.{ .ns = std.time.ns_per_day, .suffix = 'd' },
.{ .ns = std.time.ns_per_hour, .suffix = 'h' },
.{ .ns = std.time.ns_per_min, .suffix = 'm' },
.{ .ns = std.time.ns_per_s, .suffix = 's' },
};
for (odd_units[0 .. odd_units.len - 1]) |unit, i| {
if (ns < unit.ns) continue;
// Print this unit
try std.fmt.formatInt(ns / unit.ns, 10, .lower, options, writer);
try writer.writeByte(unit.suffix);
// Print the next unit
const remaining = ns % unit.ns;
const next = odd_units[i + 1];
try std.fmt.formatInt(remaining / next.ns, 10, .lower, .{ .width = 2, .fill = '0' }, writer);
try writer.writeByte(next.suffix);
return;
}
const dec_units = [_]struct { ns: u64, suffix: []const u8 }{
.{ .ns = std.time.ns_per_s, .suffix = "s" },
.{ .ns = std.time.ns_per_ms, .suffix = "ms" },
.{ .ns = std.time.ns_per_us, .suffix = "us" },
};
for (dec_units) |unit, i| {
if (ns < unit.ns) continue;
var float = @intToFloat(f64, ns) / @intToFloat(f64, unit.ns);
var suffix = unit.suffix;
if (float >= 999.5) {
// Will be rounded up to 1000; promote unit
float = 1;
suffix = dec_units[i - 1].suffix;
}
try formatFloatPrecision(float, options, writer);
try writer.writeAll(suffix);
return;
}
try std.fmt.formatInt(ns, 10, .lower, .{}, writer);
try writer.writeAll("ns");
}
test "formatDuration" {
const cases = [_]struct { ns: u64, s: []const u8 }{
.{ .ns = 1, .s = "1ns" },
.{ .ns = 999, .s = "999ns" },
.{ .ns = 1_000, .s = "1.00us" },
.{ .ns = 1_004, .s = "1.00us" },
.{ .ns = 1_005, .s = "1.01us" },
.{ .ns = 1_010, .s = "1.01us" },
.{ .ns = 99_040, .s = "99.0us" },
.{ .ns = 99_050, .s = "99.1us" },
.{ .ns = 998_499, .s = "998us" },
.{ .ns = 998_500, .s = "999us" },
.{ .ns = 999_499, .s = "999us" },
.{ .ns = 999_500, .s = "1.00ms" },
.{ .ns = 999_499_999, .s = "999ms" },
.{ .ns = 999_500_000, .s = "1.00s" },
.{ .ns = std.time.ns_per_s - 1, .s = "1.00s" },
.{ .ns = std.time.ns_per_min - 1, .s = "60.0s" },
.{ .ns = std.time.ns_per_min, .s = "1m00s" },
.{ .ns = std.time.ns_per_min + 1, .s = "1m00s" },
.{ .ns = std.time.ns_per_min + std.time.ns_per_s, .s = "1m01s" },
.{ .ns = 2 * 365 * std.time.ns_per_day - 1, .s = "1y11m" },
.{ .ns = 2 * 365 * std.time.ns_per_day, .s = "2y00m" },
.{ .ns = 2 * 365 * std.time.ns_per_day + 1, .s = "2y00m" },
.{ .ns = 2 * 365 * std.time.ns_per_day + 61 * std.time.ns_per_day, .s = "2y02m" },
};
for (cases) |case| {
var buffer: [128]u8 = undefined;
var stream = std.io.fixedBufferStream(&buffer);
try formatDuration(case.ns, "", .{ .precision = 2 }, stream.writer());
std.debug.print("{d} = {s}\n", .{ case.ns, buffer[0..stream.pos] });
try std.testing.expectEqualStrings(case.s, buffer[0..stream.pos]);
}
}
fn fmtDuration(ns: u64) std.fmt.Formatter(formatDuration) {
return .{ .data = ns };
}
fn formatFloatPrecision(value: f64, options: std.fmt.FormatOptions, writer: anytype) !void {
if (!std.math.isFinite(value)) return std.fmt.formatFloatDecimal(value, options, writer);
const precision = @intToFloat(f64, options.precision orelse return std.fmt.formatFloatDecimal(value, options, writer));
const exponent = std.math.floor(std.math.log10(value));
var opts = options;
opts.precision = if (exponent > precision)
0
else
@floatToInt(usize, std.math.min(precision, precision - exponent));
return std.fmt.formatFloatDecimal(value, opts, writer);
}
fn formatPrecision(value: f64, comptime fmt: []const u8, options: std.fmt.FormatOptions, writer: anytype) !void {
_ = fmt;
return formatFloatPrecision(value, options, writer);
}
fn fmtPrecision(value: f64) std.fmt.Formatter(formatPrecision) {
return .{ .data = value };
}
test "formatFloatPrecision" {
const cases = [_]struct { n: f64, s: []const u8 }{
.{ .n = 0.0011111, .s = "0.00" },
.{ .n = 0.011111, .s = "0.01" },
.{ .n = 0.11111, .s = "0.11" },
.{ .n = 1.11111, .s = "1.11" },
.{ .n = 11.11111, .s = "11.1" },
.{ .n = 111.11111, .s = "111" },
.{ .n = 1111.11111, .s = "1111" },
.{ .n = 11111.11111, .s = "11111" },
};
for (cases) |case| {
var buffer: [128]u8 = undefined;
var stream = std.io.fixedBufferStream(&buffer);
try formatFloatPrecision(case.n, .{ .precision = 2 }, stream.writer());
try std.testing.expectEqualStrings(case.s, buffer[0..stream.pos]);
}
}
fn FormatSizeImpl(comptime radix: comptime_int) type {
return struct {
fn f(
value: u64,
comptime fmt: []const u8,
options: std.fmt.FormatOptions,
writer: anytype,
) !void {
_ = fmt;
if (value == 0) {
return writer.writeAll("0B");
}
const mags_si = " kMGTPEZY";
const mags_iec = " KMGTPEZY";
const log2 = std.math.log2(value);
const magnitude = switch (radix) {
1000 => std.math.min(log2 / comptime std.math.log2(1000), mags_si.len - 1),
1024 => std.math.min(log2 / 10, mags_iec.len - 1),
else => unreachable,
};
var new_value = std.math.lossyCast(f64, value) / std.math.pow(f64, std.math.lossyCast(f64, radix), std.math.lossyCast(f64, magnitude));
var suffix = switch (radix) {
1000 => mags_si[magnitude],
1024 => mags_iec[magnitude],
else => unreachable,
};
if (new_value >= 999.5) {
new_value /= radix;
suffix = switch (radix) {
1000 => mags_si[magnitude + 1],
1024 => mags_iec[magnitude + 1],
else => unreachable,
};
}
try formatFloatPrecision(new_value, options, writer);
if (suffix == ' ') {
return writer.writeAll("B");
}
const buf = switch (radix) {
1000 => &[_]u8{ suffix, 'B' },
1024 => &[_]u8{ suffix, 'i', 'B' },
else => unreachable,
};
return writer.writeAll(buf);
}
};
}
const formatSizeDec = FormatSizeImpl(1000).f;
const formatSizeBin = FormatSizeImpl(1024).f;
/// Return a Formatter for a u64 value representing a file size.
/// This formatter represents the number as multiple of 1000 and uses the SI
/// measurement units (kB, MB, GB, ...).
pub fn fmtIntSizeDec(value: u64) std.fmt.Formatter(formatSizeDec) {
return .{ .data = value };
}
/// Return a Formatter for a u64 value representing a file size.
/// This formatter represents the number as multiple of 1024 and uses the IEC
/// measurement units (KiB, MiB, GiB, ...).
pub fn fmtIntSizeBin(value: u64) std.fmt.Formatter(formatSizeBin) {
return .{ .data = value };
} | src/main.zig |
const std = @import("std");
const io = std.io;
const mem = std.mem;
const fs = std.fs;
const process = std.process;
const Allocator = mem.Allocator;
const ArrayList = std.ArrayList;
const Buffer = std.Buffer;
const arg = @import("arg.zig");
const self_hosted_main = @import("main.zig");
const Args = arg.Args;
const Flag = arg.Flag;
const errmsg = @import("errmsg.zig");
const DepTokenizer = @import("dep_tokenizer.zig").Tokenizer;
var stderr_file: fs.File = undefined;
var stderr: *io.OutStream(fs.File.WriteError) = undefined;
var stdout: *io.OutStream(fs.File.WriteError) = undefined;
comptime {
_ = @import("dep_tokenizer.zig");
}
// ABI warning
export fn stage2_zen(ptr: *[*]const u8, len: *usize) void {
const info_zen = @import("main.zig").info_zen;
ptr.* = info_zen;
len.* = info_zen.len;
}
// ABI warning
export fn stage2_panic(ptr: [*]const u8, len: usize) void {
@panic(ptr[0..len]);
}
// ABI warning
const TranslateMode = extern enum {
import,
translate,
};
// ABI warning
const Error = extern enum {
None,
OutOfMemory,
InvalidFormat,
SemanticAnalyzeFail,
AccessDenied,
Interrupted,
SystemResources,
FileNotFound,
FileSystem,
FileTooBig,
DivByZero,
Overflow,
PathAlreadyExists,
Unexpected,
ExactDivRemainder,
NegativeDenominator,
ShiftedOutOneBits,
CCompileErrors,
EndOfFile,
IsDir,
NotDir,
UnsupportedOperatingSystem,
SharingViolation,
PipeBusy,
PrimitiveTypeNotFound,
CacheUnavailable,
PathTooLong,
CCompilerCannotFindFile,
ReadingDepFile,
InvalidDepFile,
MissingArchitecture,
MissingOperatingSystem,
UnknownArchitecture,
UnknownOperatingSystem,
UnknownABI,
InvalidFilename,
DiskQuota,
DiskSpace,
UnexpectedWriteFailure,
UnexpectedSeekFailure,
UnexpectedFileTruncationFailure,
Unimplemented,
OperationAborted,
BrokenPipe,
NoSpaceLeft,
};
const FILE = std.c.FILE;
const ast = std.zig.ast;
const translate_c = @import("translate_c.zig");
/// Args should have a null terminating last arg.
export fn stage2_translate_c(
out_ast: **ast.Tree,
out_errors_ptr: *[*]translate_c.ClangErrMsg,
out_errors_len: *usize,
args_begin: [*]?[*]const u8,
args_end: [*]?[*]const u8,
mode: TranslateMode,
resources_path: [*]const u8,
) Error {
var errors: []translate_c.ClangErrMsg = undefined;
out_ast.* = translate_c.translate(std.heap.c_allocator, args_begin, args_end, switch (mode) {
.import => translate_c.Mode.import,
.translate => translate_c.Mode.translate,
}, &errors, resources_path) catch |err| switch (err) {
error.SemanticAnalyzeFail => {
out_errors_ptr.* = errors.ptr;
out_errors_len.* = errors.len;
return Error.CCompileErrors;
},
error.OutOfMemory => return Error.OutOfMemory,
};
return Error.None;
}
export fn stage2_free_clang_errors(errors_ptr: [*]translate_c.ClangErrMsg, errors_len: usize) void {
translate_c.freeErrors(errors_ptr[0..errors_len]);
}
export fn stage2_render_ast(tree: *ast.Tree, output_file: *FILE) Error {
const c_out_stream = &std.io.COutStream.init(output_file).stream;
_ = std.zig.render(std.heap.c_allocator, c_out_stream, tree) catch |e| switch (e) {
error.WouldBlock => unreachable, // stage1 opens stuff in exclusively blocking mode
error.SystemResources => return Error.SystemResources,
error.OperationAborted => return Error.OperationAborted,
error.BrokenPipe => return Error.BrokenPipe,
error.DiskQuota => return Error.DiskQuota,
error.FileTooBig => return Error.FileTooBig,
error.NoSpaceLeft => return Error.NoSpaceLeft,
error.AccessDenied => return Error.AccessDenied,
error.OutOfMemory => return Error.OutOfMemory,
error.Unexpected => return Error.Unexpected,
error.InputOutput => return Error.FileSystem,
};
return Error.None;
}
// TODO: just use the actual self-hosted zig fmt. Until https://github.com/ziglang/zig/issues/2377,
// we use a blocking implementation.
export fn stage2_fmt(argc: c_int, argv: [*]const [*:0]const u8) c_int {
if (std.debug.runtime_safety) {
fmtMain(argc, argv) catch unreachable;
} else {
fmtMain(argc, argv) catch |e| {
std.debug.warn("{}\n", @errorName(e));
return -1;
};
}
return 0;
}
fn fmtMain(argc: c_int, argv: [*]const [*:0]const u8) !void {
const allocator = std.heap.c_allocator;
var args_list = std.ArrayList([]const u8).init(allocator);
const argc_usize = @intCast(usize, argc);
var arg_i: usize = 0;
while (arg_i < argc_usize) : (arg_i += 1) {
try args_list.append(std.mem.toSliceConst(u8, argv[arg_i]));
}
stdout = &std.io.getStdOut().outStream().stream;
stderr_file = std.io.getStdErr();
stderr = &stderr_file.outStream().stream;
const args = args_list.toSliceConst();
var flags = try Args.parse(allocator, &self_hosted_main.args_fmt_spec, args[2..]);
defer flags.deinit();
if (flags.present("help")) {
try stdout.write(self_hosted_main.usage_fmt);
process.exit(0);
}
const color = blk: {
if (flags.single("color")) |color_flag| {
if (mem.eql(u8, color_flag, "auto")) {
break :blk errmsg.Color.Auto;
} else if (mem.eql(u8, color_flag, "on")) {
break :blk errmsg.Color.On;
} else if (mem.eql(u8, color_flag, "off")) {
break :blk errmsg.Color.Off;
} else unreachable;
} else {
break :blk errmsg.Color.Auto;
}
};
if (flags.present("stdin")) {
if (flags.positionals.len != 0) {
try stderr.write("cannot use --stdin with positional arguments\n");
process.exit(1);
}
const stdin_file = io.getStdIn();
var stdin = stdin_file.inStream();
const source_code = try stdin.stream.readAllAlloc(allocator, self_hosted_main.max_src_size);
defer allocator.free(source_code);
const tree = std.zig.parse(allocator, source_code) catch |err| {
try stderr.print("error parsing stdin: {}\n", err);
process.exit(1);
};
defer tree.deinit();
var error_it = tree.errors.iterator(0);
while (error_it.next()) |parse_error| {
try printErrMsgToFile(allocator, parse_error, tree, "<stdin>", stderr_file, color);
}
if (tree.errors.len != 0) {
process.exit(1);
}
if (flags.present("check")) {
const anything_changed = try std.zig.render(allocator, io.null_out_stream, tree);
const code = if (anything_changed) @as(u8, 1) else @as(u8, 0);
process.exit(code);
}
_ = try std.zig.render(allocator, stdout, tree);
return;
}
if (flags.positionals.len == 0) {
try stderr.write("expected at least one source file argument\n");
process.exit(1);
}
var fmt = Fmt{
.seen = Fmt.SeenMap.init(allocator),
.any_error = false,
.color = color,
.allocator = allocator,
};
const check_mode = flags.present("check");
for (flags.positionals.toSliceConst()) |file_path| {
try fmtPath(&fmt, file_path, check_mode);
}
if (fmt.any_error) {
process.exit(1);
}
}
const FmtError = error{
SystemResources,
OperationAborted,
IoPending,
BrokenPipe,
Unexpected,
WouldBlock,
FileClosed,
DestinationAddressRequired,
DiskQuota,
FileTooBig,
InputOutput,
NoSpaceLeft,
AccessDenied,
OutOfMemory,
RenameAcrossMountPoints,
ReadOnlyFileSystem,
LinkQuotaExceeded,
FileBusy,
} || fs.File.OpenError;
fn fmtPath(fmt: *Fmt, file_path_ref: []const u8, check_mode: bool) FmtError!void {
const file_path = try std.mem.dupe(fmt.allocator, u8, file_path_ref);
defer fmt.allocator.free(file_path);
if (try fmt.seen.put(file_path, {})) |_| return;
const source_code = io.readFileAlloc(fmt.allocator, file_path) catch |err| switch (err) {
error.IsDir, error.AccessDenied => {
// TODO make event based (and dir.next())
var dir = try fs.cwd().openDirList(file_path);
defer dir.close();
var dir_it = dir.iterate();
while (try dir_it.next()) |entry| {
if (entry.kind == .Directory or mem.endsWith(u8, entry.name, ".zig")) {
const full_path = try fs.path.join(fmt.allocator, &[_][]const u8{ file_path, entry.name });
try fmtPath(fmt, full_path, check_mode);
}
}
return;
},
else => {
// TODO lock stderr printing
try stderr.print("unable to open '{}': {}\n", file_path, err);
fmt.any_error = true;
return;
},
};
defer fmt.allocator.free(source_code);
const tree = std.zig.parse(fmt.allocator, source_code) catch |err| {
try stderr.print("error parsing file '{}': {}\n", file_path, err);
fmt.any_error = true;
return;
};
defer tree.deinit();
var error_it = tree.errors.iterator(0);
while (error_it.next()) |parse_error| {
try printErrMsgToFile(fmt.allocator, parse_error, tree, file_path, stderr_file, fmt.color);
}
if (tree.errors.len != 0) {
fmt.any_error = true;
return;
}
if (check_mode) {
const anything_changed = try std.zig.render(fmt.allocator, io.null_out_stream, tree);
if (anything_changed) {
try stderr.print("{}\n", file_path);
fmt.any_error = true;
}
} else {
const baf = try io.BufferedAtomicFile.create(fmt.allocator, file_path);
defer baf.destroy();
const anything_changed = try std.zig.render(fmt.allocator, baf.stream(), tree);
if (anything_changed) {
try stderr.print("{}\n", file_path);
try baf.finish();
}
}
}
const Fmt = struct {
seen: SeenMap,
any_error: bool,
color: errmsg.Color,
allocator: *mem.Allocator,
const SeenMap = std.StringHashMap(void);
};
fn printErrMsgToFile(
allocator: *mem.Allocator,
parse_error: *const ast.Error,
tree: *ast.Tree,
path: []const u8,
file: fs.File,
color: errmsg.Color,
) !void {
const color_on = switch (color) {
.Auto => file.isTty(),
.On => true,
.Off => false,
};
const lok_token = parse_error.loc();
const span = errmsg.Span{
.first = lok_token,
.last = lok_token,
};
const first_token = tree.tokens.at(span.first);
const last_token = tree.tokens.at(span.last);
const start_loc = tree.tokenLocationPtr(0, first_token);
const end_loc = tree.tokenLocationPtr(first_token.end, last_token);
var text_buf = try std.Buffer.initSize(allocator, 0);
var out_stream = &std.io.BufferOutStream.init(&text_buf).stream;
try parse_error.render(&tree.tokens, out_stream);
const text = text_buf.toOwnedSlice();
const stream = &file.outStream().stream;
try stream.print("{}:{}:{}: error: {}\n", path, start_loc.line + 1, start_loc.column + 1, text);
if (!color_on) return;
// Print \r and \t as one space each so that column counts line up
for (tree.source[start_loc.line_start..start_loc.line_end]) |byte| {
try stream.writeByte(switch (byte) {
'\r', '\t' => ' ',
else => byte,
});
}
try stream.writeByte('\n');
try stream.writeByteNTimes(' ', start_loc.column);
try stream.writeByteNTimes('~', last_token.end - first_token.start);
try stream.writeByte('\n');
}
export fn stage2_DepTokenizer_init(input: [*]const u8, len: usize) stage2_DepTokenizer {
const t = std.heap.c_allocator.create(DepTokenizer) catch @panic("failed to create .d tokenizer");
t.* = DepTokenizer.init(std.heap.c_allocator, input[0..len]);
return stage2_DepTokenizer{
.handle = t,
};
}
export fn stage2_DepTokenizer_deinit(self: *stage2_DepTokenizer) void {
self.handle.deinit();
}
export fn stage2_DepTokenizer_next(self: *stage2_DepTokenizer) stage2_DepNextResult {
const otoken = self.handle.next() catch {
const textz = std.Buffer.init(&self.handle.arena.allocator, self.handle.error_text) catch @panic("failed to create .d tokenizer error text");
return stage2_DepNextResult{
.type_id = .error_,
.textz = textz.toSlice().ptr,
};
};
const token = otoken orelse {
return stage2_DepNextResult{
.type_id = .null_,
.textz = undefined,
};
};
const textz = std.Buffer.init(&self.handle.arena.allocator, token.bytes) catch @panic("failed to create .d tokenizer token text");
return stage2_DepNextResult{
.type_id = switch (token.id) {
.target => .target,
.prereq => .prereq,
},
.textz = textz.toSlice().ptr,
};
}
const stage2_DepTokenizer = extern struct {
handle: *DepTokenizer,
};
const stage2_DepNextResult = extern struct {
type_id: TypeId,
// when type_id == error --> error text
// when type_id == null --> undefined
// when type_id == target --> target pathname
// when type_id == prereq --> prereq pathname
textz: [*]const u8,
const TypeId = extern enum {
error_,
null_,
target,
prereq,
};
};
// ABI warning
export fn stage2_attach_segfault_handler() void {
if (std.debug.runtime_safety and std.debug.have_segfault_handling_support) {
std.debug.attachSegfaultHandler();
}
}
// ABI warning
export fn stage2_progress_create() *std.Progress {
const ptr = std.heap.c_allocator.create(std.Progress) catch @panic("out of memory");
ptr.* = std.Progress{};
return ptr;
}
// ABI warning
export fn stage2_progress_destroy(progress: *std.Progress) void {
std.heap.c_allocator.destroy(progress);
}
// ABI warning
export fn stage2_progress_start_root(
progress: *std.Progress,
name_ptr: [*]const u8,
name_len: usize,
estimated_total_items: usize,
) *std.Progress.Node {
return progress.start(
name_ptr[0..name_len],
if (estimated_total_items == 0) null else estimated_total_items,
) catch @panic("timer unsupported");
}
// ABI warning
export fn stage2_progress_disable_tty(progress: *std.Progress) void {
progress.terminal = null;
}
// ABI warning
export fn stage2_progress_start(
node: *std.Progress.Node,
name_ptr: [*]const u8,
name_len: usize,
estimated_total_items: usize,
) *std.Progress.Node {
const child_node = std.heap.c_allocator.create(std.Progress.Node) catch @panic("out of memory");
child_node.* = node.start(
name_ptr[0..name_len],
if (estimated_total_items == 0) null else estimated_total_items,
);
child_node.activate();
return child_node;
}
// ABI warning
export fn stage2_progress_end(node: *std.Progress.Node) void {
node.end();
if (&node.context.root != node) {
std.heap.c_allocator.destroy(node);
}
}
// ABI warning
export fn stage2_progress_complete_one(node: *std.Progress.Node) void {
node.completeOne();
}
// ABI warning
export fn stage2_progress_update_node(node: *std.Progress.Node, done_count: usize, total_count: usize) void {
node.completed_items = done_count;
node.estimated_total_items = total_count;
node.activate();
node.context.maybeRefresh();
} | src-self-hosted/stage1.zig |
const std = @import("std.zig");
const target = std.Target.current;
pub const Ordering = std.builtin.AtomicOrder;
pub const Stack = @import("atomic/stack.zig").Stack;
pub const Queue = @import("atomic/queue.zig").Queue;
pub const Atomic = @import("atomic/Atomic.zig").Atomic;
test "std.atomic" {
_ = @import("atomic/stack.zig");
_ = @import("atomic/queue.zig");
_ = @import("atomic/Atomic.zig");
}
pub fn fence(comptime ordering: Ordering) callconv(.Inline) void {
switch (ordering) {
.Acquire, .Release, .AcqRel, .SeqCst => {
@fence(ordering);
},
else => {
@compileLog(ordering, " only applies to a given memory location");
},
}
}
pub fn compilerFence(comptime ordering: Ordering) callconv(.Inline) void {
switch (ordering) {
.Acquire, .Release, .AcqRel, .SeqCst => asm volatile ("" ::: "memory"),
else => @compileLog(ordering, " only applies to a given memory location"),
}
}
test "fence/compilerFence" {
inline for (.{ .Acquire, .Release, .AcqRel, .SeqCst }) |ordering| {
compilerFence(ordering);
fence(ordering);
}
}
/// Signals to the processor that the caller is inside a busy-wait spin-loop.
pub fn spinLoopHint() callconv(.Inline) void {
const hint_instruction = switch (target.cpu.arch) {
// No-op instruction that can hint to save (or share with a hardware-thread) pipelining/power resources
// https://software.intel.com/content/www/us/en/develop/articles/benefitting-power-and-performance-sleep-loops.html
.i386, .x86_64 => "pause",
// No-op instruction that serves as a hardware-thread resource yield hint.
// https://stackoverflow.com/a/7588941
.powerpc64, .powerpc64le => "or 27, 27, 27",
// `isb` appears more reliable for releasing execution resources than `yield` on common aarch64 CPUs.
// https://bugs.java.com/bugdatabase/view_bug.do?bug_id=8258604
// https://bugs.mysql.com/bug.php?id=100664
.aarch64, .aarch64_be, .aarch64_32 => "isb",
// `yield` was introduced in v6k but is also available on v6m.
// https://www.keil.com/support/man/docs/armasm/armasm_dom1361289926796.htm
.arm, .armeb, .thumb, .thumbeb => blk: {
const can_yield = comptime std.Target.arm.featureSetHasAny(target.cpu.features, .{ .has_v6k, .has_v6m });
const instruction = if (can_yield) "yield" else "";
break :blk instruction;
},
else => "",
};
// Memory barrier to prevent the compiler from optimizing away the spin-loop
// even if no hint_instruction was provided.
asm volatile (hint_instruction ::: "memory");
}
test "spinLoopHint" {
var i: usize = 10;
while (i > 0) : (i -= 1) {
spinLoopHint();
}
} | lib/std/atomic.zig |
const std = @import("std");
const utils = @import("utils");
const Allocator = std.mem.Allocator;
const ArenaAllocator = std.heap.ArenaAllocator;
const print = utils.print;
const eql = std.mem.eql;
const isLower = std.ascii.isLower;
const Kind = union(enum) {
Start,
End,
Small,
Large,
};
const Cave = struct {
name: []const u8,
kind: Kind,
visits: i32,
};
const Connection = struct { left: usize, right: usize };
const CaveSystem = struct {
caves: []Cave,
connections: []Connection,
};
fn readInput(arena: *ArenaAllocator, lines_it: *utils.FileLineIterator) anyerror!CaveSystem {
var caves = try std.ArrayList(Cave).initCapacity(&arena.allocator, 100);
var connections = try std.ArrayList(Connection).initCapacity(&arena.allocator, 100);
while (lines_it.next()) |line| {
var parts = std.mem.tokenize(u8, line, "-");
const left = try appendOrGetCave(&caves, parts.next().?);
const right = try appendOrGetCave(&caves, parts.next().?);
try connections.append(Connection{ .left = left, .right = right });
}
print("File ok :) Number of inputs: {d}", .{connections.items.len});
return CaveSystem{
.caves = caves.items,
.connections = connections.items,
};
}
fn appendOrGetCave(caves: *std.ArrayList(Cave), name: []const u8) anyerror!usize {
for (caves.items) |cave, i| {
if (eql(u8, name, cave.name)) {
return i;
}
} else {
if (eql(u8, name, "start")) {
try caves.append(Cave{ .name = name, .kind = Kind.Start, .visits = 0 });
} else if (eql(u8, name, "end")) {
try caves.append(Cave{ .name = name, .kind = Kind.End, .visits = 0 });
} else if (isLower(name[0])) {
try caves.append(Cave{ .name = name, .kind = Kind.Small, .visits = 0 });
} else {
try caves.append(Cave{ .name = name, .kind = Kind.Large, .visits = 0 });
}
return caves.items.len - 1;
}
}
fn countPaths(system: *CaveSystem, cave_index: usize, small_visited_twice: bool) i32 {
var cave = &system.caves[cave_index];
switch (cave.kind) {
Kind.End => return 1,
Kind.Start => if (cave.visits > 0) return 0,
Kind.Large => {},
Kind.Small => if (cave.visits > 0 and small_visited_twice) return 0,
}
const visiting_small_second_time = cave.visits >= 1 and cave.kind == Kind.Small;
cave.visits += 1;
var res: i32 = 0;
for (system.connections) |con| {
if (cave_index == con.left) {
res += countPaths(system, con.right, small_visited_twice or visiting_small_second_time);
}
if (cave_index == con.right) {
res += countPaths(system, con.left, small_visited_twice or visiting_small_second_time);
}
}
cave.visits -= 1;
return res;
}
fn part1(system: *CaveSystem) i32 {
for (system.caves) |cave, i| {
if (cave.kind == Kind.Start) {
return countPaths(system, i, true);
}
}
unreachable;
}
fn part2(system: *CaveSystem) i32 {
for (system.caves) |cave, i| {
if (cave.kind == Kind.Start) {
return countPaths(system, i, false);
}
}
unreachable;
}
pub fn main() anyerror!void {
var arena = std.heap.ArenaAllocator.init(std.heap.page_allocator);
defer arena.deinit();
var lines_it = try utils.iterateLinesInFile(&arena.allocator, "input.txt");
defer lines_it.deinit();
var input = try readInput(&arena, &lines_it);
const part1_result = part1(&input);
print("Part 1: {d}", .{part1_result});
const part2_result = part2(&input);
print("Part 2: {d}", .{part2_result});
} | day12/src/main.zig |
const io = @import("./io.zig");
const Terminal = @import("tty.zig");
const cpu = @import("./cpu.zig");
// The slave 8259 is connected to the master's IRQ2 line.
// This is really only to enhance clarity.
pub const SLAVE_INDEX = 2;
pub const PIC0_CTL = 0x20;
pub const PIC0_CMD = 0x21;
pub const PIC1_CTL = 0xA0;
pub const PIC1_CMD = 0xA1;
pub const PIC = struct {
var initialized = false;
pub fn disable(irq: u8) void {
var imr: u8 = undefined;
if ((irq & 8) != 0) {
imr = io.in(u8, PIC1_CMD);
imr |= (@as(u8, 1) << @intCast(u3, irq - 8));
io.out(u8, PIC1_CMD, imr);
} else {
imr = io.in(u8, PIC0_CMD);
imr |= (@as(u8, 1) << @intCast(u3, irq));
io.out(u8, PIC0_CMD, imr);
}
}
pub fn enable(irq: u8) void {
var imr: u8 = undefined;
if ((irq & 8) != 0) {
imr = io.in(u8, PIC1_CMD);
imr |= ~(1 << (irq - 8));
io.out(u8, PIC1_CMD, imr);
} else {
imr = io.in(u8, PIC0_CMD);
imr |= ~(1 << irq);
io.out(u8, PIC0_CMD, imr);
}
}
pub fn eoi(irq: u8) void {
if ((irq & 8) != 0)
io.out(u8, PIC1_CTL, 0x20);
io.out(u8, PIC0_CTL, 0x20);
}
pub fn init() void {
// ICW1 (edge triggered mode, cascading controllers, expect ICW4)
io.out(u8, PIC0_CTL, 0x11);
io.out(u8, PIC1_CTL, 0x11);
// ICW2 (upper 5 bits specify ISR indices, lower 3 idunno)
io.out(u8, PIC0_CMD, cpu.IRQ_VECTOR_BASE);
io.out(u8, PIC1_CMD, cpu.IRQ_VECTOR_BASE + 0x08);
// ICW3 (configure master/slave relationship)
io.out(u8, PIC0_CMD, 1 << SLAVE_INDEX);
io.out(u8, PIC1_CMD, SLAVE_INDEX);
// ICW4 (set x86 mode)
io.out(u8, PIC0_CMD, 0x01);
io.out(u8, PIC1_CMD, 0x01);
// Mask -- enable all interrupts on both PICs.
// Not really what I want here, but I'm unsure how to
// selectively enable secondary PIC IRQs...
io.out(u8, PIC0_CMD, 0x00);
io.out(u8, PIC1_CMD, 0x00);
// HACK: Disable busmouse IRQ for now.
disable(5);
Terminal.print("PIC(i8259): cascading mode, vectors 0x{b:}-0x{b:}\r\n", .{ cpu.IRQ_VECTOR_BASE, cpu.IRQ_VECTOR_BASE + 0x08 });
}
}; | src/kernel/arch/x86/boot/pic.zig |
const std = @import("std");
const upaya = @import("upaya.zig");
usingnamespace upaya.sokol;
pub const Texture = extern struct {
img: sg_image = undefined,
width: i32 = 0,
height: i32 = 0,
pub const Filter = enum { linear, nearest };
pub fn initOffscreen(width: i32, height: i32, filter: Filter) Texture {
var img_desc = std.mem.zeroes(sg_image_desc);
img_desc.render_target = true;
img_desc.width = width;
img_desc.height = height;
img_desc.pixel_format = .SG_PIXELFORMAT_RGBA8;
img_desc.min_filter = if (filter == .linear) .SG_FILTER_LINEAR else .SG_FILTER_NEAREST;
img_desc.mag_filter = if (filter == .linear) .SG_FILTER_LINEAR else .SG_FILTER_NEAREST;
return .{ .width = width, .height = height, .img = sg_make_image(&img_desc) };
}
pub fn init(width: i32, height: i32, filter: Filter) Texture {
var img_desc = std.mem.zeroes(sg_image_desc);
img_desc.width = width;
img_desc.height = height;
img_desc.pixel_format = .SG_PIXELFORMAT_RGBA8;
img_desc.wrap_u = .SG_WRAP_CLAMP_TO_EDGE;
img_desc.wrap_v = .SG_WRAP_CLAMP_TO_EDGE;
img_desc.min_filter = if (filter == .linear) .SG_FILTER_LINEAR else .SG_FILTER_NEAREST;
img_desc.mag_filter = if (filter == .linear) .SG_FILTER_LINEAR else .SG_FILTER_NEAREST;
img_desc.content.subimage[0][0].size = width * height * 4 * @sizeOf(u8);
return .{ .width = width, .height = height, .img = sg_make_image(&img_desc) };
}
pub fn initWithData(pixels: []u8, width: i32, height: i32, filter: Filter) Texture {
var img_desc = std.mem.zeroes(sg_image_desc);
img_desc.width = width;
img_desc.height = height;
img_desc.pixel_format = .SG_PIXELFORMAT_RGBA8;
img_desc.wrap_u = .SG_WRAP_CLAMP_TO_EDGE;
img_desc.wrap_v = .SG_WRAP_CLAMP_TO_EDGE;
img_desc.min_filter = if (filter == .linear) .SG_FILTER_LINEAR else .SG_FILTER_NEAREST;
img_desc.mag_filter = if (filter == .linear) .SG_FILTER_LINEAR else .SG_FILTER_NEAREST;
img_desc.content.subimage[0][0].ptr = pixels.ptr;
img_desc.content.subimage[0][0].size = width * height * 4 * @sizeOf(u8);
img_desc.label = "upaya-texture";
return .{ .width = width, .height = height, .img = sg_make_image(&img_desc) };
}
pub fn initWithColorData(pixels: []u32, width: i32, height: i32, filter: Filter) Texture {
var img_desc = std.mem.zeroes(sg_image_desc);
img_desc.width = width;
img_desc.height = height;
img_desc.pixel_format = .SG_PIXELFORMAT_RGBA8;
img_desc.wrap_u = .SG_WRAP_CLAMP_TO_EDGE;
img_desc.wrap_v = .SG_WRAP_CLAMP_TO_EDGE;
img_desc.min_filter = if (filter == .linear) .SG_FILTER_LINEAR else .SG_FILTER_NEAREST;
img_desc.mag_filter = if (filter == .linear) .SG_FILTER_LINEAR else .SG_FILTER_NEAREST;
img_desc.content.subimage[0][0].ptr = pixels.ptr;
img_desc.content.subimage[0][0].size = width * height * @sizeOf(u32);
img_desc.label = "upaya-texture";
return .{ .width = width, .height = height, .img = sg_make_image(&img_desc) };
}
pub fn initFromFile(file: []const u8, filter: Filter) !Texture {
const image_contents = try upaya.fs.read(upaya.mem.tmp_allocator, file);
var w: c_int = undefined;
var h: c_int = undefined;
var channels: c_int = undefined;
const load_res = upaya.stb.stbi_load_from_memory(image_contents.ptr, @intCast(c_int, image_contents.len), &w, &h, &channels, 4);
if (load_res == null) return error.ImageLoadFailed;
defer upaya.stb.stbi_image_free(load_res);
return Texture.initWithData(load_res[0..@intCast(usize, w * h * channels)], w, h, filter);
}
pub fn deinit(self: Texture) void {
sg_destroy_image(self.img);
}
pub fn setData(self: Texture, data: []u8) void {
std.debug.panic("not implemented\n", .{});
// aya.gfx.device.setTextureData2D(self.tex, .color, 0, 0, self.width, self.height, 0, &data[0], @intCast(i32, data.len));
}
pub fn setColorData(self: Texture, data: []u32) void {
std.debug.panic("not implemented\n", .{});
// aya.gfx.device.setTextureData2D(self.tex, .color, 0, 0, self.width, self.height, 0, &data[0], @intCast(i32, data.len));
}
pub fn imTextureID(self: Texture) upaya.imgui.ImTextureID {
return @intToPtr(*c_void, self.img.id);
}
/// returns true if the image was loaded successfully
pub fn getTextureSize(file: []const u8, w: *c_int, h: *c_int) bool {
const image_contents = upaya.fs.read(upaya.mem.tmp_allocator, file) catch unreachable;
var comp: c_int = undefined;
if (upaya.stb.stbi_info_from_memory(image_contents.ptr, @intCast(c_int, image_contents.len), w, h, &comp) == 1) {
return true;
}
return false;
}
}; | src/texture.zig |
const std = @import("std");
const vk = @import("../vk.zig");
const c = @import("../c.zig");
const tracy = @import("../tracy.zig");
const vkctxt = @import("../vulkan_wrapper/vulkan_context.zig");
const Allocator = std.mem.Allocator;
const Application = @import("../application/application.zig").Application;
pub const System = @import("../system/system.zig").System;
const rg = @import("render_graph/render_graph.zig");
const RenderGraph = rg.RenderGraph;
const RGPass = @import("render_graph/render_graph_pass.zig").RGPass;
const RGResource = @import("render_graph/render_graph_resource.zig").RGResource;
const printError = @import("../application/print_error.zig").printError;
const frames_in_flight: u32 = 2;
pub const DefaultRenderer = struct {
allocator: Allocator,
name: []const u8,
system: System,
app: *Application,
image_available_semaphores: [frames_in_flight]vk.Semaphore,
render_finished_semaphores: [frames_in_flight]vk.Semaphore,
in_flight_fences: [frames_in_flight]vk.Fence,
framebuffer_resized: bool,
pub fn init(self: *DefaultRenderer, comptime name: []const u8, allocator: Allocator) void {
self.allocator = allocator;
self.name = name;
self.framebuffer_resized = false;
self.system = System.create(name ++ " System", systemInit, systemDeinit, systemUpdate);
rg.global_render_graph.init(self.allocator);
rg.global_render_graph.final_swapchain.rg_resource.init("Final Swapchain", self.allocator);
}
fn systemInit(system: *System, app: *Application) void {
const self: *DefaultRenderer = @fieldParentPtr(DefaultRenderer, "system", system);
self.app = app;
vkctxt.vkc.init(self.allocator, app) catch @panic("Error during vulkan context initialization");
var width: i32 = undefined;
var height: i32 = undefined;
c.glfwGetFramebufferSize(app.window, &width, &height);
rg.global_render_graph.final_swapchain.init(@intCast(u32, width), @intCast(u32, height), frames_in_flight) catch @panic("Error during swapchain creation");
rg.global_render_graph.initVulkan(frames_in_flight);
self.createSyncObjects() catch @panic("Can't create sync objects");
}
fn systemDeinit(system: *System) void {
const self: *DefaultRenderer = @fieldParentPtr(DefaultRenderer, "system", system);
for (rg.global_render_graph.passes.items) |pass|
pass.deinitFn(pass);
self.destroySyncObjects();
rg.global_render_graph.final_swapchain.deinit();
rg.global_render_graph.deinit();
vkctxt.vkc.deinit();
}
fn systemUpdate(system: *System, elapsed_time: f64) void {
_ = elapsed_time;
const self: *DefaultRenderer = @fieldParentPtr(DefaultRenderer, "system", system);
self.render() catch @panic("Error during rendering");
}
fn createSyncObjects(self: *DefaultRenderer) !void {
const semaphore_info: vk.SemaphoreCreateInfo = .{
.flags = .{},
};
const fence_info: vk.FenceCreateInfo = .{
.flags = .{
.signaled_bit = true,
},
};
var i: usize = 0;
while (i < frames_in_flight) : (i += 1) {
self.image_available_semaphores[i] = vkctxt.vkd.createSemaphore(vkctxt.vkc.device, semaphore_info, null) catch |err| {
vkctxt.printVulkanError("Can't create semaphore", err, self.allocator);
return err;
};
self.render_finished_semaphores[i] = vkctxt.vkd.createSemaphore(vkctxt.vkc.device, semaphore_info, null) catch |err| {
vkctxt.printVulkanError("Can't create semaphore", err, self.allocator);
return err;
};
self.in_flight_fences[i] = vkctxt.vkd.createFence(vkctxt.vkc.device, fence_info, null) catch |err| {
vkctxt.printVulkanError("Can't create fence", err, self.allocator);
return err;
};
}
}
fn destroySyncObjects(self: *DefaultRenderer) void {
var i: usize = 0;
while (i < frames_in_flight) : (i += 1) {
vkctxt.vkd.destroySemaphore(vkctxt.vkc.device, self.image_available_semaphores[i], null);
vkctxt.vkd.destroySemaphore(vkctxt.vkc.device, self.render_finished_semaphores[i], null);
vkctxt.vkd.destroyFence(vkctxt.vkc.device, self.in_flight_fences[i], null);
}
}
fn recreateSwapchain(self: *DefaultRenderer) !void {
var width: c_int = undefined;
var height: c_int = undefined;
while (width <= 0 or height <= 0) {
c.glfwGetFramebufferSize(self.app.window, &width, &height);
c.glfwWaitEvents();
}
try rg.global_render_graph.final_swapchain.recreate(@intCast(u32, width), @intCast(u32, height));
}
fn render(self: *DefaultRenderer) !void {
_ = vkctxt.vkd.waitForFences(vkctxt.vkc.device, 1, @ptrCast([*]const vk.Fence, &self.in_flight_fences[rg.global_render_graph.frame_index]), vk.TRUE, std.math.maxInt(u64)) catch |err| {
vkctxt.printVulkanError("Can't wait for a in flight fence", err, self.allocator);
return err;
};
var image_index: u32 = undefined;
const vkres_acquire: vk.Result = vkctxt.vkd.vkAcquireNextImageKHR(
vkctxt.vkc.device,
rg.global_render_graph.final_swapchain.swapchain,
std.math.maxInt(u64),
self.image_available_semaphores[rg.global_render_graph.frame_index],
.null_handle,
&image_index,
);
rg.global_render_graph.image_index = image_index;
if (vkres_acquire == .error_out_of_date_khr) {
try self.recreateSwapchain();
return;
} else if (vkres_acquire != .success and vkres_acquire != .suboptimal_khr) {
printError("Renderer", "Error while getting swapchain image");
return error.Unknown;
}
var command_buffer: vk.CommandBuffer = rg.global_render_graph.command_buffers[rg.global_render_graph.frame_index];
vkctxt.vkd.resetCommandBuffer(command_buffer, .{}) catch |err| {
vkctxt.printVulkanError("Can't reset command buffer", err, self.allocator);
};
RenderGraph.beginSingleTimeCommands(command_buffer);
rg.global_render_graph.render(command_buffer);
RenderGraph.endSingleTimeCommands(command_buffer);
const wait_stage: vk.PipelineStageFlags = .{ .color_attachment_output_bit = true };
const submit_info: vk.SubmitInfo = .{
.wait_semaphore_count = 1,
.p_wait_semaphores = @ptrCast([*]vk.Semaphore, &self.image_available_semaphores[rg.global_render_graph.frame_index]),
.p_wait_dst_stage_mask = @ptrCast([*]const vk.PipelineStageFlags, &wait_stage),
.command_buffer_count = 1,
.p_command_buffers = @ptrCast([*]vk.CommandBuffer, &command_buffer),
.signal_semaphore_count = 1,
.p_signal_semaphores = @ptrCast([*]vk.Semaphore, &self.render_finished_semaphores[rg.global_render_graph.frame_index]),
};
vkctxt.vkd.resetFences(vkctxt.vkc.device, 1, @ptrCast([*]vk.Fence, &self.in_flight_fences[rg.global_render_graph.frame_index])) catch |err| {
vkctxt.printVulkanError("Can't reset in flight fence", err, self.allocator);
return err;
};
vkctxt.vkd.queueSubmit(vkctxt.vkc.graphics_queue, 1, @ptrCast([*]const vk.SubmitInfo, &submit_info), self.in_flight_fences[rg.global_render_graph.frame_index]) catch |err| {
vkctxt.printVulkanError("Can't submit render queue", err, vkctxt.vkc.allocator);
};
const present_info: vk.PresentInfoKHR = .{
.wait_semaphore_count = 1,
.p_wait_semaphores = @ptrCast([*]vk.Semaphore, &self.render_finished_semaphores[rg.global_render_graph.frame_index]),
.swapchain_count = 1,
.p_swapchains = @ptrCast([*]vk.SwapchainKHR, &rg.global_render_graph.final_swapchain.swapchain),
.p_image_indices = @ptrCast([*]const u32, &image_index),
.p_results = null,
};
const vkres_present = vkctxt.vkd.vkQueuePresentKHR(vkctxt.vkc.present_queue, &present_info);
if (vkres_present == .error_out_of_date_khr or vkres_present == .suboptimal_khr) {
try self.recreateSwapchain();
} else if (vkres_present != .success) {
printError("Vulkan Wrapper", "Can't queue present");
return error.Unknown;
}
rg.global_render_graph.frame_index = (rg.global_render_graph.frame_index + 1) % frames_in_flight;
rg.global_render_graph.executeResourceChanges();
if (rg.global_render_graph.needs_rebuilding)
rg.global_render_graph.build();
}
}; | src/renderer/default_renderer.zig |
const std = @import("std");
const bmp = @import("bmp.zig");
const png = @import("png.zig");
const Image = @import("image.zig").Image;
const IcoHeader = struct {
reserved: u16,
image_type: u16,
image_count: u16,
pub fn read(reader: anytype) !IcoHeader {
var ico_header: IcoHeader = undefined;
ico_header.reserved = try reader.readIntLittle(u16);
ico_header.image_type = try reader.readIntLittle(u16);
ico_header.image_count = try reader.readIntLittle(u16);
return ico_header;
}
};
const IcoDirEntry = struct {
width: u8,
height: u8,
colpaletter: u8,
reserved: u8,
planes: u16,
bpp: u16,
size: u32,
offset: u32,
pub fn read(reader: anytype) !IcoDirEntry {
var ico_dir_entry: IcoDirEntry = undefined;
ico_dir_entry.width = try reader.readIntLittle(u8);
ico_dir_entry.height = try reader.readIntLittle(u8);
ico_dir_entry.colpaletter = try reader.readIntLittle(u8);
ico_dir_entry.reserved = try reader.readIntLittle(u8);
ico_dir_entry.planes = try reader.readIntLittle(u16);
ico_dir_entry.bpp = try reader.readIntLittle(u16);
ico_dir_entry.size = try reader.readIntLittle(u32);
ico_dir_entry.offset = try reader.readIntLittle(u32);
return ico_dir_entry;
}
};
pub fn parse(reader: anytype, allocator: std.mem.Allocator) ![]Image {
const header: IcoHeader = IcoHeader.read(reader) catch unreachable;
const icons: []IcoDirEntry = allocator.alloc(IcoDirEntry, header.image_count) catch unreachable;
defer allocator.free(icons);
for (icons) |*ico|
ico.* = IcoDirEntry.read(reader) catch unreachable;
var seekable_stream = reader.context.seekableStream();
var images: []Image = allocator.alloc(Image, header.image_count) catch unreachable;
for (icons) |ico, i| {
try seekable_stream.seekTo(ico.offset);
if (png.check_header(reader) catch false) {
images[i] = try png.parse(reader, allocator);
} else {
seekable_stream.seekTo(ico.offset) catch unreachable;
images[i] = try bmp.parse(reader, allocator);
}
}
return images;
} | src/image/ico.zig |
//--------------------------------------------------------------------------------
// Section: Types (6)
//--------------------------------------------------------------------------------
pub const HCN_NOTIFICATIONS = enum(i32) {
Invalid = 0,
NetworkPreCreate = 1,
NetworkCreate = 2,
NetworkPreDelete = 3,
NetworkDelete = 4,
NamespaceCreate = 5,
NamespaceDelete = 6,
GuestNetworkServiceCreate = 7,
GuestNetworkServiceDelete = 8,
NetworkEndpointAttached = 9,
NetworkEndpointDetached = 16,
GuestNetworkServiceStateChanged = 17,
GuestNetworkServiceInterfaceStateChanged = 18,
ServiceDisconnect = 16777216,
FlagsReserved = -268435456,
};
pub const HcnNotificationInvalid = HCN_NOTIFICATIONS.Invalid;
pub const HcnNotificationNetworkPreCreate = HCN_NOTIFICATIONS.NetworkPreCreate;
pub const HcnNotificationNetworkCreate = HCN_NOTIFICATIONS.NetworkCreate;
pub const HcnNotificationNetworkPreDelete = HCN_NOTIFICATIONS.NetworkPreDelete;
pub const HcnNotificationNetworkDelete = HCN_NOTIFICATIONS.NetworkDelete;
pub const HcnNotificationNamespaceCreate = HCN_NOTIFICATIONS.NamespaceCreate;
pub const HcnNotificationNamespaceDelete = HCN_NOTIFICATIONS.NamespaceDelete;
pub const HcnNotificationGuestNetworkServiceCreate = HCN_NOTIFICATIONS.GuestNetworkServiceCreate;
pub const HcnNotificationGuestNetworkServiceDelete = HCN_NOTIFICATIONS.GuestNetworkServiceDelete;
pub const HcnNotificationNetworkEndpointAttached = HCN_NOTIFICATIONS.NetworkEndpointAttached;
pub const HcnNotificationNetworkEndpointDetached = HCN_NOTIFICATIONS.NetworkEndpointDetached;
pub const HcnNotificationGuestNetworkServiceStateChanged = HCN_NOTIFICATIONS.GuestNetworkServiceStateChanged;
pub const HcnNotificationGuestNetworkServiceInterfaceStateChanged = HCN_NOTIFICATIONS.GuestNetworkServiceInterfaceStateChanged;
pub const HcnNotificationServiceDisconnect = HCN_NOTIFICATIONS.ServiceDisconnect;
pub const HcnNotificationFlagsReserved = HCN_NOTIFICATIONS.FlagsReserved;
pub const HCN_NOTIFICATION_CALLBACK = fn(
NotificationType: u32,
Context: ?*anyopaque,
NotificationStatus: HRESULT,
NotificationData: ?[*:0]const u16,
) callconv(@import("std").os.windows.WINAPI) void;
pub const HCN_PORT_PROTOCOL = enum(i32) {
TCP = 1,
UDP = 2,
BOTH = 3,
};
pub const HCN_PORT_PROTOCOL_TCP = HCN_PORT_PROTOCOL.TCP;
pub const HCN_PORT_PROTOCOL_UDP = HCN_PORT_PROTOCOL.UDP;
pub const HCN_PORT_PROTOCOL_BOTH = HCN_PORT_PROTOCOL.BOTH;
pub const HCN_PORT_ACCESS = enum(i32) {
EXCLUSIVE = 1,
SHARED = 2,
};
pub const HCN_PORT_ACCESS_EXCLUSIVE = HCN_PORT_ACCESS.EXCLUSIVE;
pub const HCN_PORT_ACCESS_SHARED = HCN_PORT_ACCESS.SHARED;
pub const HCN_PORT_RANGE_RESERVATION = extern struct {
startingPort: u16,
endingPort: u16,
};
pub const HCN_PORT_RANGE_ENTRY = extern struct {
OwningPartitionId: Guid,
TargetPartitionId: Guid,
Protocol: HCN_PORT_PROTOCOL,
Priority: u64,
ReservationType: u32,
SharingFlags: u32,
DeliveryMode: u32,
StartingPort: u16,
EndingPort: u16,
};
//--------------------------------------------------------------------------------
// Section: Functions (41)
//--------------------------------------------------------------------------------
pub extern "computenetwork" fn HcnEnumerateNetworks(
Query: ?[*:0]const u16,
Networks: ?*?PWSTR,
ErrorRecord: ?*?PWSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT;
pub extern "computenetwork" fn HcnCreateNetwork(
Id: ?*const Guid,
Settings: ?[*:0]const u16,
Network: ?*?*anyopaque,
ErrorRecord: ?*?PWSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT;
pub extern "computenetwork" fn HcnOpenNetwork(
Id: ?*const Guid,
Network: ?*?*anyopaque,
ErrorRecord: ?*?PWSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT;
pub extern "computenetwork" fn HcnModifyNetwork(
Network: ?*anyopaque,
Settings: ?[*:0]const u16,
ErrorRecord: ?*?PWSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT;
pub extern "computenetwork" fn HcnQueryNetworkProperties(
Network: ?*anyopaque,
Query: ?[*:0]const u16,
Properties: ?*?PWSTR,
ErrorRecord: ?*?PWSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT;
pub extern "computenetwork" fn HcnDeleteNetwork(
Id: ?*const Guid,
ErrorRecord: ?*?PWSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT;
pub extern "computenetwork" fn HcnCloseNetwork(
Network: ?*anyopaque,
) callconv(@import("std").os.windows.WINAPI) HRESULT;
pub extern "computenetwork" fn HcnEnumerateNamespaces(
Query: ?[*:0]const u16,
Namespaces: ?*?PWSTR,
ErrorRecord: ?*?PWSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT;
pub extern "computenetwork" fn HcnCreateNamespace(
Id: ?*const Guid,
Settings: ?[*:0]const u16,
Namespace: ?*?*anyopaque,
ErrorRecord: ?*?PWSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT;
pub extern "computenetwork" fn HcnOpenNamespace(
Id: ?*const Guid,
Namespace: ?*?*anyopaque,
ErrorRecord: ?*?PWSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT;
pub extern "computenetwork" fn HcnModifyNamespace(
Namespace: ?*anyopaque,
Settings: ?[*:0]const u16,
ErrorRecord: ?*?PWSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT;
pub extern "computenetwork" fn HcnQueryNamespaceProperties(
Namespace: ?*anyopaque,
Query: ?[*:0]const u16,
Properties: ?*?PWSTR,
ErrorRecord: ?*?PWSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT;
pub extern "computenetwork" fn HcnDeleteNamespace(
Id: ?*const Guid,
ErrorRecord: ?*?PWSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT;
pub extern "computenetwork" fn HcnCloseNamespace(
Namespace: ?*anyopaque,
) callconv(@import("std").os.windows.WINAPI) HRESULT;
pub extern "computenetwork" fn HcnEnumerateEndpoints(
Query: ?[*:0]const u16,
Endpoints: ?*?PWSTR,
ErrorRecord: ?*?PWSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT;
pub extern "computenetwork" fn HcnCreateEndpoint(
Network: ?*anyopaque,
Id: ?*const Guid,
Settings: ?[*:0]const u16,
Endpoint: ?*?*anyopaque,
ErrorRecord: ?*?PWSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT;
pub extern "computenetwork" fn HcnOpenEndpoint(
Id: ?*const Guid,
Endpoint: ?*?*anyopaque,
ErrorRecord: ?*?PWSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT;
pub extern "computenetwork" fn HcnModifyEndpoint(
Endpoint: ?*anyopaque,
Settings: ?[*:0]const u16,
ErrorRecord: ?*?PWSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT;
pub extern "computenetwork" fn HcnQueryEndpointProperties(
Endpoint: ?*anyopaque,
Query: ?[*:0]const u16,
Properties: ?*?PWSTR,
ErrorRecord: ?*?PWSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT;
pub extern "computenetwork" fn HcnDeleteEndpoint(
Id: ?*const Guid,
ErrorRecord: ?*?PWSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT;
pub extern "computenetwork" fn HcnCloseEndpoint(
Endpoint: ?*anyopaque,
) callconv(@import("std").os.windows.WINAPI) HRESULT;
pub extern "computenetwork" fn HcnEnumerateLoadBalancers(
Query: ?[*:0]const u16,
LoadBalancer: ?*?PWSTR,
ErrorRecord: ?*?PWSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT;
pub extern "computenetwork" fn HcnCreateLoadBalancer(
Id: ?*const Guid,
Settings: ?[*:0]const u16,
LoadBalancer: ?*?*anyopaque,
ErrorRecord: ?*?PWSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT;
pub extern "computenetwork" fn HcnOpenLoadBalancer(
Id: ?*const Guid,
LoadBalancer: ?*?*anyopaque,
ErrorRecord: ?*?PWSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT;
pub extern "computenetwork" fn HcnModifyLoadBalancer(
LoadBalancer: ?*anyopaque,
Settings: ?[*:0]const u16,
ErrorRecord: ?*?PWSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT;
pub extern "computenetwork" fn HcnQueryLoadBalancerProperties(
LoadBalancer: ?*anyopaque,
Query: ?[*:0]const u16,
Properties: ?*?PWSTR,
ErrorRecord: ?*?PWSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT;
pub extern "computenetwork" fn HcnDeleteLoadBalancer(
Id: ?*const Guid,
ErrorRecord: ?*?PWSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT;
pub extern "computenetwork" fn HcnCloseLoadBalancer(
LoadBalancer: ?*anyopaque,
) callconv(@import("std").os.windows.WINAPI) HRESULT;
pub extern "computenetwork" fn HcnRegisterServiceCallback(
Callback: ?HCN_NOTIFICATION_CALLBACK,
Context: ?*anyopaque,
CallbackHandle: ?*?*anyopaque,
) callconv(@import("std").os.windows.WINAPI) HRESULT;
pub extern "computenetwork" fn HcnUnregisterServiceCallback(
CallbackHandle: ?*anyopaque,
) callconv(@import("std").os.windows.WINAPI) HRESULT;
pub extern "computenetwork" fn HcnRegisterGuestNetworkServiceCallback(
GuestNetworkService: ?*anyopaque,
Callback: ?HCN_NOTIFICATION_CALLBACK,
Context: ?*anyopaque,
CallbackHandle: ?*?*anyopaque,
) callconv(@import("std").os.windows.WINAPI) HRESULT;
pub extern "computenetwork" fn HcnUnregisterGuestNetworkServiceCallback(
CallbackHandle: ?*anyopaque,
) callconv(@import("std").os.windows.WINAPI) HRESULT;
pub extern "computenetwork" fn HcnCreateGuestNetworkService(
Id: ?*const Guid,
Settings: ?[*:0]const u16,
GuestNetworkService: ?*?*anyopaque,
ErrorRecord: ?*?PWSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT;
pub extern "computenetwork" fn HcnCloseGuestNetworkService(
GuestNetworkService: ?*anyopaque,
) callconv(@import("std").os.windows.WINAPI) HRESULT;
pub extern "computenetwork" fn HcnModifyGuestNetworkService(
GuestNetworkService: ?*anyopaque,
Settings: ?[*:0]const u16,
ErrorRecord: ?*?PWSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT;
pub extern "computenetwork" fn HcnDeleteGuestNetworkService(
Id: ?*const Guid,
ErrorRecord: ?*?PWSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT;
pub extern "computenetwork" fn HcnReserveGuestNetworkServicePort(
GuestNetworkService: ?*anyopaque,
Protocol: HCN_PORT_PROTOCOL,
Access: HCN_PORT_ACCESS,
Port: u16,
PortReservationHandle: ?*?HANDLE,
) callconv(@import("std").os.windows.WINAPI) HRESULT;
pub extern "computenetwork" fn HcnReserveGuestNetworkServicePortRange(
GuestNetworkService: ?*anyopaque,
PortCount: u16,
PortRangeReservation: ?*HCN_PORT_RANGE_RESERVATION,
PortReservationHandle: ?*?HANDLE,
) callconv(@import("std").os.windows.WINAPI) HRESULT;
pub extern "computenetwork" fn HcnReleaseGuestNetworkServicePortReservationHandle(
PortReservationHandle: ?HANDLE,
) callconv(@import("std").os.windows.WINAPI) HRESULT;
pub extern "computenetwork" fn HcnEnumerateGuestNetworkPortReservations(
ReturnCount: ?*u32,
PortEntries: ?*?*HCN_PORT_RANGE_ENTRY,
) callconv(@import("std").os.windows.WINAPI) HRESULT;
pub extern "computenetwork" fn HcnFreeGuestNetworkPortReservations(
PortEntries: ?*HCN_PORT_RANGE_ENTRY,
) callconv(@import("std").os.windows.WINAPI) void;
//--------------------------------------------------------------------------------
// Section: Unicode Aliases (0)
//--------------------------------------------------------------------------------
const thismodule = @This();
pub usingnamespace switch (@import("../zig.zig").unicode_mode) {
.ansi => struct {
},
.wide => struct {
},
.unspecified => if (@import("builtin").is_test) struct {
} else struct {
},
};
//--------------------------------------------------------------------------------
// Section: Imports (4)
//--------------------------------------------------------------------------------
const Guid = @import("../zig.zig").Guid;
const HANDLE = @import("../foundation.zig").HANDLE;
const HRESULT = @import("../foundation.zig").HRESULT;
const PWSTR = @import("../foundation.zig").PWSTR;
test {
// The following '_ = <FuncPtrType>' lines are a workaround for https://github.com/ziglang/zig/issues/4476
if (@hasDecl(@This(), "HCN_NOTIFICATION_CALLBACK")) { _ = HCN_NOTIFICATION_CALLBACK; }
@setEvalBranchQuota(
@import("std").meta.declarations(@This()).len * 3
);
// reference all the pub declarations
if (!@import("builtin").is_test) return;
inline for (@import("std").meta.declarations(@This())) |decl| {
if (decl.is_pub) {
_ = decl;
}
}
} | win32/system/host_compute_network.zig |
pub const CLSID_XFeedsManager = Guid.initString("fe6b11c3-c72e-4061-86c6-9d163121f229");
pub const WMPGC_FLAGS_ALLOW_PREROLL = @as(u32, 1);
pub const WMPGC_FLAGS_SUPPRESS_DIALOGS = @as(u32, 2);
pub const WMPGC_FLAGS_IGNORE_AV_SYNC = @as(u32, 4);
pub const WMPGC_FLAGS_DISABLE_PLUGINS = @as(u32, 8);
pub const WMPGC_FLAGS_USE_CUSTOM_GRAPH = @as(u32, 16);
pub const WMPUE_EC_USER = @as(u32, 33024);
pub const WMP_MDRT_FLAGS_UNREPORTED_DELETED_ITEMS = @as(u32, 1);
pub const WMP_MDRT_FLAGS_UNREPORTED_ADDED_ITEMS = @as(u32, 2);
pub const IOCTL_WMP_METADATA_ROUND_TRIP = @as(u32, 827346263);
pub const IOCTL_WMP_DEVICE_CAN_SYNC = @as(u32, 844123479);
pub const EFFECT_CANGOFULLSCREEN = @as(u32, 1);
pub const EFFECT_HASPROPERTYPAGE = @as(u32, 2);
pub const EFFECT_VARIABLEFREQSTEP = @as(u32, 4);
pub const EFFECT_WINDOWEDONLY = @as(u32, 8);
pub const EFFECT2_FULLSCREENEXCLUSIVE = @as(u32, 16);
pub const SA_BUFFER_SIZE = @as(u32, 1024);
pub const PLUGIN_TYPE_BACKGROUND = @as(u32, 1);
pub const PLUGIN_TYPE_SEPARATEWINDOW = @as(u32, 2);
pub const PLUGIN_TYPE_DISPLAYAREA = @as(u32, 3);
pub const PLUGIN_TYPE_SETTINGSAREA = @as(u32, 4);
pub const PLUGIN_TYPE_METADATAAREA = @as(u32, 5);
pub const PLUGIN_FLAGS_HASPROPERTYPAGE = @as(u32, 2147483648);
pub const PLUGIN_FLAGS_INSTALLAUTORUN = @as(u32, 1073741824);
pub const PLUGIN_FLAGS_LAUNCHPROPERTYPAGE = @as(u32, 536870912);
pub const PLUGIN_FLAGS_ACCEPTSMEDIA = @as(u32, 268435456);
pub const PLUGIN_FLAGS_ACCEPTSPLAYLISTS = @as(u32, 134217728);
pub const PLUGIN_FLAGS_HASPRESETS = @as(u32, 67108864);
pub const PLUGIN_FLAGS_HIDDEN = @as(u32, 33554432);
pub const SUBSCRIPTION_CAP_DEVICEAVAILABLE = @as(u32, 16);
pub const SUBSCRIPTION_CAP_BACKGROUNDPROCESSING = @as(u32, 8);
pub const SUBSCRIPTION_CAP_IS_CONTENTPARTNER = @as(u32, 64);
pub const SUBSCRIPTION_CAP_ALTLOGIN = @as(u32, 128);
pub const SUBSCRIPTION_CAP_ALLOWPLAY = @as(u32, 1);
pub const SUBSCRIPTION_CAP_ALLOWCDBURN = @as(u32, 2);
pub const SUBSCRIPTION_CAP_ALLOWPDATRANSFER = @as(u32, 4);
pub const SUBSCRIPTION_CAP_PREPAREFORSYNC = @as(u32, 32);
pub const SUBSCRIPTION_V1_CAPS = @as(u32, 15);
pub const SUBSCRIPTION_CAP_UILESSMODE_ALLOWPLAY = @as(u32, 256);
pub const DISPID_FEEDS_RootFolder = @as(u32, 4096);
pub const DISPID_FEEDS_IsSubscribed = @as(u32, 4097);
pub const DISPID_FEEDS_ExistsFeed = @as(u32, 4098);
pub const DISPID_FEEDS_GetFeed = @as(u32, 4099);
pub const DISPID_FEEDS_ExistsFolder = @as(u32, 4100);
pub const DISPID_FEEDS_GetFolder = @as(u32, 4101);
pub const DISPID_FEEDS_DeleteFeed = @as(u32, 4102);
pub const DISPID_FEEDS_DeleteFolder = @as(u32, 4103);
pub const DISPID_FEEDS_GetFeedByUrl = @as(u32, 4104);
pub const DISPID_FEEDS_BackgroundSync = @as(u32, 4105);
pub const DISPID_FEEDS_BackgroundSyncStatus = @as(u32, 4106);
pub const DISPID_FEEDS_DefaultInterval = @as(u32, 4107);
pub const DISPID_FEEDS_AsyncSyncAll = @as(u32, 4108);
pub const DISPID_FEEDS_Normalize = @as(u32, 4109);
pub const DISPID_FEEDS_ItemCountLimit = @as(u32, 4110);
pub const DISPID_FEEDSENUM_Count = @as(u32, 8192);
pub const DISPID_FEEDSENUM_Item = @as(u32, 8193);
pub const DISPID_FEEDFOLDER_Feeds = @as(u32, 12288);
pub const DISPID_FEEDFOLDER_Subfolders = @as(u32, 12289);
pub const DISPID_FEEDFOLDER_CreateFeed = @as(u32, 12290);
pub const DISPID_FEEDFOLDER_CreateSubfolder = @as(u32, 12291);
pub const DISPID_FEEDFOLDER_ExistsFeed = @as(u32, 12292);
pub const DISPID_FEEDFOLDER_GetFeed = @as(u32, 12293);
pub const DISPID_FEEDFOLDER_ExistsSubfolder = @as(u32, 12294);
pub const DISPID_FEEDFOLDER_GetSubfolder = @as(u32, 12295);
pub const DISPID_FEEDFOLDER_Delete = @as(u32, 12296);
pub const DISPID_FEEDFOLDER_Name = @as(u32, 12297);
pub const DISPID_FEEDFOLDER_Rename = @as(u32, 12298);
pub const DISPID_FEEDFOLDER_Path = @as(u32, 12299);
pub const DISPID_FEEDFOLDER_Move = @as(u32, 12300);
pub const DISPID_FEEDFOLDER_Parent = @as(u32, 12301);
pub const DISPID_FEEDFOLDER_IsRoot = @as(u32, 12302);
pub const DISPID_FEEDFOLDER_TotalUnreadItemCount = @as(u32, 12303);
pub const DISPID_FEEDFOLDER_TotalItemCount = @as(u32, 12304);
pub const DISPID_FEEDFOLDER_GetWatcher = @as(u32, 12305);
pub const DISPID_FEED_Xml = @as(u32, 16384);
pub const DISPID_FEED_Name = @as(u32, 16385);
pub const DISPID_FEED_Rename = @as(u32, 16386);
pub const DISPID_FEED_Url = @as(u32, 16387);
pub const DISPID_FEED_LocalId = @as(u32, 16388);
pub const DISPID_FEED_Path = @as(u32, 16389);
pub const DISPID_FEED_Move = @as(u32, 16390);
pub const DISPID_FEED_Parent = @as(u32, 16391);
pub const DISPID_FEED_LastWriteTime = @as(u32, 16392);
pub const DISPID_FEED_Delete = @as(u32, 16393);
pub const DISPID_FEED_Download = @as(u32, 16394);
pub const DISPID_FEED_AsyncDownload = @as(u32, 16395);
pub const DISPID_FEED_CancelAsyncDownload = @as(u32, 16396);
pub const DISPID_FEED_Interval = @as(u32, 16397);
pub const DISPID_FEED_SyncSetting = @as(u32, 16398);
pub const DISPID_FEED_LastDownloadTime = @as(u32, 16399);
pub const DISPID_FEED_LocalEnclosurePath = @as(u32, 16400);
pub const DISPID_FEED_Items = @as(u32, 16401);
pub const DISPID_FEED_GetItem = @as(u32, 16402);
pub const DISPID_FEED_Title = @as(u32, 16403);
pub const DISPID_FEED_Description = @as(u32, 16404);
pub const DISPID_FEED_Link = @as(u32, 16405);
pub const DISPID_FEED_Image = @as(u32, 16406);
pub const DISPID_FEED_LastBuildDate = @as(u32, 16407);
pub const DISPID_FEED_PubDate = @as(u32, 16408);
pub const DISPID_FEED_Ttl = @as(u32, 16409);
pub const DISPID_FEED_Language = @as(u32, 16410);
pub const DISPID_FEED_Copyright = @as(u32, 16411);
pub const DISPID_FEED_DownloadEnclosuresAutomatically = @as(u32, 16412);
pub const DISPID_FEED_DownloadStatus = @as(u32, 16413);
pub const DISPID_FEED_LastDownloadError = @as(u32, 16414);
pub const DISPID_FEED_Merge = @as(u32, 16415);
pub const DISPID_FEED_DownloadUrl = @as(u32, 16416);
pub const DISPID_FEED_IsList = @as(u32, 16417);
pub const DISPID_FEED_MarkAllItemsRead = @as(u32, 16418);
pub const DISPID_FEED_GetWatcher = @as(u32, 16419);
pub const DISPID_FEED_UnreadItemCount = @as(u32, 16420);
pub const DISPID_FEED_ItemCount = @as(u32, 16421);
pub const DISPID_FEED_MaxItemCount = @as(u32, 16422);
pub const DISPID_FEED_GetItemByEffectiveId = @as(u32, 16423);
pub const DISPID_FEED_LastItemDownloadTime = @as(u32, 16424);
pub const DISPID_FEED_Username = @as(u32, 16425);
pub const DISPID_FEED_Password = @as(u32, 16426);
pub const DISPID_FEED_SetCredentials = @as(u32, 16427);
pub const DISPID_FEED_ClearCredentials = @as(u32, 16428);
pub const DISPID_FEEDITEM_Xml = @as(u32, 20480);
pub const DISPID_FEEDITEM_Title = @as(u32, 20481);
pub const DISPID_FEEDITEM_Link = @as(u32, 20482);
pub const DISPID_FEEDITEM_Guid = @as(u32, 20483);
pub const DISPID_FEEDITEM_Description = @as(u32, 20484);
pub const DISPID_FEEDITEM_PubDate = @as(u32, 20485);
pub const DISPID_FEEDITEM_Comments = @as(u32, 20486);
pub const DISPID_FEEDITEM_Author = @as(u32, 20487);
pub const DISPID_FEEDITEM_Enclosure = @as(u32, 20488);
pub const DISPID_FEEDITEM_IsRead = @as(u32, 20489);
pub const DISPID_FEEDITEM_LocalId = @as(u32, 20490);
pub const DISPID_FEEDITEM_Parent = @as(u32, 20491);
pub const DISPID_FEEDITEM_Delete = @as(u32, 20492);
pub const DISPID_FEEDITEM_DownloadUrl = @as(u32, 20493);
pub const DISPID_FEEDITEM_LastDownloadTime = @as(u32, 20494);
pub const DISPID_FEEDITEM_Modified = @as(u32, 20495);
pub const DISPID_FEEDITEM_EffectiveId = @as(u32, 20496);
pub const DISPID_FEEDENCLOSURE_Url = @as(u32, 24576);
pub const DISPID_FEEDENCLOSURE_Type = @as(u32, 24577);
pub const DISPID_FEEDENCLOSURE_Length = @as(u32, 24578);
pub const DISPID_FEEDENCLOSURE_AsyncDownload = @as(u32, 24579);
pub const DISPID_FEEDENCLOSURE_CancelAsyncDownload = @as(u32, 24580);
pub const DISPID_FEEDENCLOSURE_DownloadStatus = @as(u32, 24581);
pub const DISPID_FEEDENCLOSURE_LastDownloadError = @as(u32, 24582);
pub const DISPID_FEEDENCLOSURE_LocalPath = @as(u32, 24583);
pub const DISPID_FEEDENCLOSURE_Parent = @as(u32, 24584);
pub const DISPID_FEEDENCLOSURE_DownloadUrl = @as(u32, 24585);
pub const DISPID_FEEDENCLOSURE_DownloadMimeType = @as(u32, 24586);
pub const DISPID_FEEDENCLOSURE_RemoveFile = @as(u32, 24587);
pub const DISPID_FEEDENCLOSURE_SetFile = @as(u32, 24588);
pub const DISPID_FEEDFOLDEREVENTS_Error = @as(u32, 28672);
pub const DISPID_FEEDFOLDEREVENTS_FolderAdded = @as(u32, 28673);
pub const DISPID_FEEDFOLDEREVENTS_FolderDeleted = @as(u32, 28674);
pub const DISPID_FEEDFOLDEREVENTS_FolderRenamed = @as(u32, 28675);
pub const DISPID_FEEDFOLDEREVENTS_FolderMovedFrom = @as(u32, 28676);
pub const DISPID_FEEDFOLDEREVENTS_FolderMovedTo = @as(u32, 28677);
pub const DISPID_FEEDFOLDEREVENTS_FolderItemCountChanged = @as(u32, 28678);
pub const DISPID_FEEDFOLDEREVENTS_FeedAdded = @as(u32, 28679);
pub const DISPID_FEEDFOLDEREVENTS_FeedDeleted = @as(u32, 28680);
pub const DISPID_FEEDFOLDEREVENTS_FeedRenamed = @as(u32, 28681);
pub const DISPID_FEEDFOLDEREVENTS_FeedUrlChanged = @as(u32, 28682);
pub const DISPID_FEEDFOLDEREVENTS_FeedMovedFrom = @as(u32, 28683);
pub const DISPID_FEEDFOLDEREVENTS_FeedMovedTo = @as(u32, 28684);
pub const DISPID_FEEDFOLDEREVENTS_FeedDownloading = @as(u32, 28685);
pub const DISPID_FEEDFOLDEREVENTS_FeedDownloadCompleted = @as(u32, 28686);
pub const DISPID_FEEDFOLDEREVENTS_FeedItemCountChanged = @as(u32, 28687);
pub const DISPID_FEEDEVENTS_Error = @as(u32, 32768);
pub const DISPID_FEEDEVENTS_FeedDeleted = @as(u32, 32769);
pub const DISPID_FEEDEVENTS_FeedRenamed = @as(u32, 32770);
pub const DISPID_FEEDEVENTS_FeedUrlChanged = @as(u32, 32771);
pub const DISPID_FEEDEVENTS_FeedMoved = @as(u32, 32772);
pub const DISPID_FEEDEVENTS_FeedDownloading = @as(u32, 32773);
pub const DISPID_FEEDEVENTS_FeedDownloadCompleted = @as(u32, 32774);
pub const DISPID_FEEDEVENTS_FeedItemCountChanged = @as(u32, 32775);
pub const DISPID_DELTA = @as(u32, 50);
pub const DISPID_WMPCORE_BASE = @as(u32, 0);
pub const DISPID_WMPCORE_URL = @as(u32, 1);
pub const DISPID_WMPCORE_OPENSTATE = @as(u32, 2);
pub const DISPID_WMPCORE_CLOSE = @as(u32, 3);
pub const DISPID_WMPCORE_CONTROLS = @as(u32, 4);
pub const DISPID_WMPCORE_SETTINGS = @as(u32, 5);
pub const DISPID_WMPCORE_CURRENTMEDIA = @as(u32, 6);
pub const DISPID_WMPCORE_NETWORK = @as(u32, 7);
pub const DISPID_WMPCORE_MEDIACOLLECTION = @as(u32, 8);
pub const DISPID_WMPCORE_PLAYLISTCOLLECTION = @as(u32, 9);
pub const DISPID_WMPCORE_PLAYSTATE = @as(u32, 10);
pub const DISPID_WMPCORE_VERSIONINFO = @as(u32, 11);
pub const DISPID_WMPCORE_LAUNCHURL = @as(u32, 12);
pub const DISPID_WMPCORE_CURRENTPLAYLIST = @as(u32, 13);
pub const DISPID_WMPCORE_CDROMCOLLECTION = @as(u32, 14);
pub const DISPID_WMPCORE_CLOSEDCAPTION = @as(u32, 15);
pub const DISPID_WMPCORE_ISONLINE = @as(u32, 16);
pub const DISPID_WMPCORE_ERROR = @as(u32, 17);
pub const DISPID_WMPCORE_STATUS = @as(u32, 18);
pub const DISPID_WMPCORE_LAST = @as(u32, 18);
pub const DISPID_WMPOCX_BASE = @as(u32, 18);
pub const DISPID_WMPOCX_ENABLED = @as(u32, 19);
pub const DISPID_WMPOCX_TRANSPARENTATSTART = @as(u32, 20);
pub const DISPID_WMPOCX_FULLSCREEN = @as(u32, 21);
pub const DISPID_WMPOCX_ENABLECONTEXTMENU = @as(u32, 22);
pub const DISPID_WMPOCX_UIMODE = @as(u32, 23);
pub const DISPID_WMPOCX_LAST = @as(u32, 23);
pub const DISPID_WMPOCX2_BASE = @as(u32, 23);
pub const DISPID_WMPOCX2_STRETCHTOFIT = @as(u32, 24);
pub const DISPID_WMPOCX2_WINDOWLESSVIDEO = @as(u32, 25);
pub const DISPID_WMPOCX4_ISREMOTE = @as(u32, 26);
pub const DISPID_WMPOCX4_PLAYERAPPLICATION = @as(u32, 27);
pub const DISPID_WMPOCX4_OPENPLAYER = @as(u32, 28);
pub const DISPID_WMPCORE2_BASE = @as(u32, 39);
pub const DISPID_WMPCORE2_DVD = @as(u32, 40);
pub const DISPID_WMPCORE3_NEWPLAYLIST = @as(u32, 41);
pub const DISPID_WMPCORE3_NEWMEDIA = @as(u32, 42);
pub const DISPID_WMPCONTROLS_PLAY = @as(u32, 51);
pub const DISPID_WMPCONTROLS_STOP = @as(u32, 52);
pub const DISPID_WMPCONTROLS_PAUSE = @as(u32, 53);
pub const DISPID_WMPCONTROLS_FASTFORWARD = @as(u32, 54);
pub const DISPID_WMPCONTROLS_FASTREVERSE = @as(u32, 55);
pub const DISPID_WMPCONTROLS_CURRENTPOSITION = @as(u32, 56);
pub const DISPID_WMPCONTROLS_CURRENTPOSITIONSTRING = @as(u32, 57);
pub const DISPID_WMPCONTROLS_NEXT = @as(u32, 58);
pub const DISPID_WMPCONTROLS_PREVIOUS = @as(u32, 59);
pub const DISPID_WMPCONTROLS_CURRENTITEM = @as(u32, 60);
pub const DISPID_WMPCONTROLS_CURRENTMARKER = @as(u32, 61);
pub const DISPID_WMPCONTROLS_ISAVAILABLE = @as(u32, 62);
pub const DISPID_WMPCONTROLS_PLAYITEM = @as(u32, 63);
pub const DISPID_WMPCONTROLS2_STEP = @as(u32, 64);
pub const DISPID_WMPCONTROLS3_AUDIOLANGUAGECOUNT = @as(u32, 65);
pub const DISPID_WMPCONTROLS3_GETAUDIOLANGUAGEID = @as(u32, 66);
pub const DISPID_WMPCONTROLS3_GETAUDIOLANGUAGEDESC = @as(u32, 67);
pub const DISPID_WMPCONTROLS3_CURRENTAUDIOLANGUAGE = @as(u32, 68);
pub const DISPID_WMPCONTROLS3_CURRENTAUDIOLANGUAGEINDEX = @as(u32, 69);
pub const DISPID_WMPCONTROLS3_GETLANGUAGENAME = @as(u32, 70);
pub const DISPID_WMPCONTROLS3_CURRENTPOSITIONTIMECODE = @as(u32, 71);
pub const DISPID_WMPCONTROLSFAKE_TIMECOMPRESSION = @as(u32, 72);
pub const DISPID_WMPSETTINGS_AUTOSTART = @as(u32, 101);
pub const DISPID_WMPSETTINGS_BALANCE = @as(u32, 102);
pub const DISPID_WMPSETTINGS_INVOKEURLS = @as(u32, 103);
pub const DISPID_WMPSETTINGS_MUTE = @as(u32, 104);
pub const DISPID_WMPSETTINGS_PLAYCOUNT = @as(u32, 105);
pub const DISPID_WMPSETTINGS_RATE = @as(u32, 106);
pub const DISPID_WMPSETTINGS_VOLUME = @as(u32, 107);
pub const DISPID_WMPSETTINGS_BASEURL = @as(u32, 108);
pub const DISPID_WMPSETTINGS_DEFAULTFRAME = @as(u32, 109);
pub const DISPID_WMPSETTINGS_GETMODE = @as(u32, 110);
pub const DISPID_WMPSETTINGS_SETMODE = @as(u32, 111);
pub const DISPID_WMPSETTINGS_ENABLEERRORDIALOGS = @as(u32, 112);
pub const DISPID_WMPSETTINGS_ISAVAILABLE = @as(u32, 113);
pub const DISPID_WMPSETTINGS2_DEFAULTAUDIOLANGUAGE = @as(u32, 114);
pub const DISPID_WMPSETTINGS2_LIBRARYACCESSRIGHTS = @as(u32, 115);
pub const DISPID_WMPSETTINGS2_REQUESTLIBRARYACCESSRIGHTS = @as(u32, 116);
pub const DISPID_WMPPLAYLIST_COUNT = @as(u32, 201);
pub const DISPID_WMPPLAYLIST_NAME = @as(u32, 202);
pub const DISPID_WMPPLAYLIST_GETITEMINFO = @as(u32, 203);
pub const DISPID_WMPPLAYLIST_SETITEMINFO = @as(u32, 204);
pub const DISPID_WMPPLAYLIST_CLEAR = @as(u32, 205);
pub const DISPID_WMPPLAYLIST_INSERTITEM = @as(u32, 206);
pub const DISPID_WMPPLAYLIST_APPENDITEM = @as(u32, 207);
pub const DISPID_WMPPLAYLIST_REMOVEITEM = @as(u32, 208);
pub const DISPID_WMPPLAYLIST_MOVEITEM = @as(u32, 209);
pub const DISPID_WMPPLAYLIST_ATTRIBUTECOUNT = @as(u32, 210);
pub const DISPID_WMPPLAYLIST_ATTRIBUTENAME = @as(u32, 211);
pub const DISPID_WMPPLAYLIST_ITEM = @as(u32, 212);
pub const DISPID_WMPPLAYLIST_ISIDENTICAL = @as(u32, 213);
pub const DISPID_WMPCDROM_DRIVESPECIFIER = @as(u32, 251);
pub const DISPID_WMPCDROM_PLAYLIST = @as(u32, 252);
pub const DISPID_WMPCDROM_EJECT = @as(u32, 253);
pub const DISPID_WMPCDROMCOLLECTION_COUNT = @as(u32, 301);
pub const DISPID_WMPCDROMCOLLECTION_ITEM = @as(u32, 302);
pub const DISPID_WMPCDROMCOLLECTION_GETBYDRIVESPECIFIER = @as(u32, 303);
pub const DISPID_WMPCDROMCOLLECTION_STARTMONITORINGCDROMS = @as(u32, 304);
pub const DISPID_WMPCDROMCOLLECTION_STOPMONITORINGCDROMS = @as(u32, 305);
pub const DISPID_WMPSTRINGCOLLECTION_COUNT = @as(u32, 401);
pub const DISPID_WMPSTRINGCOLLECTION_ITEM = @as(u32, 402);
pub const DISPID_WMPMEDIACOLLECTION_ADD = @as(u32, 452);
pub const DISPID_WMPMEDIACOLLECTION_GETALL = @as(u32, 453);
pub const DISPID_WMPMEDIACOLLECTION_GETBYNAME = @as(u32, 454);
pub const DISPID_WMPMEDIACOLLECTION_GETBYGENRE = @as(u32, 455);
pub const DISPID_WMPMEDIACOLLECTION_GETBYAUTHOR = @as(u32, 456);
pub const DISPID_WMPMEDIACOLLECTION_GETBYALBUM = @as(u32, 457);
pub const DISPID_WMPMEDIACOLLECTION_GETBYATTRIBUTE = @as(u32, 458);
pub const DISPID_WMPMEDIACOLLECTION_REMOVE = @as(u32, 459);
pub const DISPID_WMPMEDIACOLLECTION_GETATTRIBUTESTRINGCOLLECTION = @as(u32, 461);
pub const DISPID_WMPMEDIACOLLECTION_NEWQUERY = @as(u32, 462);
pub const DISPID_WMPMEDIACOLLECTION_STARTMONITORING = @as(u32, 463);
pub const DISPID_WMPMEDIACOLLECTION_STOPMONITORING = @as(u32, 464);
pub const DISPID_WMPMEDIACOLLECTION_STARTCONTENTSCAN = @as(u32, 465);
pub const DISPID_WMPMEDIACOLLECTION_STOPCONTENTSCAN = @as(u32, 466);
pub const DISPID_WMPMEDIACOLLECTION_STARTSEARCH = @as(u32, 467);
pub const DISPID_WMPMEDIACOLLECTION_STOPSEARCH = @as(u32, 468);
pub const DISPID_WMPMEDIACOLLECTION_UPDATEMETADATA = @as(u32, 469);
pub const DISPID_WMPMEDIACOLLECTION_GETMEDIAATOM = @as(u32, 470);
pub const DISPID_WMPMEDIACOLLECTION_SETDELETED = @as(u32, 471);
pub const DISPID_WMPMEDIACOLLECTION_ISDELETED = @as(u32, 472);
pub const DISPID_WMPMEDIACOLLECTION_GETBYQUERYDESCRIPTION = @as(u32, 473);
pub const DISPID_WMPMEDIACOLLECTION_FREEZECOLLECTIONCHANGE = @as(u32, 474);
pub const DISPID_WMPMEDIACOLLECTION_UNFREEZECOLLECTIONCHANGE = @as(u32, 475);
pub const DISPID_WMPMEDIACOLLECTION_POSTCOLLECTIONCHANGE = @as(u32, 476);
pub const DISPID_WMPPLAYLISTARRAY_COUNT = @as(u32, 501);
pub const DISPID_WMPPLAYLISTARRAY_ITEM = @as(u32, 502);
pub const DISPID_WMPPLAYLISTCOLLECTION_NEWPLAYLIST = @as(u32, 552);
pub const DISPID_WMPPLAYLISTCOLLECTION_GETALL = @as(u32, 553);
pub const DISPID_WMPPLAYLISTCOLLECTION_GETBYNAME = @as(u32, 554);
pub const DISPID_WMPPLAYLISTCOLLECTION_GETBYQUERYDESCRIPTION = @as(u32, 555);
pub const DISPID_WMPPLAYLISTCOLLECTION_REMOVE = @as(u32, 556);
pub const DISPID_WMPPLAYLISTCOLLECTION_NEWQUERY = @as(u32, 557);
pub const DISPID_WMPPLAYLISTCOLLECTION_STARTMONITORING = @as(u32, 558);
pub const DISPID_WMPPLAYLISTCOLLECTION_STOPMONITORING = @as(u32, 559);
pub const DISPID_WMPPLAYLISTCOLLECTION_SETDELETED = @as(u32, 560);
pub const DISPID_WMPPLAYLISTCOLLECTION_ISDELETED = @as(u32, 561);
pub const DISPID_WMPPLAYLISTCOLLECTION_IMPORTPLAYLIST = @as(u32, 562);
pub const DISPID_WMPMEDIA_SOURCEURL = @as(u32, 751);
pub const DISPID_WMPMEDIA_IMAGESOURCEWIDTH = @as(u32, 752);
pub const DISPID_WMPMEDIA_IMAGESOURCEHEIGHT = @as(u32, 753);
pub const DISPID_WMPMEDIA_MARKERCOUNT = @as(u32, 754);
pub const DISPID_WMPMEDIA_GETMARKERTIME = @as(u32, 755);
pub const DISPID_WMPMEDIA_GETMARKERNAME = @as(u32, 756);
pub const DISPID_WMPMEDIA_DURATION = @as(u32, 757);
pub const DISPID_WMPMEDIA_DURATIONSTRING = @as(u32, 758);
pub const DISPID_WMPMEDIA_ATTRIBUTECOUNT = @as(u32, 759);
pub const DISPID_WMPMEDIA_GETATTRIBUTENAME = @as(u32, 760);
pub const DISPID_WMPMEDIA_GETITEMINFO = @as(u32, 761);
pub const DISPID_WMPMEDIA_SETITEMINFO = @as(u32, 762);
pub const DISPID_WMPMEDIA_ISIDENTICAL = @as(u32, 763);
pub const DISPID_WMPMEDIA_NAME = @as(u32, 764);
pub const DISPID_WMPMEDIA_GETITEMINFOBYATOM = @as(u32, 765);
pub const DISPID_WMPMEDIA_ISMEMBEROF = @as(u32, 766);
pub const DISPID_WMPMEDIA_ISREADONLYITEM = @as(u32, 767);
pub const DISPID_WMPMEDIA2_ERROR = @as(u32, 768);
pub const DISPID_WMPMEDIA3_GETATTRIBUTECOUNTBYTYPE = @as(u32, 769);
pub const DISPID_WMPMEDIA3_GETITEMINFOBYTYPE = @as(u32, 770);
pub const DISPID_WMPNETWORK_BANDWIDTH = @as(u32, 801);
pub const DISPID_WMPNETWORK_RECOVEREDPACKETS = @as(u32, 802);
pub const DISPID_WMPNETWORK_SOURCEPROTOCOL = @as(u32, 803);
pub const DISPID_WMPNETWORK_RECEIVEDPACKETS = @as(u32, 804);
pub const DISPID_WMPNETWORK_LOSTPACKETS = @as(u32, 805);
pub const DISPID_WMPNETWORK_RECEPTIONQUALITY = @as(u32, 806);
pub const DISPID_WMPNETWORK_BUFFERINGCOUNT = @as(u32, 807);
pub const DISPID_WMPNETWORK_BUFFERINGPROGRESS = @as(u32, 808);
pub const DISPID_WMPNETWORK_BUFFERINGTIME = @as(u32, 809);
pub const DISPID_WMPNETWORK_FRAMERATE = @as(u32, 810);
pub const DISPID_WMPNETWORK_MAXBITRATE = @as(u32, 811);
pub const DISPID_WMPNETWORK_BITRATE = @as(u32, 812);
pub const DISPID_WMPNETWORK_GETPROXYSETTINGS = @as(u32, 813);
pub const DISPID_WMPNETWORK_SETPROXYSETTINGS = @as(u32, 814);
pub const DISPID_WMPNETWORK_GETPROXYNAME = @as(u32, 815);
pub const DISPID_WMPNETWORK_SETPROXYNAME = @as(u32, 816);
pub const DISPID_WMPNETWORK_GETPROXYPORT = @as(u32, 817);
pub const DISPID_WMPNETWORK_SETPROXYPORT = @as(u32, 818);
pub const DISPID_WMPNETWORK_GETPROXYEXCEPTIONLIST = @as(u32, 819);
pub const DISPID_WMPNETWORK_SETPROXYEXCEPTIONLIST = @as(u32, 820);
pub const DISPID_WMPNETWORK_GETPROXYBYPASSFORLOCAL = @as(u32, 821);
pub const DISPID_WMPNETWORK_SETPROXYBYPASSFORLOCAL = @as(u32, 822);
pub const DISPID_WMPNETWORK_MAXBANDWIDTH = @as(u32, 823);
pub const DISPID_WMPNETWORK_DOWNLOADPROGRESS = @as(u32, 824);
pub const DISPID_WMPNETWORK_ENCODEDFRAMERATE = @as(u32, 825);
pub const DISPID_WMPNETWORK_FRAMESSKIPPED = @as(u32, 826);
pub const DISPID_WMPERROR_CLEARERRORQUEUE = @as(u32, 851);
pub const DISPID_WMPERROR_ERRORCOUNT = @as(u32, 852);
pub const DISPID_WMPERROR_ITEM = @as(u32, 853);
pub const DISPID_WMPERROR_WEBHELP = @as(u32, 854);
pub const DISPID_WMPERRORITEM_ERRORCODE = @as(u32, 901);
pub const DISPID_WMPERRORITEM_ERRORDESCRIPTION = @as(u32, 902);
pub const DISPID_WMPERRORITEM_ERRORCONTEXT = @as(u32, 903);
pub const DISPID_WMPERRORITEM_REMEDY = @as(u32, 904);
pub const DISPID_WMPERRORITEM_CUSTOMURL = @as(u32, 905);
pub const DISPID_WMPERRORITEM2_CONDITION = @as(u32, 906);
pub const DISPID_WMPCLOSEDCAPTION_SAMISTYLE = @as(u32, 951);
pub const DISPID_WMPCLOSEDCAPTION_SAMILANG = @as(u32, 952);
pub const DISPID_WMPCLOSEDCAPTION_SAMIFILENAME = @as(u32, 953);
pub const DISPID_WMPCLOSEDCAPTION_CAPTIONINGID = @as(u32, 954);
pub const DISPID_WMPCLOSEDCAPTION2_GETLANGCOUNT = @as(u32, 955);
pub const DISPID_WMPCLOSEDCAPTION2_GETLANGNAME = @as(u32, 956);
pub const DISPID_WMPCLOSEDCAPTION2_GETLANGID = @as(u32, 957);
pub const DISPID_WMPCLOSEDCAPTION2_GETSTYLECOUNT = @as(u32, 958);
pub const DISPID_WMPCLOSEDCAPTION2_GETSTYLENAME = @as(u32, 959);
pub const DISPID_WMPDVD_ISAVAILABLE = @as(u32, 1001);
pub const DISPID_WMPDVD_DOMAIN = @as(u32, 1002);
pub const DISPID_WMPDVD_TOPMENU = @as(u32, 1003);
pub const DISPID_WMPDVD_TITLEMENU = @as(u32, 1004);
pub const DISPID_WMPDVD_BACK = @as(u32, 1005);
pub const DISPID_WMPDVD_RESUME = @as(u32, 1006);
pub const DISPID_WMPMETADATA_PICTURE_MIMETYPE = @as(u32, 1051);
pub const DISPID_WMPMETADATA_PICTURE_PICTURETYPE = @as(u32, 1052);
pub const DISPID_WMPMETADATA_PICTURE_DESCRIPTION = @as(u32, 1053);
pub const DISPID_WMPMETADATA_PICTURE_URL = @as(u32, 1054);
pub const DISPID_WMPMETADATA_TEXT_TEXT = @as(u32, 1055);
pub const DISPID_WMPMETADATA_TEXT_DESCRIPTION = @as(u32, 1056);
pub const DISPID_WMPPLAYERAPP_SWITCHTOPLAYERAPPLICATION = @as(u32, 1101);
pub const DISPID_WMPPLAYERAPP_SWITCHTOCONTROL = @as(u32, 1102);
pub const DISPID_WMPPLAYERAPP_PLAYERDOCKED = @as(u32, 1103);
pub const DISPID_WMPPLAYERAPP_HASDISPLAY = @as(u32, 1104);
pub const DISPID_WMPPLAYERAPP_REMOTESTATUS = @as(u32, 1105);
pub const DISPID_WMPDOWNLOADMANAGER_GETDOWNLOADCOLLECTION = @as(u32, 1151);
pub const DISPID_WMPDOWNLOADMANAGER_CREATEDOWNLOADCOLLECTION = @as(u32, 1152);
pub const DISPID_WMPDOWNLOADCOLLECTION_ID = @as(u32, 1201);
pub const DISPID_WMPDOWNLOADCOLLECTION_COUNT = @as(u32, 1202);
pub const DISPID_WMPDOWNLOADCOLLECTION_ITEM = @as(u32, 1203);
pub const DISPID_WMPDOWNLOADCOLLECTION_STARTDOWNLOAD = @as(u32, 1204);
pub const DISPID_WMPDOWNLOADCOLLECTION_REMOVEITEM = @as(u32, 1205);
pub const DISPID_WMPDOWNLOADCOLLECTION_CLEAR = @as(u32, 1206);
pub const DISPID_WMPDOWNLOADITEM_SOURCEURL = @as(u32, 1251);
pub const DISPID_WMPDOWNLOADITEM_SIZE = @as(u32, 1252);
pub const DISPID_WMPDOWNLOADITEM_TYPE = @as(u32, 1253);
pub const DISPID_WMPDOWNLOADITEM_PROGRESS = @as(u32, 1254);
pub const DISPID_WMPDOWNLOADITEM_DOWNLOADSTATE = @as(u32, 1255);
pub const DISPID_WMPDOWNLOADITEM_PAUSE = @as(u32, 1256);
pub const DISPID_WMPDOWNLOADITEM_RESUME = @as(u32, 1257);
pub const DISPID_WMPDOWNLOADITEM_CANCEL = @as(u32, 1258);
pub const DISPID_WMPDOWNLOADITEM2_GETITEMINFO = @as(u32, 1301);
pub const DISPID_WMPQUERY_ADDCONDITION = @as(u32, 1351);
pub const DISPID_WMPQUERY_BEGINNEXTGROUP = @as(u32, 1352);
pub const DISPID_WMPMEDIACOLLECTION2_CREATEQUERY = @as(u32, 1401);
pub const DISPID_WMPMEDIACOLLECTION2_GETPLAYLISTBYQUERY = @as(u32, 1402);
pub const DISPID_WMPMEDIACOLLECTION2_GETSTRINGCOLLBYQUERY = @as(u32, 1403);
pub const DISPID_WMPMEDIACOLLECTION2_GETBYATTRANDMEDIATYPE = @as(u32, 1404);
pub const DISPID_WMPSTRINGCOLLECTION2_ISIDENTICAL = @as(u32, 1451);
pub const DISPID_WMPSTRINGCOLLECTION2_GETITEMINFO = @as(u32, 1452);
pub const DISPID_WMPSTRINGCOLLECTION2_GETATTRCOUNTBYTYPE = @as(u32, 1453);
pub const DISPID_WMPSTRINGCOLLECTION2_GETITEMINFOBYTYPE = @as(u32, 1454);
pub const DISPID_WMPCORE_MIN = @as(u32, 1);
pub const DISPID_WMPCORE_MAX = @as(u32, 1454);
pub const WMPCOREEVENT_BASE = @as(u32, 5000);
pub const DISPID_WMPCOREEVENT_OPENSTATECHANGE = @as(u32, 5001);
pub const DISPID_WMPCOREEVENT_STATUSCHANGE = @as(u32, 5002);
pub const WMPCOREEVENT_CONTROL_BASE = @as(u32, 5100);
pub const DISPID_WMPCOREEVENT_PLAYSTATECHANGE = @as(u32, 5101);
pub const DISPID_WMPCOREEVENT_AUDIOLANGUAGECHANGE = @as(u32, 5102);
pub const WMPCOREEVENT_SEEK_BASE = @as(u32, 5200);
pub const DISPID_WMPCOREEVENT_ENDOFSTREAM = @as(u32, 5201);
pub const DISPID_WMPCOREEVENT_POSITIONCHANGE = @as(u32, 5202);
pub const DISPID_WMPCOREEVENT_MARKERHIT = @as(u32, 5203);
pub const DISPID_WMPCOREEVENT_DURATIONUNITCHANGE = @as(u32, 5204);
pub const WMPCOREEVENT_CONTENT_BASE = @as(u32, 5300);
pub const DISPID_WMPCOREEVENT_SCRIPTCOMMAND = @as(u32, 5301);
pub const WMPCOREEVENT_NETWORK_BASE = @as(u32, 5400);
pub const DISPID_WMPCOREEVENT_DISCONNECT = @as(u32, 5401);
pub const DISPID_WMPCOREEVENT_BUFFERING = @as(u32, 5402);
pub const DISPID_WMPCOREEVENT_NEWSTREAM = @as(u32, 5403);
pub const WMPCOREEVENT_ERROR_BASE = @as(u32, 5500);
pub const DISPID_WMPCOREEVENT_ERROR = @as(u32, 5501);
pub const WMPCOREEVENT_WARNING_BASE = @as(u32, 5600);
pub const DISPID_WMPCOREEVENT_WARNING = @as(u32, 5601);
pub const WMPCOREEVENT_CDROM_BASE = @as(u32, 5700);
pub const DISPID_WMPCOREEVENT_CDROMMEDIACHANGE = @as(u32, 5701);
pub const WMPCOREEVENT_PLAYLIST_BASE = @as(u32, 5800);
pub const DISPID_WMPCOREEVENT_PLAYLISTCHANGE = @as(u32, 5801);
pub const DISPID_WMPCOREEVENT_MEDIACHANGE = @as(u32, 5802);
pub const DISPID_WMPCOREEVENT_CURRENTMEDIAITEMAVAILABLE = @as(u32, 5803);
pub const DISPID_WMPCOREEVENT_CURRENTPLAYLISTCHANGE = @as(u32, 5804);
pub const DISPID_WMPCOREEVENT_CURRENTPLAYLISTITEMAVAILABLE = @as(u32, 5805);
pub const DISPID_WMPCOREEVENT_CURRENTITEMCHANGE = @as(u32, 5806);
pub const DISPID_WMPCOREEVENT_MEDIACOLLECTIONCHANGE = @as(u32, 5807);
pub const DISPID_WMPCOREEVENT_MEDIACOLLECTIONATTRIBUTESTRINGADDED = @as(u32, 5808);
pub const DISPID_WMPCOREEVENT_MEDIACOLLECTIONATTRIBUTESTRINGREMOVED = @as(u32, 5809);
pub const DISPID_WMPCOREEVENT_PLAYLISTCOLLECTIONCHANGE = @as(u32, 5810);
pub const DISPID_WMPCOREEVENT_PLAYLISTCOLLECTIONPLAYLISTADDED = @as(u32, 5811);
pub const DISPID_WMPCOREEVENT_PLAYLISTCOLLECTIONPLAYLISTREMOVED = @as(u32, 5812);
pub const DISPID_WMPCOREEVENT_MEDIACOLLECTIONCONTENTSCANADDEDITEM = @as(u32, 5813);
pub const DISPID_WMPCOREEVENT_MEDIACOLLECTIONCONTENTSCANPROGRESS = @as(u32, 5814);
pub const DISPID_WMPCOREEVENT_MEDIACOLLECTIONSEARCHFOUNDITEM = @as(u32, 5815);
pub const DISPID_WMPCOREEVENT_MEDIACOLLECTIONSEARCHPROGRESS = @as(u32, 5816);
pub const DISPID_WMPCOREEVENT_MEDIACOLLECTIONSEARCHCOMPLETE = @as(u32, 5817);
pub const DISPID_WMPCOREEVENT_PLAYLISTCOLLECTIONPLAYLISTSETASDELETED = @as(u32, 5818);
pub const DISPID_WMPCOREEVENT_MODECHANGE = @as(u32, 5819);
pub const DISPID_WMPCOREEVENT_MEDIACOLLECTIONATTRIBUTESTRINGCHANGED = @as(u32, 5820);
pub const DISPID_WMPCOREEVENT_MEDIAERROR = @as(u32, 5821);
pub const DISPID_WMPCOREEVENT_DOMAINCHANGE = @as(u32, 5822);
pub const DISPID_WMPCOREEVENT_OPENPLAYLISTSWITCH = @as(u32, 5823);
pub const DISPID_WMPCOREEVENT_STRINGCOLLECTIONCHANGE = @as(u32, 5824);
pub const DISPID_WMPCOREEVENT_MEDIACOLLECTIONMEDIAADDED = @as(u32, 5825);
pub const DISPID_WMPCOREEVENT_MEDIACOLLECTIONMEDIAREMOVED = @as(u32, 5826);
pub const WMPOCXEVENT_BASE = @as(u32, 6500);
pub const DISPID_WMPOCXEVENT_SWITCHEDTOPLAYERAPPLICATION = @as(u32, 6501);
pub const DISPID_WMPOCXEVENT_SWITCHEDTOCONTROL = @as(u32, 6502);
pub const DISPID_WMPOCXEVENT_PLAYERDOCKEDSTATECHANGE = @as(u32, 6503);
pub const DISPID_WMPOCXEVENT_PLAYERRECONNECT = @as(u32, 6504);
pub const DISPID_WMPOCXEVENT_CLICK = @as(u32, 6505);
pub const DISPID_WMPOCXEVENT_DOUBLECLICK = @as(u32, 6506);
pub const DISPID_WMPOCXEVENT_KEYDOWN = @as(u32, 6507);
pub const DISPID_WMPOCXEVENT_KEYPRESS = @as(u32, 6508);
pub const DISPID_WMPOCXEVENT_KEYUP = @as(u32, 6509);
pub const DISPID_WMPOCXEVENT_MOUSEDOWN = @as(u32, 6510);
pub const DISPID_WMPOCXEVENT_MOUSEMOVE = @as(u32, 6511);
pub const DISPID_WMPOCXEVENT_MOUSEUP = @as(u32, 6512);
pub const DISPID_WMPOCXEVENT_DEVICECONNECT = @as(u32, 6513);
pub const DISPID_WMPOCXEVENT_DEVICEDISCONNECT = @as(u32, 6514);
pub const DISPID_WMPOCXEVENT_DEVICESTATUSCHANGE = @as(u32, 6515);
pub const DISPID_WMPOCXEVENT_DEVICESYNCSTATECHANGE = @as(u32, 6516);
pub const DISPID_WMPOCXEVENT_DEVICESYNCERROR = @as(u32, 6517);
pub const DISPID_WMPOCXEVENT_CREATEPARTNERSHIPCOMPLETE = @as(u32, 6518);
pub const DISPID_WMPOCXEVENT_CDROMRIPSTATECHANGE = @as(u32, 6519);
pub const DISPID_WMPOCXEVENT_CDROMRIPMEDIAERROR = @as(u32, 6520);
pub const DISPID_WMPOCXEVENT_CDROMBURNSTATECHANGE = @as(u32, 6521);
pub const DISPID_WMPOCXEVENT_CDROMBURNMEDIAERROR = @as(u32, 6522);
pub const DISPID_WMPOCXEVENT_CDROMBURNERROR = @as(u32, 6523);
pub const DISPID_WMPOCXEVENT_LIBRARYCONNECT = @as(u32, 6524);
pub const DISPID_WMPOCXEVENT_LIBRARYDISCONNECT = @as(u32, 6525);
pub const DISPID_WMPOCXEVENT_FOLDERSCANSTATECHANGE = @as(u32, 6526);
pub const DISPID_WMPOCXEVENT_DEVICEESTIMATION = @as(u32, 6527);
pub const DISPID_WMPCONTROLS_BASE = @as(u32, 50);
pub const DISPID_WMPSETTINGS_BASE = @as(u32, 100);
pub const DISPID_WMPPLAYLIST_BASE = @as(u32, 200);
pub const DISPID_WMPCDROM_BASE = @as(u32, 250);
pub const DISPID_WMPCDROMCOLLECTION_BASE = @as(u32, 300);
pub const DISPID_WMPSTRINGCOLLECTION_BASE = @as(u32, 400);
pub const DISPID_WMPMEDIACOLLECTION_BASE = @as(u32, 450);
pub const DISPID_WMPPLAYLISTARRAY_BASE = @as(u32, 500);
pub const DISPID_WMPPLAYLISTCOLLECTION_BASE = @as(u32, 550);
pub const DISPID_WMPMEDIA_BASE = @as(u32, 750);
pub const DISPID_WMPNETWORK_BASE = @as(u32, 800);
pub const DISPID_WMPERROR_BASE = @as(u32, 850);
pub const DISPID_WMPERRORITEM_BASE = @as(u32, 900);
pub const DISPID_WMPCLOSEDCAPTION_BASE = @as(u32, 950);
pub const DISPID_WMPDVD_BASE = @as(u32, 1000);
pub const DISPID_WMPMETADATA_BASE = @as(u32, 1050);
pub const DISPID_WMPPLAYERAPP_BASE = @as(u32, 1100);
pub const DISPID_WMPDOWNLOADMANAGER_BASE = @as(u32, 1150);
pub const DISPID_WMPDOWNLOADCOLLECTION_BASE = @as(u32, 1200);
pub const DISPID_WMPDOWNLOADITEM_BASE = @as(u32, 1250);
pub const DISPID_WMPDOWNLOADITEM2_BASE = @as(u32, 1300);
pub const DISPID_WMPQUERY_BASE = @as(u32, 1350);
pub const DISPID_WMPMEDIACOLLECTION2_BASE = @as(u32, 1400);
pub const DISPID_WMPSTRINGCOLLECTION2_BASE = @as(u32, 1450);
pub const CLSID_WMPSkinManager = Guid.initString("b2a7fd52-301f-4348-b93a-638c6de49229");
pub const CLSID_WMPMediaPluginRegistrar = Guid.initString("5569e7f5-424b-4b93-89ca-79d17924689a");
pub const WMP_PLUGINTYPE_DSP = Guid.initString("6434baea-4954-498d-abd5-2b07123e1f04");
pub const WMP_PLUGINTYPE_DSP_OUTOFPROC = Guid.initString("ef29b174-c347-44cc-9a4f-2399118ff38c");
pub const WMP_PLUGINTYPE_RENDERING = Guid.initString("a8554541-115d-406a-a4c7-51111c330183");
pub const kfltTimedLevelMaximumFrequency = @as(f32, 22050);
pub const kfltTimedLevelMinimumFrequency = @as(f32, 20);
pub const g_szContentPartnerInfo_LoginState = "LoginState";
pub const g_szContentPartnerInfo_MediaPlayerAccountType = "MediaPlayerAccountType";
pub const g_szContentPartnerInfo_AccountType = "AccountType";
pub const g_szContentPartnerInfo_HasCachedCredentials = "HasCachedCredentials";
pub const g_szContentPartnerInfo_LicenseRefreshAdvanceWarning = "LicenseRefreshAdvanceWarning";
pub const g_szContentPartnerInfo_PurchasedTrackRequiresReDownload = "PurchasedTrackRequiresReDownload";
pub const g_szContentPartnerInfo_MaximumTrackPurchasePerPurchase = "MaximumNumberOfTracksPerPurchase";
pub const g_szContentPartnerInfo_AccountBalance = "AccountBalance";
pub const g_szContentPartnerInfo_UserName = "UserName";
pub const g_szMediaPlayerTask_Burn = "Burn";
pub const g_szMediaPlayerTask_Browse = "Browse";
pub const g_szMediaPlayerTask_Sync = "Sync";
pub const g_szItemInfo_PopupURL = "Popup";
pub const g_szItemInfo_AuthenticationSuccessURL = "AuthenticationSuccessURL";
pub const g_szItemInfo_LoginFailureURL = "LoginFailureURL";
pub const g_szItemInfo_HTMLViewURL = "HTMLViewURL";
pub const g_szItemInfo_PopupCaption = "PopupCaption";
pub const g_szItemInfo_ALTLoginURL = "ALTLoginURL";
pub const g_szItemInfo_ALTLoginCaption = "ALTLoginCaption";
pub const g_szItemInfo_ForgetPasswordURL = "ForgotPassword";
pub const g_szItemInfo_CreateAccountURL = "CreateAccount";
pub const g_szItemInfo_ArtistArtURL = "ArtistArt";
pub const g_szItemInfo_AlbumArtURL = "AlbumArt";
pub const g_szItemInfo_ListArtURL = "ListArt";
pub const g_szItemInfo_GenreArtURL = "GenreArt";
pub const g_szItemInfo_SubGenreArtURL = "SubGenreArt";
pub const g_szItemInfo_RadioArtURL = "RadioArt";
pub const g_szItemInfo_TreeListIconURL = "CPListIDIcon";
pub const g_szItemInfo_ErrorDescription = "CPErrorDescription";
pub const g_szItemInfo_ErrorURL = "CPErrorURL";
pub const g_szItemInfo_ErrorURLLinkText = "CPErrorURLLinkText";
pub const g_szUnknownLocation = "UnknownLocation";
pub const g_szRootLocation = "RootLocation";
pub const g_szFlyoutMenu = "FlyoutMenu";
pub const g_szOnlineStore = "OnlineStore";
pub const g_szVideoRecent = "VideoRecent";
pub const g_szVideoRoot = "VideoRoot";
pub const g_szCPListID = "CPListID";
pub const g_szAllCPListIDs = "AllCPListIDs";
pub const g_szCPTrackID = "CPTrackID";
pub const g_szAllCPTrackIDs = "AllCPTrackIDs";
pub const g_szCPArtistID = "CPArtistID";
pub const g_szAllCPArtistIDs = "AllCPArtistIDs";
pub const g_szCPAlbumID = "CPAlbumID";
pub const g_szAllCPAlbumIDs = "AllCPAlbumIDs";
pub const g_szCPGenreID = "CPGenreID";
pub const g_szAllCPGenreIDs = "AllCPGenreIDs";
pub const g_szCPAlbumSubGenreID = "CPAlbumSubGenreID";
pub const g_szAllCPAlbumSubGenreIDs = "AllCPAlbumSubGenreIDs";
pub const g_szReleaseDateYear = "ReleaseDateYear";
pub const g_szAllReleaseDateYears = "AllReleaseDateYears";
pub const g_szCPRadioID = "CPRadioID";
pub const g_szAllCPRadioIDs = "AllCPRadioIDs";
pub const g_szAuthor = "Author";
pub const g_szAllAuthors = "AllAuthors";
pub const g_szWMParentalRating = "WMParentalRating";
pub const g_szAllWMParentalRatings = "AllWMParentalRatings";
pub const g_szAllUserEffectiveRatingStarss = "AllUserEffectiveRatingStarss";
pub const g_szUserEffectiveRatingStars = "UserEffectiveRatingStars";
pub const g_szUserPlaylist = "UserPlaylist";
pub const g_szViewMode_Report = "ViewModeReport";
pub const g_szViewMode_Details = "ViewModeDetails";
pub const g_szViewMode_Icon = "ViewModeIcon";
pub const g_szViewMode_Tile = "ViewModeTile";
pub const g_szViewMode_OrderedList = "ViewModeOrderedList";
pub const g_szContentPrice_Unknown = "PriceUnknown";
pub const g_szContentPrice_CannotBuy = "PriceCannotBuy";
pub const g_szContentPrice_Free = "PriceFree";
pub const g_szRefreshLicensePlay = "RefreshForPlay";
pub const g_szRefreshLicenseBurn = "RefreshForBurn";
pub const g_szRefreshLicenseSync = "RefreshForSync";
pub const g_szVerifyPermissionSync = "VerifyPermissionSync";
pub const g_szStationEvent_Started = "TrackStarted";
pub const g_szStationEvent_Complete = "TrackComplete";
pub const g_szStationEvent_Skipped = "TrackSkipped";
pub const WMProfile_V40_DialUpMBR = Guid.initString("fd7f47f1-72a6-45a4-80f0-3aecefc32c07");
pub const WMProfile_V40_IntranetMBR = Guid.initString("82cd3321-a94a-4ffc-9c2b-092c10ca16e7");
pub const WMProfile_V40_2856100MBR = Guid.initString("5a1c2206-dc5e-4186-beb2-4c5a994b132e");
pub const WMProfile_V40_6VoiceAudio = Guid.initString("d508978a-11a0-4d15-b0da-acdc99d4f890");
pub const WMProfile_V40_16AMRadio = Guid.initString("0f4be81f-d57d-41e1-b2e3-2fad986bfec2");
pub const WMProfile_V40_288FMRadioMono = Guid.initString("7fa57fc8-6ea4-4645-8abf-b6e5a8f814a1");
pub const WMProfile_V40_288FMRadioStereo = Guid.initString("22fcf466-aa40-431f-a289-06d0ea1a1e40");
pub const WMProfile_V40_56DialUpStereo = Guid.initString("e8026f87-e905-4594-a3c7-00d00041d1d9");
pub const WMProfile_V40_64Audio = Guid.initString("4820b3f7-cbec-41dc-9391-78598714c8e5");
pub const WMProfile_V40_96Audio = Guid.initString("0efa0ee3-9e64-41e2-837f-3c0038f327ba");
pub const WMProfile_V40_128Audio = Guid.initString("93ddbe12-13dc-4e32-a35e-40378e34279a");
pub const WMProfile_V40_288VideoVoice = Guid.initString("bb2bc274-0eb6-4da9-b550-ecf7f2b9948f");
pub const WMProfile_V40_288VideoAudio = Guid.initString("ac617f2d-6cbe-4e84-8e9a-ce151a12a354");
pub const WMProfile_V40_288VideoWebServer = Guid.initString("abf2f00d-d555-4815-94ce-8275f3a70bfe");
pub const WMProfile_V40_56DialUpVideo = Guid.initString("e21713bb-652f-4dab-99de-71e04400270f");
pub const WMProfile_V40_56DialUpVideoWebServer = Guid.initString("b756ff10-520f-4749-a399-b780e2fc9250");
pub const WMProfile_V40_100Video = Guid.initString("8f99ddd8-6684-456b-a0a3-33e1316895f0");
pub const WMProfile_V40_250Video = Guid.initString("541841c3-9339-4f7b-9a22-b11540894e42");
pub const WMProfile_V40_512Video = Guid.initString("70440e6d-c4ef-4f84-8cd0-d5c28686e784");
pub const WMProfile_V40_1MBVideo = Guid.initString("b4482a4c-cc17-4b07-a94e-9818d5e0f13f");
pub const WMProfile_V40_3MBVideo = Guid.initString("55374ac0-309b-4396-b88f-e6e292113f28");
pub const WMProfile_V70_DialUpMBR = Guid.initString("5b16e74b-4068-45b5-b80e-7bf8c80d2c2f");
pub const WMProfile_V70_IntranetMBR = Guid.initString("045880dc-34b6-4ca9-a326-73557ed143f3");
pub const WMProfile_V70_2856100MBR = Guid.initString("07df7a25-3fe2-4a5b-8b1e-348b0721ca70");
pub const WMProfile_V70_288VideoVoice = Guid.initString("b952f38e-7dbc-4533-a9ca-b00b1c6e9800");
pub const WMProfile_V70_288VideoAudio = Guid.initString("58bba0ee-896a-4948-9953-85b736f83947");
pub const WMProfile_V70_288VideoWebServer = Guid.initString("70a32e2b-e2df-4ebd-9105-d9ca194a2d50");
pub const WMProfile_V70_56VideoWebServer = Guid.initString("def99e40-57bc-4ab3-b2d1-b6e3caf64257");
pub const WMProfile_V70_64VideoISDN = Guid.initString("c2b7a7e9-7b8e-4992-a1a1-068217a3b311");
pub const WMProfile_V70_100Video = Guid.initString("d9f3c932-5ea9-4c6d-89b4-2686e515426e");
pub const WMProfile_V70_256Video = Guid.initString("afe69b3a-403f-4a1b-8007-0e21cfb3df84");
pub const WMProfile_V70_384Video = Guid.initString("f3d45fbb-8782-44df-97c6-8678e2f9b13d");
pub const WMProfile_V70_768Video = Guid.initString("0326ebb6-f76e-4964-b0db-e729978d35ee");
pub const WMProfile_V70_1500Video = Guid.initString("0b89164a-5490-4686-9e37-5a80884e5146");
pub const WMProfile_V70_2000Video = Guid.initString("aa980124-bf10-4e4f-9afd-4329a7395cff");
pub const WMProfile_V70_700FilmContentVideo = Guid.initString("7a747920-2449-4d76-99cb-fdb0c90484d4");
pub const WMProfile_V70_1500FilmContentVideo = Guid.initString("f6a5f6df-ee3f-434c-a433-523ce55f516b");
pub const WMProfile_V70_6VoiceAudio = Guid.initString("eaba9fbf-b64f-49b3-aa0c-73fbdd150ad0");
pub const WMProfile_V70_288FMRadioMono = Guid.initString("c012a833-a03b-44a5-96dc-ed95cc65582d");
pub const WMProfile_V70_288FMRadioStereo = Guid.initString("e96d67c9-1a39-4dc4-b900-b1184dc83620");
pub const WMProfile_V70_56DialUpStereo = Guid.initString("674ee767-0949-4fac-875e-f4c9c292013b");
pub const WMProfile_V70_64AudioISDN = Guid.initString("91dea458-9d60-4212-9c59-d40919c939e4");
pub const WMProfile_V70_64Audio = Guid.initString("b29cffc6-f131-41db-b5e8-99d8b0b945f4");
pub const WMProfile_V70_96Audio = Guid.initString("a9d4b819-16cc-4a59-9f37-693dbb0302d6");
pub const WMProfile_V70_128Audio = Guid.initString("c64cf5da-df45-40d3-8027-de698d68dc66");
pub const WMProfile_V70_225VideoPDA = Guid.initString("f55ea573-4c02-42b5-9026-a8260c438a9f");
pub const WMProfile_V70_150VideoPDA = Guid.initString("0f472967-e3c6-4797-9694-f0304c5e2f17");
pub const WMProfile_V80_255VideoPDA = Guid.initString("feedbcdf-3fac-4c93-ac0d-47941ec72c0b");
pub const WMProfile_V80_150VideoPDA = Guid.initString("aee16dfa-2c14-4a2f-ad3f-a3034031784f");
pub const WMProfile_V80_28856VideoMBR = Guid.initString("d66920c4-c21f-4ec8-a0b4-95cf2bd57fc4");
pub const WMProfile_V80_100768VideoMBR = Guid.initString("5bdb5a0e-979e-47d3-9596-73b386392a55");
pub const WMProfile_V80_288100VideoMBR = Guid.initString("d8722c69-2419-4b36-b4e0-6e17b60564e5");
pub const WMProfile_V80_288Video = Guid.initString("3df678d9-1352-4186-bbf8-74f0c19b6ae2");
pub const WMProfile_V80_56Video = Guid.initString("254e8a96-2612-405c-8039-f0bf725ced7d");
pub const WMProfile_V80_100Video = Guid.initString("a2e300b4-c2d4-4fc0-b5dd-ecbd948dc0df");
pub const WMProfile_V80_256Video = Guid.initString("bbc75500-33d2-4466-b86b-122b201cc9ae");
pub const WMProfile_V80_384Video = Guid.initString("29b00c2b-09a9-48bd-ad09-cdae117d1da7");
pub const WMProfile_V80_768Video = Guid.initString("74d01102-e71a-4820-8f0d-13d2ec1e4872");
pub const WMProfile_V80_700NTSCVideo = Guid.initString("c8c2985f-e5d9-4538-9e23-9b21bf78f745");
pub const WMProfile_V80_1400NTSCVideo = Guid.initString("931d1bee-617a-4bcd-9905-ccd0786683ee");
pub const WMProfile_V80_384PALVideo = Guid.initString("9227c692-ae62-4f72-a7ea-736062d0e21e");
pub const WMProfile_V80_700PALVideo = Guid.initString("ec298949-639b-45e2-96fd-4ab32d5919c2");
pub const WMProfile_V80_288MonoAudio = Guid.initString("7ea3126d-e1ba-4716-89af-f65cee0c0c67");
pub const WMProfile_V80_288StereoAudio = Guid.initString("7e4cab5c-35dc-45bb-a7c0-19b28070d0cc");
pub const WMProfile_V80_32StereoAudio = Guid.initString("60907f9f-b352-47e5-b210-0ef1f47e9f9d");
pub const WMProfile_V80_48StereoAudio = Guid.initString("5ee06be5-492b-480a-8a8f-12f373ecf9d4");
pub const WMProfile_V80_64StereoAudio = Guid.initString("09bb5bc4-3176-457f-8dd6-3cd919123e2d");
pub const WMProfile_V80_96StereoAudio = Guid.initString("1fc81930-61f2-436f-9d33-349f2a1c0f10");
pub const WMProfile_V80_128StereoAudio = Guid.initString("407b9450-8bdc-4ee5-88b8-6f527bd941f2");
pub const WMProfile_V80_288VideoOnly = Guid.initString("8c45b4c7-4aeb-4f78-a5ec-88420b9dadef");
pub const WMProfile_V80_56VideoOnly = Guid.initString("6e2a6955-81df-4943-ba50-68a986a708f6");
pub const WMProfile_V80_FAIRVBRVideo = Guid.initString("3510a862-5850-4886-835f-d78ec6a64042");
pub const WMProfile_V80_HIGHVBRVideo = Guid.initString("0f10d9d3-3b04-4fb0-a3d3-88d4ac854acc");
pub const WMProfile_V80_BESTVBRVideo = Guid.initString("048439ba-309c-440e-9cb4-3dcca3756423");
//--------------------------------------------------------------------------------
// Section: Types (153)
//--------------------------------------------------------------------------------
const CLSID_WindowsMediaPlayer_Value = Guid.initString("6bf52a52-394a-11d3-b153-00c04f79faa6");
pub const CLSID_WindowsMediaPlayer = &CLSID_WindowsMediaPlayer_Value;
pub const WMPOpenState = enum(i32) {
Undefined = 0,
PlaylistChanging = 1,
PlaylistLocating = 2,
PlaylistConnecting = 3,
PlaylistLoading = 4,
PlaylistOpening = 5,
PlaylistOpenNoMedia = 6,
PlaylistChanged = 7,
MediaChanging = 8,
MediaLocating = 9,
MediaConnecting = 10,
MediaLoading = 11,
MediaOpening = 12,
MediaOpen = 13,
BeginCodecAcquisition = 14,
EndCodecAcquisition = 15,
BeginLicenseAcquisition = 16,
EndLicenseAcquisition = 17,
BeginIndividualization = 18,
EndIndividualization = 19,
MediaWaiting = 20,
OpeningUnknownURL = 21,
};
pub const wmposUndefined = WMPOpenState.Undefined;
pub const wmposPlaylistChanging = WMPOpenState.PlaylistChanging;
pub const wmposPlaylistLocating = WMPOpenState.PlaylistLocating;
pub const wmposPlaylistConnecting = WMPOpenState.PlaylistConnecting;
pub const wmposPlaylistLoading = WMPOpenState.PlaylistLoading;
pub const wmposPlaylistOpening = WMPOpenState.PlaylistOpening;
pub const wmposPlaylistOpenNoMedia = WMPOpenState.PlaylistOpenNoMedia;
pub const wmposPlaylistChanged = WMPOpenState.PlaylistChanged;
pub const wmposMediaChanging = WMPOpenState.MediaChanging;
pub const wmposMediaLocating = WMPOpenState.MediaLocating;
pub const wmposMediaConnecting = WMPOpenState.MediaConnecting;
pub const wmposMediaLoading = WMPOpenState.MediaLoading;
pub const wmposMediaOpening = WMPOpenState.MediaOpening;
pub const wmposMediaOpen = WMPOpenState.MediaOpen;
pub const wmposBeginCodecAcquisition = WMPOpenState.BeginCodecAcquisition;
pub const wmposEndCodecAcquisition = WMPOpenState.EndCodecAcquisition;
pub const wmposBeginLicenseAcquisition = WMPOpenState.BeginLicenseAcquisition;
pub const wmposEndLicenseAcquisition = WMPOpenState.EndLicenseAcquisition;
pub const wmposBeginIndividualization = WMPOpenState.BeginIndividualization;
pub const wmposEndIndividualization = WMPOpenState.EndIndividualization;
pub const wmposMediaWaiting = WMPOpenState.MediaWaiting;
pub const wmposOpeningUnknownURL = WMPOpenState.OpeningUnknownURL;
pub const WMPPlayState = enum(i32) {
Undefined = 0,
Stopped = 1,
Paused = 2,
Playing = 3,
ScanForward = 4,
ScanReverse = 5,
Buffering = 6,
Waiting = 7,
MediaEnded = 8,
Transitioning = 9,
Ready = 10,
Reconnecting = 11,
Last = 12,
};
pub const wmppsUndefined = WMPPlayState.Undefined;
pub const wmppsStopped = WMPPlayState.Stopped;
pub const wmppsPaused = WMPPlayState.Paused;
pub const wmppsPlaying = WMPPlayState.Playing;
pub const wmppsScanForward = WMPPlayState.ScanForward;
pub const wmppsScanReverse = WMPPlayState.ScanReverse;
pub const wmppsBuffering = WMPPlayState.Buffering;
pub const wmppsWaiting = WMPPlayState.Waiting;
pub const wmppsMediaEnded = WMPPlayState.MediaEnded;
pub const wmppsTransitioning = WMPPlayState.Transitioning;
pub const wmppsReady = WMPPlayState.Ready;
pub const wmppsReconnecting = WMPPlayState.Reconnecting;
pub const wmppsLast = WMPPlayState.Last;
pub const WMPPlaylistChangeEventType = enum(i32) {
Unknown = 0,
Clear = 1,
InfoChange = 2,
Move = 3,
Delete = 4,
Insert = 5,
Append = 6,
Private = 7,
NameChange = 8,
Morph = 9,
Sort = 10,
Last = 11,
};
pub const wmplcUnknown = WMPPlaylistChangeEventType.Unknown;
pub const wmplcClear = WMPPlaylistChangeEventType.Clear;
pub const wmplcInfoChange = WMPPlaylistChangeEventType.InfoChange;
pub const wmplcMove = WMPPlaylistChangeEventType.Move;
pub const wmplcDelete = WMPPlaylistChangeEventType.Delete;
pub const wmplcInsert = WMPPlaylistChangeEventType.Insert;
pub const wmplcAppend = WMPPlaylistChangeEventType.Append;
pub const wmplcPrivate = WMPPlaylistChangeEventType.Private;
pub const wmplcNameChange = WMPPlaylistChangeEventType.NameChange;
pub const wmplcMorph = WMPPlaylistChangeEventType.Morph;
pub const wmplcSort = WMPPlaylistChangeEventType.Sort;
pub const wmplcLast = WMPPlaylistChangeEventType.Last;
const IID_IWMPErrorItem_Value = Guid.initString("3614c646-3b3b-4de7-a81e-930e3f2127b3");
pub const IID_IWMPErrorItem = &IID_IWMPErrorItem_Value;
pub const IWMPErrorItem = extern struct {
pub const VTable = extern struct {
base: IDispatch.VTable,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_errorCode: fn(
self: *const IWMPErrorItem,
phr: ?*i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_errorDescription: fn(
self: *const IWMPErrorItem,
pbstrDescription: ?*?BSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_errorContext: fn(
self: *const IWMPErrorItem,
pvarContext: ?*VARIANT,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_remedy: fn(
self: *const IWMPErrorItem,
plRemedy: ?*i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_customUrl: fn(
self: *const IWMPErrorItem,
pbstrCustomUrl: ?*?BSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
};
vtable: *const VTable,
pub fn MethodMixin(comptime T: type) type { return struct {
pub usingnamespace IDispatch.MethodMixin(T);
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IWMPErrorItem_get_errorCode(self: *const T, phr: ?*i32) callconv(.Inline) HRESULT {
return @ptrCast(*const IWMPErrorItem.VTable, self.vtable).get_errorCode(@ptrCast(*const IWMPErrorItem, self), phr);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IWMPErrorItem_get_errorDescription(self: *const T, pbstrDescription: ?*?BSTR) callconv(.Inline) HRESULT {
return @ptrCast(*const IWMPErrorItem.VTable, self.vtable).get_errorDescription(@ptrCast(*const IWMPErrorItem, self), pbstrDescription);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IWMPErrorItem_get_errorContext(self: *const T, pvarContext: ?*VARIANT) callconv(.Inline) HRESULT {
return @ptrCast(*const IWMPErrorItem.VTable, self.vtable).get_errorContext(@ptrCast(*const IWMPErrorItem, self), pvarContext);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IWMPErrorItem_get_remedy(self: *const T, plRemedy: ?*i32) callconv(.Inline) HRESULT {
return @ptrCast(*const IWMPErrorItem.VTable, self.vtable).get_remedy(@ptrCast(*const IWMPErrorItem, self), plRemedy);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IWMPErrorItem_get_customUrl(self: *const T, pbstrCustomUrl: ?*?BSTR) callconv(.Inline) HRESULT {
return @ptrCast(*const IWMPErrorItem.VTable, self.vtable).get_customUrl(@ptrCast(*const IWMPErrorItem, self), pbstrCustomUrl);
}
};}
pub usingnamespace MethodMixin(@This());
};
const IID_IWMPError_Value = Guid.initString("a12dcf7d-14ab-4c1b-a8cd-63909f06025b");
pub const IID_IWMPError = &IID_IWMPError_Value;
pub const IWMPError = extern struct {
pub const VTable = extern struct {
base: IDispatch.VTable,
clearErrorQueue: fn(
self: *const IWMPError,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_errorCount: fn(
self: *const IWMPError,
plNumErrors: ?*i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_item: fn(
self: *const IWMPError,
dwIndex: i32,
ppErrorItem: ?*?*IWMPErrorItem,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
webHelp: fn(
self: *const IWMPError,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
};
vtable: *const VTable,
pub fn MethodMixin(comptime T: type) type { return struct {
pub usingnamespace IDispatch.MethodMixin(T);
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IWMPError_clearErrorQueue(self: *const T) callconv(.Inline) HRESULT {
return @ptrCast(*const IWMPError.VTable, self.vtable).clearErrorQueue(@ptrCast(*const IWMPError, self));
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IWMPError_get_errorCount(self: *const T, plNumErrors: ?*i32) callconv(.Inline) HRESULT {
return @ptrCast(*const IWMPError.VTable, self.vtable).get_errorCount(@ptrCast(*const IWMPError, self), plNumErrors);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IWMPError_get_item(self: *const T, dwIndex: i32, ppErrorItem: ?*?*IWMPErrorItem) callconv(.Inline) HRESULT {
return @ptrCast(*const IWMPError.VTable, self.vtable).get_item(@ptrCast(*const IWMPError, self), dwIndex, ppErrorItem);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IWMPError_webHelp(self: *const T) callconv(.Inline) HRESULT {
return @ptrCast(*const IWMPError.VTable, self.vtable).webHelp(@ptrCast(*const IWMPError, self));
}
};}
pub usingnamespace MethodMixin(@This());
};
const IID_IWMPMedia_Value = Guid.initString("94d55e95-3fac-11d3-b155-00c04f79faa6");
pub const IID_IWMPMedia = &IID_IWMPMedia_Value;
pub const IWMPMedia = extern struct {
pub const VTable = extern struct {
base: IDispatch.VTable,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_isIdentical: fn(
self: *const IWMPMedia,
pIWMPMedia: ?*IWMPMedia,
pvbool: ?*i16,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_sourceURL: fn(
self: *const IWMPMedia,
pbstrSourceURL: ?*?BSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_name: fn(
self: *const IWMPMedia,
pbstrName: ?*?BSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
put_name: fn(
self: *const IWMPMedia,
bstrName: ?BSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_imageSourceWidth: fn(
self: *const IWMPMedia,
pWidth: ?*i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_imageSourceHeight: fn(
self: *const IWMPMedia,
pHeight: ?*i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_markerCount: fn(
self: *const IWMPMedia,
pMarkerCount: ?*i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
getMarkerTime: fn(
self: *const IWMPMedia,
MarkerNum: i32,
pMarkerTime: ?*f64,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
getMarkerName: fn(
self: *const IWMPMedia,
MarkerNum: i32,
pbstrMarkerName: ?*?BSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_duration: fn(
self: *const IWMPMedia,
pDuration: ?*f64,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_durationString: fn(
self: *const IWMPMedia,
pbstrDuration: ?*?BSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_attributeCount: fn(
self: *const IWMPMedia,
plCount: ?*i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
getAttributeName: fn(
self: *const IWMPMedia,
lIndex: i32,
pbstrItemName: ?*?BSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
getItemInfo: fn(
self: *const IWMPMedia,
bstrItemName: ?BSTR,
pbstrVal: ?*?BSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
setItemInfo: fn(
self: *const IWMPMedia,
bstrItemName: ?BSTR,
bstrVal: ?BSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
getItemInfoByAtom: fn(
self: *const IWMPMedia,
lAtom: i32,
pbstrVal: ?*?BSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
isMemberOf: fn(
self: *const IWMPMedia,
pPlaylist: ?*IWMPPlaylist,
pvarfIsMemberOf: ?*i16,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
isReadOnlyItem: fn(
self: *const IWMPMedia,
bstrItemName: ?BSTR,
pvarfIsReadOnly: ?*i16,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
};
vtable: *const VTable,
pub fn MethodMixin(comptime T: type) type { return struct {
pub usingnamespace IDispatch.MethodMixin(T);
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IWMPMedia_get_isIdentical(self: *const T, pIWMPMedia: ?*IWMPMedia, pvbool: ?*i16) callconv(.Inline) HRESULT {
return @ptrCast(*const IWMPMedia.VTable, self.vtable).get_isIdentical(@ptrCast(*const IWMPMedia, self), pIWMPMedia, pvbool);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IWMPMedia_get_sourceURL(self: *const T, pbstrSourceURL: ?*?BSTR) callconv(.Inline) HRESULT {
return @ptrCast(*const IWMPMedia.VTable, self.vtable).get_sourceURL(@ptrCast(*const IWMPMedia, self), pbstrSourceURL);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IWMPMedia_get_name(self: *const T, pbstrName: ?*?BSTR) callconv(.Inline) HRESULT {
return @ptrCast(*const IWMPMedia.VTable, self.vtable).get_name(@ptrCast(*const IWMPMedia, self), pbstrName);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IWMPMedia_put_name(self: *const T, bstrName: ?BSTR) callconv(.Inline) HRESULT {
return @ptrCast(*const IWMPMedia.VTable, self.vtable).put_name(@ptrCast(*const IWMPMedia, self), bstrName);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IWMPMedia_get_imageSourceWidth(self: *const T, pWidth: ?*i32) callconv(.Inline) HRESULT {
return @ptrCast(*const IWMPMedia.VTable, self.vtable).get_imageSourceWidth(@ptrCast(*const IWMPMedia, self), pWidth);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IWMPMedia_get_imageSourceHeight(self: *const T, pHeight: ?*i32) callconv(.Inline) HRESULT {
return @ptrCast(*const IWMPMedia.VTable, self.vtable).get_imageSourceHeight(@ptrCast(*const IWMPMedia, self), pHeight);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IWMPMedia_get_markerCount(self: *const T, pMarkerCount: ?*i32) callconv(.Inline) HRESULT {
return @ptrCast(*const IWMPMedia.VTable, self.vtable).get_markerCount(@ptrCast(*const IWMPMedia, self), pMarkerCount);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IWMPMedia_getMarkerTime(self: *const T, MarkerNum: i32, pMarkerTime: ?*f64) callconv(.Inline) HRESULT {
return @ptrCast(*const IWMPMedia.VTable, self.vtable).getMarkerTime(@ptrCast(*const IWMPMedia, self), MarkerNum, pMarkerTime);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IWMPMedia_getMarkerName(self: *const T, MarkerNum: i32, pbstrMarkerName: ?*?BSTR) callconv(.Inline) HRESULT {
return @ptrCast(*const IWMPMedia.VTable, self.vtable).getMarkerName(@ptrCast(*const IWMPMedia, self), MarkerNum, pbstrMarkerName);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IWMPMedia_get_duration(self: *const T, pDuration: ?*f64) callconv(.Inline) HRESULT {
return @ptrCast(*const IWMPMedia.VTable, self.vtable).get_duration(@ptrCast(*const IWMPMedia, self), pDuration);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IWMPMedia_get_durationString(self: *const T, pbstrDuration: ?*?BSTR) callconv(.Inline) HRESULT {
return @ptrCast(*const IWMPMedia.VTable, self.vtable).get_durationString(@ptrCast(*const IWMPMedia, self), pbstrDuration);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IWMPMedia_get_attributeCount(self: *const T, plCount: ?*i32) callconv(.Inline) HRESULT {
return @ptrCast(*const IWMPMedia.VTable, self.vtable).get_attributeCount(@ptrCast(*const IWMPMedia, self), plCount);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IWMPMedia_getAttributeName(self: *const T, lIndex: i32, pbstrItemName: ?*?BSTR) callconv(.Inline) HRESULT {
return @ptrCast(*const IWMPMedia.VTable, self.vtable).getAttributeName(@ptrCast(*const IWMPMedia, self), lIndex, pbstrItemName);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IWMPMedia_getItemInfo(self: *const T, bstrItemName: ?BSTR, pbstrVal: ?*?BSTR) callconv(.Inline) HRESULT {
return @ptrCast(*const IWMPMedia.VTable, self.vtable).getItemInfo(@ptrCast(*const IWMPMedia, self), bstrItemName, pbstrVal);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IWMPMedia_setItemInfo(self: *const T, bstrItemName: ?BSTR, bstrVal: ?BSTR) callconv(.Inline) HRESULT {
return @ptrCast(*const IWMPMedia.VTable, self.vtable).setItemInfo(@ptrCast(*const IWMPMedia, self), bstrItemName, bstrVal);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IWMPMedia_getItemInfoByAtom(self: *const T, lAtom: i32, pbstrVal: ?*?BSTR) callconv(.Inline) HRESULT {
return @ptrCast(*const IWMPMedia.VTable, self.vtable).getItemInfoByAtom(@ptrCast(*const IWMPMedia, self), lAtom, pbstrVal);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IWMPMedia_isMemberOf(self: *const T, pPlaylist: ?*IWMPPlaylist, pvarfIsMemberOf: ?*i16) callconv(.Inline) HRESULT {
return @ptrCast(*const IWMPMedia.VTable, self.vtable).isMemberOf(@ptrCast(*const IWMPMedia, self), pPlaylist, pvarfIsMemberOf);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IWMPMedia_isReadOnlyItem(self: *const T, bstrItemName: ?BSTR, pvarfIsReadOnly: ?*i16) callconv(.Inline) HRESULT {
return @ptrCast(*const IWMPMedia.VTable, self.vtable).isReadOnlyItem(@ptrCast(*const IWMPMedia, self), bstrItemName, pvarfIsReadOnly);
}
};}
pub usingnamespace MethodMixin(@This());
};
const IID_IWMPControls_Value = Guid.initString("74c09e02-f828-11d2-a74b-00a0c905f36e");
pub const IID_IWMPControls = &IID_IWMPControls_Value;
pub const IWMPControls = extern struct {
pub const VTable = extern struct {
base: IDispatch.VTable,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_isAvailable: fn(
self: *const IWMPControls,
bstrItem: ?BSTR,
pIsAvailable: ?*i16,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
play: fn(
self: *const IWMPControls,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
stop: fn(
self: *const IWMPControls,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
pause: fn(
self: *const IWMPControls,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
fastForward: fn(
self: *const IWMPControls,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
fastReverse: fn(
self: *const IWMPControls,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_currentPosition: fn(
self: *const IWMPControls,
pdCurrentPosition: ?*f64,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
put_currentPosition: fn(
self: *const IWMPControls,
dCurrentPosition: f64,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_currentPositionString: fn(
self: *const IWMPControls,
pbstrCurrentPosition: ?*?BSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
next: fn(
self: *const IWMPControls,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
previous: fn(
self: *const IWMPControls,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_currentItem: fn(
self: *const IWMPControls,
ppIWMPMedia: ?*?*IWMPMedia,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
put_currentItem: fn(
self: *const IWMPControls,
pIWMPMedia: ?*IWMPMedia,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_currentMarker: fn(
self: *const IWMPControls,
plMarker: ?*i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
put_currentMarker: fn(
self: *const IWMPControls,
lMarker: i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
playItem: fn(
self: *const IWMPControls,
pIWMPMedia: ?*IWMPMedia,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
};
vtable: *const VTable,
pub fn MethodMixin(comptime T: type) type { return struct {
pub usingnamespace IDispatch.MethodMixin(T);
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IWMPControls_get_isAvailable(self: *const T, bstrItem: ?BSTR, pIsAvailable: ?*i16) callconv(.Inline) HRESULT {
return @ptrCast(*const IWMPControls.VTable, self.vtable).get_isAvailable(@ptrCast(*const IWMPControls, self), bstrItem, pIsAvailable);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IWMPControls_play(self: *const T) callconv(.Inline) HRESULT {
return @ptrCast(*const IWMPControls.VTable, self.vtable).play(@ptrCast(*const IWMPControls, self));
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IWMPControls_stop(self: *const T) callconv(.Inline) HRESULT {
return @ptrCast(*const IWMPControls.VTable, self.vtable).stop(@ptrCast(*const IWMPControls, self));
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IWMPControls_pause(self: *const T) callconv(.Inline) HRESULT {
return @ptrCast(*const IWMPControls.VTable, self.vtable).pause(@ptrCast(*const IWMPControls, self));
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IWMPControls_fastForward(self: *const T) callconv(.Inline) HRESULT {
return @ptrCast(*const IWMPControls.VTable, self.vtable).fastForward(@ptrCast(*const IWMPControls, self));
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IWMPControls_fastReverse(self: *const T) callconv(.Inline) HRESULT {
return @ptrCast(*const IWMPControls.VTable, self.vtable).fastReverse(@ptrCast(*const IWMPControls, self));
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IWMPControls_get_currentPosition(self: *const T, pdCurrentPosition: ?*f64) callconv(.Inline) HRESULT {
return @ptrCast(*const IWMPControls.VTable, self.vtable).get_currentPosition(@ptrCast(*const IWMPControls, self), pdCurrentPosition);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IWMPControls_put_currentPosition(self: *const T, dCurrentPosition: f64) callconv(.Inline) HRESULT {
return @ptrCast(*const IWMPControls.VTable, self.vtable).put_currentPosition(@ptrCast(*const IWMPControls, self), dCurrentPosition);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IWMPControls_get_currentPositionString(self: *const T, pbstrCurrentPosition: ?*?BSTR) callconv(.Inline) HRESULT {
return @ptrCast(*const IWMPControls.VTable, self.vtable).get_currentPositionString(@ptrCast(*const IWMPControls, self), pbstrCurrentPosition);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IWMPControls_next(self: *const T) callconv(.Inline) HRESULT {
return @ptrCast(*const IWMPControls.VTable, self.vtable).next(@ptrCast(*const IWMPControls, self));
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IWMPControls_previous(self: *const T) callconv(.Inline) HRESULT {
return @ptrCast(*const IWMPControls.VTable, self.vtable).previous(@ptrCast(*const IWMPControls, self));
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IWMPControls_get_currentItem(self: *const T, ppIWMPMedia: ?*?*IWMPMedia) callconv(.Inline) HRESULT {
return @ptrCast(*const IWMPControls.VTable, self.vtable).get_currentItem(@ptrCast(*const IWMPControls, self), ppIWMPMedia);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IWMPControls_put_currentItem(self: *const T, pIWMPMedia: ?*IWMPMedia) callconv(.Inline) HRESULT {
return @ptrCast(*const IWMPControls.VTable, self.vtable).put_currentItem(@ptrCast(*const IWMPControls, self), pIWMPMedia);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IWMPControls_get_currentMarker(self: *const T, plMarker: ?*i32) callconv(.Inline) HRESULT {
return @ptrCast(*const IWMPControls.VTable, self.vtable).get_currentMarker(@ptrCast(*const IWMPControls, self), plMarker);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IWMPControls_put_currentMarker(self: *const T, lMarker: i32) callconv(.Inline) HRESULT {
return @ptrCast(*const IWMPControls.VTable, self.vtable).put_currentMarker(@ptrCast(*const IWMPControls, self), lMarker);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IWMPControls_playItem(self: *const T, pIWMPMedia: ?*IWMPMedia) callconv(.Inline) HRESULT {
return @ptrCast(*const IWMPControls.VTable, self.vtable).playItem(@ptrCast(*const IWMPControls, self), pIWMPMedia);
}
};}
pub usingnamespace MethodMixin(@This());
};
const IID_IWMPSettings_Value = Guid.initString("9104d1ab-80c9-4fed-abf0-2e6417a6df14");
pub const IID_IWMPSettings = &IID_IWMPSettings_Value;
pub const IWMPSettings = extern struct {
pub const VTable = extern struct {
base: IDispatch.VTable,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_isAvailable: fn(
self: *const IWMPSettings,
bstrItem: ?BSTR,
pIsAvailable: ?*i16,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_autoStart: fn(
self: *const IWMPSettings,
pfAutoStart: ?*i16,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
put_autoStart: fn(
self: *const IWMPSettings,
fAutoStart: i16,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_baseURL: fn(
self: *const IWMPSettings,
pbstrBaseURL: ?*?BSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
put_baseURL: fn(
self: *const IWMPSettings,
bstrBaseURL: ?BSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_defaultFrame: fn(
self: *const IWMPSettings,
pbstrDefaultFrame: ?*?BSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
put_defaultFrame: fn(
self: *const IWMPSettings,
bstrDefaultFrame: ?BSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_invokeURLs: fn(
self: *const IWMPSettings,
pfInvokeURLs: ?*i16,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
put_invokeURLs: fn(
self: *const IWMPSettings,
fInvokeURLs: i16,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_mute: fn(
self: *const IWMPSettings,
pfMute: ?*i16,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
put_mute: fn(
self: *const IWMPSettings,
fMute: i16,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_playCount: fn(
self: *const IWMPSettings,
plCount: ?*i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
put_playCount: fn(
self: *const IWMPSettings,
lCount: i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_rate: fn(
self: *const IWMPSettings,
pdRate: ?*f64,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
put_rate: fn(
self: *const IWMPSettings,
dRate: f64,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_balance: fn(
self: *const IWMPSettings,
plBalance: ?*i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
put_balance: fn(
self: *const IWMPSettings,
lBalance: i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_volume: fn(
self: *const IWMPSettings,
plVolume: ?*i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
put_volume: fn(
self: *const IWMPSettings,
lVolume: i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
getMode: fn(
self: *const IWMPSettings,
bstrMode: ?BSTR,
pvarfMode: ?*i16,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
setMode: fn(
self: *const IWMPSettings,
bstrMode: ?BSTR,
varfMode: i16,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_enableErrorDialogs: fn(
self: *const IWMPSettings,
pfEnableErrorDialogs: ?*i16,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
put_enableErrorDialogs: fn(
self: *const IWMPSettings,
fEnableErrorDialogs: i16,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
};
vtable: *const VTable,
pub fn MethodMixin(comptime T: type) type { return struct {
pub usingnamespace IDispatch.MethodMixin(T);
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IWMPSettings_get_isAvailable(self: *const T, bstrItem: ?BSTR, pIsAvailable: ?*i16) callconv(.Inline) HRESULT {
return @ptrCast(*const IWMPSettings.VTable, self.vtable).get_isAvailable(@ptrCast(*const IWMPSettings, self), bstrItem, pIsAvailable);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IWMPSettings_get_autoStart(self: *const T, pfAutoStart: ?*i16) callconv(.Inline) HRESULT {
return @ptrCast(*const IWMPSettings.VTable, self.vtable).get_autoStart(@ptrCast(*const IWMPSettings, self), pfAutoStart);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IWMPSettings_put_autoStart(self: *const T, fAutoStart: i16) callconv(.Inline) HRESULT {
return @ptrCast(*const IWMPSettings.VTable, self.vtable).put_autoStart(@ptrCast(*const IWMPSettings, self), fAutoStart);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IWMPSettings_get_baseURL(self: *const T, pbstrBaseURL: ?*?BSTR) callconv(.Inline) HRESULT {
return @ptrCast(*const IWMPSettings.VTable, self.vtable).get_baseURL(@ptrCast(*const IWMPSettings, self), pbstrBaseURL);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IWMPSettings_put_baseURL(self: *const T, bstrBaseURL: ?BSTR) callconv(.Inline) HRESULT {
return @ptrCast(*const IWMPSettings.VTable, self.vtable).put_baseURL(@ptrCast(*const IWMPSettings, self), bstrBaseURL);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IWMPSettings_get_defaultFrame(self: *const T, pbstrDefaultFrame: ?*?BSTR) callconv(.Inline) HRESULT {
return @ptrCast(*const IWMPSettings.VTable, self.vtable).get_defaultFrame(@ptrCast(*const IWMPSettings, self), pbstrDefaultFrame);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IWMPSettings_put_defaultFrame(self: *const T, bstrDefaultFrame: ?BSTR) callconv(.Inline) HRESULT {
return @ptrCast(*const IWMPSettings.VTable, self.vtable).put_defaultFrame(@ptrCast(*const IWMPSettings, self), bstrDefaultFrame);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IWMPSettings_get_invokeURLs(self: *const T, pfInvokeURLs: ?*i16) callconv(.Inline) HRESULT {
return @ptrCast(*const IWMPSettings.VTable, self.vtable).get_invokeURLs(@ptrCast(*const IWMPSettings, self), pfInvokeURLs);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IWMPSettings_put_invokeURLs(self: *const T, fInvokeURLs: i16) callconv(.Inline) HRESULT {
return @ptrCast(*const IWMPSettings.VTable, self.vtable).put_invokeURLs(@ptrCast(*const IWMPSettings, self), fInvokeURLs);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IWMPSettings_get_mute(self: *const T, pfMute: ?*i16) callconv(.Inline) HRESULT {
return @ptrCast(*const IWMPSettings.VTable, self.vtable).get_mute(@ptrCast(*const IWMPSettings, self), pfMute);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IWMPSettings_put_mute(self: *const T, fMute: i16) callconv(.Inline) HRESULT {
return @ptrCast(*const IWMPSettings.VTable, self.vtable).put_mute(@ptrCast(*const IWMPSettings, self), fMute);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IWMPSettings_get_playCount(self: *const T, plCount: ?*i32) callconv(.Inline) HRESULT {
return @ptrCast(*const IWMPSettings.VTable, self.vtable).get_playCount(@ptrCast(*const IWMPSettings, self), plCount);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IWMPSettings_put_playCount(self: *const T, lCount: i32) callconv(.Inline) HRESULT {
return @ptrCast(*const IWMPSettings.VTable, self.vtable).put_playCount(@ptrCast(*const IWMPSettings, self), lCount);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IWMPSettings_get_rate(self: *const T, pdRate: ?*f64) callconv(.Inline) HRESULT {
return @ptrCast(*const IWMPSettings.VTable, self.vtable).get_rate(@ptrCast(*const IWMPSettings, self), pdRate);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IWMPSettings_put_rate(self: *const T, dRate: f64) callconv(.Inline) HRESULT {
return @ptrCast(*const IWMPSettings.VTable, self.vtable).put_rate(@ptrCast(*const IWMPSettings, self), dRate);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IWMPSettings_get_balance(self: *const T, plBalance: ?*i32) callconv(.Inline) HRESULT {
return @ptrCast(*const IWMPSettings.VTable, self.vtable).get_balance(@ptrCast(*const IWMPSettings, self), plBalance);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IWMPSettings_put_balance(self: *const T, lBalance: i32) callconv(.Inline) HRESULT {
return @ptrCast(*const IWMPSettings.VTable, self.vtable).put_balance(@ptrCast(*const IWMPSettings, self), lBalance);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IWMPSettings_get_volume(self: *const T, plVolume: ?*i32) callconv(.Inline) HRESULT {
return @ptrCast(*const IWMPSettings.VTable, self.vtable).get_volume(@ptrCast(*const IWMPSettings, self), plVolume);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IWMPSettings_put_volume(self: *const T, lVolume: i32) callconv(.Inline) HRESULT {
return @ptrCast(*const IWMPSettings.VTable, self.vtable).put_volume(@ptrCast(*const IWMPSettings, self), lVolume);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IWMPSettings_getMode(self: *const T, bstrMode: ?BSTR, pvarfMode: ?*i16) callconv(.Inline) HRESULT {
return @ptrCast(*const IWMPSettings.VTable, self.vtable).getMode(@ptrCast(*const IWMPSettings, self), bstrMode, pvarfMode);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IWMPSettings_setMode(self: *const T, bstrMode: ?BSTR, varfMode: i16) callconv(.Inline) HRESULT {
return @ptrCast(*const IWMPSettings.VTable, self.vtable).setMode(@ptrCast(*const IWMPSettings, self), bstrMode, varfMode);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IWMPSettings_get_enableErrorDialogs(self: *const T, pfEnableErrorDialogs: ?*i16) callconv(.Inline) HRESULT {
return @ptrCast(*const IWMPSettings.VTable, self.vtable).get_enableErrorDialogs(@ptrCast(*const IWMPSettings, self), pfEnableErrorDialogs);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IWMPSettings_put_enableErrorDialogs(self: *const T, fEnableErrorDialogs: i16) callconv(.Inline) HRESULT {
return @ptrCast(*const IWMPSettings.VTable, self.vtable).put_enableErrorDialogs(@ptrCast(*const IWMPSettings, self), fEnableErrorDialogs);
}
};}
pub usingnamespace MethodMixin(@This());
};
const IID_IWMPClosedCaption_Value = Guid.initString("4f2df574-c588-11d3-9ed0-00c04fb6e937");
pub const IID_IWMPClosedCaption = &IID_IWMPClosedCaption_Value;
pub const IWMPClosedCaption = extern struct {
pub const VTable = extern struct {
base: IDispatch.VTable,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_SAMIStyle: fn(
self: *const IWMPClosedCaption,
pbstrSAMIStyle: ?*?BSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
put_SAMIStyle: fn(
self: *const IWMPClosedCaption,
bstrSAMIStyle: ?BSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_SAMILang: fn(
self: *const IWMPClosedCaption,
pbstrSAMILang: ?*?BSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
put_SAMILang: fn(
self: *const IWMPClosedCaption,
bstrSAMILang: ?BSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_SAMIFileName: fn(
self: *const IWMPClosedCaption,
pbstrSAMIFileName: ?*?BSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
put_SAMIFileName: fn(
self: *const IWMPClosedCaption,
bstrSAMIFileName: ?BSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_captioningId: fn(
self: *const IWMPClosedCaption,
pbstrCaptioningID: ?*?BSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
put_captioningId: fn(
self: *const IWMPClosedCaption,
bstrCaptioningID: ?BSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
};
vtable: *const VTable,
pub fn MethodMixin(comptime T: type) type { return struct {
pub usingnamespace IDispatch.MethodMixin(T);
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IWMPClosedCaption_get_SAMIStyle(self: *const T, pbstrSAMIStyle: ?*?BSTR) callconv(.Inline) HRESULT {
return @ptrCast(*const IWMPClosedCaption.VTable, self.vtable).get_SAMIStyle(@ptrCast(*const IWMPClosedCaption, self), pbstrSAMIStyle);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IWMPClosedCaption_put_SAMIStyle(self: *const T, bstrSAMIStyle: ?BSTR) callconv(.Inline) HRESULT {
return @ptrCast(*const IWMPClosedCaption.VTable, self.vtable).put_SAMIStyle(@ptrCast(*const IWMPClosedCaption, self), bstrSAMIStyle);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IWMPClosedCaption_get_SAMILang(self: *const T, pbstrSAMILang: ?*?BSTR) callconv(.Inline) HRESULT {
return @ptrCast(*const IWMPClosedCaption.VTable, self.vtable).get_SAMILang(@ptrCast(*const IWMPClosedCaption, self), pbstrSAMILang);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IWMPClosedCaption_put_SAMILang(self: *const T, bstrSAMILang: ?BSTR) callconv(.Inline) HRESULT {
return @ptrCast(*const IWMPClosedCaption.VTable, self.vtable).put_SAMILang(@ptrCast(*const IWMPClosedCaption, self), bstrSAMILang);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IWMPClosedCaption_get_SAMIFileName(self: *const T, pbstrSAMIFileName: ?*?BSTR) callconv(.Inline) HRESULT {
return @ptrCast(*const IWMPClosedCaption.VTable, self.vtable).get_SAMIFileName(@ptrCast(*const IWMPClosedCaption, self), pbstrSAMIFileName);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IWMPClosedCaption_put_SAMIFileName(self: *const T, bstrSAMIFileName: ?BSTR) callconv(.Inline) HRESULT {
return @ptrCast(*const IWMPClosedCaption.VTable, self.vtable).put_SAMIFileName(@ptrCast(*const IWMPClosedCaption, self), bstrSAMIFileName);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IWMPClosedCaption_get_captioningId(self: *const T, pbstrCaptioningID: ?*?BSTR) callconv(.Inline) HRESULT {
return @ptrCast(*const IWMPClosedCaption.VTable, self.vtable).get_captioningId(@ptrCast(*const IWMPClosedCaption, self), pbstrCaptioningID);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IWMPClosedCaption_put_captioningId(self: *const T, bstrCaptioningID: ?BSTR) callconv(.Inline) HRESULT {
return @ptrCast(*const IWMPClosedCaption.VTable, self.vtable).put_captioningId(@ptrCast(*const IWMPClosedCaption, self), bstrCaptioningID);
}
};}
pub usingnamespace MethodMixin(@This());
};
const IID_IWMPPlaylist_Value = Guid.initString("d5f0f4f1-130c-11d3-b14e-00c04f79faa6");
pub const IID_IWMPPlaylist = &IID_IWMPPlaylist_Value;
pub const IWMPPlaylist = extern struct {
pub const VTable = extern struct {
base: IDispatch.VTable,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_count: fn(
self: *const IWMPPlaylist,
plCount: ?*i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_name: fn(
self: *const IWMPPlaylist,
pbstrName: ?*?BSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
put_name: fn(
self: *const IWMPPlaylist,
bstrName: ?BSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_attributeCount: fn(
self: *const IWMPPlaylist,
plCount: ?*i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_attributeName: fn(
self: *const IWMPPlaylist,
lIndex: i32,
pbstrAttributeName: ?*?BSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_item: fn(
self: *const IWMPPlaylist,
lIndex: i32,
ppIWMPMedia: ?*?*IWMPMedia,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
getItemInfo: fn(
self: *const IWMPPlaylist,
bstrName: ?BSTR,
pbstrVal: ?*?BSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
setItemInfo: fn(
self: *const IWMPPlaylist,
bstrName: ?BSTR,
bstrValue: ?BSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_isIdentical: fn(
self: *const IWMPPlaylist,
pIWMPPlaylist: ?*IWMPPlaylist,
pvbool: ?*i16,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
clear: fn(
self: *const IWMPPlaylist,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
insertItem: fn(
self: *const IWMPPlaylist,
lIndex: i32,
pIWMPMedia: ?*IWMPMedia,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
appendItem: fn(
self: *const IWMPPlaylist,
pIWMPMedia: ?*IWMPMedia,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
removeItem: fn(
self: *const IWMPPlaylist,
pIWMPMedia: ?*IWMPMedia,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
moveItem: fn(
self: *const IWMPPlaylist,
lIndexOld: i32,
lIndexNew: i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
};
vtable: *const VTable,
pub fn MethodMixin(comptime T: type) type { return struct {
pub usingnamespace IDispatch.MethodMixin(T);
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IWMPPlaylist_get_count(self: *const T, plCount: ?*i32) callconv(.Inline) HRESULT {
return @ptrCast(*const IWMPPlaylist.VTable, self.vtable).get_count(@ptrCast(*const IWMPPlaylist, self), plCount);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IWMPPlaylist_get_name(self: *const T, pbstrName: ?*?BSTR) callconv(.Inline) HRESULT {
return @ptrCast(*const IWMPPlaylist.VTable, self.vtable).get_name(@ptrCast(*const IWMPPlaylist, self), pbstrName);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IWMPPlaylist_put_name(self: *const T, bstrName: ?BSTR) callconv(.Inline) HRESULT {
return @ptrCast(*const IWMPPlaylist.VTable, self.vtable).put_name(@ptrCast(*const IWMPPlaylist, self), bstrName);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IWMPPlaylist_get_attributeCount(self: *const T, plCount: ?*i32) callconv(.Inline) HRESULT {
return @ptrCast(*const IWMPPlaylist.VTable, self.vtable).get_attributeCount(@ptrCast(*const IWMPPlaylist, self), plCount);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IWMPPlaylist_get_attributeName(self: *const T, lIndex: i32, pbstrAttributeName: ?*?BSTR) callconv(.Inline) HRESULT {
return @ptrCast(*const IWMPPlaylist.VTable, self.vtable).get_attributeName(@ptrCast(*const IWMPPlaylist, self), lIndex, pbstrAttributeName);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IWMPPlaylist_get_item(self: *const T, lIndex: i32, ppIWMPMedia: ?*?*IWMPMedia) callconv(.Inline) HRESULT {
return @ptrCast(*const IWMPPlaylist.VTable, self.vtable).get_item(@ptrCast(*const IWMPPlaylist, self), lIndex, ppIWMPMedia);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IWMPPlaylist_getItemInfo(self: *const T, bstrName: ?BSTR, pbstrVal: ?*?BSTR) callconv(.Inline) HRESULT {
return @ptrCast(*const IWMPPlaylist.VTable, self.vtable).getItemInfo(@ptrCast(*const IWMPPlaylist, self), bstrName, pbstrVal);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IWMPPlaylist_setItemInfo(self: *const T, bstrName: ?BSTR, bstrValue: ?BSTR) callconv(.Inline) HRESULT {
return @ptrCast(*const IWMPPlaylist.VTable, self.vtable).setItemInfo(@ptrCast(*const IWMPPlaylist, self), bstrName, bstrValue);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IWMPPlaylist_get_isIdentical(self: *const T, pIWMPPlaylist: ?*IWMPPlaylist, pvbool: ?*i16) callconv(.Inline) HRESULT {
return @ptrCast(*const IWMPPlaylist.VTable, self.vtable).get_isIdentical(@ptrCast(*const IWMPPlaylist, self), pIWMPPlaylist, pvbool);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IWMPPlaylist_clear(self: *const T) callconv(.Inline) HRESULT {
return @ptrCast(*const IWMPPlaylist.VTable, self.vtable).clear(@ptrCast(*const IWMPPlaylist, self));
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IWMPPlaylist_insertItem(self: *const T, lIndex: i32, pIWMPMedia: ?*IWMPMedia) callconv(.Inline) HRESULT {
return @ptrCast(*const IWMPPlaylist.VTable, self.vtable).insertItem(@ptrCast(*const IWMPPlaylist, self), lIndex, pIWMPMedia);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IWMPPlaylist_appendItem(self: *const T, pIWMPMedia: ?*IWMPMedia) callconv(.Inline) HRESULT {
return @ptrCast(*const IWMPPlaylist.VTable, self.vtable).appendItem(@ptrCast(*const IWMPPlaylist, self), pIWMPMedia);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IWMPPlaylist_removeItem(self: *const T, pIWMPMedia: ?*IWMPMedia) callconv(.Inline) HRESULT {
return @ptrCast(*const IWMPPlaylist.VTable, self.vtable).removeItem(@ptrCast(*const IWMPPlaylist, self), pIWMPMedia);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IWMPPlaylist_moveItem(self: *const T, lIndexOld: i32, lIndexNew: i32) callconv(.Inline) HRESULT {
return @ptrCast(*const IWMPPlaylist.VTable, self.vtable).moveItem(@ptrCast(*const IWMPPlaylist, self), lIndexOld, lIndexNew);
}
};}
pub usingnamespace MethodMixin(@This());
};
const IID_IWMPCdrom_Value = Guid.initString("cfab6e98-8730-11d3-b388-00c04f68574b");
pub const IID_IWMPCdrom = &IID_IWMPCdrom_Value;
pub const IWMPCdrom = extern struct {
pub const VTable = extern struct {
base: IDispatch.VTable,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_driveSpecifier: fn(
self: *const IWMPCdrom,
pbstrDrive: ?*?BSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_playlist: fn(
self: *const IWMPCdrom,
ppPlaylist: ?*?*IWMPPlaylist,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
eject: fn(
self: *const IWMPCdrom,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
};
vtable: *const VTable,
pub fn MethodMixin(comptime T: type) type { return struct {
pub usingnamespace IDispatch.MethodMixin(T);
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IWMPCdrom_get_driveSpecifier(self: *const T, pbstrDrive: ?*?BSTR) callconv(.Inline) HRESULT {
return @ptrCast(*const IWMPCdrom.VTable, self.vtable).get_driveSpecifier(@ptrCast(*const IWMPCdrom, self), pbstrDrive);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IWMPCdrom_get_playlist(self: *const T, ppPlaylist: ?*?*IWMPPlaylist) callconv(.Inline) HRESULT {
return @ptrCast(*const IWMPCdrom.VTable, self.vtable).get_playlist(@ptrCast(*const IWMPCdrom, self), ppPlaylist);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IWMPCdrom_eject(self: *const T) callconv(.Inline) HRESULT {
return @ptrCast(*const IWMPCdrom.VTable, self.vtable).eject(@ptrCast(*const IWMPCdrom, self));
}
};}
pub usingnamespace MethodMixin(@This());
};
const IID_IWMPCdromCollection_Value = Guid.initString("ee4c8fe2-34b2-11d3-a3bf-006097c9b344");
pub const IID_IWMPCdromCollection = &IID_IWMPCdromCollection_Value;
pub const IWMPCdromCollection = extern struct {
pub const VTable = extern struct {
base: IDispatch.VTable,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_count: fn(
self: *const IWMPCdromCollection,
plCount: ?*i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
item: fn(
self: *const IWMPCdromCollection,
lIndex: i32,
ppItem: ?*?*IWMPCdrom,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
getByDriveSpecifier: fn(
self: *const IWMPCdromCollection,
bstrDriveSpecifier: ?BSTR,
ppCdrom: ?*?*IWMPCdrom,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
};
vtable: *const VTable,
pub fn MethodMixin(comptime T: type) type { return struct {
pub usingnamespace IDispatch.MethodMixin(T);
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IWMPCdromCollection_get_count(self: *const T, plCount: ?*i32) callconv(.Inline) HRESULT {
return @ptrCast(*const IWMPCdromCollection.VTable, self.vtable).get_count(@ptrCast(*const IWMPCdromCollection, self), plCount);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IWMPCdromCollection_item(self: *const T, lIndex: i32, ppItem: ?*?*IWMPCdrom) callconv(.Inline) HRESULT {
return @ptrCast(*const IWMPCdromCollection.VTable, self.vtable).item(@ptrCast(*const IWMPCdromCollection, self), lIndex, ppItem);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IWMPCdromCollection_getByDriveSpecifier(self: *const T, bstrDriveSpecifier: ?BSTR, ppCdrom: ?*?*IWMPCdrom) callconv(.Inline) HRESULT {
return @ptrCast(*const IWMPCdromCollection.VTable, self.vtable).getByDriveSpecifier(@ptrCast(*const IWMPCdromCollection, self), bstrDriveSpecifier, ppCdrom);
}
};}
pub usingnamespace MethodMixin(@This());
};
const IID_IWMPStringCollection_Value = Guid.initString("4a976298-8c0d-11d3-b389-00c04f68574b");
pub const IID_IWMPStringCollection = &IID_IWMPStringCollection_Value;
pub const IWMPStringCollection = extern struct {
pub const VTable = extern struct {
base: IDispatch.VTable,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_count: fn(
self: *const IWMPStringCollection,
plCount: ?*i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
item: fn(
self: *const IWMPStringCollection,
lIndex: i32,
pbstrString: ?*?BSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
};
vtable: *const VTable,
pub fn MethodMixin(comptime T: type) type { return struct {
pub usingnamespace IDispatch.MethodMixin(T);
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IWMPStringCollection_get_count(self: *const T, plCount: ?*i32) callconv(.Inline) HRESULT {
return @ptrCast(*const IWMPStringCollection.VTable, self.vtable).get_count(@ptrCast(*const IWMPStringCollection, self), plCount);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IWMPStringCollection_item(self: *const T, lIndex: i32, pbstrString: ?*?BSTR) callconv(.Inline) HRESULT {
return @ptrCast(*const IWMPStringCollection.VTable, self.vtable).item(@ptrCast(*const IWMPStringCollection, self), lIndex, pbstrString);
}
};}
pub usingnamespace MethodMixin(@This());
};
const IID_IWMPMediaCollection_Value = Guid.initString("8363bc22-b4b4-4b19-989d-1cd765749dd1");
pub const IID_IWMPMediaCollection = &IID_IWMPMediaCollection_Value;
pub const IWMPMediaCollection = extern struct {
pub const VTable = extern struct {
base: IDispatch.VTable,
add: fn(
self: *const IWMPMediaCollection,
bstrURL: ?BSTR,
ppItem: ?*?*IWMPMedia,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
getAll: fn(
self: *const IWMPMediaCollection,
ppMediaItems: ?*?*IWMPPlaylist,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
getByName: fn(
self: *const IWMPMediaCollection,
bstrName: ?BSTR,
ppMediaItems: ?*?*IWMPPlaylist,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
getByGenre: fn(
self: *const IWMPMediaCollection,
bstrGenre: ?BSTR,
ppMediaItems: ?*?*IWMPPlaylist,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
getByAuthor: fn(
self: *const IWMPMediaCollection,
bstrAuthor: ?BSTR,
ppMediaItems: ?*?*IWMPPlaylist,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
getByAlbum: fn(
self: *const IWMPMediaCollection,
bstrAlbum: ?BSTR,
ppMediaItems: ?*?*IWMPPlaylist,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
getByAttribute: fn(
self: *const IWMPMediaCollection,
bstrAttribute: ?BSTR,
bstrValue: ?BSTR,
ppMediaItems: ?*?*IWMPPlaylist,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
remove: fn(
self: *const IWMPMediaCollection,
pItem: ?*IWMPMedia,
varfDeleteFile: i16,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
getAttributeStringCollection: fn(
self: *const IWMPMediaCollection,
bstrAttribute: ?BSTR,
bstrMediaType: ?BSTR,
ppStringCollection: ?*?*IWMPStringCollection,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
getMediaAtom: fn(
self: *const IWMPMediaCollection,
bstrItemName: ?BSTR,
plAtom: ?*i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
setDeleted: fn(
self: *const IWMPMediaCollection,
pItem: ?*IWMPMedia,
varfIsDeleted: i16,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
isDeleted: fn(
self: *const IWMPMediaCollection,
pItem: ?*IWMPMedia,
pvarfIsDeleted: ?*i16,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
};
vtable: *const VTable,
pub fn MethodMixin(comptime T: type) type { return struct {
pub usingnamespace IDispatch.MethodMixin(T);
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IWMPMediaCollection_add(self: *const T, bstrURL: ?BSTR, ppItem: ?*?*IWMPMedia) callconv(.Inline) HRESULT {
return @ptrCast(*const IWMPMediaCollection.VTable, self.vtable).add(@ptrCast(*const IWMPMediaCollection, self), bstrURL, ppItem);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IWMPMediaCollection_getAll(self: *const T, ppMediaItems: ?*?*IWMPPlaylist) callconv(.Inline) HRESULT {
return @ptrCast(*const IWMPMediaCollection.VTable, self.vtable).getAll(@ptrCast(*const IWMPMediaCollection, self), ppMediaItems);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IWMPMediaCollection_getByName(self: *const T, bstrName: ?BSTR, ppMediaItems: ?*?*IWMPPlaylist) callconv(.Inline) HRESULT {
return @ptrCast(*const IWMPMediaCollection.VTable, self.vtable).getByName(@ptrCast(*const IWMPMediaCollection, self), bstrName, ppMediaItems);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IWMPMediaCollection_getByGenre(self: *const T, bstrGenre: ?BSTR, ppMediaItems: ?*?*IWMPPlaylist) callconv(.Inline) HRESULT {
return @ptrCast(*const IWMPMediaCollection.VTable, self.vtable).getByGenre(@ptrCast(*const IWMPMediaCollection, self), bstrGenre, ppMediaItems);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IWMPMediaCollection_getByAuthor(self: *const T, bstrAuthor: ?BSTR, ppMediaItems: ?*?*IWMPPlaylist) callconv(.Inline) HRESULT {
return @ptrCast(*const IWMPMediaCollection.VTable, self.vtable).getByAuthor(@ptrCast(*const IWMPMediaCollection, self), bstrAuthor, ppMediaItems);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IWMPMediaCollection_getByAlbum(self: *const T, bstrAlbum: ?BSTR, ppMediaItems: ?*?*IWMPPlaylist) callconv(.Inline) HRESULT {
return @ptrCast(*const IWMPMediaCollection.VTable, self.vtable).getByAlbum(@ptrCast(*const IWMPMediaCollection, self), bstrAlbum, ppMediaItems);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IWMPMediaCollection_getByAttribute(self: *const T, bstrAttribute: ?BSTR, bstrValue: ?BSTR, ppMediaItems: ?*?*IWMPPlaylist) callconv(.Inline) HRESULT {
return @ptrCast(*const IWMPMediaCollection.VTable, self.vtable).getByAttribute(@ptrCast(*const IWMPMediaCollection, self), bstrAttribute, bstrValue, ppMediaItems);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IWMPMediaCollection_remove(self: *const T, pItem: ?*IWMPMedia, varfDeleteFile: i16) callconv(.Inline) HRESULT {
return @ptrCast(*const IWMPMediaCollection.VTable, self.vtable).remove(@ptrCast(*const IWMPMediaCollection, self), pItem, varfDeleteFile);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IWMPMediaCollection_getAttributeStringCollection(self: *const T, bstrAttribute: ?BSTR, bstrMediaType: ?BSTR, ppStringCollection: ?*?*IWMPStringCollection) callconv(.Inline) HRESULT {
return @ptrCast(*const IWMPMediaCollection.VTable, self.vtable).getAttributeStringCollection(@ptrCast(*const IWMPMediaCollection, self), bstrAttribute, bstrMediaType, ppStringCollection);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IWMPMediaCollection_getMediaAtom(self: *const T, bstrItemName: ?BSTR, plAtom: ?*i32) callconv(.Inline) HRESULT {
return @ptrCast(*const IWMPMediaCollection.VTable, self.vtable).getMediaAtom(@ptrCast(*const IWMPMediaCollection, self), bstrItemName, plAtom);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IWMPMediaCollection_setDeleted(self: *const T, pItem: ?*IWMPMedia, varfIsDeleted: i16) callconv(.Inline) HRESULT {
return @ptrCast(*const IWMPMediaCollection.VTable, self.vtable).setDeleted(@ptrCast(*const IWMPMediaCollection, self), pItem, varfIsDeleted);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IWMPMediaCollection_isDeleted(self: *const T, pItem: ?*IWMPMedia, pvarfIsDeleted: ?*i16) callconv(.Inline) HRESULT {
return @ptrCast(*const IWMPMediaCollection.VTable, self.vtable).isDeleted(@ptrCast(*const IWMPMediaCollection, self), pItem, pvarfIsDeleted);
}
};}
pub usingnamespace MethodMixin(@This());
};
const IID_IWMPPlaylistArray_Value = Guid.initString("679409c0-99f7-11d3-9fb7-00105aa620bb");
pub const IID_IWMPPlaylistArray = &IID_IWMPPlaylistArray_Value;
pub const IWMPPlaylistArray = extern struct {
pub const VTable = extern struct {
base: IDispatch.VTable,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_count: fn(
self: *const IWMPPlaylistArray,
plCount: ?*i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
item: fn(
self: *const IWMPPlaylistArray,
lIndex: i32,
ppItem: ?*?*IWMPPlaylist,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
};
vtable: *const VTable,
pub fn MethodMixin(comptime T: type) type { return struct {
pub usingnamespace IDispatch.MethodMixin(T);
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IWMPPlaylistArray_get_count(self: *const T, plCount: ?*i32) callconv(.Inline) HRESULT {
return @ptrCast(*const IWMPPlaylistArray.VTable, self.vtable).get_count(@ptrCast(*const IWMPPlaylistArray, self), plCount);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IWMPPlaylistArray_item(self: *const T, lIndex: i32, ppItem: ?*?*IWMPPlaylist) callconv(.Inline) HRESULT {
return @ptrCast(*const IWMPPlaylistArray.VTable, self.vtable).item(@ptrCast(*const IWMPPlaylistArray, self), lIndex, ppItem);
}
};}
pub usingnamespace MethodMixin(@This());
};
const IID_IWMPPlaylistCollection_Value = Guid.initString("10a13217-23a7-439b-b1c0-d847c79b7774");
pub const IID_IWMPPlaylistCollection = &IID_IWMPPlaylistCollection_Value;
pub const IWMPPlaylistCollection = extern struct {
pub const VTable = extern struct {
base: IDispatch.VTable,
newPlaylist: fn(
self: *const IWMPPlaylistCollection,
bstrName: ?BSTR,
ppItem: ?*?*IWMPPlaylist,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
getAll: fn(
self: *const IWMPPlaylistCollection,
ppPlaylistArray: ?*?*IWMPPlaylistArray,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
getByName: fn(
self: *const IWMPPlaylistCollection,
bstrName: ?BSTR,
ppPlaylistArray: ?*?*IWMPPlaylistArray,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
remove: fn(
self: *const IWMPPlaylistCollection,
pItem: ?*IWMPPlaylist,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
setDeleted: fn(
self: *const IWMPPlaylistCollection,
pItem: ?*IWMPPlaylist,
varfIsDeleted: i16,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
isDeleted: fn(
self: *const IWMPPlaylistCollection,
pItem: ?*IWMPPlaylist,
pvarfIsDeleted: ?*i16,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
importPlaylist: fn(
self: *const IWMPPlaylistCollection,
pItem: ?*IWMPPlaylist,
ppImportedItem: ?*?*IWMPPlaylist,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
};
vtable: *const VTable,
pub fn MethodMixin(comptime T: type) type { return struct {
pub usingnamespace IDispatch.MethodMixin(T);
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IWMPPlaylistCollection_newPlaylist(self: *const T, bstrName: ?BSTR, ppItem: ?*?*IWMPPlaylist) callconv(.Inline) HRESULT {
return @ptrCast(*const IWMPPlaylistCollection.VTable, self.vtable).newPlaylist(@ptrCast(*const IWMPPlaylistCollection, self), bstrName, ppItem);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IWMPPlaylistCollection_getAll(self: *const T, ppPlaylistArray: ?*?*IWMPPlaylistArray) callconv(.Inline) HRESULT {
return @ptrCast(*const IWMPPlaylistCollection.VTable, self.vtable).getAll(@ptrCast(*const IWMPPlaylistCollection, self), ppPlaylistArray);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IWMPPlaylistCollection_getByName(self: *const T, bstrName: ?BSTR, ppPlaylistArray: ?*?*IWMPPlaylistArray) callconv(.Inline) HRESULT {
return @ptrCast(*const IWMPPlaylistCollection.VTable, self.vtable).getByName(@ptrCast(*const IWMPPlaylistCollection, self), bstrName, ppPlaylistArray);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IWMPPlaylistCollection_remove(self: *const T, pItem: ?*IWMPPlaylist) callconv(.Inline) HRESULT {
return @ptrCast(*const IWMPPlaylistCollection.VTable, self.vtable).remove(@ptrCast(*const IWMPPlaylistCollection, self), pItem);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IWMPPlaylistCollection_setDeleted(self: *const T, pItem: ?*IWMPPlaylist, varfIsDeleted: i16) callconv(.Inline) HRESULT {
return @ptrCast(*const IWMPPlaylistCollection.VTable, self.vtable).setDeleted(@ptrCast(*const IWMPPlaylistCollection, self), pItem, varfIsDeleted);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IWMPPlaylistCollection_isDeleted(self: *const T, pItem: ?*IWMPPlaylist, pvarfIsDeleted: ?*i16) callconv(.Inline) HRESULT {
return @ptrCast(*const IWMPPlaylistCollection.VTable, self.vtable).isDeleted(@ptrCast(*const IWMPPlaylistCollection, self), pItem, pvarfIsDeleted);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IWMPPlaylistCollection_importPlaylist(self: *const T, pItem: ?*IWMPPlaylist, ppImportedItem: ?*?*IWMPPlaylist) callconv(.Inline) HRESULT {
return @ptrCast(*const IWMPPlaylistCollection.VTable, self.vtable).importPlaylist(@ptrCast(*const IWMPPlaylistCollection, self), pItem, ppImportedItem);
}
};}
pub usingnamespace MethodMixin(@This());
};
const IID_IWMPNetwork_Value = Guid.initString("ec21b779-edef-462d-bba4-ad9dde2b29a7");
pub const IID_IWMPNetwork = &IID_IWMPNetwork_Value;
pub const IWMPNetwork = extern struct {
pub const VTable = extern struct {
base: IDispatch.VTable,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_bandWidth: fn(
self: *const IWMPNetwork,
plBandwidth: ?*i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_recoveredPackets: fn(
self: *const IWMPNetwork,
plRecoveredPackets: ?*i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_sourceProtocol: fn(
self: *const IWMPNetwork,
pbstrSourceProtocol: ?*?BSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_receivedPackets: fn(
self: *const IWMPNetwork,
plReceivedPackets: ?*i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_lostPackets: fn(
self: *const IWMPNetwork,
plLostPackets: ?*i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_receptionQuality: fn(
self: *const IWMPNetwork,
plReceptionQuality: ?*i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_bufferingCount: fn(
self: *const IWMPNetwork,
plBufferingCount: ?*i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_bufferingProgress: fn(
self: *const IWMPNetwork,
plBufferingProgress: ?*i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_bufferingTime: fn(
self: *const IWMPNetwork,
plBufferingTime: ?*i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
put_bufferingTime: fn(
self: *const IWMPNetwork,
lBufferingTime: i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_frameRate: fn(
self: *const IWMPNetwork,
plFrameRate: ?*i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_maxBitRate: fn(
self: *const IWMPNetwork,
plBitRate: ?*i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_bitRate: fn(
self: *const IWMPNetwork,
plBitRate: ?*i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
getProxySettings: fn(
self: *const IWMPNetwork,
bstrProtocol: ?BSTR,
plProxySetting: ?*i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
setProxySettings: fn(
self: *const IWMPNetwork,
bstrProtocol: ?BSTR,
lProxySetting: i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
getProxyName: fn(
self: *const IWMPNetwork,
bstrProtocol: ?BSTR,
pbstrProxyName: ?*?BSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
setProxyName: fn(
self: *const IWMPNetwork,
bstrProtocol: ?BSTR,
bstrProxyName: ?BSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
getProxyPort: fn(
self: *const IWMPNetwork,
bstrProtocol: ?BSTR,
lProxyPort: ?*i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
setProxyPort: fn(
self: *const IWMPNetwork,
bstrProtocol: ?BSTR,
lProxyPort: i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
getProxyExceptionList: fn(
self: *const IWMPNetwork,
bstrProtocol: ?BSTR,
pbstrExceptionList: ?*?BSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
setProxyExceptionList: fn(
self: *const IWMPNetwork,
bstrProtocol: ?BSTR,
pbstrExceptionList: ?BSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
getProxyBypassForLocal: fn(
self: *const IWMPNetwork,
bstrProtocol: ?BSTR,
pfBypassForLocal: ?*i16,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
setProxyBypassForLocal: fn(
self: *const IWMPNetwork,
bstrProtocol: ?BSTR,
fBypassForLocal: i16,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_maxBandwidth: fn(
self: *const IWMPNetwork,
lMaxBandwidth: ?*i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
put_maxBandwidth: fn(
self: *const IWMPNetwork,
lMaxBandwidth: i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_downloadProgress: fn(
self: *const IWMPNetwork,
plDownloadProgress: ?*i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_encodedFrameRate: fn(
self: *const IWMPNetwork,
plFrameRate: ?*i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_framesSkipped: fn(
self: *const IWMPNetwork,
plFrames: ?*i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
};
vtable: *const VTable,
pub fn MethodMixin(comptime T: type) type { return struct {
pub usingnamespace IDispatch.MethodMixin(T);
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IWMPNetwork_get_bandWidth(self: *const T, plBandwidth: ?*i32) callconv(.Inline) HRESULT {
return @ptrCast(*const IWMPNetwork.VTable, self.vtable).get_bandWidth(@ptrCast(*const IWMPNetwork, self), plBandwidth);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IWMPNetwork_get_recoveredPackets(self: *const T, plRecoveredPackets: ?*i32) callconv(.Inline) HRESULT {
return @ptrCast(*const IWMPNetwork.VTable, self.vtable).get_recoveredPackets(@ptrCast(*const IWMPNetwork, self), plRecoveredPackets);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IWMPNetwork_get_sourceProtocol(self: *const T, pbstrSourceProtocol: ?*?BSTR) callconv(.Inline) HRESULT {
return @ptrCast(*const IWMPNetwork.VTable, self.vtable).get_sourceProtocol(@ptrCast(*const IWMPNetwork, self), pbstrSourceProtocol);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IWMPNetwork_get_receivedPackets(self: *const T, plReceivedPackets: ?*i32) callconv(.Inline) HRESULT {
return @ptrCast(*const IWMPNetwork.VTable, self.vtable).get_receivedPackets(@ptrCast(*const IWMPNetwork, self), plReceivedPackets);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IWMPNetwork_get_lostPackets(self: *const T, plLostPackets: ?*i32) callconv(.Inline) HRESULT {
return @ptrCast(*const IWMPNetwork.VTable, self.vtable).get_lostPackets(@ptrCast(*const IWMPNetwork, self), plLostPackets);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IWMPNetwork_get_receptionQuality(self: *const T, plReceptionQuality: ?*i32) callconv(.Inline) HRESULT {
return @ptrCast(*const IWMPNetwork.VTable, self.vtable).get_receptionQuality(@ptrCast(*const IWMPNetwork, self), plReceptionQuality);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IWMPNetwork_get_bufferingCount(self: *const T, plBufferingCount: ?*i32) callconv(.Inline) HRESULT {
return @ptrCast(*const IWMPNetwork.VTable, self.vtable).get_bufferingCount(@ptrCast(*const IWMPNetwork, self), plBufferingCount);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IWMPNetwork_get_bufferingProgress(self: *const T, plBufferingProgress: ?*i32) callconv(.Inline) HRESULT {
return @ptrCast(*const IWMPNetwork.VTable, self.vtable).get_bufferingProgress(@ptrCast(*const IWMPNetwork, self), plBufferingProgress);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IWMPNetwork_get_bufferingTime(self: *const T, plBufferingTime: ?*i32) callconv(.Inline) HRESULT {
return @ptrCast(*const IWMPNetwork.VTable, self.vtable).get_bufferingTime(@ptrCast(*const IWMPNetwork, self), plBufferingTime);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IWMPNetwork_put_bufferingTime(self: *const T, lBufferingTime: i32) callconv(.Inline) HRESULT {
return @ptrCast(*const IWMPNetwork.VTable, self.vtable).put_bufferingTime(@ptrCast(*const IWMPNetwork, self), lBufferingTime);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IWMPNetwork_get_frameRate(self: *const T, plFrameRate: ?*i32) callconv(.Inline) HRESULT {
return @ptrCast(*const IWMPNetwork.VTable, self.vtable).get_frameRate(@ptrCast(*const IWMPNetwork, self), plFrameRate);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IWMPNetwork_get_maxBitRate(self: *const T, plBitRate: ?*i32) callconv(.Inline) HRESULT {
return @ptrCast(*const IWMPNetwork.VTable, self.vtable).get_maxBitRate(@ptrCast(*const IWMPNetwork, self), plBitRate);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IWMPNetwork_get_bitRate(self: *const T, plBitRate: ?*i32) callconv(.Inline) HRESULT {
return @ptrCast(*const IWMPNetwork.VTable, self.vtable).get_bitRate(@ptrCast(*const IWMPNetwork, self), plBitRate);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IWMPNetwork_getProxySettings(self: *const T, bstrProtocol: ?BSTR, plProxySetting: ?*i32) callconv(.Inline) HRESULT {
return @ptrCast(*const IWMPNetwork.VTable, self.vtable).getProxySettings(@ptrCast(*const IWMPNetwork, self), bstrProtocol, plProxySetting);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IWMPNetwork_setProxySettings(self: *const T, bstrProtocol: ?BSTR, lProxySetting: i32) callconv(.Inline) HRESULT {
return @ptrCast(*const IWMPNetwork.VTable, self.vtable).setProxySettings(@ptrCast(*const IWMPNetwork, self), bstrProtocol, lProxySetting);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IWMPNetwork_getProxyName(self: *const T, bstrProtocol: ?BSTR, pbstrProxyName: ?*?BSTR) callconv(.Inline) HRESULT {
return @ptrCast(*const IWMPNetwork.VTable, self.vtable).getProxyName(@ptrCast(*const IWMPNetwork, self), bstrProtocol, pbstrProxyName);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IWMPNetwork_setProxyName(self: *const T, bstrProtocol: ?BSTR, bstrProxyName: ?BSTR) callconv(.Inline) HRESULT {
return @ptrCast(*const IWMPNetwork.VTable, self.vtable).setProxyName(@ptrCast(*const IWMPNetwork, self), bstrProtocol, bstrProxyName);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IWMPNetwork_getProxyPort(self: *const T, bstrProtocol: ?BSTR, lProxyPort: ?*i32) callconv(.Inline) HRESULT {
return @ptrCast(*const IWMPNetwork.VTable, self.vtable).getProxyPort(@ptrCast(*const IWMPNetwork, self), bstrProtocol, lProxyPort);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IWMPNetwork_setProxyPort(self: *const T, bstrProtocol: ?BSTR, lProxyPort: i32) callconv(.Inline) HRESULT {
return @ptrCast(*const IWMPNetwork.VTable, self.vtable).setProxyPort(@ptrCast(*const IWMPNetwork, self), bstrProtocol, lProxyPort);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IWMPNetwork_getProxyExceptionList(self: *const T, bstrProtocol: ?BSTR, pbstrExceptionList: ?*?BSTR) callconv(.Inline) HRESULT {
return @ptrCast(*const IWMPNetwork.VTable, self.vtable).getProxyExceptionList(@ptrCast(*const IWMPNetwork, self), bstrProtocol, pbstrExceptionList);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IWMPNetwork_setProxyExceptionList(self: *const T, bstrProtocol: ?BSTR, pbstrExceptionList: ?BSTR) callconv(.Inline) HRESULT {
return @ptrCast(*const IWMPNetwork.VTable, self.vtable).setProxyExceptionList(@ptrCast(*const IWMPNetwork, self), bstrProtocol, pbstrExceptionList);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IWMPNetwork_getProxyBypassForLocal(self: *const T, bstrProtocol: ?BSTR, pfBypassForLocal: ?*i16) callconv(.Inline) HRESULT {
return @ptrCast(*const IWMPNetwork.VTable, self.vtable).getProxyBypassForLocal(@ptrCast(*const IWMPNetwork, self), bstrProtocol, pfBypassForLocal);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IWMPNetwork_setProxyBypassForLocal(self: *const T, bstrProtocol: ?BSTR, fBypassForLocal: i16) callconv(.Inline) HRESULT {
return @ptrCast(*const IWMPNetwork.VTable, self.vtable).setProxyBypassForLocal(@ptrCast(*const IWMPNetwork, self), bstrProtocol, fBypassForLocal);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IWMPNetwork_get_maxBandwidth(self: *const T, lMaxBandwidth: ?*i32) callconv(.Inline) HRESULT {
return @ptrCast(*const IWMPNetwork.VTable, self.vtable).get_maxBandwidth(@ptrCast(*const IWMPNetwork, self), lMaxBandwidth);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IWMPNetwork_put_maxBandwidth(self: *const T, lMaxBandwidth: i32) callconv(.Inline) HRESULT {
return @ptrCast(*const IWMPNetwork.VTable, self.vtable).put_maxBandwidth(@ptrCast(*const IWMPNetwork, self), lMaxBandwidth);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IWMPNetwork_get_downloadProgress(self: *const T, plDownloadProgress: ?*i32) callconv(.Inline) HRESULT {
return @ptrCast(*const IWMPNetwork.VTable, self.vtable).get_downloadProgress(@ptrCast(*const IWMPNetwork, self), plDownloadProgress);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IWMPNetwork_get_encodedFrameRate(self: *const T, plFrameRate: ?*i32) callconv(.Inline) HRESULT {
return @ptrCast(*const IWMPNetwork.VTable, self.vtable).get_encodedFrameRate(@ptrCast(*const IWMPNetwork, self), plFrameRate);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IWMPNetwork_get_framesSkipped(self: *const T, plFrames: ?*i32) callconv(.Inline) HRESULT {
return @ptrCast(*const IWMPNetwork.VTable, self.vtable).get_framesSkipped(@ptrCast(*const IWMPNetwork, self), plFrames);
}
};}
pub usingnamespace MethodMixin(@This());
};
const IID_IWMPCore_Value = Guid.initString("d84cca99-cce2-11d2-9ecc-0000f8085981");
pub const IID_IWMPCore = &IID_IWMPCore_Value;
pub const IWMPCore = extern struct {
pub const VTable = extern struct {
base: IDispatch.VTable,
close: fn(
self: *const IWMPCore,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_URL: fn(
self: *const IWMPCore,
pbstrURL: ?*?BSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
put_URL: fn(
self: *const IWMPCore,
bstrURL: ?BSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_openState: fn(
self: *const IWMPCore,
pwmpos: ?*WMPOpenState,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_playState: fn(
self: *const IWMPCore,
pwmpps: ?*WMPPlayState,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_controls: fn(
self: *const IWMPCore,
ppControl: ?*?*IWMPControls,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_settings: fn(
self: *const IWMPCore,
ppSettings: ?*?*IWMPSettings,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_currentMedia: fn(
self: *const IWMPCore,
ppMedia: ?*?*IWMPMedia,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
put_currentMedia: fn(
self: *const IWMPCore,
pMedia: ?*IWMPMedia,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_mediaCollection: fn(
self: *const IWMPCore,
ppMediaCollection: ?*?*IWMPMediaCollection,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_playlistCollection: fn(
self: *const IWMPCore,
ppPlaylistCollection: ?*?*IWMPPlaylistCollection,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_versionInfo: fn(
self: *const IWMPCore,
pbstrVersionInfo: ?*?BSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
launchURL: fn(
self: *const IWMPCore,
bstrURL: ?BSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_network: fn(
self: *const IWMPCore,
ppQNI: ?*?*IWMPNetwork,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_currentPlaylist: fn(
self: *const IWMPCore,
ppPL: ?*?*IWMPPlaylist,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
put_currentPlaylist: fn(
self: *const IWMPCore,
pPL: ?*IWMPPlaylist,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_cdromCollection: fn(
self: *const IWMPCore,
ppCdromCollection: ?*?*IWMPCdromCollection,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_closedCaption: fn(
self: *const IWMPCore,
ppClosedCaption: ?*?*IWMPClosedCaption,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_isOnline: fn(
self: *const IWMPCore,
pfOnline: ?*i16,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_error: fn(
self: *const IWMPCore,
ppError: ?*?*IWMPError,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_status: fn(
self: *const IWMPCore,
pbstrStatus: ?*?BSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
};
vtable: *const VTable,
pub fn MethodMixin(comptime T: type) type { return struct {
pub usingnamespace IDispatch.MethodMixin(T);
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IWMPCore_close(self: *const T) callconv(.Inline) HRESULT {
return @ptrCast(*const IWMPCore.VTable, self.vtable).close(@ptrCast(*const IWMPCore, self));
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IWMPCore_get_URL(self: *const T, pbstrURL: ?*?BSTR) callconv(.Inline) HRESULT {
return @ptrCast(*const IWMPCore.VTable, self.vtable).get_URL(@ptrCast(*const IWMPCore, self), pbstrURL);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IWMPCore_put_URL(self: *const T, bstrURL: ?BSTR) callconv(.Inline) HRESULT {
return @ptrCast(*const IWMPCore.VTable, self.vtable).put_URL(@ptrCast(*const IWMPCore, self), bstrURL);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IWMPCore_get_openState(self: *const T, pwmpos: ?*WMPOpenState) callconv(.Inline) HRESULT {
return @ptrCast(*const IWMPCore.VTable, self.vtable).get_openState(@ptrCast(*const IWMPCore, self), pwmpos);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IWMPCore_get_playState(self: *const T, pwmpps: ?*WMPPlayState) callconv(.Inline) HRESULT {
return @ptrCast(*const IWMPCore.VTable, self.vtable).get_playState(@ptrCast(*const IWMPCore, self), pwmpps);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IWMPCore_get_controls(self: *const T, ppControl: ?*?*IWMPControls) callconv(.Inline) HRESULT {
return @ptrCast(*const IWMPCore.VTable, self.vtable).get_controls(@ptrCast(*const IWMPCore, self), ppControl);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IWMPCore_get_settings(self: *const T, ppSettings: ?*?*IWMPSettings) callconv(.Inline) HRESULT {
return @ptrCast(*const IWMPCore.VTable, self.vtable).get_settings(@ptrCast(*const IWMPCore, self), ppSettings);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IWMPCore_get_currentMedia(self: *const T, ppMedia: ?*?*IWMPMedia) callconv(.Inline) HRESULT {
return @ptrCast(*const IWMPCore.VTable, self.vtable).get_currentMedia(@ptrCast(*const IWMPCore, self), ppMedia);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IWMPCore_put_currentMedia(self: *const T, pMedia: ?*IWMPMedia) callconv(.Inline) HRESULT {
return @ptrCast(*const IWMPCore.VTable, self.vtable).put_currentMedia(@ptrCast(*const IWMPCore, self), pMedia);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IWMPCore_get_mediaCollection(self: *const T, ppMediaCollection: ?*?*IWMPMediaCollection) callconv(.Inline) HRESULT {
return @ptrCast(*const IWMPCore.VTable, self.vtable).get_mediaCollection(@ptrCast(*const IWMPCore, self), ppMediaCollection);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IWMPCore_get_playlistCollection(self: *const T, ppPlaylistCollection: ?*?*IWMPPlaylistCollection) callconv(.Inline) HRESULT {
return @ptrCast(*const IWMPCore.VTable, self.vtable).get_playlistCollection(@ptrCast(*const IWMPCore, self), ppPlaylistCollection);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IWMPCore_get_versionInfo(self: *const T, pbstrVersionInfo: ?*?BSTR) callconv(.Inline) HRESULT {
return @ptrCast(*const IWMPCore.VTable, self.vtable).get_versionInfo(@ptrCast(*const IWMPCore, self), pbstrVersionInfo);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IWMPCore_launchURL(self: *const T, bstrURL: ?BSTR) callconv(.Inline) HRESULT {
return @ptrCast(*const IWMPCore.VTable, self.vtable).launchURL(@ptrCast(*const IWMPCore, self), bstrURL);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IWMPCore_get_network(self: *const T, ppQNI: ?*?*IWMPNetwork) callconv(.Inline) HRESULT {
return @ptrCast(*const IWMPCore.VTable, self.vtable).get_network(@ptrCast(*const IWMPCore, self), ppQNI);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IWMPCore_get_currentPlaylist(self: *const T, ppPL: ?*?*IWMPPlaylist) callconv(.Inline) HRESULT {
return @ptrCast(*const IWMPCore.VTable, self.vtable).get_currentPlaylist(@ptrCast(*const IWMPCore, self), ppPL);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IWMPCore_put_currentPlaylist(self: *const T, pPL: ?*IWMPPlaylist) callconv(.Inline) HRESULT {
return @ptrCast(*const IWMPCore.VTable, self.vtable).put_currentPlaylist(@ptrCast(*const IWMPCore, self), pPL);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IWMPCore_get_cdromCollection(self: *const T, ppCdromCollection: ?*?*IWMPCdromCollection) callconv(.Inline) HRESULT {
return @ptrCast(*const IWMPCore.VTable, self.vtable).get_cdromCollection(@ptrCast(*const IWMPCore, self), ppCdromCollection);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IWMPCore_get_closedCaption(self: *const T, ppClosedCaption: ?*?*IWMPClosedCaption) callconv(.Inline) HRESULT {
return @ptrCast(*const IWMPCore.VTable, self.vtable).get_closedCaption(@ptrCast(*const IWMPCore, self), ppClosedCaption);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IWMPCore_get_isOnline(self: *const T, pfOnline: ?*i16) callconv(.Inline) HRESULT {
return @ptrCast(*const IWMPCore.VTable, self.vtable).get_isOnline(@ptrCast(*const IWMPCore, self), pfOnline);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IWMPCore_get_error(self: *const T, ppError: ?*?*IWMPError) callconv(.Inline) HRESULT {
return @ptrCast(*const IWMPCore.VTable, self.vtable).get_error(@ptrCast(*const IWMPCore, self), ppError);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IWMPCore_get_status(self: *const T, pbstrStatus: ?*?BSTR) callconv(.Inline) HRESULT {
return @ptrCast(*const IWMPCore.VTable, self.vtable).get_status(@ptrCast(*const IWMPCore, self), pbstrStatus);
}
};}
pub usingnamespace MethodMixin(@This());
};
const IID_IWMPPlayer_Value = Guid.initString("6bf52a4f-394a-11d3-b153-00c04f79faa6");
pub const IID_IWMPPlayer = &IID_IWMPPlayer_Value;
pub const IWMPPlayer = extern struct {
pub const VTable = extern struct {
base: IWMPCore.VTable,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_enabled: fn(
self: *const IWMPPlayer,
pbEnabled: ?*i16,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
put_enabled: fn(
self: *const IWMPPlayer,
bEnabled: i16,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_fullScreen: fn(
self: *const IWMPPlayer,
pbFullScreen: ?*i16,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
put_fullScreen: fn(
self: *const IWMPPlayer,
bFullScreen: i16,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_enableContextMenu: fn(
self: *const IWMPPlayer,
pbEnableContextMenu: ?*i16,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
put_enableContextMenu: fn(
self: *const IWMPPlayer,
bEnableContextMenu: i16,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
put_uiMode: fn(
self: *const IWMPPlayer,
bstrMode: ?BSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_uiMode: fn(
self: *const IWMPPlayer,
pbstrMode: ?*?BSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
};
vtable: *const VTable,
pub fn MethodMixin(comptime T: type) type { return struct {
pub usingnamespace IWMPCore.MethodMixin(T);
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IWMPPlayer_get_enabled(self: *const T, pbEnabled: ?*i16) callconv(.Inline) HRESULT {
return @ptrCast(*const IWMPPlayer.VTable, self.vtable).get_enabled(@ptrCast(*const IWMPPlayer, self), pbEnabled);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IWMPPlayer_put_enabled(self: *const T, bEnabled: i16) callconv(.Inline) HRESULT {
return @ptrCast(*const IWMPPlayer.VTable, self.vtable).put_enabled(@ptrCast(*const IWMPPlayer, self), bEnabled);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IWMPPlayer_get_fullScreen(self: *const T, pbFullScreen: ?*i16) callconv(.Inline) HRESULT {
return @ptrCast(*const IWMPPlayer.VTable, self.vtable).get_fullScreen(@ptrCast(*const IWMPPlayer, self), pbFullScreen);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IWMPPlayer_put_fullScreen(self: *const T, bFullScreen: i16) callconv(.Inline) HRESULT {
return @ptrCast(*const IWMPPlayer.VTable, self.vtable).put_fullScreen(@ptrCast(*const IWMPPlayer, self), bFullScreen);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IWMPPlayer_get_enableContextMenu(self: *const T, pbEnableContextMenu: ?*i16) callconv(.Inline) HRESULT {
return @ptrCast(*const IWMPPlayer.VTable, self.vtable).get_enableContextMenu(@ptrCast(*const IWMPPlayer, self), pbEnableContextMenu);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IWMPPlayer_put_enableContextMenu(self: *const T, bEnableContextMenu: i16) callconv(.Inline) HRESULT {
return @ptrCast(*const IWMPPlayer.VTable, self.vtable).put_enableContextMenu(@ptrCast(*const IWMPPlayer, self), bEnableContextMenu);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IWMPPlayer_put_uiMode(self: *const T, bstrMode: ?BSTR) callconv(.Inline) HRESULT {
return @ptrCast(*const IWMPPlayer.VTable, self.vtable).put_uiMode(@ptrCast(*const IWMPPlayer, self), bstrMode);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IWMPPlayer_get_uiMode(self: *const T, pbstrMode: ?*?BSTR) callconv(.Inline) HRESULT {
return @ptrCast(*const IWMPPlayer.VTable, self.vtable).get_uiMode(@ptrCast(*const IWMPPlayer, self), pbstrMode);
}
};}
pub usingnamespace MethodMixin(@This());
};
const IID_IWMPPlayer2_Value = Guid.initString("0e6b01d1-d407-4c85-bf5f-1c01f6150280");
pub const IID_IWMPPlayer2 = &IID_IWMPPlayer2_Value;
pub const IWMPPlayer2 = extern struct {
pub const VTable = extern struct {
base: IWMPCore.VTable,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_enabled: fn(
self: *const IWMPPlayer2,
pbEnabled: ?*i16,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
put_enabled: fn(
self: *const IWMPPlayer2,
bEnabled: i16,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_fullScreen: fn(
self: *const IWMPPlayer2,
pbFullScreen: ?*i16,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
put_fullScreen: fn(
self: *const IWMPPlayer2,
bFullScreen: i16,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_enableContextMenu: fn(
self: *const IWMPPlayer2,
pbEnableContextMenu: ?*i16,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
put_enableContextMenu: fn(
self: *const IWMPPlayer2,
bEnableContextMenu: i16,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
put_uiMode: fn(
self: *const IWMPPlayer2,
bstrMode: ?BSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_uiMode: fn(
self: *const IWMPPlayer2,
pbstrMode: ?*?BSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_stretchToFit: fn(
self: *const IWMPPlayer2,
pbEnabled: ?*i16,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
put_stretchToFit: fn(
self: *const IWMPPlayer2,
bEnabled: i16,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_windowlessVideo: fn(
self: *const IWMPPlayer2,
pbEnabled: ?*i16,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
put_windowlessVideo: fn(
self: *const IWMPPlayer2,
bEnabled: i16,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
};
vtable: *const VTable,
pub fn MethodMixin(comptime T: type) type { return struct {
pub usingnamespace IWMPCore.MethodMixin(T);
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IWMPPlayer2_get_enabled(self: *const T, pbEnabled: ?*i16) callconv(.Inline) HRESULT {
return @ptrCast(*const IWMPPlayer2.VTable, self.vtable).get_enabled(@ptrCast(*const IWMPPlayer2, self), pbEnabled);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IWMPPlayer2_put_enabled(self: *const T, bEnabled: i16) callconv(.Inline) HRESULT {
return @ptrCast(*const IWMPPlayer2.VTable, self.vtable).put_enabled(@ptrCast(*const IWMPPlayer2, self), bEnabled);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IWMPPlayer2_get_fullScreen(self: *const T, pbFullScreen: ?*i16) callconv(.Inline) HRESULT {
return @ptrCast(*const IWMPPlayer2.VTable, self.vtable).get_fullScreen(@ptrCast(*const IWMPPlayer2, self), pbFullScreen);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IWMPPlayer2_put_fullScreen(self: *const T, bFullScreen: i16) callconv(.Inline) HRESULT {
return @ptrCast(*const IWMPPlayer2.VTable, self.vtable).put_fullScreen(@ptrCast(*const IWMPPlayer2, self), bFullScreen);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IWMPPlayer2_get_enableContextMenu(self: *const T, pbEnableContextMenu: ?*i16) callconv(.Inline) HRESULT {
return @ptrCast(*const IWMPPlayer2.VTable, self.vtable).get_enableContextMenu(@ptrCast(*const IWMPPlayer2, self), pbEnableContextMenu);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IWMPPlayer2_put_enableContextMenu(self: *const T, bEnableContextMenu: i16) callconv(.Inline) HRESULT {
return @ptrCast(*const IWMPPlayer2.VTable, self.vtable).put_enableContextMenu(@ptrCast(*const IWMPPlayer2, self), bEnableContextMenu);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IWMPPlayer2_put_uiMode(self: *const T, bstrMode: ?BSTR) callconv(.Inline) HRESULT {
return @ptrCast(*const IWMPPlayer2.VTable, self.vtable).put_uiMode(@ptrCast(*const IWMPPlayer2, self), bstrMode);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IWMPPlayer2_get_uiMode(self: *const T, pbstrMode: ?*?BSTR) callconv(.Inline) HRESULT {
return @ptrCast(*const IWMPPlayer2.VTable, self.vtable).get_uiMode(@ptrCast(*const IWMPPlayer2, self), pbstrMode);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IWMPPlayer2_get_stretchToFit(self: *const T, pbEnabled: ?*i16) callconv(.Inline) HRESULT {
return @ptrCast(*const IWMPPlayer2.VTable, self.vtable).get_stretchToFit(@ptrCast(*const IWMPPlayer2, self), pbEnabled);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IWMPPlayer2_put_stretchToFit(self: *const T, bEnabled: i16) callconv(.Inline) HRESULT {
return @ptrCast(*const IWMPPlayer2.VTable, self.vtable).put_stretchToFit(@ptrCast(*const IWMPPlayer2, self), bEnabled);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IWMPPlayer2_get_windowlessVideo(self: *const T, pbEnabled: ?*i16) callconv(.Inline) HRESULT {
return @ptrCast(*const IWMPPlayer2.VTable, self.vtable).get_windowlessVideo(@ptrCast(*const IWMPPlayer2, self), pbEnabled);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IWMPPlayer2_put_windowlessVideo(self: *const T, bEnabled: i16) callconv(.Inline) HRESULT {
return @ptrCast(*const IWMPPlayer2.VTable, self.vtable).put_windowlessVideo(@ptrCast(*const IWMPPlayer2, self), bEnabled);
}
};}
pub usingnamespace MethodMixin(@This());
};
const IID_IWMPMedia2_Value = Guid.initString("ab7c88bb-143e-4ea4-acc3-e4350b2106c3");
pub const IID_IWMPMedia2 = &IID_IWMPMedia2_Value;
pub const IWMPMedia2 = extern struct {
pub const VTable = extern struct {
base: IWMPMedia.VTable,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_error: fn(
self: *const IWMPMedia2,
ppIWMPErrorItem: ?*?*IWMPErrorItem,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
};
vtable: *const VTable,
pub fn MethodMixin(comptime T: type) type { return struct {
pub usingnamespace IWMPMedia.MethodMixin(T);
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IWMPMedia2_get_error(self: *const T, ppIWMPErrorItem: ?*?*IWMPErrorItem) callconv(.Inline) HRESULT {
return @ptrCast(*const IWMPMedia2.VTable, self.vtable).get_error(@ptrCast(*const IWMPMedia2, self), ppIWMPErrorItem);
}
};}
pub usingnamespace MethodMixin(@This());
};
const IID_IWMPControls2_Value = Guid.initString("6f030d25-0890-480f-9775-1f7e40ab5b8e");
pub const IID_IWMPControls2 = &IID_IWMPControls2_Value;
pub const IWMPControls2 = extern struct {
pub const VTable = extern struct {
base: IWMPControls.VTable,
step: fn(
self: *const IWMPControls2,
lStep: i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
};
vtable: *const VTable,
pub fn MethodMixin(comptime T: type) type { return struct {
pub usingnamespace IWMPControls.MethodMixin(T);
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IWMPControls2_step(self: *const T, lStep: i32) callconv(.Inline) HRESULT {
return @ptrCast(*const IWMPControls2.VTable, self.vtable).step(@ptrCast(*const IWMPControls2, self), lStep);
}
};}
pub usingnamespace MethodMixin(@This());
};
const IID_IWMPDVD_Value = Guid.initString("8da61686-4668-4a5c-ae5d-803193293dbe");
pub const IID_IWMPDVD = &IID_IWMPDVD_Value;
pub const IWMPDVD = extern struct {
pub const VTable = extern struct {
base: IDispatch.VTable,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_isAvailable: fn(
self: *const IWMPDVD,
bstrItem: ?BSTR,
pIsAvailable: ?*i16,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_domain: fn(
self: *const IWMPDVD,
strDomain: ?*?BSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
topMenu: fn(
self: *const IWMPDVD,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
titleMenu: fn(
self: *const IWMPDVD,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
back: fn(
self: *const IWMPDVD,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
@"resume": fn(
self: *const IWMPDVD,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
};
vtable: *const VTable,
pub fn MethodMixin(comptime T: type) type { return struct {
pub usingnamespace IDispatch.MethodMixin(T);
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IWMPDVD_get_isAvailable(self: *const T, bstrItem: ?BSTR, pIsAvailable: ?*i16) callconv(.Inline) HRESULT {
return @ptrCast(*const IWMPDVD.VTable, self.vtable).get_isAvailable(@ptrCast(*const IWMPDVD, self), bstrItem, pIsAvailable);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IWMPDVD_get_domain(self: *const T, strDomain: ?*?BSTR) callconv(.Inline) HRESULT {
return @ptrCast(*const IWMPDVD.VTable, self.vtable).get_domain(@ptrCast(*const IWMPDVD, self), strDomain);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IWMPDVD_topMenu(self: *const T) callconv(.Inline) HRESULT {
return @ptrCast(*const IWMPDVD.VTable, self.vtable).topMenu(@ptrCast(*const IWMPDVD, self));
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IWMPDVD_titleMenu(self: *const T) callconv(.Inline) HRESULT {
return @ptrCast(*const IWMPDVD.VTable, self.vtable).titleMenu(@ptrCast(*const IWMPDVD, self));
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IWMPDVD_back(self: *const T) callconv(.Inline) HRESULT {
return @ptrCast(*const IWMPDVD.VTable, self.vtable).back(@ptrCast(*const IWMPDVD, self));
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IWMPDVD_resume(self: *const T) callconv(.Inline) HRESULT {
return @ptrCast(*const IWMPDVD.VTable, self.vtable).@"resume"(@ptrCast(*const IWMPDVD, self));
}
};}
pub usingnamespace MethodMixin(@This());
};
const IID_IWMPCore2_Value = Guid.initString("bc17e5b7-7561-4c18-bb90-17d485775659");
pub const IID_IWMPCore2 = &IID_IWMPCore2_Value;
pub const IWMPCore2 = extern struct {
pub const VTable = extern struct {
base: IWMPCore.VTable,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_dvd: fn(
self: *const IWMPCore2,
ppDVD: ?*?*IWMPDVD,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
};
vtable: *const VTable,
pub fn MethodMixin(comptime T: type) type { return struct {
pub usingnamespace IWMPCore.MethodMixin(T);
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IWMPCore2_get_dvd(self: *const T, ppDVD: ?*?*IWMPDVD) callconv(.Inline) HRESULT {
return @ptrCast(*const IWMPCore2.VTable, self.vtable).get_dvd(@ptrCast(*const IWMPCore2, self), ppDVD);
}
};}
pub usingnamespace MethodMixin(@This());
};
const IID_IWMPPlayer3_Value = Guid.initString("54062b68-052a-4c25-a39f-8b63346511d4");
pub const IID_IWMPPlayer3 = &IID_IWMPPlayer3_Value;
pub const IWMPPlayer3 = extern struct {
pub const VTable = extern struct {
base: IWMPCore2.VTable,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_enabled: fn(
self: *const IWMPPlayer3,
pbEnabled: ?*i16,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
put_enabled: fn(
self: *const IWMPPlayer3,
bEnabled: i16,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_fullScreen: fn(
self: *const IWMPPlayer3,
pbFullScreen: ?*i16,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
put_fullScreen: fn(
self: *const IWMPPlayer3,
bFullScreen: i16,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_enableContextMenu: fn(
self: *const IWMPPlayer3,
pbEnableContextMenu: ?*i16,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
put_enableContextMenu: fn(
self: *const IWMPPlayer3,
bEnableContextMenu: i16,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
put_uiMode: fn(
self: *const IWMPPlayer3,
bstrMode: ?BSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_uiMode: fn(
self: *const IWMPPlayer3,
pbstrMode: ?*?BSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_stretchToFit: fn(
self: *const IWMPPlayer3,
pbEnabled: ?*i16,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
put_stretchToFit: fn(
self: *const IWMPPlayer3,
bEnabled: i16,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_windowlessVideo: fn(
self: *const IWMPPlayer3,
pbEnabled: ?*i16,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
put_windowlessVideo: fn(
self: *const IWMPPlayer3,
bEnabled: i16,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
};
vtable: *const VTable,
pub fn MethodMixin(comptime T: type) type { return struct {
pub usingnamespace IWMPCore2.MethodMixin(T);
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IWMPPlayer3_get_enabled(self: *const T, pbEnabled: ?*i16) callconv(.Inline) HRESULT {
return @ptrCast(*const IWMPPlayer3.VTable, self.vtable).get_enabled(@ptrCast(*const IWMPPlayer3, self), pbEnabled);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IWMPPlayer3_put_enabled(self: *const T, bEnabled: i16) callconv(.Inline) HRESULT {
return @ptrCast(*const IWMPPlayer3.VTable, self.vtable).put_enabled(@ptrCast(*const IWMPPlayer3, self), bEnabled);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IWMPPlayer3_get_fullScreen(self: *const T, pbFullScreen: ?*i16) callconv(.Inline) HRESULT {
return @ptrCast(*const IWMPPlayer3.VTable, self.vtable).get_fullScreen(@ptrCast(*const IWMPPlayer3, self), pbFullScreen);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IWMPPlayer3_put_fullScreen(self: *const T, bFullScreen: i16) callconv(.Inline) HRESULT {
return @ptrCast(*const IWMPPlayer3.VTable, self.vtable).put_fullScreen(@ptrCast(*const IWMPPlayer3, self), bFullScreen);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IWMPPlayer3_get_enableContextMenu(self: *const T, pbEnableContextMenu: ?*i16) callconv(.Inline) HRESULT {
return @ptrCast(*const IWMPPlayer3.VTable, self.vtable).get_enableContextMenu(@ptrCast(*const IWMPPlayer3, self), pbEnableContextMenu);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IWMPPlayer3_put_enableContextMenu(self: *const T, bEnableContextMenu: i16) callconv(.Inline) HRESULT {
return @ptrCast(*const IWMPPlayer3.VTable, self.vtable).put_enableContextMenu(@ptrCast(*const IWMPPlayer3, self), bEnableContextMenu);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IWMPPlayer3_put_uiMode(self: *const T, bstrMode: ?BSTR) callconv(.Inline) HRESULT {
return @ptrCast(*const IWMPPlayer3.VTable, self.vtable).put_uiMode(@ptrCast(*const IWMPPlayer3, self), bstrMode);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IWMPPlayer3_get_uiMode(self: *const T, pbstrMode: ?*?BSTR) callconv(.Inline) HRESULT {
return @ptrCast(*const IWMPPlayer3.VTable, self.vtable).get_uiMode(@ptrCast(*const IWMPPlayer3, self), pbstrMode);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IWMPPlayer3_get_stretchToFit(self: *const T, pbEnabled: ?*i16) callconv(.Inline) HRESULT {
return @ptrCast(*const IWMPPlayer3.VTable, self.vtable).get_stretchToFit(@ptrCast(*const IWMPPlayer3, self), pbEnabled);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IWMPPlayer3_put_stretchToFit(self: *const T, bEnabled: i16) callconv(.Inline) HRESULT {
return @ptrCast(*const IWMPPlayer3.VTable, self.vtable).put_stretchToFit(@ptrCast(*const IWMPPlayer3, self), bEnabled);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IWMPPlayer3_get_windowlessVideo(self: *const T, pbEnabled: ?*i16) callconv(.Inline) HRESULT {
return @ptrCast(*const IWMPPlayer3.VTable, self.vtable).get_windowlessVideo(@ptrCast(*const IWMPPlayer3, self), pbEnabled);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IWMPPlayer3_put_windowlessVideo(self: *const T, bEnabled: i16) callconv(.Inline) HRESULT {
return @ptrCast(*const IWMPPlayer3.VTable, self.vtable).put_windowlessVideo(@ptrCast(*const IWMPPlayer3, self), bEnabled);
}
};}
pub usingnamespace MethodMixin(@This());
};
const IID_IWMPErrorItem2_Value = Guid.initString("f75ccec0-c67c-475c-931e-8719870bee7d");
pub const IID_IWMPErrorItem2 = &IID_IWMPErrorItem2_Value;
pub const IWMPErrorItem2 = extern struct {
pub const VTable = extern struct {
base: IWMPErrorItem.VTable,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_condition: fn(
self: *const IWMPErrorItem2,
plCondition: ?*i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
};
vtable: *const VTable,
pub fn MethodMixin(comptime T: type) type { return struct {
pub usingnamespace IWMPErrorItem.MethodMixin(T);
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IWMPErrorItem2_get_condition(self: *const T, plCondition: ?*i32) callconv(.Inline) HRESULT {
return @ptrCast(*const IWMPErrorItem2.VTable, self.vtable).get_condition(@ptrCast(*const IWMPErrorItem2, self), plCondition);
}
};}
pub usingnamespace MethodMixin(@This());
};
const IID_IWMPRemoteMediaServices_Value = Guid.initString("cbb92747-741f-44fe-ab5b-f1a48f3b2a59");
pub const IID_IWMPRemoteMediaServices = &IID_IWMPRemoteMediaServices_Value;
pub const IWMPRemoteMediaServices = extern struct {
pub const VTable = extern struct {
base: IUnknown.VTable,
GetServiceType: fn(
self: *const IWMPRemoteMediaServices,
pbstrType: ?*?BSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetApplicationName: fn(
self: *const IWMPRemoteMediaServices,
pbstrName: ?*?BSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetScriptableObject: fn(
self: *const IWMPRemoteMediaServices,
pbstrName: ?*?BSTR,
ppDispatch: ?*?*IDispatch,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetCustomUIMode: fn(
self: *const IWMPRemoteMediaServices,
pbstrFile: ?*?BSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
};
vtable: *const VTable,
pub fn MethodMixin(comptime T: type) type { return struct {
pub usingnamespace IUnknown.MethodMixin(T);
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IWMPRemoteMediaServices_GetServiceType(self: *const T, pbstrType: ?*?BSTR) callconv(.Inline) HRESULT {
return @ptrCast(*const IWMPRemoteMediaServices.VTable, self.vtable).GetServiceType(@ptrCast(*const IWMPRemoteMediaServices, self), pbstrType);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IWMPRemoteMediaServices_GetApplicationName(self: *const T, pbstrName: ?*?BSTR) callconv(.Inline) HRESULT {
return @ptrCast(*const IWMPRemoteMediaServices.VTable, self.vtable).GetApplicationName(@ptrCast(*const IWMPRemoteMediaServices, self), pbstrName);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IWMPRemoteMediaServices_GetScriptableObject(self: *const T, pbstrName: ?*?BSTR, ppDispatch: ?*?*IDispatch) callconv(.Inline) HRESULT {
return @ptrCast(*const IWMPRemoteMediaServices.VTable, self.vtable).GetScriptableObject(@ptrCast(*const IWMPRemoteMediaServices, self), pbstrName, ppDispatch);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IWMPRemoteMediaServices_GetCustomUIMode(self: *const T, pbstrFile: ?*?BSTR) callconv(.Inline) HRESULT {
return @ptrCast(*const IWMPRemoteMediaServices.VTable, self.vtable).GetCustomUIMode(@ptrCast(*const IWMPRemoteMediaServices, self), pbstrFile);
}
};}
pub usingnamespace MethodMixin(@This());
};
const IID_IWMPSkinManager_Value = Guid.initString("076f2fa6-ed30-448b-8cc5-3f3ef3529c7a");
pub const IID_IWMPSkinManager = &IID_IWMPSkinManager_Value;
pub const IWMPSkinManager = extern struct {
pub const VTable = extern struct {
base: IUnknown.VTable,
SetVisualStyle: fn(
self: *const IWMPSkinManager,
bstrPath: ?BSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
};
vtable: *const VTable,
pub fn MethodMixin(comptime T: type) type { return struct {
pub usingnamespace IUnknown.MethodMixin(T);
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IWMPSkinManager_SetVisualStyle(self: *const T, bstrPath: ?BSTR) callconv(.Inline) HRESULT {
return @ptrCast(*const IWMPSkinManager.VTable, self.vtable).SetVisualStyle(@ptrCast(*const IWMPSkinManager, self), bstrPath);
}
};}
pub usingnamespace MethodMixin(@This());
};
const IID_IWMPMetadataPicture_Value = Guid.initString("5c29bbe0-f87d-4c45-aa28-a70f0230ffa9");
pub const IID_IWMPMetadataPicture = &IID_IWMPMetadataPicture_Value;
pub const IWMPMetadataPicture = extern struct {
pub const VTable = extern struct {
base: IDispatch.VTable,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_mimeType: fn(
self: *const IWMPMetadataPicture,
pbstrMimeType: ?*?BSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_pictureType: fn(
self: *const IWMPMetadataPicture,
pbstrPictureType: ?*?BSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_description: fn(
self: *const IWMPMetadataPicture,
pbstrDescription: ?*?BSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_URL: fn(
self: *const IWMPMetadataPicture,
pbstrURL: ?*?BSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
};
vtable: *const VTable,
pub fn MethodMixin(comptime T: type) type { return struct {
pub usingnamespace IDispatch.MethodMixin(T);
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IWMPMetadataPicture_get_mimeType(self: *const T, pbstrMimeType: ?*?BSTR) callconv(.Inline) HRESULT {
return @ptrCast(*const IWMPMetadataPicture.VTable, self.vtable).get_mimeType(@ptrCast(*const IWMPMetadataPicture, self), pbstrMimeType);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IWMPMetadataPicture_get_pictureType(self: *const T, pbstrPictureType: ?*?BSTR) callconv(.Inline) HRESULT {
return @ptrCast(*const IWMPMetadataPicture.VTable, self.vtable).get_pictureType(@ptrCast(*const IWMPMetadataPicture, self), pbstrPictureType);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IWMPMetadataPicture_get_description(self: *const T, pbstrDescription: ?*?BSTR) callconv(.Inline) HRESULT {
return @ptrCast(*const IWMPMetadataPicture.VTable, self.vtable).get_description(@ptrCast(*const IWMPMetadataPicture, self), pbstrDescription);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IWMPMetadataPicture_get_URL(self: *const T, pbstrURL: ?*?BSTR) callconv(.Inline) HRESULT {
return @ptrCast(*const IWMPMetadataPicture.VTable, self.vtable).get_URL(@ptrCast(*const IWMPMetadataPicture, self), pbstrURL);
}
};}
pub usingnamespace MethodMixin(@This());
};
const IID_IWMPMetadataText_Value = Guid.initString("769a72db-13d2-45e2-9c48-53ca9d5b7450");
pub const IID_IWMPMetadataText = &IID_IWMPMetadataText_Value;
pub const IWMPMetadataText = extern struct {
pub const VTable = extern struct {
base: IDispatch.VTable,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_description: fn(
self: *const IWMPMetadataText,
pbstrDescription: ?*?BSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_text: fn(
self: *const IWMPMetadataText,
pbstrText: ?*?BSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
};
vtable: *const VTable,
pub fn MethodMixin(comptime T: type) type { return struct {
pub usingnamespace IDispatch.MethodMixin(T);
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IWMPMetadataText_get_description(self: *const T, pbstrDescription: ?*?BSTR) callconv(.Inline) HRESULT {
return @ptrCast(*const IWMPMetadataText.VTable, self.vtable).get_description(@ptrCast(*const IWMPMetadataText, self), pbstrDescription);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IWMPMetadataText_get_text(self: *const T, pbstrText: ?*?BSTR) callconv(.Inline) HRESULT {
return @ptrCast(*const IWMPMetadataText.VTable, self.vtable).get_text(@ptrCast(*const IWMPMetadataText, self), pbstrText);
}
};}
pub usingnamespace MethodMixin(@This());
};
const IID_IWMPMedia3_Value = Guid.initString("f118efc7-f03a-4fb4-99c9-1c02a5c1065b");
pub const IID_IWMPMedia3 = &IID_IWMPMedia3_Value;
pub const IWMPMedia3 = extern struct {
pub const VTable = extern struct {
base: IWMPMedia2.VTable,
getAttributeCountByType: fn(
self: *const IWMPMedia3,
bstrType: ?BSTR,
bstrLanguage: ?BSTR,
plCount: ?*i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
getItemInfoByType: fn(
self: *const IWMPMedia3,
bstrType: ?BSTR,
bstrLanguage: ?BSTR,
lIndex: i32,
pvarValue: ?*VARIANT,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
};
vtable: *const VTable,
pub fn MethodMixin(comptime T: type) type { return struct {
pub usingnamespace IWMPMedia2.MethodMixin(T);
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IWMPMedia3_getAttributeCountByType(self: *const T, bstrType: ?BSTR, bstrLanguage: ?BSTR, plCount: ?*i32) callconv(.Inline) HRESULT {
return @ptrCast(*const IWMPMedia3.VTable, self.vtable).getAttributeCountByType(@ptrCast(*const IWMPMedia3, self), bstrType, bstrLanguage, plCount);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IWMPMedia3_getItemInfoByType(self: *const T, bstrType: ?BSTR, bstrLanguage: ?BSTR, lIndex: i32, pvarValue: ?*VARIANT) callconv(.Inline) HRESULT {
return @ptrCast(*const IWMPMedia3.VTable, self.vtable).getItemInfoByType(@ptrCast(*const IWMPMedia3, self), bstrType, bstrLanguage, lIndex, pvarValue);
}
};}
pub usingnamespace MethodMixin(@This());
};
const IID_IWMPSettings2_Value = Guid.initString("fda937a4-eece-4da5-a0b6-39bf89ade2c2");
pub const IID_IWMPSettings2 = &IID_IWMPSettings2_Value;
pub const IWMPSettings2 = extern struct {
pub const VTable = extern struct {
base: IWMPSettings.VTable,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_defaultAudioLanguage: fn(
self: *const IWMPSettings2,
plLangID: ?*i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_mediaAccessRights: fn(
self: *const IWMPSettings2,
pbstrRights: ?*?BSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
requestMediaAccessRights: fn(
self: *const IWMPSettings2,
bstrDesiredAccess: ?BSTR,
pvbAccepted: ?*i16,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
};
vtable: *const VTable,
pub fn MethodMixin(comptime T: type) type { return struct {
pub usingnamespace IWMPSettings.MethodMixin(T);
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IWMPSettings2_get_defaultAudioLanguage(self: *const T, plLangID: ?*i32) callconv(.Inline) HRESULT {
return @ptrCast(*const IWMPSettings2.VTable, self.vtable).get_defaultAudioLanguage(@ptrCast(*const IWMPSettings2, self), plLangID);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IWMPSettings2_get_mediaAccessRights(self: *const T, pbstrRights: ?*?BSTR) callconv(.Inline) HRESULT {
return @ptrCast(*const IWMPSettings2.VTable, self.vtable).get_mediaAccessRights(@ptrCast(*const IWMPSettings2, self), pbstrRights);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IWMPSettings2_requestMediaAccessRights(self: *const T, bstrDesiredAccess: ?BSTR, pvbAccepted: ?*i16) callconv(.Inline) HRESULT {
return @ptrCast(*const IWMPSettings2.VTable, self.vtable).requestMediaAccessRights(@ptrCast(*const IWMPSettings2, self), bstrDesiredAccess, pvbAccepted);
}
};}
pub usingnamespace MethodMixin(@This());
};
const IID_IWMPControls3_Value = Guid.initString("a1d1110e-d545-476a-9a78-ac3e4cb1e6bd");
pub const IID_IWMPControls3 = &IID_IWMPControls3_Value;
pub const IWMPControls3 = extern struct {
pub const VTable = extern struct {
base: IWMPControls2.VTable,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_audioLanguageCount: fn(
self: *const IWMPControls3,
plCount: ?*i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
getAudioLanguageID: fn(
self: *const IWMPControls3,
lIndex: i32,
plLangID: ?*i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
getAudioLanguageDescription: fn(
self: *const IWMPControls3,
lIndex: i32,
pbstrLangDesc: ?*?BSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_currentAudioLanguage: fn(
self: *const IWMPControls3,
plLangID: ?*i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
put_currentAudioLanguage: fn(
self: *const IWMPControls3,
lLangID: i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_currentAudioLanguageIndex: fn(
self: *const IWMPControls3,
plIndex: ?*i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
put_currentAudioLanguageIndex: fn(
self: *const IWMPControls3,
lIndex: i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
getLanguageName: fn(
self: *const IWMPControls3,
lLangID: i32,
pbstrLangName: ?*?BSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_currentPositionTimecode: fn(
self: *const IWMPControls3,
bstrTimecode: ?*?BSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
put_currentPositionTimecode: fn(
self: *const IWMPControls3,
bstrTimecode: ?BSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
};
vtable: *const VTable,
pub fn MethodMixin(comptime T: type) type { return struct {
pub usingnamespace IWMPControls2.MethodMixin(T);
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IWMPControls3_get_audioLanguageCount(self: *const T, plCount: ?*i32) callconv(.Inline) HRESULT {
return @ptrCast(*const IWMPControls3.VTable, self.vtable).get_audioLanguageCount(@ptrCast(*const IWMPControls3, self), plCount);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IWMPControls3_getAudioLanguageID(self: *const T, lIndex: i32, plLangID: ?*i32) callconv(.Inline) HRESULT {
return @ptrCast(*const IWMPControls3.VTable, self.vtable).getAudioLanguageID(@ptrCast(*const IWMPControls3, self), lIndex, plLangID);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IWMPControls3_getAudioLanguageDescription(self: *const T, lIndex: i32, pbstrLangDesc: ?*?BSTR) callconv(.Inline) HRESULT {
return @ptrCast(*const IWMPControls3.VTable, self.vtable).getAudioLanguageDescription(@ptrCast(*const IWMPControls3, self), lIndex, pbstrLangDesc);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IWMPControls3_get_currentAudioLanguage(self: *const T, plLangID: ?*i32) callconv(.Inline) HRESULT {
return @ptrCast(*const IWMPControls3.VTable, self.vtable).get_currentAudioLanguage(@ptrCast(*const IWMPControls3, self), plLangID);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IWMPControls3_put_currentAudioLanguage(self: *const T, lLangID: i32) callconv(.Inline) HRESULT {
return @ptrCast(*const IWMPControls3.VTable, self.vtable).put_currentAudioLanguage(@ptrCast(*const IWMPControls3, self), lLangID);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IWMPControls3_get_currentAudioLanguageIndex(self: *const T, plIndex: ?*i32) callconv(.Inline) HRESULT {
return @ptrCast(*const IWMPControls3.VTable, self.vtable).get_currentAudioLanguageIndex(@ptrCast(*const IWMPControls3, self), plIndex);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IWMPControls3_put_currentAudioLanguageIndex(self: *const T, lIndex: i32) callconv(.Inline) HRESULT {
return @ptrCast(*const IWMPControls3.VTable, self.vtable).put_currentAudioLanguageIndex(@ptrCast(*const IWMPControls3, self), lIndex);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IWMPControls3_getLanguageName(self: *const T, lLangID: i32, pbstrLangName: ?*?BSTR) callconv(.Inline) HRESULT {
return @ptrCast(*const IWMPControls3.VTable, self.vtable).getLanguageName(@ptrCast(*const IWMPControls3, self), lLangID, pbstrLangName);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IWMPControls3_get_currentPositionTimecode(self: *const T, bstrTimecode: ?*?BSTR) callconv(.Inline) HRESULT {
return @ptrCast(*const IWMPControls3.VTable, self.vtable).get_currentPositionTimecode(@ptrCast(*const IWMPControls3, self), bstrTimecode);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IWMPControls3_put_currentPositionTimecode(self: *const T, bstrTimecode: ?BSTR) callconv(.Inline) HRESULT {
return @ptrCast(*const IWMPControls3.VTable, self.vtable).put_currentPositionTimecode(@ptrCast(*const IWMPControls3, self), bstrTimecode);
}
};}
pub usingnamespace MethodMixin(@This());
};
const IID_IWMPClosedCaption2_Value = Guid.initString("350ba78b-6bc8-4113-a5f5-312056934eb6");
pub const IID_IWMPClosedCaption2 = &IID_IWMPClosedCaption2_Value;
pub const IWMPClosedCaption2 = extern struct {
pub const VTable = extern struct {
base: IWMPClosedCaption.VTable,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_SAMILangCount: fn(
self: *const IWMPClosedCaption2,
plCount: ?*i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
getSAMILangName: fn(
self: *const IWMPClosedCaption2,
nIndex: i32,
pbstrName: ?*?BSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
getSAMILangID: fn(
self: *const IWMPClosedCaption2,
nIndex: i32,
plLangID: ?*i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_SAMIStyleCount: fn(
self: *const IWMPClosedCaption2,
plCount: ?*i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
getSAMIStyleName: fn(
self: *const IWMPClosedCaption2,
nIndex: i32,
pbstrName: ?*?BSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
};
vtable: *const VTable,
pub fn MethodMixin(comptime T: type) type { return struct {
pub usingnamespace IWMPClosedCaption.MethodMixin(T);
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IWMPClosedCaption2_get_SAMILangCount(self: *const T, plCount: ?*i32) callconv(.Inline) HRESULT {
return @ptrCast(*const IWMPClosedCaption2.VTable, self.vtable).get_SAMILangCount(@ptrCast(*const IWMPClosedCaption2, self), plCount);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IWMPClosedCaption2_getSAMILangName(self: *const T, nIndex: i32, pbstrName: ?*?BSTR) callconv(.Inline) HRESULT {
return @ptrCast(*const IWMPClosedCaption2.VTable, self.vtable).getSAMILangName(@ptrCast(*const IWMPClosedCaption2, self), nIndex, pbstrName);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IWMPClosedCaption2_getSAMILangID(self: *const T, nIndex: i32, plLangID: ?*i32) callconv(.Inline) HRESULT {
return @ptrCast(*const IWMPClosedCaption2.VTable, self.vtable).getSAMILangID(@ptrCast(*const IWMPClosedCaption2, self), nIndex, plLangID);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IWMPClosedCaption2_get_SAMIStyleCount(self: *const T, plCount: ?*i32) callconv(.Inline) HRESULT {
return @ptrCast(*const IWMPClosedCaption2.VTable, self.vtable).get_SAMIStyleCount(@ptrCast(*const IWMPClosedCaption2, self), plCount);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IWMPClosedCaption2_getSAMIStyleName(self: *const T, nIndex: i32, pbstrName: ?*?BSTR) callconv(.Inline) HRESULT {
return @ptrCast(*const IWMPClosedCaption2.VTable, self.vtable).getSAMIStyleName(@ptrCast(*const IWMPClosedCaption2, self), nIndex, pbstrName);
}
};}
pub usingnamespace MethodMixin(@This());
};
const IID_IWMPPlayerApplication_Value = Guid.initString("40897764-ceab-47be-ad4a-8e28537f9bbf");
pub const IID_IWMPPlayerApplication = &IID_IWMPPlayerApplication_Value;
pub const IWMPPlayerApplication = extern struct {
pub const VTable = extern struct {
base: IDispatch.VTable,
switchToPlayerApplication: fn(
self: *const IWMPPlayerApplication,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
switchToControl: fn(
self: *const IWMPPlayerApplication,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_playerDocked: fn(
self: *const IWMPPlayerApplication,
pbPlayerDocked: ?*i16,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_hasDisplay: fn(
self: *const IWMPPlayerApplication,
pbHasDisplay: ?*i16,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
};
vtable: *const VTable,
pub fn MethodMixin(comptime T: type) type { return struct {
pub usingnamespace IDispatch.MethodMixin(T);
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IWMPPlayerApplication_switchToPlayerApplication(self: *const T) callconv(.Inline) HRESULT {
return @ptrCast(*const IWMPPlayerApplication.VTable, self.vtable).switchToPlayerApplication(@ptrCast(*const IWMPPlayerApplication, self));
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IWMPPlayerApplication_switchToControl(self: *const T) callconv(.Inline) HRESULT {
return @ptrCast(*const IWMPPlayerApplication.VTable, self.vtable).switchToControl(@ptrCast(*const IWMPPlayerApplication, self));
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IWMPPlayerApplication_get_playerDocked(self: *const T, pbPlayerDocked: ?*i16) callconv(.Inline) HRESULT {
return @ptrCast(*const IWMPPlayerApplication.VTable, self.vtable).get_playerDocked(@ptrCast(*const IWMPPlayerApplication, self), pbPlayerDocked);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IWMPPlayerApplication_get_hasDisplay(self: *const T, pbHasDisplay: ?*i16) callconv(.Inline) HRESULT {
return @ptrCast(*const IWMPPlayerApplication.VTable, self.vtable).get_hasDisplay(@ptrCast(*const IWMPPlayerApplication, self), pbHasDisplay);
}
};}
pub usingnamespace MethodMixin(@This());
};
const IID_IWMPCore3_Value = Guid.initString("7587c667-628f-499f-88e7-6a6f4e888464");
pub const IID_IWMPCore3 = &IID_IWMPCore3_Value;
pub const IWMPCore3 = extern struct {
pub const VTable = extern struct {
base: IWMPCore2.VTable,
newPlaylist: fn(
self: *const IWMPCore3,
bstrName: ?BSTR,
bstrURL: ?BSTR,
ppPlaylist: ?*?*IWMPPlaylist,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
newMedia: fn(
self: *const IWMPCore3,
bstrURL: ?BSTR,
ppMedia: ?*?*IWMPMedia,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
};
vtable: *const VTable,
pub fn MethodMixin(comptime T: type) type { return struct {
pub usingnamespace IWMPCore2.MethodMixin(T);
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IWMPCore3_newPlaylist(self: *const T, bstrName: ?BSTR, bstrURL: ?BSTR, ppPlaylist: ?*?*IWMPPlaylist) callconv(.Inline) HRESULT {
return @ptrCast(*const IWMPCore3.VTable, self.vtable).newPlaylist(@ptrCast(*const IWMPCore3, self), bstrName, bstrURL, ppPlaylist);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IWMPCore3_newMedia(self: *const T, bstrURL: ?BSTR, ppMedia: ?*?*IWMPMedia) callconv(.Inline) HRESULT {
return @ptrCast(*const IWMPCore3.VTable, self.vtable).newMedia(@ptrCast(*const IWMPCore3, self), bstrURL, ppMedia);
}
};}
pub usingnamespace MethodMixin(@This());
};
const IID_IWMPPlayer4_Value = Guid.initString("6c497d62-8919-413c-82db-e935fb3ec584");
pub const IID_IWMPPlayer4 = &IID_IWMPPlayer4_Value;
pub const IWMPPlayer4 = extern struct {
pub const VTable = extern struct {
base: IWMPCore3.VTable,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_enabled: fn(
self: *const IWMPPlayer4,
pbEnabled: ?*i16,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
put_enabled: fn(
self: *const IWMPPlayer4,
bEnabled: i16,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_fullScreen: fn(
self: *const IWMPPlayer4,
pbFullScreen: ?*i16,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
put_fullScreen: fn(
self: *const IWMPPlayer4,
bFullScreen: i16,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_enableContextMenu: fn(
self: *const IWMPPlayer4,
pbEnableContextMenu: ?*i16,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
put_enableContextMenu: fn(
self: *const IWMPPlayer4,
bEnableContextMenu: i16,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
put_uiMode: fn(
self: *const IWMPPlayer4,
bstrMode: ?BSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_uiMode: fn(
self: *const IWMPPlayer4,
pbstrMode: ?*?BSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_stretchToFit: fn(
self: *const IWMPPlayer4,
pbEnabled: ?*i16,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
put_stretchToFit: fn(
self: *const IWMPPlayer4,
bEnabled: i16,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_windowlessVideo: fn(
self: *const IWMPPlayer4,
pbEnabled: ?*i16,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
put_windowlessVideo: fn(
self: *const IWMPPlayer4,
bEnabled: i16,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_isRemote: fn(
self: *const IWMPPlayer4,
pvarfIsRemote: ?*i16,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_playerApplication: fn(
self: *const IWMPPlayer4,
ppIWMPPlayerApplication: ?*?*IWMPPlayerApplication,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
openPlayer: fn(
self: *const IWMPPlayer4,
bstrURL: ?BSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
};
vtable: *const VTable,
pub fn MethodMixin(comptime T: type) type { return struct {
pub usingnamespace IWMPCore3.MethodMixin(T);
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IWMPPlayer4_get_enabled(self: *const T, pbEnabled: ?*i16) callconv(.Inline) HRESULT {
return @ptrCast(*const IWMPPlayer4.VTable, self.vtable).get_enabled(@ptrCast(*const IWMPPlayer4, self), pbEnabled);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IWMPPlayer4_put_enabled(self: *const T, bEnabled: i16) callconv(.Inline) HRESULT {
return @ptrCast(*const IWMPPlayer4.VTable, self.vtable).put_enabled(@ptrCast(*const IWMPPlayer4, self), bEnabled);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IWMPPlayer4_get_fullScreen(self: *const T, pbFullScreen: ?*i16) callconv(.Inline) HRESULT {
return @ptrCast(*const IWMPPlayer4.VTable, self.vtable).get_fullScreen(@ptrCast(*const IWMPPlayer4, self), pbFullScreen);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IWMPPlayer4_put_fullScreen(self: *const T, bFullScreen: i16) callconv(.Inline) HRESULT {
return @ptrCast(*const IWMPPlayer4.VTable, self.vtable).put_fullScreen(@ptrCast(*const IWMPPlayer4, self), bFullScreen);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IWMPPlayer4_get_enableContextMenu(self: *const T, pbEnableContextMenu: ?*i16) callconv(.Inline) HRESULT {
return @ptrCast(*const IWMPPlayer4.VTable, self.vtable).get_enableContextMenu(@ptrCast(*const IWMPPlayer4, self), pbEnableContextMenu);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IWMPPlayer4_put_enableContextMenu(self: *const T, bEnableContextMenu: i16) callconv(.Inline) HRESULT {
return @ptrCast(*const IWMPPlayer4.VTable, self.vtable).put_enableContextMenu(@ptrCast(*const IWMPPlayer4, self), bEnableContextMenu);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IWMPPlayer4_put_uiMode(self: *const T, bstrMode: ?BSTR) callconv(.Inline) HRESULT {
return @ptrCast(*const IWMPPlayer4.VTable, self.vtable).put_uiMode(@ptrCast(*const IWMPPlayer4, self), bstrMode);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IWMPPlayer4_get_uiMode(self: *const T, pbstrMode: ?*?BSTR) callconv(.Inline) HRESULT {
return @ptrCast(*const IWMPPlayer4.VTable, self.vtable).get_uiMode(@ptrCast(*const IWMPPlayer4, self), pbstrMode);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IWMPPlayer4_get_stretchToFit(self: *const T, pbEnabled: ?*i16) callconv(.Inline) HRESULT {
return @ptrCast(*const IWMPPlayer4.VTable, self.vtable).get_stretchToFit(@ptrCast(*const IWMPPlayer4, self), pbEnabled);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IWMPPlayer4_put_stretchToFit(self: *const T, bEnabled: i16) callconv(.Inline) HRESULT {
return @ptrCast(*const IWMPPlayer4.VTable, self.vtable).put_stretchToFit(@ptrCast(*const IWMPPlayer4, self), bEnabled);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IWMPPlayer4_get_windowlessVideo(self: *const T, pbEnabled: ?*i16) callconv(.Inline) HRESULT {
return @ptrCast(*const IWMPPlayer4.VTable, self.vtable).get_windowlessVideo(@ptrCast(*const IWMPPlayer4, self), pbEnabled);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IWMPPlayer4_put_windowlessVideo(self: *const T, bEnabled: i16) callconv(.Inline) HRESULT {
return @ptrCast(*const IWMPPlayer4.VTable, self.vtable).put_windowlessVideo(@ptrCast(*const IWMPPlayer4, self), bEnabled);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IWMPPlayer4_get_isRemote(self: *const T, pvarfIsRemote: ?*i16) callconv(.Inline) HRESULT {
return @ptrCast(*const IWMPPlayer4.VTable, self.vtable).get_isRemote(@ptrCast(*const IWMPPlayer4, self), pvarfIsRemote);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IWMPPlayer4_get_playerApplication(self: *const T, ppIWMPPlayerApplication: ?*?*IWMPPlayerApplication) callconv(.Inline) HRESULT {
return @ptrCast(*const IWMPPlayer4.VTable, self.vtable).get_playerApplication(@ptrCast(*const IWMPPlayer4, self), ppIWMPPlayerApplication);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IWMPPlayer4_openPlayer(self: *const T, bstrURL: ?BSTR) callconv(.Inline) HRESULT {
return @ptrCast(*const IWMPPlayer4.VTable, self.vtable).openPlayer(@ptrCast(*const IWMPPlayer4, self), bstrURL);
}
};}
pub usingnamespace MethodMixin(@This());
};
const IID_IWMPPlayerServices_Value = Guid.initString("1d01fbdb-ade2-4c8d-9842-c190b95c3306");
pub const IID_IWMPPlayerServices = &IID_IWMPPlayerServices_Value;
pub const IWMPPlayerServices = extern struct {
pub const VTable = extern struct {
base: IUnknown.VTable,
activateUIPlugin: fn(
self: *const IWMPPlayerServices,
bstrPlugin: ?BSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
setTaskPane: fn(
self: *const IWMPPlayerServices,
bstrTaskPane: ?BSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
setTaskPaneURL: fn(
self: *const IWMPPlayerServices,
bstrTaskPane: ?BSTR,
bstrURL: ?BSTR,
bstrFriendlyName: ?BSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
};
vtable: *const VTable,
pub fn MethodMixin(comptime T: type) type { return struct {
pub usingnamespace IUnknown.MethodMixin(T);
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IWMPPlayerServices_activateUIPlugin(self: *const T, bstrPlugin: ?BSTR) callconv(.Inline) HRESULT {
return @ptrCast(*const IWMPPlayerServices.VTable, self.vtable).activateUIPlugin(@ptrCast(*const IWMPPlayerServices, self), bstrPlugin);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IWMPPlayerServices_setTaskPane(self: *const T, bstrTaskPane: ?BSTR) callconv(.Inline) HRESULT {
return @ptrCast(*const IWMPPlayerServices.VTable, self.vtable).setTaskPane(@ptrCast(*const IWMPPlayerServices, self), bstrTaskPane);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IWMPPlayerServices_setTaskPaneURL(self: *const T, bstrTaskPane: ?BSTR, bstrURL: ?BSTR, bstrFriendlyName: ?BSTR) callconv(.Inline) HRESULT {
return @ptrCast(*const IWMPPlayerServices.VTable, self.vtable).setTaskPaneURL(@ptrCast(*const IWMPPlayerServices, self), bstrTaskPane, bstrURL, bstrFriendlyName);
}
};}
pub usingnamespace MethodMixin(@This());
};
pub const WMPSyncState = enum(i32) {
Unknown = 0,
Synchronizing = 1,
Stopped = 2,
Estimating = 3,
Last = 4,
};
pub const wmpssUnknown = WMPSyncState.Unknown;
pub const wmpssSynchronizing = WMPSyncState.Synchronizing;
pub const wmpssStopped = WMPSyncState.Stopped;
pub const wmpssEstimating = WMPSyncState.Estimating;
pub const wmpssLast = WMPSyncState.Last;
pub const WMPDeviceStatus = enum(i32) {
Unknown = 0,
PartnershipExists = 1,
PartnershipDeclined = 2,
PartnershipAnother = 3,
ManualDevice = 4,
NewDevice = 5,
Last = 6,
};
pub const wmpdsUnknown = WMPDeviceStatus.Unknown;
pub const wmpdsPartnershipExists = WMPDeviceStatus.PartnershipExists;
pub const wmpdsPartnershipDeclined = WMPDeviceStatus.PartnershipDeclined;
pub const wmpdsPartnershipAnother = WMPDeviceStatus.PartnershipAnother;
pub const wmpdsManualDevice = WMPDeviceStatus.ManualDevice;
pub const wmpdsNewDevice = WMPDeviceStatus.NewDevice;
pub const wmpdsLast = WMPDeviceStatus.Last;
const IID_IWMPSyncDevice_Value = Guid.initString("82a2986c-0293-4fd0-b279-b21b86c058be");
pub const IID_IWMPSyncDevice = &IID_IWMPSyncDevice_Value;
pub const IWMPSyncDevice = extern struct {
pub const VTable = extern struct {
base: IUnknown.VTable,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_friendlyName: fn(
self: *const IWMPSyncDevice,
pbstrName: ?*?BSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
put_friendlyName: fn(
self: *const IWMPSyncDevice,
bstrName: ?BSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_deviceName: fn(
self: *const IWMPSyncDevice,
pbstrName: ?*?BSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_deviceId: fn(
self: *const IWMPSyncDevice,
pbstrDeviceId: ?*?BSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_partnershipIndex: fn(
self: *const IWMPSyncDevice,
plIndex: ?*i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_connected: fn(
self: *const IWMPSyncDevice,
pvbConnected: ?*i16,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_status: fn(
self: *const IWMPSyncDevice,
pwmpds: ?*WMPDeviceStatus,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_syncState: fn(
self: *const IWMPSyncDevice,
pwmpss: ?*WMPSyncState,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_progress: fn(
self: *const IWMPSyncDevice,
plProgress: ?*i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
getItemInfo: fn(
self: *const IWMPSyncDevice,
bstrItemName: ?BSTR,
pbstrVal: ?*?BSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
createPartnership: fn(
self: *const IWMPSyncDevice,
vbShowUI: i16,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
deletePartnership: fn(
self: *const IWMPSyncDevice,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
start: fn(
self: *const IWMPSyncDevice,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
stop: fn(
self: *const IWMPSyncDevice,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
showSettings: fn(
self: *const IWMPSyncDevice,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
isIdentical: fn(
self: *const IWMPSyncDevice,
pDevice: ?*IWMPSyncDevice,
pvbool: ?*i16,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
};
vtable: *const VTable,
pub fn MethodMixin(comptime T: type) type { return struct {
pub usingnamespace IUnknown.MethodMixin(T);
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IWMPSyncDevice_get_friendlyName(self: *const T, pbstrName: ?*?BSTR) callconv(.Inline) HRESULT {
return @ptrCast(*const IWMPSyncDevice.VTable, self.vtable).get_friendlyName(@ptrCast(*const IWMPSyncDevice, self), pbstrName);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IWMPSyncDevice_put_friendlyName(self: *const T, bstrName: ?BSTR) callconv(.Inline) HRESULT {
return @ptrCast(*const IWMPSyncDevice.VTable, self.vtable).put_friendlyName(@ptrCast(*const IWMPSyncDevice, self), bstrName);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IWMPSyncDevice_get_deviceName(self: *const T, pbstrName: ?*?BSTR) callconv(.Inline) HRESULT {
return @ptrCast(*const IWMPSyncDevice.VTable, self.vtable).get_deviceName(@ptrCast(*const IWMPSyncDevice, self), pbstrName);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IWMPSyncDevice_get_deviceId(self: *const T, pbstrDeviceId: ?*?BSTR) callconv(.Inline) HRESULT {
return @ptrCast(*const IWMPSyncDevice.VTable, self.vtable).get_deviceId(@ptrCast(*const IWMPSyncDevice, self), pbstrDeviceId);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IWMPSyncDevice_get_partnershipIndex(self: *const T, plIndex: ?*i32) callconv(.Inline) HRESULT {
return @ptrCast(*const IWMPSyncDevice.VTable, self.vtable).get_partnershipIndex(@ptrCast(*const IWMPSyncDevice, self), plIndex);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IWMPSyncDevice_get_connected(self: *const T, pvbConnected: ?*i16) callconv(.Inline) HRESULT {
return @ptrCast(*const IWMPSyncDevice.VTable, self.vtable).get_connected(@ptrCast(*const IWMPSyncDevice, self), pvbConnected);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IWMPSyncDevice_get_status(self: *const T, pwmpds: ?*WMPDeviceStatus) callconv(.Inline) HRESULT {
return @ptrCast(*const IWMPSyncDevice.VTable, self.vtable).get_status(@ptrCast(*const IWMPSyncDevice, self), pwmpds);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IWMPSyncDevice_get_syncState(self: *const T, pwmpss: ?*WMPSyncState) callconv(.Inline) HRESULT {
return @ptrCast(*const IWMPSyncDevice.VTable, self.vtable).get_syncState(@ptrCast(*const IWMPSyncDevice, self), pwmpss);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IWMPSyncDevice_get_progress(self: *const T, plProgress: ?*i32) callconv(.Inline) HRESULT {
return @ptrCast(*const IWMPSyncDevice.VTable, self.vtable).get_progress(@ptrCast(*const IWMPSyncDevice, self), plProgress);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IWMPSyncDevice_getItemInfo(self: *const T, bstrItemName: ?BSTR, pbstrVal: ?*?BSTR) callconv(.Inline) HRESULT {
return @ptrCast(*const IWMPSyncDevice.VTable, self.vtable).getItemInfo(@ptrCast(*const IWMPSyncDevice, self), bstrItemName, pbstrVal);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IWMPSyncDevice_createPartnership(self: *const T, vbShowUI: i16) callconv(.Inline) HRESULT {
return @ptrCast(*const IWMPSyncDevice.VTable, self.vtable).createPartnership(@ptrCast(*const IWMPSyncDevice, self), vbShowUI);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IWMPSyncDevice_deletePartnership(self: *const T) callconv(.Inline) HRESULT {
return @ptrCast(*const IWMPSyncDevice.VTable, self.vtable).deletePartnership(@ptrCast(*const IWMPSyncDevice, self));
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IWMPSyncDevice_start(self: *const T) callconv(.Inline) HRESULT {
return @ptrCast(*const IWMPSyncDevice.VTable, self.vtable).start(@ptrCast(*const IWMPSyncDevice, self));
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IWMPSyncDevice_stop(self: *const T) callconv(.Inline) HRESULT {
return @ptrCast(*const IWMPSyncDevice.VTable, self.vtable).stop(@ptrCast(*const IWMPSyncDevice, self));
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IWMPSyncDevice_showSettings(self: *const T) callconv(.Inline) HRESULT {
return @ptrCast(*const IWMPSyncDevice.VTable, self.vtable).showSettings(@ptrCast(*const IWMPSyncDevice, self));
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IWMPSyncDevice_isIdentical(self: *const T, pDevice: ?*IWMPSyncDevice, pvbool: ?*i16) callconv(.Inline) HRESULT {
return @ptrCast(*const IWMPSyncDevice.VTable, self.vtable).isIdentical(@ptrCast(*const IWMPSyncDevice, self), pDevice, pvbool);
}
};}
pub usingnamespace MethodMixin(@This());
};
const IID_IWMPSyncServices_Value = Guid.initString("8b5050ff-e0a4-4808-b3a8-893a9e1ed894");
pub const IID_IWMPSyncServices = &IID_IWMPSyncServices_Value;
pub const IWMPSyncServices = extern struct {
pub const VTable = extern struct {
base: IUnknown.VTable,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_deviceCount: fn(
self: *const IWMPSyncServices,
plCount: ?*i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
getDevice: fn(
self: *const IWMPSyncServices,
lIndex: i32,
ppDevice: ?*?*IWMPSyncDevice,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
};
vtable: *const VTable,
pub fn MethodMixin(comptime T: type) type { return struct {
pub usingnamespace IUnknown.MethodMixin(T);
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IWMPSyncServices_get_deviceCount(self: *const T, plCount: ?*i32) callconv(.Inline) HRESULT {
return @ptrCast(*const IWMPSyncServices.VTable, self.vtable).get_deviceCount(@ptrCast(*const IWMPSyncServices, self), plCount);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IWMPSyncServices_getDevice(self: *const T, lIndex: i32, ppDevice: ?*?*IWMPSyncDevice) callconv(.Inline) HRESULT {
return @ptrCast(*const IWMPSyncServices.VTable, self.vtable).getDevice(@ptrCast(*const IWMPSyncServices, self), lIndex, ppDevice);
}
};}
pub usingnamespace MethodMixin(@This());
};
const IID_IWMPPlayerServices2_Value = Guid.initString("1bb1592f-f040-418a-9f71-17c7512b4d70");
pub const IID_IWMPPlayerServices2 = &IID_IWMPPlayerServices2_Value;
pub const IWMPPlayerServices2 = extern struct {
pub const VTable = extern struct {
base: IWMPPlayerServices.VTable,
setBackgroundProcessingPriority: fn(
self: *const IWMPPlayerServices2,
bstrPriority: ?BSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
};
vtable: *const VTable,
pub fn MethodMixin(comptime T: type) type { return struct {
pub usingnamespace IWMPPlayerServices.MethodMixin(T);
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IWMPPlayerServices2_setBackgroundProcessingPriority(self: *const T, bstrPriority: ?BSTR) callconv(.Inline) HRESULT {
return @ptrCast(*const IWMPPlayerServices2.VTable, self.vtable).setBackgroundProcessingPriority(@ptrCast(*const IWMPPlayerServices2, self), bstrPriority);
}
};}
pub usingnamespace MethodMixin(@This());
};
pub const WMPRipState = enum(i32) {
Unknown = 0,
Ripping = 1,
Stopped = 2,
};
pub const wmprsUnknown = WMPRipState.Unknown;
pub const wmprsRipping = WMPRipState.Ripping;
pub const wmprsStopped = WMPRipState.Stopped;
pub const WMPBurnFormat = enum(i32) {
AudioCD = 0,
DataCD = 1,
};
pub const wmpbfAudioCD = WMPBurnFormat.AudioCD;
pub const wmpbfDataCD = WMPBurnFormat.DataCD;
pub const WMPBurnState = enum(i32) {
Unknown = 0,
Busy = 1,
Ready = 2,
WaitingForDisc = 3,
RefreshStatusPending = 4,
PreparingToBurn = 5,
Burning = 6,
Stopped = 7,
Erasing = 8,
Downloading = 9,
};
pub const wmpbsUnknown = WMPBurnState.Unknown;
pub const wmpbsBusy = WMPBurnState.Busy;
pub const wmpbsReady = WMPBurnState.Ready;
pub const wmpbsWaitingForDisc = WMPBurnState.WaitingForDisc;
pub const wmpbsRefreshStatusPending = WMPBurnState.RefreshStatusPending;
pub const wmpbsPreparingToBurn = WMPBurnState.PreparingToBurn;
pub const wmpbsBurning = WMPBurnState.Burning;
pub const wmpbsStopped = WMPBurnState.Stopped;
pub const wmpbsErasing = WMPBurnState.Erasing;
pub const wmpbsDownloading = WMPBurnState.Downloading;
pub const WMPStringCollectionChangeEventType = enum(i32) {
Unknown = 0,
Insert = 1,
Change = 2,
Delete = 3,
Clear = 4,
BeginUpdates = 5,
EndUpdates = 6,
};
pub const wmpsccetUnknown = WMPStringCollectionChangeEventType.Unknown;
pub const wmpsccetInsert = WMPStringCollectionChangeEventType.Insert;
pub const wmpsccetChange = WMPStringCollectionChangeEventType.Change;
pub const wmpsccetDelete = WMPStringCollectionChangeEventType.Delete;
pub const wmpsccetClear = WMPStringCollectionChangeEventType.Clear;
pub const wmpsccetBeginUpdates = WMPStringCollectionChangeEventType.BeginUpdates;
pub const wmpsccetEndUpdates = WMPStringCollectionChangeEventType.EndUpdates;
const IID_IWMPCdromRip_Value = Guid.initString("56e2294f-69ed-4629-a869-aea72c0dcc2c");
pub const IID_IWMPCdromRip = &IID_IWMPCdromRip_Value;
pub const IWMPCdromRip = extern struct {
pub const VTable = extern struct {
base: IUnknown.VTable,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_ripState: fn(
self: *const IWMPCdromRip,
pwmprs: ?*WMPRipState,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_ripProgress: fn(
self: *const IWMPCdromRip,
plProgress: ?*i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
startRip: fn(
self: *const IWMPCdromRip,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
stopRip: fn(
self: *const IWMPCdromRip,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
};
vtable: *const VTable,
pub fn MethodMixin(comptime T: type) type { return struct {
pub usingnamespace IUnknown.MethodMixin(T);
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IWMPCdromRip_get_ripState(self: *const T, pwmprs: ?*WMPRipState) callconv(.Inline) HRESULT {
return @ptrCast(*const IWMPCdromRip.VTable, self.vtable).get_ripState(@ptrCast(*const IWMPCdromRip, self), pwmprs);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IWMPCdromRip_get_ripProgress(self: *const T, plProgress: ?*i32) callconv(.Inline) HRESULT {
return @ptrCast(*const IWMPCdromRip.VTable, self.vtable).get_ripProgress(@ptrCast(*const IWMPCdromRip, self), plProgress);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IWMPCdromRip_startRip(self: *const T) callconv(.Inline) HRESULT {
return @ptrCast(*const IWMPCdromRip.VTable, self.vtable).startRip(@ptrCast(*const IWMPCdromRip, self));
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IWMPCdromRip_stopRip(self: *const T) callconv(.Inline) HRESULT {
return @ptrCast(*const IWMPCdromRip.VTable, self.vtable).stopRip(@ptrCast(*const IWMPCdromRip, self));
}
};}
pub usingnamespace MethodMixin(@This());
};
const IID_IWMPCdromBurn_Value = Guid.initString("bd94dbeb-417f-4928-aa06-087d56ed9b59");
pub const IID_IWMPCdromBurn = &IID_IWMPCdromBurn_Value;
pub const IWMPCdromBurn = extern struct {
pub const VTable = extern struct {
base: IUnknown.VTable,
isAvailable: fn(
self: *const IWMPCdromBurn,
bstrItem: ?BSTR,
pIsAvailable: ?*i16,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
getItemInfo: fn(
self: *const IWMPCdromBurn,
bstrItem: ?BSTR,
pbstrVal: ?*?BSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_label: fn(
self: *const IWMPCdromBurn,
pbstrLabel: ?*?BSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
put_label: fn(
self: *const IWMPCdromBurn,
bstrLabel: ?BSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_burnFormat: fn(
self: *const IWMPCdromBurn,
pwmpbf: ?*WMPBurnFormat,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
put_burnFormat: fn(
self: *const IWMPCdromBurn,
wmpbf: WMPBurnFormat,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_burnPlaylist: fn(
self: *const IWMPCdromBurn,
ppPlaylist: ?*?*IWMPPlaylist,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
put_burnPlaylist: fn(
self: *const IWMPCdromBurn,
pPlaylist: ?*IWMPPlaylist,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
refreshStatus: fn(
self: *const IWMPCdromBurn,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_burnState: fn(
self: *const IWMPCdromBurn,
pwmpbs: ?*WMPBurnState,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_burnProgress: fn(
self: *const IWMPCdromBurn,
plProgress: ?*i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
startBurn: fn(
self: *const IWMPCdromBurn,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
stopBurn: fn(
self: *const IWMPCdromBurn,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
erase: fn(
self: *const IWMPCdromBurn,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
};
vtable: *const VTable,
pub fn MethodMixin(comptime T: type) type { return struct {
pub usingnamespace IUnknown.MethodMixin(T);
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IWMPCdromBurn_isAvailable(self: *const T, bstrItem: ?BSTR, pIsAvailable: ?*i16) callconv(.Inline) HRESULT {
return @ptrCast(*const IWMPCdromBurn.VTable, self.vtable).isAvailable(@ptrCast(*const IWMPCdromBurn, self), bstrItem, pIsAvailable);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IWMPCdromBurn_getItemInfo(self: *const T, bstrItem: ?BSTR, pbstrVal: ?*?BSTR) callconv(.Inline) HRESULT {
return @ptrCast(*const IWMPCdromBurn.VTable, self.vtable).getItemInfo(@ptrCast(*const IWMPCdromBurn, self), bstrItem, pbstrVal);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IWMPCdromBurn_get_label(self: *const T, pbstrLabel: ?*?BSTR) callconv(.Inline) HRESULT {
return @ptrCast(*const IWMPCdromBurn.VTable, self.vtable).get_label(@ptrCast(*const IWMPCdromBurn, self), pbstrLabel);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IWMPCdromBurn_put_label(self: *const T, bstrLabel: ?BSTR) callconv(.Inline) HRESULT {
return @ptrCast(*const IWMPCdromBurn.VTable, self.vtable).put_label(@ptrCast(*const IWMPCdromBurn, self), bstrLabel);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IWMPCdromBurn_get_burnFormat(self: *const T, pwmpbf: ?*WMPBurnFormat) callconv(.Inline) HRESULT {
return @ptrCast(*const IWMPCdromBurn.VTable, self.vtable).get_burnFormat(@ptrCast(*const IWMPCdromBurn, self), pwmpbf);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IWMPCdromBurn_put_burnFormat(self: *const T, wmpbf: WMPBurnFormat) callconv(.Inline) HRESULT {
return @ptrCast(*const IWMPCdromBurn.VTable, self.vtable).put_burnFormat(@ptrCast(*const IWMPCdromBurn, self), wmpbf);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IWMPCdromBurn_get_burnPlaylist(self: *const T, ppPlaylist: ?*?*IWMPPlaylist) callconv(.Inline) HRESULT {
return @ptrCast(*const IWMPCdromBurn.VTable, self.vtable).get_burnPlaylist(@ptrCast(*const IWMPCdromBurn, self), ppPlaylist);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IWMPCdromBurn_put_burnPlaylist(self: *const T, pPlaylist: ?*IWMPPlaylist) callconv(.Inline) HRESULT {
return @ptrCast(*const IWMPCdromBurn.VTable, self.vtable).put_burnPlaylist(@ptrCast(*const IWMPCdromBurn, self), pPlaylist);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IWMPCdromBurn_refreshStatus(self: *const T) callconv(.Inline) HRESULT {
return @ptrCast(*const IWMPCdromBurn.VTable, self.vtable).refreshStatus(@ptrCast(*const IWMPCdromBurn, self));
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IWMPCdromBurn_get_burnState(self: *const T, pwmpbs: ?*WMPBurnState) callconv(.Inline) HRESULT {
return @ptrCast(*const IWMPCdromBurn.VTable, self.vtable).get_burnState(@ptrCast(*const IWMPCdromBurn, self), pwmpbs);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IWMPCdromBurn_get_burnProgress(self: *const T, plProgress: ?*i32) callconv(.Inline) HRESULT {
return @ptrCast(*const IWMPCdromBurn.VTable, self.vtable).get_burnProgress(@ptrCast(*const IWMPCdromBurn, self), plProgress);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IWMPCdromBurn_startBurn(self: *const T) callconv(.Inline) HRESULT {
return @ptrCast(*const IWMPCdromBurn.VTable, self.vtable).startBurn(@ptrCast(*const IWMPCdromBurn, self));
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IWMPCdromBurn_stopBurn(self: *const T) callconv(.Inline) HRESULT {
return @ptrCast(*const IWMPCdromBurn.VTable, self.vtable).stopBurn(@ptrCast(*const IWMPCdromBurn, self));
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IWMPCdromBurn_erase(self: *const T) callconv(.Inline) HRESULT {
return @ptrCast(*const IWMPCdromBurn.VTable, self.vtable).erase(@ptrCast(*const IWMPCdromBurn, self));
}
};}
pub usingnamespace MethodMixin(@This());
};
const IID_IWMPQuery_Value = Guid.initString("a00918f3-a6b0-4bfb-9189-fd834c7bc5a5");
pub const IID_IWMPQuery = &IID_IWMPQuery_Value;
pub const IWMPQuery = extern struct {
pub const VTable = extern struct {
base: IDispatch.VTable,
addCondition: fn(
self: *const IWMPQuery,
bstrAttribute: ?BSTR,
bstrOperator: ?BSTR,
bstrValue: ?BSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
beginNextGroup: fn(
self: *const IWMPQuery,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
};
vtable: *const VTable,
pub fn MethodMixin(comptime T: type) type { return struct {
pub usingnamespace IDispatch.MethodMixin(T);
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IWMPQuery_addCondition(self: *const T, bstrAttribute: ?BSTR, bstrOperator: ?BSTR, bstrValue: ?BSTR) callconv(.Inline) HRESULT {
return @ptrCast(*const IWMPQuery.VTable, self.vtable).addCondition(@ptrCast(*const IWMPQuery, self), bstrAttribute, bstrOperator, bstrValue);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IWMPQuery_beginNextGroup(self: *const T) callconv(.Inline) HRESULT {
return @ptrCast(*const IWMPQuery.VTable, self.vtable).beginNextGroup(@ptrCast(*const IWMPQuery, self));
}
};}
pub usingnamespace MethodMixin(@This());
};
const IID_IWMPMediaCollection2_Value = Guid.initString("8ba957f5-fd8c-4791-b82d-f840401ee474");
pub const IID_IWMPMediaCollection2 = &IID_IWMPMediaCollection2_Value;
pub const IWMPMediaCollection2 = extern struct {
pub const VTable = extern struct {
base: IWMPMediaCollection.VTable,
createQuery: fn(
self: *const IWMPMediaCollection2,
ppQuery: ?*?*IWMPQuery,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
getPlaylistByQuery: fn(
self: *const IWMPMediaCollection2,
pQuery: ?*IWMPQuery,
bstrMediaType: ?BSTR,
bstrSortAttribute: ?BSTR,
fSortAscending: i16,
ppPlaylist: ?*?*IWMPPlaylist,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
getStringCollectionByQuery: fn(
self: *const IWMPMediaCollection2,
bstrAttribute: ?BSTR,
pQuery: ?*IWMPQuery,
bstrMediaType: ?BSTR,
bstrSortAttribute: ?BSTR,
fSortAscending: i16,
ppStringCollection: ?*?*IWMPStringCollection,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
getByAttributeAndMediaType: fn(
self: *const IWMPMediaCollection2,
bstrAttribute: ?BSTR,
bstrValue: ?BSTR,
bstrMediaType: ?BSTR,
ppMediaItems: ?*?*IWMPPlaylist,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
};
vtable: *const VTable,
pub fn MethodMixin(comptime T: type) type { return struct {
pub usingnamespace IWMPMediaCollection.MethodMixin(T);
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IWMPMediaCollection2_createQuery(self: *const T, ppQuery: ?*?*IWMPQuery) callconv(.Inline) HRESULT {
return @ptrCast(*const IWMPMediaCollection2.VTable, self.vtable).createQuery(@ptrCast(*const IWMPMediaCollection2, self), ppQuery);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IWMPMediaCollection2_getPlaylistByQuery(self: *const T, pQuery: ?*IWMPQuery, bstrMediaType: ?BSTR, bstrSortAttribute: ?BSTR, fSortAscending: i16, ppPlaylist: ?*?*IWMPPlaylist) callconv(.Inline) HRESULT {
return @ptrCast(*const IWMPMediaCollection2.VTable, self.vtable).getPlaylistByQuery(@ptrCast(*const IWMPMediaCollection2, self), pQuery, bstrMediaType, bstrSortAttribute, fSortAscending, ppPlaylist);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IWMPMediaCollection2_getStringCollectionByQuery(self: *const T, bstrAttribute: ?BSTR, pQuery: ?*IWMPQuery, bstrMediaType: ?BSTR, bstrSortAttribute: ?BSTR, fSortAscending: i16, ppStringCollection: ?*?*IWMPStringCollection) callconv(.Inline) HRESULT {
return @ptrCast(*const IWMPMediaCollection2.VTable, self.vtable).getStringCollectionByQuery(@ptrCast(*const IWMPMediaCollection2, self), bstrAttribute, pQuery, bstrMediaType, bstrSortAttribute, fSortAscending, ppStringCollection);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IWMPMediaCollection2_getByAttributeAndMediaType(self: *const T, bstrAttribute: ?BSTR, bstrValue: ?BSTR, bstrMediaType: ?BSTR, ppMediaItems: ?*?*IWMPPlaylist) callconv(.Inline) HRESULT {
return @ptrCast(*const IWMPMediaCollection2.VTable, self.vtable).getByAttributeAndMediaType(@ptrCast(*const IWMPMediaCollection2, self), bstrAttribute, bstrValue, bstrMediaType, ppMediaItems);
}
};}
pub usingnamespace MethodMixin(@This());
};
const IID_IWMPStringCollection2_Value = Guid.initString("46ad648d-53f1-4a74-92e2-2a1b68d63fd4");
pub const IID_IWMPStringCollection2 = &IID_IWMPStringCollection2_Value;
pub const IWMPStringCollection2 = extern struct {
pub const VTable = extern struct {
base: IWMPStringCollection.VTable,
isIdentical: fn(
self: *const IWMPStringCollection2,
pIWMPStringCollection2: ?*IWMPStringCollection2,
pvbool: ?*i16,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
getItemInfo: fn(
self: *const IWMPStringCollection2,
lCollectionIndex: i32,
bstrItemName: ?BSTR,
pbstrValue: ?*?BSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
getAttributeCountByType: fn(
self: *const IWMPStringCollection2,
lCollectionIndex: i32,
bstrType: ?BSTR,
bstrLanguage: ?BSTR,
plCount: ?*i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
getItemInfoByType: fn(
self: *const IWMPStringCollection2,
lCollectionIndex: i32,
bstrType: ?BSTR,
bstrLanguage: ?BSTR,
lAttributeIndex: i32,
pvarValue: ?*VARIANT,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
};
vtable: *const VTable,
pub fn MethodMixin(comptime T: type) type { return struct {
pub usingnamespace IWMPStringCollection.MethodMixin(T);
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IWMPStringCollection2_isIdentical(self: *const T, pIWMPStringCollection2: ?*IWMPStringCollection2, pvbool: ?*i16) callconv(.Inline) HRESULT {
return @ptrCast(*const IWMPStringCollection2.VTable, self.vtable).isIdentical(@ptrCast(*const IWMPStringCollection2, self), pIWMPStringCollection2, pvbool);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IWMPStringCollection2_getItemInfo(self: *const T, lCollectionIndex: i32, bstrItemName: ?BSTR, pbstrValue: ?*?BSTR) callconv(.Inline) HRESULT {
return @ptrCast(*const IWMPStringCollection2.VTable, self.vtable).getItemInfo(@ptrCast(*const IWMPStringCollection2, self), lCollectionIndex, bstrItemName, pbstrValue);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IWMPStringCollection2_getAttributeCountByType(self: *const T, lCollectionIndex: i32, bstrType: ?BSTR, bstrLanguage: ?BSTR, plCount: ?*i32) callconv(.Inline) HRESULT {
return @ptrCast(*const IWMPStringCollection2.VTable, self.vtable).getAttributeCountByType(@ptrCast(*const IWMPStringCollection2, self), lCollectionIndex, bstrType, bstrLanguage, plCount);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IWMPStringCollection2_getItemInfoByType(self: *const T, lCollectionIndex: i32, bstrType: ?BSTR, bstrLanguage: ?BSTR, lAttributeIndex: i32, pvarValue: ?*VARIANT) callconv(.Inline) HRESULT {
return @ptrCast(*const IWMPStringCollection2.VTable, self.vtable).getItemInfoByType(@ptrCast(*const IWMPStringCollection2, self), lCollectionIndex, bstrType, bstrLanguage, lAttributeIndex, pvarValue);
}
};}
pub usingnamespace MethodMixin(@This());
};
pub const WMPLibraryType = enum(i32) {
Unknown = 0,
All = 1,
Local = 2,
Remote = 3,
Disc = 4,
PortableDevice = 5,
};
pub const wmpltUnknown = WMPLibraryType.Unknown;
pub const wmpltAll = WMPLibraryType.All;
pub const wmpltLocal = WMPLibraryType.Local;
pub const wmpltRemote = WMPLibraryType.Remote;
pub const wmpltDisc = WMPLibraryType.Disc;
pub const wmpltPortableDevice = WMPLibraryType.PortableDevice;
const IID_IWMPLibrary_Value = Guid.initString("3df47861-7df1-4c1f-a81b-4c26f0f7a7c6");
pub const IID_IWMPLibrary = &IID_IWMPLibrary_Value;
pub const IWMPLibrary = extern struct {
pub const VTable = extern struct {
base: IUnknown.VTable,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_name: fn(
self: *const IWMPLibrary,
pbstrName: ?*?BSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_type: fn(
self: *const IWMPLibrary,
pwmplt: ?*WMPLibraryType,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_mediaCollection: fn(
self: *const IWMPLibrary,
ppIWMPMediaCollection: ?*?*IWMPMediaCollection,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
isIdentical: fn(
self: *const IWMPLibrary,
pIWMPLibrary: ?*IWMPLibrary,
pvbool: ?*i16,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
};
vtable: *const VTable,
pub fn MethodMixin(comptime T: type) type { return struct {
pub usingnamespace IUnknown.MethodMixin(T);
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IWMPLibrary_get_name(self: *const T, pbstrName: ?*?BSTR) callconv(.Inline) HRESULT {
return @ptrCast(*const IWMPLibrary.VTable, self.vtable).get_name(@ptrCast(*const IWMPLibrary, self), pbstrName);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IWMPLibrary_get_type(self: *const T, pwmplt: ?*WMPLibraryType) callconv(.Inline) HRESULT {
return @ptrCast(*const IWMPLibrary.VTable, self.vtable).get_type(@ptrCast(*const IWMPLibrary, self), pwmplt);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IWMPLibrary_get_mediaCollection(self: *const T, ppIWMPMediaCollection: ?*?*IWMPMediaCollection) callconv(.Inline) HRESULT {
return @ptrCast(*const IWMPLibrary.VTable, self.vtable).get_mediaCollection(@ptrCast(*const IWMPLibrary, self), ppIWMPMediaCollection);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IWMPLibrary_isIdentical(self: *const T, pIWMPLibrary: ?*IWMPLibrary, pvbool: ?*i16) callconv(.Inline) HRESULT {
return @ptrCast(*const IWMPLibrary.VTable, self.vtable).isIdentical(@ptrCast(*const IWMPLibrary, self), pIWMPLibrary, pvbool);
}
};}
pub usingnamespace MethodMixin(@This());
};
const IID_IWMPLibraryServices_Value = Guid.initString("39c2f8d5-1cf2-4d5e-ae09-d73492cf9eaa");
pub const IID_IWMPLibraryServices = &IID_IWMPLibraryServices_Value;
pub const IWMPLibraryServices = extern struct {
pub const VTable = extern struct {
base: IUnknown.VTable,
getCountByType: fn(
self: *const IWMPLibraryServices,
wmplt: WMPLibraryType,
plCount: ?*i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
getLibraryByType: fn(
self: *const IWMPLibraryServices,
wmplt: WMPLibraryType,
lIndex: i32,
ppIWMPLibrary: ?*?*IWMPLibrary,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
};
vtable: *const VTable,
pub fn MethodMixin(comptime T: type) type { return struct {
pub usingnamespace IUnknown.MethodMixin(T);
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IWMPLibraryServices_getCountByType(self: *const T, wmplt: WMPLibraryType, plCount: ?*i32) callconv(.Inline) HRESULT {
return @ptrCast(*const IWMPLibraryServices.VTable, self.vtable).getCountByType(@ptrCast(*const IWMPLibraryServices, self), wmplt, plCount);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IWMPLibraryServices_getLibraryByType(self: *const T, wmplt: WMPLibraryType, lIndex: i32, ppIWMPLibrary: ?*?*IWMPLibrary) callconv(.Inline) HRESULT {
return @ptrCast(*const IWMPLibraryServices.VTable, self.vtable).getLibraryByType(@ptrCast(*const IWMPLibraryServices, self), wmplt, lIndex, ppIWMPLibrary);
}
};}
pub usingnamespace MethodMixin(@This());
};
const IID_IWMPLibrarySharingServices_Value = Guid.initString("82cba86b-9f04-474b-a365-d6dd1466e541");
pub const IID_IWMPLibrarySharingServices = &IID_IWMPLibrarySharingServices_Value;
pub const IWMPLibrarySharingServices = extern struct {
pub const VTable = extern struct {
base: IUnknown.VTable,
isLibraryShared: fn(
self: *const IWMPLibrarySharingServices,
pvbShared: ?*i16,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
isLibrarySharingEnabled: fn(
self: *const IWMPLibrarySharingServices,
pvbEnabled: ?*i16,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
showLibrarySharing: fn(
self: *const IWMPLibrarySharingServices,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
};
vtable: *const VTable,
pub fn MethodMixin(comptime T: type) type { return struct {
pub usingnamespace IUnknown.MethodMixin(T);
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IWMPLibrarySharingServices_isLibraryShared(self: *const T, pvbShared: ?*i16) callconv(.Inline) HRESULT {
return @ptrCast(*const IWMPLibrarySharingServices.VTable, self.vtable).isLibraryShared(@ptrCast(*const IWMPLibrarySharingServices, self), pvbShared);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IWMPLibrarySharingServices_isLibrarySharingEnabled(self: *const T, pvbEnabled: ?*i16) callconv(.Inline) HRESULT {
return @ptrCast(*const IWMPLibrarySharingServices.VTable, self.vtable).isLibrarySharingEnabled(@ptrCast(*const IWMPLibrarySharingServices, self), pvbEnabled);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IWMPLibrarySharingServices_showLibrarySharing(self: *const T) callconv(.Inline) HRESULT {
return @ptrCast(*const IWMPLibrarySharingServices.VTable, self.vtable).showLibrarySharing(@ptrCast(*const IWMPLibrarySharingServices, self));
}
};}
pub usingnamespace MethodMixin(@This());
};
pub const WMPFolderScanState = enum(i32) {
Unknown = 0,
Scanning = 1,
Updating = 2,
Stopped = 3,
};
pub const wmpfssUnknown = WMPFolderScanState.Unknown;
pub const wmpfssScanning = WMPFolderScanState.Scanning;
pub const wmpfssUpdating = WMPFolderScanState.Updating;
pub const wmpfssStopped = WMPFolderScanState.Stopped;
const IID_IWMPFolderMonitorServices_Value = Guid.initString("788c8743-e57f-439d-a468-5bc77f2e59c6");
pub const IID_IWMPFolderMonitorServices = &IID_IWMPFolderMonitorServices_Value;
pub const IWMPFolderMonitorServices = extern struct {
pub const VTable = extern struct {
base: IUnknown.VTable,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_count: fn(
self: *const IWMPFolderMonitorServices,
plCount: ?*i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
item: fn(
self: *const IWMPFolderMonitorServices,
lIndex: i32,
pbstrFolder: ?*?BSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
add: fn(
self: *const IWMPFolderMonitorServices,
bstrFolder: ?BSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
remove: fn(
self: *const IWMPFolderMonitorServices,
lIndex: i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_scanState: fn(
self: *const IWMPFolderMonitorServices,
pwmpfss: ?*WMPFolderScanState,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_currentFolder: fn(
self: *const IWMPFolderMonitorServices,
pbstrFolder: ?*?BSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_scannedFilesCount: fn(
self: *const IWMPFolderMonitorServices,
plCount: ?*i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_addedFilesCount: fn(
self: *const IWMPFolderMonitorServices,
plCount: ?*i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_updateProgress: fn(
self: *const IWMPFolderMonitorServices,
plProgress: ?*i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
startScan: fn(
self: *const IWMPFolderMonitorServices,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
stopScan: fn(
self: *const IWMPFolderMonitorServices,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
};
vtable: *const VTable,
pub fn MethodMixin(comptime T: type) type { return struct {
pub usingnamespace IUnknown.MethodMixin(T);
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IWMPFolderMonitorServices_get_count(self: *const T, plCount: ?*i32) callconv(.Inline) HRESULT {
return @ptrCast(*const IWMPFolderMonitorServices.VTable, self.vtable).get_count(@ptrCast(*const IWMPFolderMonitorServices, self), plCount);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IWMPFolderMonitorServices_item(self: *const T, lIndex: i32, pbstrFolder: ?*?BSTR) callconv(.Inline) HRESULT {
return @ptrCast(*const IWMPFolderMonitorServices.VTable, self.vtable).item(@ptrCast(*const IWMPFolderMonitorServices, self), lIndex, pbstrFolder);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IWMPFolderMonitorServices_add(self: *const T, bstrFolder: ?BSTR) callconv(.Inline) HRESULT {
return @ptrCast(*const IWMPFolderMonitorServices.VTable, self.vtable).add(@ptrCast(*const IWMPFolderMonitorServices, self), bstrFolder);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IWMPFolderMonitorServices_remove(self: *const T, lIndex: i32) callconv(.Inline) HRESULT {
return @ptrCast(*const IWMPFolderMonitorServices.VTable, self.vtable).remove(@ptrCast(*const IWMPFolderMonitorServices, self), lIndex);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IWMPFolderMonitorServices_get_scanState(self: *const T, pwmpfss: ?*WMPFolderScanState) callconv(.Inline) HRESULT {
return @ptrCast(*const IWMPFolderMonitorServices.VTable, self.vtable).get_scanState(@ptrCast(*const IWMPFolderMonitorServices, self), pwmpfss);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IWMPFolderMonitorServices_get_currentFolder(self: *const T, pbstrFolder: ?*?BSTR) callconv(.Inline) HRESULT {
return @ptrCast(*const IWMPFolderMonitorServices.VTable, self.vtable).get_currentFolder(@ptrCast(*const IWMPFolderMonitorServices, self), pbstrFolder);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IWMPFolderMonitorServices_get_scannedFilesCount(self: *const T, plCount: ?*i32) callconv(.Inline) HRESULT {
return @ptrCast(*const IWMPFolderMonitorServices.VTable, self.vtable).get_scannedFilesCount(@ptrCast(*const IWMPFolderMonitorServices, self), plCount);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IWMPFolderMonitorServices_get_addedFilesCount(self: *const T, plCount: ?*i32) callconv(.Inline) HRESULT {
return @ptrCast(*const IWMPFolderMonitorServices.VTable, self.vtable).get_addedFilesCount(@ptrCast(*const IWMPFolderMonitorServices, self), plCount);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IWMPFolderMonitorServices_get_updateProgress(self: *const T, plProgress: ?*i32) callconv(.Inline) HRESULT {
return @ptrCast(*const IWMPFolderMonitorServices.VTable, self.vtable).get_updateProgress(@ptrCast(*const IWMPFolderMonitorServices, self), plProgress);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IWMPFolderMonitorServices_startScan(self: *const T) callconv(.Inline) HRESULT {
return @ptrCast(*const IWMPFolderMonitorServices.VTable, self.vtable).startScan(@ptrCast(*const IWMPFolderMonitorServices, self));
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IWMPFolderMonitorServices_stopScan(self: *const T) callconv(.Inline) HRESULT {
return @ptrCast(*const IWMPFolderMonitorServices.VTable, self.vtable).stopScan(@ptrCast(*const IWMPFolderMonitorServices, self));
}
};}
pub usingnamespace MethodMixin(@This());
};
const IID_IWMPSyncDevice2_Value = Guid.initString("88afb4b2-140a-44d2-91e6-4543da467cd1");
pub const IID_IWMPSyncDevice2 = &IID_IWMPSyncDevice2_Value;
pub const IWMPSyncDevice2 = extern struct {
pub const VTable = extern struct {
base: IWMPSyncDevice.VTable,
setItemInfo: fn(
self: *const IWMPSyncDevice2,
bstrItemName: ?BSTR,
bstrVal: ?BSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
};
vtable: *const VTable,
pub fn MethodMixin(comptime T: type) type { return struct {
pub usingnamespace IWMPSyncDevice.MethodMixin(T);
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IWMPSyncDevice2_setItemInfo(self: *const T, bstrItemName: ?BSTR, bstrVal: ?BSTR) callconv(.Inline) HRESULT {
return @ptrCast(*const IWMPSyncDevice2.VTable, self.vtable).setItemInfo(@ptrCast(*const IWMPSyncDevice2, self), bstrItemName, bstrVal);
}
};}
pub usingnamespace MethodMixin(@This());
};
const IID_IWMPSyncDevice3_Value = Guid.initString("b22c85f9-263c-4372-a0da-b518db9b4098");
pub const IID_IWMPSyncDevice3 = &IID_IWMPSyncDevice3_Value;
pub const IWMPSyncDevice3 = extern struct {
pub const VTable = extern struct {
base: IWMPSyncDevice2.VTable,
estimateSyncSize: fn(
self: *const IWMPSyncDevice3,
pNonRulePlaylist: ?*IWMPPlaylist,
pRulesPlaylist: ?*IWMPPlaylist,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
cancelEstimation: fn(
self: *const IWMPSyncDevice3,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
};
vtable: *const VTable,
pub fn MethodMixin(comptime T: type) type { return struct {
pub usingnamespace IWMPSyncDevice2.MethodMixin(T);
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IWMPSyncDevice3_estimateSyncSize(self: *const T, pNonRulePlaylist: ?*IWMPPlaylist, pRulesPlaylist: ?*IWMPPlaylist) callconv(.Inline) HRESULT {
return @ptrCast(*const IWMPSyncDevice3.VTable, self.vtable).estimateSyncSize(@ptrCast(*const IWMPSyncDevice3, self), pNonRulePlaylist, pRulesPlaylist);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IWMPSyncDevice3_cancelEstimation(self: *const T) callconv(.Inline) HRESULT {
return @ptrCast(*const IWMPSyncDevice3.VTable, self.vtable).cancelEstimation(@ptrCast(*const IWMPSyncDevice3, self));
}
};}
pub usingnamespace MethodMixin(@This());
};
const IID_IWMPLibrary2_Value = Guid.initString("dd578a4e-79b1-426c-bf8f-3add9072500b");
pub const IID_IWMPLibrary2 = &IID_IWMPLibrary2_Value;
pub const IWMPLibrary2 = extern struct {
pub const VTable = extern struct {
base: IWMPLibrary.VTable,
getItemInfo: fn(
self: *const IWMPLibrary2,
bstrItemName: ?BSTR,
pbstrVal: ?*?BSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
};
vtable: *const VTable,
pub fn MethodMixin(comptime T: type) type { return struct {
pub usingnamespace IWMPLibrary.MethodMixin(T);
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IWMPLibrary2_getItemInfo(self: *const T, bstrItemName: ?BSTR, pbstrVal: ?*?BSTR) callconv(.Inline) HRESULT {
return @ptrCast(*const IWMPLibrary2.VTable, self.vtable).getItemInfo(@ptrCast(*const IWMPLibrary2, self), bstrItemName, pbstrVal);
}
};}
pub usingnamespace MethodMixin(@This());
};
const CLSID_WMPLib_Value = Guid.initString("6bf52a50-394a-11d3-b153-00c04f79faa6");
pub const CLSID_WMPLib = &CLSID_WMPLib_Value;
const CLSID_WMPRemoteMediaServices_Value = Guid.initString("df333473-2cf7-4be2-907f-9aad5661364f");
pub const CLSID_WMPRemoteMediaServices = &CLSID_WMPRemoteMediaServices_Value;
const IID_IWMPEvents_Value = Guid.initString("19a6627b-da9e-47c1-bb23-00b5e668236a");
pub const IID_IWMPEvents = &IID_IWMPEvents_Value;
pub const IWMPEvents = extern struct {
pub const VTable = extern struct {
base: IUnknown.VTable,
OpenStateChange: fn(
self: *const IWMPEvents,
NewState: i32,
) callconv(@import("std").os.windows.WINAPI) void,
PlayStateChange: fn(
self: *const IWMPEvents,
NewState: i32,
) callconv(@import("std").os.windows.WINAPI) void,
AudioLanguageChange: fn(
self: *const IWMPEvents,
LangID: i32,
) callconv(@import("std").os.windows.WINAPI) void,
StatusChange: fn(
self: *const IWMPEvents,
) callconv(@import("std").os.windows.WINAPI) void,
ScriptCommand: fn(
self: *const IWMPEvents,
scType: ?BSTR,
Param: ?BSTR,
) callconv(@import("std").os.windows.WINAPI) void,
NewStream: fn(
self: *const IWMPEvents,
) callconv(@import("std").os.windows.WINAPI) void,
Disconnect: fn(
self: *const IWMPEvents,
Result: i32,
) callconv(@import("std").os.windows.WINAPI) void,
Buffering: fn(
self: *const IWMPEvents,
Start: i16,
) callconv(@import("std").os.windows.WINAPI) void,
Error: fn(
self: *const IWMPEvents,
) callconv(@import("std").os.windows.WINAPI) void,
Warning: fn(
self: *const IWMPEvents,
WarningType: i32,
Param: i32,
Description: ?BSTR,
) callconv(@import("std").os.windows.WINAPI) void,
EndOfStream: fn(
self: *const IWMPEvents,
Result: i32,
) callconv(@import("std").os.windows.WINAPI) void,
PositionChange: fn(
self: *const IWMPEvents,
oldPosition: f64,
newPosition: f64,
) callconv(@import("std").os.windows.WINAPI) void,
MarkerHit: fn(
self: *const IWMPEvents,
MarkerNum: i32,
) callconv(@import("std").os.windows.WINAPI) void,
DurationUnitChange: fn(
self: *const IWMPEvents,
NewDurationUnit: i32,
) callconv(@import("std").os.windows.WINAPI) void,
CdromMediaChange: fn(
self: *const IWMPEvents,
CdromNum: i32,
) callconv(@import("std").os.windows.WINAPI) void,
PlaylistChange: fn(
self: *const IWMPEvents,
Playlist: ?*IDispatch,
change: WMPPlaylistChangeEventType,
) callconv(@import("std").os.windows.WINAPI) void,
CurrentPlaylistChange: fn(
self: *const IWMPEvents,
change: WMPPlaylistChangeEventType,
) callconv(@import("std").os.windows.WINAPI) void,
CurrentPlaylistItemAvailable: fn(
self: *const IWMPEvents,
bstrItemName: ?BSTR,
) callconv(@import("std").os.windows.WINAPI) void,
MediaChange: fn(
self: *const IWMPEvents,
Item: ?*IDispatch,
) callconv(@import("std").os.windows.WINAPI) void,
CurrentMediaItemAvailable: fn(
self: *const IWMPEvents,
bstrItemName: ?BSTR,
) callconv(@import("std").os.windows.WINAPI) void,
CurrentItemChange: fn(
self: *const IWMPEvents,
pdispMedia: ?*IDispatch,
) callconv(@import("std").os.windows.WINAPI) void,
MediaCollectionChange: fn(
self: *const IWMPEvents,
) callconv(@import("std").os.windows.WINAPI) void,
MediaCollectionAttributeStringAdded: fn(
self: *const IWMPEvents,
bstrAttribName: ?BSTR,
bstrAttribVal: ?BSTR,
) callconv(@import("std").os.windows.WINAPI) void,
MediaCollectionAttributeStringRemoved: fn(
self: *const IWMPEvents,
bstrAttribName: ?BSTR,
bstrAttribVal: ?BSTR,
) callconv(@import("std").os.windows.WINAPI) void,
MediaCollectionAttributeStringChanged: fn(
self: *const IWMPEvents,
bstrAttribName: ?BSTR,
bstrOldAttribVal: ?BSTR,
bstrNewAttribVal: ?BSTR,
) callconv(@import("std").os.windows.WINAPI) void,
PlaylistCollectionChange: fn(
self: *const IWMPEvents,
) callconv(@import("std").os.windows.WINAPI) void,
PlaylistCollectionPlaylistAdded: fn(
self: *const IWMPEvents,
bstrPlaylistName: ?BSTR,
) callconv(@import("std").os.windows.WINAPI) void,
PlaylistCollectionPlaylistRemoved: fn(
self: *const IWMPEvents,
bstrPlaylistName: ?BSTR,
) callconv(@import("std").os.windows.WINAPI) void,
PlaylistCollectionPlaylistSetAsDeleted: fn(
self: *const IWMPEvents,
bstrPlaylistName: ?BSTR,
varfIsDeleted: i16,
) callconv(@import("std").os.windows.WINAPI) void,
ModeChange: fn(
self: *const IWMPEvents,
ModeName: ?BSTR,
NewValue: i16,
) callconv(@import("std").os.windows.WINAPI) void,
MediaError: fn(
self: *const IWMPEvents,
pMediaObject: ?*IDispatch,
) callconv(@import("std").os.windows.WINAPI) void,
OpenPlaylistSwitch: fn(
self: *const IWMPEvents,
pItem: ?*IDispatch,
) callconv(@import("std").os.windows.WINAPI) void,
DomainChange: fn(
self: *const IWMPEvents,
strDomain: ?BSTR,
) callconv(@import("std").os.windows.WINAPI) void,
SwitchedToPlayerApplication: fn(
self: *const IWMPEvents,
) callconv(@import("std").os.windows.WINAPI) void,
SwitchedToControl: fn(
self: *const IWMPEvents,
) callconv(@import("std").os.windows.WINAPI) void,
PlayerDockedStateChange: fn(
self: *const IWMPEvents,
) callconv(@import("std").os.windows.WINAPI) void,
PlayerReconnect: fn(
self: *const IWMPEvents,
) callconv(@import("std").os.windows.WINAPI) void,
Click: fn(
self: *const IWMPEvents,
nButton: i16,
nShiftState: i16,
fX: i32,
fY: i32,
) callconv(@import("std").os.windows.WINAPI) void,
DoubleClick: fn(
self: *const IWMPEvents,
nButton: i16,
nShiftState: i16,
fX: i32,
fY: i32,
) callconv(@import("std").os.windows.WINAPI) void,
KeyDown: fn(
self: *const IWMPEvents,
nKeyCode: i16,
nShiftState: i16,
) callconv(@import("std").os.windows.WINAPI) void,
KeyPress: fn(
self: *const IWMPEvents,
nKeyAscii: i16,
) callconv(@import("std").os.windows.WINAPI) void,
KeyUp: fn(
self: *const IWMPEvents,
nKeyCode: i16,
nShiftState: i16,
) callconv(@import("std").os.windows.WINAPI) void,
MouseDown: fn(
self: *const IWMPEvents,
nButton: i16,
nShiftState: i16,
fX: i32,
fY: i32,
) callconv(@import("std").os.windows.WINAPI) void,
MouseMove: fn(
self: *const IWMPEvents,
nButton: i16,
nShiftState: i16,
fX: i32,
fY: i32,
) callconv(@import("std").os.windows.WINAPI) void,
MouseUp: fn(
self: *const IWMPEvents,
nButton: i16,
nShiftState: i16,
fX: i32,
fY: i32,
) callconv(@import("std").os.windows.WINAPI) void,
};
vtable: *const VTable,
pub fn MethodMixin(comptime T: type) type { return struct {
pub usingnamespace IUnknown.MethodMixin(T);
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IWMPEvents_OpenStateChange(self: *const T, NewState: i32) callconv(.Inline) void {
return @ptrCast(*const IWMPEvents.VTable, self.vtable).OpenStateChange(@ptrCast(*const IWMPEvents, self), NewState);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IWMPEvents_PlayStateChange(self: *const T, NewState: i32) callconv(.Inline) void {
return @ptrCast(*const IWMPEvents.VTable, self.vtable).PlayStateChange(@ptrCast(*const IWMPEvents, self), NewState);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IWMPEvents_AudioLanguageChange(self: *const T, LangID: i32) callconv(.Inline) void {
return @ptrCast(*const IWMPEvents.VTable, self.vtable).AudioLanguageChange(@ptrCast(*const IWMPEvents, self), LangID);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IWMPEvents_StatusChange(self: *const T) callconv(.Inline) void {
return @ptrCast(*const IWMPEvents.VTable, self.vtable).StatusChange(@ptrCast(*const IWMPEvents, self));
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IWMPEvents_ScriptCommand(self: *const T, scType: ?BSTR, Param: ?BSTR) callconv(.Inline) void {
return @ptrCast(*const IWMPEvents.VTable, self.vtable).ScriptCommand(@ptrCast(*const IWMPEvents, self), scType, Param);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IWMPEvents_NewStream(self: *const T) callconv(.Inline) void {
return @ptrCast(*const IWMPEvents.VTable, self.vtable).NewStream(@ptrCast(*const IWMPEvents, self));
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IWMPEvents_Disconnect(self: *const T, Result: i32) callconv(.Inline) void {
return @ptrCast(*const IWMPEvents.VTable, self.vtable).Disconnect(@ptrCast(*const IWMPEvents, self), Result);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IWMPEvents_Buffering(self: *const T, Start: i16) callconv(.Inline) void {
return @ptrCast(*const IWMPEvents.VTable, self.vtable).Buffering(@ptrCast(*const IWMPEvents, self), Start);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IWMPEvents_Error(self: *const T) callconv(.Inline) void {
return @ptrCast(*const IWMPEvents.VTable, self.vtable).Error(@ptrCast(*const IWMPEvents, self));
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IWMPEvents_Warning(self: *const T, WarningType: i32, Param: i32, Description: ?BSTR) callconv(.Inline) void {
return @ptrCast(*const IWMPEvents.VTable, self.vtable).Warning(@ptrCast(*const IWMPEvents, self), WarningType, Param, Description);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IWMPEvents_EndOfStream(self: *const T, Result: i32) callconv(.Inline) void {
return @ptrCast(*const IWMPEvents.VTable, self.vtable).EndOfStream(@ptrCast(*const IWMPEvents, self), Result);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IWMPEvents_PositionChange(self: *const T, oldPosition: f64, newPosition: f64) callconv(.Inline) void {
return @ptrCast(*const IWMPEvents.VTable, self.vtable).PositionChange(@ptrCast(*const IWMPEvents, self), oldPosition, newPosition);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IWMPEvents_MarkerHit(self: *const T, MarkerNum: i32) callconv(.Inline) void {
return @ptrCast(*const IWMPEvents.VTable, self.vtable).MarkerHit(@ptrCast(*const IWMPEvents, self), MarkerNum);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IWMPEvents_DurationUnitChange(self: *const T, NewDurationUnit: i32) callconv(.Inline) void {
return @ptrCast(*const IWMPEvents.VTable, self.vtable).DurationUnitChange(@ptrCast(*const IWMPEvents, self), NewDurationUnit);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IWMPEvents_CdromMediaChange(self: *const T, CdromNum: i32) callconv(.Inline) void {
return @ptrCast(*const IWMPEvents.VTable, self.vtable).CdromMediaChange(@ptrCast(*const IWMPEvents, self), CdromNum);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IWMPEvents_PlaylistChange(self: *const T, Playlist: ?*IDispatch, change: WMPPlaylistChangeEventType) callconv(.Inline) void {
return @ptrCast(*const IWMPEvents.VTable, self.vtable).PlaylistChange(@ptrCast(*const IWMPEvents, self), Playlist, change);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IWMPEvents_CurrentPlaylistChange(self: *const T, change: WMPPlaylistChangeEventType) callconv(.Inline) void {
return @ptrCast(*const IWMPEvents.VTable, self.vtable).CurrentPlaylistChange(@ptrCast(*const IWMPEvents, self), change);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IWMPEvents_CurrentPlaylistItemAvailable(self: *const T, bstrItemName: ?BSTR) callconv(.Inline) void {
return @ptrCast(*const IWMPEvents.VTable, self.vtable).CurrentPlaylistItemAvailable(@ptrCast(*const IWMPEvents, self), bstrItemName);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IWMPEvents_MediaChange(self: *const T, Item: ?*IDispatch) callconv(.Inline) void {
return @ptrCast(*const IWMPEvents.VTable, self.vtable).MediaChange(@ptrCast(*const IWMPEvents, self), Item);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IWMPEvents_CurrentMediaItemAvailable(self: *const T, bstrItemName: ?BSTR) callconv(.Inline) void {
return @ptrCast(*const IWMPEvents.VTable, self.vtable).CurrentMediaItemAvailable(@ptrCast(*const IWMPEvents, self), bstrItemName);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IWMPEvents_CurrentItemChange(self: *const T, pdispMedia: ?*IDispatch) callconv(.Inline) void {
return @ptrCast(*const IWMPEvents.VTable, self.vtable).CurrentItemChange(@ptrCast(*const IWMPEvents, self), pdispMedia);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IWMPEvents_MediaCollectionChange(self: *const T) callconv(.Inline) void {
return @ptrCast(*const IWMPEvents.VTable, self.vtable).MediaCollectionChange(@ptrCast(*const IWMPEvents, self));
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IWMPEvents_MediaCollectionAttributeStringAdded(self: *const T, bstrAttribName: ?BSTR, bstrAttribVal: ?BSTR) callconv(.Inline) void {
return @ptrCast(*const IWMPEvents.VTable, self.vtable).MediaCollectionAttributeStringAdded(@ptrCast(*const IWMPEvents, self), bstrAttribName, bstrAttribVal);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IWMPEvents_MediaCollectionAttributeStringRemoved(self: *const T, bstrAttribName: ?BSTR, bstrAttribVal: ?BSTR) callconv(.Inline) void {
return @ptrCast(*const IWMPEvents.VTable, self.vtable).MediaCollectionAttributeStringRemoved(@ptrCast(*const IWMPEvents, self), bstrAttribName, bstrAttribVal);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IWMPEvents_MediaCollectionAttributeStringChanged(self: *const T, bstrAttribName: ?BSTR, bstrOldAttribVal: ?BSTR, bstrNewAttribVal: ?BSTR) callconv(.Inline) void {
return @ptrCast(*const IWMPEvents.VTable, self.vtable).MediaCollectionAttributeStringChanged(@ptrCast(*const IWMPEvents, self), bstrAttribName, bstrOldAttribVal, bstrNewAttribVal);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IWMPEvents_PlaylistCollectionChange(self: *const T) callconv(.Inline) void {
return @ptrCast(*const IWMPEvents.VTable, self.vtable).PlaylistCollectionChange(@ptrCast(*const IWMPEvents, self));
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IWMPEvents_PlaylistCollectionPlaylistAdded(self: *const T, bstrPlaylistName: ?BSTR) callconv(.Inline) void {
return @ptrCast(*const IWMPEvents.VTable, self.vtable).PlaylistCollectionPlaylistAdded(@ptrCast(*const IWMPEvents, self), bstrPlaylistName);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IWMPEvents_PlaylistCollectionPlaylistRemoved(self: *const T, bstrPlaylistName: ?BSTR) callconv(.Inline) void {
return @ptrCast(*const IWMPEvents.VTable, self.vtable).PlaylistCollectionPlaylistRemoved(@ptrCast(*const IWMPEvents, self), bstrPlaylistName);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IWMPEvents_PlaylistCollectionPlaylistSetAsDeleted(self: *const T, bstrPlaylistName: ?BSTR, varfIsDeleted: i16) callconv(.Inline) void {
return @ptrCast(*const IWMPEvents.VTable, self.vtable).PlaylistCollectionPlaylistSetAsDeleted(@ptrCast(*const IWMPEvents, self), bstrPlaylistName, varfIsDeleted);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IWMPEvents_ModeChange(self: *const T, ModeName: ?BSTR, NewValue: i16) callconv(.Inline) void {
return @ptrCast(*const IWMPEvents.VTable, self.vtable).ModeChange(@ptrCast(*const IWMPEvents, self), ModeName, NewValue);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IWMPEvents_MediaError(self: *const T, pMediaObject: ?*IDispatch) callconv(.Inline) void {
return @ptrCast(*const IWMPEvents.VTable, self.vtable).MediaError(@ptrCast(*const IWMPEvents, self), pMediaObject);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IWMPEvents_OpenPlaylistSwitch(self: *const T, pItem: ?*IDispatch) callconv(.Inline) void {
return @ptrCast(*const IWMPEvents.VTable, self.vtable).OpenPlaylistSwitch(@ptrCast(*const IWMPEvents, self), pItem);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IWMPEvents_DomainChange(self: *const T, strDomain: ?BSTR) callconv(.Inline) void {
return @ptrCast(*const IWMPEvents.VTable, self.vtable).DomainChange(@ptrCast(*const IWMPEvents, self), strDomain);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IWMPEvents_SwitchedToPlayerApplication(self: *const T) callconv(.Inline) void {
return @ptrCast(*const IWMPEvents.VTable, self.vtable).SwitchedToPlayerApplication(@ptrCast(*const IWMPEvents, self));
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IWMPEvents_SwitchedToControl(self: *const T) callconv(.Inline) void {
return @ptrCast(*const IWMPEvents.VTable, self.vtable).SwitchedToControl(@ptrCast(*const IWMPEvents, self));
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IWMPEvents_PlayerDockedStateChange(self: *const T) callconv(.Inline) void {
return @ptrCast(*const IWMPEvents.VTable, self.vtable).PlayerDockedStateChange(@ptrCast(*const IWMPEvents, self));
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IWMPEvents_PlayerReconnect(self: *const T) callconv(.Inline) void {
return @ptrCast(*const IWMPEvents.VTable, self.vtable).PlayerReconnect(@ptrCast(*const IWMPEvents, self));
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IWMPEvents_Click(self: *const T, nButton: i16, nShiftState: i16, fX: i32, fY: i32) callconv(.Inline) void {
return @ptrCast(*const IWMPEvents.VTable, self.vtable).Click(@ptrCast(*const IWMPEvents, self), nButton, nShiftState, fX, fY);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IWMPEvents_DoubleClick(self: *const T, nButton: i16, nShiftState: i16, fX: i32, fY: i32) callconv(.Inline) void {
return @ptrCast(*const IWMPEvents.VTable, self.vtable).DoubleClick(@ptrCast(*const IWMPEvents, self), nButton, nShiftState, fX, fY);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IWMPEvents_KeyDown(self: *const T, nKeyCode: i16, nShiftState: i16) callconv(.Inline) void {
return @ptrCast(*const IWMPEvents.VTable, self.vtable).KeyDown(@ptrCast(*const IWMPEvents, self), nKeyCode, nShiftState);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IWMPEvents_KeyPress(self: *const T, nKeyAscii: i16) callconv(.Inline) void {
return @ptrCast(*const IWMPEvents.VTable, self.vtable).KeyPress(@ptrCast(*const IWMPEvents, self), nKeyAscii);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IWMPEvents_KeyUp(self: *const T, nKeyCode: i16, nShiftState: i16) callconv(.Inline) void {
return @ptrCast(*const IWMPEvents.VTable, self.vtable).KeyUp(@ptrCast(*const IWMPEvents, self), nKeyCode, nShiftState);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IWMPEvents_MouseDown(self: *const T, nButton: i16, nShiftState: i16, fX: i32, fY: i32) callconv(.Inline) void {
return @ptrCast(*const IWMPEvents.VTable, self.vtable).MouseDown(@ptrCast(*const IWMPEvents, self), nButton, nShiftState, fX, fY);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IWMPEvents_MouseMove(self: *const T, nButton: i16, nShiftState: i16, fX: i32, fY: i32) callconv(.Inline) void {
return @ptrCast(*const IWMPEvents.VTable, self.vtable).MouseMove(@ptrCast(*const IWMPEvents, self), nButton, nShiftState, fX, fY);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IWMPEvents_MouseUp(self: *const T, nButton: i16, nShiftState: i16, fX: i32, fY: i32) callconv(.Inline) void {
return @ptrCast(*const IWMPEvents.VTable, self.vtable).MouseUp(@ptrCast(*const IWMPEvents, self), nButton, nShiftState, fX, fY);
}
};}
pub usingnamespace MethodMixin(@This());
};
const IID_IWMPEvents2_Value = Guid.initString("1e7601fa-47ea-4107-9ea9-9004ed9684ff");
pub const IID_IWMPEvents2 = &IID_IWMPEvents2_Value;
pub const IWMPEvents2 = extern struct {
pub const VTable = extern struct {
base: IWMPEvents.VTable,
DeviceConnect: fn(
self: *const IWMPEvents2,
pDevice: ?*IWMPSyncDevice,
) callconv(@import("std").os.windows.WINAPI) void,
DeviceDisconnect: fn(
self: *const IWMPEvents2,
pDevice: ?*IWMPSyncDevice,
) callconv(@import("std").os.windows.WINAPI) void,
DeviceStatusChange: fn(
self: *const IWMPEvents2,
pDevice: ?*IWMPSyncDevice,
NewStatus: WMPDeviceStatus,
) callconv(@import("std").os.windows.WINAPI) void,
DeviceSyncStateChange: fn(
self: *const IWMPEvents2,
pDevice: ?*IWMPSyncDevice,
NewState: WMPSyncState,
) callconv(@import("std").os.windows.WINAPI) void,
DeviceSyncError: fn(
self: *const IWMPEvents2,
pDevice: ?*IWMPSyncDevice,
pMedia: ?*IDispatch,
) callconv(@import("std").os.windows.WINAPI) void,
CreatePartnershipComplete: fn(
self: *const IWMPEvents2,
pDevice: ?*IWMPSyncDevice,
hrResult: HRESULT,
) callconv(@import("std").os.windows.WINAPI) void,
};
vtable: *const VTable,
pub fn MethodMixin(comptime T: type) type { return struct {
pub usingnamespace IWMPEvents.MethodMixin(T);
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IWMPEvents2_DeviceConnect(self: *const T, pDevice: ?*IWMPSyncDevice) callconv(.Inline) void {
return @ptrCast(*const IWMPEvents2.VTable, self.vtable).DeviceConnect(@ptrCast(*const IWMPEvents2, self), pDevice);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IWMPEvents2_DeviceDisconnect(self: *const T, pDevice: ?*IWMPSyncDevice) callconv(.Inline) void {
return @ptrCast(*const IWMPEvents2.VTable, self.vtable).DeviceDisconnect(@ptrCast(*const IWMPEvents2, self), pDevice);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IWMPEvents2_DeviceStatusChange(self: *const T, pDevice: ?*IWMPSyncDevice, NewStatus: WMPDeviceStatus) callconv(.Inline) void {
return @ptrCast(*const IWMPEvents2.VTable, self.vtable).DeviceStatusChange(@ptrCast(*const IWMPEvents2, self), pDevice, NewStatus);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IWMPEvents2_DeviceSyncStateChange(self: *const T, pDevice: ?*IWMPSyncDevice, NewState: WMPSyncState) callconv(.Inline) void {
return @ptrCast(*const IWMPEvents2.VTable, self.vtable).DeviceSyncStateChange(@ptrCast(*const IWMPEvents2, self), pDevice, NewState);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IWMPEvents2_DeviceSyncError(self: *const T, pDevice: ?*IWMPSyncDevice, pMedia: ?*IDispatch) callconv(.Inline) void {
return @ptrCast(*const IWMPEvents2.VTable, self.vtable).DeviceSyncError(@ptrCast(*const IWMPEvents2, self), pDevice, pMedia);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IWMPEvents2_CreatePartnershipComplete(self: *const T, pDevice: ?*IWMPSyncDevice, hrResult: HRESULT) callconv(.Inline) void {
return @ptrCast(*const IWMPEvents2.VTable, self.vtable).CreatePartnershipComplete(@ptrCast(*const IWMPEvents2, self), pDevice, hrResult);
}
};}
pub usingnamespace MethodMixin(@This());
};
const IID_IWMPEvents3_Value = Guid.initString("1f504270-a66b-4223-8e96-26a06c63d69f");
pub const IID_IWMPEvents3 = &IID_IWMPEvents3_Value;
pub const IWMPEvents3 = extern struct {
pub const VTable = extern struct {
base: IWMPEvents2.VTable,
CdromRipStateChange: fn(
self: *const IWMPEvents3,
pCdromRip: ?*IWMPCdromRip,
wmprs: WMPRipState,
) callconv(@import("std").os.windows.WINAPI) void,
CdromRipMediaError: fn(
self: *const IWMPEvents3,
pCdromRip: ?*IWMPCdromRip,
pMedia: ?*IDispatch,
) callconv(@import("std").os.windows.WINAPI) void,
CdromBurnStateChange: fn(
self: *const IWMPEvents3,
pCdromBurn: ?*IWMPCdromBurn,
wmpbs: WMPBurnState,
) callconv(@import("std").os.windows.WINAPI) void,
CdromBurnMediaError: fn(
self: *const IWMPEvents3,
pCdromBurn: ?*IWMPCdromBurn,
pMedia: ?*IDispatch,
) callconv(@import("std").os.windows.WINAPI) void,
CdromBurnError: fn(
self: *const IWMPEvents3,
pCdromBurn: ?*IWMPCdromBurn,
hrError: HRESULT,
) callconv(@import("std").os.windows.WINAPI) void,
LibraryConnect: fn(
self: *const IWMPEvents3,
pLibrary: ?*IWMPLibrary,
) callconv(@import("std").os.windows.WINAPI) void,
LibraryDisconnect: fn(
self: *const IWMPEvents3,
pLibrary: ?*IWMPLibrary,
) callconv(@import("std").os.windows.WINAPI) void,
FolderScanStateChange: fn(
self: *const IWMPEvents3,
wmpfss: WMPFolderScanState,
) callconv(@import("std").os.windows.WINAPI) void,
StringCollectionChange: fn(
self: *const IWMPEvents3,
pdispStringCollection: ?*IDispatch,
change: WMPStringCollectionChangeEventType,
lCollectionIndex: i32,
) callconv(@import("std").os.windows.WINAPI) void,
MediaCollectionMediaAdded: fn(
self: *const IWMPEvents3,
pdispMedia: ?*IDispatch,
) callconv(@import("std").os.windows.WINAPI) void,
MediaCollectionMediaRemoved: fn(
self: *const IWMPEvents3,
pdispMedia: ?*IDispatch,
) callconv(@import("std").os.windows.WINAPI) void,
};
vtable: *const VTable,
pub fn MethodMixin(comptime T: type) type { return struct {
pub usingnamespace IWMPEvents2.MethodMixin(T);
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IWMPEvents3_CdromRipStateChange(self: *const T, pCdromRip: ?*IWMPCdromRip, wmprs: WMPRipState) callconv(.Inline) void {
return @ptrCast(*const IWMPEvents3.VTable, self.vtable).CdromRipStateChange(@ptrCast(*const IWMPEvents3, self), pCdromRip, wmprs);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IWMPEvents3_CdromRipMediaError(self: *const T, pCdromRip: ?*IWMPCdromRip, pMedia: ?*IDispatch) callconv(.Inline) void {
return @ptrCast(*const IWMPEvents3.VTable, self.vtable).CdromRipMediaError(@ptrCast(*const IWMPEvents3, self), pCdromRip, pMedia);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IWMPEvents3_CdromBurnStateChange(self: *const T, pCdromBurn: ?*IWMPCdromBurn, wmpbs: WMPBurnState) callconv(.Inline) void {
return @ptrCast(*const IWMPEvents3.VTable, self.vtable).CdromBurnStateChange(@ptrCast(*const IWMPEvents3, self), pCdromBurn, wmpbs);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IWMPEvents3_CdromBurnMediaError(self: *const T, pCdromBurn: ?*IWMPCdromBurn, pMedia: ?*IDispatch) callconv(.Inline) void {
return @ptrCast(*const IWMPEvents3.VTable, self.vtable).CdromBurnMediaError(@ptrCast(*const IWMPEvents3, self), pCdromBurn, pMedia);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IWMPEvents3_CdromBurnError(self: *const T, pCdromBurn: ?*IWMPCdromBurn, hrError: HRESULT) callconv(.Inline) void {
return @ptrCast(*const IWMPEvents3.VTable, self.vtable).CdromBurnError(@ptrCast(*const IWMPEvents3, self), pCdromBurn, hrError);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IWMPEvents3_LibraryConnect(self: *const T, pLibrary: ?*IWMPLibrary) callconv(.Inline) void {
return @ptrCast(*const IWMPEvents3.VTable, self.vtable).LibraryConnect(@ptrCast(*const IWMPEvents3, self), pLibrary);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IWMPEvents3_LibraryDisconnect(self: *const T, pLibrary: ?*IWMPLibrary) callconv(.Inline) void {
return @ptrCast(*const IWMPEvents3.VTable, self.vtable).LibraryDisconnect(@ptrCast(*const IWMPEvents3, self), pLibrary);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IWMPEvents3_FolderScanStateChange(self: *const T, wmpfss: WMPFolderScanState) callconv(.Inline) void {
return @ptrCast(*const IWMPEvents3.VTable, self.vtable).FolderScanStateChange(@ptrCast(*const IWMPEvents3, self), wmpfss);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IWMPEvents3_StringCollectionChange(self: *const T, pdispStringCollection: ?*IDispatch, change: WMPStringCollectionChangeEventType, lCollectionIndex: i32) callconv(.Inline) void {
return @ptrCast(*const IWMPEvents3.VTable, self.vtable).StringCollectionChange(@ptrCast(*const IWMPEvents3, self), pdispStringCollection, change, lCollectionIndex);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IWMPEvents3_MediaCollectionMediaAdded(self: *const T, pdispMedia: ?*IDispatch) callconv(.Inline) void {
return @ptrCast(*const IWMPEvents3.VTable, self.vtable).MediaCollectionMediaAdded(@ptrCast(*const IWMPEvents3, self), pdispMedia);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IWMPEvents3_MediaCollectionMediaRemoved(self: *const T, pdispMedia: ?*IDispatch) callconv(.Inline) void {
return @ptrCast(*const IWMPEvents3.VTable, self.vtable).MediaCollectionMediaRemoved(@ptrCast(*const IWMPEvents3, self), pdispMedia);
}
};}
pub usingnamespace MethodMixin(@This());
};
const IID_IWMPEvents4_Value = Guid.initString("26dabcfa-306b-404d-9a6f-630a8405048d");
pub const IID_IWMPEvents4 = &IID_IWMPEvents4_Value;
pub const IWMPEvents4 = extern struct {
pub const VTable = extern struct {
base: IWMPEvents3.VTable,
DeviceEstimation: fn(
self: *const IWMPEvents4,
pDevice: ?*IWMPSyncDevice,
hrResult: HRESULT,
qwEstimatedUsedSpace: i64,
qwEstimatedSpace: i64,
) callconv(@import("std").os.windows.WINAPI) void,
};
vtable: *const VTable,
pub fn MethodMixin(comptime T: type) type { return struct {
pub usingnamespace IWMPEvents3.MethodMixin(T);
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IWMPEvents4_DeviceEstimation(self: *const T, pDevice: ?*IWMPSyncDevice, hrResult: HRESULT, qwEstimatedUsedSpace: i64, qwEstimatedSpace: i64) callconv(.Inline) void {
return @ptrCast(*const IWMPEvents4.VTable, self.vtable).DeviceEstimation(@ptrCast(*const IWMPEvents4, self), pDevice, hrResult, qwEstimatedUsedSpace, qwEstimatedSpace);
}
};}
pub usingnamespace MethodMixin(@This());
};
const IID__WMPOCXEvents_Value = Guid.initString("6bf52a51-394a-11d3-b153-00c04f79faa6");
pub const IID__WMPOCXEvents = &IID__WMPOCXEvents_Value;
pub const _WMPOCXEvents = extern struct {
pub const VTable = extern struct {
base: IDispatch.VTable,
};
vtable: *const VTable,
pub fn MethodMixin(comptime T: type) type { return struct {
pub usingnamespace IDispatch.MethodMixin(T);
};}
pub usingnamespace MethodMixin(@This());
};
const IID_IWMPNodeRealEstate_Value = Guid.initString("42751198-5a50-4460-bcb4-709f8bdc8e59");
pub const IID_IWMPNodeRealEstate = &IID_IWMPNodeRealEstate_Value;
pub const IWMPNodeRealEstate = extern struct {
pub const VTable = extern struct {
base: IUnknown.VTable,
GetDesiredSize: fn(
self: *const IWMPNodeRealEstate,
pSize: ?*SIZE,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
SetRects: fn(
self: *const IWMPNodeRealEstate,
pSrc: ?*const RECT,
pDest: ?*const RECT,
pClip: ?*const RECT,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetRects: fn(
self: *const IWMPNodeRealEstate,
pSrc: ?*RECT,
pDest: ?*RECT,
pClip: ?*RECT,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
SetWindowless: fn(
self: *const IWMPNodeRealEstate,
fWindowless: BOOL,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetWindowless: fn(
self: *const IWMPNodeRealEstate,
pfWindowless: ?*BOOL,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
SetFullScreen: fn(
self: *const IWMPNodeRealEstate,
fFullScreen: BOOL,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetFullScreen: fn(
self: *const IWMPNodeRealEstate,
pfFullScreen: ?*BOOL,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
};
vtable: *const VTable,
pub fn MethodMixin(comptime T: type) type { return struct {
pub usingnamespace IUnknown.MethodMixin(T);
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IWMPNodeRealEstate_GetDesiredSize(self: *const T, pSize: ?*SIZE) callconv(.Inline) HRESULT {
return @ptrCast(*const IWMPNodeRealEstate.VTable, self.vtable).GetDesiredSize(@ptrCast(*const IWMPNodeRealEstate, self), pSize);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IWMPNodeRealEstate_SetRects(self: *const T, pSrc: ?*const RECT, pDest: ?*const RECT, pClip: ?*const RECT) callconv(.Inline) HRESULT {
return @ptrCast(*const IWMPNodeRealEstate.VTable, self.vtable).SetRects(@ptrCast(*const IWMPNodeRealEstate, self), pSrc, pDest, pClip);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IWMPNodeRealEstate_GetRects(self: *const T, pSrc: ?*RECT, pDest: ?*RECT, pClip: ?*RECT) callconv(.Inline) HRESULT {
return @ptrCast(*const IWMPNodeRealEstate.VTable, self.vtable).GetRects(@ptrCast(*const IWMPNodeRealEstate, self), pSrc, pDest, pClip);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IWMPNodeRealEstate_SetWindowless(self: *const T, fWindowless: BOOL) callconv(.Inline) HRESULT {
return @ptrCast(*const IWMPNodeRealEstate.VTable, self.vtable).SetWindowless(@ptrCast(*const IWMPNodeRealEstate, self), fWindowless);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IWMPNodeRealEstate_GetWindowless(self: *const T, pfWindowless: ?*BOOL) callconv(.Inline) HRESULT {
return @ptrCast(*const IWMPNodeRealEstate.VTable, self.vtable).GetWindowless(@ptrCast(*const IWMPNodeRealEstate, self), pfWindowless);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IWMPNodeRealEstate_SetFullScreen(self: *const T, fFullScreen: BOOL) callconv(.Inline) HRESULT {
return @ptrCast(*const IWMPNodeRealEstate.VTable, self.vtable).SetFullScreen(@ptrCast(*const IWMPNodeRealEstate, self), fFullScreen);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IWMPNodeRealEstate_GetFullScreen(self: *const T, pfFullScreen: ?*BOOL) callconv(.Inline) HRESULT {
return @ptrCast(*const IWMPNodeRealEstate.VTable, self.vtable).GetFullScreen(@ptrCast(*const IWMPNodeRealEstate, self), pfFullScreen);
}
};}
pub usingnamespace MethodMixin(@This());
};
const IID_IWMPNodeRealEstateHost_Value = Guid.initString("1491087d-2c6b-44c8-b019-b3c929d2ada9");
pub const IID_IWMPNodeRealEstateHost = &IID_IWMPNodeRealEstateHost_Value;
pub const IWMPNodeRealEstateHost = extern struct {
pub const VTable = extern struct {
base: IUnknown.VTable,
OnDesiredSizeChange: fn(
self: *const IWMPNodeRealEstateHost,
pSize: ?*SIZE,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
OnFullScreenTransition: fn(
self: *const IWMPNodeRealEstateHost,
fFullScreen: BOOL,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
};
vtable: *const VTable,
pub fn MethodMixin(comptime T: type) type { return struct {
pub usingnamespace IUnknown.MethodMixin(T);
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IWMPNodeRealEstateHost_OnDesiredSizeChange(self: *const T, pSize: ?*SIZE) callconv(.Inline) HRESULT {
return @ptrCast(*const IWMPNodeRealEstateHost.VTable, self.vtable).OnDesiredSizeChange(@ptrCast(*const IWMPNodeRealEstateHost, self), pSize);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IWMPNodeRealEstateHost_OnFullScreenTransition(self: *const T, fFullScreen: BOOL) callconv(.Inline) HRESULT {
return @ptrCast(*const IWMPNodeRealEstateHost.VTable, self.vtable).OnFullScreenTransition(@ptrCast(*const IWMPNodeRealEstateHost, self), fFullScreen);
}
};}
pub usingnamespace MethodMixin(@This());
};
const IID_IWMPNodeWindowed_Value = Guid.initString("96740bfa-c56a-45d1-a3a4-762914d4ade9");
pub const IID_IWMPNodeWindowed = &IID_IWMPNodeWindowed_Value;
pub const IWMPNodeWindowed = extern struct {
pub const VTable = extern struct {
base: IUnknown.VTable,
SetOwnerWindow: fn(
self: *const IWMPNodeWindowed,
hwnd: isize,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetOwnerWindow: fn(
self: *const IWMPNodeWindowed,
phwnd: ?*isize,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
};
vtable: *const VTable,
pub fn MethodMixin(comptime T: type) type { return struct {
pub usingnamespace IUnknown.MethodMixin(T);
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IWMPNodeWindowed_SetOwnerWindow(self: *const T, hwnd: isize) callconv(.Inline) HRESULT {
return @ptrCast(*const IWMPNodeWindowed.VTable, self.vtable).SetOwnerWindow(@ptrCast(*const IWMPNodeWindowed, self), hwnd);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IWMPNodeWindowed_GetOwnerWindow(self: *const T, phwnd: ?*isize) callconv(.Inline) HRESULT {
return @ptrCast(*const IWMPNodeWindowed.VTable, self.vtable).GetOwnerWindow(@ptrCast(*const IWMPNodeWindowed, self), phwnd);
}
};}
pub usingnamespace MethodMixin(@This());
};
const IID_IWMPNodeWindowedHost_Value = Guid.initString("a300415a-54aa-4081-adbf-3b13610d8958");
pub const IID_IWMPNodeWindowedHost = &IID_IWMPNodeWindowedHost_Value;
pub const IWMPNodeWindowedHost = extern struct {
pub const VTable = extern struct {
base: IUnknown.VTable,
OnWindowMessageFromRenderer: fn(
self: *const IWMPNodeWindowedHost,
uMsg: u32,
wparam: WPARAM,
lparam: LPARAM,
plRet: ?*LRESULT,
pfHandled: ?*BOOL,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
};
vtable: *const VTable,
pub fn MethodMixin(comptime T: type) type { return struct {
pub usingnamespace IUnknown.MethodMixin(T);
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IWMPNodeWindowedHost_OnWindowMessageFromRenderer(self: *const T, uMsg: u32, wparam: WPARAM, lparam: LPARAM, plRet: ?*LRESULT, pfHandled: ?*BOOL) callconv(.Inline) HRESULT {
return @ptrCast(*const IWMPNodeWindowedHost.VTable, self.vtable).OnWindowMessageFromRenderer(@ptrCast(*const IWMPNodeWindowedHost, self), uMsg, wparam, lparam, plRet, pfHandled);
}
};}
pub usingnamespace MethodMixin(@This());
};
const IID_IWMPWindowMessageSink_Value = Guid.initString("3a0daa30-908d-4789-ba87-aed879b5c49b");
pub const IID_IWMPWindowMessageSink = &IID_IWMPWindowMessageSink_Value;
pub const IWMPWindowMessageSink = extern struct {
pub const VTable = extern struct {
base: IUnknown.VTable,
OnWindowMessage: fn(
self: *const IWMPWindowMessageSink,
uMsg: u32,
wparam: WPARAM,
lparam: LPARAM,
plRet: ?*LRESULT,
pfHandled: ?*BOOL,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
};
vtable: *const VTable,
pub fn MethodMixin(comptime T: type) type { return struct {
pub usingnamespace IUnknown.MethodMixin(T);
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IWMPWindowMessageSink_OnWindowMessage(self: *const T, uMsg: u32, wparam: WPARAM, lparam: LPARAM, plRet: ?*LRESULT, pfHandled: ?*BOOL) callconv(.Inline) HRESULT {
return @ptrCast(*const IWMPWindowMessageSink.VTable, self.vtable).OnWindowMessage(@ptrCast(*const IWMPWindowMessageSink, self), uMsg, wparam, lparam, plRet, pfHandled);
}
};}
pub usingnamespace MethodMixin(@This());
};
const IID_IWMPNodeWindowless_Value = Guid.initString("9b9199ad-780c-4eda-b816-261eba5d1575");
pub const IID_IWMPNodeWindowless = &IID_IWMPNodeWindowless_Value;
pub const IWMPNodeWindowless = extern struct {
pub const VTable = extern struct {
base: IWMPWindowMessageSink.VTable,
OnDraw: fn(
self: *const IWMPNodeWindowless,
hdc: isize,
prcDraw: ?*const RECT,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
};
vtable: *const VTable,
pub fn MethodMixin(comptime T: type) type { return struct {
pub usingnamespace IWMPWindowMessageSink.MethodMixin(T);
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IWMPNodeWindowless_OnDraw(self: *const T, hdc: isize, prcDraw: ?*const RECT) callconv(.Inline) HRESULT {
return @ptrCast(*const IWMPNodeWindowless.VTable, self.vtable).OnDraw(@ptrCast(*const IWMPNodeWindowless, self), hdc, prcDraw);
}
};}
pub usingnamespace MethodMixin(@This());
};
const IID_IWMPNodeWindowlessHost_Value = Guid.initString("be7017c6-ce34-4901-8106-770381aa6e3e");
pub const IID_IWMPNodeWindowlessHost = &IID_IWMPNodeWindowlessHost_Value;
pub const IWMPNodeWindowlessHost = extern struct {
pub const VTable = extern struct {
base: IUnknown.VTable,
InvalidateRect: fn(
self: *const IWMPNodeWindowlessHost,
prc: ?*const RECT,
fErase: BOOL,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
};
vtable: *const VTable,
pub fn MethodMixin(comptime T: type) type { return struct {
pub usingnamespace IUnknown.MethodMixin(T);
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IWMPNodeWindowlessHost_InvalidateRect(self: *const T, prc: ?*const RECT, fErase: BOOL) callconv(.Inline) HRESULT {
return @ptrCast(*const IWMPNodeWindowlessHost.VTable, self.vtable).InvalidateRect(@ptrCast(*const IWMPNodeWindowlessHost, self), prc, fErase);
}
};}
pub usingnamespace MethodMixin(@This());
};
const IID_IWMPVideoRenderConfig_Value = Guid.initString("6d6cf803-1ec0-4c8d-b3ca-f18e27282074");
pub const IID_IWMPVideoRenderConfig = &IID_IWMPVideoRenderConfig_Value;
pub const IWMPVideoRenderConfig = extern struct {
pub const VTable = extern struct {
base: IUnknown.VTable,
// TODO: this function has a "SpecialName", should Zig do anything with this?
put_presenterActivate: fn(
self: *const IWMPVideoRenderConfig,
pActivate: ?*IMFActivate,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
};
vtable: *const VTable,
pub fn MethodMixin(comptime T: type) type { return struct {
pub usingnamespace IUnknown.MethodMixin(T);
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IWMPVideoRenderConfig_put_presenterActivate(self: *const T, pActivate: ?*IMFActivate) callconv(.Inline) HRESULT {
return @ptrCast(*const IWMPVideoRenderConfig.VTable, self.vtable).put_presenterActivate(@ptrCast(*const IWMPVideoRenderConfig, self), pActivate);
}
};}
pub usingnamespace MethodMixin(@This());
};
const IID_IWMPAudioRenderConfig_Value = Guid.initString("e79c6349-5997-4ce4-917c-22a3391ec564");
pub const IID_IWMPAudioRenderConfig = &IID_IWMPAudioRenderConfig_Value;
pub const IWMPAudioRenderConfig = extern struct {
pub const VTable = extern struct {
base: IUnknown.VTable,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_audioOutputDevice: fn(
self: *const IWMPAudioRenderConfig,
pbstrOutputDevice: ?*?BSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
put_audioOutputDevice: fn(
self: *const IWMPAudioRenderConfig,
bstrOutputDevice: ?BSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
};
vtable: *const VTable,
pub fn MethodMixin(comptime T: type) type { return struct {
pub usingnamespace IUnknown.MethodMixin(T);
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IWMPAudioRenderConfig_get_audioOutputDevice(self: *const T, pbstrOutputDevice: ?*?BSTR) callconv(.Inline) HRESULT {
return @ptrCast(*const IWMPAudioRenderConfig.VTable, self.vtable).get_audioOutputDevice(@ptrCast(*const IWMPAudioRenderConfig, self), pbstrOutputDevice);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IWMPAudioRenderConfig_put_audioOutputDevice(self: *const T, bstrOutputDevice: ?BSTR) callconv(.Inline) HRESULT {
return @ptrCast(*const IWMPAudioRenderConfig.VTable, self.vtable).put_audioOutputDevice(@ptrCast(*const IWMPAudioRenderConfig, self), bstrOutputDevice);
}
};}
pub usingnamespace MethodMixin(@This());
};
const IID_IWMPRenderConfig_Value = Guid.initString("959506c1-0314-4ec5-9e61-8528db5e5478");
pub const IID_IWMPRenderConfig = &IID_IWMPRenderConfig_Value;
pub const IWMPRenderConfig = extern struct {
pub const VTable = extern struct {
base: IUnknown.VTable,
// TODO: this function has a "SpecialName", should Zig do anything with this?
put_inProcOnly: fn(
self: *const IWMPRenderConfig,
fInProc: BOOL,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_inProcOnly: fn(
self: *const IWMPRenderConfig,
pfInProc: ?*BOOL,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
};
vtable: *const VTable,
pub fn MethodMixin(comptime T: type) type { return struct {
pub usingnamespace IUnknown.MethodMixin(T);
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IWMPRenderConfig_put_inProcOnly(self: *const T, fInProc: BOOL) callconv(.Inline) HRESULT {
return @ptrCast(*const IWMPRenderConfig.VTable, self.vtable).put_inProcOnly(@ptrCast(*const IWMPRenderConfig, self), fInProc);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IWMPRenderConfig_get_inProcOnly(self: *const T, pfInProc: ?*BOOL) callconv(.Inline) HRESULT {
return @ptrCast(*const IWMPRenderConfig.VTable, self.vtable).get_inProcOnly(@ptrCast(*const IWMPRenderConfig, self), pfInProc);
}
};}
pub usingnamespace MethodMixin(@This());
};
pub const WMPServices_StreamState = enum(i32) {
Stop = 0,
Pause = 1,
Play = 2,
};
pub const WMPServices_StreamState_Stop = WMPServices_StreamState.Stop;
pub const WMPServices_StreamState_Pause = WMPServices_StreamState.Pause;
pub const WMPServices_StreamState_Play = WMPServices_StreamState.Play;
const IID_IWMPServices_Value = Guid.initString("afb6b76b-1e20-4198-83b3-191db6e0b149");
pub const IID_IWMPServices = &IID_IWMPServices_Value;
pub const IWMPServices = extern struct {
pub const VTable = extern struct {
base: IUnknown.VTable,
GetStreamTime: fn(
self: *const IWMPServices,
prt: ?*i64,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetStreamState: fn(
self: *const IWMPServices,
pState: ?*WMPServices_StreamState,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
};
vtable: *const VTable,
pub fn MethodMixin(comptime T: type) type { return struct {
pub usingnamespace IUnknown.MethodMixin(T);
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IWMPServices_GetStreamTime(self: *const T, prt: ?*i64) callconv(.Inline) HRESULT {
return @ptrCast(*const IWMPServices.VTable, self.vtable).GetStreamTime(@ptrCast(*const IWMPServices, self), prt);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IWMPServices_GetStreamState(self: *const T, pState: ?*WMPServices_StreamState) callconv(.Inline) HRESULT {
return @ptrCast(*const IWMPServices.VTable, self.vtable).GetStreamState(@ptrCast(*const IWMPServices, self), pState);
}
};}
pub usingnamespace MethodMixin(@This());
};
const IID_IWMPMediaPluginRegistrar_Value = Guid.initString("68e27045-05bd-40b2-9720-23088c78e390");
pub const IID_IWMPMediaPluginRegistrar = &IID_IWMPMediaPluginRegistrar_Value;
pub const IWMPMediaPluginRegistrar = extern struct {
pub const VTable = extern struct {
base: IUnknown.VTable,
WMPRegisterPlayerPlugin: fn(
self: *const IWMPMediaPluginRegistrar,
pwszFriendlyName: ?PWSTR,
pwszDescription: ?PWSTR,
pwszUninstallString: ?PWSTR,
dwPriority: u32,
guidPluginType: Guid,
clsid: Guid,
cMediaTypes: u32,
pMediaTypes: ?*anyopaque,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
WMPUnRegisterPlayerPlugin: fn(
self: *const IWMPMediaPluginRegistrar,
guidPluginType: Guid,
clsid: Guid,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
};
vtable: *const VTable,
pub fn MethodMixin(comptime T: type) type { return struct {
pub usingnamespace IUnknown.MethodMixin(T);
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IWMPMediaPluginRegistrar_WMPRegisterPlayerPlugin(self: *const T, pwszFriendlyName: ?PWSTR, pwszDescription: ?PWSTR, pwszUninstallString: ?PWSTR, dwPriority: u32, guidPluginType: Guid, clsid: Guid, cMediaTypes: u32, pMediaTypes: ?*anyopaque) callconv(.Inline) HRESULT {
return @ptrCast(*const IWMPMediaPluginRegistrar.VTable, self.vtable).WMPRegisterPlayerPlugin(@ptrCast(*const IWMPMediaPluginRegistrar, self), pwszFriendlyName, pwszDescription, pwszUninstallString, dwPriority, guidPluginType, clsid, cMediaTypes, pMediaTypes);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IWMPMediaPluginRegistrar_WMPUnRegisterPlayerPlugin(self: *const T, guidPluginType: Guid, clsid: Guid) callconv(.Inline) HRESULT {
return @ptrCast(*const IWMPMediaPluginRegistrar.VTable, self.vtable).WMPUnRegisterPlayerPlugin(@ptrCast(*const IWMPMediaPluginRegistrar, self), guidPluginType, clsid);
}
};}
pub usingnamespace MethodMixin(@This());
};
pub const WMPPlugin_Caps = enum(i32) {
s = 1,
};
pub const WMPPlugin_Caps_CannotConvertFormats = WMPPlugin_Caps.s;
const IID_IWMPPlugin_Value = Guid.initString("f1392a70-024c-42bb-a998-73dfdfe7d5a7");
pub const IID_IWMPPlugin = &IID_IWMPPlugin_Value;
pub const IWMPPlugin = extern struct {
pub const VTable = extern struct {
base: IUnknown.VTable,
Init: fn(
self: *const IWMPPlugin,
dwPlaybackContext: usize,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
Shutdown: fn(
self: *const IWMPPlugin,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetID: fn(
self: *const IWMPPlugin,
pGUID: ?*Guid,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetCaps: fn(
self: *const IWMPPlugin,
pdwFlags: ?*u32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
AdviseWMPServices: fn(
self: *const IWMPPlugin,
pWMPServices: ?*IWMPServices,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
UnAdviseWMPServices: fn(
self: *const IWMPPlugin,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
};
vtable: *const VTable,
pub fn MethodMixin(comptime T: type) type { return struct {
pub usingnamespace IUnknown.MethodMixin(T);
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IWMPPlugin_Init(self: *const T, dwPlaybackContext: usize) callconv(.Inline) HRESULT {
return @ptrCast(*const IWMPPlugin.VTable, self.vtable).Init(@ptrCast(*const IWMPPlugin, self), dwPlaybackContext);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IWMPPlugin_Shutdown(self: *const T) callconv(.Inline) HRESULT {
return @ptrCast(*const IWMPPlugin.VTable, self.vtable).Shutdown(@ptrCast(*const IWMPPlugin, self));
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IWMPPlugin_GetID(self: *const T, pGUID: ?*Guid) callconv(.Inline) HRESULT {
return @ptrCast(*const IWMPPlugin.VTable, self.vtable).GetID(@ptrCast(*const IWMPPlugin, self), pGUID);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IWMPPlugin_GetCaps(self: *const T, pdwFlags: ?*u32) callconv(.Inline) HRESULT {
return @ptrCast(*const IWMPPlugin.VTable, self.vtable).GetCaps(@ptrCast(*const IWMPPlugin, self), pdwFlags);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IWMPPlugin_AdviseWMPServices(self: *const T, pWMPServices: ?*IWMPServices) callconv(.Inline) HRESULT {
return @ptrCast(*const IWMPPlugin.VTable, self.vtable).AdviseWMPServices(@ptrCast(*const IWMPPlugin, self), pWMPServices);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IWMPPlugin_UnAdviseWMPServices(self: *const T) callconv(.Inline) HRESULT {
return @ptrCast(*const IWMPPlugin.VTable, self.vtable).UnAdviseWMPServices(@ptrCast(*const IWMPPlugin, self));
}
};}
pub usingnamespace MethodMixin(@This());
};
const IID_IWMPPluginEnable_Value = Guid.initString("5fca444c-7ad1-479d-a4ef-40566a5309d6");
pub const IID_IWMPPluginEnable = &IID_IWMPPluginEnable_Value;
pub const IWMPPluginEnable = extern struct {
pub const VTable = extern struct {
base: IUnknown.VTable,
SetEnable: fn(
self: *const IWMPPluginEnable,
fEnable: BOOL,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetEnable: fn(
self: *const IWMPPluginEnable,
pfEnable: ?*BOOL,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
};
vtable: *const VTable,
pub fn MethodMixin(comptime T: type) type { return struct {
pub usingnamespace IUnknown.MethodMixin(T);
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IWMPPluginEnable_SetEnable(self: *const T, fEnable: BOOL) callconv(.Inline) HRESULT {
return @ptrCast(*const IWMPPluginEnable.VTable, self.vtable).SetEnable(@ptrCast(*const IWMPPluginEnable, self), fEnable);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IWMPPluginEnable_GetEnable(self: *const T, pfEnable: ?*BOOL) callconv(.Inline) HRESULT {
return @ptrCast(*const IWMPPluginEnable.VTable, self.vtable).GetEnable(@ptrCast(*const IWMPPluginEnable, self), pfEnable);
}
};}
pub usingnamespace MethodMixin(@This());
};
const IID_IWMPGraphCreation_Value = Guid.initString("bfb377e5-c594-4369-a970-de896d5ece74");
pub const IID_IWMPGraphCreation = &IID_IWMPGraphCreation_Value;
pub const IWMPGraphCreation = extern struct {
pub const VTable = extern struct {
base: IUnknown.VTable,
GraphCreationPreRender: fn(
self: *const IWMPGraphCreation,
pFilterGraph: ?*IUnknown,
pReserved: ?*IUnknown,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GraphCreationPostRender: fn(
self: *const IWMPGraphCreation,
pFilterGraph: ?*IUnknown,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetGraphCreationFlags: fn(
self: *const IWMPGraphCreation,
pdwFlags: ?*u32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
};
vtable: *const VTable,
pub fn MethodMixin(comptime T: type) type { return struct {
pub usingnamespace IUnknown.MethodMixin(T);
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IWMPGraphCreation_GraphCreationPreRender(self: *const T, pFilterGraph: ?*IUnknown, pReserved: ?*IUnknown) callconv(.Inline) HRESULT {
return @ptrCast(*const IWMPGraphCreation.VTable, self.vtable).GraphCreationPreRender(@ptrCast(*const IWMPGraphCreation, self), pFilterGraph, pReserved);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IWMPGraphCreation_GraphCreationPostRender(self: *const T, pFilterGraph: ?*IUnknown) callconv(.Inline) HRESULT {
return @ptrCast(*const IWMPGraphCreation.VTable, self.vtable).GraphCreationPostRender(@ptrCast(*const IWMPGraphCreation, self), pFilterGraph);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IWMPGraphCreation_GetGraphCreationFlags(self: *const T, pdwFlags: ?*u32) callconv(.Inline) HRESULT {
return @ptrCast(*const IWMPGraphCreation.VTable, self.vtable).GetGraphCreationFlags(@ptrCast(*const IWMPGraphCreation, self), pdwFlags);
}
};}
pub usingnamespace MethodMixin(@This());
};
const IID_IWMPConvert_Value = Guid.initString("d683162f-57d4-4108-8373-4a9676d1c2e9");
pub const IID_IWMPConvert = &IID_IWMPConvert_Value;
pub const IWMPConvert = extern struct {
pub const VTable = extern struct {
base: IUnknown.VTable,
ConvertFile: fn(
self: *const IWMPConvert,
bstrInputFile: ?BSTR,
bstrDestinationFolder: ?BSTR,
pbstrOutputFile: ?*?BSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetErrorURL: fn(
self: *const IWMPConvert,
pbstrURL: ?*?BSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
};
vtable: *const VTable,
pub fn MethodMixin(comptime T: type) type { return struct {
pub usingnamespace IUnknown.MethodMixin(T);
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IWMPConvert_ConvertFile(self: *const T, bstrInputFile: ?BSTR, bstrDestinationFolder: ?BSTR, pbstrOutputFile: ?*?BSTR) callconv(.Inline) HRESULT {
return @ptrCast(*const IWMPConvert.VTable, self.vtable).ConvertFile(@ptrCast(*const IWMPConvert, self), bstrInputFile, bstrDestinationFolder, pbstrOutputFile);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IWMPConvert_GetErrorURL(self: *const T, pbstrURL: ?*?BSTR) callconv(.Inline) HRESULT {
return @ptrCast(*const IWMPConvert.VTable, self.vtable).GetErrorURL(@ptrCast(*const IWMPConvert, self), pbstrURL);
}
};}
pub usingnamespace MethodMixin(@This());
};
const IID_IWMPTranscodePolicy_Value = Guid.initString("b64cbac3-401c-4327-a3e8-b9feb3a8c25c");
pub const IID_IWMPTranscodePolicy = &IID_IWMPTranscodePolicy_Value;
pub const IWMPTranscodePolicy = extern struct {
pub const VTable = extern struct {
base: IUnknown.VTable,
allowTranscode: fn(
self: *const IWMPTranscodePolicy,
pvbAllow: ?*i16,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
};
vtable: *const VTable,
pub fn MethodMixin(comptime T: type) type { return struct {
pub usingnamespace IUnknown.MethodMixin(T);
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IWMPTranscodePolicy_allowTranscode(self: *const T, pvbAllow: ?*i16) callconv(.Inline) HRESULT {
return @ptrCast(*const IWMPTranscodePolicy.VTable, self.vtable).allowTranscode(@ptrCast(*const IWMPTranscodePolicy, self), pvbAllow);
}
};}
pub usingnamespace MethodMixin(@This());
};
const IID_IWMPUserEventSink_Value = Guid.initString("cfccfa72-c343-48c3-a2de-b7a4402e39f2");
pub const IID_IWMPUserEventSink = &IID_IWMPUserEventSink_Value;
pub const IWMPUserEventSink = extern struct {
pub const VTable = extern struct {
base: IUnknown.VTable,
NotifyUserEvent: fn(
self: *const IWMPUserEventSink,
EventCode: i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
};
vtable: *const VTable,
pub fn MethodMixin(comptime T: type) type { return struct {
pub usingnamespace IUnknown.MethodMixin(T);
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IWMPUserEventSink_NotifyUserEvent(self: *const T, EventCode: i32) callconv(.Inline) HRESULT {
return @ptrCast(*const IWMPUserEventSink.VTable, self.vtable).NotifyUserEvent(@ptrCast(*const IWMPUserEventSink, self), EventCode);
}
};}
pub usingnamespace MethodMixin(@This());
};
const CLSID_FeedsManager_Value = Guid.initString("faeb54c4-f66f-4806-83a0-805299f5e3ad");
pub const CLSID_FeedsManager = &CLSID_FeedsManager_Value;
const CLSID_FeedFolderWatcher_Value = Guid.initString("281001ed-7765-4cb0-84af-e9b387af01ff");
pub const CLSID_FeedFolderWatcher = &CLSID_FeedFolderWatcher_Value;
const CLSID_FeedWatcher_Value = Guid.initString("18a6737b-f433-4687-89bc-a1b4dfb9f123");
pub const CLSID_FeedWatcher = &CLSID_FeedWatcher_Value;
pub const FEEDS_BACKGROUNDSYNC_ACTION = enum(i32) {
DISABLE = 0,
ENABLE = 1,
RUNNOW = 2,
};
pub const FBSA_DISABLE = FEEDS_BACKGROUNDSYNC_ACTION.DISABLE;
pub const FBSA_ENABLE = FEEDS_BACKGROUNDSYNC_ACTION.ENABLE;
pub const FBSA_RUNNOW = FEEDS_BACKGROUNDSYNC_ACTION.RUNNOW;
pub const FEEDS_BACKGROUNDSYNC_STATUS = enum(i32) {
DISABLED = 0,
ENABLED = 1,
};
pub const FBSS_DISABLED = FEEDS_BACKGROUNDSYNC_STATUS.DISABLED;
pub const FBSS_ENABLED = FEEDS_BACKGROUNDSYNC_STATUS.ENABLED;
pub const FEEDS_EVENTS_SCOPE = enum(i32) {
ALL = 0,
SELF_ONLY = 1,
SELF_AND_CHILDREN_ONLY = 2,
};
pub const FES_ALL = FEEDS_EVENTS_SCOPE.ALL;
pub const FES_SELF_ONLY = FEEDS_EVENTS_SCOPE.SELF_ONLY;
pub const FES_SELF_AND_CHILDREN_ONLY = FEEDS_EVENTS_SCOPE.SELF_AND_CHILDREN_ONLY;
pub const FEEDS_EVENTS_MASK = enum(i32) {
OLDEREVENTS = 1,
EEDEVENTS = 2,
};
pub const FEM_FOLDEREVENTS = FEEDS_EVENTS_MASK.OLDEREVENTS;
pub const FEM_FEEDEVENTS = FEEDS_EVENTS_MASK.EEDEVENTS;
pub const FEEDS_XML_SORT_PROPERTY = enum(i32) {
NONE = 0,
PUBDATE = 1,
DOWNLOADTIME = 2,
};
pub const FXSP_NONE = FEEDS_XML_SORT_PROPERTY.NONE;
pub const FXSP_PUBDATE = FEEDS_XML_SORT_PROPERTY.PUBDATE;
pub const FXSP_DOWNLOADTIME = FEEDS_XML_SORT_PROPERTY.DOWNLOADTIME;
pub const FEEDS_XML_SORT_ORDER = enum(i32) {
NONE = 0,
ASCENDING = 1,
DESCENDING = 2,
};
pub const FXSO_NONE = FEEDS_XML_SORT_ORDER.NONE;
pub const FXSO_ASCENDING = FEEDS_XML_SORT_ORDER.ASCENDING;
pub const FXSO_DESCENDING = FEEDS_XML_SORT_ORDER.DESCENDING;
pub const FEEDS_XML_FILTER_FLAGS = enum(i32) {
ALL = 0,
UNREAD = 1,
READ = 2,
};
pub const FXFF_ALL = FEEDS_XML_FILTER_FLAGS.ALL;
pub const FXFF_UNREAD = FEEDS_XML_FILTER_FLAGS.UNREAD;
pub const FXFF_READ = FEEDS_XML_FILTER_FLAGS.READ;
pub const FEEDS_XML_INCLUDE_FLAGS = enum(i32) {
NONE = 0,
CF_EXTENSIONS = 1,
};
pub const FXIF_NONE = FEEDS_XML_INCLUDE_FLAGS.NONE;
pub const FXIF_CF_EXTENSIONS = FEEDS_XML_INCLUDE_FLAGS.CF_EXTENSIONS;
pub const FEEDS_DOWNLOAD_STATUS = enum(i32) {
NONE = 0,
PENDING = 1,
DOWNLOADING = 2,
DOWNLOADED = 3,
DOWNLOAD_FAILED = 4,
};
pub const FDS_NONE = FEEDS_DOWNLOAD_STATUS.NONE;
pub const FDS_PENDING = FEEDS_DOWNLOAD_STATUS.PENDING;
pub const FDS_DOWNLOADING = FEEDS_DOWNLOAD_STATUS.DOWNLOADING;
pub const FDS_DOWNLOADED = FEEDS_DOWNLOAD_STATUS.DOWNLOADED;
pub const FDS_DOWNLOAD_FAILED = FEEDS_DOWNLOAD_STATUS.DOWNLOAD_FAILED;
pub const FEEDS_SYNC_SETTING = enum(i32) {
DEFAULT = 0,
INTERVAL = 1,
MANUAL = 2,
SUGGESTED = 3,
};
pub const FSS_DEFAULT = FEEDS_SYNC_SETTING.DEFAULT;
pub const FSS_INTERVAL = FEEDS_SYNC_SETTING.INTERVAL;
pub const FSS_MANUAL = FEEDS_SYNC_SETTING.MANUAL;
pub const FSS_SUGGESTED = FEEDS_SYNC_SETTING.SUGGESTED;
pub const FEEDS_DOWNLOAD_ERROR = enum(i32) {
NONE = 0,
DOWNLOAD_FAILED = 1,
INVALID_FEED_FORMAT = 2,
NORMALIZATION_FAILED = 3,
PERSISTENCE_FAILED = 4,
DOWNLOAD_BLOCKED = 5,
CANCELED = 6,
UNSUPPORTED_AUTH = 7,
BACKGROUND_DOWNLOAD_DISABLED = 8,
NOT_EXIST = 9,
UNSUPPORTED_MSXML = 10,
UNSUPPORTED_DTD = 11,
DOWNLOAD_SIZE_LIMIT_EXCEEDED = 12,
ACCESS_DENIED = 13,
AUTH_FAILED = 14,
INVALID_AUTH = 15,
};
pub const FDE_NONE = FEEDS_DOWNLOAD_ERROR.NONE;
pub const FDE_DOWNLOAD_FAILED = FEEDS_DOWNLOAD_ERROR.DOWNLOAD_FAILED;
pub const FDE_INVALID_FEED_FORMAT = FEEDS_DOWNLOAD_ERROR.INVALID_FEED_FORMAT;
pub const FDE_NORMALIZATION_FAILED = FEEDS_DOWNLOAD_ERROR.NORMALIZATION_FAILED;
pub const FDE_PERSISTENCE_FAILED = FEEDS_DOWNLOAD_ERROR.PERSISTENCE_FAILED;
pub const FDE_DOWNLOAD_BLOCKED = FEEDS_DOWNLOAD_ERROR.DOWNLOAD_BLOCKED;
pub const FDE_CANCELED = FEEDS_DOWNLOAD_ERROR.CANCELED;
pub const FDE_UNSUPPORTED_AUTH = FEEDS_DOWNLOAD_ERROR.UNSUPPORTED_AUTH;
pub const FDE_BACKGROUND_DOWNLOAD_DISABLED = FEEDS_DOWNLOAD_ERROR.BACKGROUND_DOWNLOAD_DISABLED;
pub const FDE_NOT_EXIST = FEEDS_DOWNLOAD_ERROR.NOT_EXIST;
pub const FDE_UNSUPPORTED_MSXML = FEEDS_DOWNLOAD_ERROR.UNSUPPORTED_MSXML;
pub const FDE_UNSUPPORTED_DTD = FEEDS_DOWNLOAD_ERROR.UNSUPPORTED_DTD;
pub const FDE_DOWNLOAD_SIZE_LIMIT_EXCEEDED = FEEDS_DOWNLOAD_ERROR.DOWNLOAD_SIZE_LIMIT_EXCEEDED;
pub const FDE_ACCESS_DENIED = FEEDS_DOWNLOAD_ERROR.ACCESS_DENIED;
pub const FDE_AUTH_FAILED = FEEDS_DOWNLOAD_ERROR.AUTH_FAILED;
pub const FDE_INVALID_AUTH = FEEDS_DOWNLOAD_ERROR.INVALID_AUTH;
pub const FEEDS_EVENTS_ITEM_COUNT_FLAGS = enum(i32) {
READ_ITEM_COUNT_CHANGED = 1,
UNREAD_ITEM_COUNT_CHANGED = 2,
};
pub const FEICF_READ_ITEM_COUNT_CHANGED = FEEDS_EVENTS_ITEM_COUNT_FLAGS.READ_ITEM_COUNT_CHANGED;
pub const FEICF_UNREAD_ITEM_COUNT_CHANGED = FEEDS_EVENTS_ITEM_COUNT_FLAGS.UNREAD_ITEM_COUNT_CHANGED;
pub const FEEDS_ERROR_CODE = enum(i32) {
ERRORBASE = -1073479168,
// INVALIDMSXMLPROPERTY = -1073479168, this enum value conflicts with ERRORBASE
DOWNLOADSIZELIMITEXCEEDED = -1073479167,
};
pub const FEC_E_ERRORBASE = FEEDS_ERROR_CODE.ERRORBASE;
pub const FEC_E_INVALIDMSXMLPROPERTY = FEEDS_ERROR_CODE.ERRORBASE;
pub const FEC_E_DOWNLOADSIZELIMITEXCEEDED = FEEDS_ERROR_CODE.DOWNLOADSIZELIMITEXCEEDED;
const IID_IXFeedsManager_Value = Guid.initString("5357e238-fb12-4aca-a930-cab7832b84bf");
pub const IID_IXFeedsManager = &IID_IXFeedsManager_Value;
pub const IXFeedsManager = extern struct {
pub const VTable = extern struct {
base: IUnknown.VTable,
RootFolder: fn(
self: *const IXFeedsManager,
riid: ?*const Guid,
ppv: ?*?*anyopaque,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
IsSubscribed: fn(
self: *const IXFeedsManager,
pszUrl: ?[*:0]const u16,
pbSubscribed: ?*BOOL,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
ExistsFeed: fn(
self: *const IXFeedsManager,
pszPath: ?[*:0]const u16,
pbFeedExists: ?*BOOL,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetFeed: fn(
self: *const IXFeedsManager,
pszPath: ?[*:0]const u16,
riid: ?*const Guid,
ppv: ?*?*anyopaque,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetFeedByUrl: fn(
self: *const IXFeedsManager,
pszUrl: ?[*:0]const u16,
riid: ?*const Guid,
ppv: ?*?*anyopaque,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
ExistsFolder: fn(
self: *const IXFeedsManager,
pszPath: ?[*:0]const u16,
pbFolderExists: ?*BOOL,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetFolder: fn(
self: *const IXFeedsManager,
pszPath: ?[*:0]const u16,
riid: ?*const Guid,
ppv: ?*?*anyopaque,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
DeleteFeed: fn(
self: *const IXFeedsManager,
pszPath: ?[*:0]const u16,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
DeleteFolder: fn(
self: *const IXFeedsManager,
pszPath: ?[*:0]const u16,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
BackgroundSync: fn(
self: *const IXFeedsManager,
fbsa: FEEDS_BACKGROUNDSYNC_ACTION,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
BackgroundSyncStatus: fn(
self: *const IXFeedsManager,
pfbss: ?*FEEDS_BACKGROUNDSYNC_STATUS,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
DefaultInterval: fn(
self: *const IXFeedsManager,
puiInterval: ?*u32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
SetDefaultInterval: fn(
self: *const IXFeedsManager,
uiInterval: u32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
AsyncSyncAll: fn(
self: *const IXFeedsManager,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
Normalize: fn(
self: *const IXFeedsManager,
pStreamIn: ?*IStream,
ppStreamOut: ?*?*IStream,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
ItemCountLimit: fn(
self: *const IXFeedsManager,
puiItemCountLimit: ?*u32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
};
vtable: *const VTable,
pub fn MethodMixin(comptime T: type) type { return struct {
pub usingnamespace IUnknown.MethodMixin(T);
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IXFeedsManager_RootFolder(self: *const T, riid: ?*const Guid, ppv: ?*?*anyopaque) callconv(.Inline) HRESULT {
return @ptrCast(*const IXFeedsManager.VTable, self.vtable).RootFolder(@ptrCast(*const IXFeedsManager, self), riid, ppv);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IXFeedsManager_IsSubscribed(self: *const T, pszUrl: ?[*:0]const u16, pbSubscribed: ?*BOOL) callconv(.Inline) HRESULT {
return @ptrCast(*const IXFeedsManager.VTable, self.vtable).IsSubscribed(@ptrCast(*const IXFeedsManager, self), pszUrl, pbSubscribed);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IXFeedsManager_ExistsFeed(self: *const T, pszPath: ?[*:0]const u16, pbFeedExists: ?*BOOL) callconv(.Inline) HRESULT {
return @ptrCast(*const IXFeedsManager.VTable, self.vtable).ExistsFeed(@ptrCast(*const IXFeedsManager, self), pszPath, pbFeedExists);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IXFeedsManager_GetFeed(self: *const T, pszPath: ?[*:0]const u16, riid: ?*const Guid, ppv: ?*?*anyopaque) callconv(.Inline) HRESULT {
return @ptrCast(*const IXFeedsManager.VTable, self.vtable).GetFeed(@ptrCast(*const IXFeedsManager, self), pszPath, riid, ppv);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IXFeedsManager_GetFeedByUrl(self: *const T, pszUrl: ?[*:0]const u16, riid: ?*const Guid, ppv: ?*?*anyopaque) callconv(.Inline) HRESULT {
return @ptrCast(*const IXFeedsManager.VTable, self.vtable).GetFeedByUrl(@ptrCast(*const IXFeedsManager, self), pszUrl, riid, ppv);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IXFeedsManager_ExistsFolder(self: *const T, pszPath: ?[*:0]const u16, pbFolderExists: ?*BOOL) callconv(.Inline) HRESULT {
return @ptrCast(*const IXFeedsManager.VTable, self.vtable).ExistsFolder(@ptrCast(*const IXFeedsManager, self), pszPath, pbFolderExists);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IXFeedsManager_GetFolder(self: *const T, pszPath: ?[*:0]const u16, riid: ?*const Guid, ppv: ?*?*anyopaque) callconv(.Inline) HRESULT {
return @ptrCast(*const IXFeedsManager.VTable, self.vtable).GetFolder(@ptrCast(*const IXFeedsManager, self), pszPath, riid, ppv);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IXFeedsManager_DeleteFeed(self: *const T, pszPath: ?[*:0]const u16) callconv(.Inline) HRESULT {
return @ptrCast(*const IXFeedsManager.VTable, self.vtable).DeleteFeed(@ptrCast(*const IXFeedsManager, self), pszPath);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IXFeedsManager_DeleteFolder(self: *const T, pszPath: ?[*:0]const u16) callconv(.Inline) HRESULT {
return @ptrCast(*const IXFeedsManager.VTable, self.vtable).DeleteFolder(@ptrCast(*const IXFeedsManager, self), pszPath);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IXFeedsManager_BackgroundSync(self: *const T, fbsa: FEEDS_BACKGROUNDSYNC_ACTION) callconv(.Inline) HRESULT {
return @ptrCast(*const IXFeedsManager.VTable, self.vtable).BackgroundSync(@ptrCast(*const IXFeedsManager, self), fbsa);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IXFeedsManager_BackgroundSyncStatus(self: *const T, pfbss: ?*FEEDS_BACKGROUNDSYNC_STATUS) callconv(.Inline) HRESULT {
return @ptrCast(*const IXFeedsManager.VTable, self.vtable).BackgroundSyncStatus(@ptrCast(*const IXFeedsManager, self), pfbss);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IXFeedsManager_DefaultInterval(self: *const T, puiInterval: ?*u32) callconv(.Inline) HRESULT {
return @ptrCast(*const IXFeedsManager.VTable, self.vtable).DefaultInterval(@ptrCast(*const IXFeedsManager, self), puiInterval);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IXFeedsManager_SetDefaultInterval(self: *const T, uiInterval: u32) callconv(.Inline) HRESULT {
return @ptrCast(*const IXFeedsManager.VTable, self.vtable).SetDefaultInterval(@ptrCast(*const IXFeedsManager, self), uiInterval);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IXFeedsManager_AsyncSyncAll(self: *const T) callconv(.Inline) HRESULT {
return @ptrCast(*const IXFeedsManager.VTable, self.vtable).AsyncSyncAll(@ptrCast(*const IXFeedsManager, self));
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IXFeedsManager_Normalize(self: *const T, pStreamIn: ?*IStream, ppStreamOut: ?*?*IStream) callconv(.Inline) HRESULT {
return @ptrCast(*const IXFeedsManager.VTable, self.vtable).Normalize(@ptrCast(*const IXFeedsManager, self), pStreamIn, ppStreamOut);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IXFeedsManager_ItemCountLimit(self: *const T, puiItemCountLimit: ?*u32) callconv(.Inline) HRESULT {
return @ptrCast(*const IXFeedsManager.VTable, self.vtable).ItemCountLimit(@ptrCast(*const IXFeedsManager, self), puiItemCountLimit);
}
};}
pub usingnamespace MethodMixin(@This());
};
const IID_IXFeedsEnum_Value = Guid.initString("dc43a9d5-5015-4301-8c96-a47434b4d658");
pub const IID_IXFeedsEnum = &IID_IXFeedsEnum_Value;
pub const IXFeedsEnum = extern struct {
pub const VTable = extern struct {
base: IUnknown.VTable,
Count: fn(
self: *const IXFeedsEnum,
puiCount: ?*u32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
Item: fn(
self: *const IXFeedsEnum,
uiIndex: u32,
riid: ?*const Guid,
ppv: ?*?*anyopaque,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
};
vtable: *const VTable,
pub fn MethodMixin(comptime T: type) type { return struct {
pub usingnamespace IUnknown.MethodMixin(T);
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IXFeedsEnum_Count(self: *const T, puiCount: ?*u32) callconv(.Inline) HRESULT {
return @ptrCast(*const IXFeedsEnum.VTable, self.vtable).Count(@ptrCast(*const IXFeedsEnum, self), puiCount);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IXFeedsEnum_Item(self: *const T, uiIndex: u32, riid: ?*const Guid, ppv: ?*?*anyopaque) callconv(.Inline) HRESULT {
return @ptrCast(*const IXFeedsEnum.VTable, self.vtable).Item(@ptrCast(*const IXFeedsEnum, self), uiIndex, riid, ppv);
}
};}
pub usingnamespace MethodMixin(@This());
};
const IID_IXFeedFolder_Value = Guid.initString("4c963678-3a51-4b88-8531-98b90b6508f2");
pub const IID_IXFeedFolder = &IID_IXFeedFolder_Value;
pub const IXFeedFolder = extern struct {
pub const VTable = extern struct {
base: IUnknown.VTable,
Feeds: fn(
self: *const IXFeedFolder,
ppfe: ?*?*IXFeedsEnum,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
Subfolders: fn(
self: *const IXFeedFolder,
ppfe: ?*?*IXFeedsEnum,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
CreateFeed: fn(
self: *const IXFeedFolder,
pszName: ?[*:0]const u16,
pszUrl: ?[*:0]const u16,
riid: ?*const Guid,
ppv: ?*?*anyopaque,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
CreateSubfolder: fn(
self: *const IXFeedFolder,
pszName: ?[*:0]const u16,
riid: ?*const Guid,
ppv: ?*?*anyopaque,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
ExistsFeed: fn(
self: *const IXFeedFolder,
pszName: ?[*:0]const u16,
pbFeedExists: ?*BOOL,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
ExistsSubfolder: fn(
self: *const IXFeedFolder,
pszName: ?[*:0]const u16,
pbSubfolderExists: ?*BOOL,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetFeed: fn(
self: *const IXFeedFolder,
pszName: ?[*:0]const u16,
riid: ?*const Guid,
ppv: ?*?*anyopaque,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetSubfolder: fn(
self: *const IXFeedFolder,
pszName: ?[*:0]const u16,
riid: ?*const Guid,
ppv: ?*?*anyopaque,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
Delete: fn(
self: *const IXFeedFolder,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
Name: fn(
self: *const IXFeedFolder,
ppszName: ?*?PWSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
Rename: fn(
self: *const IXFeedFolder,
pszName: ?[*:0]const u16,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
Path: fn(
self: *const IXFeedFolder,
ppszPath: ?*?PWSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
Move: fn(
self: *const IXFeedFolder,
pszPath: ?[*:0]const u16,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
Parent: fn(
self: *const IXFeedFolder,
riid: ?*const Guid,
ppv: ?*?*anyopaque,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
IsRoot: fn(
self: *const IXFeedFolder,
pbIsRootFeedFolder: ?*BOOL,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetWatcher: fn(
self: *const IXFeedFolder,
scope: FEEDS_EVENTS_SCOPE,
mask: FEEDS_EVENTS_MASK,
riid: ?*const Guid,
ppv: ?*?*anyopaque,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
TotalUnreadItemCount: fn(
self: *const IXFeedFolder,
puiTotalUnreadItemCount: ?*u32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
TotalItemCount: fn(
self: *const IXFeedFolder,
puiTotalItemCount: ?*u32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
};
vtable: *const VTable,
pub fn MethodMixin(comptime T: type) type { return struct {
pub usingnamespace IUnknown.MethodMixin(T);
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IXFeedFolder_Feeds(self: *const T, ppfe: ?*?*IXFeedsEnum) callconv(.Inline) HRESULT {
return @ptrCast(*const IXFeedFolder.VTable, self.vtable).Feeds(@ptrCast(*const IXFeedFolder, self), ppfe);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IXFeedFolder_Subfolders(self: *const T, ppfe: ?*?*IXFeedsEnum) callconv(.Inline) HRESULT {
return @ptrCast(*const IXFeedFolder.VTable, self.vtable).Subfolders(@ptrCast(*const IXFeedFolder, self), ppfe);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IXFeedFolder_CreateFeed(self: *const T, pszName: ?[*:0]const u16, pszUrl: ?[*:0]const u16, riid: ?*const Guid, ppv: ?*?*anyopaque) callconv(.Inline) HRESULT {
return @ptrCast(*const IXFeedFolder.VTable, self.vtable).CreateFeed(@ptrCast(*const IXFeedFolder, self), pszName, pszUrl, riid, ppv);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IXFeedFolder_CreateSubfolder(self: *const T, pszName: ?[*:0]const u16, riid: ?*const Guid, ppv: ?*?*anyopaque) callconv(.Inline) HRESULT {
return @ptrCast(*const IXFeedFolder.VTable, self.vtable).CreateSubfolder(@ptrCast(*const IXFeedFolder, self), pszName, riid, ppv);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IXFeedFolder_ExistsFeed(self: *const T, pszName: ?[*:0]const u16, pbFeedExists: ?*BOOL) callconv(.Inline) HRESULT {
return @ptrCast(*const IXFeedFolder.VTable, self.vtable).ExistsFeed(@ptrCast(*const IXFeedFolder, self), pszName, pbFeedExists);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IXFeedFolder_ExistsSubfolder(self: *const T, pszName: ?[*:0]const u16, pbSubfolderExists: ?*BOOL) callconv(.Inline) HRESULT {
return @ptrCast(*const IXFeedFolder.VTable, self.vtable).ExistsSubfolder(@ptrCast(*const IXFeedFolder, self), pszName, pbSubfolderExists);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IXFeedFolder_GetFeed(self: *const T, pszName: ?[*:0]const u16, riid: ?*const Guid, ppv: ?*?*anyopaque) callconv(.Inline) HRESULT {
return @ptrCast(*const IXFeedFolder.VTable, self.vtable).GetFeed(@ptrCast(*const IXFeedFolder, self), pszName, riid, ppv);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IXFeedFolder_GetSubfolder(self: *const T, pszName: ?[*:0]const u16, riid: ?*const Guid, ppv: ?*?*anyopaque) callconv(.Inline) HRESULT {
return @ptrCast(*const IXFeedFolder.VTable, self.vtable).GetSubfolder(@ptrCast(*const IXFeedFolder, self), pszName, riid, ppv);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IXFeedFolder_Delete(self: *const T) callconv(.Inline) HRESULT {
return @ptrCast(*const IXFeedFolder.VTable, self.vtable).Delete(@ptrCast(*const IXFeedFolder, self));
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IXFeedFolder_Name(self: *const T, ppszName: ?*?PWSTR) callconv(.Inline) HRESULT {
return @ptrCast(*const IXFeedFolder.VTable, self.vtable).Name(@ptrCast(*const IXFeedFolder, self), ppszName);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IXFeedFolder_Rename(self: *const T, pszName: ?[*:0]const u16) callconv(.Inline) HRESULT {
return @ptrCast(*const IXFeedFolder.VTable, self.vtable).Rename(@ptrCast(*const IXFeedFolder, self), pszName);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IXFeedFolder_Path(self: *const T, ppszPath: ?*?PWSTR) callconv(.Inline) HRESULT {
return @ptrCast(*const IXFeedFolder.VTable, self.vtable).Path(@ptrCast(*const IXFeedFolder, self), ppszPath);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IXFeedFolder_Move(self: *const T, pszPath: ?[*:0]const u16) callconv(.Inline) HRESULT {
return @ptrCast(*const IXFeedFolder.VTable, self.vtable).Move(@ptrCast(*const IXFeedFolder, self), pszPath);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IXFeedFolder_Parent(self: *const T, riid: ?*const Guid, ppv: ?*?*anyopaque) callconv(.Inline) HRESULT {
return @ptrCast(*const IXFeedFolder.VTable, self.vtable).Parent(@ptrCast(*const IXFeedFolder, self), riid, ppv);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IXFeedFolder_IsRoot(self: *const T, pbIsRootFeedFolder: ?*BOOL) callconv(.Inline) HRESULT {
return @ptrCast(*const IXFeedFolder.VTable, self.vtable).IsRoot(@ptrCast(*const IXFeedFolder, self), pbIsRootFeedFolder);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IXFeedFolder_GetWatcher(self: *const T, scope: FEEDS_EVENTS_SCOPE, mask: FEEDS_EVENTS_MASK, riid: ?*const Guid, ppv: ?*?*anyopaque) callconv(.Inline) HRESULT {
return @ptrCast(*const IXFeedFolder.VTable, self.vtable).GetWatcher(@ptrCast(*const IXFeedFolder, self), scope, mask, riid, ppv);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IXFeedFolder_TotalUnreadItemCount(self: *const T, puiTotalUnreadItemCount: ?*u32) callconv(.Inline) HRESULT {
return @ptrCast(*const IXFeedFolder.VTable, self.vtable).TotalUnreadItemCount(@ptrCast(*const IXFeedFolder, self), puiTotalUnreadItemCount);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IXFeedFolder_TotalItemCount(self: *const T, puiTotalItemCount: ?*u32) callconv(.Inline) HRESULT {
return @ptrCast(*const IXFeedFolder.VTable, self.vtable).TotalItemCount(@ptrCast(*const IXFeedFolder, self), puiTotalItemCount);
}
};}
pub usingnamespace MethodMixin(@This());
};
const IID_IXFeedFolderEvents_Value = Guid.initString("7964b769-234a-4bb1-a5f4-90454c8ad07e");
pub const IID_IXFeedFolderEvents = &IID_IXFeedFolderEvents_Value;
pub const IXFeedFolderEvents = extern struct {
pub const VTable = extern struct {
base: IUnknown.VTable,
Error: fn(
self: *const IXFeedFolderEvents,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
FolderAdded: fn(
self: *const IXFeedFolderEvents,
pszPath: ?[*:0]const u16,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
FolderDeleted: fn(
self: *const IXFeedFolderEvents,
pszPath: ?[*:0]const u16,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
FolderRenamed: fn(
self: *const IXFeedFolderEvents,
pszPath: ?[*:0]const u16,
pszOldPath: ?[*:0]const u16,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
FolderMovedFrom: fn(
self: *const IXFeedFolderEvents,
pszPath: ?[*:0]const u16,
pszOldPath: ?[*:0]const u16,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
FolderMovedTo: fn(
self: *const IXFeedFolderEvents,
pszPath: ?[*:0]const u16,
pszOldPath: ?[*:0]const u16,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
FolderItemCountChanged: fn(
self: *const IXFeedFolderEvents,
pszPath: ?[*:0]const u16,
feicfFlags: i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
FeedAdded: fn(
self: *const IXFeedFolderEvents,
pszPath: ?[*:0]const u16,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
FeedDeleted: fn(
self: *const IXFeedFolderEvents,
pszPath: ?[*:0]const u16,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
FeedRenamed: fn(
self: *const IXFeedFolderEvents,
pszPath: ?[*:0]const u16,
pszOldPath: ?[*:0]const u16,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
FeedUrlChanged: fn(
self: *const IXFeedFolderEvents,
pszPath: ?[*:0]const u16,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
FeedMovedFrom: fn(
self: *const IXFeedFolderEvents,
pszPath: ?[*:0]const u16,
pszOldPath: ?[*:0]const u16,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
FeedMovedTo: fn(
self: *const IXFeedFolderEvents,
pszPath: ?[*:0]const u16,
pszOldPath: ?[*:0]const u16,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
FeedDownloading: fn(
self: *const IXFeedFolderEvents,
pszPath: ?[*:0]const u16,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
FeedDownloadCompleted: fn(
self: *const IXFeedFolderEvents,
pszPath: ?[*:0]const u16,
fde: FEEDS_DOWNLOAD_ERROR,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
FeedItemCountChanged: fn(
self: *const IXFeedFolderEvents,
pszPath: ?[*:0]const u16,
feicfFlags: i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
};
vtable: *const VTable,
pub fn MethodMixin(comptime T: type) type { return struct {
pub usingnamespace IUnknown.MethodMixin(T);
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IXFeedFolderEvents_Error(self: *const T) callconv(.Inline) HRESULT {
return @ptrCast(*const IXFeedFolderEvents.VTable, self.vtable).Error(@ptrCast(*const IXFeedFolderEvents, self));
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IXFeedFolderEvents_FolderAdded(self: *const T, pszPath: ?[*:0]const u16) callconv(.Inline) HRESULT {
return @ptrCast(*const IXFeedFolderEvents.VTable, self.vtable).FolderAdded(@ptrCast(*const IXFeedFolderEvents, self), pszPath);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IXFeedFolderEvents_FolderDeleted(self: *const T, pszPath: ?[*:0]const u16) callconv(.Inline) HRESULT {
return @ptrCast(*const IXFeedFolderEvents.VTable, self.vtable).FolderDeleted(@ptrCast(*const IXFeedFolderEvents, self), pszPath);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IXFeedFolderEvents_FolderRenamed(self: *const T, pszPath: ?[*:0]const u16, pszOldPath: ?[*:0]const u16) callconv(.Inline) HRESULT {
return @ptrCast(*const IXFeedFolderEvents.VTable, self.vtable).FolderRenamed(@ptrCast(*const IXFeedFolderEvents, self), pszPath, pszOldPath);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IXFeedFolderEvents_FolderMovedFrom(self: *const T, pszPath: ?[*:0]const u16, pszOldPath: ?[*:0]const u16) callconv(.Inline) HRESULT {
return @ptrCast(*const IXFeedFolderEvents.VTable, self.vtable).FolderMovedFrom(@ptrCast(*const IXFeedFolderEvents, self), pszPath, pszOldPath);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IXFeedFolderEvents_FolderMovedTo(self: *const T, pszPath: ?[*:0]const u16, pszOldPath: ?[*:0]const u16) callconv(.Inline) HRESULT {
return @ptrCast(*const IXFeedFolderEvents.VTable, self.vtable).FolderMovedTo(@ptrCast(*const IXFeedFolderEvents, self), pszPath, pszOldPath);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IXFeedFolderEvents_FolderItemCountChanged(self: *const T, pszPath: ?[*:0]const u16, feicfFlags: i32) callconv(.Inline) HRESULT {
return @ptrCast(*const IXFeedFolderEvents.VTable, self.vtable).FolderItemCountChanged(@ptrCast(*const IXFeedFolderEvents, self), pszPath, feicfFlags);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IXFeedFolderEvents_FeedAdded(self: *const T, pszPath: ?[*:0]const u16) callconv(.Inline) HRESULT {
return @ptrCast(*const IXFeedFolderEvents.VTable, self.vtable).FeedAdded(@ptrCast(*const IXFeedFolderEvents, self), pszPath);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IXFeedFolderEvents_FeedDeleted(self: *const T, pszPath: ?[*:0]const u16) callconv(.Inline) HRESULT {
return @ptrCast(*const IXFeedFolderEvents.VTable, self.vtable).FeedDeleted(@ptrCast(*const IXFeedFolderEvents, self), pszPath);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IXFeedFolderEvents_FeedRenamed(self: *const T, pszPath: ?[*:0]const u16, pszOldPath: ?[*:0]const u16) callconv(.Inline) HRESULT {
return @ptrCast(*const IXFeedFolderEvents.VTable, self.vtable).FeedRenamed(@ptrCast(*const IXFeedFolderEvents, self), pszPath, pszOldPath);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IXFeedFolderEvents_FeedUrlChanged(self: *const T, pszPath: ?[*:0]const u16) callconv(.Inline) HRESULT {
return @ptrCast(*const IXFeedFolderEvents.VTable, self.vtable).FeedUrlChanged(@ptrCast(*const IXFeedFolderEvents, self), pszPath);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IXFeedFolderEvents_FeedMovedFrom(self: *const T, pszPath: ?[*:0]const u16, pszOldPath: ?[*:0]const u16) callconv(.Inline) HRESULT {
return @ptrCast(*const IXFeedFolderEvents.VTable, self.vtable).FeedMovedFrom(@ptrCast(*const IXFeedFolderEvents, self), pszPath, pszOldPath);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IXFeedFolderEvents_FeedMovedTo(self: *const T, pszPath: ?[*:0]const u16, pszOldPath: ?[*:0]const u16) callconv(.Inline) HRESULT {
return @ptrCast(*const IXFeedFolderEvents.VTable, self.vtable).FeedMovedTo(@ptrCast(*const IXFeedFolderEvents, self), pszPath, pszOldPath);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IXFeedFolderEvents_FeedDownloading(self: *const T, pszPath: ?[*:0]const u16) callconv(.Inline) HRESULT {
return @ptrCast(*const IXFeedFolderEvents.VTable, self.vtable).FeedDownloading(@ptrCast(*const IXFeedFolderEvents, self), pszPath);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IXFeedFolderEvents_FeedDownloadCompleted(self: *const T, pszPath: ?[*:0]const u16, fde: FEEDS_DOWNLOAD_ERROR) callconv(.Inline) HRESULT {
return @ptrCast(*const IXFeedFolderEvents.VTable, self.vtable).FeedDownloadCompleted(@ptrCast(*const IXFeedFolderEvents, self), pszPath, fde);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IXFeedFolderEvents_FeedItemCountChanged(self: *const T, pszPath: ?[*:0]const u16, feicfFlags: i32) callconv(.Inline) HRESULT {
return @ptrCast(*const IXFeedFolderEvents.VTable, self.vtable).FeedItemCountChanged(@ptrCast(*const IXFeedFolderEvents, self), pszPath, feicfFlags);
}
};}
pub usingnamespace MethodMixin(@This());
};
const IID_IXFeed_Value = Guid.initString("a44179a4-e0f6-403b-af8d-d080f425a451");
pub const IID_IXFeed = &IID_IXFeed_Value;
pub const IXFeed = extern struct {
pub const VTable = extern struct {
base: IUnknown.VTable,
Xml: fn(
self: *const IXFeed,
uiItemCount: u32,
sortProperty: FEEDS_XML_SORT_PROPERTY,
sortOrder: FEEDS_XML_SORT_ORDER,
filterFlags: FEEDS_XML_FILTER_FLAGS,
includeFlags: FEEDS_XML_INCLUDE_FLAGS,
pps: ?*?*IStream,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
Name: fn(
self: *const IXFeed,
ppszName: ?*?PWSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
Rename: fn(
self: *const IXFeed,
pszName: ?[*:0]const u16,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
Url: fn(
self: *const IXFeed,
ppszUrl: ?*?PWSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
SetUrl: fn(
self: *const IXFeed,
pszUrl: ?[*:0]const u16,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
LocalId: fn(
self: *const IXFeed,
pguid: ?*Guid,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
Path: fn(
self: *const IXFeed,
ppszPath: ?*?PWSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
Move: fn(
self: *const IXFeed,
pszPath: ?[*:0]const u16,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
Parent: fn(
self: *const IXFeed,
riid: ?*const Guid,
ppv: ?*?*anyopaque,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
LastWriteTime: fn(
self: *const IXFeed,
pstLastWriteTime: ?*SYSTEMTIME,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
Delete: fn(
self: *const IXFeed,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
Download: fn(
self: *const IXFeed,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
AsyncDownload: fn(
self: *const IXFeed,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
CancelAsyncDownload: fn(
self: *const IXFeed,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
SyncSetting: fn(
self: *const IXFeed,
pfss: ?*FEEDS_SYNC_SETTING,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
SetSyncSetting: fn(
self: *const IXFeed,
fss: FEEDS_SYNC_SETTING,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
Interval: fn(
self: *const IXFeed,
puiInterval: ?*u32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
SetInterval: fn(
self: *const IXFeed,
uiInterval: u32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
LastDownloadTime: fn(
self: *const IXFeed,
pstLastDownloadTime: ?*SYSTEMTIME,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
LocalEnclosurePath: fn(
self: *const IXFeed,
ppszPath: ?*?PWSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
Items: fn(
self: *const IXFeed,
ppfe: ?*?*IXFeedsEnum,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetItem: fn(
self: *const IXFeed,
uiId: u32,
riid: ?*const Guid,
ppv: ?*?*anyopaque,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
MarkAllItemsRead: fn(
self: *const IXFeed,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
MaxItemCount: fn(
self: *const IXFeed,
puiMaxItemCount: ?*u32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
SetMaxItemCount: fn(
self: *const IXFeed,
uiMaxItemCount: u32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
DownloadEnclosuresAutomatically: fn(
self: *const IXFeed,
pbDownloadEnclosuresAutomatically: ?*BOOL,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
SetDownloadEnclosuresAutomatically: fn(
self: *const IXFeed,
bDownloadEnclosuresAutomatically: BOOL,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
DownloadStatus: fn(
self: *const IXFeed,
pfds: ?*FEEDS_DOWNLOAD_STATUS,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
LastDownloadError: fn(
self: *const IXFeed,
pfde: ?*FEEDS_DOWNLOAD_ERROR,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
Merge: fn(
self: *const IXFeed,
pStream: ?*IStream,
pszUrl: ?[*:0]const u16,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
DownloadUrl: fn(
self: *const IXFeed,
ppszUrl: ?*?PWSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
Title: fn(
self: *const IXFeed,
ppszTitle: ?*?PWSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
Description: fn(
self: *const IXFeed,
ppszDescription: ?*?PWSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
Link: fn(
self: *const IXFeed,
ppszHomePage: ?*?PWSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
Image: fn(
self: *const IXFeed,
ppszImageUrl: ?*?PWSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
LastBuildDate: fn(
self: *const IXFeed,
pstLastBuildDate: ?*SYSTEMTIME,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
PubDate: fn(
self: *const IXFeed,
pstPubDate: ?*SYSTEMTIME,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
Ttl: fn(
self: *const IXFeed,
puiTtl: ?*u32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
Language: fn(
self: *const IXFeed,
ppszLanguage: ?*?PWSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
Copyright: fn(
self: *const IXFeed,
ppszCopyright: ?*?PWSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
IsList: fn(
self: *const IXFeed,
pbIsList: ?*BOOL,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetWatcher: fn(
self: *const IXFeed,
scope: FEEDS_EVENTS_SCOPE,
mask: FEEDS_EVENTS_MASK,
riid: ?*const Guid,
ppv: ?*?*anyopaque,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
UnreadItemCount: fn(
self: *const IXFeed,
puiUnreadItemCount: ?*u32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
ItemCount: fn(
self: *const IXFeed,
puiItemCount: ?*u32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
};
vtable: *const VTable,
pub fn MethodMixin(comptime T: type) type { return struct {
pub usingnamespace IUnknown.MethodMixin(T);
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IXFeed_Xml(self: *const T, uiItemCount: u32, sortProperty: FEEDS_XML_SORT_PROPERTY, sortOrder: FEEDS_XML_SORT_ORDER, filterFlags: FEEDS_XML_FILTER_FLAGS, includeFlags: FEEDS_XML_INCLUDE_FLAGS, pps: ?*?*IStream) callconv(.Inline) HRESULT {
return @ptrCast(*const IXFeed.VTable, self.vtable).Xml(@ptrCast(*const IXFeed, self), uiItemCount, sortProperty, sortOrder, filterFlags, includeFlags, pps);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IXFeed_Name(self: *const T, ppszName: ?*?PWSTR) callconv(.Inline) HRESULT {
return @ptrCast(*const IXFeed.VTable, self.vtable).Name(@ptrCast(*const IXFeed, self), ppszName);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IXFeed_Rename(self: *const T, pszName: ?[*:0]const u16) callconv(.Inline) HRESULT {
return @ptrCast(*const IXFeed.VTable, self.vtable).Rename(@ptrCast(*const IXFeed, self), pszName);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IXFeed_Url(self: *const T, ppszUrl: ?*?PWSTR) callconv(.Inline) HRESULT {
return @ptrCast(*const IXFeed.VTable, self.vtable).Url(@ptrCast(*const IXFeed, self), ppszUrl);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IXFeed_SetUrl(self: *const T, pszUrl: ?[*:0]const u16) callconv(.Inline) HRESULT {
return @ptrCast(*const IXFeed.VTable, self.vtable).SetUrl(@ptrCast(*const IXFeed, self), pszUrl);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IXFeed_LocalId(self: *const T, pguid: ?*Guid) callconv(.Inline) HRESULT {
return @ptrCast(*const IXFeed.VTable, self.vtable).LocalId(@ptrCast(*const IXFeed, self), pguid);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IXFeed_Path(self: *const T, ppszPath: ?*?PWSTR) callconv(.Inline) HRESULT {
return @ptrCast(*const IXFeed.VTable, self.vtable).Path(@ptrCast(*const IXFeed, self), ppszPath);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IXFeed_Move(self: *const T, pszPath: ?[*:0]const u16) callconv(.Inline) HRESULT {
return @ptrCast(*const IXFeed.VTable, self.vtable).Move(@ptrCast(*const IXFeed, self), pszPath);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IXFeed_Parent(self: *const T, riid: ?*const Guid, ppv: ?*?*anyopaque) callconv(.Inline) HRESULT {
return @ptrCast(*const IXFeed.VTable, self.vtable).Parent(@ptrCast(*const IXFeed, self), riid, ppv);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IXFeed_LastWriteTime(self: *const T, pstLastWriteTime: ?*SYSTEMTIME) callconv(.Inline) HRESULT {
return @ptrCast(*const IXFeed.VTable, self.vtable).LastWriteTime(@ptrCast(*const IXFeed, self), pstLastWriteTime);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IXFeed_Delete(self: *const T) callconv(.Inline) HRESULT {
return @ptrCast(*const IXFeed.VTable, self.vtable).Delete(@ptrCast(*const IXFeed, self));
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IXFeed_Download(self: *const T) callconv(.Inline) HRESULT {
return @ptrCast(*const IXFeed.VTable, self.vtable).Download(@ptrCast(*const IXFeed, self));
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IXFeed_AsyncDownload(self: *const T) callconv(.Inline) HRESULT {
return @ptrCast(*const IXFeed.VTable, self.vtable).AsyncDownload(@ptrCast(*const IXFeed, self));
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IXFeed_CancelAsyncDownload(self: *const T) callconv(.Inline) HRESULT {
return @ptrCast(*const IXFeed.VTable, self.vtable).CancelAsyncDownload(@ptrCast(*const IXFeed, self));
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IXFeed_SyncSetting(self: *const T, pfss: ?*FEEDS_SYNC_SETTING) callconv(.Inline) HRESULT {
return @ptrCast(*const IXFeed.VTable, self.vtable).SyncSetting(@ptrCast(*const IXFeed, self), pfss);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IXFeed_SetSyncSetting(self: *const T, fss: FEEDS_SYNC_SETTING) callconv(.Inline) HRESULT {
return @ptrCast(*const IXFeed.VTable, self.vtable).SetSyncSetting(@ptrCast(*const IXFeed, self), fss);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IXFeed_Interval(self: *const T, puiInterval: ?*u32) callconv(.Inline) HRESULT {
return @ptrCast(*const IXFeed.VTable, self.vtable).Interval(@ptrCast(*const IXFeed, self), puiInterval);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IXFeed_SetInterval(self: *const T, uiInterval: u32) callconv(.Inline) HRESULT {
return @ptrCast(*const IXFeed.VTable, self.vtable).SetInterval(@ptrCast(*const IXFeed, self), uiInterval);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IXFeed_LastDownloadTime(self: *const T, pstLastDownloadTime: ?*SYSTEMTIME) callconv(.Inline) HRESULT {
return @ptrCast(*const IXFeed.VTable, self.vtable).LastDownloadTime(@ptrCast(*const IXFeed, self), pstLastDownloadTime);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IXFeed_LocalEnclosurePath(self: *const T, ppszPath: ?*?PWSTR) callconv(.Inline) HRESULT {
return @ptrCast(*const IXFeed.VTable, self.vtable).LocalEnclosurePath(@ptrCast(*const IXFeed, self), ppszPath);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IXFeed_Items(self: *const T, ppfe: ?*?*IXFeedsEnum) callconv(.Inline) HRESULT {
return @ptrCast(*const IXFeed.VTable, self.vtable).Items(@ptrCast(*const IXFeed, self), ppfe);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IXFeed_GetItem(self: *const T, uiId: u32, riid: ?*const Guid, ppv: ?*?*anyopaque) callconv(.Inline) HRESULT {
return @ptrCast(*const IXFeed.VTable, self.vtable).GetItem(@ptrCast(*const IXFeed, self), uiId, riid, ppv);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IXFeed_MarkAllItemsRead(self: *const T) callconv(.Inline) HRESULT {
return @ptrCast(*const IXFeed.VTable, self.vtable).MarkAllItemsRead(@ptrCast(*const IXFeed, self));
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IXFeed_MaxItemCount(self: *const T, puiMaxItemCount: ?*u32) callconv(.Inline) HRESULT {
return @ptrCast(*const IXFeed.VTable, self.vtable).MaxItemCount(@ptrCast(*const IXFeed, self), puiMaxItemCount);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IXFeed_SetMaxItemCount(self: *const T, uiMaxItemCount: u32) callconv(.Inline) HRESULT {
return @ptrCast(*const IXFeed.VTable, self.vtable).SetMaxItemCount(@ptrCast(*const IXFeed, self), uiMaxItemCount);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IXFeed_DownloadEnclosuresAutomatically(self: *const T, pbDownloadEnclosuresAutomatically: ?*BOOL) callconv(.Inline) HRESULT {
return @ptrCast(*const IXFeed.VTable, self.vtable).DownloadEnclosuresAutomatically(@ptrCast(*const IXFeed, self), pbDownloadEnclosuresAutomatically);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IXFeed_SetDownloadEnclosuresAutomatically(self: *const T, bDownloadEnclosuresAutomatically: BOOL) callconv(.Inline) HRESULT {
return @ptrCast(*const IXFeed.VTable, self.vtable).SetDownloadEnclosuresAutomatically(@ptrCast(*const IXFeed, self), bDownloadEnclosuresAutomatically);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IXFeed_DownloadStatus(self: *const T, pfds: ?*FEEDS_DOWNLOAD_STATUS) callconv(.Inline) HRESULT {
return @ptrCast(*const IXFeed.VTable, self.vtable).DownloadStatus(@ptrCast(*const IXFeed, self), pfds);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IXFeed_LastDownloadError(self: *const T, pfde: ?*FEEDS_DOWNLOAD_ERROR) callconv(.Inline) HRESULT {
return @ptrCast(*const IXFeed.VTable, self.vtable).LastDownloadError(@ptrCast(*const IXFeed, self), pfde);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IXFeed_Merge(self: *const T, pStream: ?*IStream, pszUrl: ?[*:0]const u16) callconv(.Inline) HRESULT {
return @ptrCast(*const IXFeed.VTable, self.vtable).Merge(@ptrCast(*const IXFeed, self), pStream, pszUrl);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IXFeed_DownloadUrl(self: *const T, ppszUrl: ?*?PWSTR) callconv(.Inline) HRESULT {
return @ptrCast(*const IXFeed.VTable, self.vtable).DownloadUrl(@ptrCast(*const IXFeed, self), ppszUrl);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IXFeed_Title(self: *const T, ppszTitle: ?*?PWSTR) callconv(.Inline) HRESULT {
return @ptrCast(*const IXFeed.VTable, self.vtable).Title(@ptrCast(*const IXFeed, self), ppszTitle);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IXFeed_Description(self: *const T, ppszDescription: ?*?PWSTR) callconv(.Inline) HRESULT {
return @ptrCast(*const IXFeed.VTable, self.vtable).Description(@ptrCast(*const IXFeed, self), ppszDescription);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IXFeed_Link(self: *const T, ppszHomePage: ?*?PWSTR) callconv(.Inline) HRESULT {
return @ptrCast(*const IXFeed.VTable, self.vtable).Link(@ptrCast(*const IXFeed, self), ppszHomePage);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IXFeed_Image(self: *const T, ppszImageUrl: ?*?PWSTR) callconv(.Inline) HRESULT {
return @ptrCast(*const IXFeed.VTable, self.vtable).Image(@ptrCast(*const IXFeed, self), ppszImageUrl);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IXFeed_LastBuildDate(self: *const T, pstLastBuildDate: ?*SYSTEMTIME) callconv(.Inline) HRESULT {
return @ptrCast(*const IXFeed.VTable, self.vtable).LastBuildDate(@ptrCast(*const IXFeed, self), pstLastBuildDate);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IXFeed_PubDate(self: *const T, pstPubDate: ?*SYSTEMTIME) callconv(.Inline) HRESULT {
return @ptrCast(*const IXFeed.VTable, self.vtable).PubDate(@ptrCast(*const IXFeed, self), pstPubDate);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IXFeed_Ttl(self: *const T, puiTtl: ?*u32) callconv(.Inline) HRESULT {
return @ptrCast(*const IXFeed.VTable, self.vtable).Ttl(@ptrCast(*const IXFeed, self), puiTtl);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IXFeed_Language(self: *const T, ppszLanguage: ?*?PWSTR) callconv(.Inline) HRESULT {
return @ptrCast(*const IXFeed.VTable, self.vtable).Language(@ptrCast(*const IXFeed, self), ppszLanguage);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IXFeed_Copyright(self: *const T, ppszCopyright: ?*?PWSTR) callconv(.Inline) HRESULT {
return @ptrCast(*const IXFeed.VTable, self.vtable).Copyright(@ptrCast(*const IXFeed, self), ppszCopyright);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IXFeed_IsList(self: *const T, pbIsList: ?*BOOL) callconv(.Inline) HRESULT {
return @ptrCast(*const IXFeed.VTable, self.vtable).IsList(@ptrCast(*const IXFeed, self), pbIsList);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IXFeed_GetWatcher(self: *const T, scope: FEEDS_EVENTS_SCOPE, mask: FEEDS_EVENTS_MASK, riid: ?*const Guid, ppv: ?*?*anyopaque) callconv(.Inline) HRESULT {
return @ptrCast(*const IXFeed.VTable, self.vtable).GetWatcher(@ptrCast(*const IXFeed, self), scope, mask, riid, ppv);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IXFeed_UnreadItemCount(self: *const T, puiUnreadItemCount: ?*u32) callconv(.Inline) HRESULT {
return @ptrCast(*const IXFeed.VTable, self.vtable).UnreadItemCount(@ptrCast(*const IXFeed, self), puiUnreadItemCount);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IXFeed_ItemCount(self: *const T, puiItemCount: ?*u32) callconv(.Inline) HRESULT {
return @ptrCast(*const IXFeed.VTable, self.vtable).ItemCount(@ptrCast(*const IXFeed, self), puiItemCount);
}
};}
pub usingnamespace MethodMixin(@This());
};
const IID_IXFeed2_Value = Guid.initString("ce528e77-3716-4eb7-956d-f5e37502e12a");
pub const IID_IXFeed2 = &IID_IXFeed2_Value;
pub const IXFeed2 = extern struct {
pub const VTable = extern struct {
base: IXFeed.VTable,
GetItemByEffectiveId: fn(
self: *const IXFeed2,
uiEffectiveId: u32,
riid: ?*const Guid,
ppv: ?*?*anyopaque,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
LastItemDownloadTime: fn(
self: *const IXFeed2,
pstLastItemDownloadTime: ?*SYSTEMTIME,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
Username: fn(
self: *const IXFeed2,
ppszUsername: ?*?PWSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
Password: fn(
self: *const IXFeed2,
ppszPassword: ?*?PWSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
SetCredentials: fn(
self: *const IXFeed2,
pszUsername: ?[*:0]const u16,
pszPassword: ?[*:0]const u16,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
ClearCredentials: fn(
self: *const IXFeed2,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
};
vtable: *const VTable,
pub fn MethodMixin(comptime T: type) type { return struct {
pub usingnamespace IXFeed.MethodMixin(T);
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IXFeed2_GetItemByEffectiveId(self: *const T, uiEffectiveId: u32, riid: ?*const Guid, ppv: ?*?*anyopaque) callconv(.Inline) HRESULT {
return @ptrCast(*const IXFeed2.VTable, self.vtable).GetItemByEffectiveId(@ptrCast(*const IXFeed2, self), uiEffectiveId, riid, ppv);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IXFeed2_LastItemDownloadTime(self: *const T, pstLastItemDownloadTime: ?*SYSTEMTIME) callconv(.Inline) HRESULT {
return @ptrCast(*const IXFeed2.VTable, self.vtable).LastItemDownloadTime(@ptrCast(*const IXFeed2, self), pstLastItemDownloadTime);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IXFeed2_Username(self: *const T, ppszUsername: ?*?PWSTR) callconv(.Inline) HRESULT {
return @ptrCast(*const IXFeed2.VTable, self.vtable).Username(@ptrCast(*const IXFeed2, self), ppszUsername);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IXFeed2_Password(self: *const T, ppszPassword: ?*?PWSTR) callconv(.Inline) HRESULT {
return @ptrCast(*const IXFeed2.VTable, self.vtable).Password(@ptrCast(*const IXFeed2, self), ppszPassword);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IXFeed2_SetCredentials(self: *const T, pszUsername: ?[*:0]const u16, pszPassword: ?[*:0]const u16) callconv(.Inline) HRESULT {
return @ptrCast(*const IXFeed2.VTable, self.vtable).SetCredentials(@ptrCast(*const IXFeed2, self), pszUsername, pszPassword);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IXFeed2_ClearCredentials(self: *const T) callconv(.Inline) HRESULT {
return @ptrCast(*const IXFeed2.VTable, self.vtable).ClearCredentials(@ptrCast(*const IXFeed2, self));
}
};}
pub usingnamespace MethodMixin(@This());
};
const IID_IXFeedEvents_Value = Guid.initString("1630852e-1263-465b-98e5-fe60ffec4ac2");
pub const IID_IXFeedEvents = &IID_IXFeedEvents_Value;
pub const IXFeedEvents = extern struct {
pub const VTable = extern struct {
base: IUnknown.VTable,
Error: fn(
self: *const IXFeedEvents,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
FeedDeleted: fn(
self: *const IXFeedEvents,
pszPath: ?[*:0]const u16,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
FeedRenamed: fn(
self: *const IXFeedEvents,
pszPath: ?[*:0]const u16,
pszOldPath: ?[*:0]const u16,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
FeedUrlChanged: fn(
self: *const IXFeedEvents,
pszPath: ?[*:0]const u16,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
FeedMoved: fn(
self: *const IXFeedEvents,
pszPath: ?[*:0]const u16,
pszOldPath: ?[*:0]const u16,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
FeedDownloading: fn(
self: *const IXFeedEvents,
pszPath: ?[*:0]const u16,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
FeedDownloadCompleted: fn(
self: *const IXFeedEvents,
pszPath: ?[*:0]const u16,
fde: FEEDS_DOWNLOAD_ERROR,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
FeedItemCountChanged: fn(
self: *const IXFeedEvents,
pszPath: ?[*:0]const u16,
feicfFlags: i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
};
vtable: *const VTable,
pub fn MethodMixin(comptime T: type) type { return struct {
pub usingnamespace IUnknown.MethodMixin(T);
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IXFeedEvents_Error(self: *const T) callconv(.Inline) HRESULT {
return @ptrCast(*const IXFeedEvents.VTable, self.vtable).Error(@ptrCast(*const IXFeedEvents, self));
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IXFeedEvents_FeedDeleted(self: *const T, pszPath: ?[*:0]const u16) callconv(.Inline) HRESULT {
return @ptrCast(*const IXFeedEvents.VTable, self.vtable).FeedDeleted(@ptrCast(*const IXFeedEvents, self), pszPath);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IXFeedEvents_FeedRenamed(self: *const T, pszPath: ?[*:0]const u16, pszOldPath: ?[*:0]const u16) callconv(.Inline) HRESULT {
return @ptrCast(*const IXFeedEvents.VTable, self.vtable).FeedRenamed(@ptrCast(*const IXFeedEvents, self), pszPath, pszOldPath);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IXFeedEvents_FeedUrlChanged(self: *const T, pszPath: ?[*:0]const u16) callconv(.Inline) HRESULT {
return @ptrCast(*const IXFeedEvents.VTable, self.vtable).FeedUrlChanged(@ptrCast(*const IXFeedEvents, self), pszPath);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IXFeedEvents_FeedMoved(self: *const T, pszPath: ?[*:0]const u16, pszOldPath: ?[*:0]const u16) callconv(.Inline) HRESULT {
return @ptrCast(*const IXFeedEvents.VTable, self.vtable).FeedMoved(@ptrCast(*const IXFeedEvents, self), pszPath, pszOldPath);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IXFeedEvents_FeedDownloading(self: *const T, pszPath: ?[*:0]const u16) callconv(.Inline) HRESULT {
return @ptrCast(*const IXFeedEvents.VTable, self.vtable).FeedDownloading(@ptrCast(*const IXFeedEvents, self), pszPath);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IXFeedEvents_FeedDownloadCompleted(self: *const T, pszPath: ?[*:0]const u16, fde: FEEDS_DOWNLOAD_ERROR) callconv(.Inline) HRESULT {
return @ptrCast(*const IXFeedEvents.VTable, self.vtable).FeedDownloadCompleted(@ptrCast(*const IXFeedEvents, self), pszPath, fde);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IXFeedEvents_FeedItemCountChanged(self: *const T, pszPath: ?[*:0]const u16, feicfFlags: i32) callconv(.Inline) HRESULT {
return @ptrCast(*const IXFeedEvents.VTable, self.vtable).FeedItemCountChanged(@ptrCast(*const IXFeedEvents, self), pszPath, feicfFlags);
}
};}
pub usingnamespace MethodMixin(@This());
};
const IID_IXFeedItem_Value = Guid.initString("e757b2f5-e73e-434e-a1bf-2bd7c3e60fcb");
pub const IID_IXFeedItem = &IID_IXFeedItem_Value;
pub const IXFeedItem = extern struct {
pub const VTable = extern struct {
base: IUnknown.VTable,
Xml: fn(
self: *const IXFeedItem,
fxif: FEEDS_XML_INCLUDE_FLAGS,
pps: ?*?*IStream,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
Title: fn(
self: *const IXFeedItem,
ppszTitle: ?*?PWSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
Link: fn(
self: *const IXFeedItem,
ppszUrl: ?*?PWSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
Guid: fn(
self: *const IXFeedItem,
ppszGuid: ?*?PWSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
Description: fn(
self: *const IXFeedItem,
ppszDescription: ?*?PWSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
PubDate: fn(
self: *const IXFeedItem,
pstPubDate: ?*SYSTEMTIME,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
Comments: fn(
self: *const IXFeedItem,
ppszUrl: ?*?PWSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
Author: fn(
self: *const IXFeedItem,
ppszAuthor: ?*?PWSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
Enclosure: fn(
self: *const IXFeedItem,
riid: ?*const Guid,
ppv: ?*?*anyopaque,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
IsRead: fn(
self: *const IXFeedItem,
pbIsRead: ?*BOOL,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
SetIsRead: fn(
self: *const IXFeedItem,
bIsRead: BOOL,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
LocalId: fn(
self: *const IXFeedItem,
puiId: ?*u32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
Parent: fn(
self: *const IXFeedItem,
riid: ?*const Guid,
ppv: ?*?*anyopaque,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
Delete: fn(
self: *const IXFeedItem,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
DownloadUrl: fn(
self: *const IXFeedItem,
ppszUrl: ?*?PWSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
LastDownloadTime: fn(
self: *const IXFeedItem,
pstLastDownloadTime: ?*SYSTEMTIME,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
Modified: fn(
self: *const IXFeedItem,
pstModifiedTime: ?*SYSTEMTIME,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
};
vtable: *const VTable,
pub fn MethodMixin(comptime T: type) type { return struct {
pub usingnamespace IUnknown.MethodMixin(T);
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IXFeedItem_Xml(self: *const T, fxif: FEEDS_XML_INCLUDE_FLAGS, pps: ?*?*IStream) callconv(.Inline) HRESULT {
return @ptrCast(*const IXFeedItem.VTable, self.vtable).Xml(@ptrCast(*const IXFeedItem, self), fxif, pps);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IXFeedItem_Title(self: *const T, ppszTitle: ?*?PWSTR) callconv(.Inline) HRESULT {
return @ptrCast(*const IXFeedItem.VTable, self.vtable).Title(@ptrCast(*const IXFeedItem, self), ppszTitle);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IXFeedItem_Link(self: *const T, ppszUrl: ?*?PWSTR) callconv(.Inline) HRESULT {
return @ptrCast(*const IXFeedItem.VTable, self.vtable).Link(@ptrCast(*const IXFeedItem, self), ppszUrl);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IXFeedItem_Guid(self: *const T, ppszGuid: ?*?PWSTR) callconv(.Inline) HRESULT {
return @ptrCast(*const IXFeedItem.VTable, self.vtable).Guid(@ptrCast(*const IXFeedItem, self), ppszGuid);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IXFeedItem_Description(self: *const T, ppszDescription: ?*?PWSTR) callconv(.Inline) HRESULT {
return @ptrCast(*const IXFeedItem.VTable, self.vtable).Description(@ptrCast(*const IXFeedItem, self), ppszDescription);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IXFeedItem_PubDate(self: *const T, pstPubDate: ?*SYSTEMTIME) callconv(.Inline) HRESULT {
return @ptrCast(*const IXFeedItem.VTable, self.vtable).PubDate(@ptrCast(*const IXFeedItem, self), pstPubDate);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IXFeedItem_Comments(self: *const T, ppszUrl: ?*?PWSTR) callconv(.Inline) HRESULT {
return @ptrCast(*const IXFeedItem.VTable, self.vtable).Comments(@ptrCast(*const IXFeedItem, self), ppszUrl);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IXFeedItem_Author(self: *const T, ppszAuthor: ?*?PWSTR) callconv(.Inline) HRESULT {
return @ptrCast(*const IXFeedItem.VTable, self.vtable).Author(@ptrCast(*const IXFeedItem, self), ppszAuthor);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IXFeedItem_Enclosure(self: *const T, riid: ?*const Guid, ppv: ?*?*anyopaque) callconv(.Inline) HRESULT {
return @ptrCast(*const IXFeedItem.VTable, self.vtable).Enclosure(@ptrCast(*const IXFeedItem, self), riid, ppv);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IXFeedItem_IsRead(self: *const T, pbIsRead: ?*BOOL) callconv(.Inline) HRESULT {
return @ptrCast(*const IXFeedItem.VTable, self.vtable).IsRead(@ptrCast(*const IXFeedItem, self), pbIsRead);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IXFeedItem_SetIsRead(self: *const T, bIsRead: BOOL) callconv(.Inline) HRESULT {
return @ptrCast(*const IXFeedItem.VTable, self.vtable).SetIsRead(@ptrCast(*const IXFeedItem, self), bIsRead);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IXFeedItem_LocalId(self: *const T, puiId: ?*u32) callconv(.Inline) HRESULT {
return @ptrCast(*const IXFeedItem.VTable, self.vtable).LocalId(@ptrCast(*const IXFeedItem, self), puiId);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IXFeedItem_Parent(self: *const T, riid: ?*const Guid, ppv: ?*?*anyopaque) callconv(.Inline) HRESULT {
return @ptrCast(*const IXFeedItem.VTable, self.vtable).Parent(@ptrCast(*const IXFeedItem, self), riid, ppv);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IXFeedItem_Delete(self: *const T) callconv(.Inline) HRESULT {
return @ptrCast(*const IXFeedItem.VTable, self.vtable).Delete(@ptrCast(*const IXFeedItem, self));
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IXFeedItem_DownloadUrl(self: *const T, ppszUrl: ?*?PWSTR) callconv(.Inline) HRESULT {
return @ptrCast(*const IXFeedItem.VTable, self.vtable).DownloadUrl(@ptrCast(*const IXFeedItem, self), ppszUrl);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IXFeedItem_LastDownloadTime(self: *const T, pstLastDownloadTime: ?*SYSTEMTIME) callconv(.Inline) HRESULT {
return @ptrCast(*const IXFeedItem.VTable, self.vtable).LastDownloadTime(@ptrCast(*const IXFeedItem, self), pstLastDownloadTime);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IXFeedItem_Modified(self: *const T, pstModifiedTime: ?*SYSTEMTIME) callconv(.Inline) HRESULT {
return @ptrCast(*const IXFeedItem.VTable, self.vtable).Modified(@ptrCast(*const IXFeedItem, self), pstModifiedTime);
}
};}
pub usingnamespace MethodMixin(@This());
};
const IID_IXFeedItem2_Value = Guid.initString("6cda2dc7-9013-4522-9970-2a9dd9ead5a3");
pub const IID_IXFeedItem2 = &IID_IXFeedItem2_Value;
pub const IXFeedItem2 = extern struct {
pub const VTable = extern struct {
base: IXFeedItem.VTable,
EffectiveId: fn(
self: *const IXFeedItem2,
puiEffectiveId: ?*u32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
};
vtable: *const VTable,
pub fn MethodMixin(comptime T: type) type { return struct {
pub usingnamespace IXFeedItem.MethodMixin(T);
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IXFeedItem2_EffectiveId(self: *const T, puiEffectiveId: ?*u32) callconv(.Inline) HRESULT {
return @ptrCast(*const IXFeedItem2.VTable, self.vtable).EffectiveId(@ptrCast(*const IXFeedItem2, self), puiEffectiveId);
}
};}
pub usingnamespace MethodMixin(@This());
};
const IID_IXFeedEnclosure_Value = Guid.initString("bfbfb953-644f-4792-b69c-dfaca4cbf89a");
pub const IID_IXFeedEnclosure = &IID_IXFeedEnclosure_Value;
pub const IXFeedEnclosure = extern struct {
pub const VTable = extern struct {
base: IUnknown.VTable,
Url: fn(
self: *const IXFeedEnclosure,
ppszUrl: ?*?PWSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
Type: fn(
self: *const IXFeedEnclosure,
ppszMimeType: ?*?PWSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
Length: fn(
self: *const IXFeedEnclosure,
puiLength: ?*u32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
AsyncDownload: fn(
self: *const IXFeedEnclosure,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
CancelAsyncDownload: fn(
self: *const IXFeedEnclosure,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
DownloadStatus: fn(
self: *const IXFeedEnclosure,
pfds: ?*FEEDS_DOWNLOAD_STATUS,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
LastDownloadError: fn(
self: *const IXFeedEnclosure,
pfde: ?*FEEDS_DOWNLOAD_ERROR,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
LocalPath: fn(
self: *const IXFeedEnclosure,
ppszPath: ?*?PWSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
Parent: fn(
self: *const IXFeedEnclosure,
riid: ?*const Guid,
ppv: ?*?*anyopaque,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
DownloadUrl: fn(
self: *const IXFeedEnclosure,
ppszUrl: ?*?PWSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
DownloadMimeType: fn(
self: *const IXFeedEnclosure,
ppszMimeType: ?*?PWSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
RemoveFile: fn(
self: *const IXFeedEnclosure,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
SetFile: fn(
self: *const IXFeedEnclosure,
pszDownloadUrl: ?[*:0]const u16,
pszDownloadFilePath: ?[*:0]const u16,
pszDownloadMimeType: ?[*:0]const u16,
pszEnclosureFilename: ?[*:0]const u16,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
};
vtable: *const VTable,
pub fn MethodMixin(comptime T: type) type { return struct {
pub usingnamespace IUnknown.MethodMixin(T);
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IXFeedEnclosure_Url(self: *const T, ppszUrl: ?*?PWSTR) callconv(.Inline) HRESULT {
return @ptrCast(*const IXFeedEnclosure.VTable, self.vtable).Url(@ptrCast(*const IXFeedEnclosure, self), ppszUrl);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IXFeedEnclosure_Type(self: *const T, ppszMimeType: ?*?PWSTR) callconv(.Inline) HRESULT {
return @ptrCast(*const IXFeedEnclosure.VTable, self.vtable).Type(@ptrCast(*const IXFeedEnclosure, self), ppszMimeType);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IXFeedEnclosure_Length(self: *const T, puiLength: ?*u32) callconv(.Inline) HRESULT {
return @ptrCast(*const IXFeedEnclosure.VTable, self.vtable).Length(@ptrCast(*const IXFeedEnclosure, self), puiLength);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IXFeedEnclosure_AsyncDownload(self: *const T) callconv(.Inline) HRESULT {
return @ptrCast(*const IXFeedEnclosure.VTable, self.vtable).AsyncDownload(@ptrCast(*const IXFeedEnclosure, self));
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IXFeedEnclosure_CancelAsyncDownload(self: *const T) callconv(.Inline) HRESULT {
return @ptrCast(*const IXFeedEnclosure.VTable, self.vtable).CancelAsyncDownload(@ptrCast(*const IXFeedEnclosure, self));
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IXFeedEnclosure_DownloadStatus(self: *const T, pfds: ?*FEEDS_DOWNLOAD_STATUS) callconv(.Inline) HRESULT {
return @ptrCast(*const IXFeedEnclosure.VTable, self.vtable).DownloadStatus(@ptrCast(*const IXFeedEnclosure, self), pfds);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IXFeedEnclosure_LastDownloadError(self: *const T, pfde: ?*FEEDS_DOWNLOAD_ERROR) callconv(.Inline) HRESULT {
return @ptrCast(*const IXFeedEnclosure.VTable, self.vtable).LastDownloadError(@ptrCast(*const IXFeedEnclosure, self), pfde);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IXFeedEnclosure_LocalPath(self: *const T, ppszPath: ?*?PWSTR) callconv(.Inline) HRESULT {
return @ptrCast(*const IXFeedEnclosure.VTable, self.vtable).LocalPath(@ptrCast(*const IXFeedEnclosure, self), ppszPath);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IXFeedEnclosure_Parent(self: *const T, riid: ?*const Guid, ppv: ?*?*anyopaque) callconv(.Inline) HRESULT {
return @ptrCast(*const IXFeedEnclosure.VTable, self.vtable).Parent(@ptrCast(*const IXFeedEnclosure, self), riid, ppv);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IXFeedEnclosure_DownloadUrl(self: *const T, ppszUrl: ?*?PWSTR) callconv(.Inline) HRESULT {
return @ptrCast(*const IXFeedEnclosure.VTable, self.vtable).DownloadUrl(@ptrCast(*const IXFeedEnclosure, self), ppszUrl);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IXFeedEnclosure_DownloadMimeType(self: *const T, ppszMimeType: ?*?PWSTR) callconv(.Inline) HRESULT {
return @ptrCast(*const IXFeedEnclosure.VTable, self.vtable).DownloadMimeType(@ptrCast(*const IXFeedEnclosure, self), ppszMimeType);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IXFeedEnclosure_RemoveFile(self: *const T) callconv(.Inline) HRESULT {
return @ptrCast(*const IXFeedEnclosure.VTable, self.vtable).RemoveFile(@ptrCast(*const IXFeedEnclosure, self));
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IXFeedEnclosure_SetFile(self: *const T, pszDownloadUrl: ?[*:0]const u16, pszDownloadFilePath: ?[*:0]const u16, pszDownloadMimeType: ?[*:0]const u16, pszEnclosureFilename: ?[*:0]const u16) callconv(.Inline) HRESULT {
return @ptrCast(*const IXFeedEnclosure.VTable, self.vtable).SetFile(@ptrCast(*const IXFeedEnclosure, self), pszDownloadUrl, pszDownloadFilePath, pszDownloadMimeType, pszEnclosureFilename);
}
};}
pub usingnamespace MethodMixin(@This());
};
const IID_IFeedsManager_Value = Guid.initString("a74029cc-1f1a-4906-88f0-810638d86591");
pub const IID_IFeedsManager = &IID_IFeedsManager_Value;
pub const IFeedsManager = extern struct {
pub const VTable = extern struct {
base: IDispatch.VTable,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_RootFolder: fn(
self: *const IFeedsManager,
disp: ?*?*IDispatch,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
IsSubscribed: fn(
self: *const IFeedsManager,
feedUrl: ?BSTR,
subscribed: ?*i16,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
ExistsFeed: fn(
self: *const IFeedsManager,
feedPath: ?BSTR,
exists: ?*i16,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetFeed: fn(
self: *const IFeedsManager,
feedPath: ?BSTR,
disp: ?*?*IDispatch,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetFeedByUrl: fn(
self: *const IFeedsManager,
feedUrl: ?BSTR,
disp: ?*?*IDispatch,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
ExistsFolder: fn(
self: *const IFeedsManager,
folderPath: ?BSTR,
exists: ?*i16,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetFolder: fn(
self: *const IFeedsManager,
folderPath: ?BSTR,
disp: ?*?*IDispatch,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
DeleteFeed: fn(
self: *const IFeedsManager,
feedPath: ?BSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
DeleteFolder: fn(
self: *const IFeedsManager,
folderPath: ?BSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
BackgroundSync: fn(
self: *const IFeedsManager,
action: FEEDS_BACKGROUNDSYNC_ACTION,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_BackgroundSyncStatus: fn(
self: *const IFeedsManager,
status: ?*FEEDS_BACKGROUNDSYNC_STATUS,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_DefaultInterval: fn(
self: *const IFeedsManager,
minutes: ?*i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
put_DefaultInterval: fn(
self: *const IFeedsManager,
minutes: i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
AsyncSyncAll: fn(
self: *const IFeedsManager,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
Normalize: fn(
self: *const IFeedsManager,
feedXmlIn: ?BSTR,
feedXmlOut: ?*?BSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_ItemCountLimit: fn(
self: *const IFeedsManager,
itemCountLimit: ?*i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
};
vtable: *const VTable,
pub fn MethodMixin(comptime T: type) type { return struct {
pub usingnamespace IDispatch.MethodMixin(T);
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IFeedsManager_get_RootFolder(self: *const T, disp: ?*?*IDispatch) callconv(.Inline) HRESULT {
return @ptrCast(*const IFeedsManager.VTable, self.vtable).get_RootFolder(@ptrCast(*const IFeedsManager, self), disp);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IFeedsManager_IsSubscribed(self: *const T, feedUrl: ?BSTR, subscribed: ?*i16) callconv(.Inline) HRESULT {
return @ptrCast(*const IFeedsManager.VTable, self.vtable).IsSubscribed(@ptrCast(*const IFeedsManager, self), feedUrl, subscribed);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IFeedsManager_ExistsFeed(self: *const T, feedPath: ?BSTR, exists: ?*i16) callconv(.Inline) HRESULT {
return @ptrCast(*const IFeedsManager.VTable, self.vtable).ExistsFeed(@ptrCast(*const IFeedsManager, self), feedPath, exists);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IFeedsManager_GetFeed(self: *const T, feedPath: ?BSTR, disp: ?*?*IDispatch) callconv(.Inline) HRESULT {
return @ptrCast(*const IFeedsManager.VTable, self.vtable).GetFeed(@ptrCast(*const IFeedsManager, self), feedPath, disp);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IFeedsManager_GetFeedByUrl(self: *const T, feedUrl: ?BSTR, disp: ?*?*IDispatch) callconv(.Inline) HRESULT {
return @ptrCast(*const IFeedsManager.VTable, self.vtable).GetFeedByUrl(@ptrCast(*const IFeedsManager, self), feedUrl, disp);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IFeedsManager_ExistsFolder(self: *const T, folderPath: ?BSTR, exists: ?*i16) callconv(.Inline) HRESULT {
return @ptrCast(*const IFeedsManager.VTable, self.vtable).ExistsFolder(@ptrCast(*const IFeedsManager, self), folderPath, exists);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IFeedsManager_GetFolder(self: *const T, folderPath: ?BSTR, disp: ?*?*IDispatch) callconv(.Inline) HRESULT {
return @ptrCast(*const IFeedsManager.VTable, self.vtable).GetFolder(@ptrCast(*const IFeedsManager, self), folderPath, disp);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IFeedsManager_DeleteFeed(self: *const T, feedPath: ?BSTR) callconv(.Inline) HRESULT {
return @ptrCast(*const IFeedsManager.VTable, self.vtable).DeleteFeed(@ptrCast(*const IFeedsManager, self), feedPath);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IFeedsManager_DeleteFolder(self: *const T, folderPath: ?BSTR) callconv(.Inline) HRESULT {
return @ptrCast(*const IFeedsManager.VTable, self.vtable).DeleteFolder(@ptrCast(*const IFeedsManager, self), folderPath);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IFeedsManager_BackgroundSync(self: *const T, action: FEEDS_BACKGROUNDSYNC_ACTION) callconv(.Inline) HRESULT {
return @ptrCast(*const IFeedsManager.VTable, self.vtable).BackgroundSync(@ptrCast(*const IFeedsManager, self), action);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IFeedsManager_get_BackgroundSyncStatus(self: *const T, status: ?*FEEDS_BACKGROUNDSYNC_STATUS) callconv(.Inline) HRESULT {
return @ptrCast(*const IFeedsManager.VTable, self.vtable).get_BackgroundSyncStatus(@ptrCast(*const IFeedsManager, self), status);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IFeedsManager_get_DefaultInterval(self: *const T, minutes: ?*i32) callconv(.Inline) HRESULT {
return @ptrCast(*const IFeedsManager.VTable, self.vtable).get_DefaultInterval(@ptrCast(*const IFeedsManager, self), minutes);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IFeedsManager_put_DefaultInterval(self: *const T, minutes: i32) callconv(.Inline) HRESULT {
return @ptrCast(*const IFeedsManager.VTable, self.vtable).put_DefaultInterval(@ptrCast(*const IFeedsManager, self), minutes);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IFeedsManager_AsyncSyncAll(self: *const T) callconv(.Inline) HRESULT {
return @ptrCast(*const IFeedsManager.VTable, self.vtable).AsyncSyncAll(@ptrCast(*const IFeedsManager, self));
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IFeedsManager_Normalize(self: *const T, feedXmlIn: ?BSTR, feedXmlOut: ?*?BSTR) callconv(.Inline) HRESULT {
return @ptrCast(*const IFeedsManager.VTable, self.vtable).Normalize(@ptrCast(*const IFeedsManager, self), feedXmlIn, feedXmlOut);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IFeedsManager_get_ItemCountLimit(self: *const T, itemCountLimit: ?*i32) callconv(.Inline) HRESULT {
return @ptrCast(*const IFeedsManager.VTable, self.vtable).get_ItemCountLimit(@ptrCast(*const IFeedsManager, self), itemCountLimit);
}
};}
pub usingnamespace MethodMixin(@This());
};
const IID_IFeedsEnum_Value = Guid.initString("e3cd0028-2eed-4c60-8fae-a3225309a836");
pub const IID_IFeedsEnum = &IID_IFeedsEnum_Value;
pub const IFeedsEnum = extern struct {
pub const VTable = extern struct {
base: IDispatch.VTable,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_Count: fn(
self: *const IFeedsEnum,
count: ?*i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
Item: fn(
self: *const IFeedsEnum,
index: i32,
disp: ?*?*IDispatch,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get__NewEnum: fn(
self: *const IFeedsEnum,
enumVar: ?*?*IEnumVARIANT,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
};
vtable: *const VTable,
pub fn MethodMixin(comptime T: type) type { return struct {
pub usingnamespace IDispatch.MethodMixin(T);
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IFeedsEnum_get_Count(self: *const T, count: ?*i32) callconv(.Inline) HRESULT {
return @ptrCast(*const IFeedsEnum.VTable, self.vtable).get_Count(@ptrCast(*const IFeedsEnum, self), count);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IFeedsEnum_Item(self: *const T, index: i32, disp: ?*?*IDispatch) callconv(.Inline) HRESULT {
return @ptrCast(*const IFeedsEnum.VTable, self.vtable).Item(@ptrCast(*const IFeedsEnum, self), index, disp);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IFeedsEnum_get__NewEnum(self: *const T, enumVar: ?*?*IEnumVARIANT) callconv(.Inline) HRESULT {
return @ptrCast(*const IFeedsEnum.VTable, self.vtable).get__NewEnum(@ptrCast(*const IFeedsEnum, self), enumVar);
}
};}
pub usingnamespace MethodMixin(@This());
};
const IID_IFeedFolder_Value = Guid.initString("81f04ad1-4194-4d7d-86d6-11813cec163c");
pub const IID_IFeedFolder = &IID_IFeedFolder_Value;
pub const IFeedFolder = extern struct {
pub const VTable = extern struct {
base: IDispatch.VTable,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_Feeds: fn(
self: *const IFeedFolder,
disp: ?*?*IDispatch,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_Subfolders: fn(
self: *const IFeedFolder,
disp: ?*?*IDispatch,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
CreateFeed: fn(
self: *const IFeedFolder,
feedName: ?BSTR,
feedUrl: ?BSTR,
disp: ?*?*IDispatch,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
CreateSubfolder: fn(
self: *const IFeedFolder,
folderName: ?BSTR,
disp: ?*?*IDispatch,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
ExistsFeed: fn(
self: *const IFeedFolder,
feedName: ?BSTR,
exists: ?*i16,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetFeed: fn(
self: *const IFeedFolder,
feedName: ?BSTR,
disp: ?*?*IDispatch,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
ExistsSubfolder: fn(
self: *const IFeedFolder,
folderName: ?BSTR,
exists: ?*i16,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetSubfolder: fn(
self: *const IFeedFolder,
folderName: ?BSTR,
disp: ?*?*IDispatch,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
Delete: fn(
self: *const IFeedFolder,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_Name: fn(
self: *const IFeedFolder,
folderName: ?*?BSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
Rename: fn(
self: *const IFeedFolder,
folderName: ?BSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_Path: fn(
self: *const IFeedFolder,
folderPath: ?*?BSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
Move: fn(
self: *const IFeedFolder,
newParentPath: ?BSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_Parent: fn(
self: *const IFeedFolder,
disp: ?*?*IDispatch,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_IsRoot: fn(
self: *const IFeedFolder,
isRoot: ?*i16,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_TotalUnreadItemCount: fn(
self: *const IFeedFolder,
count: ?*i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_TotalItemCount: fn(
self: *const IFeedFolder,
count: ?*i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetWatcher: fn(
self: *const IFeedFolder,
scope: FEEDS_EVENTS_SCOPE,
mask: FEEDS_EVENTS_MASK,
disp: ?*?*IDispatch,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
};
vtable: *const VTable,
pub fn MethodMixin(comptime T: type) type { return struct {
pub usingnamespace IDispatch.MethodMixin(T);
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IFeedFolder_get_Feeds(self: *const T, disp: ?*?*IDispatch) callconv(.Inline) HRESULT {
return @ptrCast(*const IFeedFolder.VTable, self.vtable).get_Feeds(@ptrCast(*const IFeedFolder, self), disp);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IFeedFolder_get_Subfolders(self: *const T, disp: ?*?*IDispatch) callconv(.Inline) HRESULT {
return @ptrCast(*const IFeedFolder.VTable, self.vtable).get_Subfolders(@ptrCast(*const IFeedFolder, self), disp);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IFeedFolder_CreateFeed(self: *const T, feedName: ?BSTR, feedUrl: ?BSTR, disp: ?*?*IDispatch) callconv(.Inline) HRESULT {
return @ptrCast(*const IFeedFolder.VTable, self.vtable).CreateFeed(@ptrCast(*const IFeedFolder, self), feedName, feedUrl, disp);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IFeedFolder_CreateSubfolder(self: *const T, folderName: ?BSTR, disp: ?*?*IDispatch) callconv(.Inline) HRESULT {
return @ptrCast(*const IFeedFolder.VTable, self.vtable).CreateSubfolder(@ptrCast(*const IFeedFolder, self), folderName, disp);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IFeedFolder_ExistsFeed(self: *const T, feedName: ?BSTR, exists: ?*i16) callconv(.Inline) HRESULT {
return @ptrCast(*const IFeedFolder.VTable, self.vtable).ExistsFeed(@ptrCast(*const IFeedFolder, self), feedName, exists);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IFeedFolder_GetFeed(self: *const T, feedName: ?BSTR, disp: ?*?*IDispatch) callconv(.Inline) HRESULT {
return @ptrCast(*const IFeedFolder.VTable, self.vtable).GetFeed(@ptrCast(*const IFeedFolder, self), feedName, disp);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IFeedFolder_ExistsSubfolder(self: *const T, folderName: ?BSTR, exists: ?*i16) callconv(.Inline) HRESULT {
return @ptrCast(*const IFeedFolder.VTable, self.vtable).ExistsSubfolder(@ptrCast(*const IFeedFolder, self), folderName, exists);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IFeedFolder_GetSubfolder(self: *const T, folderName: ?BSTR, disp: ?*?*IDispatch) callconv(.Inline) HRESULT {
return @ptrCast(*const IFeedFolder.VTable, self.vtable).GetSubfolder(@ptrCast(*const IFeedFolder, self), folderName, disp);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IFeedFolder_Delete(self: *const T) callconv(.Inline) HRESULT {
return @ptrCast(*const IFeedFolder.VTable, self.vtable).Delete(@ptrCast(*const IFeedFolder, self));
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IFeedFolder_get_Name(self: *const T, folderName: ?*?BSTR) callconv(.Inline) HRESULT {
return @ptrCast(*const IFeedFolder.VTable, self.vtable).get_Name(@ptrCast(*const IFeedFolder, self), folderName);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IFeedFolder_Rename(self: *const T, folderName: ?BSTR) callconv(.Inline) HRESULT {
return @ptrCast(*const IFeedFolder.VTable, self.vtable).Rename(@ptrCast(*const IFeedFolder, self), folderName);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IFeedFolder_get_Path(self: *const T, folderPath: ?*?BSTR) callconv(.Inline) HRESULT {
return @ptrCast(*const IFeedFolder.VTable, self.vtable).get_Path(@ptrCast(*const IFeedFolder, self), folderPath);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IFeedFolder_Move(self: *const T, newParentPath: ?BSTR) callconv(.Inline) HRESULT {
return @ptrCast(*const IFeedFolder.VTable, self.vtable).Move(@ptrCast(*const IFeedFolder, self), newParentPath);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IFeedFolder_get_Parent(self: *const T, disp: ?*?*IDispatch) callconv(.Inline) HRESULT {
return @ptrCast(*const IFeedFolder.VTable, self.vtable).get_Parent(@ptrCast(*const IFeedFolder, self), disp);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IFeedFolder_get_IsRoot(self: *const T, isRoot: ?*i16) callconv(.Inline) HRESULT {
return @ptrCast(*const IFeedFolder.VTable, self.vtable).get_IsRoot(@ptrCast(*const IFeedFolder, self), isRoot);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IFeedFolder_get_TotalUnreadItemCount(self: *const T, count: ?*i32) callconv(.Inline) HRESULT {
return @ptrCast(*const IFeedFolder.VTable, self.vtable).get_TotalUnreadItemCount(@ptrCast(*const IFeedFolder, self), count);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IFeedFolder_get_TotalItemCount(self: *const T, count: ?*i32) callconv(.Inline) HRESULT {
return @ptrCast(*const IFeedFolder.VTable, self.vtable).get_TotalItemCount(@ptrCast(*const IFeedFolder, self), count);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IFeedFolder_GetWatcher(self: *const T, scope: FEEDS_EVENTS_SCOPE, mask: FEEDS_EVENTS_MASK, disp: ?*?*IDispatch) callconv(.Inline) HRESULT {
return @ptrCast(*const IFeedFolder.VTable, self.vtable).GetWatcher(@ptrCast(*const IFeedFolder, self), scope, mask, disp);
}
};}
pub usingnamespace MethodMixin(@This());
};
const IID_IFeedFolderEvents_Value = Guid.initString("20a59fa6-a844-4630-9e98-175f70b4d55b");
pub const IID_IFeedFolderEvents = &IID_IFeedFolderEvents_Value;
pub const IFeedFolderEvents = extern struct {
pub const VTable = extern struct {
base: IDispatch.VTable,
Error: fn(
self: *const IFeedFolderEvents,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
FolderAdded: fn(
self: *const IFeedFolderEvents,
path: ?BSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
FolderDeleted: fn(
self: *const IFeedFolderEvents,
path: ?BSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
FolderRenamed: fn(
self: *const IFeedFolderEvents,
path: ?BSTR,
oldPath: ?BSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
FolderMovedFrom: fn(
self: *const IFeedFolderEvents,
path: ?BSTR,
oldPath: ?BSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
FolderMovedTo: fn(
self: *const IFeedFolderEvents,
path: ?BSTR,
oldPath: ?BSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
FolderItemCountChanged: fn(
self: *const IFeedFolderEvents,
path: ?BSTR,
itemCountType: i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
FeedAdded: fn(
self: *const IFeedFolderEvents,
path: ?BSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
FeedDeleted: fn(
self: *const IFeedFolderEvents,
path: ?BSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
FeedRenamed: fn(
self: *const IFeedFolderEvents,
path: ?BSTR,
oldPath: ?BSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
FeedUrlChanged: fn(
self: *const IFeedFolderEvents,
path: ?BSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
FeedMovedFrom: fn(
self: *const IFeedFolderEvents,
path: ?BSTR,
oldPath: ?BSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
FeedMovedTo: fn(
self: *const IFeedFolderEvents,
path: ?BSTR,
oldPath: ?BSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
FeedDownloading: fn(
self: *const IFeedFolderEvents,
path: ?BSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
FeedDownloadCompleted: fn(
self: *const IFeedFolderEvents,
path: ?BSTR,
@"error": FEEDS_DOWNLOAD_ERROR,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
FeedItemCountChanged: fn(
self: *const IFeedFolderEvents,
path: ?BSTR,
itemCountType: i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
};
vtable: *const VTable,
pub fn MethodMixin(comptime T: type) type { return struct {
pub usingnamespace IDispatch.MethodMixin(T);
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IFeedFolderEvents_Error(self: *const T) callconv(.Inline) HRESULT {
return @ptrCast(*const IFeedFolderEvents.VTable, self.vtable).Error(@ptrCast(*const IFeedFolderEvents, self));
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IFeedFolderEvents_FolderAdded(self: *const T, path: ?BSTR) callconv(.Inline) HRESULT {
return @ptrCast(*const IFeedFolderEvents.VTable, self.vtable).FolderAdded(@ptrCast(*const IFeedFolderEvents, self), path);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IFeedFolderEvents_FolderDeleted(self: *const T, path: ?BSTR) callconv(.Inline) HRESULT {
return @ptrCast(*const IFeedFolderEvents.VTable, self.vtable).FolderDeleted(@ptrCast(*const IFeedFolderEvents, self), path);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IFeedFolderEvents_FolderRenamed(self: *const T, path: ?BSTR, oldPath: ?BSTR) callconv(.Inline) HRESULT {
return @ptrCast(*const IFeedFolderEvents.VTable, self.vtable).FolderRenamed(@ptrCast(*const IFeedFolderEvents, self), path, oldPath);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IFeedFolderEvents_FolderMovedFrom(self: *const T, path: ?BSTR, oldPath: ?BSTR) callconv(.Inline) HRESULT {
return @ptrCast(*const IFeedFolderEvents.VTable, self.vtable).FolderMovedFrom(@ptrCast(*const IFeedFolderEvents, self), path, oldPath);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IFeedFolderEvents_FolderMovedTo(self: *const T, path: ?BSTR, oldPath: ?BSTR) callconv(.Inline) HRESULT {
return @ptrCast(*const IFeedFolderEvents.VTable, self.vtable).FolderMovedTo(@ptrCast(*const IFeedFolderEvents, self), path, oldPath);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IFeedFolderEvents_FolderItemCountChanged(self: *const T, path: ?BSTR, itemCountType: i32) callconv(.Inline) HRESULT {
return @ptrCast(*const IFeedFolderEvents.VTable, self.vtable).FolderItemCountChanged(@ptrCast(*const IFeedFolderEvents, self), path, itemCountType);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IFeedFolderEvents_FeedAdded(self: *const T, path: ?BSTR) callconv(.Inline) HRESULT {
return @ptrCast(*const IFeedFolderEvents.VTable, self.vtable).FeedAdded(@ptrCast(*const IFeedFolderEvents, self), path);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IFeedFolderEvents_FeedDeleted(self: *const T, path: ?BSTR) callconv(.Inline) HRESULT {
return @ptrCast(*const IFeedFolderEvents.VTable, self.vtable).FeedDeleted(@ptrCast(*const IFeedFolderEvents, self), path);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IFeedFolderEvents_FeedRenamed(self: *const T, path: ?BSTR, oldPath: ?BSTR) callconv(.Inline) HRESULT {
return @ptrCast(*const IFeedFolderEvents.VTable, self.vtable).FeedRenamed(@ptrCast(*const IFeedFolderEvents, self), path, oldPath);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IFeedFolderEvents_FeedUrlChanged(self: *const T, path: ?BSTR) callconv(.Inline) HRESULT {
return @ptrCast(*const IFeedFolderEvents.VTable, self.vtable).FeedUrlChanged(@ptrCast(*const IFeedFolderEvents, self), path);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IFeedFolderEvents_FeedMovedFrom(self: *const T, path: ?BSTR, oldPath: ?BSTR) callconv(.Inline) HRESULT {
return @ptrCast(*const IFeedFolderEvents.VTable, self.vtable).FeedMovedFrom(@ptrCast(*const IFeedFolderEvents, self), path, oldPath);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IFeedFolderEvents_FeedMovedTo(self: *const T, path: ?BSTR, oldPath: ?BSTR) callconv(.Inline) HRESULT {
return @ptrCast(*const IFeedFolderEvents.VTable, self.vtable).FeedMovedTo(@ptrCast(*const IFeedFolderEvents, self), path, oldPath);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IFeedFolderEvents_FeedDownloading(self: *const T, path: ?BSTR) callconv(.Inline) HRESULT {
return @ptrCast(*const IFeedFolderEvents.VTable, self.vtable).FeedDownloading(@ptrCast(*const IFeedFolderEvents, self), path);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IFeedFolderEvents_FeedDownloadCompleted(self: *const T, path: ?BSTR, @"error": FEEDS_DOWNLOAD_ERROR) callconv(.Inline) HRESULT {
return @ptrCast(*const IFeedFolderEvents.VTable, self.vtable).FeedDownloadCompleted(@ptrCast(*const IFeedFolderEvents, self), path, @"error");
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IFeedFolderEvents_FeedItemCountChanged(self: *const T, path: ?BSTR, itemCountType: i32) callconv(.Inline) HRESULT {
return @ptrCast(*const IFeedFolderEvents.VTable, self.vtable).FeedItemCountChanged(@ptrCast(*const IFeedFolderEvents, self), path, itemCountType);
}
};}
pub usingnamespace MethodMixin(@This());
};
const IID_IFeed_Value = Guid.initString("f7f915d8-2ede-42bc-98e7-a5d05063a757");
pub const IID_IFeed = &IID_IFeed_Value;
pub const IFeed = extern struct {
pub const VTable = extern struct {
base: IDispatch.VTable,
Xml: fn(
self: *const IFeed,
count: i32,
sortProperty: FEEDS_XML_SORT_PROPERTY,
sortOrder: FEEDS_XML_SORT_ORDER,
filterFlags: FEEDS_XML_FILTER_FLAGS,
includeFlags: FEEDS_XML_INCLUDE_FLAGS,
xml: ?*?BSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_Name: fn(
self: *const IFeed,
name: ?*?BSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
Rename: fn(
self: *const IFeed,
name: ?BSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_Url: fn(
self: *const IFeed,
feedUrl: ?*?BSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
put_Url: fn(
self: *const IFeed,
feedUrl: ?BSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_LocalId: fn(
self: *const IFeed,
feedGuid: ?*?BSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_Path: fn(
self: *const IFeed,
path: ?*?BSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
Move: fn(
self: *const IFeed,
newParentPath: ?BSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_Parent: fn(
self: *const IFeed,
disp: ?*?*IDispatch,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_LastWriteTime: fn(
self: *const IFeed,
lastWrite: ?*f64,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
Delete: fn(
self: *const IFeed,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
Download: fn(
self: *const IFeed,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
AsyncDownload: fn(
self: *const IFeed,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
CancelAsyncDownload: fn(
self: *const IFeed,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_SyncSetting: fn(
self: *const IFeed,
syncSetting: ?*FEEDS_SYNC_SETTING,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
put_SyncSetting: fn(
self: *const IFeed,
syncSetting: FEEDS_SYNC_SETTING,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_Interval: fn(
self: *const IFeed,
minutes: ?*i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
put_Interval: fn(
self: *const IFeed,
minutes: i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_LastDownloadTime: fn(
self: *const IFeed,
lastDownload: ?*f64,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_LocalEnclosurePath: fn(
self: *const IFeed,
path: ?*?BSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_Items: fn(
self: *const IFeed,
disp: ?*?*IDispatch,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetItem: fn(
self: *const IFeed,
itemId: i32,
disp: ?*?*IDispatch,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_Title: fn(
self: *const IFeed,
title: ?*?BSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_Description: fn(
self: *const IFeed,
description: ?*?BSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_Link: fn(
self: *const IFeed,
homePage: ?*?BSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_Image: fn(
self: *const IFeed,
imageUrl: ?*?BSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_LastBuildDate: fn(
self: *const IFeed,
lastBuildDate: ?*f64,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_PubDate: fn(
self: *const IFeed,
lastPopulateDate: ?*f64,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_Ttl: fn(
self: *const IFeed,
ttl: ?*i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_Language: fn(
self: *const IFeed,
language: ?*?BSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_Copyright: fn(
self: *const IFeed,
copyright: ?*?BSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_MaxItemCount: fn(
self: *const IFeed,
count: ?*i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
put_MaxItemCount: fn(
self: *const IFeed,
count: i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_DownloadEnclosuresAutomatically: fn(
self: *const IFeed,
downloadEnclosuresAutomatically: ?*i16,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
put_DownloadEnclosuresAutomatically: fn(
self: *const IFeed,
downloadEnclosuresAutomatically: i16,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_DownloadStatus: fn(
self: *const IFeed,
status: ?*FEEDS_DOWNLOAD_STATUS,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_LastDownloadError: fn(
self: *const IFeed,
@"error": ?*FEEDS_DOWNLOAD_ERROR,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
Merge: fn(
self: *const IFeed,
feedXml: ?BSTR,
feedUrl: ?BSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_DownloadUrl: fn(
self: *const IFeed,
feedUrl: ?*?BSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_IsList: fn(
self: *const IFeed,
isList: ?*i16,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
MarkAllItemsRead: fn(
self: *const IFeed,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetWatcher: fn(
self: *const IFeed,
scope: FEEDS_EVENTS_SCOPE,
mask: FEEDS_EVENTS_MASK,
disp: ?*?*IDispatch,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_UnreadItemCount: fn(
self: *const IFeed,
count: ?*i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_ItemCount: fn(
self: *const IFeed,
count: ?*i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
};
vtable: *const VTable,
pub fn MethodMixin(comptime T: type) type { return struct {
pub usingnamespace IDispatch.MethodMixin(T);
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IFeed_Xml(self: *const T, count: i32, sortProperty: FEEDS_XML_SORT_PROPERTY, sortOrder: FEEDS_XML_SORT_ORDER, filterFlags: FEEDS_XML_FILTER_FLAGS, includeFlags: FEEDS_XML_INCLUDE_FLAGS, xml: ?*?BSTR) callconv(.Inline) HRESULT {
return @ptrCast(*const IFeed.VTable, self.vtable).Xml(@ptrCast(*const IFeed, self), count, sortProperty, sortOrder, filterFlags, includeFlags, xml);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IFeed_get_Name(self: *const T, name: ?*?BSTR) callconv(.Inline) HRESULT {
return @ptrCast(*const IFeed.VTable, self.vtable).get_Name(@ptrCast(*const IFeed, self), name);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IFeed_Rename(self: *const T, name: ?BSTR) callconv(.Inline) HRESULT {
return @ptrCast(*const IFeed.VTable, self.vtable).Rename(@ptrCast(*const IFeed, self), name);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IFeed_get_Url(self: *const T, feedUrl: ?*?BSTR) callconv(.Inline) HRESULT {
return @ptrCast(*const IFeed.VTable, self.vtable).get_Url(@ptrCast(*const IFeed, self), feedUrl);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IFeed_put_Url(self: *const T, feedUrl: ?BSTR) callconv(.Inline) HRESULT {
return @ptrCast(*const IFeed.VTable, self.vtable).put_Url(@ptrCast(*const IFeed, self), feedUrl);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IFeed_get_LocalId(self: *const T, feedGuid: ?*?BSTR) callconv(.Inline) HRESULT {
return @ptrCast(*const IFeed.VTable, self.vtable).get_LocalId(@ptrCast(*const IFeed, self), feedGuid);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IFeed_get_Path(self: *const T, path: ?*?BSTR) callconv(.Inline) HRESULT {
return @ptrCast(*const IFeed.VTable, self.vtable).get_Path(@ptrCast(*const IFeed, self), path);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IFeed_Move(self: *const T, newParentPath: ?BSTR) callconv(.Inline) HRESULT {
return @ptrCast(*const IFeed.VTable, self.vtable).Move(@ptrCast(*const IFeed, self), newParentPath);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IFeed_get_Parent(self: *const T, disp: ?*?*IDispatch) callconv(.Inline) HRESULT {
return @ptrCast(*const IFeed.VTable, self.vtable).get_Parent(@ptrCast(*const IFeed, self), disp);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IFeed_get_LastWriteTime(self: *const T, lastWrite: ?*f64) callconv(.Inline) HRESULT {
return @ptrCast(*const IFeed.VTable, self.vtable).get_LastWriteTime(@ptrCast(*const IFeed, self), lastWrite);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IFeed_Delete(self: *const T) callconv(.Inline) HRESULT {
return @ptrCast(*const IFeed.VTable, self.vtable).Delete(@ptrCast(*const IFeed, self));
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IFeed_Download(self: *const T) callconv(.Inline) HRESULT {
return @ptrCast(*const IFeed.VTable, self.vtable).Download(@ptrCast(*const IFeed, self));
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IFeed_AsyncDownload(self: *const T) callconv(.Inline) HRESULT {
return @ptrCast(*const IFeed.VTable, self.vtable).AsyncDownload(@ptrCast(*const IFeed, self));
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IFeed_CancelAsyncDownload(self: *const T) callconv(.Inline) HRESULT {
return @ptrCast(*const IFeed.VTable, self.vtable).CancelAsyncDownload(@ptrCast(*const IFeed, self));
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IFeed_get_SyncSetting(self: *const T, syncSetting: ?*FEEDS_SYNC_SETTING) callconv(.Inline) HRESULT {
return @ptrCast(*const IFeed.VTable, self.vtable).get_SyncSetting(@ptrCast(*const IFeed, self), syncSetting);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IFeed_put_SyncSetting(self: *const T, syncSetting: FEEDS_SYNC_SETTING) callconv(.Inline) HRESULT {
return @ptrCast(*const IFeed.VTable, self.vtable).put_SyncSetting(@ptrCast(*const IFeed, self), syncSetting);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IFeed_get_Interval(self: *const T, minutes: ?*i32) callconv(.Inline) HRESULT {
return @ptrCast(*const IFeed.VTable, self.vtable).get_Interval(@ptrCast(*const IFeed, self), minutes);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IFeed_put_Interval(self: *const T, minutes: i32) callconv(.Inline) HRESULT {
return @ptrCast(*const IFeed.VTable, self.vtable).put_Interval(@ptrCast(*const IFeed, self), minutes);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IFeed_get_LastDownloadTime(self: *const T, lastDownload: ?*f64) callconv(.Inline) HRESULT {
return @ptrCast(*const IFeed.VTable, self.vtable).get_LastDownloadTime(@ptrCast(*const IFeed, self), lastDownload);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IFeed_get_LocalEnclosurePath(self: *const T, path: ?*?BSTR) callconv(.Inline) HRESULT {
return @ptrCast(*const IFeed.VTable, self.vtable).get_LocalEnclosurePath(@ptrCast(*const IFeed, self), path);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IFeed_get_Items(self: *const T, disp: ?*?*IDispatch) callconv(.Inline) HRESULT {
return @ptrCast(*const IFeed.VTable, self.vtable).get_Items(@ptrCast(*const IFeed, self), disp);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IFeed_GetItem(self: *const T, itemId: i32, disp: ?*?*IDispatch) callconv(.Inline) HRESULT {
return @ptrCast(*const IFeed.VTable, self.vtable).GetItem(@ptrCast(*const IFeed, self), itemId, disp);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IFeed_get_Title(self: *const T, title: ?*?BSTR) callconv(.Inline) HRESULT {
return @ptrCast(*const IFeed.VTable, self.vtable).get_Title(@ptrCast(*const IFeed, self), title);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IFeed_get_Description(self: *const T, description: ?*?BSTR) callconv(.Inline) HRESULT {
return @ptrCast(*const IFeed.VTable, self.vtable).get_Description(@ptrCast(*const IFeed, self), description);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IFeed_get_Link(self: *const T, homePage: ?*?BSTR) callconv(.Inline) HRESULT {
return @ptrCast(*const IFeed.VTable, self.vtable).get_Link(@ptrCast(*const IFeed, self), homePage);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IFeed_get_Image(self: *const T, imageUrl: ?*?BSTR) callconv(.Inline) HRESULT {
return @ptrCast(*const IFeed.VTable, self.vtable).get_Image(@ptrCast(*const IFeed, self), imageUrl);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IFeed_get_LastBuildDate(self: *const T, lastBuildDate: ?*f64) callconv(.Inline) HRESULT {
return @ptrCast(*const IFeed.VTable, self.vtable).get_LastBuildDate(@ptrCast(*const IFeed, self), lastBuildDate);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IFeed_get_PubDate(self: *const T, lastPopulateDate: ?*f64) callconv(.Inline) HRESULT {
return @ptrCast(*const IFeed.VTable, self.vtable).get_PubDate(@ptrCast(*const IFeed, self), lastPopulateDate);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IFeed_get_Ttl(self: *const T, ttl: ?*i32) callconv(.Inline) HRESULT {
return @ptrCast(*const IFeed.VTable, self.vtable).get_Ttl(@ptrCast(*const IFeed, self), ttl);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IFeed_get_Language(self: *const T, language: ?*?BSTR) callconv(.Inline) HRESULT {
return @ptrCast(*const IFeed.VTable, self.vtable).get_Language(@ptrCast(*const IFeed, self), language);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IFeed_get_Copyright(self: *const T, copyright: ?*?BSTR) callconv(.Inline) HRESULT {
return @ptrCast(*const IFeed.VTable, self.vtable).get_Copyright(@ptrCast(*const IFeed, self), copyright);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IFeed_get_MaxItemCount(self: *const T, count: ?*i32) callconv(.Inline) HRESULT {
return @ptrCast(*const IFeed.VTable, self.vtable).get_MaxItemCount(@ptrCast(*const IFeed, self), count);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IFeed_put_MaxItemCount(self: *const T, count: i32) callconv(.Inline) HRESULT {
return @ptrCast(*const IFeed.VTable, self.vtable).put_MaxItemCount(@ptrCast(*const IFeed, self), count);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IFeed_get_DownloadEnclosuresAutomatically(self: *const T, downloadEnclosuresAutomatically: ?*i16) callconv(.Inline) HRESULT {
return @ptrCast(*const IFeed.VTable, self.vtable).get_DownloadEnclosuresAutomatically(@ptrCast(*const IFeed, self), downloadEnclosuresAutomatically);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IFeed_put_DownloadEnclosuresAutomatically(self: *const T, downloadEnclosuresAutomatically: i16) callconv(.Inline) HRESULT {
return @ptrCast(*const IFeed.VTable, self.vtable).put_DownloadEnclosuresAutomatically(@ptrCast(*const IFeed, self), downloadEnclosuresAutomatically);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IFeed_get_DownloadStatus(self: *const T, status: ?*FEEDS_DOWNLOAD_STATUS) callconv(.Inline) HRESULT {
return @ptrCast(*const IFeed.VTable, self.vtable).get_DownloadStatus(@ptrCast(*const IFeed, self), status);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IFeed_get_LastDownloadError(self: *const T, @"error": ?*FEEDS_DOWNLOAD_ERROR) callconv(.Inline) HRESULT {
return @ptrCast(*const IFeed.VTable, self.vtable).get_LastDownloadError(@ptrCast(*const IFeed, self), @"error");
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IFeed_Merge(self: *const T, feedXml: ?BSTR, feedUrl: ?BSTR) callconv(.Inline) HRESULT {
return @ptrCast(*const IFeed.VTable, self.vtable).Merge(@ptrCast(*const IFeed, self), feedXml, feedUrl);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IFeed_get_DownloadUrl(self: *const T, feedUrl: ?*?BSTR) callconv(.Inline) HRESULT {
return @ptrCast(*const IFeed.VTable, self.vtable).get_DownloadUrl(@ptrCast(*const IFeed, self), feedUrl);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IFeed_get_IsList(self: *const T, isList: ?*i16) callconv(.Inline) HRESULT {
return @ptrCast(*const IFeed.VTable, self.vtable).get_IsList(@ptrCast(*const IFeed, self), isList);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IFeed_MarkAllItemsRead(self: *const T) callconv(.Inline) HRESULT {
return @ptrCast(*const IFeed.VTable, self.vtable).MarkAllItemsRead(@ptrCast(*const IFeed, self));
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IFeed_GetWatcher(self: *const T, scope: FEEDS_EVENTS_SCOPE, mask: FEEDS_EVENTS_MASK, disp: ?*?*IDispatch) callconv(.Inline) HRESULT {
return @ptrCast(*const IFeed.VTable, self.vtable).GetWatcher(@ptrCast(*const IFeed, self), scope, mask, disp);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IFeed_get_UnreadItemCount(self: *const T, count: ?*i32) callconv(.Inline) HRESULT {
return @ptrCast(*const IFeed.VTable, self.vtable).get_UnreadItemCount(@ptrCast(*const IFeed, self), count);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IFeed_get_ItemCount(self: *const T, count: ?*i32) callconv(.Inline) HRESULT {
return @ptrCast(*const IFeed.VTable, self.vtable).get_ItemCount(@ptrCast(*const IFeed, self), count);
}
};}
pub usingnamespace MethodMixin(@This());
};
const IID_IFeed2_Value = Guid.initString("33f2ea09-1398-4ab9-b6a4-f94b49d0a42e");
pub const IID_IFeed2 = &IID_IFeed2_Value;
pub const IFeed2 = extern struct {
pub const VTable = extern struct {
base: IFeed.VTable,
GetItemByEffectiveId: fn(
self: *const IFeed2,
itemEffectiveId: i32,
disp: ?*?*IDispatch,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_LastItemDownloadTime: fn(
self: *const IFeed2,
lastItemDownloadTime: ?*f64,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_Username: fn(
self: *const IFeed2,
username: ?*?BSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_Password: fn(
self: *const IFeed2,
password: ?*?BSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
SetCredentials: fn(
self: *const IFeed2,
username: ?BSTR,
password: ?BSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
ClearCredentials: fn(
self: *const IFeed2,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
};
vtable: *const VTable,
pub fn MethodMixin(comptime T: type) type { return struct {
pub usingnamespace IFeed.MethodMixin(T);
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IFeed2_GetItemByEffectiveId(self: *const T, itemEffectiveId: i32, disp: ?*?*IDispatch) callconv(.Inline) HRESULT {
return @ptrCast(*const IFeed2.VTable, self.vtable).GetItemByEffectiveId(@ptrCast(*const IFeed2, self), itemEffectiveId, disp);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IFeed2_get_LastItemDownloadTime(self: *const T, lastItemDownloadTime: ?*f64) callconv(.Inline) HRESULT {
return @ptrCast(*const IFeed2.VTable, self.vtable).get_LastItemDownloadTime(@ptrCast(*const IFeed2, self), lastItemDownloadTime);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IFeed2_get_Username(self: *const T, username: ?*?BSTR) callconv(.Inline) HRESULT {
return @ptrCast(*const IFeed2.VTable, self.vtable).get_Username(@ptrCast(*const IFeed2, self), username);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IFeed2_get_Password(self: *const T, password: ?*?BSTR) callconv(.Inline) HRESULT {
return @ptrCast(*const IFeed2.VTable, self.vtable).get_Password(@ptrCast(*const IFeed2, self), password);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IFeed2_SetCredentials(self: *const T, username: ?BSTR, password: ?BSTR) callconv(.Inline) HRESULT {
return @ptrCast(*const IFeed2.VTable, self.vtable).SetCredentials(@ptrCast(*const IFeed2, self), username, password);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IFeed2_ClearCredentials(self: *const T) callconv(.Inline) HRESULT {
return @ptrCast(*const IFeed2.VTable, self.vtable).ClearCredentials(@ptrCast(*const IFeed2, self));
}
};}
pub usingnamespace MethodMixin(@This());
};
const IID_IFeedEvents_Value = Guid.initString("abf35c99-0681-47ea-9a8c-1436a375a99e");
pub const IID_IFeedEvents = &IID_IFeedEvents_Value;
pub const IFeedEvents = extern struct {
pub const VTable = extern struct {
base: IDispatch.VTable,
Error: fn(
self: *const IFeedEvents,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
FeedDeleted: fn(
self: *const IFeedEvents,
path: ?BSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
FeedRenamed: fn(
self: *const IFeedEvents,
path: ?BSTR,
oldPath: ?BSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
FeedUrlChanged: fn(
self: *const IFeedEvents,
path: ?BSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
FeedMoved: fn(
self: *const IFeedEvents,
path: ?BSTR,
oldPath: ?BSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
FeedDownloading: fn(
self: *const IFeedEvents,
path: ?BSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
FeedDownloadCompleted: fn(
self: *const IFeedEvents,
path: ?BSTR,
@"error": FEEDS_DOWNLOAD_ERROR,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
FeedItemCountChanged: fn(
self: *const IFeedEvents,
path: ?BSTR,
itemCountType: i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
};
vtable: *const VTable,
pub fn MethodMixin(comptime T: type) type { return struct {
pub usingnamespace IDispatch.MethodMixin(T);
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IFeedEvents_Error(self: *const T) callconv(.Inline) HRESULT {
return @ptrCast(*const IFeedEvents.VTable, self.vtable).Error(@ptrCast(*const IFeedEvents, self));
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IFeedEvents_FeedDeleted(self: *const T, path: ?BSTR) callconv(.Inline) HRESULT {
return @ptrCast(*const IFeedEvents.VTable, self.vtable).FeedDeleted(@ptrCast(*const IFeedEvents, self), path);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IFeedEvents_FeedRenamed(self: *const T, path: ?BSTR, oldPath: ?BSTR) callconv(.Inline) HRESULT {
return @ptrCast(*const IFeedEvents.VTable, self.vtable).FeedRenamed(@ptrCast(*const IFeedEvents, self), path, oldPath);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IFeedEvents_FeedUrlChanged(self: *const T, path: ?BSTR) callconv(.Inline) HRESULT {
return @ptrCast(*const IFeedEvents.VTable, self.vtable).FeedUrlChanged(@ptrCast(*const IFeedEvents, self), path);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IFeedEvents_FeedMoved(self: *const T, path: ?BSTR, oldPath: ?BSTR) callconv(.Inline) HRESULT {
return @ptrCast(*const IFeedEvents.VTable, self.vtable).FeedMoved(@ptrCast(*const IFeedEvents, self), path, oldPath);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IFeedEvents_FeedDownloading(self: *const T, path: ?BSTR) callconv(.Inline) HRESULT {
return @ptrCast(*const IFeedEvents.VTable, self.vtable).FeedDownloading(@ptrCast(*const IFeedEvents, self), path);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IFeedEvents_FeedDownloadCompleted(self: *const T, path: ?BSTR, @"error": FEEDS_DOWNLOAD_ERROR) callconv(.Inline) HRESULT {
return @ptrCast(*const IFeedEvents.VTable, self.vtable).FeedDownloadCompleted(@ptrCast(*const IFeedEvents, self), path, @"error");
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IFeedEvents_FeedItemCountChanged(self: *const T, path: ?BSTR, itemCountType: i32) callconv(.Inline) HRESULT {
return @ptrCast(*const IFeedEvents.VTable, self.vtable).FeedItemCountChanged(@ptrCast(*const IFeedEvents, self), path, itemCountType);
}
};}
pub usingnamespace MethodMixin(@This());
};
const IID_IFeedItem_Value = Guid.initString("0a1e6cad-0a47-4da2-a13d-5baaa5c8bd4f");
pub const IID_IFeedItem = &IID_IFeedItem_Value;
pub const IFeedItem = extern struct {
pub const VTable = extern struct {
base: IDispatch.VTable,
Xml: fn(
self: *const IFeedItem,
includeFlags: FEEDS_XML_INCLUDE_FLAGS,
xml: ?*?BSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_Title: fn(
self: *const IFeedItem,
title: ?*?BSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_Link: fn(
self: *const IFeedItem,
linkUrl: ?*?BSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_Guid: fn(
self: *const IFeedItem,
itemGuid: ?*?BSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_Description: fn(
self: *const IFeedItem,
description: ?*?BSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_PubDate: fn(
self: *const IFeedItem,
pubDate: ?*f64,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_Comments: fn(
self: *const IFeedItem,
comments: ?*?BSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_Author: fn(
self: *const IFeedItem,
author: ?*?BSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_Enclosure: fn(
self: *const IFeedItem,
disp: ?*?*IDispatch,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_IsRead: fn(
self: *const IFeedItem,
isRead: ?*i16,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
put_IsRead: fn(
self: *const IFeedItem,
isRead: i16,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_LocalId: fn(
self: *const IFeedItem,
itemId: ?*i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_Parent: fn(
self: *const IFeedItem,
disp: ?*?*IDispatch,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
Delete: fn(
self: *const IFeedItem,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_DownloadUrl: fn(
self: *const IFeedItem,
itemUrl: ?*?BSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_LastDownloadTime: fn(
self: *const IFeedItem,
lastDownload: ?*f64,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_Modified: fn(
self: *const IFeedItem,
modified: ?*f64,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
};
vtable: *const VTable,
pub fn MethodMixin(comptime T: type) type { return struct {
pub usingnamespace IDispatch.MethodMixin(T);
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IFeedItem_Xml(self: *const T, includeFlags: FEEDS_XML_INCLUDE_FLAGS, xml: ?*?BSTR) callconv(.Inline) HRESULT {
return @ptrCast(*const IFeedItem.VTable, self.vtable).Xml(@ptrCast(*const IFeedItem, self), includeFlags, xml);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IFeedItem_get_Title(self: *const T, title: ?*?BSTR) callconv(.Inline) HRESULT {
return @ptrCast(*const IFeedItem.VTable, self.vtable).get_Title(@ptrCast(*const IFeedItem, self), title);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IFeedItem_get_Link(self: *const T, linkUrl: ?*?BSTR) callconv(.Inline) HRESULT {
return @ptrCast(*const IFeedItem.VTable, self.vtable).get_Link(@ptrCast(*const IFeedItem, self), linkUrl);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IFeedItem_get_Guid(self: *const T, itemGuid: ?*?BSTR) callconv(.Inline) HRESULT {
return @ptrCast(*const IFeedItem.VTable, self.vtable).get_Guid(@ptrCast(*const IFeedItem, self), itemGuid);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IFeedItem_get_Description(self: *const T, description: ?*?BSTR) callconv(.Inline) HRESULT {
return @ptrCast(*const IFeedItem.VTable, self.vtable).get_Description(@ptrCast(*const IFeedItem, self), description);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IFeedItem_get_PubDate(self: *const T, pubDate: ?*f64) callconv(.Inline) HRESULT {
return @ptrCast(*const IFeedItem.VTable, self.vtable).get_PubDate(@ptrCast(*const IFeedItem, self), pubDate);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IFeedItem_get_Comments(self: *const T, comments: ?*?BSTR) callconv(.Inline) HRESULT {
return @ptrCast(*const IFeedItem.VTable, self.vtable).get_Comments(@ptrCast(*const IFeedItem, self), comments);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IFeedItem_get_Author(self: *const T, author: ?*?BSTR) callconv(.Inline) HRESULT {
return @ptrCast(*const IFeedItem.VTable, self.vtable).get_Author(@ptrCast(*const IFeedItem, self), author);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IFeedItem_get_Enclosure(self: *const T, disp: ?*?*IDispatch) callconv(.Inline) HRESULT {
return @ptrCast(*const IFeedItem.VTable, self.vtable).get_Enclosure(@ptrCast(*const IFeedItem, self), disp);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IFeedItem_get_IsRead(self: *const T, isRead: ?*i16) callconv(.Inline) HRESULT {
return @ptrCast(*const IFeedItem.VTable, self.vtable).get_IsRead(@ptrCast(*const IFeedItem, self), isRead);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IFeedItem_put_IsRead(self: *const T, isRead: i16) callconv(.Inline) HRESULT {
return @ptrCast(*const IFeedItem.VTable, self.vtable).put_IsRead(@ptrCast(*const IFeedItem, self), isRead);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IFeedItem_get_LocalId(self: *const T, itemId: ?*i32) callconv(.Inline) HRESULT {
return @ptrCast(*const IFeedItem.VTable, self.vtable).get_LocalId(@ptrCast(*const IFeedItem, self), itemId);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IFeedItem_get_Parent(self: *const T, disp: ?*?*IDispatch) callconv(.Inline) HRESULT {
return @ptrCast(*const IFeedItem.VTable, self.vtable).get_Parent(@ptrCast(*const IFeedItem, self), disp);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IFeedItem_Delete(self: *const T) callconv(.Inline) HRESULT {
return @ptrCast(*const IFeedItem.VTable, self.vtable).Delete(@ptrCast(*const IFeedItem, self));
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IFeedItem_get_DownloadUrl(self: *const T, itemUrl: ?*?BSTR) callconv(.Inline) HRESULT {
return @ptrCast(*const IFeedItem.VTable, self.vtable).get_DownloadUrl(@ptrCast(*const IFeedItem, self), itemUrl);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IFeedItem_get_LastDownloadTime(self: *const T, lastDownload: ?*f64) callconv(.Inline) HRESULT {
return @ptrCast(*const IFeedItem.VTable, self.vtable).get_LastDownloadTime(@ptrCast(*const IFeedItem, self), lastDownload);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IFeedItem_get_Modified(self: *const T, modified: ?*f64) callconv(.Inline) HRESULT {
return @ptrCast(*const IFeedItem.VTable, self.vtable).get_Modified(@ptrCast(*const IFeedItem, self), modified);
}
};}
pub usingnamespace MethodMixin(@This());
};
const IID_IFeedItem2_Value = Guid.initString("79ac9ef4-f9c1-4d2b-a50b-a7ffba4dcf37");
pub const IID_IFeedItem2 = &IID_IFeedItem2_Value;
pub const IFeedItem2 = extern struct {
pub const VTable = extern struct {
base: IFeedItem.VTable,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_EffectiveId: fn(
self: *const IFeedItem2,
effectiveId: ?*i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
};
vtable: *const VTable,
pub fn MethodMixin(comptime T: type) type { return struct {
pub usingnamespace IFeedItem.MethodMixin(T);
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IFeedItem2_get_EffectiveId(self: *const T, effectiveId: ?*i32) callconv(.Inline) HRESULT {
return @ptrCast(*const IFeedItem2.VTable, self.vtable).get_EffectiveId(@ptrCast(*const IFeedItem2, self), effectiveId);
}
};}
pub usingnamespace MethodMixin(@This());
};
const IID_IFeedEnclosure_Value = Guid.initString("361c26f7-90a4-4e67-ae09-3a36a546436a");
pub const IID_IFeedEnclosure = &IID_IFeedEnclosure_Value;
pub const IFeedEnclosure = extern struct {
pub const VTable = extern struct {
base: IDispatch.VTable,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_Url: fn(
self: *const IFeedEnclosure,
enclosureUrl: ?*?BSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_Type: fn(
self: *const IFeedEnclosure,
mimeType: ?*?BSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_Length: fn(
self: *const IFeedEnclosure,
length: ?*i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
AsyncDownload: fn(
self: *const IFeedEnclosure,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
CancelAsyncDownload: fn(
self: *const IFeedEnclosure,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_DownloadStatus: fn(
self: *const IFeedEnclosure,
status: ?*FEEDS_DOWNLOAD_STATUS,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_LastDownloadError: fn(
self: *const IFeedEnclosure,
@"error": ?*FEEDS_DOWNLOAD_ERROR,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_LocalPath: fn(
self: *const IFeedEnclosure,
localPath: ?*?BSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_Parent: fn(
self: *const IFeedEnclosure,
disp: ?*?*IDispatch,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_DownloadUrl: fn(
self: *const IFeedEnclosure,
enclosureUrl: ?*?BSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_DownloadMimeType: fn(
self: *const IFeedEnclosure,
mimeType: ?*?BSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
RemoveFile: fn(
self: *const IFeedEnclosure,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
SetFile: fn(
self: *const IFeedEnclosure,
downloadUrl: ?BSTR,
downloadFilePath: ?BSTR,
downloadMimeType: ?BSTR,
enclosureFilename: ?BSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
};
vtable: *const VTable,
pub fn MethodMixin(comptime T: type) type { return struct {
pub usingnamespace IDispatch.MethodMixin(T);
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IFeedEnclosure_get_Url(self: *const T, enclosureUrl: ?*?BSTR) callconv(.Inline) HRESULT {
return @ptrCast(*const IFeedEnclosure.VTable, self.vtable).get_Url(@ptrCast(*const IFeedEnclosure, self), enclosureUrl);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IFeedEnclosure_get_Type(self: *const T, mimeType: ?*?BSTR) callconv(.Inline) HRESULT {
return @ptrCast(*const IFeedEnclosure.VTable, self.vtable).get_Type(@ptrCast(*const IFeedEnclosure, self), mimeType);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IFeedEnclosure_get_Length(self: *const T, length: ?*i32) callconv(.Inline) HRESULT {
return @ptrCast(*const IFeedEnclosure.VTable, self.vtable).get_Length(@ptrCast(*const IFeedEnclosure, self), length);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IFeedEnclosure_AsyncDownload(self: *const T) callconv(.Inline) HRESULT {
return @ptrCast(*const IFeedEnclosure.VTable, self.vtable).AsyncDownload(@ptrCast(*const IFeedEnclosure, self));
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IFeedEnclosure_CancelAsyncDownload(self: *const T) callconv(.Inline) HRESULT {
return @ptrCast(*const IFeedEnclosure.VTable, self.vtable).CancelAsyncDownload(@ptrCast(*const IFeedEnclosure, self));
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IFeedEnclosure_get_DownloadStatus(self: *const T, status: ?*FEEDS_DOWNLOAD_STATUS) callconv(.Inline) HRESULT {
return @ptrCast(*const IFeedEnclosure.VTable, self.vtable).get_DownloadStatus(@ptrCast(*const IFeedEnclosure, self), status);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IFeedEnclosure_get_LastDownloadError(self: *const T, @"error": ?*FEEDS_DOWNLOAD_ERROR) callconv(.Inline) HRESULT {
return @ptrCast(*const IFeedEnclosure.VTable, self.vtable).get_LastDownloadError(@ptrCast(*const IFeedEnclosure, self), @"error");
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IFeedEnclosure_get_LocalPath(self: *const T, localPath: ?*?BSTR) callconv(.Inline) HRESULT {
return @ptrCast(*const IFeedEnclosure.VTable, self.vtable).get_LocalPath(@ptrCast(*const IFeedEnclosure, self), localPath);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IFeedEnclosure_get_Parent(self: *const T, disp: ?*?*IDispatch) callconv(.Inline) HRESULT {
return @ptrCast(*const IFeedEnclosure.VTable, self.vtable).get_Parent(@ptrCast(*const IFeedEnclosure, self), disp);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IFeedEnclosure_get_DownloadUrl(self: *const T, enclosureUrl: ?*?BSTR) callconv(.Inline) HRESULT {
return @ptrCast(*const IFeedEnclosure.VTable, self.vtable).get_DownloadUrl(@ptrCast(*const IFeedEnclosure, self), enclosureUrl);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IFeedEnclosure_get_DownloadMimeType(self: *const T, mimeType: ?*?BSTR) callconv(.Inline) HRESULT {
return @ptrCast(*const IFeedEnclosure.VTable, self.vtable).get_DownloadMimeType(@ptrCast(*const IFeedEnclosure, self), mimeType);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IFeedEnclosure_RemoveFile(self: *const T) callconv(.Inline) HRESULT {
return @ptrCast(*const IFeedEnclosure.VTable, self.vtable).RemoveFile(@ptrCast(*const IFeedEnclosure, self));
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IFeedEnclosure_SetFile(self: *const T, downloadUrl: ?BSTR, downloadFilePath: ?BSTR, downloadMimeType: ?BSTR, enclosureFilename: ?BSTR) callconv(.Inline) HRESULT {
return @ptrCast(*const IFeedEnclosure.VTable, self.vtable).SetFile(@ptrCast(*const IFeedEnclosure, self), downloadUrl, downloadFilePath, downloadMimeType, enclosureFilename);
}
};}
pub usingnamespace MethodMixin(@This());
};
pub const PlayerState = enum(i32) {
stop_state = 0,
pause_state = 1,
play_state = 2,
};
pub const stop_state = PlayerState.stop_state;
pub const pause_state = PlayerState.pause_state;
pub const play_state = PlayerState.play_state;
pub const TimedLevel = extern struct {
frequency: [2048]u8,
waveform: [2048]u8,
state: i32,
timeStamp: i64,
};
const IID_IWMPEffects_Value = Guid.initString("d3984c13-c3cb-48e2-8be5-5168340b4f35");
pub const IID_IWMPEffects = &IID_IWMPEffects_Value;
pub const IWMPEffects = extern struct {
pub const VTable = extern struct {
base: IUnknown.VTable,
Render: fn(
self: *const IWMPEffects,
pLevels: ?*TimedLevel,
hdc: ?HDC,
prc: ?*RECT,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
MediaInfo: fn(
self: *const IWMPEffects,
lChannelCount: i32,
lSampleRate: i32,
bstrTitle: ?BSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetCapabilities: fn(
self: *const IWMPEffects,
pdwCapabilities: ?*u32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetTitle: fn(
self: *const IWMPEffects,
bstrTitle: ?*?BSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetPresetTitle: fn(
self: *const IWMPEffects,
nPreset: i32,
bstrPresetTitle: ?*?BSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetPresetCount: fn(
self: *const IWMPEffects,
pnPresetCount: ?*i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
SetCurrentPreset: fn(
self: *const IWMPEffects,
nPreset: i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetCurrentPreset: fn(
self: *const IWMPEffects,
pnPreset: ?*i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
DisplayPropertyPage: fn(
self: *const IWMPEffects,
hwndOwner: ?HWND,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GoFullscreen: fn(
self: *const IWMPEffects,
fFullScreen: BOOL,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
RenderFullScreen: fn(
self: *const IWMPEffects,
pLevels: ?*TimedLevel,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
};
vtable: *const VTable,
pub fn MethodMixin(comptime T: type) type { return struct {
pub usingnamespace IUnknown.MethodMixin(T);
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IWMPEffects_Render(self: *const T, pLevels: ?*TimedLevel, hdc: ?HDC, prc: ?*RECT) callconv(.Inline) HRESULT {
return @ptrCast(*const IWMPEffects.VTable, self.vtable).Render(@ptrCast(*const IWMPEffects, self), pLevels, hdc, prc);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IWMPEffects_MediaInfo(self: *const T, lChannelCount: i32, lSampleRate: i32, bstrTitle: ?BSTR) callconv(.Inline) HRESULT {
return @ptrCast(*const IWMPEffects.VTable, self.vtable).MediaInfo(@ptrCast(*const IWMPEffects, self), lChannelCount, lSampleRate, bstrTitle);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IWMPEffects_GetCapabilities(self: *const T, pdwCapabilities: ?*u32) callconv(.Inline) HRESULT {
return @ptrCast(*const IWMPEffects.VTable, self.vtable).GetCapabilities(@ptrCast(*const IWMPEffects, self), pdwCapabilities);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IWMPEffects_GetTitle(self: *const T, bstrTitle: ?*?BSTR) callconv(.Inline) HRESULT {
return @ptrCast(*const IWMPEffects.VTable, self.vtable).GetTitle(@ptrCast(*const IWMPEffects, self), bstrTitle);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IWMPEffects_GetPresetTitle(self: *const T, nPreset: i32, bstrPresetTitle: ?*?BSTR) callconv(.Inline) HRESULT {
return @ptrCast(*const IWMPEffects.VTable, self.vtable).GetPresetTitle(@ptrCast(*const IWMPEffects, self), nPreset, bstrPresetTitle);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IWMPEffects_GetPresetCount(self: *const T, pnPresetCount: ?*i32) callconv(.Inline) HRESULT {
return @ptrCast(*const IWMPEffects.VTable, self.vtable).GetPresetCount(@ptrCast(*const IWMPEffects, self), pnPresetCount);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IWMPEffects_SetCurrentPreset(self: *const T, nPreset: i32) callconv(.Inline) HRESULT {
return @ptrCast(*const IWMPEffects.VTable, self.vtable).SetCurrentPreset(@ptrCast(*const IWMPEffects, self), nPreset);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IWMPEffects_GetCurrentPreset(self: *const T, pnPreset: ?*i32) callconv(.Inline) HRESULT {
return @ptrCast(*const IWMPEffects.VTable, self.vtable).GetCurrentPreset(@ptrCast(*const IWMPEffects, self), pnPreset);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IWMPEffects_DisplayPropertyPage(self: *const T, hwndOwner: ?HWND) callconv(.Inline) HRESULT {
return @ptrCast(*const IWMPEffects.VTable, self.vtable).DisplayPropertyPage(@ptrCast(*const IWMPEffects, self), hwndOwner);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IWMPEffects_GoFullscreen(self: *const T, fFullScreen: BOOL) callconv(.Inline) HRESULT {
return @ptrCast(*const IWMPEffects.VTable, self.vtable).GoFullscreen(@ptrCast(*const IWMPEffects, self), fFullScreen);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IWMPEffects_RenderFullScreen(self: *const T, pLevels: ?*TimedLevel) callconv(.Inline) HRESULT {
return @ptrCast(*const IWMPEffects.VTable, self.vtable).RenderFullScreen(@ptrCast(*const IWMPEffects, self), pLevels);
}
};}
pub usingnamespace MethodMixin(@This());
};
const IID_IWMPEffects2_Value = Guid.initString("695386ec-aa3c-4618-a5e1-dd9a8b987632");
pub const IID_IWMPEffects2 = &IID_IWMPEffects2_Value;
pub const IWMPEffects2 = extern struct {
pub const VTable = extern struct {
base: IWMPEffects.VTable,
SetCore: fn(
self: *const IWMPEffects2,
pPlayer: ?*IWMPCore,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
Create: fn(
self: *const IWMPEffects2,
hwndParent: ?HWND,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
Destroy: fn(
self: *const IWMPEffects2,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
NotifyNewMedia: fn(
self: *const IWMPEffects2,
pMedia: ?*IWMPMedia,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
OnWindowMessage: fn(
self: *const IWMPEffects2,
msg: u32,
WParam: WPARAM,
LParam: LPARAM,
plResultParam: ?*LRESULT,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
RenderWindowed: fn(
self: *const IWMPEffects2,
pData: ?*TimedLevel,
fRequiredRender: BOOL,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
};
vtable: *const VTable,
pub fn MethodMixin(comptime T: type) type { return struct {
pub usingnamespace IWMPEffects.MethodMixin(T);
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IWMPEffects2_SetCore(self: *const T, pPlayer: ?*IWMPCore) callconv(.Inline) HRESULT {
return @ptrCast(*const IWMPEffects2.VTable, self.vtable).SetCore(@ptrCast(*const IWMPEffects2, self), pPlayer);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IWMPEffects2_Create(self: *const T, hwndParent: ?HWND) callconv(.Inline) HRESULT {
return @ptrCast(*const IWMPEffects2.VTable, self.vtable).Create(@ptrCast(*const IWMPEffects2, self), hwndParent);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IWMPEffects2_Destroy(self: *const T) callconv(.Inline) HRESULT {
return @ptrCast(*const IWMPEffects2.VTable, self.vtable).Destroy(@ptrCast(*const IWMPEffects2, self));
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IWMPEffects2_NotifyNewMedia(self: *const T, pMedia: ?*IWMPMedia) callconv(.Inline) HRESULT {
return @ptrCast(*const IWMPEffects2.VTable, self.vtable).NotifyNewMedia(@ptrCast(*const IWMPEffects2, self), pMedia);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IWMPEffects2_OnWindowMessage(self: *const T, msg: u32, WParam: WPARAM, LParam: LPARAM, plResultParam: ?*LRESULT) callconv(.Inline) HRESULT {
return @ptrCast(*const IWMPEffects2.VTable, self.vtable).OnWindowMessage(@ptrCast(*const IWMPEffects2, self), msg, WParam, LParam, plResultParam);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IWMPEffects2_RenderWindowed(self: *const T, pData: ?*TimedLevel, fRequiredRender: BOOL) callconv(.Inline) HRESULT {
return @ptrCast(*const IWMPEffects2.VTable, self.vtable).RenderWindowed(@ptrCast(*const IWMPEffects2, self), pData, fRequiredRender);
}
};}
pub usingnamespace MethodMixin(@This());
};
const IID_IWMPPluginUI_Value = Guid.initString("4c5e8f9f-ad3e-4bf9-9753-fcd30d6d38dd");
pub const IID_IWMPPluginUI = &IID_IWMPPluginUI_Value;
pub const IWMPPluginUI = extern struct {
pub const VTable = extern struct {
base: IUnknown.VTable,
SetCore: fn(
self: *const IWMPPluginUI,
pCore: ?*IWMPCore,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
Create: fn(
self: *const IWMPPluginUI,
hwndParent: ?HWND,
phwndWindow: ?*?HWND,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
Destroy: fn(
self: *const IWMPPluginUI,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
DisplayPropertyPage: fn(
self: *const IWMPPluginUI,
hwndParent: ?HWND,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetProperty: fn(
self: *const IWMPPluginUI,
pwszName: ?[*:0]const u16,
pvarProperty: ?*VARIANT,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
SetProperty: fn(
self: *const IWMPPluginUI,
pwszName: ?[*:0]const u16,
pvarProperty: ?*const VARIANT,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
TranslateAccelerator: fn(
self: *const IWMPPluginUI,
lpmsg: ?*MSG,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
};
vtable: *const VTable,
pub fn MethodMixin(comptime T: type) type { return struct {
pub usingnamespace IUnknown.MethodMixin(T);
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IWMPPluginUI_SetCore(self: *const T, pCore: ?*IWMPCore) callconv(.Inline) HRESULT {
return @ptrCast(*const IWMPPluginUI.VTable, self.vtable).SetCore(@ptrCast(*const IWMPPluginUI, self), pCore);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IWMPPluginUI_Create(self: *const T, hwndParent: ?HWND, phwndWindow: ?*?HWND) callconv(.Inline) HRESULT {
return @ptrCast(*const IWMPPluginUI.VTable, self.vtable).Create(@ptrCast(*const IWMPPluginUI, self), hwndParent, phwndWindow);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IWMPPluginUI_Destroy(self: *const T) callconv(.Inline) HRESULT {
return @ptrCast(*const IWMPPluginUI.VTable, self.vtable).Destroy(@ptrCast(*const IWMPPluginUI, self));
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IWMPPluginUI_DisplayPropertyPage(self: *const T, hwndParent: ?HWND) callconv(.Inline) HRESULT {
return @ptrCast(*const IWMPPluginUI.VTable, self.vtable).DisplayPropertyPage(@ptrCast(*const IWMPPluginUI, self), hwndParent);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IWMPPluginUI_GetProperty(self: *const T, pwszName: ?[*:0]const u16, pvarProperty: ?*VARIANT) callconv(.Inline) HRESULT {
return @ptrCast(*const IWMPPluginUI.VTable, self.vtable).GetProperty(@ptrCast(*const IWMPPluginUI, self), pwszName, pvarProperty);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IWMPPluginUI_SetProperty(self: *const T, pwszName: ?[*:0]const u16, pvarProperty: ?*const VARIANT) callconv(.Inline) HRESULT {
return @ptrCast(*const IWMPPluginUI.VTable, self.vtable).SetProperty(@ptrCast(*const IWMPPluginUI, self), pwszName, pvarProperty);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IWMPPluginUI_TranslateAccelerator(self: *const T, lpmsg: ?*MSG) callconv(.Inline) HRESULT {
return @ptrCast(*const IWMPPluginUI.VTable, self.vtable).TranslateAccelerator(@ptrCast(*const IWMPPluginUI, self), lpmsg);
}
};}
pub usingnamespace MethodMixin(@This());
};
pub const WMPPartnerNotification = enum(i32) {
BackgroundProcessingBegin = 1,
BackgroundProcessingEnd = 2,
CatalogDownloadFailure = 3,
CatalogDownloadComplete = 4,
};
pub const wmpsnBackgroundProcessingBegin = WMPPartnerNotification.BackgroundProcessingBegin;
pub const wmpsnBackgroundProcessingEnd = WMPPartnerNotification.BackgroundProcessingEnd;
pub const wmpsnCatalogDownloadFailure = WMPPartnerNotification.CatalogDownloadFailure;
pub const wmpsnCatalogDownloadComplete = WMPPartnerNotification.CatalogDownloadComplete;
pub const WMPCallbackNotification = enum(i32) {
LoginStateChange = 1,
AuthResult = 2,
LicenseUpdated = 3,
NewCatalogAvailable = 4,
NewPluginAvailable = 5,
DisableRadioSkipping = 6,
};
pub const wmpcnLoginStateChange = WMPCallbackNotification.LoginStateChange;
pub const wmpcnAuthResult = WMPCallbackNotification.AuthResult;
pub const wmpcnLicenseUpdated = WMPCallbackNotification.LicenseUpdated;
pub const wmpcnNewCatalogAvailable = WMPCallbackNotification.NewCatalogAvailable;
pub const wmpcnNewPluginAvailable = WMPCallbackNotification.NewPluginAvailable;
pub const wmpcnDisableRadioSkipping = WMPCallbackNotification.DisableRadioSkipping;
pub const WMPTaskType = enum(i32) {
Browse = 1,
Sync = 2,
Burn = 3,
Current = 4,
};
pub const wmpttBrowse = WMPTaskType.Browse;
pub const wmpttSync = WMPTaskType.Sync;
pub const wmpttBurn = WMPTaskType.Burn;
pub const wmpttCurrent = WMPTaskType.Current;
pub const WMPContextMenuInfo = extern struct {
dwID: u32,
bstrMenuText: ?BSTR,
bstrHelpText: ?BSTR,
};
const IID_IWMPContentContainer_Value = Guid.initString("ad7f4d9c-1a9f-4ed2-9815-ecc0b58cb616");
pub const IID_IWMPContentContainer = &IID_IWMPContentContainer_Value;
pub const IWMPContentContainer = extern struct {
pub const VTable = extern struct {
base: IUnknown.VTable,
GetID: fn(
self: *const IWMPContentContainer,
pContentID: ?*u32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetPrice: fn(
self: *const IWMPContentContainer,
pbstrPrice: ?*?BSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetType: fn(
self: *const IWMPContentContainer,
pbstrType: ?*?BSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetContentCount: fn(
self: *const IWMPContentContainer,
pcContent: ?*u32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetContentPrice: fn(
self: *const IWMPContentContainer,
idxContent: u32,
pbstrPrice: ?*?BSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetContentID: fn(
self: *const IWMPContentContainer,
idxContent: u32,
pContentID: ?*u32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
};
vtable: *const VTable,
pub fn MethodMixin(comptime T: type) type { return struct {
pub usingnamespace IUnknown.MethodMixin(T);
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IWMPContentContainer_GetID(self: *const T, pContentID: ?*u32) callconv(.Inline) HRESULT {
return @ptrCast(*const IWMPContentContainer.VTable, self.vtable).GetID(@ptrCast(*const IWMPContentContainer, self), pContentID);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IWMPContentContainer_GetPrice(self: *const T, pbstrPrice: ?*?BSTR) callconv(.Inline) HRESULT {
return @ptrCast(*const IWMPContentContainer.VTable, self.vtable).GetPrice(@ptrCast(*const IWMPContentContainer, self), pbstrPrice);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IWMPContentContainer_GetType(self: *const T, pbstrType: ?*?BSTR) callconv(.Inline) HRESULT {
return @ptrCast(*const IWMPContentContainer.VTable, self.vtable).GetType(@ptrCast(*const IWMPContentContainer, self), pbstrType);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IWMPContentContainer_GetContentCount(self: *const T, pcContent: ?*u32) callconv(.Inline) HRESULT {
return @ptrCast(*const IWMPContentContainer.VTable, self.vtable).GetContentCount(@ptrCast(*const IWMPContentContainer, self), pcContent);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IWMPContentContainer_GetContentPrice(self: *const T, idxContent: u32, pbstrPrice: ?*?BSTR) callconv(.Inline) HRESULT {
return @ptrCast(*const IWMPContentContainer.VTable, self.vtable).GetContentPrice(@ptrCast(*const IWMPContentContainer, self), idxContent, pbstrPrice);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IWMPContentContainer_GetContentID(self: *const T, idxContent: u32, pContentID: ?*u32) callconv(.Inline) HRESULT {
return @ptrCast(*const IWMPContentContainer.VTable, self.vtable).GetContentID(@ptrCast(*const IWMPContentContainer, self), idxContent, pContentID);
}
};}
pub usingnamespace MethodMixin(@This());
};
pub const WMPTransactionType = enum(i32) {
NoTransaction = 0,
Download = 1,
Buy = 2,
};
pub const wmpttNoTransaction = WMPTransactionType.NoTransaction;
pub const wmpttDownload = WMPTransactionType.Download;
pub const wmpttBuy = WMPTransactionType.Buy;
const IID_IWMPContentContainerList_Value = Guid.initString("a9937f78-0802-4af8-8b8d-e3f045bc8ab5");
pub const IID_IWMPContentContainerList = &IID_IWMPContentContainerList_Value;
pub const IWMPContentContainerList = extern struct {
pub const VTable = extern struct {
base: IUnknown.VTable,
GetTransactionType: fn(
self: *const IWMPContentContainerList,
pwmptt: ?*WMPTransactionType,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetContainerCount: fn(
self: *const IWMPContentContainerList,
pcContainer: ?*u32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetContainer: fn(
self: *const IWMPContentContainerList,
idxContainer: u32,
ppContent: ?*?*IWMPContentContainer,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
};
vtable: *const VTable,
pub fn MethodMixin(comptime T: type) type { return struct {
pub usingnamespace IUnknown.MethodMixin(T);
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IWMPContentContainerList_GetTransactionType(self: *const T, pwmptt: ?*WMPTransactionType) callconv(.Inline) HRESULT {
return @ptrCast(*const IWMPContentContainerList.VTable, self.vtable).GetTransactionType(@ptrCast(*const IWMPContentContainerList, self), pwmptt);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IWMPContentContainerList_GetContainerCount(self: *const T, pcContainer: ?*u32) callconv(.Inline) HRESULT {
return @ptrCast(*const IWMPContentContainerList.VTable, self.vtable).GetContainerCount(@ptrCast(*const IWMPContentContainerList, self), pcContainer);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IWMPContentContainerList_GetContainer(self: *const T, idxContainer: u32, ppContent: ?*?*IWMPContentContainer) callconv(.Inline) HRESULT {
return @ptrCast(*const IWMPContentContainerList.VTable, self.vtable).GetContainer(@ptrCast(*const IWMPContentContainerList, self), idxContainer, ppContent);
}
};}
pub usingnamespace MethodMixin(@This());
};
pub const WMPTemplateSize = enum(i32) {
Small = 0,
Medium = 1,
Large = 2,
};
pub const wmptsSmall = WMPTemplateSize.Small;
pub const wmptsMedium = WMPTemplateSize.Medium;
pub const wmptsLarge = WMPTemplateSize.Large;
pub const WMPStreamingType = enum(i32) {
Unknown = 0,
Music = 1,
Video = 2,
Radio = 3,
};
pub const wmpstUnknown = WMPStreamingType.Unknown;
pub const wmpstMusic = WMPStreamingType.Music;
pub const wmpstVideo = WMPStreamingType.Video;
pub const wmpstRadio = WMPStreamingType.Radio;
pub const WMPAccountType = enum(i32) {
BuyOnly = 1,
Subscription = 2,
Janus = 3,
};
pub const wmpatBuyOnly = WMPAccountType.BuyOnly;
pub const wmpatSubscription = WMPAccountType.Subscription;
pub const wmpatJanus = WMPAccountType.Janus;
const IID_IWMPContentPartnerCallback_Value = Guid.initString("9e8f7da2-0695-403c-b697-da10fafaa676");
pub const IID_IWMPContentPartnerCallback = &IID_IWMPContentPartnerCallback_Value;
pub const IWMPContentPartnerCallback = extern struct {
pub const VTable = extern struct {
base: IUnknown.VTable,
Notify: fn(
self: *const IWMPContentPartnerCallback,
type: WMPCallbackNotification,
pContext: ?*VARIANT,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
BuyComplete: fn(
self: *const IWMPContentPartnerCallback,
hrResult: HRESULT,
dwBuyCookie: u32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
DownloadTrack: fn(
self: *const IWMPContentPartnerCallback,
cookie: u32,
bstrTrackURL: ?BSTR,
dwServiceTrackID: u32,
bstrDownloadParams: ?BSTR,
hrDownload: HRESULT,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetCatalogVersion: fn(
self: *const IWMPContentPartnerCallback,
pdwVersion: ?*u32,
pdwSchemaVersion: ?*u32,
plcid: ?*u32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
UpdateDeviceComplete: fn(
self: *const IWMPContentPartnerCallback,
bstrDeviceName: ?BSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
ChangeView: fn(
self: *const IWMPContentPartnerCallback,
bstrType: ?BSTR,
bstrID: ?BSTR,
bstrFilter: ?BSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
AddListContents: fn(
self: *const IWMPContentPartnerCallback,
dwListCookie: u32,
cItems: u32,
prgItems: [*]u32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
ListContentsComplete: fn(
self: *const IWMPContentPartnerCallback,
dwListCookie: u32,
hrSuccess: HRESULT,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
SendMessageComplete: fn(
self: *const IWMPContentPartnerCallback,
bstrMsg: ?BSTR,
bstrParam: ?BSTR,
bstrResult: ?BSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetContentIDsInLibrary: fn(
self: *const IWMPContentPartnerCallback,
pcContentIDs: ?*u32,
pprgIDs: ?[*]?*u32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
RefreshLicenseComplete: fn(
self: *const IWMPContentPartnerCallback,
dwCookie: u32,
contentID: u32,
hrRefresh: HRESULT,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
ShowPopup: fn(
self: *const IWMPContentPartnerCallback,
lIndex: i32,
bstrParameters: ?BSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
VerifyPermissionComplete: fn(
self: *const IWMPContentPartnerCallback,
bstrPermission: ?BSTR,
pContext: ?*VARIANT,
hrPermission: HRESULT,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
};
vtable: *const VTable,
pub fn MethodMixin(comptime T: type) type { return struct {
pub usingnamespace IUnknown.MethodMixin(T);
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IWMPContentPartnerCallback_Notify(self: *const T, type_: WMPCallbackNotification, pContext: ?*VARIANT) callconv(.Inline) HRESULT {
return @ptrCast(*const IWMPContentPartnerCallback.VTable, self.vtable).Notify(@ptrCast(*const IWMPContentPartnerCallback, self), type_, pContext);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IWMPContentPartnerCallback_BuyComplete(self: *const T, hrResult: HRESULT, dwBuyCookie: u32) callconv(.Inline) HRESULT {
return @ptrCast(*const IWMPContentPartnerCallback.VTable, self.vtable).BuyComplete(@ptrCast(*const IWMPContentPartnerCallback, self), hrResult, dwBuyCookie);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IWMPContentPartnerCallback_DownloadTrack(self: *const T, cookie: u32, bstrTrackURL: ?BSTR, dwServiceTrackID: u32, bstrDownloadParams: ?BSTR, hrDownload: HRESULT) callconv(.Inline) HRESULT {
return @ptrCast(*const IWMPContentPartnerCallback.VTable, self.vtable).DownloadTrack(@ptrCast(*const IWMPContentPartnerCallback, self), cookie, bstrTrackURL, dwServiceTrackID, bstrDownloadParams, hrDownload);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IWMPContentPartnerCallback_GetCatalogVersion(self: *const T, pdwVersion: ?*u32, pdwSchemaVersion: ?*u32, plcid: ?*u32) callconv(.Inline) HRESULT {
return @ptrCast(*const IWMPContentPartnerCallback.VTable, self.vtable).GetCatalogVersion(@ptrCast(*const IWMPContentPartnerCallback, self), pdwVersion, pdwSchemaVersion, plcid);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IWMPContentPartnerCallback_UpdateDeviceComplete(self: *const T, bstrDeviceName: ?BSTR) callconv(.Inline) HRESULT {
return @ptrCast(*const IWMPContentPartnerCallback.VTable, self.vtable).UpdateDeviceComplete(@ptrCast(*const IWMPContentPartnerCallback, self), bstrDeviceName);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IWMPContentPartnerCallback_ChangeView(self: *const T, bstrType: ?BSTR, bstrID: ?BSTR, bstrFilter: ?BSTR) callconv(.Inline) HRESULT {
return @ptrCast(*const IWMPContentPartnerCallback.VTable, self.vtable).ChangeView(@ptrCast(*const IWMPContentPartnerCallback, self), bstrType, bstrID, bstrFilter);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IWMPContentPartnerCallback_AddListContents(self: *const T, dwListCookie: u32, cItems: u32, prgItems: [*]u32) callconv(.Inline) HRESULT {
return @ptrCast(*const IWMPContentPartnerCallback.VTable, self.vtable).AddListContents(@ptrCast(*const IWMPContentPartnerCallback, self), dwListCookie, cItems, prgItems);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IWMPContentPartnerCallback_ListContentsComplete(self: *const T, dwListCookie: u32, hrSuccess: HRESULT) callconv(.Inline) HRESULT {
return @ptrCast(*const IWMPContentPartnerCallback.VTable, self.vtable).ListContentsComplete(@ptrCast(*const IWMPContentPartnerCallback, self), dwListCookie, hrSuccess);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IWMPContentPartnerCallback_SendMessageComplete(self: *const T, bstrMsg: ?BSTR, bstrParam: ?BSTR, bstrResult: ?BSTR) callconv(.Inline) HRESULT {
return @ptrCast(*const IWMPContentPartnerCallback.VTable, self.vtable).SendMessageComplete(@ptrCast(*const IWMPContentPartnerCallback, self), bstrMsg, bstrParam, bstrResult);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IWMPContentPartnerCallback_GetContentIDsInLibrary(self: *const T, pcContentIDs: ?*u32, pprgIDs: ?[*]?*u32) callconv(.Inline) HRESULT {
return @ptrCast(*const IWMPContentPartnerCallback.VTable, self.vtable).GetContentIDsInLibrary(@ptrCast(*const IWMPContentPartnerCallback, self), pcContentIDs, pprgIDs);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IWMPContentPartnerCallback_RefreshLicenseComplete(self: *const T, dwCookie: u32, contentID: u32, hrRefresh: HRESULT) callconv(.Inline) HRESULT {
return @ptrCast(*const IWMPContentPartnerCallback.VTable, self.vtable).RefreshLicenseComplete(@ptrCast(*const IWMPContentPartnerCallback, self), dwCookie, contentID, hrRefresh);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IWMPContentPartnerCallback_ShowPopup(self: *const T, lIndex: i32, bstrParameters: ?BSTR) callconv(.Inline) HRESULT {
return @ptrCast(*const IWMPContentPartnerCallback.VTable, self.vtable).ShowPopup(@ptrCast(*const IWMPContentPartnerCallback, self), lIndex, bstrParameters);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IWMPContentPartnerCallback_VerifyPermissionComplete(self: *const T, bstrPermission: ?BSTR, pContext: ?*VARIANT, hrPermission: HRESULT) callconv(.Inline) HRESULT {
return @ptrCast(*const IWMPContentPartnerCallback.VTable, self.vtable).VerifyPermissionComplete(@ptrCast(*const IWMPContentPartnerCallback, self), bstrPermission, pContext, hrPermission);
}
};}
pub usingnamespace MethodMixin(@This());
};
const IID_IWMPContentPartner_Value = Guid.initString("55455073-41b5-4e75-87b8-f13bdb291d08");
pub const IID_IWMPContentPartner = &IID_IWMPContentPartner_Value;
pub const IWMPContentPartner = extern struct {
pub const VTable = extern struct {
base: IUnknown.VTable,
SetCallback: fn(
self: *const IWMPContentPartner,
pCallback: ?*IWMPContentPartnerCallback,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
Notify: fn(
self: *const IWMPContentPartner,
type: WMPPartnerNotification,
pContext: ?*VARIANT,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetItemInfo: fn(
self: *const IWMPContentPartner,
bstrInfoName: ?BSTR,
pContext: ?*VARIANT,
pData: ?*VARIANT,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetContentPartnerInfo: fn(
self: *const IWMPContentPartner,
bstrInfoName: ?BSTR,
pData: ?*VARIANT,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetCommands: fn(
self: *const IWMPContentPartner,
location: ?BSTR,
pLocationContext: ?*VARIANT,
itemLocation: ?BSTR,
cItemIDs: u32,
prgItemIDs: [*]u32,
pcItemIDs: ?*u32,
pprgItems: ?[*]?*WMPContextMenuInfo,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
InvokeCommand: fn(
self: *const IWMPContentPartner,
dwCommandID: u32,
location: ?BSTR,
pLocationContext: ?*VARIANT,
itemLocation: ?BSTR,
cItemIDs: u32,
rgItemIDs: [*]u32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
CanBuySilent: fn(
self: *const IWMPContentPartner,
pInfo: ?*IWMPContentContainerList,
pbstrTotalPrice: ?*?BSTR,
pSilentOK: ?*i16,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
Buy: fn(
self: *const IWMPContentPartner,
pInfo: ?*IWMPContentContainerList,
cookie: u32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetStreamingURL: fn(
self: *const IWMPContentPartner,
st: WMPStreamingType,
pStreamContext: ?*VARIANT,
pbstrURL: ?*?BSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
Download: fn(
self: *const IWMPContentPartner,
pInfo: ?*IWMPContentContainerList,
cookie: u32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
DownloadTrackComplete: fn(
self: *const IWMPContentPartner,
hrResult: HRESULT,
contentID: u32,
downloadTrackParam: ?BSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
RefreshLicense: fn(
self: *const IWMPContentPartner,
dwCookie: u32,
fLocal: i16,
bstrURL: ?BSTR,
type: WMPStreamingType,
contentID: u32,
bstrRefreshReason: ?BSTR,
pReasonContext: ?*VARIANT,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetCatalogURL: fn(
self: *const IWMPContentPartner,
dwCatalogVersion: u32,
dwCatalogSchemaVersion: u32,
catalogLCID: u32,
pdwNewCatalogVersion: ?*u32,
pbstrCatalogURL: ?*?BSTR,
pExpirationDate: ?*VARIANT,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetTemplate: fn(
self: *const IWMPContentPartner,
task: WMPTaskType,
location: ?BSTR,
pContext: ?*VARIANT,
clickLocation: ?BSTR,
pClickContext: ?*VARIANT,
bstrFilter: ?BSTR,
bstrViewParams: ?BSTR,
pbstrTemplateURL: ?*?BSTR,
pTemplateSize: ?*WMPTemplateSize,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
UpdateDevice: fn(
self: *const IWMPContentPartner,
bstrDeviceName: ?BSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetListContents: fn(
self: *const IWMPContentPartner,
location: ?BSTR,
pContext: ?*VARIANT,
bstrListType: ?BSTR,
bstrParams: ?BSTR,
dwListCookie: u32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
Login: fn(
self: *const IWMPContentPartner,
userInfo: BLOB,
pwdInfo: BLOB,
fUsedCachedCreds: i16,
fOkToCache: i16,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
Authenticate: fn(
self: *const IWMPContentPartner,
userInfo: BLOB,
pwdInfo: BLOB,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
Logout: fn(
self: *const IWMPContentPartner,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
SendMessage: fn(
self: *const IWMPContentPartner,
bstrMsg: ?BSTR,
bstrParam: ?BSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
StationEvent: fn(
self: *const IWMPContentPartner,
bstrStationEventType: ?BSTR,
StationId: u32,
PlaylistIndex: u32,
TrackID: u32,
TrackData: ?BSTR,
dwSecondsPlayed: u32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
CompareContainerListPrices: fn(
self: *const IWMPContentPartner,
pListBase: ?*IWMPContentContainerList,
pListCompare: ?*IWMPContentContainerList,
pResult: ?*i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
VerifyPermission: fn(
self: *const IWMPContentPartner,
bstrPermission: ?BSTR,
pContext: ?*VARIANT,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
};
vtable: *const VTable,
pub fn MethodMixin(comptime T: type) type { return struct {
pub usingnamespace IUnknown.MethodMixin(T);
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IWMPContentPartner_SetCallback(self: *const T, pCallback: ?*IWMPContentPartnerCallback) callconv(.Inline) HRESULT {
return @ptrCast(*const IWMPContentPartner.VTable, self.vtable).SetCallback(@ptrCast(*const IWMPContentPartner, self), pCallback);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IWMPContentPartner_Notify(self: *const T, type_: WMPPartnerNotification, pContext: ?*VARIANT) callconv(.Inline) HRESULT {
return @ptrCast(*const IWMPContentPartner.VTable, self.vtable).Notify(@ptrCast(*const IWMPContentPartner, self), type_, pContext);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IWMPContentPartner_GetItemInfo(self: *const T, bstrInfoName: ?BSTR, pContext: ?*VARIANT, pData: ?*VARIANT) callconv(.Inline) HRESULT {
return @ptrCast(*const IWMPContentPartner.VTable, self.vtable).GetItemInfo(@ptrCast(*const IWMPContentPartner, self), bstrInfoName, pContext, pData);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IWMPContentPartner_GetContentPartnerInfo(self: *const T, bstrInfoName: ?BSTR, pData: ?*VARIANT) callconv(.Inline) HRESULT {
return @ptrCast(*const IWMPContentPartner.VTable, self.vtable).GetContentPartnerInfo(@ptrCast(*const IWMPContentPartner, self), bstrInfoName, pData);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IWMPContentPartner_GetCommands(self: *const T, location: ?BSTR, pLocationContext: ?*VARIANT, itemLocation: ?BSTR, cItemIDs: u32, prgItemIDs: [*]u32, pcItemIDs: ?*u32, pprgItems: ?[*]?*WMPContextMenuInfo) callconv(.Inline) HRESULT {
return @ptrCast(*const IWMPContentPartner.VTable, self.vtable).GetCommands(@ptrCast(*const IWMPContentPartner, self), location, pLocationContext, itemLocation, cItemIDs, prgItemIDs, pcItemIDs, pprgItems);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IWMPContentPartner_InvokeCommand(self: *const T, dwCommandID: u32, location: ?BSTR, pLocationContext: ?*VARIANT, itemLocation: ?BSTR, cItemIDs: u32, rgItemIDs: [*]u32) callconv(.Inline) HRESULT {
return @ptrCast(*const IWMPContentPartner.VTable, self.vtable).InvokeCommand(@ptrCast(*const IWMPContentPartner, self), dwCommandID, location, pLocationContext, itemLocation, cItemIDs, rgItemIDs);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IWMPContentPartner_CanBuySilent(self: *const T, pInfo: ?*IWMPContentContainerList, pbstrTotalPrice: ?*?BSTR, pSilentOK: ?*i16) callconv(.Inline) HRESULT {
return @ptrCast(*const IWMPContentPartner.VTable, self.vtable).CanBuySilent(@ptrCast(*const IWMPContentPartner, self), pInfo, pbstrTotalPrice, pSilentOK);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IWMPContentPartner_Buy(self: *const T, pInfo: ?*IWMPContentContainerList, cookie: u32) callconv(.Inline) HRESULT {
return @ptrCast(*const IWMPContentPartner.VTable, self.vtable).Buy(@ptrCast(*const IWMPContentPartner, self), pInfo, cookie);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IWMPContentPartner_GetStreamingURL(self: *const T, st: WMPStreamingType, pStreamContext: ?*VARIANT, pbstrURL: ?*?BSTR) callconv(.Inline) HRESULT {
return @ptrCast(*const IWMPContentPartner.VTable, self.vtable).GetStreamingURL(@ptrCast(*const IWMPContentPartner, self), st, pStreamContext, pbstrURL);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IWMPContentPartner_Download(self: *const T, pInfo: ?*IWMPContentContainerList, cookie: u32) callconv(.Inline) HRESULT {
return @ptrCast(*const IWMPContentPartner.VTable, self.vtable).Download(@ptrCast(*const IWMPContentPartner, self), pInfo, cookie);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IWMPContentPartner_DownloadTrackComplete(self: *const T, hrResult: HRESULT, contentID: u32, downloadTrackParam: ?BSTR) callconv(.Inline) HRESULT {
return @ptrCast(*const IWMPContentPartner.VTable, self.vtable).DownloadTrackComplete(@ptrCast(*const IWMPContentPartner, self), hrResult, contentID, downloadTrackParam);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IWMPContentPartner_RefreshLicense(self: *const T, dwCookie: u32, fLocal: i16, bstrURL: ?BSTR, type_: WMPStreamingType, contentID: u32, bstrRefreshReason: ?BSTR, pReasonContext: ?*VARIANT) callconv(.Inline) HRESULT {
return @ptrCast(*const IWMPContentPartner.VTable, self.vtable).RefreshLicense(@ptrCast(*const IWMPContentPartner, self), dwCookie, fLocal, bstrURL, type_, contentID, bstrRefreshReason, pReasonContext);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IWMPContentPartner_GetCatalogURL(self: *const T, dwCatalogVersion: u32, dwCatalogSchemaVersion: u32, catalogLCID: u32, pdwNewCatalogVersion: ?*u32, pbstrCatalogURL: ?*?BSTR, pExpirationDate: ?*VARIANT) callconv(.Inline) HRESULT {
return @ptrCast(*const IWMPContentPartner.VTable, self.vtable).GetCatalogURL(@ptrCast(*const IWMPContentPartner, self), dwCatalogVersion, dwCatalogSchemaVersion, catalogLCID, pdwNewCatalogVersion, pbstrCatalogURL, pExpirationDate);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IWMPContentPartner_GetTemplate(self: *const T, task: WMPTaskType, location: ?BSTR, pContext: ?*VARIANT, clickLocation: ?BSTR, pClickContext: ?*VARIANT, bstrFilter: ?BSTR, bstrViewParams: ?BSTR, pbstrTemplateURL: ?*?BSTR, pTemplateSize: ?*WMPTemplateSize) callconv(.Inline) HRESULT {
return @ptrCast(*const IWMPContentPartner.VTable, self.vtable).GetTemplate(@ptrCast(*const IWMPContentPartner, self), task, location, pContext, clickLocation, pClickContext, bstrFilter, bstrViewParams, pbstrTemplateURL, pTemplateSize);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IWMPContentPartner_UpdateDevice(self: *const T, bstrDeviceName: ?BSTR) callconv(.Inline) HRESULT {
return @ptrCast(*const IWMPContentPartner.VTable, self.vtable).UpdateDevice(@ptrCast(*const IWMPContentPartner, self), bstrDeviceName);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IWMPContentPartner_GetListContents(self: *const T, location: ?BSTR, pContext: ?*VARIANT, bstrListType: ?BSTR, bstrParams: ?BSTR, dwListCookie: u32) callconv(.Inline) HRESULT {
return @ptrCast(*const IWMPContentPartner.VTable, self.vtable).GetListContents(@ptrCast(*const IWMPContentPartner, self), location, pContext, bstrListType, bstrParams, dwListCookie);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IWMPContentPartner_Login(self: *const T, userInfo: BLOB, pwdInfo: BLOB, fUsedCachedCreds: i16, fOkToCache: i16) callconv(.Inline) HRESULT {
return @ptrCast(*const IWMPContentPartner.VTable, self.vtable).Login(@ptrCast(*const IWMPContentPartner, self), userInfo, pwdInfo, fUsedCachedCreds, fOkToCache);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IWMPContentPartner_Authenticate(self: *const T, userInfo: BLOB, pwdInfo: BLOB) callconv(.Inline) HRESULT {
return @ptrCast(*const IWMPContentPartner.VTable, self.vtable).Authenticate(@ptrCast(*const IWMPContentPartner, self), userInfo, pwdInfo);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IWMPContentPartner_Logout(self: *const T) callconv(.Inline) HRESULT {
return @ptrCast(*const IWMPContentPartner.VTable, self.vtable).Logout(@ptrCast(*const IWMPContentPartner, self));
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IWMPContentPartner_SendMessage(self: *const T, bstrMsg: ?BSTR, bstrParam: ?BSTR) callconv(.Inline) HRESULT {
return @ptrCast(*const IWMPContentPartner.VTable, self.vtable).SendMessage(@ptrCast(*const IWMPContentPartner, self), bstrMsg, bstrParam);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IWMPContentPartner_StationEvent(self: *const T, bstrStationEventType: ?BSTR, StationId: u32, PlaylistIndex: u32, TrackID: u32, TrackData: ?BSTR, dwSecondsPlayed: u32) callconv(.Inline) HRESULT {
return @ptrCast(*const IWMPContentPartner.VTable, self.vtable).StationEvent(@ptrCast(*const IWMPContentPartner, self), bstrStationEventType, StationId, PlaylistIndex, TrackID, TrackData, dwSecondsPlayed);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IWMPContentPartner_CompareContainerListPrices(self: *const T, pListBase: ?*IWMPContentContainerList, pListCompare: ?*IWMPContentContainerList, pResult: ?*i32) callconv(.Inline) HRESULT {
return @ptrCast(*const IWMPContentPartner.VTable, self.vtable).CompareContainerListPrices(@ptrCast(*const IWMPContentPartner, self), pListBase, pListCompare, pResult);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IWMPContentPartner_VerifyPermission(self: *const T, bstrPermission: ?BSTR, pContext: ?*VARIANT) callconv(.Inline) HRESULT {
return @ptrCast(*const IWMPContentPartner.VTable, self.vtable).VerifyPermission(@ptrCast(*const IWMPContentPartner, self), bstrPermission, pContext);
}
};}
pub usingnamespace MethodMixin(@This());
};
pub const WMPSubscriptionServiceEvent = enum(i32) {
CurrentBegin = 1,
CurrentEnd = 2,
FullBegin = 3,
FullEnd = 4,
};
pub const wmpsseCurrentBegin = WMPSubscriptionServiceEvent.CurrentBegin;
pub const wmpsseCurrentEnd = WMPSubscriptionServiceEvent.CurrentEnd;
pub const wmpsseFullBegin = WMPSubscriptionServiceEvent.FullBegin;
pub const wmpsseFullEnd = WMPSubscriptionServiceEvent.FullEnd;
const IID_IWMPSubscriptionService_Value = Guid.initString("376055f8-2a59-4a73-9501-dca5273a7a10");
pub const IID_IWMPSubscriptionService = &IID_IWMPSubscriptionService_Value;
pub const IWMPSubscriptionService = extern struct {
pub const VTable = extern struct {
base: IUnknown.VTable,
allowPlay: fn(
self: *const IWMPSubscriptionService,
hwnd: ?HWND,
pMedia: ?*IWMPMedia,
pfAllowPlay: ?*BOOL,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
allowCDBurn: fn(
self: *const IWMPSubscriptionService,
hwnd: ?HWND,
pPlaylist: ?*IWMPPlaylist,
pfAllowBurn: ?*BOOL,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
allowPDATransfer: fn(
self: *const IWMPSubscriptionService,
hwnd: ?HWND,
pPlaylist: ?*IWMPPlaylist,
pfAllowTransfer: ?*BOOL,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
startBackgroundProcessing: fn(
self: *const IWMPSubscriptionService,
hwnd: ?HWND,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
};
vtable: *const VTable,
pub fn MethodMixin(comptime T: type) type { return struct {
pub usingnamespace IUnknown.MethodMixin(T);
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IWMPSubscriptionService_allowPlay(self: *const T, hwnd: ?HWND, pMedia: ?*IWMPMedia, pfAllowPlay: ?*BOOL) callconv(.Inline) HRESULT {
return @ptrCast(*const IWMPSubscriptionService.VTable, self.vtable).allowPlay(@ptrCast(*const IWMPSubscriptionService, self), hwnd, pMedia, pfAllowPlay);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IWMPSubscriptionService_allowCDBurn(self: *const T, hwnd: ?HWND, pPlaylist: ?*IWMPPlaylist, pfAllowBurn: ?*BOOL) callconv(.Inline) HRESULT {
return @ptrCast(*const IWMPSubscriptionService.VTable, self.vtable).allowCDBurn(@ptrCast(*const IWMPSubscriptionService, self), hwnd, pPlaylist, pfAllowBurn);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IWMPSubscriptionService_allowPDATransfer(self: *const T, hwnd: ?HWND, pPlaylist: ?*IWMPPlaylist, pfAllowTransfer: ?*BOOL) callconv(.Inline) HRESULT {
return @ptrCast(*const IWMPSubscriptionService.VTable, self.vtable).allowPDATransfer(@ptrCast(*const IWMPSubscriptionService, self), hwnd, pPlaylist, pfAllowTransfer);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IWMPSubscriptionService_startBackgroundProcessing(self: *const T, hwnd: ?HWND) callconv(.Inline) HRESULT {
return @ptrCast(*const IWMPSubscriptionService.VTable, self.vtable).startBackgroundProcessing(@ptrCast(*const IWMPSubscriptionService, self), hwnd);
}
};}
pub usingnamespace MethodMixin(@This());
};
const IID_IWMPSubscriptionServiceCallback_Value = Guid.initString("dd01d127-2dc2-4c3a-876e-63312079f9b0");
pub const IID_IWMPSubscriptionServiceCallback = &IID_IWMPSubscriptionServiceCallback_Value;
pub const IWMPSubscriptionServiceCallback = extern struct {
pub const VTable = extern struct {
base: IUnknown.VTable,
onComplete: fn(
self: *const IWMPSubscriptionServiceCallback,
hrResult: HRESULT,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
};
vtable: *const VTable,
pub fn MethodMixin(comptime T: type) type { return struct {
pub usingnamespace IUnknown.MethodMixin(T);
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IWMPSubscriptionServiceCallback_onComplete(self: *const T, hrResult: HRESULT) callconv(.Inline) HRESULT {
return @ptrCast(*const IWMPSubscriptionServiceCallback.VTable, self.vtable).onComplete(@ptrCast(*const IWMPSubscriptionServiceCallback, self), hrResult);
}
};}
pub usingnamespace MethodMixin(@This());
};
const IID_IWMPSubscriptionService2_Value = Guid.initString("a94c120e-d600-4ec6-b05e-ec9d56d84de0");
pub const IID_IWMPSubscriptionService2 = &IID_IWMPSubscriptionService2_Value;
pub const IWMPSubscriptionService2 = extern struct {
pub const VTable = extern struct {
base: IWMPSubscriptionService.VTable,
stopBackgroundProcessing: fn(
self: *const IWMPSubscriptionService2,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
serviceEvent: fn(
self: *const IWMPSubscriptionService2,
event: WMPSubscriptionServiceEvent,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
deviceAvailable: fn(
self: *const IWMPSubscriptionService2,
bstrDeviceName: ?BSTR,
pCB: ?*IWMPSubscriptionServiceCallback,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
prepareForSync: fn(
self: *const IWMPSubscriptionService2,
bstrFilename: ?BSTR,
bstrDeviceName: ?BSTR,
pCB: ?*IWMPSubscriptionServiceCallback,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
};
vtable: *const VTable,
pub fn MethodMixin(comptime T: type) type { return struct {
pub usingnamespace IWMPSubscriptionService.MethodMixin(T);
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IWMPSubscriptionService2_stopBackgroundProcessing(self: *const T) callconv(.Inline) HRESULT {
return @ptrCast(*const IWMPSubscriptionService2.VTable, self.vtable).stopBackgroundProcessing(@ptrCast(*const IWMPSubscriptionService2, self));
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IWMPSubscriptionService2_serviceEvent(self: *const T, event: WMPSubscriptionServiceEvent) callconv(.Inline) HRESULT {
return @ptrCast(*const IWMPSubscriptionService2.VTable, self.vtable).serviceEvent(@ptrCast(*const IWMPSubscriptionService2, self), event);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IWMPSubscriptionService2_deviceAvailable(self: *const T, bstrDeviceName: ?BSTR, pCB: ?*IWMPSubscriptionServiceCallback) callconv(.Inline) HRESULT {
return @ptrCast(*const IWMPSubscriptionService2.VTable, self.vtable).deviceAvailable(@ptrCast(*const IWMPSubscriptionService2, self), bstrDeviceName, pCB);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IWMPSubscriptionService2_prepareForSync(self: *const T, bstrFilename: ?BSTR, bstrDeviceName: ?BSTR, pCB: ?*IWMPSubscriptionServiceCallback) callconv(.Inline) HRESULT {
return @ptrCast(*const IWMPSubscriptionService2.VTable, self.vtable).prepareForSync(@ptrCast(*const IWMPSubscriptionService2, self), bstrFilename, bstrDeviceName, pCB);
}
};}
pub usingnamespace MethodMixin(@This());
};
pub const WMPSubscriptionDownloadState = enum(i32) {
Downloading = 0,
Paused = 1,
Processing = 2,
Completed = 3,
Cancelled = 4,
};
pub const wmpsdlsDownloading = WMPSubscriptionDownloadState.Downloading;
pub const wmpsdlsPaused = WMPSubscriptionDownloadState.Paused;
pub const wmpsdlsProcessing = WMPSubscriptionDownloadState.Processing;
pub const wmpsdlsCompleted = WMPSubscriptionDownloadState.Completed;
pub const wmpsdlsCancelled = WMPSubscriptionDownloadState.Cancelled;
const IID_IWMPDownloadItem_Value = Guid.initString("c9470e8e-3f6b-46a9-a0a9-452815c34297");
pub const IID_IWMPDownloadItem = &IID_IWMPDownloadItem_Value;
pub const IWMPDownloadItem = extern struct {
pub const VTable = extern struct {
base: IDispatch.VTable,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_sourceURL: fn(
self: *const IWMPDownloadItem,
pbstrURL: ?*?BSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_size: fn(
self: *const IWMPDownloadItem,
plSize: ?*i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_type: fn(
self: *const IWMPDownloadItem,
pbstrType: ?*?BSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_progress: fn(
self: *const IWMPDownloadItem,
plProgress: ?*i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_downloadState: fn(
self: *const IWMPDownloadItem,
pwmpsdls: ?*WMPSubscriptionDownloadState,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
pause: fn(
self: *const IWMPDownloadItem,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
@"resume": fn(
self: *const IWMPDownloadItem,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
cancel: fn(
self: *const IWMPDownloadItem,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
};
vtable: *const VTable,
pub fn MethodMixin(comptime T: type) type { return struct {
pub usingnamespace IDispatch.MethodMixin(T);
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IWMPDownloadItem_get_sourceURL(self: *const T, pbstrURL: ?*?BSTR) callconv(.Inline) HRESULT {
return @ptrCast(*const IWMPDownloadItem.VTable, self.vtable).get_sourceURL(@ptrCast(*const IWMPDownloadItem, self), pbstrURL);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IWMPDownloadItem_get_size(self: *const T, plSize: ?*i32) callconv(.Inline) HRESULT {
return @ptrCast(*const IWMPDownloadItem.VTable, self.vtable).get_size(@ptrCast(*const IWMPDownloadItem, self), plSize);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IWMPDownloadItem_get_type(self: *const T, pbstrType: ?*?BSTR) callconv(.Inline) HRESULT {
return @ptrCast(*const IWMPDownloadItem.VTable, self.vtable).get_type(@ptrCast(*const IWMPDownloadItem, self), pbstrType);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IWMPDownloadItem_get_progress(self: *const T, plProgress: ?*i32) callconv(.Inline) HRESULT {
return @ptrCast(*const IWMPDownloadItem.VTable, self.vtable).get_progress(@ptrCast(*const IWMPDownloadItem, self), plProgress);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IWMPDownloadItem_get_downloadState(self: *const T, pwmpsdls: ?*WMPSubscriptionDownloadState) callconv(.Inline) HRESULT {
return @ptrCast(*const IWMPDownloadItem.VTable, self.vtable).get_downloadState(@ptrCast(*const IWMPDownloadItem, self), pwmpsdls);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IWMPDownloadItem_pause(self: *const T) callconv(.Inline) HRESULT {
return @ptrCast(*const IWMPDownloadItem.VTable, self.vtable).pause(@ptrCast(*const IWMPDownloadItem, self));
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IWMPDownloadItem_resume(self: *const T) callconv(.Inline) HRESULT {
return @ptrCast(*const IWMPDownloadItem.VTable, self.vtable).@"resume"(@ptrCast(*const IWMPDownloadItem, self));
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IWMPDownloadItem_cancel(self: *const T) callconv(.Inline) HRESULT {
return @ptrCast(*const IWMPDownloadItem.VTable, self.vtable).cancel(@ptrCast(*const IWMPDownloadItem, self));
}
};}
pub usingnamespace MethodMixin(@This());
};
const IID_IWMPDownloadItem2_Value = Guid.initString("9fbb3336-6da3-479d-b8ff-67d46e20a987");
pub const IID_IWMPDownloadItem2 = &IID_IWMPDownloadItem2_Value;
pub const IWMPDownloadItem2 = extern struct {
pub const VTable = extern struct {
base: IWMPDownloadItem.VTable,
getItemInfo: fn(
self: *const IWMPDownloadItem2,
bstrItemName: ?BSTR,
pbstrVal: ?*?BSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
};
vtable: *const VTable,
pub fn MethodMixin(comptime T: type) type { return struct {
pub usingnamespace IWMPDownloadItem.MethodMixin(T);
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IWMPDownloadItem2_getItemInfo(self: *const T, bstrItemName: ?BSTR, pbstrVal: ?*?BSTR) callconv(.Inline) HRESULT {
return @ptrCast(*const IWMPDownloadItem2.VTable, self.vtable).getItemInfo(@ptrCast(*const IWMPDownloadItem2, self), bstrItemName, pbstrVal);
}
};}
pub usingnamespace MethodMixin(@This());
};
const IID_IWMPDownloadCollection_Value = Guid.initString("0a319c7f-85f9-436c-b88e-82fd88000e1c");
pub const IID_IWMPDownloadCollection = &IID_IWMPDownloadCollection_Value;
pub const IWMPDownloadCollection = extern struct {
pub const VTable = extern struct {
base: IDispatch.VTable,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_id: fn(
self: *const IWMPDownloadCollection,
plId: ?*i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
// TODO: this function has a "SpecialName", should Zig do anything with this?
get_count: fn(
self: *const IWMPDownloadCollection,
plCount: ?*i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
item: fn(
self: *const IWMPDownloadCollection,
lItem: i32,
ppDownload: ?*?*IWMPDownloadItem2,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
startDownload: fn(
self: *const IWMPDownloadCollection,
bstrSourceURL: ?BSTR,
bstrType: ?BSTR,
ppDownload: ?*?*IWMPDownloadItem2,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
removeItem: fn(
self: *const IWMPDownloadCollection,
lItem: i32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
Clear: fn(
self: *const IWMPDownloadCollection,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
};
vtable: *const VTable,
pub fn MethodMixin(comptime T: type) type { return struct {
pub usingnamespace IDispatch.MethodMixin(T);
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IWMPDownloadCollection_get_id(self: *const T, plId: ?*i32) callconv(.Inline) HRESULT {
return @ptrCast(*const IWMPDownloadCollection.VTable, self.vtable).get_id(@ptrCast(*const IWMPDownloadCollection, self), plId);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IWMPDownloadCollection_get_count(self: *const T, plCount: ?*i32) callconv(.Inline) HRESULT {
return @ptrCast(*const IWMPDownloadCollection.VTable, self.vtable).get_count(@ptrCast(*const IWMPDownloadCollection, self), plCount);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IWMPDownloadCollection_item(self: *const T, lItem: i32, ppDownload: ?*?*IWMPDownloadItem2) callconv(.Inline) HRESULT {
return @ptrCast(*const IWMPDownloadCollection.VTable, self.vtable).item(@ptrCast(*const IWMPDownloadCollection, self), lItem, ppDownload);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IWMPDownloadCollection_startDownload(self: *const T, bstrSourceURL: ?BSTR, bstrType: ?BSTR, ppDownload: ?*?*IWMPDownloadItem2) callconv(.Inline) HRESULT {
return @ptrCast(*const IWMPDownloadCollection.VTable, self.vtable).startDownload(@ptrCast(*const IWMPDownloadCollection, self), bstrSourceURL, bstrType, ppDownload);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IWMPDownloadCollection_removeItem(self: *const T, lItem: i32) callconv(.Inline) HRESULT {
return @ptrCast(*const IWMPDownloadCollection.VTable, self.vtable).removeItem(@ptrCast(*const IWMPDownloadCollection, self), lItem);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IWMPDownloadCollection_Clear(self: *const T) callconv(.Inline) HRESULT {
return @ptrCast(*const IWMPDownloadCollection.VTable, self.vtable).Clear(@ptrCast(*const IWMPDownloadCollection, self));
}
};}
pub usingnamespace MethodMixin(@This());
};
const IID_IWMPDownloadManager_Value = Guid.initString("e15e9ad1-8f20-4cc4-9ec7-1a328ca86a0d");
pub const IID_IWMPDownloadManager = &IID_IWMPDownloadManager_Value;
pub const IWMPDownloadManager = extern struct {
pub const VTable = extern struct {
base: IDispatch.VTable,
getDownloadCollection: fn(
self: *const IWMPDownloadManager,
lCollectionId: i32,
ppCollection: ?*?*IWMPDownloadCollection,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
createDownloadCollection: fn(
self: *const IWMPDownloadManager,
ppCollection: ?*?*IWMPDownloadCollection,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
};
vtable: *const VTable,
pub fn MethodMixin(comptime T: type) type { return struct {
pub usingnamespace IDispatch.MethodMixin(T);
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IWMPDownloadManager_getDownloadCollection(self: *const T, lCollectionId: i32, ppCollection: ?*?*IWMPDownloadCollection) callconv(.Inline) HRESULT {
return @ptrCast(*const IWMPDownloadManager.VTable, self.vtable).getDownloadCollection(@ptrCast(*const IWMPDownloadManager, self), lCollectionId, ppCollection);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IWMPDownloadManager_createDownloadCollection(self: *const T, ppCollection: ?*?*IWMPDownloadCollection) callconv(.Inline) HRESULT {
return @ptrCast(*const IWMPDownloadManager.VTable, self.vtable).createDownloadCollection(@ptrCast(*const IWMPDownloadManager, self), ppCollection);
}
};}
pub usingnamespace MethodMixin(@This());
};
pub const WMP_WMDM_METADATA_ROUND_TRIP_PC2DEVICE = packed struct {
dwChangesSinceTransactionID: u32,
dwResultSetStartingIndex: u32,
};
pub const WMP_WMDM_METADATA_ROUND_TRIP_DEVICE2PC = packed struct {
dwCurrentTransactionID: u32,
dwReturnedObjectCount: u32,
dwUnretrievedObjectCount: u32,
dwDeletedObjectStartingOffset: u32,
dwFlags: u32,
wsObjectPathnameList: [1]u16,
};
//--------------------------------------------------------------------------------
// 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 (21)
//--------------------------------------------------------------------------------
const Guid = @import("../zig.zig").Guid;
const BLOB = @import("../system/com.zig").BLOB;
const BOOL = @import("../foundation.zig").BOOL;
const BSTR = @import("../foundation.zig").BSTR;
const HDC = @import("../graphics/gdi.zig").HDC;
const HRESULT = @import("../foundation.zig").HRESULT;
const HWND = @import("../foundation.zig").HWND;
const IDispatch = @import("../system/com.zig").IDispatch;
const IEnumVARIANT = @import("../system/ole.zig").IEnumVARIANT;
const IMFActivate = @import("../media/media_foundation.zig").IMFActivate;
const IStream = @import("../system/com.zig").IStream;
const IUnknown = @import("../system/com.zig").IUnknown;
const LPARAM = @import("../foundation.zig").LPARAM;
const LRESULT = @import("../foundation.zig").LRESULT;
const MSG = @import("../ui/windows_and_messaging.zig").MSG;
const PWSTR = @import("../foundation.zig").PWSTR;
const RECT = @import("../foundation.zig").RECT;
const SIZE = @import("../foundation.zig").SIZE;
const SYSTEMTIME = @import("../foundation.zig").SYSTEMTIME;
const VARIANT = @import("../system/com.zig").VARIANT;
const WPARAM = @import("../foundation.zig").WPARAM;
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/media/media_player.zig |
const std = @import("../std.zig");
const maxInt = std.math.maxInt;
const iovec = std.os.iovec;
extern "c" threadlocal var errno: c_int;
pub fn _errno() *c_int {
return &errno;
}
pub extern "c" fn getdents(fd: c_int, buf_ptr: [*]u8, nbytes: usize) usize;
pub extern "c" fn sigaltstack(ss: ?*stack_t, old_ss: ?*stack_t) c_int;
pub extern "c" fn getrandom(buf_ptr: [*]u8, buf_len: usize, flags: c_uint) isize;
pub extern "c" fn pipe2(fds: *[2]fd_t, flags: u32) c_int;
pub const dl_iterate_phdr_callback = fn (info: *dl_phdr_info, size: usize, data: ?*anyopaque) callconv(.C) c_int;
pub extern "c" fn dl_iterate_phdr(callback: dl_iterate_phdr_callback, data: ?*anyopaque) c_int;
pub extern "c" fn lwp_gettid() c_int;
pub extern "c" fn posix_memalign(memptr: *?*anyopaque, alignment: usize, size: usize) c_int;
pub const pthread_mutex_t = extern struct {
inner: ?*anyopaque = null,
};
pub const pthread_cond_t = extern struct {
inner: ?*anyopaque = null,
};
pub const pthread_attr_t = extern struct { // copied from freebsd
__size: [56]u8,
__align: c_long,
};
pub const sem_t = ?*opaque {};
pub extern "c" fn pthread_setname_np(thread: std.c.pthread_t, name: [*:0]const u8) E;
pub extern "c" fn pthread_getname_np(thread: std.c.pthread_t, name: [*:0]u8, len: usize) E;
// See:
// - https://gitweb.dragonflybsd.org/dragonfly.git/blob/HEAD:/include/unistd.h
// - https://gitweb.dragonflybsd.org/dragonfly.git/blob/HEAD:/sys/sys/types.h
// TODO: mode_t should probably be changed to a u16, audit pid_t/off_t as well
pub const fd_t = c_int;
pub const pid_t = c_int;
pub const off_t = c_long;
pub const mode_t = c_uint;
pub const uid_t = u32;
pub const gid_t = u32;
pub const time_t = isize;
pub const suseconds_t = c_long;
pub const E = enum(u16) {
/// No error occurred.
SUCCESS = 0,
PERM = 1,
NOENT = 2,
SRCH = 3,
INTR = 4,
IO = 5,
NXIO = 6,
@"2BIG" = 7,
NOEXEC = 8,
BADF = 9,
CHILD = 10,
DEADLK = 11,
NOMEM = 12,
ACCES = 13,
FAULT = 14,
NOTBLK = 15,
BUSY = 16,
EXIST = 17,
XDEV = 18,
NODEV = 19,
NOTDIR = 20,
ISDIR = 21,
INVAL = 22,
NFILE = 23,
MFILE = 24,
NOTTY = 25,
TXTBSY = 26,
FBIG = 27,
NOSPC = 28,
SPIPE = 29,
ROFS = 30,
MLINK = 31,
PIPE = 32,
DOM = 33,
RANGE = 34,
/// This code is also used for `WOULDBLOCK`.
AGAIN = 35,
INPROGRESS = 36,
ALREADY = 37,
NOTSOCK = 38,
DESTADDRREQ = 39,
MSGSIZE = 40,
PROTOTYPE = 41,
NOPROTOOPT = 42,
PROTONOSUPPORT = 43,
SOCKTNOSUPPORT = 44,
/// This code is also used for `NOTSUP`.
OPNOTSUPP = 45,
PFNOSUPPORT = 46,
AFNOSUPPORT = 47,
ADDRINUSE = 48,
ADDRNOTAVAIL = 49,
NETDOWN = 50,
NETUNREACH = 51,
NETRESET = 52,
CONNABORTED = 53,
CONNRESET = 54,
NOBUFS = 55,
ISCONN = 56,
NOTCONN = 57,
SHUTDOWN = 58,
TOOMANYREFS = 59,
TIMEDOUT = 60,
CONNREFUSED = 61,
LOOP = 62,
NAMETOOLONG = 63,
HOSTDOWN = 64,
HOSTUNREACH = 65,
NOTEMPTY = 66,
PROCLIM = 67,
USERS = 68,
DQUOT = 69,
STALE = 70,
REMOTE = 71,
BADRPC = 72,
RPCMISMATCH = 73,
PROGUNAVAIL = 74,
PROGMISMATCH = 75,
PROCUNAVAIL = 76,
NOLCK = 77,
NOSYS = 78,
FTYPE = 79,
AUTH = 80,
NEEDAUTH = 81,
IDRM = 82,
NOMSG = 83,
OVERFLOW = 84,
CANCELED = 85,
ILSEQ = 86,
NOATTR = 87,
DOOFUS = 88,
BADMSG = 89,
MULTIHOP = 90,
NOLINK = 91,
PROTO = 92,
NOMEDIUM = 93,
ASYNC = 99,
_,
};
pub const STDIN_FILENO = 0;
pub const STDOUT_FILENO = 1;
pub const STDERR_FILENO = 2;
pub const PROT = struct {
pub const NONE = 0;
pub const READ = 1;
pub const WRITE = 2;
pub const EXEC = 4;
};
pub const MAP = struct {
pub const FILE = 0;
pub const FAILED = @intToPtr(*anyopaque, maxInt(usize));
pub const ANONYMOUS = ANON;
pub const COPY = PRIVATE;
pub const SHARED = 1;
pub const PRIVATE = 2;
pub const FIXED = 16;
pub const RENAME = 32;
pub const NORESERVE = 64;
pub const INHERIT = 128;
pub const NOEXTEND = 256;
pub const HASSEMAPHORE = 512;
pub const STACK = 1024;
pub const NOSYNC = 2048;
pub const ANON = 4096;
pub const VPAGETABLE = 8192;
pub const TRYFIXED = 65536;
pub const NOCORE = 131072;
pub const SIZEALIGN = 262144;
};
pub const MSF = struct {
pub const ASYNC = 1;
pub const INVALIDATE = 2;
pub const SYNC = 4;
};
pub const W = struct {
pub const NOHANG = 0x0001;
pub const UNTRACED = 0x0002;
pub const CONTINUED = 0x0004;
pub const STOPPED = UNTRACED;
pub const NOWAIT = 0x0008;
pub const EXITED = 0x0010;
pub const TRAPPED = 0x0020;
pub fn EXITSTATUS(s: u32) u8 {
return @intCast(u8, (s & 0xff00) >> 8);
}
pub fn TERMSIG(s: u32) u32 {
return s & 0x7f;
}
pub fn STOPSIG(s: u32) u32 {
return EXITSTATUS(s);
}
pub fn IFEXITED(s: u32) bool {
return TERMSIG(s) == 0;
}
pub fn IFSTOPPED(s: u32) bool {
return @truncate(u16, (((s & 0xffff) *% 0x10001) >> 8)) > 0x7f00;
}
pub fn IFSIGNALED(s: u32) bool {
return (s & 0xffff) -% 1 < 0xff;
}
};
pub const SA = struct {
pub const ONSTACK = 0x0001;
pub const RESTART = 0x0002;
pub const RESETHAND = 0x0004;
pub const NODEFER = 0x0010;
pub const NOCLDWAIT = 0x0020;
pub const SIGINFO = 0x0040;
};
pub const PATH_MAX = 1024;
pub const IOV_MAX = KERN.IOV_MAX;
pub const ino_t = c_ulong;
pub const Stat = extern struct {
ino: ino_t,
nlink: c_uint,
dev: c_uint,
mode: c_ushort,
padding1: u16,
uid: uid_t,
gid: gid_t,
rdev: c_uint,
atim: timespec,
mtim: timespec,
ctim: timespec,
size: c_ulong,
blocks: i64,
blksize: u32,
flags: u32,
gen: u32,
lspare: i32,
qspare1: i64,
qspare2: i64,
pub fn atime(self: @This()) timespec {
return self.atim;
}
pub fn mtime(self: @This()) timespec {
return self.mtim;
}
pub fn ctime(self: @This()) timespec {
return self.ctim;
}
};
pub const timespec = extern struct {
tv_sec: c_long,
tv_nsec: c_long,
};
pub const timeval = extern struct {
/// seconds
tv_sec: time_t,
/// microseconds
tv_usec: suseconds_t,
};
pub const CTL = struct {
pub const UNSPEC = 0;
pub const KERN = 1;
pub const VM = 2;
pub const VFS = 3;
pub const NET = 4;
pub const DEBUG = 5;
pub const HW = 6;
pub const MACHDEP = 7;
pub const USER = 8;
pub const LWKT = 10;
pub const MAXID = 11;
pub const MAXNAME = 12;
};
pub const KERN = struct {
pub const PROC_ALL = 0;
pub const OSTYPE = 1;
pub const PROC_PID = 1;
pub const OSRELEASE = 2;
pub const PROC_PGRP = 2;
pub const OSREV = 3;
pub const PROC_SESSION = 3;
pub const VERSION = 4;
pub const PROC_TTY = 4;
pub const MAXVNODES = 5;
pub const PROC_UID = 5;
pub const MAXPROC = 6;
pub const PROC_RUID = 6;
pub const MAXFILES = 7;
pub const PROC_ARGS = 7;
pub const ARGMAX = 8;
pub const PROC_CWD = 8;
pub const PROC_PATHNAME = 9;
pub const SECURELVL = 9;
pub const PROC_SIGTRAMP = 10;
pub const HOSTNAME = 10;
pub const HOSTID = 11;
pub const CLOCKRATE = 12;
pub const VNODE = 13;
pub const PROC = 14;
pub const FILE = 15;
pub const PROC_FLAGMASK = 16;
pub const PROF = 16;
pub const PROC_FLAG_LWP = 16;
pub const POSIX1 = 17;
pub const NGROUPS = 18;
pub const JOB_CONTROL = 19;
pub const SAVED_IDS = 20;
pub const BOOTTIME = 21;
pub const NISDOMAINNAME = 22;
pub const UPDATEINTERVAL = 23;
pub const OSRELDATE = 24;
pub const NTP_PLL = 25;
pub const BOOTFILE = 26;
pub const MAXFILESPERPROC = 27;
pub const MAXPROCPERUID = 28;
pub const DUMPDEV = 29;
pub const IPC = 30;
pub const DUMMY = 31;
pub const PS_STRINGS = 32;
pub const USRSTACK = 33;
pub const LOGSIGEXIT = 34;
pub const IOV_MAX = 35;
pub const MAXPOSIXLOCKSPERUID = 36;
pub const MAXID = 37;
};
pub const HOST_NAME_MAX = 255;
// access function
pub const F_OK = 0; // test for existence of file
pub const X_OK = 1; // test for execute or search permission
pub const W_OK = 2; // test for write permission
pub const R_OK = 4; // test for read permission
pub const O = struct {
pub const RDONLY = 0;
pub const NDELAY = NONBLOCK;
pub const WRONLY = 1;
pub const RDWR = 2;
pub const ACCMODE = 3;
pub const NONBLOCK = 4;
pub const APPEND = 8;
pub const SHLOCK = 16;
pub const EXLOCK = 32;
pub const ASYNC = 64;
pub const FSYNC = 128;
pub const SYNC = 128;
pub const NOFOLLOW = 256;
pub const CREAT = 512;
pub const TRUNC = 1024;
pub const EXCL = 2048;
pub const NOCTTY = 32768;
pub const DIRECT = 65536;
pub const CLOEXEC = 131072;
pub const FBLOCKING = 262144;
pub const FNONBLOCKING = 524288;
pub const FAPPEND = 1048576;
pub const FOFFSET = 2097152;
pub const FSYNCWRITE = 4194304;
pub const FASYNCWRITE = 8388608;
pub const DIRECTORY = 134217728;
};
pub const SEEK = struct {
pub const SET = 0;
pub const CUR = 1;
pub const END = 2;
pub const DATA = 3;
pub const HOLE = 4;
};
pub const F = struct {
pub const ULOCK = 0;
pub const LOCK = 1;
pub const TLOCK = 2;
pub const TEST = 3;
pub const DUPFD = 0;
pub const GETFD = 1;
pub const RDLCK = 1;
pub const SETFD = 2;
pub const UNLCK = 2;
pub const WRLCK = 3;
pub const GETFL = 3;
pub const SETFL = 4;
pub const GETOWN = 5;
pub const SETOWN = 6;
pub const GETLK = 7;
pub const SETLK = 8;
pub const SETLKW = 9;
pub const DUP2FD = 10;
pub const DUPFD_CLOEXEC = 17;
pub const DUP2FD_CLOEXEC = 18;
};
pub const FD_CLOEXEC = 1;
pub const AT = struct {
pub const FDCWD = -328243;
pub const SYMLINK_NOFOLLOW = 1;
pub const REMOVEDIR = 2;
pub const EACCESS = 4;
pub const SYMLINK_FOLLOW = 8;
};
pub const dirent = extern struct {
d_fileno: c_ulong,
d_namlen: u16,
d_type: u8,
d_unused1: u8,
d_unused2: u32,
d_name: [256]u8,
pub fn reclen(self: dirent) u16 {
return (@offsetOf(dirent, "d_name") + self.d_namlen + 1 + 7) & ~@as(u16, 7);
}
};
pub const DT = struct {
pub const UNKNOWN = 0;
pub const FIFO = 1;
pub const CHR = 2;
pub const DIR = 4;
pub const BLK = 6;
pub const REG = 8;
pub const LNK = 10;
pub const SOCK = 12;
pub const WHT = 14;
pub const DBF = 15;
};
pub const CLOCK = struct {
pub const REALTIME = 0;
pub const VIRTUAL = 1;
pub const PROF = 2;
pub const MONOTONIC = 4;
pub const UPTIME = 5;
pub const UPTIME_PRECISE = 7;
pub const UPTIME_FAST = 8;
pub const REALTIME_PRECISE = 9;
pub const REALTIME_FAST = 10;
pub const MONOTONIC_PRECISE = 11;
pub const MONOTONIC_FAST = 12;
pub const SECOND = 13;
pub const THREAD_CPUTIME_ID = 14;
pub const PROCESS_CPUTIME_ID = 15;
};
pub const sockaddr = extern struct {
len: u8,
family: u8,
data: [14]u8,
pub const SS_MAXSIZE = 128;
pub const storage = std.x.os.Socket.Address.Native.Storage;
pub const in = extern struct {
len: u8 = @sizeOf(in),
family: sa_family_t = AF.INET,
port: in_port_t,
addr: u32,
zero: [8]u8 = [8]u8{ 0, 0, 0, 0, 0, 0, 0, 0 },
};
pub const in6 = extern struct {
len: u8 = @sizeOf(in6),
family: sa_family_t = AF.INET6,
port: in_port_t,
flowinfo: u32,
addr: [16]u8,
scope_id: u32,
};
};
pub const Kevent = extern struct {
ident: usize,
filter: c_short,
flags: c_ushort,
fflags: c_uint,
data: isize,
udata: usize,
};
pub const EVFILT_FS = -10;
pub const EVFILT_USER = -9;
pub const EVFILT_EXCEPT = -8;
pub const EVFILT_TIMER = -7;
pub const EVFILT_SIGNAL = -6;
pub const EVFILT_PROC = -5;
pub const EVFILT_VNODE = -4;
pub const EVFILT_AIO = -3;
pub const EVFILT_WRITE = -2;
pub const EVFILT_READ = -1;
pub const EVFILT_SYSCOUNT = 10;
pub const EVFILT_MARKER = 15;
pub const EV_ADD = 1;
pub const EV_DELETE = 2;
pub const EV_ENABLE = 4;
pub const EV_DISABLE = 8;
pub const EV_ONESHOT = 16;
pub const EV_CLEAR = 32;
pub const EV_RECEIPT = 64;
pub const EV_DISPATCH = 128;
pub const EV_NODATA = 4096;
pub const EV_FLAG1 = 8192;
pub const EV_ERROR = 16384;
pub const EV_EOF = 32768;
pub const EV_SYSFLAGS = 61440;
pub const NOTE_FFNOP = 0;
pub const NOTE_TRACK = 1;
pub const NOTE_DELETE = 1;
pub const NOTE_LOWAT = 1;
pub const NOTE_TRACKERR = 2;
pub const NOTE_OOB = 2;
pub const NOTE_WRITE = 2;
pub const NOTE_EXTEND = 4;
pub const NOTE_CHILD = 4;
pub const NOTE_ATTRIB = 8;
pub const NOTE_LINK = 16;
pub const NOTE_RENAME = 32;
pub const NOTE_REVOKE = 64;
pub const NOTE_PDATAMASK = 1048575;
pub const NOTE_FFLAGSMASK = 16777215;
pub const NOTE_TRIGGER = 16777216;
pub const NOTE_EXEC = 536870912;
pub const NOTE_FFAND = 1073741824;
pub const NOTE_FORK = 1073741824;
pub const NOTE_EXIT = 2147483648;
pub const NOTE_FFOR = 2147483648;
pub const NOTE_FFCTRLMASK = 3221225472;
pub const NOTE_FFCOPY = 3221225472;
pub const NOTE_PCTRLMASK = 4026531840;
pub const stack_t = extern struct {
sp: [*]u8,
size: isize,
flags: i32,
};
pub const S = struct {
pub const IREAD = IRUSR;
pub const IEXEC = IXUSR;
pub const IWRITE = IWUSR;
pub const IXOTH = 1;
pub const IWOTH = 2;
pub const IROTH = 4;
pub const IRWXO = 7;
pub const IXGRP = 8;
pub const IWGRP = 16;
pub const IRGRP = 32;
pub const IRWXG = 56;
pub const IXUSR = 64;
pub const IWUSR = 128;
pub const IRUSR = 256;
pub const IRWXU = 448;
pub const ISTXT = 512;
pub const BLKSIZE = 512;
pub const ISVTX = 512;
pub const ISGID = 1024;
pub const ISUID = 2048;
pub const IFIFO = 4096;
pub const IFCHR = 8192;
pub const IFDIR = 16384;
pub const IFBLK = 24576;
pub const IFREG = 32768;
pub const IFDB = 36864;
pub const IFLNK = 40960;
pub const IFSOCK = 49152;
pub const IFWHT = 57344;
pub const IFMT = 61440;
pub fn ISCHR(m: u32) bool {
return m & IFMT == IFCHR;
}
};
pub const BADSIG = SIG.ERR;
pub const SIG = struct {
pub const DFL = @intToPtr(?Sigaction.sigaction_fn, 0);
pub const IGN = @intToPtr(?Sigaction.sigaction_fn, 1);
pub const ERR = @intToPtr(?Sigaction.sigaction_fn, maxInt(usize));
pub const BLOCK = 1;
pub const UNBLOCK = 2;
pub const SETMASK = 3;
pub const IOT = ABRT;
pub const HUP = 1;
pub const INT = 2;
pub const QUIT = 3;
pub const ILL = 4;
pub const TRAP = 5;
pub const ABRT = 6;
pub const EMT = 7;
pub const FPE = 8;
pub const KILL = 9;
pub const BUS = 10;
pub const SEGV = 11;
pub const SYS = 12;
pub const PIPE = 13;
pub const ALRM = 14;
pub const TERM = 15;
pub const URG = 16;
pub const STOP = 17;
pub const TSTP = 18;
pub const CONT = 19;
pub const CHLD = 20;
pub const TTIN = 21;
pub const TTOU = 22;
pub const IO = 23;
pub const XCPU = 24;
pub const XFSZ = 25;
pub const VTALRM = 26;
pub const PROF = 27;
pub const WINCH = 28;
pub const INFO = 29;
pub const USR1 = 30;
pub const USR2 = 31;
pub const THR = 32;
pub const CKPT = 33;
pub const CKPTEXIT = 34;
};
pub const siginfo_t = extern struct {
signo: c_int,
errno: c_int,
code: c_int,
pid: c_int,
uid: uid_t,
status: c_int,
addr: ?*anyopaque,
value: sigval,
band: c_long,
__spare__: [7]c_int,
};
pub const sigval = extern union {
sival_int: c_int,
sival_ptr: ?*anyopaque,
};
pub const _SIG_WORDS = 4;
pub const sigset_t = extern struct {
__bits: [_SIG_WORDS]c_uint,
};
pub const empty_sigset = sigset_t{ .__bits = [_]c_uint{0} ** _SIG_WORDS };
pub const sig_atomic_t = c_int;
pub const Sigaction = extern struct {
pub const handler_fn = fn (c_int) callconv(.C) void;
pub const sigaction_fn = fn (c_int, *const siginfo_t, ?*const anyopaque) callconv(.C) void;
/// signal handler
handler: extern union {
handler: ?handler_fn,
sigaction: ?sigaction_fn,
},
flags: c_uint,
mask: sigset_t,
};
pub const sig_t = [*c]fn (c_int) callconv(.C) void;
pub const SOCK = struct {
pub const STREAM = 1;
pub const DGRAM = 2;
pub const RAW = 3;
pub const RDM = 4;
pub const SEQPACKET = 5;
pub const MAXADDRLEN = 255;
pub const CLOEXEC = 0x10000000;
pub const NONBLOCK = 0x20000000;
};
pub const SO = struct {
pub const DEBUG = 0x0001;
pub const ACCEPTCONN = 0x0002;
pub const REUSEADDR = 0x0004;
pub const KEEPALIVE = 0x0008;
pub const DONTROUTE = 0x0010;
pub const BROADCAST = 0x0020;
pub const USELOOPBACK = 0x0040;
pub const LINGER = 0x0080;
pub const OOBINLINE = 0x0100;
pub const REUSEPORT = 0x0200;
pub const TIMESTAMP = 0x0400;
pub const NOSIGPIPE = 0x0800;
pub const ACCEPTFILTER = 0x1000;
pub const RERROR = 0x2000;
pub const PASSCRED = 0x4000;
pub const SNDBUF = 0x1001;
pub const RCVBUF = 0x1002;
pub const SNDLOWAT = 0x1003;
pub const RCVLOWAT = 0x1004;
pub const SNDTIMEO = 0x1005;
pub const RCVTIMEO = 0x1006;
pub const ERROR = 0x1007;
pub const TYPE = 0x1008;
pub const SNDSPACE = 0x100a;
pub const CPUHINT = 0x1030;
};
pub const SOL = struct {
pub const SOCKET = 0xffff;
};
pub const PF = struct {
pub const INET6 = AF.INET6;
pub const IMPLINK = AF.IMPLINK;
pub const ROUTE = AF.ROUTE;
pub const ISO = AF.ISO;
pub const PIP = AF.pseudo_PIP;
pub const CHAOS = AF.CHAOS;
pub const DATAKIT = AF.DATAKIT;
pub const INET = AF.INET;
pub const APPLETALK = AF.APPLETALK;
pub const SIP = AF.SIP;
pub const OSI = AF.ISO;
pub const CNT = AF.CNT;
pub const LINK = AF.LINK;
pub const HYLINK = AF.HYLINK;
pub const MAX = AF.MAX;
pub const KEY = AF.pseudo_KEY;
pub const PUP = AF.PUP;
pub const COIP = AF.COIP;
pub const SNA = AF.SNA;
pub const LOCAL = AF.LOCAL;
pub const NETBIOS = AF.NETBIOS;
pub const NATM = AF.NATM;
pub const BLUETOOTH = AF.BLUETOOTH;
pub const UNSPEC = AF.UNSPEC;
pub const NETGRAPH = AF.NETGRAPH;
pub const ECMA = AF.ECMA;
pub const IPX = AF.IPX;
pub const DLI = AF.DLI;
pub const ATM = AF.ATM;
pub const CCITT = AF.CCITT;
pub const ISDN = AF.ISDN;
pub const RTIP = AF.pseudo_RTIP;
pub const LAT = AF.LAT;
pub const UNIX = PF.LOCAL;
pub const XTP = AF.pseudo_XTP;
pub const DECnet = AF.DECnet;
};
pub const AF = struct {
pub const UNSPEC = 0;
pub const OSI = ISO;
pub const UNIX = LOCAL;
pub const LOCAL = 1;
pub const INET = 2;
pub const IMPLINK = 3;
pub const PUP = 4;
pub const CHAOS = 5;
pub const NETBIOS = 6;
pub const ISO = 7;
pub const ECMA = 8;
pub const DATAKIT = 9;
pub const CCITT = 10;
pub const SNA = 11;
pub const DLI = 13;
pub const LAT = 14;
pub const HYLINK = 15;
pub const APPLETALK = 16;
pub const ROUTE = 17;
pub const LINK = 18;
pub const COIP = 20;
pub const CNT = 21;
pub const IPX = 23;
pub const SIP = 24;
pub const ISDN = 26;
pub const INET6 = 28;
pub const NATM = 29;
pub const ATM = 30;
pub const NETGRAPH = 32;
pub const BLUETOOTH = 33;
pub const MPLS = 34;
pub const MAX = 36;
};
pub const in_port_t = u16;
pub const sa_family_t = u8;
pub const socklen_t = u32;
pub const EAI = enum(c_int) {
ADDRFAMILY = 1,
AGAIN = 2,
BADFLAGS = 3,
FAIL = 4,
FAMILY = 5,
MEMORY = 6,
NODATA = 7,
NONAME = 8,
SERVICE = 9,
SOCKTYPE = 10,
SYSTEM = 11,
BADHINTS = 12,
PROTOCOL = 13,
OVERFLOW = 14,
_,
};
pub const AI = struct {
pub const PASSIVE = 0x00000001;
pub const CANONNAME = 0x00000002;
pub const NUMERICHOST = 0x00000004;
pub const NUMERICSERV = 0x00000008;
pub const MASK = PASSIVE | CANONNAME | NUMERICHOST | NUMERICSERV | ADDRCONFIG;
pub const ALL = 0x00000100;
pub const V4MAPPED_CFG = 0x00000200;
pub const ADDRCONFIG = 0x00000400;
pub const V4MAPPED = 0x00000800;
pub const DEFAULT = V4MAPPED_CFG | ADDRCONFIG;
};
pub const RTLD = struct {
pub const LAZY = 1;
pub const NOW = 2;
pub const MODEMASK = 0x3;
pub const GLOBAL = 0x100;
pub const LOCAL = 0;
pub const TRACE = 0x200;
pub const NODELETE = 0x01000;
pub const NOLOAD = 0x02000;
pub const NEXT = @intToPtr(*anyopaque, @bitCast(usize, @as(isize, -1)));
pub const DEFAULT = @intToPtr(*anyopaque, @bitCast(usize, @as(isize, -2)));
pub const SELF = @intToPtr(*anyopaque, @bitCast(usize, @as(isize, -3)));
pub const ALL = @intToPtr(*anyopaque, @bitCast(usize, @as(isize, -4)));
};
pub const dl_phdr_info = extern struct {
dlpi_addr: usize,
dlpi_name: ?[*:0]const u8,
dlpi_phdr: [*]std.elf.Phdr,
dlpi_phnum: u16,
};
pub const cmsghdr = extern struct {
cmsg_len: socklen_t,
cmsg_level: c_int,
cmsg_type: c_int,
};
pub const msghdr = extern struct {
msg_name: ?*anyopaque,
msg_namelen: socklen_t,
msg_iov: [*c]iovec,
msg_iovlen: c_int,
msg_control: ?*anyopaque,
msg_controllen: socklen_t,
msg_flags: c_int,
};
pub const cmsgcred = extern struct {
cmcred_pid: pid_t,
cmcred_uid: uid_t,
cmcred_euid: uid_t,
cmcred_gid: gid_t,
cmcred_ngroups: c_short,
cmcred_groups: [16]gid_t,
};
pub const sf_hdtr = extern struct {
headers: [*c]iovec,
hdr_cnt: c_int,
trailers: [*c]iovec,
trl_cnt: c_int,
};
pub const MS_SYNC = 0;
pub const MS_ASYNC = 1;
pub const MS_INVALIDATE = 2;
pub const POSIX_MADV_SEQUENTIAL = 2;
pub const POSIX_MADV_RANDOM = 1;
pub const POSIX_MADV_DONTNEED = 4;
pub const POSIX_MADV_NORMAL = 0;
pub const POSIX_MADV_WILLNEED = 3;
pub const MADV = struct {
pub const SEQUENTIAL = 2;
pub const CONTROL_END = SETMAP;
pub const DONTNEED = 4;
pub const RANDOM = 1;
pub const WILLNEED = 3;
pub const NORMAL = 0;
pub const CONTROL_START = INVAL;
pub const FREE = 5;
pub const NOSYNC = 6;
pub const AUTOSYNC = 7;
pub const NOCORE = 8;
pub const CORE = 9;
pub const INVAL = 10;
pub const SETMAP = 11;
};
pub const LOCK = struct {
pub const SH = 1;
pub const EX = 2;
pub const UN = 8;
pub const NB = 4;
};
pub const Flock = extern struct {
l_start: off_t,
l_len: off_t,
l_pid: pid_t,
l_type: c_short,
l_whence: c_short,
};
pub const addrinfo = extern struct {
flags: i32,
family: i32,
socktype: i32,
protocol: i32,
addrlen: socklen_t,
canonname: ?[*:0]u8,
addr: ?*sockaddr,
next: ?*addrinfo,
};
pub const IPPROTO = struct {
pub const IP = 0;
pub const ICMP = 1;
pub const TCP = 6;
pub const UDP = 17;
pub const IPV6 = 41;
pub const RAW = 255;
pub const HOPOPTS = 0;
pub const IGMP = 2;
pub const GGP = 3;
pub const IPV4 = 4;
pub const IPIP = IPV4;
pub const ST = 7;
pub const EGP = 8;
pub const PIGP = 9;
pub const RCCMON = 10;
pub const NVPII = 11;
pub const PUP = 12;
pub const ARGUS = 13;
pub const EMCON = 14;
pub const XNET = 15;
pub const CHAOS = 16;
pub const MUX = 18;
pub const MEAS = 19;
pub const HMP = 20;
pub const PRM = 21;
pub const IDP = 22;
pub const TRUNK1 = 23;
pub const TRUNK2 = 24;
pub const LEAF1 = 25;
pub const LEAF2 = 26;
pub const RDP = 27;
pub const IRTP = 28;
pub const TP = 29;
pub const BLT = 30;
pub const NSP = 31;
pub const INP = 32;
pub const SEP = 33;
pub const @"3PC" = 34;
pub const IDPR = 35;
pub const XTP = 36;
pub const DDP = 37;
pub const CMTP = 38;
pub const TPXX = 39;
pub const IL = 40;
pub const SDRP = 42;
pub const ROUTING = 43;
pub const FRAGMENT = 44;
pub const IDRP = 45;
pub const RSVP = 46;
pub const GRE = 47;
pub const MHRP = 48;
pub const BHA = 49;
pub const ESP = 50;
pub const AH = 51;
pub const INLSP = 52;
pub const SWIPE = 53;
pub const NHRP = 54;
pub const MOBILE = 55;
pub const TLSP = 56;
pub const SKIP = 57;
pub const ICMPV6 = 58;
pub const NONE = 59;
pub const DSTOPTS = 60;
pub const AHIP = 61;
pub const CFTP = 62;
pub const HELLO = 63;
pub const SATEXPAK = 64;
pub const KRYPTOLAN = 65;
pub const RVD = 66;
pub const IPPC = 67;
pub const ADFS = 68;
pub const SATMON = 69;
pub const VISA = 70;
pub const IPCV = 71;
pub const CPNX = 72;
pub const CPHB = 73;
pub const WSN = 74;
pub const PVP = 75;
pub const BRSATMON = 76;
pub const ND = 77;
pub const WBMON = 78;
pub const WBEXPAK = 79;
pub const EON = 80;
pub const VMTP = 81;
pub const SVMTP = 82;
pub const VINES = 83;
pub const TTP = 84;
pub const IGP = 85;
pub const DGP = 86;
pub const TCF = 87;
pub const IGRP = 88;
pub const OSPFIGP = 89;
pub const SRPC = 90;
pub const LARP = 91;
pub const MTP = 92;
pub const AX25 = 93;
pub const IPEIP = 94;
pub const MICP = 95;
pub const SCCSP = 96;
pub const ETHERIP = 97;
pub const ENCAP = 98;
pub const APES = 99;
pub const GMTP = 100;
pub const IPCOMP = 108;
pub const PIM = 103;
pub const CARP = 112;
pub const PGM = 113;
pub const PFSYNC = 240;
pub const DIVERT = 254;
pub const MAX = 256;
pub const DONE = 257;
pub const UNKNOWN = 258;
};
pub const rlimit_resource = enum(c_int) {
CPU = 0,
FSIZE = 1,
DATA = 2,
STACK = 3,
CORE = 4,
RSS = 5,
MEMLOCK = 6,
NPROC = 7,
NOFILE = 8,
SBSIZE = 9,
VMEM = 10,
POSIXLOCKS = 11,
_,
pub const AS: rlimit_resource = .VMEM;
};
pub const rlim_t = i64;
pub const RLIM = struct {
/// No limit
pub const INFINITY: rlim_t = (1 << 63) - 1;
pub const SAVED_MAX = INFINITY;
pub const SAVED_CUR = INFINITY;
};
pub const rlimit = extern struct {
/// Soft limit
cur: rlim_t,
/// Hard limit
max: rlim_t,
};
pub const SHUT = struct {
pub const RD = 0;
pub const WR = 1;
pub const RDWR = 2;
};
pub const nfds_t = u32;
pub const pollfd = extern struct {
fd: fd_t,
events: i16,
revents: i16,
};
pub const POLL = struct {
/// Requestable events.
pub const IN = 0x0001;
pub const PRI = 0x0002;
pub const OUT = 0x0004;
pub const RDNORM = 0x0040;
pub const WRNORM = OUT;
pub const RDBAND = 0x0080;
pub const WRBAND = 0x0100;
/// These events are set if they occur regardless of whether they were requested.
pub const ERR = 0x0008;
pub const HUP = 0x0010;
pub const NVAL = 0x0020;
}; | lib/std/c/dragonfly.zig |
const std = @import("std");
const AnalysisContext = @import("document_store.zig").AnalysisContext;
const ast = std.zig.ast;
const types = @import("types.zig");
/// REALLY BAD CODE, PLEASE DON'T USE THIS!!!!!!! (only for testing)
pub fn getFunctionByName(tree: *ast.Tree, name: []const u8) ?*ast.Node.FnProto {
var decls = tree.root_node.decls.iterator(0);
while (decls.next()) |decl_ptr| {
var decl = decl_ptr.*;
switch (decl.id) {
.FnProto => {
const func = decl.cast(ast.Node.FnProto).?;
if (std.mem.eql(u8, tree.tokenSlice(func.name_token.?), name)) return func;
},
else => {},
}
}
return null;
}
/// Get a declaration's doc comment node
fn getDocCommentNode(tree: *ast.Tree, node: *ast.Node) ?*ast.Node.DocComment {
if (node.cast(ast.Node.FnProto)) |func| {
return func.doc_comments;
} else if (node.cast(ast.Node.VarDecl)) |var_decl| {
return var_decl.doc_comments;
} else if (node.cast(ast.Node.ContainerField)) |field| {
return field.doc_comments;
} else if (node.cast(ast.Node.ErrorTag)) |tag| {
return tag.doc_comments;
}
return null;
}
/// Gets a declaration's doc comments, caller must free memory when a value is returned
/// Like:
///```zig
///var comments = getFunctionDocComments(allocator, tree, func);
///defer if (comments) |comments_pointer| allocator.free(comments_pointer);
///```
pub fn getDocComments(allocator: *std.mem.Allocator, tree: *ast.Tree, node: *ast.Node) !?[]const u8 {
if (getDocCommentNode(tree, node)) |doc_comment_node| {
return try collectDocComments(allocator, tree, doc_comment_node);
}
return null;
}
fn collectDocComments(allocator: *std.mem.Allocator, tree: *ast.Tree, doc_comments: *ast.Node.DocComment) ![]const u8 {
var lines = std.ArrayList([]const u8).init(allocator);
defer lines.deinit();
var curr_line_tok = doc_comments.first_line;
while (true) : (curr_line_tok += 1) {
switch (tree.token_ids[curr_line_tok]) {
.LineComment => continue,
.DocComment, .ContainerDocComment => {
try lines.append(std.fmt.trim(tree.tokenSlice(curr_line_tok)[3..]));
},
else => break,
}
}
return try std.mem.join(allocator, "\\\n", lines.items);
}
/// Gets a function signature (keywords, name, return value)
pub fn getFunctionSignature(tree: *ast.Tree, func: *ast.Node.FnProto) []const u8 {
const start = tree.token_locs[func.firstToken()].start;
const end = tree.token_locs[switch (func.return_type) {
.Explicit, .InferErrorSet => |node| node.lastToken(),
.Invalid => |r_paren| r_paren,
}].end;
return tree.source[start..end];
}
/// Gets a function snippet insert text
pub fn getFunctionSnippet(allocator: *std.mem.Allocator, tree: *ast.Tree, func: *ast.Node.FnProto) ![]const u8 {
const name_tok = func.name_token orelse unreachable;
var buffer = std.ArrayList(u8).init(allocator);
try buffer.ensureCapacity(128);
try buffer.appendSlice(tree.tokenSlice(name_tok));
try buffer.append('(');
var buf_stream = buffer.outStream();
for (func.paramsConst()) |param, param_num| {
if (param_num != 0) try buffer.appendSlice(", ${") else try buffer.appendSlice("${");
try buf_stream.print("{}:", .{param_num + 1});
if (param.comptime_token) |_| {
try buffer.appendSlice("comptime ");
}
if (param.noalias_token) |_| {
try buffer.appendSlice("noalias ");
}
if (param.name_token) |name_token| {
try buffer.appendSlice(tree.tokenSlice(name_token));
try buffer.appendSlice(": ");
}
switch (param.param_type) {
.var_args => try buffer.appendSlice("..."),
.var_type => try buffer.appendSlice("var"),
.type_expr => |type_expr| {
var curr_tok = type_expr.firstToken();
var end_tok = type_expr.lastToken();
while (curr_tok <= end_tok) : (curr_tok += 1) {
const id = tree.token_ids[curr_tok];
const is_comma = id == .Comma;
if (curr_tok == end_tok and is_comma) continue;
try buffer.appendSlice(tree.tokenSlice(curr_tok));
if (is_comma or id == .Keyword_const) try buffer.append(' ');
}
},
}
try buffer.append('}');
}
try buffer.append(')');
return buffer.toOwnedSlice();
}
/// Gets a function signature (keywords, name, return value)
pub fn getVariableSignature(tree: *ast.Tree, var_decl: *ast.Node.VarDecl) []const u8 {
const start = tree.token_locs[var_decl.firstToken()].start;
const end = tree.token_locs[var_decl.semicolon_token].start;
return tree.source[start..end];
}
pub fn isTypeFunction(tree: *ast.Tree, func: *ast.Node.FnProto) bool {
switch (func.return_type) {
.Explicit => |node| return if (node.cast(std.zig.ast.Node.Identifier)) |ident|
std.mem.eql(u8, tree.tokenSlice(ident.token), "type")
else
false,
.InferErrorSet, .Invalid => return false,
}
}
// STYLE
pub fn isCamelCase(name: []const u8) bool {
return !std.ascii.isUpper(name[0]) and std.mem.indexOf(u8, name, "_") == null;
}
pub fn isPascalCase(name: []const u8) bool {
return std.ascii.isUpper(name[0]) and std.mem.indexOf(u8, name, "_") == null;
}
// ANALYSIS ENGINE
pub fn getDeclNameToken(tree: *ast.Tree, node: *ast.Node) ?ast.TokenIndex {
switch (node.id) {
.VarDecl => {
const vari = node.cast(ast.Node.VarDecl).?;
return vari.name_token;
},
.FnProto => {
const func = node.cast(ast.Node.FnProto).?;
if (func.name_token == null) return null;
return func.name_token.?;
},
.ContainerField => {
const field = node.cast(ast.Node.ContainerField).?;
return field.name_token;
},
// We need identifier for captures
.Identifier => {
const ident = node.cast(ast.Node.Identifier).?;
return ident.token;
},
.TestDecl => {
const decl = node.cast(ast.Node.TestDecl).?;
return (decl.name.cast(ast.Node.StringLiteral) orelse return null).token;
},
else => {},
}
return null;
}
fn getDeclName(tree: *ast.Tree, node: *ast.Node) ?[]const u8 {
const name = tree.tokenSlice(getDeclNameToken(tree, node) orelse return null);
return switch (node.id) {
.TestDecl => name[1 .. name.len - 1],
else => name,
};
}
/// Gets the child of node
pub fn getChild(tree: *ast.Tree, node: *ast.Node, name: []const u8) ?*ast.Node {
var child_idx: usize = 0;
while (node.iterate(child_idx)) |child| : (child_idx += 1) {
const child_name = getDeclName(tree, child) orelse continue;
if (std.mem.eql(u8, child_name, name)) return child;
}
return null;
}
/// Gets the child of slice
pub fn getChildOfSlice(tree: *ast.Tree, nodes: []*ast.Node, name: []const u8) ?*ast.Node {
for (nodes) |child| {
const child_name = getDeclName(tree, child) orelse continue;
if (std.mem.eql(u8, child_name, name)) return child;
}
return null;
}
fn findReturnStatementInternal(
tree: *ast.Tree,
fn_decl: *ast.Node.FnProto,
base_node: *ast.Node,
already_found: *bool,
) ?*ast.Node.ControlFlowExpression {
var result: ?*ast.Node.ControlFlowExpression = null;
var child_idx: usize = 0;
while (base_node.iterate(child_idx)) |child_node| : (child_idx += 1) {
switch (child_node.id) {
.ControlFlowExpression => {
const cfe = child_node.cast(ast.Node.ControlFlowExpression).?;
if (cfe.kind == .Return) {
// If we are calling ourselves recursively, ignore this return.
if (cfe.rhs) |rhs| {
if (rhs.cast(ast.Node.Call)) |call_node| {
if (call_node.lhs.id == .Identifier) {
if (std.mem.eql(u8, getDeclName(tree, call_node.lhs).?, getDeclName(tree, &fn_decl.base).?)) {
continue;
}
}
}
}
if (already_found.*) return null;
already_found.* = true;
result = cfe;
continue;
}
},
else => {},
}
result = findReturnStatementInternal(tree, fn_decl, child_node, already_found);
}
return result;
}
fn findReturnStatement(tree: *ast.Tree, fn_decl: *ast.Node.FnProto) ?*ast.Node.ControlFlowExpression {
var already_found = false;
return findReturnStatementInternal(tree, fn_decl, fn_decl.body_node.?, &already_found);
}
/// Resolves the return type of a function
fn resolveReturnType(analysis_ctx: *AnalysisContext, fn_decl: *ast.Node.FnProto) ?*ast.Node {
if (isTypeFunction(analysis_ctx.tree(), fn_decl) and fn_decl.body_node != null) {
// If this is a type function and it only contains a single return statement that returns
// a container declaration, we will return that declaration.
const ret = findReturnStatement(analysis_ctx.tree(), fn_decl) orelse return null;
if (ret.rhs) |rhs|
if (resolveTypeOfNode(analysis_ctx, rhs)) |res_rhs| switch (res_rhs.id) {
.ContainerDecl => {
analysis_ctx.onContainer(res_rhs) catch return null;
return res_rhs;
},
else => return null,
};
return null;
}
return switch (fn_decl.return_type) {
.Explicit, .InferErrorSet => |return_type| resolveTypeOfNode(analysis_ctx, return_type),
.Invalid => null,
};
}
/// Resolves the child type of an optional type
fn resolveUnwrapOptionalType(analysis_ctx: *AnalysisContext, opt: *ast.Node) ?*ast.Node {
if (opt.cast(ast.Node.PrefixOp)) |prefix_op| {
if (prefix_op.op == .OptionalType) {
return resolveTypeOfNode(analysis_ctx, prefix_op.rhs);
}
}
return null;
}
/// Resolves the child type of a defer type
fn resolveDerefType(analysis_ctx: *AnalysisContext, deref: *ast.Node) ?*ast.Node {
if (deref.cast(ast.Node.PrefixOp)) |pop| {
if (pop.op == .PtrType) {
const op_token_id = analysis_ctx.tree().token_ids[pop.op_token];
switch (op_token_id) {
.Asterisk => return resolveTypeOfNode(analysis_ctx, pop.rhs),
.LBracket, .AsteriskAsterisk => return null,
else => unreachable,
}
}
}
return null;
}
fn makeSliceType(analysis_ctx: *AnalysisContext, child_type: *ast.Node) ?*ast.Node {
// TODO: Better values for fields, better way to do this?
var slice_type = analysis_ctx.arena.allocator.create(ast.Node.PrefixOp) catch return null;
slice_type.* = .{
.op_token = child_type.firstToken(),
.op = .{
.SliceType = .{
.allowzero_token = null,
.align_info = null,
.const_token = null,
.volatile_token = null,
.sentinel = null,
},
},
.rhs = child_type,
};
return &slice_type.base;
}
/// Resolves bracket access type (both slicing and array access)
fn resolveBracketAccessType(
analysis_ctx: *AnalysisContext,
lhs: *ast.Node,
rhs: enum { Single, Range },
) ?*ast.Node {
if (lhs.cast(ast.Node.PrefixOp)) |pop| {
switch (pop.op) {
.SliceType => {
if (rhs == .Single) return resolveTypeOfNode(analysis_ctx, pop.rhs);
return lhs;
},
.ArrayType => {
if (rhs == .Single) return resolveTypeOfNode(analysis_ctx, pop.rhs);
return makeSliceType(analysis_ctx, pop.rhs);
},
.PtrType => {
if (pop.rhs.cast(std.zig.ast.Node.PrefixOp)) |child_pop| {
switch (child_pop.op) {
.ArrayType => {
if (rhs == .Single) {
return resolveTypeOfNode(analysis_ctx, child_pop.rhs);
}
return lhs;
},
else => {},
}
}
},
else => {},
}
}
return null;
}
/// Called to remove one level of pointerness before a field access
fn resolveFieldAccessLhsType(analysis_ctx: *AnalysisContext, lhs: *ast.Node) *ast.Node {
return resolveDerefType(analysis_ctx, lhs) orelse lhs;
}
/// Resolves the type of a node
pub fn resolveTypeOfNode(analysis_ctx: *AnalysisContext, node: *ast.Node) ?*ast.Node {
switch (node.id) {
.VarDecl => {
const vari = node.cast(ast.Node.VarDecl).?;
return resolveTypeOfNode(analysis_ctx, vari.type_node orelse vari.init_node.?) orelse null;
},
.Identifier => {
if (getChildOfSlice(analysis_ctx.tree(), analysis_ctx.scope_nodes, analysis_ctx.tree().getNodeSource(node))) |child| {
if (child == node) return null;
return resolveTypeOfNode(analysis_ctx, child);
} else return null;
},
.ContainerField => {
const field = node.cast(ast.Node.ContainerField).?;
return resolveTypeOfNode(analysis_ctx, field.type_expr orelse return null);
},
.Call => {
const call = node.cast(ast.Node.Call).?;
const previous_tree = analysis_ctx.tree();
const decl = resolveTypeOfNode(analysis_ctx, call.lhs) orelse return null;
if (decl.cast(ast.Node.FnProto)) |fn_decl| {
if (previous_tree != analysis_ctx.tree()) {
return resolveReturnType(analysis_ctx, fn_decl);
}
// Add type param values to the scope nodes
const param_len = std.math.min(call.params_len, fn_decl.params_len);
var scope_nodes = std.ArrayList(*ast.Node).fromOwnedSlice(&analysis_ctx.arena.allocator, analysis_ctx.scope_nodes);
var analysis_ctx_clone = analysis_ctx.clone() catch return null;
for (fn_decl.paramsConst()) |decl_param, param_idx| {
if (param_idx >= param_len) break;
if (decl_param.name_token == null) continue;
const type_param = switch (decl_param.param_type) {
.type_expr => |type_node| if (type_node.cast(ast.Node.Identifier)) |ident|
std.mem.eql(u8, analysis_ctx.tree().tokenSlice(ident.token), "type")
else
false,
else => false,
};
if (!type_param) continue;
// TODO Handle errors better
// TODO This may invalidate the analysis context so we copy it.
// However, if the argument hits an import we just ignore it for now.
// Once we return our own types instead of directly using nodes we can fix this.
const call_param_type = resolveTypeOfNode(&analysis_ctx_clone, call.paramsConst()[param_idx]) orelse continue;
if (analysis_ctx_clone.handle != analysis_ctx.handle) {
analysis_ctx_clone = analysis_ctx.clone() catch return null;
continue;
}
scope_nodes.append(makeVarDeclNode(
&analysis_ctx.arena.allocator,
decl_param.doc_comments,
decl_param.comptime_token,
decl_param.name_token.?,
null,
call_param_type,
) catch return null) catch return null;
analysis_ctx.scope_nodes = scope_nodes.items;
}
return resolveReturnType(analysis_ctx, fn_decl);
}
return decl;
},
.StructInitializer => {
const struct_init = node.cast(ast.Node.StructInitializer).?;
return resolveTypeOfNode(analysis_ctx, struct_init.lhs);
},
.ErrorSetDecl => {
const set = node.cast(ast.Node.ErrorSetDecl).?;
var i: usize = 0;
while (set.iterate(i)) |decl| : (i += 1) {
// TODO handle errors better?
analysis_ctx.error_completions.add(analysis_ctx.tree(), decl) catch {};
}
return node;
},
.SuffixOp => {
const suffix_op = node.cast(ast.Node.SuffixOp).?;
switch (suffix_op.op) {
.UnwrapOptional => {
const left_type = resolveTypeOfNode(analysis_ctx, suffix_op.lhs) orelse return null;
return resolveUnwrapOptionalType(analysis_ctx, left_type);
},
.Deref => {
const left_type = resolveTypeOfNode(analysis_ctx, suffix_op.lhs) orelse return null;
return resolveDerefType(analysis_ctx, left_type);
},
.ArrayAccess => {
const left_type = resolveTypeOfNode(analysis_ctx, suffix_op.lhs) orelse return null;
return resolveBracketAccessType(analysis_ctx, left_type, .Single);
},
.Slice => {
const left_type = resolveTypeOfNode(analysis_ctx, suffix_op.lhs) orelse return null;
return resolveBracketAccessType(analysis_ctx, left_type, .Range);
},
else => {},
}
},
.InfixOp => {
const infix_op = node.cast(ast.Node.InfixOp).?;
switch (infix_op.op) {
.Period => {
// Save the child string from this tree since the tree may switch when processing
// an import lhs.
var rhs_str = nodeToString(analysis_ctx.tree(), infix_op.rhs) orelse return null;
// Use the analysis context temporary arena to store the rhs string.
rhs_str = std.mem.dupe(&analysis_ctx.arena.allocator, u8, rhs_str) catch return null;
// If we are accessing a pointer type, remove one pointerness level :)
const left_type = resolveFieldAccessLhsType(
analysis_ctx,
resolveTypeOfNode(analysis_ctx, infix_op.lhs) orelse return null,
);
const child = getChild(analysis_ctx.tree(), left_type, rhs_str) orelse return null;
return resolveTypeOfNode(analysis_ctx, child);
},
.UnwrapOptional => {
const left_type = resolveTypeOfNode(analysis_ctx, infix_op.lhs) orelse return null;
return resolveUnwrapOptionalType(analysis_ctx, left_type);
},
else => {},
}
},
.PrefixOp => {
const prefix_op = node.cast(ast.Node.PrefixOp).?;
switch (prefix_op.op) {
.SliceType,
.ArrayType,
.OptionalType,
.PtrType,
=> return node,
.Try => {
const rhs_type = resolveTypeOfNode(analysis_ctx, prefix_op.rhs) orelse return null;
switch (rhs_type.id) {
.InfixOp => {
const infix_op = rhs_type.cast(ast.Node.InfixOp).?;
if (infix_op.op == .ErrorUnion) return infix_op.rhs;
},
else => {},
}
return rhs_type;
},
else => {},
}
},
.BuiltinCall => {
const builtin_call = node.cast(ast.Node.BuiltinCall).?;
const call_name = analysis_ctx.tree().tokenSlice(builtin_call.builtin_token);
if (std.mem.eql(u8, call_name, "@This")) {
if (builtin_call.params_len != 0) return null;
return analysis_ctx.in_container;
}
if (!std.mem.eql(u8, call_name, "@import")) return null;
if (builtin_call.params_len > 1) return null;
const import_param = builtin_call.paramsConst()[0];
if (import_param.id != .StringLiteral) return null;
const import_str = analysis_ctx.tree().tokenSlice(import_param.cast(ast.Node.StringLiteral).?.token);
return analysis_ctx.onImport(import_str[1 .. import_str.len - 1]) catch |err| block: {
std.debug.warn("Error {} while processing import {}\n", .{ err, import_str });
break :block null;
};
},
.ContainerDecl => {
analysis_ctx.onContainer(node) catch return null;
const container = node.cast(ast.Node.ContainerDecl).?;
const kind = analysis_ctx.tree().token_ids[container.kind_token];
if (kind == .Keyword_struct or (kind == .Keyword_union and container.init_arg_expr == .None)) {
return node;
}
var i: usize = 0;
while (container.iterate(i)) |decl| : (i += 1) {
if (decl.id != .ContainerField) continue;
// TODO handle errors better?
analysis_ctx.enum_completions.add(analysis_ctx.tree(), decl) catch {};
}
return node;
},
.MultilineStringLiteral, .StringLiteral, .FnProto => return node,
else => std.debug.warn("Type resolution case not implemented; {}\n", .{node.id}),
}
return null;
}
fn maybeCollectImport(tree: *ast.Tree, builtin_call: *ast.Node.BuiltinCall, arr: *std.ArrayList([]const u8)) !void {
if (!std.mem.eql(u8, tree.tokenSlice(builtin_call.builtin_token), "@import")) return;
if (builtin_call.params_len > 1) return;
const import_param = builtin_call.paramsConst()[0];
if (import_param.id != .StringLiteral) return;
const import_str = tree.tokenSlice(import_param.cast(ast.Node.StringLiteral).?.token);
try arr.append(import_str[1 .. import_str.len - 1]);
}
/// Collects all imports we can find into a slice of import paths (without quotes).
/// The import paths are valid as long as the tree is.
pub fn collectImports(import_arr: *std.ArrayList([]const u8), tree: *ast.Tree) !void {
// TODO: Currently only detects `const smth = @import("string literal")<.SomeThing>;`
for (tree.root_node.decls()) |decl| {
if (decl.id != .VarDecl) continue;
const var_decl = decl.cast(ast.Node.VarDecl).?;
if (var_decl.init_node == null) continue;
switch (var_decl.init_node.?.id) {
.BuiltinCall => {
const builtin_call = var_decl.init_node.?.cast(ast.Node.BuiltinCall).?;
try maybeCollectImport(tree, builtin_call, import_arr);
},
.InfixOp => {
const infix_op = var_decl.init_node.?.cast(ast.Node.InfixOp).?;
switch (infix_op.op) {
.Period => {},
else => continue,
}
if (infix_op.lhs.id != .BuiltinCall) continue;
try maybeCollectImport(tree, infix_op.lhs.cast(ast.Node.BuiltinCall).?, import_arr);
},
else => {},
}
}
}
fn checkForContainerAndResolveFieldAccessLhsType(analysis_ctx: *AnalysisContext, node: *ast.Node) *ast.Node {
const current_node = resolveFieldAccessLhsType(analysis_ctx, node);
if (current_node.id == .ContainerDecl or current_node.id == .Root) {
// TODO: Handle errors
analysis_ctx.onContainer(current_node) catch {};
}
return current_node;
}
pub fn getFieldAccessTypeNode(
analysis_ctx: *AnalysisContext,
tokenizer: *std.zig.Tokenizer,
) ?*ast.Node {
var current_node = analysis_ctx.in_container;
while (true) {
const tok = tokenizer.next();
switch (tok.id) {
.Eof => return resolveFieldAccessLhsType(analysis_ctx, current_node),
.Identifier => {
if (getChildOfSlice(analysis_ctx.tree(), analysis_ctx.scope_nodes, tokenizer.buffer[tok.loc.start..tok.loc.end])) |child| {
if (resolveTypeOfNode(analysis_ctx, child)) |child_type| {
current_node = child_type;
} else return null;
} else return null;
},
.Period => {
const after_period = tokenizer.next();
switch (after_period.id) {
.Eof => return resolveFieldAccessLhsType(analysis_ctx, current_node),
.Identifier => {
if (after_period.loc.end == tokenizer.buffer.len) return resolveFieldAccessLhsType(analysis_ctx, current_node);
current_node = checkForContainerAndResolveFieldAccessLhsType(analysis_ctx, current_node);
if (getChild(analysis_ctx.tree(), current_node, tokenizer.buffer[after_period.loc.start..after_period.loc.end])) |child| {
if (resolveTypeOfNode(analysis_ctx, child)) |child_type| {
current_node = child_type;
} else return null;
} else return null;
},
.QuestionMark => {
if (resolveUnwrapOptionalType(analysis_ctx, current_node)) |child_type| {
current_node = child_type;
} else return null;
},
else => {
std.debug.warn("Unrecognized token {} after period.\n", .{after_period.id});
return null;
},
}
},
.PeriodAsterisk => {
if (resolveDerefType(analysis_ctx, current_node)) |child_type| {
current_node = child_type;
} else return null;
},
.LParen => {
switch (current_node.id) {
.FnProto => {
const func = current_node.cast(ast.Node.FnProto).?;
if (resolveReturnType(analysis_ctx, func)) |ret| {
current_node = ret;
// Skip to the right paren
var paren_count: usize = 1;
var next = tokenizer.next();
while (next.id != .Eof) : (next = tokenizer.next()) {
if (next.id == .RParen) {
paren_count -= 1;
if (paren_count == 0) break;
} else if (next.id == .LParen) {
paren_count += 1;
}
} else return null;
} else return null;
},
else => {},
}
},
.LBracket => {
var brack_count: usize = 1;
var next = tokenizer.next();
var is_range = false;
while (next.id != .Eof) : (next = tokenizer.next()) {
if (next.id == .RBracket) {
brack_count -= 1;
if (brack_count == 0) break;
} else if (next.id == .LBracket) {
brack_count += 1;
} else if (next.id == .Ellipsis2 and brack_count == 1) {
is_range = true;
}
} else return null;
if (resolveBracketAccessType(
analysis_ctx,
current_node,
if (is_range) .Range else .Single,
)) |child_type| {
current_node = child_type;
} else return null;
},
else => {
std.debug.warn("Unimplemented token: {}\n", .{tok.id});
return null;
},
}
if (current_node.id == .ContainerDecl or current_node.id == .Root) {
analysis_ctx.onContainer(current_node) catch return null;
}
}
return resolveFieldAccessLhsType(analysis_ctx, current_node);
}
pub fn isNodePublic(tree: *ast.Tree, node: *ast.Node) bool {
switch (node.id) {
.VarDecl => {
const var_decl = node.cast(ast.Node.VarDecl).?;
return var_decl.visib_token != null;
},
.FnProto => {
const func = node.cast(ast.Node.FnProto).?;
return func.visib_token != null;
},
else => return true,
}
}
pub fn nodeToString(tree: *ast.Tree, node: *ast.Node) ?[]const u8 {
switch (node.id) {
.ContainerField => {
const field = node.cast(ast.Node.ContainerField).?;
return tree.tokenSlice(field.name_token);
},
.ErrorTag => {
const tag = node.cast(ast.Node.ErrorTag).?;
return tree.tokenSlice(tag.name_token);
},
.Identifier => {
const field = node.cast(ast.Node.Identifier).?;
return tree.tokenSlice(field.token);
},
.FnProto => {
const func = node.cast(ast.Node.FnProto).?;
if (func.name_token) |name_token| {
return tree.tokenSlice(name_token);
}
},
else => {
std.debug.warn("INVALID: {}\n", .{node.id});
},
}
return null;
}
fn makeAccessNode(allocator: *std.mem.Allocator, expr: *ast.Node) !*ast.Node {
const suffix_op_node = try allocator.create(ast.Node.SuffixOp);
suffix_op_node.* = .{
.op = .{ .ArrayAccess = expr },
.lhs = expr,
.rtoken = expr.lastToken(),
};
return &suffix_op_node.base;
}
fn makeUnwrapNode(allocator: *std.mem.Allocator, expr: *ast.Node) !*ast.Node {
const suffix_op_node = try allocator.create(ast.Node.SuffixOp);
suffix_op_node.* = .{
.op = .UnwrapOptional,
.lhs = expr,
.rtoken = expr.lastToken(),
};
return &suffix_op_node.base;
}
fn makeVarDeclNode(
allocator: *std.mem.Allocator,
doc: ?*ast.Node.DocComment,
comptime_token: ?ast.TokenIndex,
name_token: ast.TokenIndex,
type_expr: ?*ast.Node,
init_expr: ?*ast.Node,
) !*ast.Node {
// TODO: This will not be needed anymore when we use out own decl type instead of directly
// repurposing ast nodes.
const var_decl_node = try allocator.create(ast.Node.VarDecl);
var_decl_node.* = .{
.doc_comments = doc,
.comptime_token = comptime_token,
.visib_token = null,
.thread_local_token = null,
.name_token = name_token,
.eq_token = null,
.mut_token = name_token,
.extern_export_token = null,
.lib_name = null,
.type_node = type_expr,
.align_node = null,
.section_node = null,
.init_node = init_expr,
.semicolon_token = name_token,
};
return &var_decl_node.base;
}
pub fn declsFromIndexInternal(
arena: *std.heap.ArenaAllocator,
decls: *std.ArrayList(*ast.Node),
tree: *ast.Tree,
node: *ast.Node,
source_index: usize,
innermost_container: **ast.Node,
) error{OutOfMemory}!void {
switch (node.id) {
.Root, .ContainerDecl => {
innermost_container.* = node;
var node_idx: usize = 0;
while (node.iterate(node_idx)) |child_node| : (node_idx += 1) {
// Skip over container fields, we can only dot access those.
if (child_node.id == .ContainerField) continue;
const is_contained = nodeContainsSourceIndex(tree, child_node, source_index);
// If the cursor is in a variable decls it will insert itself anyway, we don't need to take care of it.
if ((is_contained and child_node.id != .VarDecl) or !is_contained) try decls.append(child_node);
if (is_contained) {
try declsFromIndexInternal(arena, decls, tree, child_node, source_index, innermost_container);
}
}
},
.FnProto => {
const func = node.cast(ast.Node.FnProto).?;
// TODO: This is a hack to enable param decls with the new parser
for (func.paramsConst()) |param| {
if (param.param_type != .type_expr or param.name_token == null) continue;
try decls.append(try makeVarDeclNode(
&arena.allocator,
param.doc_comments,
param.comptime_token,
param.name_token.?,
param.param_type.type_expr,
null,
));
}
if (func.body_node) |body_node| {
if (!nodeContainsSourceIndex(tree, body_node, source_index)) return;
try declsFromIndexInternal(arena, decls, tree, body_node, source_index, innermost_container);
}
},
.TestDecl => {
const test_decl = node.cast(ast.Node.TestDecl).?;
if (!nodeContainsSourceIndex(tree, test_decl.body_node, source_index)) return;
try declsFromIndexInternal(arena, decls, tree, test_decl.body_node, source_index, innermost_container);
},
.Block => {
var inode_idx: usize = 0;
while (node.iterate(inode_idx)) |inode| : (inode_idx += 1) {
if (nodeComesAfterSourceIndex(tree, inode, source_index)) return;
try declsFromIndexInternal(arena, decls, tree, inode, source_index, innermost_container);
}
},
.Comptime => {
const comptime_stmt = node.cast(ast.Node.Comptime).?;
if (nodeComesAfterSourceIndex(tree, comptime_stmt.expr, source_index)) return;
try declsFromIndexInternal(arena, decls, tree, comptime_stmt.expr, source_index, innermost_container);
},
.If => {
const if_node = node.cast(ast.Node.If).?;
if (nodeContainsSourceIndex(tree, if_node.body, source_index)) {
if (if_node.payload) |payload| {
std.debug.assert(payload.id == .PointerPayload);
const ptr_payload = payload.cast(ast.Node.PointerPayload).?;
std.debug.assert(ptr_payload.value_symbol.id == .Identifier);
try decls.append(try makeVarDeclNode(
&arena.allocator,
null,
null,
ptr_payload.value_symbol.firstToken(),
null,
try makeUnwrapNode(&arena.allocator, if_node.condition),
));
}
return try declsFromIndexInternal(arena, decls, tree, if_node.body, source_index, innermost_container);
}
if (if_node.@"else") |else_node| {
if (nodeContainsSourceIndex(tree, else_node.body, source_index)) {
if (else_node.payload) |payload| {
try declsFromIndexInternal(arena, decls, tree, payload, source_index, innermost_container);
}
return try declsFromIndexInternal(arena, decls, tree, else_node.body, source_index, innermost_container);
}
}
},
.While => {
const while_node = node.cast(ast.Node.While).?;
if (nodeContainsSourceIndex(tree, while_node.body, source_index)) {
if (while_node.payload) |payload| {
std.debug.assert(payload.id == .PointerPayload);
const ptr_payload = payload.cast(ast.Node.PointerPayload).?;
std.debug.assert(ptr_payload.value_symbol.id == .Identifier);
try decls.append(try makeVarDeclNode(
&arena.allocator,
null,
null,
ptr_payload.value_symbol.firstToken(),
null,
try makeUnwrapNode(&arena.allocator, while_node.condition),
));
}
return try declsFromIndexInternal(arena, decls, tree, while_node.body, source_index, innermost_container);
}
if (while_node.@"else") |else_node| {
if (nodeContainsSourceIndex(tree, else_node.body, source_index)) {
if (else_node.payload) |payload| {
try declsFromIndexInternal(arena, decls, tree, payload, source_index, innermost_container);
}
return try declsFromIndexInternal(arena, decls, tree, else_node.body, source_index, innermost_container);
}
}
},
.For => {
const for_node = node.cast(ast.Node.For).?;
if (nodeContainsSourceIndex(tree, for_node.body, source_index)) {
std.debug.assert(for_node.payload.id == .PointerIndexPayload);
const ptr_idx_payload = for_node.payload.cast(ast.Node.PointerIndexPayload).?;
std.debug.assert(ptr_idx_payload.value_symbol.id == .Identifier);
try decls.append(try makeVarDeclNode(
&arena.allocator,
null,
null,
ptr_idx_payload.value_symbol.firstToken(),
null,
try makeAccessNode(&arena.allocator, for_node.array_expr),
));
if (ptr_idx_payload.index_symbol) |idx| {
try decls.append(idx);
}
return try declsFromIndexInternal(arena, decls, tree, for_node.body, source_index, innermost_container);
}
if (for_node.@"else") |else_node| {
if (nodeContainsSourceIndex(tree, else_node.body, source_index)) {
if (else_node.payload) |payload| {
try declsFromIndexInternal(arena, decls, tree, payload, source_index, innermost_container);
}
return try declsFromIndexInternal(arena, decls, tree, else_node.body, source_index, innermost_container);
}
}
},
.Switch => {
const switch_node = node.cast(ast.Node.Switch).?;
for (switch_node.casesConst()) |case| {
const case_node = case.*.cast(ast.Node.SwitchCase).?;
if (nodeContainsSourceIndex(tree, case_node.expr, source_index)) {
if (case_node.payload) |payload| {
try declsFromIndexInternal(arena, decls, tree, payload, source_index, innermost_container);
}
return try declsFromIndexInternal(arena, decls, tree, case_node.expr, source_index, innermost_container);
}
}
},
// TODO: These convey no type information...
.Payload => try decls.append(node.cast(ast.Node.Payload).?.error_symbol),
.PointerPayload => try decls.append(node.cast(ast.Node.PointerPayload).?.value_symbol),
// This should be completely handled for the .For code.
.PointerIndexPayload => unreachable,
.VarDecl => {
try decls.append(node);
if (node.cast(ast.Node.VarDecl).?.init_node) |child| {
if (nodeContainsSourceIndex(tree, child, source_index)) {
try declsFromIndexInternal(arena, decls, tree, child, source_index, innermost_container);
}
}
},
else => {},
}
}
pub fn addChildrenNodes(decls: *std.ArrayList(*ast.Node), tree: *ast.Tree, node: *ast.Node) !void {
var node_idx: usize = 0;
while (node.iterate(node_idx)) |child_node| : (node_idx += 1) {
try decls.append(child_node);
}
}
pub fn declsFromIndex(arena: *std.heap.ArenaAllocator, decls: *std.ArrayList(*ast.Node), tree: *ast.Tree, source_index: usize) !*ast.Node {
var innermost_container = &tree.root_node.base;
try declsFromIndexInternal(arena, decls, tree, &tree.root_node.base, source_index, &innermost_container);
return innermost_container;
}
fn nodeContainsSourceIndex(tree: *ast.Tree, node: *ast.Node, source_index: usize) bool {
const first_token = tree.token_locs[node.firstToken()];
const last_token = tree.token_locs[node.lastToken()];
return source_index >= first_token.start and source_index <= last_token.end;
}
fn nodeComesAfterSourceIndex(tree: *ast.Tree, node: *ast.Node, source_index: usize) bool {
const first_token = tree.token_locs[node.firstToken()];
const last_token = tree.token_locs[node.lastToken()];
return source_index < first_token.start;
}
pub fn getImportStr(tree: *ast.Tree, source_index: usize) ?[]const u8 {
var node = &tree.root_node.base;
var child_idx: usize = 0;
while (node.iterate(child_idx)) |child| {
if (!nodeContainsSourceIndex(tree, child, source_index)) {
child_idx += 1;
continue;
}
if (child.cast(ast.Node.BuiltinCall)) |builtin_call| blk: {
const call_name = tree.tokenSlice(builtin_call.builtin_token);
if (!std.mem.eql(u8, call_name, "@import")) break :blk;
if (builtin_call.params_len != 1) break :blk;
const import_param = builtin_call.paramsConst()[0];
const import_str_node = import_param.cast(ast.Node.StringLiteral) orelse break :blk;
const import_str = tree.tokenSlice(import_str_node.token);
return import_str[1 .. import_str.len - 1];
}
node = child;
child_idx = 0;
}
return null;
}
pub const SourceRange = std.zig.Token.Loc;
pub const PositionContext = union(enum) {
builtin: SourceRange,
comment,
string_literal: SourceRange,
field_access: SourceRange,
var_access: SourceRange,
global_error_set,
enum_literal,
other,
empty,
pub fn range(self: PositionContext) ?SourceRange {
return switch (self) {
.builtin => |r| r,
.comment => null,
.string_literal => |r| r,
.field_access => |r| r,
.var_access => |r| r,
.enum_literal => null,
.other => null,
.empty => null,
.global_error_set => null,
};
}
};
const StackState = struct {
ctx: PositionContext,
stack_id: enum { Paren, Bracket, Global },
};
fn peek(arr: *std.ArrayList(StackState)) !*StackState {
if (arr.items.len == 0) {
try arr.append(.{ .ctx = .empty, .stack_id = .Global });
}
return &arr.items[arr.items.len - 1];
}
fn tokenRangeAppend(prev: SourceRange, token: std.zig.Token) SourceRange {
return .{
.start = prev.start,
.end = token.loc.end,
};
}
pub fn documentPositionContext(allocator: *std.mem.Allocator, document: types.TextDocument, position: types.Position) !PositionContext {
const line = try document.getLine(@intCast(usize, position.line));
const pos_char = @intCast(usize, position.character) + 1;
const idx = if (pos_char > line.len) line.len else pos_char;
var arena = std.heap.ArenaAllocator.init(allocator);
defer arena.deinit();
var tokenizer = std.zig.Tokenizer.init(line[0..idx]);
var stack = try std.ArrayList(StackState).initCapacity(&arena.allocator, 8);
while (true) {
const tok = tokenizer.next();
// Early exits.
switch (tok.id) {
.Invalid, .Invalid_ampersands => {
// Single '@' do not return a builtin token so we check this on our own.
if (line[idx - 1] == '@') {
return PositionContext{
.builtin = .{
.start = idx - 1,
.end = idx,
},
};
}
return .other;
},
.LineComment, .DocComment, .ContainerDocComment => return .comment,
.Eof => break,
else => {},
}
// State changes
var curr_ctx = try peek(&stack);
switch (tok.id) {
.StringLiteral, .MultilineStringLiteralLine => curr_ctx.ctx = .{ .string_literal = tok.loc },
.Identifier => switch (curr_ctx.ctx) {
.empty => curr_ctx.ctx = .{ .var_access = tok.loc },
else => {},
},
.Builtin => switch (curr_ctx.ctx) {
.empty => curr_ctx.ctx = .{ .builtin = tok.loc },
else => {},
},
.Period, .PeriodAsterisk => switch (curr_ctx.ctx) {
.empty => curr_ctx.ctx = .enum_literal,
.enum_literal => curr_ctx.ctx = .empty,
.field_access => {},
.other => {},
.global_error_set => {},
else => curr_ctx.ctx = .{
.field_access = tokenRangeAppend(curr_ctx.ctx.range().?, tok),
},
},
.QuestionMark => switch (curr_ctx.ctx) {
.field_access => {},
else => curr_ctx.ctx = .empty,
},
.LParen => try stack.append(.{ .ctx = .empty, .stack_id = .Paren }),
.LBracket => try stack.append(.{ .ctx = .empty, .stack_id = .Bracket }),
.RParen => {
_ = stack.pop();
if (curr_ctx.stack_id != .Paren) {
(try peek(&stack)).ctx = .empty;
}
},
.RBracket => {
_ = stack.pop();
if (curr_ctx.stack_id != .Bracket) {
(try peek(&stack)).ctx = .empty;
}
},
.Keyword_error => curr_ctx.ctx = .global_error_set,
else => curr_ctx.ctx = .empty,
}
switch (curr_ctx.ctx) {
.field_access => |r| curr_ctx.ctx = .{
.field_access = tokenRangeAppend(r, tok),
},
else => {},
}
}
return block: {
if (stack.popOrNull()) |state| break :block state.ctx;
break :block .empty;
};
}
fn addOutlineNodes(allocator: *std.mem.Allocator, children: *std.ArrayList(types.DocumentSymbol), tree: *ast.Tree, child: *ast.Node) anyerror!void {
switch (child.id) {
.StringLiteral, .IntegerLiteral, .BuiltinCall, .Call, .Identifier, .InfixOp, .PrefixOp, .SuffixOp, .ControlFlowExpression, .ArrayInitializerDot, .SwitchElse, .SwitchCase, .For, .EnumLiteral, .PointerIndexPayload, .StructInitializerDot, .PointerPayload, .While, .Switch, .Else, .BoolLiteral, .NullLiteral, .Defer, .StructInitializer, .FieldInitializer, .If, .MultilineStringLiteral, .UndefinedLiteral, .VarType, .Block => return,
.ContainerDecl => {
const decl = child.cast(ast.Node.ContainerDecl).?;
for (decl.fieldsAndDecls()) |cchild|
try addOutlineNodes(allocator, children, tree, cchild);
return;
},
else => {},
}
_ = try children.append(try getDocumentSymbolsInternal(allocator, tree, child));
}
fn getDocumentSymbolsInternal(allocator: *std.mem.Allocator, tree: *ast.Tree, node: *ast.Node) anyerror!types.DocumentSymbol {
// const symbols = std.ArrayList(types.DocumentSymbol).init(allocator);
const start_loc = tree.tokenLocation(0, node.firstToken());
const end_loc = tree.tokenLocation(0, node.lastToken());
const range = types.Range{
.start = .{
.line = @intCast(i64, start_loc.line),
.character = @intCast(i64, start_loc.column),
},
.end = .{
.line = @intCast(i64, end_loc.line),
.character = @intCast(i64, end_loc.column),
},
};
if (getDeclName(tree, node) == null) {
std.debug.warn("NULL NAME: {}\n", .{node.id});
}
// TODO: Get my lazy bum to fix detail newlines
return types.DocumentSymbol{
.name = getDeclName(tree, node) orelse "no_name",
// .detail = (try getDocComments(allocator, tree, node)) orelse "",
.detail = "",
.kind = switch (node.id) {
.FnProto => .Function,
.VarDecl => .Variable,
.ContainerField => .Field,
else => .Variable,
},
.range = range,
.selectionRange = range,
.children = ch: {
var children = std.ArrayList(types.DocumentSymbol).init(allocator);
var index: usize = 0;
while (node.iterate(index)) |child| : (index += 1) {
try addOutlineNodes(allocator, &children, tree, child);
}
break :ch children.items;
},
};
// return symbols.items;
}
pub fn getDocumentSymbols(allocator: *std.mem.Allocator, tree: *ast.Tree) ![]types.DocumentSymbol {
var symbols = std.ArrayList(types.DocumentSymbol).init(allocator);
for (tree.root_node.decls()) |node| {
_ = try symbols.append(try getDocumentSymbolsInternal(allocator, tree, node));
}
return symbols.items;
} | src/analysis.zig |
const std = @import("std");
const SYS = @import("./consts.zig").SYS;
inline fn syscall0(n: SYS) usize {
return asm volatile ("int $0x80"
: [ret] "={eax}" (-> usize),
: [n] "{eax}" (n),
: "memory", "cc"
);
}
inline fn syscall1(n: SYS, arg1: usize) usize {
return asm volatile ("int $0x80"
: [ret] "={eax}" (-> usize),
: [n] "{eax}" (n),
[arg1] "{ebx}" (arg1),
: "memory", "cc"
);
}
inline fn syscall2(n: SYS, arg1: usize, arg2: usize) usize {
return asm volatile ("int $0x80"
: [ret] "={eax}" (-> usize),
: [n] "{eax}" (n),
[arg1] "{ebx}" (arg1),
[arg2] "{ecx}" (arg2),
: "memory", "cc"
);
}
inline fn syscall3(n: SYS, arg1: usize, arg2: usize, arg3: usize) usize {
return asm volatile ("int $0x80"
: [ret] "={eax}" (-> usize),
: [n] "{eax}" (n),
[arg1] "{ebx}" (arg1),
[arg2] "{ecx}" (arg2),
[arg3] "{edx}" (arg3),
: "memory", "cc"
);
}
inline fn syscall4(n: SYS, arg1: usize, arg2: usize, arg3: usize, arg4: usize) usize {
return asm volatile ("int $0x80"
: [ret] "={eax}" (-> usize),
: [n] "{eax}" (n),
[arg1] "{ebx}" (arg1),
[arg2] "{ecx}" (arg2),
[arg3] "{edx}" (arg3),
[arg4] "{esi}" (arg4),
: "memory", "cc"
);
}
inline fn syscall5(n: SYS, arg1: usize, arg2: usize, arg3: usize, arg4: usize, arg5: usize) usize {
return asm volatile ("int $0x80"
: [ret] "={eax}" (-> usize),
: [n] "{eax}" (n),
[arg1] "{ebx}" (arg1),
[arg2] "{ecx}" (arg2),
[arg3] "{edx}" (arg3),
[arg4] "{esi}" (arg4),
[arg5] "{edi}" (arg5),
: "memory", "cc"
);
}
inline fn syscall6(n: SYS, arg1: usize, arg2: usize, arg3: usize, arg4: usize, arg5: usize, arg6: usize) usize {
return asm volatile ("int $0x80"
: [ret] "={eax}" (-> usize),
: [n] "{eax}" (n),
[arg1] "{ebx}" (arg1),
[arg2] "{ecx}" (arg2),
[arg3] "{edx}" (arg3),
[arg4] "{esi}" (arg4),
[arg5] "{edi}" (arg5),
[arg6] "{ebp}" (arg6),
: "memory", "cc"
);
}
pub inline fn syscall(n: SYS, args: anytype) usize {
const typ = @TypeOf(args);
comptime if (!std.meta.trait.isTuple(typ)) {
@compileError("syscall only accept tuple as argument");
};
const fun = comptime switch (args.len) {
0 => syscall0,
1 => syscall1,
2 => syscall2,
3 => syscall3,
4 => syscall4,
5 => syscall5,
6 => syscall6,
else => @compileError("Unsupported arguments length"),
};
const full_args = comptime .{n} ++ args;
return @call(.{}, fun, full_args);
} | src/linux/i386/calls.zig |
const std = @import("std");
const gl = @import("renderkit").gl;
const gk = @import("gamekit");
const math = gk.math;
const gfx = gk.gfx;
const draw = gfx.draw;
const Thing = struct {
dir: f32,
pos: math.Vec2 = .{},
col: math.Color,
};
var white_tex: gfx.Texture = undefined;
var pass: gfx.OffscreenPass = undefined;
var points: [2]Thing = [_]Thing{
.{ .dir = 1, .pos = .{ .x = 60, .y = 300 }, .col = math.Color.red },
.{ .dir = -1, .pos = .{ .x = 600, .y = 300 }, .col = math.Color.blue },
};
pub fn main() !void {
try gk.run(.{
.init = init,
.update = update,
.render = render,
});
}
fn init() !void {
white_tex = gfx.Texture.initSingleColor(0xFFFFFFFF);
const size = gk.window.size();
pass = gfx.OffscreenPass.initWithStencil(size.w, size.h, .nearest, .clamp);
}
fn update() !void {
const speed: f32 = 5;
const size = gk.window.size();
for (points) |*p| {
p.pos.x += p.dir * speed;
if (p.pos.x + 30 > @intToFloat(f32, size.w)) p.dir *= -1;
if (p.pos.x - 30 < 0) p.dir *= -1;
}
}
fn render() !void {
// offscreen rendering. set stencil to write
gfx.setRenderState(.{
.stencil = .{
.enabled = true,
.write_mask = 0xFF,
.compare_func = .always,
.ref = 1,
.read_mask = 0xFF,
}
});
gk.gfx.beginPass(.{
.color = math.Color.purple,
.pass = pass,
.clear_stencil = true,
});
draw.point(points[0].pos, 160, points[0].col);
gk.gfx.endPass();
// set stencil to read
gfx.setRenderState(.{
.stencil = .{
.enabled = true,
.write_mask = 0x00, // disable writing to stencil
.compare_func = .equal,
.ref = 1,
.read_mask = 0xFF,
}
});
gk.gfx.beginPass(.{
.clear_color = false,
.clear_stencil = false,
.pass = pass,
});
draw.point(points[1].pos, 60, points[1].col);
gk.gfx.endPass();
// backbuffer rendering, reset stencil
gfx.setRenderState(.{});
gk.gfx.beginPass(.{});
draw.tex(pass.color_texture, .{});
gk.gfx.endPass();
} | examples/stencil.zig |
pub const SI_EDIT_PERMS = @as(i32, 0);
pub const SI_EDIT_OWNER = @as(i32, 1);
pub const SI_CONTAINER = @as(i32, 4);
pub const SI_READONLY = @as(i32, 8);
pub const SI_RESET = @as(i32, 32);
pub const SI_OWNER_READONLY = @as(i32, 64);
pub const SI_OWNER_RECURSE = @as(i32, 256);
pub const SI_NO_ACL_PROTECT = @as(i32, 512);
pub const SI_NO_TREE_APPLY = @as(i32, 1024);
pub const SI_PAGE_TITLE = @as(i32, 2048);
pub const SI_SERVER_IS_DC = @as(i32, 4096);
pub const SI_RESET_DACL_TREE = @as(i32, 16384);
pub const SI_RESET_SACL_TREE = @as(i32, 32768);
pub const SI_OBJECT_GUID = @as(i32, 65536);
pub const SI_ACCESS_SPECIFIC = @as(i32, 65536);
pub const SI_ACCESS_GENERAL = @as(i32, 131072);
pub const SI_ACCESS_CONTAINER = @as(i32, 262144);
pub const SI_ACCESS_PROPERTY = @as(i32, 524288);
pub const DOBJ_RES_CONT = @as(i32, 1);
pub const DOBJ_RES_ROOT = @as(i32, 2);
pub const DOBJ_VOL_NTACLS = @as(i32, 4);
pub const DOBJ_COND_NTACLS = @as(i32, 8);
pub const DOBJ_RIBBON_LAUNCH = @as(i32, 16);
pub const SECURITY_OBJECT_ID_OBJECT_SD = @as(u32, 1);
pub const SECURITY_OBJECT_ID_SHARE = @as(u32, 2);
pub const SECURITY_OBJECT_ID_CENTRAL_POLICY = @as(u32, 3);
pub const SECURITY_OBJECT_ID_CENTRAL_ACCESS_RULE = @as(u32, 4);
//--------------------------------------------------------------------------------
// Section: Types (18)
//--------------------------------------------------------------------------------
pub const SECURITY_INFO_PAGE_FLAGS = enum(u32) {
ADVANCED = 16,
EDIT_AUDITS = 2,
EDIT_PROPERTIES = 128,
_,
pub fn initFlags(o: struct {
ADVANCED: u1 = 0,
EDIT_AUDITS: u1 = 0,
EDIT_PROPERTIES: u1 = 0,
}) SECURITY_INFO_PAGE_FLAGS {
return @intToEnum(SECURITY_INFO_PAGE_FLAGS,
(if (o.ADVANCED == 1) @enumToInt(SECURITY_INFO_PAGE_FLAGS.ADVANCED) else 0)
| (if (o.EDIT_AUDITS == 1) @enumToInt(SECURITY_INFO_PAGE_FLAGS.EDIT_AUDITS) else 0)
| (if (o.EDIT_PROPERTIES == 1) @enumToInt(SECURITY_INFO_PAGE_FLAGS.EDIT_PROPERTIES) else 0)
);
}
};
pub const SI_ADVANCED = SECURITY_INFO_PAGE_FLAGS.ADVANCED;
pub const SI_EDIT_AUDITS = SECURITY_INFO_PAGE_FLAGS.EDIT_AUDITS;
pub const SI_EDIT_PROPERTIES = SECURITY_INFO_PAGE_FLAGS.EDIT_PROPERTIES;
pub const SI_OBJECT_INFO_FLAGS = enum(u32) {
AUDITS_ELEVATION_REQUIRED = 33554432,
DISABLE_DENY_ACE = 2147483648,
EDIT_EFFECTIVE = 131072,
ENABLE_CENTRAL_POLICY = 1073741824,
ENABLE_EDIT_ATTRIBUTE_CONDITION = 536870912,
MAY_WRITE = 268435456,
NO_ADDITIONAL_PERMISSION = 2097152,
OWNER_ELEVATION_REQUIRED = 67108864,
PERMS_ELEVATION_REQUIRED = 16777216,
RESET_DACL = 262144,
RESET_OWNER = 1048576,
RESET_SACL = 524288,
SCOPE_ELEVATION_REQUIRED = 134217728,
VIEW_ONLY = 4194304,
_,
pub fn initFlags(o: struct {
AUDITS_ELEVATION_REQUIRED: u1 = 0,
DISABLE_DENY_ACE: u1 = 0,
EDIT_EFFECTIVE: u1 = 0,
ENABLE_CENTRAL_POLICY: u1 = 0,
ENABLE_EDIT_ATTRIBUTE_CONDITION: u1 = 0,
MAY_WRITE: u1 = 0,
NO_ADDITIONAL_PERMISSION: u1 = 0,
OWNER_ELEVATION_REQUIRED: u1 = 0,
PERMS_ELEVATION_REQUIRED: u1 = 0,
RESET_DACL: u1 = 0,
RESET_OWNER: u1 = 0,
RESET_SACL: u1 = 0,
SCOPE_ELEVATION_REQUIRED: u1 = 0,
VIEW_ONLY: u1 = 0,
}) SI_OBJECT_INFO_FLAGS {
return @intToEnum(SI_OBJECT_INFO_FLAGS,
(if (o.AUDITS_ELEVATION_REQUIRED == 1) @enumToInt(SI_OBJECT_INFO_FLAGS.AUDITS_ELEVATION_REQUIRED) else 0)
| (if (o.DISABLE_DENY_ACE == 1) @enumToInt(SI_OBJECT_INFO_FLAGS.DISABLE_DENY_ACE) else 0)
| (if (o.EDIT_EFFECTIVE == 1) @enumToInt(SI_OBJECT_INFO_FLAGS.EDIT_EFFECTIVE) else 0)
| (if (o.ENABLE_CENTRAL_POLICY == 1) @enumToInt(SI_OBJECT_INFO_FLAGS.ENABLE_CENTRAL_POLICY) else 0)
| (if (o.ENABLE_EDIT_ATTRIBUTE_CONDITION == 1) @enumToInt(SI_OBJECT_INFO_FLAGS.ENABLE_EDIT_ATTRIBUTE_CONDITION) else 0)
| (if (o.MAY_WRITE == 1) @enumToInt(SI_OBJECT_INFO_FLAGS.MAY_WRITE) else 0)
| (if (o.NO_ADDITIONAL_PERMISSION == 1) @enumToInt(SI_OBJECT_INFO_FLAGS.NO_ADDITIONAL_PERMISSION) else 0)
| (if (o.OWNER_ELEVATION_REQUIRED == 1) @enumToInt(SI_OBJECT_INFO_FLAGS.OWNER_ELEVATION_REQUIRED) else 0)
| (if (o.PERMS_ELEVATION_REQUIRED == 1) @enumToInt(SI_OBJECT_INFO_FLAGS.PERMS_ELEVATION_REQUIRED) else 0)
| (if (o.RESET_DACL == 1) @enumToInt(SI_OBJECT_INFO_FLAGS.RESET_DACL) else 0)
| (if (o.RESET_OWNER == 1) @enumToInt(SI_OBJECT_INFO_FLAGS.RESET_OWNER) else 0)
| (if (o.RESET_SACL == 1) @enumToInt(SI_OBJECT_INFO_FLAGS.RESET_SACL) else 0)
| (if (o.SCOPE_ELEVATION_REQUIRED == 1) @enumToInt(SI_OBJECT_INFO_FLAGS.SCOPE_ELEVATION_REQUIRED) else 0)
| (if (o.VIEW_ONLY == 1) @enumToInt(SI_OBJECT_INFO_FLAGS.VIEW_ONLY) else 0)
);
}
};
pub const SI_AUDITS_ELEVATION_REQUIRED = SI_OBJECT_INFO_FLAGS.AUDITS_ELEVATION_REQUIRED;
pub const SI_DISABLE_DENY_ACE = SI_OBJECT_INFO_FLAGS.DISABLE_DENY_ACE;
pub const SI_EDIT_EFFECTIVE = SI_OBJECT_INFO_FLAGS.EDIT_EFFECTIVE;
pub const SI_ENABLE_CENTRAL_POLICY = SI_OBJECT_INFO_FLAGS.ENABLE_CENTRAL_POLICY;
pub const SI_ENABLE_EDIT_ATTRIBUTE_CONDITION = SI_OBJECT_INFO_FLAGS.ENABLE_EDIT_ATTRIBUTE_CONDITION;
pub const SI_MAY_WRITE = SI_OBJECT_INFO_FLAGS.MAY_WRITE;
pub const SI_NO_ADDITIONAL_PERMISSION = SI_OBJECT_INFO_FLAGS.NO_ADDITIONAL_PERMISSION;
pub const SI_OWNER_ELEVATION_REQUIRED = SI_OBJECT_INFO_FLAGS.OWNER_ELEVATION_REQUIRED;
pub const SI_PERMS_ELEVATION_REQUIRED = SI_OBJECT_INFO_FLAGS.PERMS_ELEVATION_REQUIRED;
pub const SI_RESET_DACL = SI_OBJECT_INFO_FLAGS.RESET_DACL;
pub const SI_RESET_OWNER = SI_OBJECT_INFO_FLAGS.RESET_OWNER;
pub const SI_RESET_SACL = SI_OBJECT_INFO_FLAGS.RESET_SACL;
pub const SI_SCOPE_ELEVATION_REQUIRED = SI_OBJECT_INFO_FLAGS.SCOPE_ELEVATION_REQUIRED;
pub const SI_VIEW_ONLY = SI_OBJECT_INFO_FLAGS.VIEW_ONLY;
pub const SI_OBJECT_INFO = extern struct {
dwFlags: SI_OBJECT_INFO_FLAGS,
hInstance: ?HINSTANCE,
pszServerName: ?PWSTR,
pszObjectName: ?PWSTR,
pszPageTitle: ?PWSTR,
guidObjectType: Guid,
};
pub const SI_ACCESS = extern struct {
pguid: ?*const Guid,
mask: u32,
pszName: ?[*:0]const u16,
dwFlags: u32,
};
pub const SI_INHERIT_TYPE = extern struct {
pguid: ?*const Guid,
dwFlags: ACE_FLAGS,
pszName: ?[*:0]const u16,
};
pub const SI_PAGE_TYPE = enum(i32) {
PERM = 0,
ADVPERM = 1,
AUDIT = 2,
OWNER = 3,
EFFECTIVE = 4,
TAKEOWNERSHIP = 5,
SHARE = 6,
};
pub const SI_PAGE_PERM = SI_PAGE_TYPE.PERM;
pub const SI_PAGE_ADVPERM = SI_PAGE_TYPE.ADVPERM;
pub const SI_PAGE_AUDIT = SI_PAGE_TYPE.AUDIT;
pub const SI_PAGE_OWNER = SI_PAGE_TYPE.OWNER;
pub const SI_PAGE_EFFECTIVE = SI_PAGE_TYPE.EFFECTIVE;
pub const SI_PAGE_TAKEOWNERSHIP = SI_PAGE_TYPE.TAKEOWNERSHIP;
pub const SI_PAGE_SHARE = SI_PAGE_TYPE.SHARE;
pub const SI_PAGE_ACTIVATED = enum(i32) {
DEFAULT = 0,
PERM_ACTIVATED = 1,
AUDIT_ACTIVATED = 2,
OWNER_ACTIVATED = 3,
EFFECTIVE_ACTIVATED = 4,
SHARE_ACTIVATED = 5,
CENTRAL_POLICY_ACTIVATED = 6,
};
pub const SI_SHOW_DEFAULT = SI_PAGE_ACTIVATED.DEFAULT;
pub const SI_SHOW_PERM_ACTIVATED = SI_PAGE_ACTIVATED.PERM_ACTIVATED;
pub const SI_SHOW_AUDIT_ACTIVATED = SI_PAGE_ACTIVATED.AUDIT_ACTIVATED;
pub const SI_SHOW_OWNER_ACTIVATED = SI_PAGE_ACTIVATED.OWNER_ACTIVATED;
pub const SI_SHOW_EFFECTIVE_ACTIVATED = SI_PAGE_ACTIVATED.EFFECTIVE_ACTIVATED;
pub const SI_SHOW_SHARE_ACTIVATED = SI_PAGE_ACTIVATED.SHARE_ACTIVATED;
pub const SI_SHOW_CENTRAL_POLICY_ACTIVATED = SI_PAGE_ACTIVATED.CENTRAL_POLICY_ACTIVATED;
// TODO: this type is limited to platform 'windows5.1.2600'
const IID_ISecurityInformation_Value = @import("../../zig.zig").Guid.initString("965fc360-16ff-11d0-91cb-00aa00bbb723");
pub const IID_ISecurityInformation = &IID_ISecurityInformation_Value;
pub const ISecurityInformation = extern struct {
pub const VTable = extern struct {
base: IUnknown.VTable,
GetObjectInformation: fn(
self: *const ISecurityInformation,
pObjectInfo: ?*SI_OBJECT_INFO,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetSecurity: fn(
self: *const ISecurityInformation,
RequestedInformation: OBJECT_SECURITY_INFORMATION,
ppSecurityDescriptor: ?*?*SECURITY_DESCRIPTOR,
fDefault: BOOL,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
SetSecurity: fn(
self: *const ISecurityInformation,
SecurityInformation: OBJECT_SECURITY_INFORMATION,
pSecurityDescriptor: ?*SECURITY_DESCRIPTOR,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetAccessRights: fn(
self: *const ISecurityInformation,
pguidObjectType: ?*const Guid,
dwFlags: SECURITY_INFO_PAGE_FLAGS,
ppAccess: ?*?*SI_ACCESS,
pcAccesses: ?*u32,
piDefaultAccess: ?*u32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
MapGeneric: fn(
self: *const ISecurityInformation,
pguidObjectType: ?*const Guid,
pAceFlags: ?*u8,
pMask: ?*u32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
GetInheritTypes: fn(
self: *const ISecurityInformation,
ppInheritTypes: ?*?*SI_INHERIT_TYPE,
pcInheritTypes: ?*u32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
PropertySheetPageCallback: fn(
self: *const ISecurityInformation,
hwnd: ?HWND,
uMsg: PSPCB_MESSAGE,
uPage: SI_PAGE_TYPE,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
};
vtable: *const VTable,
pub fn MethodMixin(comptime T: type) type { return struct {
pub usingnamespace IUnknown.MethodMixin(T);
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ISecurityInformation_GetObjectInformation(self: *const T, pObjectInfo: ?*SI_OBJECT_INFO) callconv(.Inline) HRESULT {
return @ptrCast(*const ISecurityInformation.VTable, self.vtable).GetObjectInformation(@ptrCast(*const ISecurityInformation, self), pObjectInfo);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ISecurityInformation_GetSecurity(self: *const T, RequestedInformation: OBJECT_SECURITY_INFORMATION, ppSecurityDescriptor: ?*?*SECURITY_DESCRIPTOR, fDefault: BOOL) callconv(.Inline) HRESULT {
return @ptrCast(*const ISecurityInformation.VTable, self.vtable).GetSecurity(@ptrCast(*const ISecurityInformation, self), RequestedInformation, ppSecurityDescriptor, fDefault);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ISecurityInformation_SetSecurity(self: *const T, SecurityInformation: OBJECT_SECURITY_INFORMATION, pSecurityDescriptor: ?*SECURITY_DESCRIPTOR) callconv(.Inline) HRESULT {
return @ptrCast(*const ISecurityInformation.VTable, self.vtable).SetSecurity(@ptrCast(*const ISecurityInformation, self), SecurityInformation, pSecurityDescriptor);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ISecurityInformation_GetAccessRights(self: *const T, pguidObjectType: ?*const Guid, dwFlags: SECURITY_INFO_PAGE_FLAGS, ppAccess: ?*?*SI_ACCESS, pcAccesses: ?*u32, piDefaultAccess: ?*u32) callconv(.Inline) HRESULT {
return @ptrCast(*const ISecurityInformation.VTable, self.vtable).GetAccessRights(@ptrCast(*const ISecurityInformation, self), pguidObjectType, dwFlags, ppAccess, pcAccesses, piDefaultAccess);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ISecurityInformation_MapGeneric(self: *const T, pguidObjectType: ?*const Guid, pAceFlags: ?*u8, pMask: ?*u32) callconv(.Inline) HRESULT {
return @ptrCast(*const ISecurityInformation.VTable, self.vtable).MapGeneric(@ptrCast(*const ISecurityInformation, self), pguidObjectType, pAceFlags, pMask);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ISecurityInformation_GetInheritTypes(self: *const T, ppInheritTypes: ?*?*SI_INHERIT_TYPE, pcInheritTypes: ?*u32) callconv(.Inline) HRESULT {
return @ptrCast(*const ISecurityInformation.VTable, self.vtable).GetInheritTypes(@ptrCast(*const ISecurityInformation, self), ppInheritTypes, pcInheritTypes);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ISecurityInformation_PropertySheetPageCallback(self: *const T, hwnd: ?HWND, uMsg: PSPCB_MESSAGE, uPage: SI_PAGE_TYPE) callconv(.Inline) HRESULT {
return @ptrCast(*const ISecurityInformation.VTable, self.vtable).PropertySheetPageCallback(@ptrCast(*const ISecurityInformation, self), hwnd, uMsg, uPage);
}
};}
pub usingnamespace MethodMixin(@This());
};
// TODO: this type is limited to platform 'windows5.1.2600'
const IID_ISecurityInformation2_Value = @import("../../zig.zig").Guid.initString("c3ccfdb4-6f88-11d2-a3ce-00c04fb1782a");
pub const IID_ISecurityInformation2 = &IID_ISecurityInformation2_Value;
pub const ISecurityInformation2 = extern struct {
pub const VTable = extern struct {
base: IUnknown.VTable,
IsDaclCanonical: fn(
self: *const ISecurityInformation2,
pDacl: ?*ACL,
) callconv(@import("std").os.windows.WINAPI) BOOL,
LookupSids: fn(
self: *const ISecurityInformation2,
cSids: u32,
rgpSids: ?*?PSID,
ppdo: ?*?*IDataObject,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
};
vtable: *const VTable,
pub fn MethodMixin(comptime T: type) type { return struct {
pub usingnamespace IUnknown.MethodMixin(T);
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ISecurityInformation2_IsDaclCanonical(self: *const T, pDacl: ?*ACL) callconv(.Inline) BOOL {
return @ptrCast(*const ISecurityInformation2.VTable, self.vtable).IsDaclCanonical(@ptrCast(*const ISecurityInformation2, self), pDacl);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ISecurityInformation2_LookupSids(self: *const T, cSids: u32, rgpSids: ?*?PSID, ppdo: ?*?*IDataObject) callconv(.Inline) HRESULT {
return @ptrCast(*const ISecurityInformation2.VTable, self.vtable).LookupSids(@ptrCast(*const ISecurityInformation2, self), cSids, rgpSids, ppdo);
}
};}
pub usingnamespace MethodMixin(@This());
};
pub const SID_INFO = extern struct {
pSid: ?PSID,
pwzCommonName: ?PWSTR,
pwzClass: ?PWSTR,
pwzUPN: ?PWSTR,
};
pub const SID_INFO_LIST = extern struct {
cItems: u32,
aSidInfo: [1]SID_INFO,
};
// TODO: this type is limited to platform 'windows5.1.2600'
const IID_IEffectivePermission_Value = @import("../../zig.zig").Guid.initString("3853dc76-9f35-407c-88a1-d19344365fbc");
pub const IID_IEffectivePermission = &IID_IEffectivePermission_Value;
pub const IEffectivePermission = extern struct {
pub const VTable = extern struct {
base: IUnknown.VTable,
GetEffectivePermission: fn(
self: *const IEffectivePermission,
pguidObjectType: ?*const Guid,
pUserSid: ?PSID,
pszServerName: ?[*:0]const u16,
pSD: ?*SECURITY_DESCRIPTOR,
ppObjectTypeList: ?*?*OBJECT_TYPE_LIST,
pcObjectTypeListLength: ?*u32,
ppGrantedAccessList: ?*?*u32,
pcGrantedAccessListLength: ?*u32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
};
vtable: *const VTable,
pub fn MethodMixin(comptime T: type) type { return struct {
pub usingnamespace IUnknown.MethodMixin(T);
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IEffectivePermission_GetEffectivePermission(self: *const T, pguidObjectType: ?*const Guid, pUserSid: ?PSID, pszServerName: ?[*:0]const u16, pSD: ?*SECURITY_DESCRIPTOR, ppObjectTypeList: ?*?*OBJECT_TYPE_LIST, pcObjectTypeListLength: ?*u32, ppGrantedAccessList: ?*?*u32, pcGrantedAccessListLength: ?*u32) callconv(.Inline) HRESULT {
return @ptrCast(*const IEffectivePermission.VTable, self.vtable).GetEffectivePermission(@ptrCast(*const IEffectivePermission, self), pguidObjectType, pUserSid, pszServerName, pSD, ppObjectTypeList, pcObjectTypeListLength, ppGrantedAccessList, pcGrantedAccessListLength);
}
};}
pub usingnamespace MethodMixin(@This());
};
// TODO: this type is limited to platform 'windows5.1.2600'
const IID_ISecurityObjectTypeInfo_Value = @import("../../zig.zig").Guid.initString("fc3066eb-79ef-444b-9111-d18a75ebf2fa");
pub const IID_ISecurityObjectTypeInfo = &IID_ISecurityObjectTypeInfo_Value;
pub const ISecurityObjectTypeInfo = extern struct {
pub const VTable = extern struct {
base: IUnknown.VTable,
GetInheritSource: fn(
self: *const ISecurityObjectTypeInfo,
si: u32,
pACL: ?*ACL,
ppInheritArray: ?*?*INHERITED_FROMA,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
};
vtable: *const VTable,
pub fn MethodMixin(comptime T: type) type { return struct {
pub usingnamespace IUnknown.MethodMixin(T);
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ISecurityObjectTypeInfo_GetInheritSource(self: *const T, si: u32, pACL: ?*ACL, ppInheritArray: ?*?*INHERITED_FROMA) callconv(.Inline) HRESULT {
return @ptrCast(*const ISecurityObjectTypeInfo.VTable, self.vtable).GetInheritSource(@ptrCast(*const ISecurityObjectTypeInfo, self), si, pACL, ppInheritArray);
}
};}
pub usingnamespace MethodMixin(@This());
};
// TODO: this type is limited to platform 'windows6.0.6000'
const IID_ISecurityInformation3_Value = @import("../../zig.zig").Guid.initString("e2cdc9cc-31bd-4f8f-8c8b-b641af516a1a");
pub const IID_ISecurityInformation3 = &IID_ISecurityInformation3_Value;
pub const ISecurityInformation3 = extern struct {
pub const VTable = extern struct {
base: IUnknown.VTable,
GetFullResourceName: fn(
self: *const ISecurityInformation3,
ppszResourceName: ?*?PWSTR,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
OpenElevatedEditor: fn(
self: *const ISecurityInformation3,
hWnd: ?HWND,
uPage: SI_PAGE_TYPE,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
};
vtable: *const VTable,
pub fn MethodMixin(comptime T: type) type { return struct {
pub usingnamespace IUnknown.MethodMixin(T);
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ISecurityInformation3_GetFullResourceName(self: *const T, ppszResourceName: ?*?PWSTR) callconv(.Inline) HRESULT {
return @ptrCast(*const ISecurityInformation3.VTable, self.vtable).GetFullResourceName(@ptrCast(*const ISecurityInformation3, self), ppszResourceName);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ISecurityInformation3_OpenElevatedEditor(self: *const T, hWnd: ?HWND, uPage: SI_PAGE_TYPE) callconv(.Inline) HRESULT {
return @ptrCast(*const ISecurityInformation3.VTable, self.vtable).OpenElevatedEditor(@ptrCast(*const ISecurityInformation3, self), hWnd, uPage);
}
};}
pub usingnamespace MethodMixin(@This());
};
pub const SECURITY_OBJECT = extern struct {
pwszName: ?PWSTR,
pData: ?*anyopaque,
cbData: u32,
pData2: ?*anyopaque,
cbData2: u32,
Id: u32,
fWellKnown: BOOLEAN,
};
pub const EFFPERM_RESULT_LIST = extern struct {
fEvaluated: BOOLEAN,
cObjectTypeListLength: u32,
pObjectTypeList: ?*OBJECT_TYPE_LIST,
pGrantedAccessList: ?*u32,
};
// TODO: this type is limited to platform 'windows8.0'
const IID_ISecurityInformation4_Value = @import("../../zig.zig").Guid.initString("ea961070-cd14-4621-ace4-f63c03e583e4");
pub const IID_ISecurityInformation4 = &IID_ISecurityInformation4_Value;
pub const ISecurityInformation4 = extern struct {
pub const VTable = extern struct {
base: IUnknown.VTable,
GetSecondarySecurity: fn(
self: *const ISecurityInformation4,
pSecurityObjects: ?*?*SECURITY_OBJECT,
pSecurityObjectCount: ?*u32,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
};
vtable: *const VTable,
pub fn MethodMixin(comptime T: type) type { return struct {
pub usingnamespace IUnknown.MethodMixin(T);
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ISecurityInformation4_GetSecondarySecurity(self: *const T, pSecurityObjects: ?*?*SECURITY_OBJECT, pSecurityObjectCount: ?*u32) callconv(.Inline) HRESULT {
return @ptrCast(*const ISecurityInformation4.VTable, self.vtable).GetSecondarySecurity(@ptrCast(*const ISecurityInformation4, self), pSecurityObjects, pSecurityObjectCount);
}
};}
pub usingnamespace MethodMixin(@This());
};
// TODO: this type is limited to platform 'windows8.0'
const IID_IEffectivePermission2_Value = @import("../../zig.zig").Guid.initString("941fabca-dd47-4fca-90bb-b0e10255f20d");
pub const IID_IEffectivePermission2 = &IID_IEffectivePermission2_Value;
pub const IEffectivePermission2 = extern struct {
pub const VTable = extern struct {
base: IUnknown.VTable,
ComputeEffectivePermissionWithSecondarySecurity: fn(
self: *const IEffectivePermission2,
pSid: ?PSID,
pDeviceSid: ?PSID,
pszServerName: ?[*:0]const u16,
pSecurityObjects: [*]SECURITY_OBJECT,
dwSecurityObjectCount: u32,
pUserGroups: ?*TOKEN_GROUPS,
pAuthzUserGroupsOperations: ?*AUTHZ_SID_OPERATION,
pDeviceGroups: ?*TOKEN_GROUPS,
pAuthzDeviceGroupsOperations: ?*AUTHZ_SID_OPERATION,
pAuthzUserClaims: ?*AUTHZ_SECURITY_ATTRIBUTES_INFORMATION,
pAuthzUserClaimsOperations: ?*AUTHZ_SECURITY_ATTRIBUTE_OPERATION,
pAuthzDeviceClaims: ?*AUTHZ_SECURITY_ATTRIBUTES_INFORMATION,
pAuthzDeviceClaimsOperations: ?*AUTHZ_SECURITY_ATTRIBUTE_OPERATION,
pEffpermResultLists: [*]EFFPERM_RESULT_LIST,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
};
vtable: *const VTable,
pub fn MethodMixin(comptime T: type) type { return struct {
pub usingnamespace IUnknown.MethodMixin(T);
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn IEffectivePermission2_ComputeEffectivePermissionWithSecondarySecurity(self: *const T, pSid: ?PSID, pDeviceSid: ?PSID, pszServerName: ?[*:0]const u16, pSecurityObjects: [*]SECURITY_OBJECT, dwSecurityObjectCount: u32, pUserGroups: ?*TOKEN_GROUPS, pAuthzUserGroupsOperations: ?*AUTHZ_SID_OPERATION, pDeviceGroups: ?*TOKEN_GROUPS, pAuthzDeviceGroupsOperations: ?*AUTHZ_SID_OPERATION, pAuthzUserClaims: ?*AUTHZ_SECURITY_ATTRIBUTES_INFORMATION, pAuthzUserClaimsOperations: ?*AUTHZ_SECURITY_ATTRIBUTE_OPERATION, pAuthzDeviceClaims: ?*AUTHZ_SECURITY_ATTRIBUTES_INFORMATION, pAuthzDeviceClaimsOperations: ?*AUTHZ_SECURITY_ATTRIBUTE_OPERATION, pEffpermResultLists: [*]EFFPERM_RESULT_LIST) callconv(.Inline) HRESULT {
return @ptrCast(*const IEffectivePermission2.VTable, self.vtable).ComputeEffectivePermissionWithSecondarySecurity(@ptrCast(*const IEffectivePermission2, self), pSid, pDeviceSid, pszServerName, pSecurityObjects, dwSecurityObjectCount, pUserGroups, pAuthzUserGroupsOperations, pDeviceGroups, pAuthzDeviceGroupsOperations, pAuthzUserClaims, pAuthzUserClaimsOperations, pAuthzDeviceClaims, pAuthzDeviceClaimsOperations, pEffpermResultLists);
}
};}
pub usingnamespace MethodMixin(@This());
};
//--------------------------------------------------------------------------------
// Section: Functions (3)
//--------------------------------------------------------------------------------
// TODO: this type is limited to platform 'windows5.1.2600'
pub extern "ACLUI" fn CreateSecurityPage(
psi: ?*ISecurityInformation,
) callconv(@import("std").os.windows.WINAPI) ?HPROPSHEETPAGE;
// TODO: this type is limited to platform 'windows5.1.2600'
pub extern "ACLUI" fn EditSecurity(
hwndOwner: ?HWND,
psi: ?*ISecurityInformation,
) callconv(@import("std").os.windows.WINAPI) BOOL;
// TODO: this type is limited to platform 'windows6.0.6000'
pub extern "ACLUI" fn EditSecurityAdvanced(
hwndOwner: ?HWND,
psi: ?*ISecurityInformation,
uSIPage: SI_PAGE_TYPE,
) callconv(@import("std").os.windows.WINAPI) HRESULT;
//--------------------------------------------------------------------------------
// Section: Unicode Aliases (0)
//--------------------------------------------------------------------------------
const thismodule = @This();
pub usingnamespace switch (@import("../../zig.zig").unicode_mode) {
.ansi => struct {
},
.wide => struct {
},
.unspecified => if (@import("builtin").is_test) struct {
} else struct {
},
};
//--------------------------------------------------------------------------------
// Section: Imports (22)
//--------------------------------------------------------------------------------
const Guid = @import("../../zig.zig").Guid;
const ACE_FLAGS = @import("../../security.zig").ACE_FLAGS;
const ACL = @import("../../security.zig").ACL;
const AUTHZ_SECURITY_ATTRIBUTE_OPERATION = @import("../../security/authorization.zig").AUTHZ_SECURITY_ATTRIBUTE_OPERATION;
const AUTHZ_SECURITY_ATTRIBUTES_INFORMATION = @import("../../security/authorization.zig").AUTHZ_SECURITY_ATTRIBUTES_INFORMATION;
const AUTHZ_SID_OPERATION = @import("../../security/authorization.zig").AUTHZ_SID_OPERATION;
const BOOL = @import("../../foundation.zig").BOOL;
const BOOLEAN = @import("../../foundation.zig").BOOLEAN;
const HINSTANCE = @import("../../foundation.zig").HINSTANCE;
const HPROPSHEETPAGE = @import("../../ui/controls.zig").HPROPSHEETPAGE;
const HRESULT = @import("../../foundation.zig").HRESULT;
const HWND = @import("../../foundation.zig").HWND;
const IDataObject = @import("../../system/com.zig").IDataObject;
const INHERITED_FROMA = @import("../../security/authorization.zig").INHERITED_FROMA;
const IUnknown = @import("../../system/com.zig").IUnknown;
const OBJECT_SECURITY_INFORMATION = @import("../../security.zig").OBJECT_SECURITY_INFORMATION;
const OBJECT_TYPE_LIST = @import("../../security.zig").OBJECT_TYPE_LIST;
const PSID = @import("../../foundation.zig").PSID;
const PSPCB_MESSAGE = @import("../../ui/controls.zig").PSPCB_MESSAGE;
const PWSTR = @import("../../foundation.zig").PWSTR;
const SECURITY_DESCRIPTOR = @import("../../security.zig").SECURITY_DESCRIPTOR;
const TOKEN_GROUPS = @import("../../security.zig").TOKEN_GROUPS;
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/security/authorization/ui.zig |
const std = @import("std");
const utils = @import("utils.zig");
pub const Error = error {
InvalidUtf8,
IncompleteUtf8,
} || utils.Error;
/// Possibly incomplete decode state to save if we don't have the entire
/// sequence at the moment.
pub const State = struct {
byte_pos: u8 = 0,
seqlen: u8 = 0,
code_point: u32 = 0,
};
/// Low-level UTF-8 to UTF-32 converter. Returns individual code points.
pub const Utf8Iterator = struct {
input: []const u8,
pos: usize = 0,
state: State = .{},
fn next_byte(self: *Utf8Iterator, first_byte: bool) callconv(.Inline) Error!u8 {
if (self.pos >= self.input.len) {
return if (first_byte) Error.OutOfBounds else Error.IncompleteUtf8;
}
const byte = self.input[self.pos];
self.pos += 1;
return byte;
}
pub fn next(self: *Utf8Iterator) Error!u32 {
// Valid UTF-8 code point sequences take these binary forms:
//
// 00000000 00000000 0aaaaaaa = 0aaaaaaa
// 00000000 00000aaa aabbbbbb = 110aaaaa 10bbbbbb
// 00000000 aaaabbbb bbcccccc = 1110aaaa 10bbbbbb 10cccccc
// 000aaabb bbbbcccc ccdddddd = 11110aaa 10bbbbbb 10cccccc 10dddddd
if (self.state.byte_pos == 0) {
const first_byte = try self.next_byte(true);
if (first_byte & 0b10000000 == 0) {
return first_byte;
}
self.state.seqlen = @clz(u8, ~first_byte);
if (self.state.seqlen < 2 or self.state.seqlen > 4) {
return Error.InvalidUtf8;
}
self.state.code_point = first_byte &
((@as(u8, 1) << @intCast(u3, 7 - self.state.seqlen)) - 1);
self.state.byte_pos = 1;
}
while (self.state.byte_pos < self.state.seqlen) {
const byte = try self.next_byte(false);
if (byte >> 6 != 0b10) {
self.state.byte_pos = 0;
return Error.InvalidUtf8;
}
self.state.code_point <<= 6;
self.state.code_point |= (byte & 0b00111111);
self.state.byte_pos += 1;
}
self.state.byte_pos = 0;
return self.state.code_point;
}
};
/// High-level UTF-8 to UTF-32 converter. Returns strings as large as the
/// buffer allows and there is input for.
pub const Utf8ToUtf32 = struct {
input: []const u8,
buffer: []u32,
// Character to insert if there are errors. If null, then errors aren't
// allowed.
allow_errors: ?u32 = '?',
state: State = .{},
pub fn next(self: *Utf8ToUtf32) Error![]u32 {
var it = Utf8Iterator{.input = self.input, .state = self.state};
var i: usize = 0;
var leftovers: ?usize = null;
var save_state = false;
var replace_char_leftover = false;
while (true) {
const last_pos = it.pos;
if (it.next()) |c| {
if (i >= self.buffer.len) {
leftovers = last_pos;
break;
}
self.buffer[i] = c;
i += 1;
} else |e| switch (e) {
Error.OutOfBounds => {
break;
},
Error.IncompleteUtf8 => {
// Can't complete sequence. Save state so we can try to
// resume when we get more input.
save_state = true;
break;
},
Error.InvalidUtf8 => {
if (self.allow_errors) |replace_char| {
if (i >= self.buffer.len) {
replace_char_leftover = true;
break;
}
self.buffer[i] = replace_char;
i += 1;
} else {
return e;
}
},
else => {
return e;
},
}
}
if (replace_char_leftover) {
self.input = @ptrCast([*]const u8, &self.allow_errors.?)[0..1];
} else {
self.input = self.input[(if (leftovers == null) it.pos else leftovers.?)..];
}
self.state = if (save_state) it.state else .{};
return self.buffer[0..i];
}
};
test "utf8_to_utf32" {
var buffer: [128]u32 = undefined;
// Use this Python function to generate expected u32 arrays:
// def utf32_array(s):
// indent = ' '
// l = ['0x{:08x},'.format(ord(i)) for i in s]
// print('\n'.join([indent + ' '.join(l[i:i+4]) for i in range(0, len(l), 4)]))
// One Byte UTF-8 Code Units
{
const input: []const u8 = "Hello";
const expected = [_]u32 {
0x00000048, 0x00000065, 0x0000006c, 0x0000006c,
0x0000006f,
};
var utf8_to_utf32 = Utf8ToUtf32{.input = input, .buffer = buffer[0..]};
try std.testing.expectEqualSlices(u32, expected[0..], try utf8_to_utf32.next());
try std.testing.expectEqualSlices(u8, "", utf8_to_utf32.input);
}
// One-Two Byte UTF-8 Code Units
{
const input: []const u8 = "Æðelstan";
const expected = [_]u32 {
0x000000c6, 0x000000f0, 0x00000065, 0x0000006c,
0x00000073, 0x00000074, 0x00000061, 0x0000006e,
};
var utf8_to_utf32 = Utf8ToUtf32{.input = input, .buffer = buffer[0..]};
try std.testing.expectEqualSlices(u32, expected[0..], try utf8_to_utf32.next());
try std.testing.expectEqualSlices(u8, "", utf8_to_utf32.input);
}
// One-Four Byte UTF-8 Code Units
{
const input: []const u8 = "🍱 頂きます";
const expected = [_]u32 {
0x0001f371, 0x00000020, 0x00009802, 0x0000304d,
0x0000307e, 0x00003059,
};
var utf8_to_utf32 = Utf8ToUtf32{.input = input, .buffer = buffer[0..]};
try std.testing.expectEqualSlices(u32, expected[0..], try utf8_to_utf32.next());
try std.testing.expectEqualSlices(u8, "", utf8_to_utf32.input);
}
// Output is Too Small, so There Are Leftovers
{
var too_small_buffer: [3]u32 = undefined;
const input: []const u8 = "Hello";
var utf8_to_utf32 = Utf8ToUtf32{.input = input, .buffer = too_small_buffer[0..]};
const expected_output1 = [_]u32 {0x00000048, 0x00000065, 0x0000006c};
try std.testing.expectEqualSlices(u32, expected_output1[0..], try utf8_to_utf32.next());
try std.testing.expectEqualSlices(u8, input[too_small_buffer.len..], utf8_to_utf32.input);
const expected_output2 = [_]u32 {0x0000006c, 0x0000006f};
try std.testing.expectEqualSlices(u32, expected_output2[0..], try utf8_to_utf32.next());
try std.testing.expectEqualSlices(u8, "", utf8_to_utf32.input);
}
// Code point is broken up over multiple inputs.
{
const expected = [_]u32 {
0x0001f371,
};
var utf8_to_utf32 = Utf8ToUtf32{.input = "\xf0\x9f", .buffer = buffer[0..]};
try std.testing.expectEqualSlices(u32, expected[0..0], try utf8_to_utf32.next());
try std.testing.expectEqualSlices(u8, "", utf8_to_utf32.input);
utf8_to_utf32.input = "\x8d\xb1";
try std.testing.expectEqualSlices(u32, expected[0..], try utf8_to_utf32.next());
try std.testing.expectEqualSlices(u8, "", utf8_to_utf32.input);
}
// Code point is incomplete AND Buffer is too small.
{
var too_small_buffer: [2]u32 = undefined;
const expected1 = [_]u32 {0x00000031, 0x00000032};
var utf8_to_utf32 = Utf8ToUtf32{
.input = "12\xf0\x9f\x8d", .buffer = too_small_buffer[0..]};
try std.testing.expectEqualSlices(u32, expected1[0..], try utf8_to_utf32.next());
try std.testing.expectEqualSlices(u8, "", utf8_to_utf32.input);
const expected2 = [_]u32 {0x0001f371, 0x00000033};
utf8_to_utf32.input = "\xb13";
try std.testing.expectEqualSlices(u32, expected2[0..], try utf8_to_utf32.next());
try std.testing.expectEqualSlices(u8, "", utf8_to_utf32.input);
}
// Errors can be overcome by default.
{
const expected = [_]u32 {
0x00000048, 0x00000069, 0x0000003f, 0x0000003f,
0x00000042, 0x00000079, 0x00000065,
};
// 0xf8 has an large number of leading ones, implies there are more
// bytes in the sequence than are possible. It should be replaced by
// '?'.
// 0xc0 is a leading byte of a sequence like 0xf8, but the next byte
// doesn't begin with 0b10 like it should. Both bytes should be
// replaced by a single '?'.
// NOTE: If the '!' byte began with 0b10, then we would accept it as
// '!', though this would technically be invalid UTF-8 and is called an
// overlong encoding.
const input: []const u8 = "Hi\xf8\xc0!Bye";
var utf8_to_utf32 = Utf8ToUtf32{.input = input, .buffer = buffer[0..]};
try std.testing.expectEqualSlices(u32, expected[0..], try utf8_to_utf32.next());
try std.testing.expectEqualSlices(u8, "", utf8_to_utf32.input);
}
// Errors can be overcome if there is no more room in the buffer
{
var too_small_buffer: [2]u32 = undefined;
const input: []const u8 = "Hi\xf8";
const expected1 = [_]u32 {0x00000048, 0x00000069};
var utf8_to_utf32 = Utf8ToUtf32{.input = input, .buffer = too_small_buffer[0..]};
try std.testing.expectEqualSlices(u32, expected1[0..], try utf8_to_utf32.next());
try std.testing.expectEqualSlices(u8, "?", utf8_to_utf32.input);
const expected2 = [_]u32 {0x0000003f};
try std.testing.expectEqualSlices(u32, expected2[0..], try utf8_to_utf32.next());
try std.testing.expectEqualSlices(u8, "", utf8_to_utf32.input);
}
// Decode can be strict
{
var utf8_to_utf32 = Utf8ToUtf32{
.input = "Hi\xf8Bye", .buffer = buffer[0..], .allow_errors = null};
try std.testing.expectError(Error.InvalidUtf8, utf8_to_utf32.next());
utf8_to_utf32 = Utf8ToUtf32{
.input = "Hi\xc0!Bye", .buffer = buffer[0..], .allow_errors = null};
try std.testing.expectError(Error.InvalidUtf8, utf8_to_utf32.next());
}
} | libs/utils/unicode.zig |
const Atom = @This();
const std = @import("std");
const types = @import("types.zig");
const Wasm = @import("../Wasm.zig");
const Symbol = @import("Symbol.zig");
const Dwarf = @import("../Dwarf.zig");
const leb = std.leb;
const log = std.log.scoped(.link);
const mem = std.mem;
const Allocator = mem.Allocator;
/// symbol index of the symbol representing this atom
sym_index: u32,
/// Size of the atom, used to calculate section sizes in the final binary
size: u32,
/// List of relocations belonging to this atom
relocs: std.ArrayListUnmanaged(types.Relocation) = .{},
/// Contains the binary data of an atom, which can be non-relocated
code: std.ArrayListUnmanaged(u8) = .{},
/// For code this is 1, for data this is set to the highest value of all segments
alignment: u32,
/// Offset into the section where the atom lives, this already accounts
/// for alignment.
offset: u32,
/// Represents the index of the file this atom was generated from.
/// This is 'null' when the atom was generated by a Decl from Zig code.
file: ?u16,
/// Next atom in relation to this atom.
/// When null, this atom is the last atom
next: ?*Atom,
/// Previous atom in relation to this atom.
/// is null when this atom is the first in its order
prev: ?*Atom,
/// Contains atoms local to a decl, all managed by this `Atom`.
/// When the parent atom is being freed, it will also do so for all local atoms.
locals: std.ArrayListUnmanaged(Atom) = .{},
/// Represents the debug Atom that holds all debug information of this Atom.
dbg_info_atom: Dwarf.Atom,
/// Represents a default empty wasm `Atom`
pub const empty: Atom = .{
.alignment = 0,
.file = null,
.next = null,
.offset = 0,
.prev = null,
.size = 0,
.sym_index = 0,
.dbg_info_atom = undefined,
};
/// Frees all resources owned by this `Atom`.
pub fn deinit(self: *Atom, gpa: Allocator) void {
self.relocs.deinit(gpa);
self.code.deinit(gpa);
for (self.locals.items) |*local| {
local.deinit(gpa);
}
self.locals.deinit(gpa);
}
/// Sets the length of relocations and code to '0',
/// effectively resetting them and allowing them to be re-populated.
pub fn clear(self: *Atom) void {
self.relocs.clearRetainingCapacity();
self.code.clearRetainingCapacity();
}
pub fn format(self: Atom, comptime fmt: []const u8, options: std.fmt.FormatOptions, writer: anytype) !void {
_ = fmt;
_ = options;
writer.print("Atom{{ .sym_index = {d}, .alignment = {d}, .size = {d}, .offset = 0x{x:0>8} }}", .{
self.sym_index,
self.alignment,
self.size,
self.offset,
});
}
/// Returns the first `Atom` from a given atom
pub fn getFirst(self: *Atom) *Atom {
var tmp = self;
while (tmp.prev) |prev| tmp = prev;
return tmp;
}
/// Returns the location of the symbol that represents this `Atom`
pub fn symbolLoc(self: Atom) Wasm.SymbolLoc {
return .{ .file = self.file, .index = self.sym_index };
}
/// Resolves the relocations within the atom, writing the new value
/// at the calculated offset.
pub fn resolveRelocs(self: *Atom, wasm_bin: *const Wasm) !void {
if (self.relocs.items.len == 0) return;
const symbol_name = self.symbolLoc().getName(wasm_bin);
log.debug("Resolving relocs in atom '{s}' count({d})", .{
symbol_name,
self.relocs.items.len,
});
for (self.relocs.items) |reloc| {
const value = try self.relocationValue(reloc, wasm_bin);
log.debug("Relocating '{s}' referenced in '{s}' offset=0x{x:0>8} value={d}", .{
(Wasm.SymbolLoc{ .file = self.file, .index = reloc.index }).getName(wasm_bin),
symbol_name,
reloc.offset,
value,
});
switch (reloc.relocation_type) {
.R_WASM_TABLE_INDEX_I32,
.R_WASM_FUNCTION_OFFSET_I32,
.R_WASM_GLOBAL_INDEX_I32,
.R_WASM_MEMORY_ADDR_I32,
.R_WASM_SECTION_OFFSET_I32,
=> std.mem.writeIntLittle(u32, self.code.items[reloc.offset..][0..4], @intCast(u32, value)),
.R_WASM_TABLE_INDEX_I64,
.R_WASM_MEMORY_ADDR_I64,
=> std.mem.writeIntLittle(u64, self.code.items[reloc.offset..][0..8], value),
.R_WASM_GLOBAL_INDEX_LEB,
.R_WASM_EVENT_INDEX_LEB,
.R_WASM_FUNCTION_INDEX_LEB,
.R_WASM_MEMORY_ADDR_LEB,
.R_WASM_MEMORY_ADDR_SLEB,
.R_WASM_TABLE_INDEX_SLEB,
.R_WASM_TABLE_NUMBER_LEB,
.R_WASM_TYPE_INDEX_LEB,
=> leb.writeUnsignedFixed(5, self.code.items[reloc.offset..][0..5], @intCast(u32, value)),
.R_WASM_MEMORY_ADDR_LEB64,
.R_WASM_MEMORY_ADDR_SLEB64,
.R_WASM_TABLE_INDEX_SLEB64,
=> leb.writeUnsignedFixed(10, self.code.items[reloc.offset..][0..10], value),
}
}
}
/// From a given `relocation` will return the new value to be written.
/// All values will be represented as a `u64` as all values can fit within it.
/// The final value must be casted to the correct size.
fn relocationValue(self: Atom, relocation: types.Relocation, wasm_bin: *const Wasm) !u64 {
const target_loc: Wasm.SymbolLoc = .{ .file = self.file, .index = relocation.index };
const symbol = target_loc.getSymbol(wasm_bin).*;
switch (relocation.relocation_type) {
.R_WASM_FUNCTION_INDEX_LEB => return symbol.index,
.R_WASM_TABLE_NUMBER_LEB => return symbol.index,
.R_WASM_TABLE_INDEX_I32,
.R_WASM_TABLE_INDEX_I64,
.R_WASM_TABLE_INDEX_SLEB,
.R_WASM_TABLE_INDEX_SLEB64,
=> return wasm_bin.function_table.get(target_loc) orelse 0,
.R_WASM_TYPE_INDEX_LEB => return wasm_bin.functions.items[symbol.index].type_index,
.R_WASM_GLOBAL_INDEX_I32,
.R_WASM_GLOBAL_INDEX_LEB,
=> return symbol.index,
.R_WASM_MEMORY_ADDR_I32,
.R_WASM_MEMORY_ADDR_I64,
.R_WASM_MEMORY_ADDR_LEB,
.R_WASM_MEMORY_ADDR_LEB64,
.R_WASM_MEMORY_ADDR_SLEB,
.R_WASM_MEMORY_ADDR_SLEB64,
=> {
if (symbol.isUndefined() and symbol.isWeak()) {
return 0;
}
std.debug.assert(symbol.tag == .data);
const merge_segment = wasm_bin.base.options.output_mode != .Obj;
const segment_name = wasm_bin.segment_info.items[symbol.index].outputName(merge_segment);
const atom_index = wasm_bin.data_segments.get(segment_name).?;
const target_atom = wasm_bin.symbol_atom.get(target_loc).?;
const segment = wasm_bin.segments.items[atom_index];
return target_atom.offset + segment.offset + (relocation.addend orelse 0);
},
.R_WASM_EVENT_INDEX_LEB => return symbol.index,
.R_WASM_SECTION_OFFSET_I32,
.R_WASM_FUNCTION_OFFSET_I32,
=> return relocation.offset,
}
} | src/link/Wasm/Atom.zig |
usingnamespace @import("root").preamble;
const log = lib.output.log.scoped(.{
.prefix = "E1000",
.filter = .info,
}).write;
const num_rx_desc = 32;
const num_tx_desc = 8;
const rx_block_size = 2048;
const Register = extern enum(u16) {
ctrl = 0x0000,
status = 0x0008,
eeprom = 0x0014,
ctrl_ex = 0x0018,
imask = 0x00D0,
rctrl = 0x0100,
tctrl = 0x0400,
tipg = 0x0410,
rx_descs_low = 0x2800,
rx_descs_high = 0x2804,
rx_descs_len = 0x2808,
rx_descs_head = 0x2810,
rx_descs_tail = 0x2818,
rdtr = 0x2820,
radv = 0x282C,
rsrpd = 0x2C00,
tx_descs_low = 0x3800,
tx_descs_high = 0x3804,
tx_descs_len = 0x3808,
tx_descs_head = 0x3810,
tx_descs_tail = 0x3818,
rxdctl = 0x3828,
mac0 = 0x5400,
mac1 = 0x5401,
mac2 = 0x5402,
mac3 = 0x5403,
mac4 = 0x5404,
mac5 = 0x5405,
};
const RXDesc = packed struct {
addr: u64,
length: u16,
checksum: u16,
status: u8,
errors: u8,
special: u16,
};
const TXDesc = packed struct {
addr: u64,
length: u16,
cso: u8,
cmd: u8,
status: u8,
css: u8,
special: u16,
};
const Controller = struct {
base_addr: u64,
advertises_eeprom: bool = false,
mac: [6]u8 = undefined,
rx_descs: *[num_rx_desc]RXDesc = undefined,
tx_descs: *[num_tx_desc]TXDesc = undefined,
fn read(self: *@This(), comptime t: type, reg: Register) t {
return os.platform.phys_ptr(*t).from_int(self.base_addr + @intCast(u64, @enumToInt(reg))).get_uncached().*;
}
fn write(self: *@This(), comptime t: type, reg: Register, value: u32) void {
os.platform.phys_ptr(*t).from_int(self.base_addr + @intCast(u64, @enumToInt(reg))).get_uncached().* = value;
}
fn detectEeprom(self: *@This()) void {
self.write(u32, .eeprom, 0x1);
var i: usize = 0;
while (i < 1000) : (i += 1) {
const val = self.read(u32, .eeprom);
if ((val & 0x10) != 0) {
self.advertises_eeprom = true;
return;
}
}
}
fn readEeprom(self: *@This(), addr: u8) u16 {
const mask: u32 = if (self.advertises_eeprom)
(1 << 4)
else
(1 << 1);
const addr_shift: u5 = if (self.advertises_eeprom)
8
else
2;
self.write(u32, .eeprom, 1 | (@as(u32, addr) << addr_shift));
while (true) {
const val = self.read(u32, .eeprom);
if ((val & mask) == 0) continue;
return @truncate(u16, val >> 16);
}
}
fn readMAC(self: *@This()) void {
if (self.advertises_eeprom) {
const v0 = self.readEeprom(0);
const v1 = self.readEeprom(1);
const v2 = self.readEeprom(2);
self.mac = [_]u8{
@truncate(u8, v0),
@truncate(u8, v0 >> 8),
@truncate(u8, v1),
@truncate(u8, v1 >> 8),
@truncate(u8, v2),
@truncate(u8, v2 >> 8),
};
} else {
self.mac = [_]u8{
self.read(u8, .mac0),
self.read(u8, .mac1),
self.read(u8, .mac2),
self.read(u8, .mac3),
self.read(u8, .mac4),
self.read(u8, .mac5),
};
}
}
fn setupRX(self: *@This()) !void {
const desc_bytes = @sizeOf(RXDesc) * num_rx_desc;
const base_phys = try os.memory.pmm.allocPhys(desc_bytes);
self.rx_descs = os.platform.phys_ptr([*]RXDesc).from_int(base_phys).get_uncached()[0..num_rx_desc];
for (self.rx_descs) |*desc| {
desc.addr = try os.memory.pmm.allocPhys(rx_block_size + 16);
desc.status = 0;
}
log(.debug, "RX list prepared", .{});
self.write(u32, .rx_descs_low, @truncate(u32, base_phys));
self.write(u32, .rx_descs_high, @truncate(u32, base_phys >> 32));
self.write(u32, .rx_descs_len, desc_bytes);
self.write(u32, .rx_descs_head, 0);
self.write(u32, .rx_descs_tail, num_rx_desc - 1);
// zig fmt: off
self.write(u32, .rctrl, 0
| (1 << 1) // EN, reciever ENable
| (1 << 2) // SBP, Store Bad Packets
| (1 << 3) // UPE, Unicast Promiscuous Enabled
| (1 << 4) // MPE, Multicast Promiscuous Enabled
| (0 << 6) // LBM_NONE, No loopback
| (0 << 8) // RDMTS_HALF, free buffer threshold is HALF of RDLEN
| (1 << 15) // BAM, Broadcast Accept Mode
| (1 << 26) // SECRC, Strip Ethernet CRC
| switch (rx_block_size) { // BSIZE
256 => (3 << 16),
512 => (2 << 16),
1024 => (1 << 16),
2048 => (0 << 16),
4096 => (3 << 16) | (1 << 25),
8192 => (2 << 16) | (1 << 25),
16384 => (1 << 16) | (1 << 25),
else => @compileError("Bad rx_block_size"),
}
);
// zig fmt: on
log(.debug, "RX set up", .{});
}
fn setupTX(self: *@This()) !void {
const desc_bytes = @sizeOf(TXDesc) * num_tx_desc;
const base_phys = try os.memory.pmm.allocPhys(desc_bytes);
self.tx_descs = os.platform.phys_ptr([*]TXDesc).from_int(base_phys).get_uncached()[0..num_tx_desc];
for (self.tx_descs) |*desc| {
desc.addr = 0;
desc.cmd = 0;
desc.status = (1 << 0); // TSTA_DD
}
log(.debug, "TX list prepared", .{});
self.write(u32, .tx_descs_low, @truncate(u32, base_phys));
self.write(u32, .tx_descs_high, @truncate(u32, base_phys >> 32));
self.write(u32, .tx_descs_len, desc_bytes);
self.write(u32, .tx_descs_head, 0);
self.write(u32, .tx_descs_tail, 0);
// zig fmt: off
self.write(u32, .tctrl, 0
| (1 << 1) // EN, transmit ENable
| (1 << 3) // PSP, Pad Short Packages
| (15 << 4) // CT, Collosition Threshold
| (64 << 12) // COLD, COLlision Distance
| (1 << 24) // RTLC, Re-Transmit on Late Collision
);
// zig fmt: on
log(.debug, "TX set up", .{});
}
fn init(self: *@This(), dev: os.platform.pci.Addr) !void {
self.* = .{
.base_addr = dev.barinfo(0).phy,
};
self.detectEeprom();
self.readMAC();
try self.setupRX();
try self.setupTX();
}
pub fn format(
self: *const @This(),
fmt: anytype,
) void {
fmt(
"Base MMIO address: 0x{X}, mac: {0X}:{0X}:{0X}:{0X}:{0X}:{0X}, eeprom: {b}",
.{
self.base_addr,
self.mac[0],
self.mac[1],
self.mac[2],
self.mac[3],
self.mac[4],
self.mac[5],
self.advertises_eeprom,
},
);
}
};
fn controllerTask(dev: os.platform.pci.Addr) void {
var c: Controller = undefined;
c.init(dev) catch |err| {
log(.crit, "Error while initializing: {e}", .{err});
if (@errorReturnTrace()) |trace| {
os.kernel.debug.dumpStackTrace(trace);
} else {
log(.crit, "No error trace.", .{});
}
};
log(.info, "Inited controller: {}", .{c});
}
pub fn registerController(dev: os.platform.pci.Addr) void {
if (comptime (!config.drivers.net.e1000.enable))
return;
dev.command().write(dev.command().read() | 0x6);
os.vital(os.thread.scheduler.spawnTask("E1000 controller task", controllerTask, .{dev}), "Spawning e1000 controller task");
} | subprojects/flork/src/drivers/net/e1000.zig |
const std = @import("std");
const expect = @import("std").testing.expect;
const Lexer = @import("lexer/lexer.zig").Lexer;
const utils = @import("./utils.zig");
pub const Errors = error{
UNKNOWN_TOKEN,
UNIMPLEMENTED,
END_OF_FILE,
NOT_CLOSED_STR,
NOT_CLOSED_CHAR,
EXP_STR_AFTER_IMPORT,
EXP_STR_AFTER_INCLUDE,
EXP_SEMICOLON,
EXP_ID_AFTER_LET,
EXP_EQUAL_AFTER_ID,
EXP_VALUE_AFTER_EQL,
NOT_ALLOWED_AT_GLOBAL,
NO_MUT_GL_VARS,
REQUIRE_VALUE,
EXIT_FAILURE,
};
pub fn isCustomError(err: Errors) bool {
switch (err) {
Errors.UNKNOWN_TOKEN,
Errors.UNIMPLEMENTED,
Errors.END_OF_FILE,
Errors.NOT_CLOSED_STR,
Errors.NOT_CLOSED_CHAR,
Errors.EXP_STR_AFTER_IMPORT,
Errors.EXP_STR_AFTER_INCLUDE,
Errors.EXP_SEMICOLON,
Errors.EXP_ID_AFTER_LET,
Errors.EXP_EQUAL_AFTER_ID,
Errors.EXP_VALUE_AFTER_EQL,
Errors.NOT_ALLOWED_AT_GLOBAL,
Errors.NO_MUT_GL_VARS,
Errors.REQUIRE_VALUE,
Errors.EXIT_FAILURE,
=> return true,
else => return false,
}
return false;
}
pub fn locationNeeded(err: Errors) bool {
switch (err) {
Errors.END_OF_FILE => return false,
else => return true,
}
}
pub fn describe(err: Errors) []const u8 {
switch (err) {
Errors.UNKNOWN_TOKEN => return "Unknown Token",
Errors.END_OF_FILE => return "Fily empty",
Errors.UNIMPLEMENTED => return "TODO: Error string",
Errors.NOT_CLOSED_STR => return "String not closed",
Errors.NOT_CLOSED_CHAR => return "Char not closed",
Errors.EXP_STR_AFTER_IMPORT => return "String expected after keyword `import`",
Errors.EXP_STR_AFTER_INCLUDE => return "String expected after keyword `include`",
Errors.EXP_SEMICOLON => return "Semicolon expected",
Errors.EXP_ID_AFTER_LET => return "Identifier expected after keyword `let`",
Errors.EXP_EQUAL_AFTER_ID => return "Equal expected after identifier",
Errors.EXP_VALUE_AFTER_EQL => return "Variable requires a value",
Errors.NO_MUT_GL_VARS => return "Global variables cannot be mutable",
Errors.NOT_ALLOWED_AT_GLOBAL => return "Found global token at its forbidden scope",
else => return "TODO err msg",
}
}
pub fn advice(err: Errors) []const u8 {
switch (err) {
Errors.UNKNOWN_TOKEN => return "Remove the unknown token",
Errors.END_OF_FILE => return "Reached end of file",
Errors.UNIMPLEMENTED => return "Error string unimplemented",
Errors.NOT_CLOSED_STR => return "Close string with double quotes",
Errors.NOT_CLOSED_CHAR => return "Close char with single quote",
Errors.EXP_STR_AFTER_IMPORT => return "Add a string after keyword `import`",
Errors.EXP_STR_AFTER_INCLUDE => return "Add a string after keyword `include`",
Errors.EXP_SEMICOLON => return "Add a semicolon",
Errors.EXP_ID_AFTER_LET => return "Add an Identifier after keyword `let`",
Errors.EXP_EQUAL_AFTER_ID => return "Add an equal symbol `=` after identifier",
Errors.EXP_VALUE_AFTER_EQL => return "Add a value to variable",
Errors.NO_MUT_GL_VARS => return "Remove the mutable `mut` keyword",
Errors.NOT_ALLOWED_AT_GLOBAL => return "Remove this token",
else => return "Error message unimplemented",
}
}
// compiler crashes logbegin
pub fn errorLog(error_describe: []const u8, error_advice: []const u8, err_num: usize, location: bool, lexer: *Lexer) !void {
// std.debug.print("col: {d}, line: {d}\n{c}\n", .{ lexer.col, lexer.length, lexer.file.code[lexer.index] });
try std.io.getStdErr().writer().print("{s}{s}error[{d:0>4}]: {s}{s}{s}\n", .{
BOLD,
LRED,
err_num,
LCYAN,
error_describe,
RESET,
});
// std.debug.print("{d}, {any}, {d}\n", .{lexer.file.code.len, lexer.lines.items, lexer.line - 1});
try std.io.getStdErr().writer().print("{s}{s}--> {s}:{d}:{d}{s}\n", .{
BOLD,
LGREEN,
lexer.file.name,
lexer.line,
lexer.col,
RESET,
});
if (location) {
var i: usize = 0;
while (lexer.file.code[lexer.index + i] != '\n') {
i += 1;
}
// std.debug.print("index: {d}\n", .{i});
var src: []const u8 = undefined;
if (lexer.line == 1) {
src = lexer.file.code[0..(lexer.index + i)];
} else {
const lines = lexer.lines.items;
src = lexer.file.code[lines[lexer.line - 2]..(lexer.index + i)];
}
// std.debug.print("{s}\n", .{src});
// const distance = try std.math.sub(usize, lexer.col, lexer.length);
// std.debug.print("{d}\n", .{distance});
try std.io.getStdErr().writer().print("{d} {s}┃{s} {s}\n", .{
lexer.line,
LYELLOW,
RESET,
src,
});
try std.io.getStdErr().writer().print("{s} {s}┃{s}{s}{s}{s} {s}{s}\n", .{
(" " ** 2048)[0..utils.getDigits(@intCast(u32, lexer.line))],
LYELLOW,
(" " ** 2048)[0..lexer.col],
LRED,
("^" ** 2048)[0..lexer.length],
LYELLOW,
error_advice,
RESET,
});
}
}
pub fn logInFile(file: std.fs.File, comptime fmt: []const u8, args: anytype) void {
std.fmt.format(file.writer(), fmt, args) catch |err| {
logErr(@errorName(err));
};
}
pub fn printLog(error_type: Errors, lexer: *Lexer) void {
errorLog(
describe(error_type),
advice(error_type),
@errorToInt(error_type),
locationNeeded(error_type),
lexer,
) catch |err| {
std.debug.print("print Log err: {s}\n", .{@errorName(err)});
// logErr(@errorName(err));
};
}
pub fn logErr(err: []const u8) void {
std.log.err("{s}", .{err});
}
// colors
const RED = "\x1b[31m";
const GREEN = "\x1b[32m";
const YELLOW = "\x1b[33m";
const BLUE = "\x1b[34m";
const PINK = "\x1b[35m";
const CYAN = "\x1b[36m";
const BLACK = "\x1b[30m";
const WHITE = "\x1b[37m";
// text visuals
const BOLD = "\x1b[1m";
const FAINT = "\x1b[2m";
// lighter colors
const DEFAULT = "\x1b[39m";
const LGRAY = "\x1b[90m";
const LRED = "\x1b[91m";
const LGREEN = "\x1b[92m";
const LYELLOW = "\x1b[93m";
const LBLUE = "\x1b[94m";
const LMAGENTA = "\x1b[95m";
const LCYAN = "\x1b[96m";
const LWHITE = "\x1b[97m";
// reset colors
const RESET = "\x1b[0m"; | src/log.zig |
const std = @import("std");
pub fn getAllPkg(comptime T: type) CalculatePkg(T) {
const info: std.builtin.TypeInfo = @typeInfo(T);
const declarations: []const std.builtin.TypeInfo.Declaration = info.Struct.decls;
var pkgs: CalculatePkg(T) = undefined;
var index: usize = 0;
inline for (declarations) |d| {
if (@TypeOf(@field(T, d.name)) == std.build.Pkg) {
pkgs[index] = @field(T, d.name);
index += 1;
}
}
return pkgs;
}
fn CalculatePkg(comptime T: type) type {
const info: std.builtin.TypeInfo = @typeInfo(T);
const declarations: []const std.builtin.TypeInfo.Declaration = info.Struct.decls;
var count: usize = 0;
for (declarations) |d| {
if (@TypeOf(@field(T, d.name)) == std.build.Pkg) {
count += 1;
}
}
return [count]std.build.Pkg;
}
pub fn build(b: *std.build.Builder) void {
const pkgs = struct {
const bottom = std.build.Pkg{
.name = "bottom",
.source = .{ .path = "bottom.zig" },
};
const args = std.build.Pkg{
.name = "zig-args",
.source = .{ .path = "vendors/zig-args/args.zig" },
};
};
const packages = getAllPkg(pkgs);
// Standard target options allows the person running `zig build` to choose
// what target to build for. Here we do not override the defaults, which
// means any target is allowed, and the default is native. Other options
// for restricting supported target set are available.
const use_c: bool = b.option(bool, "use_c", "Add C as the default allocator, much faster but uses libc (defaults to false)") orelse false;
var options = b.addOptions();
options.addOption(bool, "use_c", use_c);
options.addOption([]const u8, "version", "v0.0.3");
const target = b.standardTargetOptions(.{});
// Standard release options allow the person running `zig build` to select
// between Debug, ReleaseSafe, ReleaseFast, and ReleaseSmall.
const mode = b.standardReleaseOptions();
const install_lib_step = b.step("install-lib", "Install library only");
const exe = b.addExecutable("bottom-zig", "src/main.zig");
for (packages) |p| {
exe.addPackage(p);
}
exe.setTarget(target);
exe.setBuildMode(mode);
exe.addOptions("build_options", options);
if (use_c) {
exe.linkLibC();
}
exe.install();
const run_cmd = exe.run();
run_cmd.step.dependOn(b.getInstallStep());
if (b.args) |args| {
run_cmd.addArgs(args);
}
const run_step = b.step("run", "Run the Bottom Encoder/Decoder");
run_step.dependOn(&run_cmd.step);
var exe_tests = b.addTest("src/main.zig");
exe_tests.setBuildMode(mode);
exe_tests.addPackage(pkgs.bottom);
const test_step = b.step("test-exe", "Run unit tests for the CLI App");
test_step.dependOn(&exe_tests.step);
const lib = b.addStaticLibrary("bottom-zig", "src/clib.zig");
lib.setTarget(target);
lib.setBuildMode(mode);
lib.addOptions("build_options", options);
if (use_c) {
lib.linkLibC();
}
lib.install(); // Only works in install
const slib = b.addSharedLibrary("bottom-zig", "src/clib.zig", .unversioned);
slib.setTarget(target);
slib.setBuildMode(mode);
slib.addOptions("build_options", options);
if (use_c) {
slib.linkLibC();
}
slib.install(); // Only works in install
b.installDirectory(std.build.InstallDirectoryOptions {
.source_dir = "include",
.install_dir = .header,
.install_subdir = "bottom",
});
install_lib_step.dependOn(&slib.step);
const install_only_shared = b.addInstallArtifact(slib);
install_lib_step.dependOn(&install_only_shared.step);
install_lib_step.dependOn(&lib.step);
const install_only = b.addInstallArtifact(lib);
install_lib_step.dependOn(&install_only.step);
const wasm_shared = b.addSharedLibrary("bottom-zig", "src/wasm-example.zig", .unversioned);
wasm_shared.setTarget(std.zig.CrossTarget{ .abi = .musl, .os_tag = .freestanding, .cpu_arch = .wasm32 });
wasm_shared.setBuildMode(.ReleaseSmall);
//wasm_shared.strip = true;
wasm_shared.override_dest_dir = std.build.InstallDir{ .custom = "../public/wasm/" };
const wasm_shared_step = b.step("wasm-shared", "Build the WASM example");
wasm_shared_step.dependOn(&wasm_shared.step);
const install_to_public = b.addInstallArtifact(wasm_shared);
wasm_shared_step.dependOn(&install_to_public.step);
const exe2 = b.addExecutable("benchmark", "src/benchmark.zig");
exe2.addPackage(pkgs.bottom);
exe2.setTarget(target);
exe2.setBuildMode(.ReleaseFast);
exe2.install();
const clib_exe = b.addExecutable("clib", null);
clib_exe.linkLibC();
clib_exe.linkLibrary(lib);
clib_exe.addIncludePath("zig-out/include");
clib_exe.addCSourceFile("src/example.c", &.{});
clib_exe.setTarget(target);
clib_exe.setBuildMode(mode);
clib_exe.install();
clib_exe.step.dependOn(&lib.step);
const benchmark_step = b.step("benchmark", "Run benchmarks");
benchmark_step.dependOn(&exe2.step);
const run_cmd2 = exe2.run();
run_cmd2.step.dependOn(b.getInstallStep());
if (b.args) |args| {
run_cmd2.addArgs(args);
}
const run_step2 = b.step("run-benchmark", "Run the Bottom Encoder/Decoder benchmark");
run_step2.dependOn(&run_cmd2.step);
const test_lib = b.addTest("bottom.zig");
test_lib.setTarget(target);
test_lib.setBuildMode(mode);
const test_lib_step = b.step("test-lib", "Run unit tests for the Library");
test_lib_step.dependOn(&test_lib.step);
} | build.zig |
const c = @cImport({
@cInclude("X11/Xlib.h");
@cInclude("GL/glx.h");
});
const std = @import("std");
pub const Screen = c.Screen;
pub const _XPrivDisplay = c._XPrivDisplay;
pub const XSetWindowAttributes = c.XSetWindowAttributes;
pub const XWindowAttributes = c.XWindowAttributes;
pub const Window = c.Window;
pub const Display = c.Display;
pub const XEvent = c.XEvent;
pub const XKeyEvent = c.XKeyEvent;
pub const Colormap = c.Colormap;
pub const Visual = c.Visual;
pub const KeySym = c.KeySym;
pub const CWBackPixmap = @as(c_long, 1) << 0;
pub const CWBackPixel = @as(c_long, 1) << 1;
pub const CWBorderPixmap = @as(c_long, 1) << 2;
pub const CWBorderPixel = @as(c_long, 1) << 3;
pub const CWBitGravity = @as(c_long, 1) << 4;
pub const CWWinGravity = @as(c_long, 1) << 5;
pub const CWBackingStore = @as(c_long, 1) << 6;
pub const CWBackingPlanes = @as(c_long, 1) << 7;
pub const CWBackingPixel = @as(c_long, 1) << 8;
pub const CWOverrideRedirect = @as(c_long, 1) << 9;
pub const CWSaveUnder = @as(c_long, 1) << 10;
pub const CWEventMask = @as(c_long, 1) << 11;
pub const CWDontPropagate = @as(c_long, 1) << 12;
pub const CWColormap = @as(c_long, 1) << 13;
pub const CWCursor = @as(c_long, 1) << 14;
pub const KeyPressMask = @as(c_long, 1) << 0;
pub const KeyReleaseMask = @as(c_long, 1) << 1;
pub const ButtonPressMask = @as(c_long, 1) << 2;
pub const ButtonReleaseMask = @as(c_long, 1) << 3;
pub const EnterWindowMask = @as(c_long, 1) << 4;
pub const LeaveWindowMask = @as(c_long, 1) << 5;
pub const PointerMotionMask = @as(c_long, 1) << 6;
pub const PointerMotionHintMask = @as(c_long, 1) << 7;
pub const Button1MotionMask = @as(c_long, 1) << 8;
pub const Button2MotionMask = @as(c_long, 1) << 9;
pub const Button3MotionMask = @as(c_long, 1) << 10;
pub const Button4MotionMask = @as(c_long, 1) << 11;
pub const Button5MotionMask = @as(c_long, 1) << 12;
pub const ButtonMotionMask = @as(c_long, 1) << 13;
pub const KeymapStateMask = @as(c_long, 1) << 14;
pub const ExposureMask = @as(c_long, 1) << 15;
pub const VisibilityChangeMask = @as(c_long, 1) << 16;
pub const StructureNotifyMask = @as(c_long, 1) << 17;
pub const ResizeRedirectMask = @as(c_long, 1) << 18;
pub const SubstructureNotifyMask = @as(c_long, 1) << 19;
pub const SubstructureRedirectMask = @as(c_long, 1) << 20;
pub const FocusChangeMask = @as(c_long, 1) << 21;
pub const PropertyChangeMask = @as(c_long, 1) << 22;
pub const ColormapChangeMask = @as(c_long, 1) << 23;
pub const OwnerGrabButtonMask = @as(c_long, 1) << 24;
pub const MotionNotify = c.MotionNotify;
pub const Expose = c.Expose;
pub const KeyPress = c.KeyPress;
pub const KeyRelease = c.KeyRelease;
pub const None = c.None;
pub const CopyFromParent = c.CopyFromParent;
pub const AllocNone = c.AllocNone;
pub const NotUseful = c.NotUseful;
pub const WhenMapped = c.WhenMapped;
pub const Always = c.Always;
pub const ForgetGravity = c.ForgetGravity;
pub const NorthWestGravity = c.NorthWestGravity;
pub const InputOutput = c.InputOutput;
// GLX
pub const GLint = c.GLint;
pub const GLXContext = c.GLXContext;
pub const GLXDrawable = c.GLXDrawable;
pub const XVisualInfo = c.XVisualInfo;
pub const GL_TRUE = c.GL_TRUE;
pub const GLX_RGBA = c.GLX_RGBA;
pub const GLX_DEPTH_SIZE = c.GLX_DEPTH_SIZE;
pub const GLX_DOUBLEBUFFER = c.GLX_DOUBLEBUFFER;
pub extern fn XOpenDisplay([*c]const u8) ?*Display;
pub extern fn XCreateSimpleWindow(?*Display, Window, c_int, c_int, c_uint, c_uint, c_uint, c_ulong, c_ulong) Window;
pub extern fn XMapWindow(?*Display, Window) c_int;
pub extern fn XMoveWindow(?*Display, Window, c_int, c_int) c_int;
pub extern fn XFlush(?*Display) c_int;
pub extern fn XInitThreads() c_int;
pub extern fn XCreateColormap(?*Display, Window, [*c]Visual, c_int) Colormap;
pub extern fn XCreateWindow(?*Display, Window, c_int, c_int, c_uint, c_uint, c_uint, c_int, c_uint, [*c]Visual, c_ulong, [*c]XSetWindowAttributes) Window;
pub extern fn XStoreName(?*Display, Window, [*c]const u8) c_int;
pub extern fn XGetWindowAttributes(?*Display, Window, [*c]XWindowAttributes) c_int;
pub extern fn XNextEvent(?*Display, [*c]XEvent) c_int;
pub extern fn XPending(?*Display) c_int;
pub extern fn XDestroyWindow(?*Display, Window) c_int;
pub extern fn XLookupKeysym(?*XKeyEvent, c_int) KeySym;
pub extern fn XKeysymToString(KeySym) [*:0]const u8;
pub extern fn glXChooseVisual(dpy: ?*Display, screen: c_int, attribList: [*c]c_int) [*c]XVisualInfo;
pub extern fn glXCreateContext(dpy: ?*Display, vis: [*c]XVisualInfo, shareList: GLXContext, direct: c_int) GLXContext;
pub extern fn glXMakeCurrent(dpy: ?*Display, drawable: GLXDrawable, ctx: GLXContext) c_int;
pub extern fn glXSwapBuffers(dpy: ?*Display, drawable: GLXDrawable) void;
pub inline fn ScreenOfDisplay(dpy: anytype, scr: c_int) [*c]Screen {
return &(std.meta.cast(_XPrivDisplay, dpy)).*.screens[@intCast(usize, scr)];
}
pub inline fn DefaultRootWindow(dpy: anytype) Window {
return ScreenOfDisplay(dpy, DefaultScreen(dpy)).*.root;
}
pub inline fn WhitePixel(dpy: anytype, scr: anytype) c_ulong {
return ScreenOfDisplay(dpy, scr).*.white_pixel;
}
pub inline fn BlackPixel(dpy: anytype, scr: anytype) c_ulong {
return ScreenOfDisplay(dpy, scr).*.black_pixel;
}
pub inline fn DefaultScreen(dpy: anytype) c_int {
return (std.meta.cast(_XPrivDisplay, dpy)).*.default_screen;
} | didot-x11/c.zig |
const std = @import("std");
const raiseException = @import("cpu.zig").raiseException;
/// COP0 register aliases
pub const COP0Reg = enum(u32) {
Index = 0,
Random = 1,
EntryLo0 = 2,
EntryLo1 = 3,
Context = 4,
PageMask = 5,
Wired = 6,
R7 = 7,
BadVAddr = 8,
Count = 9,
EntryHi = 10,
Compare = 11,
Status = 12,
Cause = 13,
EPC = 14,
PRId = 15,
Config = 16,
LLAddr = 17,
WatchLo = 18,
WatchHi = 19,
XContext = 20,
R21 = 21,
R22 = 22,
R23 = 23,
R24 = 24,
R25 = 25,
ParityError = 26,
CacheError = 27,
TagLo = 28,
TagHi = 29,
ErrorEPC = 30,
R31 = 31,
};
pub const ExceptionCode = enum(u5) {
Interrupt = 0,
TLBModification = 1,
TLBMissLoad = 2,
TLBMissStore = 3,
AddressErrorLoad = 4,
AddressErrorStore = 5,
InstructionBusError = 6,
DataBusError = 7,
SystemCall = 8,
Breakpoint = 9,
ReservedInstruction = 10,
CoprocessorUnusable = 11,
Overflow = 12,
Trap = 13,
FloatingPointException = 15,
Watch = 23,
};
const Cause = packed struct {
_pad0 : u2 = 0,
excCode: u5 = 0,
_pad1 : u1 = 0,
ip : u8 = 0,
_pad2 : u12 = 0,
ce : u2 = 0,
_pad3 : u1 = 0,
bd : bool = false,
};
const Index = packed struct {
index: u5 = 0,
_pad0: u26 = 0,
p : bool = false,
};
const Status = packed struct {
ie : bool = false,
exl: bool = false,
erl: bool = false,
ksu: u2 = 0,
ux : bool = false,
sx : bool = false,
kx : bool = false,
im : u8 = 0,
ds : u9 = 0,
re : bool = false,
fr : bool = false,
rp : bool = false,
cu : u4 = 0,
};
pub const EntryHi = packed struct {
asid : u8 = 0,
_pad0 : u4 = 0,
g : bool = false,
vpn2l : u3 = 0,
vpn2h : u16 = 0,
};
pub const EntryLo = packed struct {
g : bool = false,
v : bool = false,
d : bool = false,
c : u3 = 0,
pfn : u20 = 0,
_pad1: u6 = 0,
};
const PageMask = packed struct {
_pad0: u13 = 0,
mask : u12 = 0,
_pad1: u7 = 0,
};
const TLBEntry = packed struct {
entryLo0: EntryLo = EntryLo{},
entryLo1: EntryLo = EntryLo{},
entryHi : EntryHi = EntryHi{},
pageMask: PageMask = PageMask{},
};
pub var cause: Cause = Cause{};
const causeMask: u32 = 0x0000_0300;
pub var index: Index = Index{};
const indexMask: u32 = 0x8000_003F;
pub var status: Status = Status{};
const statusMask: u32 = 0xFE00_FFFF;
pub var entryLo0: EntryLo = EntryLo{};
pub var entryLo1: EntryLo = EntryLo{};
const entryLoMask: u32 = 0x03FF_FFFF;
pub var entryHi : EntryHi = EntryHi{};
const entryHiMask: u32 = 0xFFFF_F0FF;
pub var pageMask: PageMask = PageMask{};
const pageMaskMask: u32 = 0x01FF_E000;
pub var tlbEntries: [32]TLBEntry = undefined;
var count : u32 = 0;
var compare: u32 = 0;
pub var epc: u32 = 0xFFFFFFFF;
pub var errorEPC: u32 = 0xFFFFFFFF;
pub fn init() void {
set32(@enumToInt(COP0Reg.Random), 0x0000001F);
//set32(@enumToInt(COP0Reg.Status), 0x70400004);
set32(@enumToInt(COP0Reg.PRId ), 0x00000B00);
set32(@enumToInt(COP0Reg.Config), 0x0006E463);
status = @bitCast(Status, @intCast(u32, 0x70400000));
cause = @bitCast(Cause , @intCast(u32, 0xB000007C));
}
pub fn get32(idx: u32) u32 {
var data: u32 = undefined;
switch (idx) {
@enumToInt(COP0Reg.EntryLo0) => {
data = @bitCast(u32, entryLo0);
},
@enumToInt(COP0Reg.EntryLo1) => {
data = @bitCast(u32, entryLo1);
},
@enumToInt(COP0Reg.PageMask) => {
data = @bitCast(u32, pageMask);
},
@enumToInt(COP0Reg.Count) => {
data = count;
},
@enumToInt(COP0Reg.EntryHi) => {
data = @bitCast(u32, entryHi);
},
@enumToInt(COP0Reg.Compare) => {
data = compare;
},
@enumToInt(COP0Reg.Status) => {
data = @bitCast(u32, status);
},
@enumToInt(COP0Reg.Cause) => {
data = @bitCast(u32, cause);
},
@enumToInt(COP0Reg.EPC) => {
data = epc;
},
@enumToInt(COP0Reg.ErrorEPC) => {
data = errorEPC;
},
else => {
data = 0;
}
}
//std.log.info("[COP0] Read {s}, data: {X}h", .{@tagName(@intToEnum(COP0Reg, idx)), data});
return data;
}
pub fn set32(idx: u32, data: u32) void {
switch (idx) {
@enumToInt(COP0Reg.Index) => {
index = @bitCast(Index, @bitCast(u32, index) & ~indexMask);
index = @bitCast(Index, @bitCast(u32, index) | (data & indexMask));
},
@enumToInt(COP0Reg.EntryLo0) => {
entryLo0 = @bitCast(EntryLo, @bitCast(u32, entryLo0) & ~entryLoMask);
entryLo0 = @bitCast(EntryLo, @bitCast(u32, entryLo0) | (data & entryLoMask));
},
@enumToInt(COP0Reg.EntryLo1) => {
entryLo1 = @bitCast(EntryLo, @bitCast(u32, entryLo1) & ~entryLoMask);
entryLo1 = @bitCast(EntryLo, @bitCast(u32, entryLo1) | (data & entryLoMask));
},
@enumToInt(COP0Reg.PageMask) => {
pageMask = @bitCast(PageMask, @bitCast(u32, pageMask) & ~pageMaskMask);
pageMask = @bitCast(PageMask, @bitCast(u32, pageMask) | (data & pageMaskMask));
},
@enumToInt(COP0Reg.EntryHi) => {
entryHi = @bitCast(EntryHi, @bitCast(u32, entryHi) & ~entryHiMask);
entryHi = @bitCast(EntryHi, @bitCast(u32, entryHi) | (data & entryHiMask));
},
@enumToInt(COP0Reg.Compare) => {
compare = data;
clearPending(7);
},
@enumToInt(COP0Reg.Status) => {
status = @bitCast(Status, @bitCast(u32, status) & ~statusMask);
status = @bitCast(Status, @bitCast(u32, status) | (data & statusMask));
},
@enumToInt(COP0Reg.Cause) => {
cause = @bitCast(Cause, @bitCast(u32, cause) & ~causeMask);
cause = @bitCast(Cause, @bitCast(u32, cause) | (data & causeMask));
},
@enumToInt(COP0Reg.EPC) => {
epc = data;
},
@enumToInt(COP0Reg.ErrorEPC) => {
errorEPC = data;
},
else => {}
}
// std.log.info("[COP0] Write {s}, data: {X}h.", .{@tagName(@intToEnum(COP0Reg, idx)), data});
}
pub fn tlbTranslate(addr: u64) u64 {
std.log.info("[COP0] TLB translate address {X}h", .{addr});
var idx: u6 = 0;
while (idx < 32) : (idx += 1) {
const offsetMask: u64 = 0xFFF | (@intCast(u64, tlbEntries[idx].pageMask.mask) << 12);
const vpnShift = @intCast(u6, @popCount(u12, tlbEntries[idx].pageMask.mask)) + 12;
const vpn = addr >> vpnShift;
var eVPN: u64 = ((@intCast(u64, tlbEntries[idx].entryHi.vpn2h) << 3) | @intCast(u64, tlbEntries[idx].entryHi.vpn2l)) >> (vpnShift - 12);
// std.log.info("[COP0] TLB translation, VPN: {X}h, entry VPN: {X}h.", .{vpn, eVPN});
// std.log.info("[COP0] Page Frame: {X}h:{X}h, G: {}", .{tlbEntries[idx].entryLo0.pfn, tlbEntries[idx].entryLo1.pfn, tlbEntries[idx].entryHi.g});
// std.log.info("[COP0] ASID: {X}h", .{tlbEntries[idx].entryHi.asid});
if (((vpn >> 1) == eVPN) and tlbEntries[idx].entryHi.g) {
var pAddr: u64 = undefined;
if ((vpn & 1) == 0) {
pAddr = (@intCast(u64, tlbEntries[idx].entryLo0.pfn) << 12) | (addr & offsetMask);
} else {
pAddr = (@intCast(u64, tlbEntries[idx].entryLo1.pfn) << 12) | (addr & offsetMask);
}
std.log.info("[COP0] Translated address: {X}h", .{pAddr});
return pAddr;
}
}
@panic("TLB miss");
}
pub fn checkForInterrupts() bool {
if (((cause.ip & status.im) != 0) and status.ie and !status.exl and !status.erl) {
raiseException(ExceptionCode.Interrupt);
return true;
}
return false;
}
pub fn clearPending(comptime i: u8) void {
cause.ip &= ~@intCast(u8, (1 << i));
}
pub fn setPending(comptime i: u8) void {
cause.ip |= (1 << i);
}
pub fn tickCount(c: u32) void {
count +%= c;
if (count == compare) {
std.log.info("[COP0] Compare interrupt pending.", .{});
setPending(7);
}
} | src/core/cop0.zig |
const std = @import("std");
pub const ArrayIterator = @import("array.zig").ArrayIterator;
const PathItem = union(enum) {
key: []const u8,
index: usize,
};
/// Represents possible errors in this library.
pub const Error = error{
InvalidJSON,
InvalidBlock,
KeyNotFound,
IndexNotFound,
InvalidTypeCast,
UnexpectedEOF,
};
/// Represents a JSON value
pub const Value = struct {
bytes: []const u8,
kind: ValueKind,
offset: usize,
const Self = @This();
pub fn toBool(self: Self) Error!bool {
if (std.mem.eql(u8, self.bytes, "true")) {
return true;
} else if (std.mem.eql(u8, self.bytes, "false")) {
return false;
}
return Error.NotABoolean;
}
};
/// Represents a JSON value type
pub const ValueKind = enum {
boolean,
string,
integer,
float,
object,
array,
@"null", // TODO: implement null
};
/// Represents a JSON block, such as
/// Array, Object, String
const Block = struct {
offset: usize,
bytes: []const u8,
};
/// Returns offset of the next significant char
pub fn find_next_char(input: []const u8) !usize {
var offset: usize = 0;
// advances until finds a valid char
while (offset < input.len) {
switch (input[offset]) {
' ', '\n', '\r', '\t' => {
offset += 1;
},
else => return offset,
}
}
return 0;
}
/// Returns a json `Value` based on a path.
pub fn get(input: []const u8, path: anytype) Error!Value {
// basically we get the path fields, and save as `PathItem`
const path_fields = comptime std.meta.fields(@TypeOf(path));
var keys: [path_fields.len]PathItem = undefined;
inline for (path_fields) |f, i| {
switch (f.field_type) {
// used for array indexes
comptime_int => {
keys[i] = PathItem{ .index = f.default_value.? };
},
// everything else is a string for us, the compiler should handle
// this errors, until I found a better way.
// it is pretty? NO
// does it work for now? YES
else => {
keys[i] = PathItem{ .key = f.default_value.? };
},
}
}
// reads input until match path, or until it ends
var cursor: usize = 0;
var key_matched = keys.len == 0; // this way we can run the function without path, useful to get data type
var depth: usize = 0;
while (cursor < input.len) {
cursor += try find_next_char(input[cursor..]);
// std.log.warn("depth: {d} -> {s}", .{ depth, input[0 .. cursor + 1] });
switch (input[cursor]) {
'{' => {
// we want to skip the block if its not matched,
// unless its on the first level
if (!key_matched and depth > 0) {
const block = try read_block(input[cursor..], '{', '}');
cursor += block.offset + 1; // we add 1 to include '}'
key_matched = false;
continue;
}
// we are at the end, so we return current block
if (key_matched and depth == keys.len) {
const block = try read_block(input[cursor..], '{', '}');
return Value{
.bytes = block.bytes,
.kind = .object,
.offset = cursor,
};
}
// if we are here, it means the last key was matched or we are
// just starting with the parsing so its safe to increase level
// and cursor
key_matched = false;
depth += 1;
cursor += 1;
},
'[' => {
// we want to skip the block if its not matched,
// unless its on the first level
if (!key_matched and depth > 0) {
const block = try read_block(input[cursor..], '[', ']');
cursor += block.offset + 1; // we add 1 to include ']'
continue;
}
// we are at the end, so we return current block
if (key_matched and depth == keys.len) {
const block = try read_block(input[cursor..], '[', ']');
return Value{
.bytes = block.bytes,
.kind = .array,
.offset = cursor,
};
}
// Probably used to get type, like object or array
if (keys.len == 0) {
const block = try read_block(input[cursor..], '[', ']');
return Value{
.bytes = block.bytes,
.kind = .array,
.offset = cursor,
};
}
// if we are here, it means the last key was matched or we are
// just starting with the parsing so its safe to increase level
// and cursor
if (key_matched) {
depth += 1;
const index = switch (keys[depth - 1]) {
.index => |v| v,
else => return error.KeyNotFound,
};
const item = try get_offset_by_index(input[cursor..], index);
cursor += item;
continue;
}
key_matched = false;
cursor += 1;
},
'"' => {
// parse double quote block
const value = try read_string(input[cursor..]);
// it means we are at the end
if (key_matched and depth == keys.len) {
return Value{
.bytes = value.bytes,
.kind = .string,
.offset = cursor,
};
}
cursor += value.offset + 1;
const next_cursor = try find_next_char(input[cursor..]);
// if (input[cursor + next_cursor] == ':' and keys.len > 0) not works according the compiler
if (input[cursor + next_cursor] == ':') {
if (keys.len > 0) {
cursor += next_cursor;
// here only keys works
const key = switch (keys[depth - 1]) {
.key => |v| v,
else => return Error.KeyNotFound,
};
// compare key with corresponding key in path param
if (std.mem.eql(u8, value.bytes, key)) {
key_matched = true;
}
}
}
},
// number
'-', '0'...'9' => {
const number = read_number(input[cursor..]);
if (key_matched) {
return Value{
.bytes = number.inner,
.kind = number.kind,
.offset = cursor,
};
}
cursor += number.offset;
},
// boolean
't' => {
const offset = (try read_until(input[cursor..], 'e')) + 1;
const is_valid = std.mem.eql(u8, input[cursor .. cursor + offset], "true");
if (is_valid) {
if (key_matched) {
return Value{
.bytes = input[cursor .. offset + cursor],
.kind = .boolean,
.offset = cursor + offset,
};
}
cursor += offset;
continue;
}
return Error.InvalidJSON;
},
'f' => {
const offset = (try read_until(input[cursor..], 'e')) + 1;
const is_valid = std.mem.eql(u8, input[cursor .. cursor + offset], "false");
if (is_valid) {
if (key_matched) {
return Value{
.bytes = input[cursor .. offset + cursor],
.kind = .boolean,
.offset = cursor + offset,
};
}
cursor += offset;
continue;
}
return Error.InvalidJSON;
},
'n' => {
// not pretty
var offset: usize = undefined;
if (cursor + 4 < input.len) {
offset = 4;
} else {
return Error.InvalidJSON;
}
const is_valid = std.mem.eql(u8, input[cursor .. cursor + offset], "null");
if (is_valid) {
if (key_matched) {
return Value{
.bytes = input[cursor .. offset + cursor],
.kind = .@"null",
.offset = cursor + offset,
};
}
cursor += offset;
continue;
}
return Error.InvalidJSON;
},
else => cursor += 1,
}
}
return Error.InvalidJSON;
}
fn read_block(input: []const u8, start: u8, end: u8) Error!Block {
// first we should start block, is a valid block
// this should never happens i guess
if (input[0] != start) {
@panic("library error when parsing block, this is my fault");
}
var offset: usize = 1;
// now we read until find close delimiter
while (offset < input.len and input[offset] != end) {
if (input[offset] == start) {
var block = try read_block(input[offset..], start, end);
offset += block.offset;
}
offset += 1;
}
// if we reach the end and we didnt find the end delimiter,
// it means the block is invalid, because it has no end.
if (offset == input.len) {
return Error.InvalidBlock;
}
return Block{ .offset = offset, .bytes = input[0 .. offset + 1] };
}
fn read_string(input: []const u8) Error!Block {
// first we should start block, is a valid block
// this should never happens i guess
if (input[0] != '"') {
@panic("library error when parsing string, this is my fault");
}
var cursor: usize = 1;
var last_escaped = false;
// now we read until find close delimiter
while (cursor < input.len) {
switch (input[cursor]) {
'"' => {
if (last_escaped) {
cursor += 1;
last_escaped = false;
} else {
break;
}
},
'\\' => last_escaped = true,
else => last_escaped = false,
}
cursor += 1;
}
// if we reach the end and we didnt find the end delimiter,
// it means the block is invalid, because it has no end.
if (cursor == input.len) {
return Error.InvalidBlock;
}
return Block{ .offset = cursor, .bytes = input[1..cursor] };
}
// has a lot of errors for now, specially on detecting format errors,
// ex: -8.65.4
// 8-5.6
// both valid numbers acording this function, but obviously not
fn read_number(input: []const u8) struct { offset: usize, inner: []const u8, kind: ValueKind } {
var offset: usize = 0;
var kind: ValueKind = .integer;
// now we read until find close delimeter
while (std.ascii.isDigit(input[offset]) or input[offset] == '.' or input[offset] == '-') : (offset += 1) {
if (input[offset] == '-') {
kind = .float;
}
}
return .{ .offset = offset, .inner = input[0..offset], .kind = kind };
}
// Returns the offset, between the start of input to delimeter
fn read_until(input: []const u8, delimiter: u8) Error!usize {
var offset: usize = 0;
while (offset < input.len and input[offset] != delimiter) {
offset += 1;
}
return offset;
}
// input needs to be a json array in this format:
// "[a, b, c, d, ...]"
//
// Returns the offset from 0 to the previous byte
fn get_offset_by_index(input: []const u8, index: usize) Error!usize {
var offset: usize = 0;
// check if is an array
if (input[offset] == '[') {
offset += 1;
// else return error
}
var cursor_index: usize = 0;
while (offset < input.len) {
offset += try find_next_char(input[offset..]);
if (cursor_index == index) {
return offset;
}
switch (input[offset]) {
'[', '{', '"', '-', '0'...'9', 't', 'f' => {
const value = try get(input[offset..], .{});
offset += value.offset + value.bytes.len;
},
// always at the end
']' => {
offset += 1;
},
',' => {
offset += 1;
cursor_index += 1;
},
else => @panic("Not supported yet"),
}
}
return Error.IndexNotFound;
}
test " " {
std.testing.refAllDecls(@This());
}
test "one level, only string" {
var input =
\\ {
\\ "key1": "value1",
\\ "key2": "value2",
\\ "key3": false
\\ }
;
var value1 = try get(input, .{"key1"});
try std.testing.expect(std.mem.eql(u8, value1.bytes, "value1"));
var value2 = try get(input, .{"key2"});
try std.testing.expect(std.mem.eql(u8, value2.bytes, "value2"));
var value3 = try get(input, .{"key3"});
try std.testing.expect(std.mem.eql(u8, value3.bytes, "false"));
}
test "one level, only integer" {
var input =
\\ {
\\ "key1": 8,
\\ "key2": 5654
\\ }
;
var value1 = try get(input, .{"key1"});
try std.testing.expect(std.mem.eql(u8, value1.bytes, "8"));
var value2 = try get(input, .{"key2"});
try std.testing.expect(std.mem.eql(u8, value2.bytes, "5654"));
}
test "two level, only string" {
var input =
\\ {
\\ "key1": { "key11": "value11" },
\\ "key2": "value2",
\\ "key3": { "key11": "value11" }
\\ }
;
var value1 = try get(input, .{ "key1", "key11" });
try std.testing.expect(std.mem.eql(u8, value1.bytes, "value11"));
var value2 = try get(input, .{"key2"});
try std.testing.expect(std.mem.eql(u8, value2.bytes, "value2"));
var value3 = try get(input, .{"key3"});
try std.testing.expect(std.mem.eql(u8, value3.bytes, "{ \"key11\": \"value11\" }"));
}
test "array" {
var input =
\\ {
\\ "key1": [8, 5, 6],
\\ "key2": 5654
\\ }
;
var value1 = try get(input, .{ "key1", 2 });
try std.testing.expect(std.mem.eql(u8, value1.bytes, "6"));
}
test "array with more keys" {
var input =
\\ {
\\ "key1": [8, {"foo": "bar", "value": 6}, 5],
\\ "key2": [{"foo": 23} , {"foo": "bar", "value": 6}, 5],
\\ "key3": 5654
\\ }
;
var value1 = try get(input, .{ "key1", 1, "value" });
try std.testing.expect(std.mem.eql(u8, value1.bytes, "6"));
}
test "array with more keys 2" {
var input =
\\ {
\\ "key": [
\\ {
\\ "value": 6,
\\ },
\\ {
\\ "value": 8
\\ "value2": null
\\ }
\\ ]
\\ }
;
var value1 = try get(input, .{ "key", 1, "value" });
try std.testing.expect(std.mem.eql(u8, value1.bytes, "8"));
var value2 = try get(input, .{ "key", 1, "value2" });
try std.testing.expect(value2.kind == .@"null");
} | src/lib.zig |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.